@sequenzy/mcp 0.0.107 → 0.0.109

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/index.js CHANGED
@@ -1,15 +1,15 @@
1
1
  #!/usr/bin/env node
2
- var hz=Object.create;var{getPrototypeOf:fz,defineProperty:t$,getOwnPropertyNames:gz}=Object;var cz=Object.prototype.hasOwnProperty;function mz(b){return this[b]}var nz,lz,CW=(b,w,$)=>{var W=b!=null&&typeof b==="object";if(W){var Q=w?nz??=new WeakMap:lz??=new WeakMap,G=Q.get(b);if(G)return G}$=b!=null?hz(fz(b)):{};let X=w||!b||!b.__esModule?t$($,"default",{value:b,enumerable:!0}):$;for(let Y of gz(b))if(!cz.call(X,Y))t$(X,Y,{get:mz.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 iz=(b)=>b;function pz(b,w){this[b]=iz.bind(null,w)}var xW=(b,w)=>{for(var $ in w)t$(b,$,{get:w[$],enumerable:!0,configurable:!0,set:pz.bind(w,$)})};var h1=I((uG)=>{Object.defineProperty(uG,"__esModule",{value:!0});uG.regexpCode=uG.getEsmExportName=uG.getProperty=uG.safeStringify=uG.stringify=uG.strConcat=uG.addCodeArg=uG.str=uG._=uG.nil=uG._Code=uG.Name=uG.IDENTIFIER=uG._CodeOrName=void 0;class t0{}uG._CodeOrName=t0;uG.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class pw extends t0{constructor(b){super();if(!uG.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}}}uG.Name=pw;class yb extends t0{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},{})}}uG._Code=yb;uG.nil=new yb("");function CG(b,...w){let $=[b[0]],W=0;while(W<w.length)Q6($,w[W]),$.push(b[++W]);return new yb($)}uG._=CG;var W6=new yb("+");function xG(b,...w){let $=[y1(b[0])],W=0;while(W<w.length)$.push(W6),Q6($,w[W]),$.push(W6,y1(b[++W]));return qO($),new yb($)}uG.str=xG;function Q6(b,w){if(w instanceof yb)b.push(...w._items);else if(w instanceof pw)b.push(w);else b.push(BO(w))}uG.addCodeArg=Q6;function qO(b){let w=1;while(w<b.length-1){if(b[w]===W6){let $=LO(b[w-1],b[w+1]);if($!==void 0){b.splice(w-1,3,$);continue}b[w++]="+"}w++}}function LO(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 UO(b,w){return w.emptyStr()?b:b.emptyStr()?w:xG`${b}${w}`}uG.strConcat=UO;function BO(b){return typeof b=="number"||typeof b=="boolean"||b===null?b:y1(Array.isArray(b)?b.join(","):b)}function KO(b){return new yb(y1(b))}uG.stringify=KO;function y1(b){return JSON.stringify(b).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}uG.safeStringify=y1;function FO(b){return typeof b=="string"&&uG.IDENTIFIER.test(b)?new yb(`.${b}`):CG`[${b}]`}uG.getProperty=FO;function PO(b){if(typeof b=="string"&&uG.IDENTIFIER.test(b))return new yb(`${b}`);throw Error(`CodeGen: invalid export name: ${b}, use explicit $id name mapping`)}uG.getEsmExportName=PO;function MO(b){return new yb(b.toString())}uG.regexpCode=MO});var H6=I((gG)=>{Object.defineProperty(gG,"__esModule",{value:!0});gG.ValueScope=gG.ValueScopeName=gG.Scope=gG.varKinds=gG.UsedValueState=void 0;var Pb=h1();class hG extends Error{constructor(b){super(`CodeGen: "code" for ${b} not defined`);this.value=b.value}}var e0;(function(b){b[b.Started=0]="Started",b[b.Completed=1]="Completed"})(e0||(gG.UsedValueState=e0={}));gG.varKinds={const:new Pb.Name("const"),let:new Pb.Name("let"),var:new Pb.Name("var")};class X6{constructor({prefixes:b,parent:w}={}){this._names={},this._prefixes=b,this._parent=w}toName(b){return b instanceof Pb.Name?b:this.name(b)}name(b){return new Pb.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}}}gG.Scope=X6;class Y6 extends Pb.Name{constructor(b,w){super(w);this.prefix=b}setValue(b,{property:w,itemIndex:$}){this.value=b,this.scopePath=Pb._`.${new Pb.Name(w)}[${$}]`}}gG.ValueScopeName=Y6;var CO=Pb._`\n`;class fG extends X6{constructor(b){super(b);this._values={},this._scope=b.scope,this.opts={...b,_n:b.lines?CO:Pb.nil}}get(){return this._scope}name(b){return new Y6(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 Pb._`${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=Pb.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,e0.Started);let J=w(H);if(J){let D=this.opts.es5?gG.varKinds.var:gG.varKinds.const;Q=Pb._`${Q}${D} ${H} = ${J};${this.opts._n}`}else if(J=W===null||W===void 0?void 0:W(H))Q=Pb._`${Q}${J}${this.opts._n}`;else throw new hG(H);Y.set(H,e0.Completed)})}return Q}}gG.ValueScope=fG});var u=I((Mb)=>{Object.defineProperty(Mb,"__esModule",{value:!0});Mb.or=Mb.and=Mb.not=Mb.CodeGen=Mb.operators=Mb.varKinds=Mb.ValueScopeName=Mb.ValueScope=Mb.Scope=Mb.Name=Mb.regexpCode=Mb.stringify=Mb.getProperty=Mb.nil=Mb.strConcat=Mb.str=Mb._=void 0;var c=h1(),hb=H6(),Mw=h1();Object.defineProperty(Mb,"_",{enumerable:!0,get:function(){return Mw._}});Object.defineProperty(Mb,"str",{enumerable:!0,get:function(){return Mw.str}});Object.defineProperty(Mb,"strConcat",{enumerable:!0,get:function(){return Mw.strConcat}});Object.defineProperty(Mb,"nil",{enumerable:!0,get:function(){return Mw.nil}});Object.defineProperty(Mb,"getProperty",{enumerable:!0,get:function(){return Mw.getProperty}});Object.defineProperty(Mb,"stringify",{enumerable:!0,get:function(){return Mw.stringify}});Object.defineProperty(Mb,"regexpCode",{enumerable:!0,get:function(){return Mw.regexpCode}});Object.defineProperty(Mb,"Name",{enumerable:!0,get:function(){return Mw.Name}});var W$=H6();Object.defineProperty(Mb,"Scope",{enumerable:!0,get:function(){return W$.Scope}});Object.defineProperty(Mb,"ValueScope",{enumerable:!0,get:function(){return W$.ValueScope}});Object.defineProperty(Mb,"ValueScopeName",{enumerable:!0,get:function(){return W$.ValueScopeName}});Object.defineProperty(Mb,"varKinds",{enumerable:!0,get:function(){return W$.varKinds}});Mb.operators={GT:new c._Code(">"),GTE:new c._Code(">="),LT:new c._Code("<"),LTE:new c._Code("<="),EQ:new c._Code("==="),NEQ:new c._Code("!=="),NOT:new c._Code("!"),OR:new c._Code("||"),AND:new c._Code("&&"),ADD:new c._Code("+")};class Zw{optimizeNodes(){return this}optimizeNames(b,w){return this}}class mG extends Zw{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 c._CodeOrName?this.rhs.names:{}}}class z6 extends Zw{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 c.Name&&!b[this.lhs.str]&&!this.sideEffects)return;return this.rhs=dw(this.rhs,b,w),this}get names(){let b=this.lhs instanceof c.Name?{}:{...this.lhs.names};return $$(b,this.rhs)}}class nG extends z6{constructor(b,w,$,W){super(b,$,W);this.op=w}render({_n:b}){return`${this.lhs} ${this.op}= ${this.rhs};`+b}}class lG extends Zw{constructor(b){super();this.label=b,this.names={}}render({_n:b}){return`${this.label}:`+b}}class iG extends Zw{constructor(b){super();this.label=b,this.names={}}render({_n:b}){return`break${this.label?` ${this.label}`:""};`+b}}class pG extends Zw{constructor(b){super();this.error=b}render({_n:b}){return`throw ${this.error};`+b}get names(){return this.error.names}}class oG extends Zw{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 c._CodeOrName?this.code.names:{}}}class Q$ extends Zw{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;hO(b,Q.names),$.splice(W,1)}return $.length>0?this:void 0}get names(){return this.nodes.reduce((b,w)=>vw(b,w.names),{})}}class Iw extends Q${render(b){return"{"+b._n+super.render(b)+"}"+b._n}}class dG extends Q${}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(aG(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($$(b,this.condition),this.else)vw(b,this.else.names);return b}}Ww.kind="if";class ow extends Iw{}ow.kind="for";class tG 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 vw(super.names,this.iteration.names)}}class rG 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=$$(super.names,this.from);return $$(b,this.to)}}class J6 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 vw(super.names,this.iterable.names)}}class s0 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)}}s0.kind="func";class a0 extends Q${render(b){return"return "+super.render(b)}}a0.kind="return";class eG 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)vw(b,this.catch.names);if(this.finally)vw(b,this.finally.names);return b}}class b$ extends Iw{constructor(b){super();this.error=b}render(b){return`catch(${this.error})`+super.render(b)}}b$.kind="catch";class w$ extends Iw{render(b){return"finally"+super.render(b)}}w$.kind="finally";class sG{constructor(b,w={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...w,_n:w.lines?`
3
- `:""},this._extScope=b,this._scope=new hb.Scope({parent:b}),this._nodes=[new dG]}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 mG(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 z6(b,w,$))}add(b,w){return this._leafNode(new nG(b,Mb.operators.ADD,w))}code(b){if(typeof b=="function")b();else if(b!==c.nil)this._leafNode(new oG(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,c.addCodeArg)(w,W)}return w.push("}"),new c._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 tG(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 rG(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 c.Name?w:this.var("_arr",w);return this.forRange("_i",0,c._`${G}.length`,(X)=>{this.var(Q,c._`${G}[${X}]`),$(Q)})}return this._for(new J6("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,c._`Object.keys(${w})`,$);let Q=this._scope.toName(b);return this._for(new J6("in",W,Q,w),()=>$(Q))}endFor(){return this._endBlockNode(ow)}label(b){return this._leafNode(new lG(b))}break(b){return this._leafNode(new iG(b))}return(b){let w=new a0;if(this._blockNode(w),this.code(b),w.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(a0)}try(b,w,$){if(!w&&!$)throw Error('CodeGen: "try" without "catch" and "finally"');let W=new eG;if(this._blockNode(W),this.code(b),w){let Q=this.name("e");this._currNode=W.catch=new b$(Q),w(Q)}if($)this._currNode=W.finally=new w$,this.code($);return this._endBlockNode(b$,w$)}throw(b){return this._leafNode(new pG(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=c.nil,$,W){if(this._blockNode(new s0(b,w,$)),W)this.code(W).endFunc();return this}endFunc(){return this._endBlockNode(s0)}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}}Mb.CodeGen=sG;function vw(b,w){for(let $ in w)b[$]=(b[$]||0)+(w[$]||0);return b}function $$(b,w){return w instanceof c._CodeOrName?vw(b,w.names):b}function dw(b,w,$){if(b instanceof c.Name)return W(b);if(!Q(b))return b;return new c._Code(b._items.reduce((G,X)=>{if(X instanceof c.Name)X=W(X);if(X instanceof c._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 c._Code&&G._items.some((X)=>X instanceof c.Name&&w[X.str]===1&&$[X.str]!==void 0)}}function hO(b,w){for(let $ in w)b[$]=(b[$]||0)-(w[$]||0)}function aG(b){return typeof b=="boolean"||typeof b=="number"||b===null?!b:c._`!${D6(b)}`}Mb.not=aG;var fO=bX(Mb.operators.AND);function gO(...b){return b.reduce(fO)}Mb.and=gO;var cO=bX(Mb.operators.OR);function mO(...b){return b.reduce(cO)}Mb.or=mO;function bX(b){return(w,$)=>w===c.nil?$:$===c.nil?w:c._`${D6(w)} ${b} ${D6($)}`}function D6(b){return b instanceof c.Name?b:c._`(${b})`}});var l=I((JX)=>{Object.defineProperty(JX,"__esModule",{value:!0});JX.checkStrictMode=JX.getErrorPath=JX.Type=JX.useFunc=JX.setEvaluated=JX.evaluatedPropsToName=JX.mergeEvaluated=JX.eachItem=JX.unescapeJsonPointer=JX.escapeJsonPointer=JX.escapeFragment=JX.unescapeFragment=JX.schemaRefOrVal=JX.schemaHasRulesButRef=JX.schemaHasRules=JX.checkUnknownRules=JX.alwaysValidSchema=JX.toHash=void 0;var d=u(),pO=h1();function oO(b){let w={};for(let $ of b)w[$]=!0;return w}JX.toHash=oO;function dO(b,w){if(typeof w=="boolean")return w;if(Object.keys(w).length===0)return!0;return QX(b,w),!GX(w,b.self.RULES.all)}JX.alwaysValidSchema=dO;function QX(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])HX(b,`unknown keyword: "${G}"`)}JX.checkUnknownRules=QX;function GX(b,w){if(typeof b=="boolean")return!b;for(let $ in b)if(w[$])return!0;return!1}JX.schemaHasRules=GX;function tO(b,w){if(typeof b=="boolean")return!b;for(let $ in b)if($!=="$ref"&&w.all[$])return!0;return!1}JX.schemaHasRulesButRef=tO;function rO({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)}`}JX.schemaRefOrVal=rO;function eO(b){return XX(decodeURIComponent(b))}JX.unescapeFragment=eO;function sO(b){return encodeURIComponent(O6(b))}JX.escapeFragment=sO;function O6(b){if(typeof b=="number")return`${b}`;return b.replace(/~/g,"~0").replace(/\//g,"~1")}JX.escapeJsonPointer=O6;function XX(b){return b.replace(/~1/g,"/").replace(/~0/g,"~")}JX.unescapeJsonPointer=XX;function aO(b,w){if(Array.isArray(b))for(let $ of b)w($);else w(b)}JX.eachItem=aO;function $X({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}}JX.mergeEvaluated={props:$X({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._`${$} || {}`),q6(b,$,w)}),mergeValues:(b,w)=>b===!0?!0:{...b,...w},resultToName:YX}),items:$X({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 YX(b,w){if(w===!0)return b.var("props",!0);let $=b.var("props",d._`{}`);if(w!==void 0)q6(b,$,w);return $}JX.evaluatedPropsToName=YX;function q6(b,w,$){Object.keys($).forEach((W)=>b.assign(d._`${w}${(0,d.getProperty)(W)}`,!0))}JX.setEvaluated=q6;var WX={};function bq(b,w){return b.scopeValue("func",{ref:w,code:WX[w.code]||(WX[w.code]=new pO._Code(w.code))})}JX.useFunc=bq;var A6;(function(b){b[b.Num=0]="Num",b[b.Str=1]="Str"})(A6||(JX.Type=A6={}));function wq(b,w,$){if(b instanceof d.Name){let W=w===A6.Num;return $?W?d._`"[" + ${b} + "]"`:d._`"['" + ${b} + "']"`:W?d._`"/" + ${b}`:d._`"/" + ${b}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return $?(0,d.getProperty)(b).toString():"/"+O6(b)}JX.getErrorPath=wq;function HX(b,w,$=b.opts.strictSchema){if(!$)return;if(w=`strict mode: ${w}`,$===!0)throw Error(w);b.self.logger.warn(w)}JX.checkStrictMode=HX});var Qw=I((zX)=>{Object.defineProperty(zX,"__esModule",{value:!0});var Lb=u(),Fq={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")};zX.default=Fq});var g1=I((LX)=>{Object.defineProperty(LX,"__esModule",{value:!0});LX.extendErrors=LX.resetErrorsCount=LX.reportExtraError=LX.reportError=LX.keyword$DataError=LX.keywordError=void 0;var m=u(),X$=l(),Bb=Qw();LX.keywordError={message:({keyword:b})=>m.str`must pass "${b}" keyword validation`};LX.keyword$DataError={message:({keyword:b,schemaType:w})=>w?m.str`"${b}" keyword must be ${w} ($data)`:m.str`"${b}" keyword is invalid ($data)`};function Mq(b,w=LX.keywordError,$,W){let{it:Q}=b,{gen:G,compositeRule:X,allErrors:Y}=Q,H=qX(b,w,$);if(W!==null&&W!==void 0?W:X||Y)AX(G,H);else OX(Q,m._`[${H}]`)}LX.reportError=Mq;function Zq(b,w=LX.keywordError,$){let{it:W}=b,{gen:Q,compositeRule:G,allErrors:X}=W,Y=qX(b,w,$);if(AX(Q,Y),!(G||X))OX(W,Bb.default.vErrors)}LX.reportExtraError=Zq;function Iq(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)))}LX.resetErrorsCount=Iq;function jq({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)})}LX.extendErrors=jq;function AX(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 OX(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 qX(b,w,$){let{createErrors:W}=b.it;if(W===!1)return m._`{}`;return Vq(b,w,$)}function Vq(b,w,$={}){let{gen:W,it:Q}=b,G=[Nq(Q,$),Eq(b,$)];return Tq(b,w,G),W.object(...G)}function Nq({errorPath:b},{instancePath:w}){let $=w?m.str`${b}${(0,X$.getErrorPath)(w,X$.Type.Str)}`:b;return[Bb.default.instancePath,(0,m.strConcat)(Bb.default.instancePath,$)]}function Eq({keyword:b,it:{errSchemaPath:w}},{schemaPath:$,parentSchema:W}){let Q=W?w:m.str`${w}/${b}`;if($)Q=m.str`${Q}${(0,X$.getErrorPath)($,X$.Type.Str)}`;return[kw.schemaPath,Q]}function Tq(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 PX=I((KX)=>{Object.defineProperty(KX,"__esModule",{value:!0});KX.boolOrEmptySchema=KX.topBoolOrEmptySchema=void 0;var kq=g1(),Cq=u(),xq=Qw(),uq={message:"boolean schema is false"};function yq(b){let{gen:w,schema:$,validateName:W}=b;if($===!1)BX(b,!1);else if(typeof $=="object"&&$.$async===!0)w.return(xq.default.data);else w.assign(Cq._`${W}.errors`,null),w.return(!0)}KX.topBoolOrEmptySchema=yq;function hq(b,w){let{gen:$,schema:W}=b;if(W===!1)$.var(w,!1),BX(b);else $.var(w,!0)}KX.boolOrEmptySchema=hq;function BX(b,w){let{gen:$,data:W}=b,Q={gen:$,keyword:"false schema",data:W,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:b};(0,kq.reportError)(Q,uq,void 0,w)}});var U6=I((MX)=>{Object.defineProperty(MX,"__esModule",{value:!0});MX.getRules=MX.isJSONType=void 0;var gq=["string","number","integer","boolean","null","object","array"],cq=new Set(gq);function mq(b){return typeof b=="string"&&cq.has(b)}MX.isJSONType=mq;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:{}}}MX.getRules=nq});var B6=I((VX)=>{Object.defineProperty(VX,"__esModule",{value:!0});VX.shouldUseRule=VX.shouldUseGroup=VX.schemaHasRulesForType=void 0;function iq({schema:b,self:w},$){let W=w.RULES.types[$];return W&&W!==!0&&IX(b,W)}VX.schemaHasRulesForType=iq;function IX(b,w){return w.rules.some(($)=>jX(b,$))}VX.shouldUseGroup=IX;function jX(b,w){var $;return b[w.keyword]!==void 0||(($=w.definition.implements)===null||$===void 0?void 0:$.some((W)=>b[W]!==void 0))}VX.shouldUseRule=jX});var c1=I((SX)=>{Object.defineProperty(SX,"__esModule",{value:!0});SX.reportTypeError=SX.checkDataTypes=SX.checkDataType=SX.coerceAndCheckDataType=SX.getJSONTypes=SX.getSchemaTypes=SX.DataType=void 0;var dq=U6(),tq=B6(),rq=g1(),C=u(),EX=l(),tw;(function(b){b[b.Correct=0]="Correct",b[b.Wrong=1]="Wrong"})(tw||(SX.DataType=tw={}));function eq(b){let w=TX(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}SX.getSchemaTypes=eq;function TX(b){let w=Array.isArray(b)?b:b?[b]:[];if(w.every(dq.isJSONType))return w;throw Error("type must be JSONType or JSONType[]: "+w.join(","))}SX.getJSONTypes=TX;function sq(b,w){let{gen:$,data:W,opts:Q}=b,G=aq(w,Q.coerceTypes),X=w.length>0&&!(G.length===0&&w.length===1&&(0,tq.schemaHasRulesForType)(b,w[0]));if(X){let Y=F6(w,W,Q.strictNumbers,tw.Wrong);$.if(Y,()=>{if(G.length)bL(b,w,G);else P6(b)})}return X}SX.coerceAndCheckDataType=sq;var _X=new Set(["string","number","integer","boolean","null"]);function aq(b,w){return w?b.filter(($)=>_X.has($)||w==="array"&&$==="array"):[]}function bL(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(_X.has(J)||J==="array"&&G.coerceTypes==="array")H(J);W.else(),P6(b),W.endIf(),W.if(C._`${Y} !== undefined`,()=>{W.assign(Q,Y),wL(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
2
+ var hz=Object.create;var{getPrototypeOf:fz,defineProperty:t$,getOwnPropertyNames:cz}=Object;var gz=Object.prototype.hasOwnProperty;function mz(b){return this[b]}var nz,lz,CW=(b,w,$)=>{var W=b!=null&&typeof b==="object";if(W){var Q=w?nz??=new WeakMap:lz??=new WeakMap,G=Q.get(b);if(G)return G}$=b!=null?hz(fz(b)):{};let X=w||!b||!b.__esModule?t$($,"default",{value:b,enumerable:!0}):$;for(let Y of cz(b))if(!gz.call(X,Y))t$(X,Y,{get:mz.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 iz=(b)=>b;function pz(b,w){this[b]=iz.bind(null,w)}var xW=(b,w)=>{for(var $ in w)t$(b,$,{get:w[$],enumerable:!0,configurable:!0,set:pz.bind(w,$)})};var h1=I((uG)=>{Object.defineProperty(uG,"__esModule",{value:!0});uG.regexpCode=uG.getEsmExportName=uG.getProperty=uG.safeStringify=uG.stringify=uG.strConcat=uG.addCodeArg=uG.str=uG._=uG.nil=uG._Code=uG.Name=uG.IDENTIFIER=uG._CodeOrName=void 0;class t0{}uG._CodeOrName=t0;uG.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class pw extends t0{constructor(b){super();if(!uG.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}}}uG.Name=pw;class yb extends t0{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},{})}}uG._Code=yb;uG.nil=new yb("");function CG(b,...w){let $=[b[0]],W=0;while(W<w.length)Q6($,w[W]),$.push(b[++W]);return new yb($)}uG._=CG;var W6=new yb("+");function xG(b,...w){let $=[y1(b[0])],W=0;while(W<w.length)$.push(W6),Q6($,w[W]),$.push(W6,y1(b[++W]));return qO($),new yb($)}uG.str=xG;function Q6(b,w){if(w instanceof yb)b.push(...w._items);else if(w instanceof pw)b.push(w);else b.push(BO(w))}uG.addCodeArg=Q6;function qO(b){let w=1;while(w<b.length-1){if(b[w]===W6){let $=LO(b[w-1],b[w+1]);if($!==void 0){b.splice(w-1,3,$);continue}b[w++]="+"}w++}}function LO(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 UO(b,w){return w.emptyStr()?b:b.emptyStr()?w:xG`${b}${w}`}uG.strConcat=UO;function BO(b){return typeof b=="number"||typeof b=="boolean"||b===null?b:y1(Array.isArray(b)?b.join(","):b)}function FO(b){return new yb(y1(b))}uG.stringify=FO;function y1(b){return JSON.stringify(b).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}uG.safeStringify=y1;function KO(b){return typeof b=="string"&&uG.IDENTIFIER.test(b)?new yb(`.${b}`):CG`[${b}]`}uG.getProperty=KO;function PO(b){if(typeof b=="string"&&uG.IDENTIFIER.test(b))return new yb(`${b}`);throw Error(`CodeGen: invalid export name: ${b}, use explicit $id name mapping`)}uG.getEsmExportName=PO;function MO(b){return new yb(b.toString())}uG.regexpCode=MO});var H6=I((cG)=>{Object.defineProperty(cG,"__esModule",{value:!0});cG.ValueScope=cG.ValueScopeName=cG.Scope=cG.varKinds=cG.UsedValueState=void 0;var Mb=h1();class hG extends Error{constructor(b){super(`CodeGen: "code" for ${b} not defined`);this.value=b.value}}var e0;(function(b){b[b.Started=0]="Started",b[b.Completed=1]="Completed"})(e0||(cG.UsedValueState=e0={}));cG.varKinds={const:new Mb.Name("const"),let:new Mb.Name("let"),var:new Mb.Name("var")};class X6{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}}}cG.Scope=X6;class Y6 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)}[${$}]`}}cG.ValueScopeName=Y6;var CO=Mb._`\n`;class fG extends X6{constructor(b){super(b);this._values={},this._scope=b.scope,this.opts={...b,_n:b.lines?CO:Mb.nil}}get(){return this._scope}name(b){return new Y6(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,e0.Started);let J=w(H);if(J){let D=this.opts.es5?cG.varKinds.var:cG.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 hG(H);Y.set(H,e0.Completed)})}return Q}}cG.ValueScope=fG});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=H6(),Zw=h1();Object.defineProperty(Zb,"_",{enumerable:!0,get:function(){return Zw._}});Object.defineProperty(Zb,"str",{enumerable:!0,get:function(){return Zw.str}});Object.defineProperty(Zb,"strConcat",{enumerable:!0,get:function(){return Zw.strConcat}});Object.defineProperty(Zb,"nil",{enumerable:!0,get:function(){return Zw.nil}});Object.defineProperty(Zb,"getProperty",{enumerable:!0,get:function(){return Zw.getProperty}});Object.defineProperty(Zb,"stringify",{enumerable:!0,get:function(){return Zw.stringify}});Object.defineProperty(Zb,"regexpCode",{enumerable:!0,get:function(){return Zw.regexpCode}});Object.defineProperty(Zb,"Name",{enumerable:!0,get:function(){return Zw.Name}});var W$=H6();Object.defineProperty(Zb,"Scope",{enumerable:!0,get:function(){return W$.Scope}});Object.defineProperty(Zb,"ValueScope",{enumerable:!0,get:function(){return W$.ValueScope}});Object.defineProperty(Zb,"ValueScopeName",{enumerable:!0,get:function(){return W$.ValueScopeName}});Object.defineProperty(Zb,"varKinds",{enumerable:!0,get:function(){return W$.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 Iw{optimizeNodes(){return this}optimizeNames(b,w){return this}}class mG extends Iw{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 z6 extends Iw{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 $$(b,this.rhs)}}class nG extends z6{constructor(b,w,$,W){super(b,$,W);this.op=w}render({_n:b}){return`${this.lhs} ${this.op}= ${this.rhs};`+b}}class lG extends Iw{constructor(b){super();this.label=b,this.names={}}render({_n:b}){return`${this.label}:`+b}}class iG extends Iw{constructor(b){super();this.label=b,this.names={}}render({_n:b}){return`break${this.label?` ${this.label}`:""};`+b}}class pG extends Iw{constructor(b){super();this.error=b}render({_n:b}){return`throw ${this.error};`+b}get names(){return this.error.names}}class oG extends Iw{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 Q$ extends Iw{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;hO(b,Q.names),$.splice(W,1)}return $.length>0?this:void 0}get names(){return this.nodes.reduce((b,w)=>kw(b,w.names),{})}}class jw extends Q${render(b){return"{"+b._n+super.render(b)+"}"+b._n}}class dG extends Q${}class f1 extends jw{}f1.kind="else";class Ww extends jw{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(aG(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($$(b,this.condition),this.else)kw(b,this.else.names);return b}}Ww.kind="if";class ow extends jw{}ow.kind="for";class tG 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 kw(super.names,this.iteration.names)}}class rG 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=$$(super.names,this.from);return $$(b,this.to)}}class J6 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 kw(super.names,this.iterable.names)}}class s0 extends jw{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)}}s0.kind="func";class a0 extends Q${render(b){return"return "+super.render(b)}}a0.kind="return";class eG extends jw{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)kw(b,this.catch.names);if(this.finally)kw(b,this.finally.names);return b}}class b$ extends jw{constructor(b){super();this.error=b}render(b){return`catch(${this.error})`+super.render(b)}}b$.kind="catch";class w$ extends jw{render(b){return"finally"+super.render(b)}}w$.kind="finally";class sG{constructor(b,w={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...w,_n:w.lines?`
3
+ `:""},this._extScope=b,this._scope=new hb.Scope({parent:b}),this._nodes=[new dG]}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 mG(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 z6(b,w,$))}add(b,w){return this._leafNode(new nG(b,Zb.operators.ADD,w))}code(b){if(typeof b=="function")b();else if(b!==g.nil)this._leafNode(new oG(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 tG(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 rG(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 J6("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 J6("in",W,Q,w),()=>$(Q))}endFor(){return this._endBlockNode(ow)}label(b){return this._leafNode(new lG(b))}break(b){return this._leafNode(new iG(b))}return(b){let w=new a0;if(this._blockNode(w),this.code(b),w.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(a0)}try(b,w,$){if(!w&&!$)throw Error('CodeGen: "try" without "catch" and "finally"');let W=new eG;if(this._blockNode(W),this.code(b),w){let Q=this.name("e");this._currNode=W.catch=new b$(Q),w(Q)}if($)this._currNode=W.finally=new w$,this.code($);return this._endBlockNode(b$,w$)}throw(b){return this._leafNode(new pG(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 s0(b,w,$)),W)this.code(W).endFunc();return this}endFunc(){return this._endBlockNode(s0)}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=sG;function kw(b,w){for(let $ in w)b[$]=(b[$]||0)+(w[$]||0);return b}function $$(b,w){return w instanceof g._CodeOrName?kw(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 hO(b,w){for(let $ in w)b[$]=(b[$]||0)-(w[$]||0)}function aG(b){return typeof b=="boolean"||typeof b=="number"||b===null?!b:g._`!${D6(b)}`}Zb.not=aG;var fO=bX(Zb.operators.AND);function cO(...b){return b.reduce(fO)}Zb.and=cO;var gO=bX(Zb.operators.OR);function mO(...b){return b.reduce(gO)}Zb.or=mO;function bX(b){return(w,$)=>w===g.nil?$:$===g.nil?w:g._`${D6(w)} ${b} ${D6($)}`}function D6(b){return b instanceof g.Name?b:g._`(${b})`}});var l=I((JX)=>{Object.defineProperty(JX,"__esModule",{value:!0});JX.checkStrictMode=JX.getErrorPath=JX.Type=JX.useFunc=JX.setEvaluated=JX.evaluatedPropsToName=JX.mergeEvaluated=JX.eachItem=JX.unescapeJsonPointer=JX.escapeJsonPointer=JX.escapeFragment=JX.unescapeFragment=JX.schemaRefOrVal=JX.schemaHasRulesButRef=JX.schemaHasRules=JX.checkUnknownRules=JX.alwaysValidSchema=JX.toHash=void 0;var d=u(),pO=h1();function oO(b){let w={};for(let $ of b)w[$]=!0;return w}JX.toHash=oO;function dO(b,w){if(typeof w=="boolean")return w;if(Object.keys(w).length===0)return!0;return QX(b,w),!GX(w,b.self.RULES.all)}JX.alwaysValidSchema=dO;function QX(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])HX(b,`unknown keyword: "${G}"`)}JX.checkUnknownRules=QX;function GX(b,w){if(typeof b=="boolean")return!b;for(let $ in b)if(w[$])return!0;return!1}JX.schemaHasRules=GX;function tO(b,w){if(typeof b=="boolean")return!b;for(let $ in b)if($!=="$ref"&&w.all[$])return!0;return!1}JX.schemaHasRulesButRef=tO;function rO({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)}`}JX.schemaRefOrVal=rO;function eO(b){return XX(decodeURIComponent(b))}JX.unescapeFragment=eO;function sO(b){return encodeURIComponent(O6(b))}JX.escapeFragment=sO;function O6(b){if(typeof b=="number")return`${b}`;return b.replace(/~/g,"~0").replace(/\//g,"~1")}JX.escapeJsonPointer=O6;function XX(b){return b.replace(/~1/g,"/").replace(/~0/g,"~")}JX.unescapeJsonPointer=XX;function aO(b,w){if(Array.isArray(b))for(let $ of b)w($);else w(b)}JX.eachItem=aO;function $X({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}}JX.mergeEvaluated={props:$X({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._`${$} || {}`),q6(b,$,w)}),mergeValues:(b,w)=>b===!0?!0:{...b,...w},resultToName:YX}),items:$X({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 YX(b,w){if(w===!0)return b.var("props",!0);let $=b.var("props",d._`{}`);if(w!==void 0)q6(b,$,w);return $}JX.evaluatedPropsToName=YX;function q6(b,w,$){Object.keys($).forEach((W)=>b.assign(d._`${w}${(0,d.getProperty)(W)}`,!0))}JX.setEvaluated=q6;var WX={};function bq(b,w){return b.scopeValue("func",{ref:w,code:WX[w.code]||(WX[w.code]=new pO._Code(w.code))})}JX.useFunc=bq;var A6;(function(b){b[b.Num=0]="Num",b[b.Str=1]="Str"})(A6||(JX.Type=A6={}));function wq(b,w,$){if(b instanceof d.Name){let W=w===A6.Num;return $?W?d._`"[" + ${b} + "]"`:d._`"['" + ${b} + "']"`:W?d._`"/" + ${b}`:d._`"/" + ${b}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return $?(0,d.getProperty)(b).toString():"/"+O6(b)}JX.getErrorPath=wq;function HX(b,w,$=b.opts.strictSchema){if(!$)return;if(w=`strict mode: ${w}`,$===!0)throw Error(w);b.self.logger.warn(w)}JX.checkStrictMode=HX});var Qw=I((zX)=>{Object.defineProperty(zX,"__esModule",{value:!0});var Lb=u(),Kq={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")};zX.default=Kq});var c1=I((LX)=>{Object.defineProperty(LX,"__esModule",{value:!0});LX.extendErrors=LX.resetErrorsCount=LX.reportExtraError=LX.reportError=LX.keyword$DataError=LX.keywordError=void 0;var m=u(),X$=l(),Bb=Qw();LX.keywordError={message:({keyword:b})=>m.str`must pass "${b}" keyword validation`};LX.keyword$DataError={message:({keyword:b,schemaType:w})=>w?m.str`"${b}" keyword must be ${w} ($data)`:m.str`"${b}" keyword is invalid ($data)`};function Mq(b,w=LX.keywordError,$,W){let{it:Q}=b,{gen:G,compositeRule:X,allErrors:Y}=Q,H=qX(b,w,$);if(W!==null&&W!==void 0?W:X||Y)AX(G,H);else OX(Q,m._`[${H}]`)}LX.reportError=Mq;function Zq(b,w=LX.keywordError,$){let{it:W}=b,{gen:Q,compositeRule:G,allErrors:X}=W,Y=qX(b,w,$);if(AX(Q,Y),!(G||X))OX(W,Bb.default.vErrors)}LX.reportExtraError=Zq;function Iq(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)))}LX.resetErrorsCount=Iq;function jq({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)})}LX.extendErrors=jq;function AX(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 OX(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 vw={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 qX(b,w,$){let{createErrors:W}=b.it;if(W===!1)return m._`{}`;return Vq(b,w,$)}function Vq(b,w,$={}){let{gen:W,it:Q}=b,G=[Nq(Q,$),Eq(b,$)];return Tq(b,w,G),W.object(...G)}function Nq({errorPath:b},{instancePath:w}){let $=w?m.str`${b}${(0,X$.getErrorPath)(w,X$.Type.Str)}`:b;return[Bb.default.instancePath,(0,m.strConcat)(Bb.default.instancePath,$)]}function Eq({keyword:b,it:{errSchemaPath:w}},{schemaPath:$,parentSchema:W}){let Q=W?w:m.str`${w}/${b}`;if($)Q=m.str`${Q}${(0,X$.getErrorPath)($,X$.Type.Str)}`;return[vw.schemaPath,Q]}function Tq(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([vw.keyword,Q],[vw.params,typeof w=="function"?w(b):w||m._`{}`]),H.messages)W.push([vw.message,typeof $=="function"?$(b):$]);if(H.verbose)W.push([vw.schema,X],[vw.parentSchema,m._`${D}${z}`],[Bb.default.data,G]);if(J)W.push([vw.propertyName,J])}});var PX=I((FX)=>{Object.defineProperty(FX,"__esModule",{value:!0});FX.boolOrEmptySchema=FX.topBoolOrEmptySchema=void 0;var vq=c1(),Cq=u(),xq=Qw(),uq={message:"boolean schema is false"};function yq(b){let{gen:w,schema:$,validateName:W}=b;if($===!1)BX(b,!1);else if(typeof $=="object"&&$.$async===!0)w.return(xq.default.data);else w.assign(Cq._`${W}.errors`,null),w.return(!0)}FX.topBoolOrEmptySchema=yq;function hq(b,w){let{gen:$,schema:W}=b;if(W===!1)$.var(w,!1),BX(b);else $.var(w,!0)}FX.boolOrEmptySchema=hq;function BX(b,w){let{gen:$,data:W}=b,Q={gen:$,keyword:"false schema",data:W,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:b};(0,vq.reportError)(Q,uq,void 0,w)}});var U6=I((MX)=>{Object.defineProperty(MX,"__esModule",{value:!0});MX.getRules=MX.isJSONType=void 0;var cq=["string","number","integer","boolean","null","object","array"],gq=new Set(cq);function mq(b){return typeof b=="string"&&gq.has(b)}MX.isJSONType=mq;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:{}}}MX.getRules=nq});var B6=I((VX)=>{Object.defineProperty(VX,"__esModule",{value:!0});VX.shouldUseRule=VX.shouldUseGroup=VX.schemaHasRulesForType=void 0;function iq({schema:b,self:w},$){let W=w.RULES.types[$];return W&&W!==!0&&IX(b,W)}VX.schemaHasRulesForType=iq;function IX(b,w){return w.rules.some(($)=>jX(b,$))}VX.shouldUseGroup=IX;function jX(b,w){var $;return b[w.keyword]!==void 0||(($=w.definition.implements)===null||$===void 0?void 0:$.some((W)=>b[W]!==void 0))}VX.shouldUseRule=jX});var g1=I((SX)=>{Object.defineProperty(SX,"__esModule",{value:!0});SX.reportTypeError=SX.checkDataTypes=SX.checkDataType=SX.coerceAndCheckDataType=SX.getJSONTypes=SX.getSchemaTypes=SX.DataType=void 0;var dq=U6(),tq=B6(),rq=c1(),C=u(),EX=l(),tw;(function(b){b[b.Correct=0]="Correct",b[b.Wrong=1]="Wrong"})(tw||(SX.DataType=tw={}));function eq(b){let w=TX(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}SX.getSchemaTypes=eq;function TX(b){let w=Array.isArray(b)?b:b?[b]:[];if(w.every(dq.isJSONType))return w;throw Error("type must be JSONType or JSONType[]: "+w.join(","))}SX.getJSONTypes=TX;function sq(b,w){let{gen:$,data:W,opts:Q}=b,G=aq(w,Q.coerceTypes),X=w.length>0&&!(G.length===0&&w.length===1&&(0,tq.schemaHasRulesForType)(b,w[0]));if(X){let Y=K6(w,W,Q.strictNumbers,tw.Wrong);$.if(Y,()=>{if(G.length)bL(b,w,G);else P6(b)})}return X}SX.coerceAndCheckDataType=sq;var _X=new Set(["string","number","integer","boolean","null"]);function aq(b,w){return w?b.filter(($)=>_X.has($)||w==="array"&&$==="array"):[]}function bL(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(K6(w,Q,G.strictNumbers),()=>W.assign(Y,Q)));W.if(C._`${Y} !== undefined`);for(let J of $)if(_X.has(J)||J==="array"&&G.coerceTypes==="array")H(J);W.else(),P6(b),W.endIf(),W.if(C._`${Y} !== undefined`,()=>{W.assign(Q,Y),wL(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
4
4
  || (${X} == "string" && ${Q} && ${Q} == +${Q})`).assign(Y,C._`+${Q}`);return;case"integer":W.elseIf(C._`${X} === "boolean" || ${Q} === null
5
5
  || (${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"
6
- || ${X} === "boolean" || ${Q} === null`).assign(Y,C._`[${Q}]`)}}}function wL({gen:b,parentData:w,parentDataProperty:$},W){b.if(C._`${w} !== undefined`,()=>b.assign(C._`${w}[${$}]`,W))}function K6(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)}}SX.checkDataType=K6;function F6(b,w,$,W){if(b.length===1)return K6(b[0],w,$,W);let Q,G=(0,EX.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,K6(X,w,$,W));return Q}SX.checkDataTypes=F6;var $L={message:({schema:b})=>`must be ${b}`,params:({schema:b,schemaValue:w})=>typeof b=="string"?C._`{type: ${b}}`:C._`{type: ${w}}`};function P6(b){let w=WL(b);(0,rq.reportError)(w,$L)}SX.reportTypeError=P6;function WL(b){let{gen:w,data:$,schema:W}=b,Q=(0,EX.schemaRefOrVal)(b,W,"type");return{gen:w,keyword:"type",data:$,schema:W.type,schemaCode:Q,schemaValue:Q,parentSchema:W,params:{},it:b}}});var xX=I((kX)=>{Object.defineProperty(kX,"__esModule",{value:!0});kX.assignDefaults=void 0;var rw=u(),DL=l();function zL(b,w){let{properties:$,items:W}=b.schema;if(w==="object"&&$)for(let Q in $)vX(b,Q,$[Q].default);else if(w==="array"&&Array.isArray(W))W.forEach((Q,G)=>vX(b,G,Q.default))}kX.assignDefaults=zL;function vX(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,DL.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((hX)=>{Object.defineProperty(hX,"__esModule",{value:!0});hX.validateUnion=hX.validateArray=hX.usePattern=hX.callValidateCode=hX.schemaProperties=hX.allSchemaProperties=hX.noPropertyInData=hX.propertyInData=hX.isOwnProperty=hX.hasPropFunc=hX.reportMissingProp=hX.checkMissingProp=hX.checkReportMissingProp=void 0;var a=u(),M6=l(),jw=Qw(),AL=l();function OL(b,w){let{gen:$,data:W,it:Q}=b;$.if(I6($,W,w,Q.opts.ownProperties),()=>{b.setParams({missingProperty:a._`${w}`},!0),b.error()})}hX.checkReportMissingProp=OL;function qL({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}`)))}hX.checkMissingProp=qL;function LL(b,w){b.setParams({missingProperty:w},!0),b.error()}hX.reportMissingProp=LL;function uX(b){return b.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:a._`Object.prototype.hasOwnProperty`})}hX.hasPropFunc=uX;function Z6(b,w,$){return a._`${uX(b)}.call(${w}, ${$})`}hX.isOwnProperty=Z6;function UL(b,w,$,W){let Q=a._`${w}${(0,a.getProperty)($)} !== undefined`;return W?a._`${Q} && ${Z6(b,w,$)}`:Q}hX.propertyInData=UL;function I6(b,w,$,W){let Q=a._`${w}${(0,a.getProperty)($)} === undefined`;return W?(0,a.or)(Q,(0,a.not)(Z6(b,w,$))):Q}hX.noPropertyInData=I6;function yX(b){return b?Object.keys(b).filter((w)=>w!=="__proto__"):[]}hX.allSchemaProperties=yX;function BL(b,w){return yX(w).filter(($)=>!(0,M6.alwaysValidSchema)(b,w[$]))}hX.schemaProperties=BL;function KL({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})`}hX.callValidateCode=KL;var FL=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"?FL:(0,AL.useFunc)(b,Q)}(${$}, ${W})`})}hX.usePattern=PL;function ML(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:M6.Type.Num},G),w.if((0,a.not)(G),Y)})}}hX.validateArray=ML;function ZL(b){let{gen:w,schema:$,keyword:W,it:Q}=b;if(!Array.isArray($))throw Error("ajv implementation error");if($.some((H)=>(0,M6.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))}hX.validateUnion=ZL});var lX=I((mX)=>{Object.defineProperty(mX,"__esModule",{value:!0});mX.validateKeywordUsage=mX.validSchemaType=mX.funcKeywordCode=mX.macroKeywordCode=void 0;var Kb=u(),Cw=Qw(),xL=vb(),uL=g1();function yL(b,w){let{gen:$,keyword:W,schema:Q,parentSchema:G,it:X}=b,Y=w.macro.call(X.self,Q,G,X),H=cX($,W,Y);if(X.opts.validateSchema!==!1)X.self.validateSchema(Y,!0);let J=$.name("valid");b.subschema({schema:Y,schemaPath:Kb.nil,errSchemaPath:`${X.errSchemaPath}/${W}`,topSchemaRef:H,compositeRule:!0},J),b.pass(J,()=>b.error(!0))}mX.macroKeywordCode=yL;function hL(b,w){var $;let{gen:W,keyword:Q,schema:G,parentSchema:X,$data:Y,it:H}=b;gL(H,w);let J=!Y&&w.compile?w.compile.call(H.self,G,X,H):w.validate,D=cX(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(F(),w.modifying)gX(b);Z(()=>b.error())}else{let M=w.async?q():B();if(w.modifying)gX(b);Z(()=>fL(b,M))}}function q(){let M=W.let("ruleErrs",null);return W.try(()=>F(Kb._`await `),(v)=>W.assign(z,!1).if(Kb._`${v} instanceof ${H.ValidationError}`,()=>W.assign(M,Kb._`${v}.errors`),()=>W.throw(v))),M}function B(){let M=Kb._`${D}.errors`;return W.assign(M,null),F(Kb.nil),M}function F(M=w.async?Kb._`await `:Kb.nil){let v=H.opts.passContext?Cw.default.this:Cw.default.self,S=!(("compile"in w)&&!Y||w.schema===!1);W.assign(z,Kb._`${M}${(0,xL.callValidateCode)(b,D,v,S)}`,w.modifying)}function Z(M){var v;W.if((0,Kb.not)((v=w.valid)!==null&&v!==void 0?v:z),M)}}mX.funcKeywordCode=hL;function gX(b){let{gen:w,data:$,it:W}=b;w.if(W.parentData,()=>w.assign($,Kb._`${W.parentData}[${W.parentDataProperty}]`))}function fL(b,w){let{gen:$}=b;$.if(Kb._`Array.isArray(${w})`,()=>{$.assign(Cw.default.vErrors,Kb._`${Cw.default.vErrors} === null ? ${w} : ${Cw.default.vErrors}.concat(${w})`).assign(Cw.default.errors,Kb._`${Cw.default.vErrors}.length`),(0,uL.extendErrors)(b)},()=>b.error())}function gL({schemaEnv:b},w){if(w.async&&!b.$async)throw Error("async keyword in sync schema")}function cX(b,w,$){if($===void 0)throw Error(`keyword "${w}" failed to compile`);return b.scopeValue("keyword",typeof $=="function"?{ref:$}:{ref:$,code:(0,Kb.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")}mX.validSchemaType=cL;function mL({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)}}}mX.validateKeywordUsage=mL});var dX=I((pX)=>{Object.defineProperty(pX,"__esModule",{value:!0});pX.extendSubschemaMode=pX.extendSubschemaData=pX.getSubschema=void 0;var ob=u(),iX=l();function pL(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:ob._`${b.schemaPath}${(0,ob.getProperty)(w)}`,errSchemaPath:`${b.errSchemaPath}/${w}`}:{schema:Y[$],schemaPath:ob._`${b.schemaPath}${(0,ob.getProperty)(w)}${(0,ob.getProperty)($)}`,errSchemaPath:`${b.errSchemaPath}/${w}/${(0,iX.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')}pX.getSubschema=pL;function oL(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",ob._`${w.data}${(0,ob.getProperty)($)}`,!0);H(O),b.errorPath=ob.str`${J}${(0,iX.getErrorPath)($,W,z.jsPropertySyntax)}`,b.parentDataProperty=ob._`${$}`,b.dataPathArr=[...D,b.parentDataProperty]}if(Q!==void 0){let J=Q instanceof ob.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]}}pX.extendSubschemaData=oL;function dL(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=$}pX.extendSubschemaMode=dL});var j6=I((cE,tX)=>{tX.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 eX=I((mE,rX)=>{var Vw=rX.exports=function(b,w,$){if(typeof w=="function")$=w,w={};$=w.cb||$;var W=typeof $=="function"?$:$.pre||function(){},Q=$.post||function(){};Y$(w,W,Q,b,"",b)};Vw.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Vw.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Vw.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Vw.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 Y$(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 Vw.arrayKeywords)for(var O=0;O<z.length;O++)Y$(b,w,$,z[O],Q+"/"+D+"/"+O,G,Q,D,W,O)}else if(D in Vw.propsKeywords){if(z&&typeof z=="object")for(var q in z)Y$(b,w,$,z[q],Q+"/"+D+"/"+eL(q),G,Q,D,W,q)}else if(D in Vw.keywords||b.allKeys&&!(D in Vw.skipKeywords))Y$(b,w,$,z,Q+"/"+D,G,Q,D,W)}$(W,Q,G,X,Y,H,J)}}function eL(b){return b.replace(/~/g,"~0").replace(/\//g,"~1")}});var m1=I((wY)=>{Object.defineProperty(wY,"__esModule",{value:!0});wY.getSchemaRefs=wY.resolveUrl=wY.normalizeId=wY._getFullPath=wY.getFullPath=wY.inlineRef=void 0;var sL=l(),aL=j6(),b3=eX(),w3=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function $3(b,w=!0){if(typeof b=="boolean")return!0;if(w===!0)return!V6(b);if(!w)return!1;return sX(b)<=w}wY.inlineRef=$3;var W3=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function V6(b){for(let w in b){if(W3.has(w))return!0;let $=b[w];if(Array.isArray($)&&$.some(V6))return!0;if(typeof $=="object"&&V6($))return!0}return!1}function sX(b){let w=0;for(let $ in b){if($==="$ref")return 1/0;if(w++,w3.has($))continue;if(typeof b[$]=="object")(0,sL.eachItem)(b[$],(W)=>w+=sX(W));if(w===1/0)return 1/0}return w}function aX(b,w="",$){if($!==!1)w=ew(w);let W=b.parse(w);return bY(b,W)}wY.getFullPath=aX;function bY(b,w){return b.serialize(w).split("#")[0]+"#"}wY._getFullPath=bY;var Q3=/#\/?$/;function ew(b){return b?b.replace(Q3,""):""}wY.normalizeId=ew;function G3(b,w,$){return $=ew($),b.resolve(w,$)}wY.resolveUrl=G3;var X3=/^[a-z_][-a-z0-9._]*$/i;function Y3(b,w){if(typeof b=="boolean")return{};let{schemaId:$,uriResolver:W}=this.opts,Q=ew(b[$]||w),G={"":Q},X=aX(W,Q,!1),Y={},H=new Set;return b3(b,{allKeys:!0},(z,O,q,B)=>{if(B===void 0)return;let F=X+O,Z=G[B];if(typeof z[$]=="string")Z=M.call(this,z[$]);v.call(this,z.$anchor),v.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(F))if(S[0]==="#")J(z,Y[S],S),Y[S]=z;else this.refs[S]=F;return S}function v(S){if(typeof S=="string"){if(!X3.test(S))throw Error(`invalid anchor "${S}"`);M.call(this,`#${S}`)}}}),Y;function J(z,O,q){if(O!==void 0&&!aL(z,O))throw D(q)}function D(z){return Error(`reference "${z}" resolves to more than one schema`)}}wY.getSchemaRefs=Y3});var i1=I((BY)=>{Object.defineProperty(BY,"__esModule",{value:!0});BY.getData=BY.KeywordCxt=BY.validateFunctionCode=void 0;var YY=PX(),WY=c1(),E6=B6(),H$=c1(),O3=xX(),l1=lX(),N6=dX(),E=u(),k=Qw(),q3=m1(),Gw=l(),n1=g1();function L3(b){if(DY(b)){if(zY(b),JY(b)){K3(b);return}}HY(b,()=>(0,YY.topBoolOrEmptySchema)(b))}BY.validateFunctionCode=L3;function HY({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"; ${QY($,Q)}`),B3(b,Q),b.code(G)});else b.func(w,E._`${k.default.data}, ${U3(Q)}`,W.$async,()=>b.code(QY($,Q)).code(G))}function U3(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 B3(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 K3(b){let{schema:w,opts:$,gen:W}=b;HY(b,()=>{if($.$comment&&w.$comment)OY(b);if(I3(b),W.let(k.default.vErrors,null),W.let(k.default.errors,0),$.unevaluated)F3(b);AY(b),N3(b)});return}function F3(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 QY(b,w){let $=typeof b=="object"&&b[w.schemaId];return $&&(w.code.source||w.code.process)?E._`/*# sourceURL=${$} */`:E.nil}function P3(b,w){if(DY(b)){if(zY(b),JY(b)){M3(b,w);return}}(0,YY.boolOrEmptySchema)(b,w)}function JY({schema:b,self:w}){if(typeof b=="boolean")return!b;for(let $ in b)if(w.RULES.all[$])return!0;return!1}function DY(b){return typeof b.schema!="boolean"}function M3(b,w){let{schema:$,gen:W,opts:Q}=b;if(Q.$comment&&$.$comment)OY(b);j3(b),V3(b);let G=W.const("_errs",k.default.errors);AY(b,G),W.var(w,E._`${G} === ${k.default.errors}`)}function zY(b){(0,Gw.checkUnknownRules)(b),Z3(b)}function AY(b,w){if(b.opts.jtd)return GY(b,[],!1,w);let $=(0,WY.getSchemaTypes)(b.schema),W=(0,WY.coerceAndCheckDataType)(b,$);GY(b,$,!W,w)}function Z3(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 I3(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 j3(b){let w=b.schema[b.opts.schemaId];if(w)b.baseId=(0,q3.resolveUrl)(b.opts.uriResolver,b.baseId,w)}function V3(b){if(b.schema.$async&&!b.schemaEnv.$async)throw Error("async schema in sync schema")}function OY({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 X=E.str`${W}/$comment`,Y=b.scopeValue("root",{ref:w.root});b.code(E._`${k.default.self}.opts.$comment(${G}, ${X}, ${Y}.schema)`)}}function N3(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)E3(b);w.return(E._`${k.default.errors} === 0`)}}function E3({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 GY(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(()=>LY(b,"$ref",D.all.$ref.definition));return}if(!H.jtd)T3(b,w);Q.block(()=>{for(let O of D.rules)z(O);z(D.post)});function z(O){if(!(0,E6.shouldUseGroup)(G,O))return;if(O.type){if(Q.if((0,H$.checkDataType)(O.type,X,H.strictNumbers)),XY(b,O),w.length===1&&w[0]===O.type&&$)Q.else(),(0,H$.reportTypeError)(b);Q.endIf()}else XY(b,O);if(!Y)Q.if(E._`${k.default.errors} === ${W||0}`)}}function XY(b,w){let{gen:$,schema:W,opts:{useDefaults:Q}}=b;if(Q)(0,O3.assignDefaults)(b,w.type);$.block(()=>{for(let G of w.rules)if((0,E6.shouldUseRule)(W,G))LY(b,G.keyword,G.definition,w.type)})}function T3(b,w){if(b.schemaEnv.meta||!b.opts.strictTypes)return;if(_3(b,w),!b.opts.allowUnionTypes)S3(b,w);R3(b,b.dataTypes)}function _3(b,w){if(!w.length)return;if(!b.dataTypes.length){b.dataTypes=w;return}w.forEach(($)=>{if(!qY(b.dataTypes,$))T6(b,`type "${$}" not allowed by context "${b.dataTypes.join(",")}"`)}),k3(b,w)}function S3(b,w){if(w.length>1&&!(w.length===2&&w.includes("null")))T6(b,"use allowUnionTypes to allow union type keyword")}function R3(b,w){let $=b.self.RULES.all;for(let W in $){let Q=$[W];if(typeof Q=="object"&&(0,E6.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 qY(b,w){return b.includes(w)||w==="integer"&&b.includes("number")}function k3(b,w){let $=[];for(let W of b.dataTypes)if(qY(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 _6{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",UY(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",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?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,H$.checkDataTypes)(Y,w,Q.opts.strictNumbers,H$.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,N6.getSubschema)(this.it,b);(0,N6.extendSubschemaData)($,this.it,b),(0,N6.extendSubschemaMode)($,b);let W={...this.it,...$,items:void 0,props:void 0};return P3(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}}BY.KeywordCxt=_6;function LY(b,w,$,W){let Q=new _6(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 C3=/^\/(?:[^~]|~0|~1)*$/,x3=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function UY(b,{dataLevel:w,dataNames:$,dataPathArr:W}){let Q,G;if(b==="")return k.default.rootData;if(b[0]==="/"){if(!C3.test(b))throw Error(`Invalid JSON-pointer: ${b}`);Q=b,G=k.default.rootData}else{let J=x3.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}`}}BY.getData=UY});var J$=I((PY)=>{Object.defineProperty(PY,"__esModule",{value:!0});class FY extends Error{constructor(b){super("validation failed");this.errors=b,this.ajv=this.validation=!0}}PY.default=FY});var p1=I((ZY)=>{Object.defineProperty(ZY,"__esModule",{value:!0});var S6=m1();class MY extends Error{constructor(b,w,$,W){super(W||`can't resolve reference ${$} from id ${w}`);this.missingRef=(0,S6.resolveUrl)(b,w,$),this.missingSchema=(0,S6.normalizeId)((0,S6.getFullPath)(b,this.missingRef))}}ZY.default=MY});var z$=I((VY)=>{Object.defineProperty(VY,"__esModule",{value:!0});VY.resolveSchema=VY.getCompilingSchema=VY.resolveRef=VY.compileSchema=VY.SchemaEnv=void 0;var fb=u(),g3=J$(),xw=Qw(),gb=m1(),IY=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,gb.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={}}}VY.SchemaEnv=o1;function v6(b){let w=jY.call(this,b);if(w)return w;let $=(0,gb.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:g3.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:xw.default.data,parentData:xw.default.parentData,parentDataProperty:xw.default.parentDataProperty,dataNames:[xw.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(xw.default.scope)}return ${z}`,this.opts.code.process)D=this.opts.code.process(D,b);let q=Function(`${xw.default.self}`,`${xw.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:F}=J;if(q.evaluated={props:B instanceof fb.Name?void 0:B,items:F instanceof fb.Name?void 0:F,dynamicProps:B instanceof fb.Name,dynamicItems:F 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)}}VY.compileSchema=v6;function m3(b,w,$){var W;$=(0,gb.resolveUrl)(this.opts.uriResolver,w,$);let Q=b.refs[$];if(Q)return Q;let G=i3.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[$]=n3.call(this,G)}VY.resolveRef=m3;function n3(b){if((0,gb.inlineRef)(b.schema,this.opts.inlineRefs))return b.schema;return b.validate?b:v6.call(this,b)}function jY(b){for(let w of this._compilations)if(l3(w,b))return w}VY.getCompilingSchema=jY;function l3(b,w){return b.schema===w.schema&&b.root===w.root&&b.baseId===w.baseId}function i3(b,w){let $;while(typeof($=this.refs[w])=="string")w=$;return $||this.schemas[w]||D$.call(this,b,w)}function D$(b,w){let $=this.opts.uriResolver.parse(w),W=(0,gb._getFullPath)(this.opts.uriResolver,$),Q=(0,gb.getFullPath)(this.opts.uriResolver,b.baseId,void 0);if(Object.keys(b.schema).length>0&&W===Q)return R6.call(this,$,b);let G=(0,gb.normalizeId)(W),X=this.refs[G]||this.schemas[G];if(typeof X=="string"){let Y=D$.call(this,b,X);if(typeof(Y===null||Y===void 0?void 0:Y.schema)!=="object")return;return R6.call(this,$,Y)}if(typeof(X===null||X===void 0?void 0:X.schema)!=="object")return;if(!X.validate)v6.call(this,X);if(G===(0,gb.normalizeId)(w)){let{schema:Y}=X,{schemaId:H}=this.opts,J=Y[H];if(J)Q=(0,gb.resolveUrl)(this.opts.uriResolver,Q,J);return new o1({schema:Y,schemaId:H,root:b,baseId:Q})}return R6.call(this,$,X)}VY.resolveSchema=D$;var p3=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function R6(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,IY.unescapeFragment)(Y)];if(H===void 0)return;$=H;let J=typeof $==="object"&&$[this.opts.schemaId];if(!p3.has(Y)&&J)w=(0,gb.resolveUrl)(this.opts.uriResolver,w,J)}let G;if(typeof $!="boolean"&&$.$ref&&!(0,IY.schemaHasRulesButRef)($,this.RULES)){let Y=(0,gb.resolveUrl)(this.opts.uriResolver,w,$.$ref);G=D$.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 EY=I((dE,e3)=>{e3.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 C6=I((tE,RY)=>{var s3=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),_Y=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 a3=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function TY(b){return b.length=0,!0}function bU(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 wU(b){let w=0,$={error:!1,address:"",zone:""},W=[],Q=[],G=!1,X=!1,Y=bU;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=TY}else{Q.push(J);continue}}if(Q.length)if(Y===TY)$.zone=Q.join("");else if(X)W.push(Q.join(""));else W.push(k6(Q));return $.address=W.join(""),$}function SY(b){if($U(b,":")<2)return{host:b,isIPV6:!1};let w=wU(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 $U(b,w){let $=0;for(let W=0;W<b.length;W++)if(b[W]===w)$++;return $}function WU(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 QU(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 GU(b){let w=[];if(b.userinfo!==void 0)w.push(b.userinfo),w.push("@");if(b.host!==void 0){let $=unescape(b.host);if(!_Y($)){let W=SY($);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}RY.exports={nonSimpleDomain:a3,recomposeAuthority:GU,normalizeComponentEncoding:QU,removeDotSegments:WU,isIPv4:_Y,isUUID:s3,normalizeIPv6:SY,stringArrayToHexStripped:k6}});var uY=I((rE,xY)=>{var{isUUID:XU}=C6(),YU=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,HU=["http","https","ws","wss","urn","urn:uuid"];function JU(b){return HU.indexOf(b)!==-1}function x6(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 vY(b){if(!b.host)b.error=b.error||"HTTP URIs must have a host.";return b}function kY(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 DU(b){return b.secure=x6(b),b.resourceName=(b.path||"/")+(b.query?"?"+b.query:""),b.path=void 0,b.query=void 0,b}function zU(b){if(b.port===(x6(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 AU(b,w){if(!b.path)return b.error="URN can not be parsed",b;let $=b.path.match(YU);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 OU(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 X=b,Y=b.nss;return X.path=`${W||w.nid}:${Y}`,w.skipEscape=!0,X}function qU(b,w){let $=b;if($.uuid=$.nss,$.nss=void 0,!w.tolerant&&(!$.uuid||!XU($.uuid)))$.error=$.error||"UUID is not valid.";return $}function LU(b){let w=b;return w.nss=(b.uuid||"").toLowerCase(),w}var CY={scheme:"http",domainHost:!0,parse:vY,serialize:kY},UU={scheme:"https",domainHost:CY.domainHost,parse:vY,serialize:kY},A$={scheme:"ws",domainHost:!0,parse:DU,serialize:zU},BU={scheme:"wss",domainHost:A$.domainHost,parse:A$.parse,serialize:A$.serialize},KU={scheme:"urn",parse:AU,serialize:OU,skipNormalize:!0},FU={scheme:"urn:uuid",parse:qU,serialize:LU,skipNormalize:!0},O$={http:CY,https:UU,ws:A$,wss:BU,urn:KU,"urn:uuid":FU};Object.setPrototypeOf(O$,null);function u6(b){return b&&(O$[b]||O$[b.toLowerCase()])||void 0}xY.exports={wsIsSecure:x6,SCHEMES:O$,isValidSchemeName:JU,getSchemeHandler:u6}});var fY=I((eE,L$)=>{var{normalizeIPv6:PU,removeDotSegments:d1,recomposeAuthority:MU,normalizeComponentEncoding:q$,isIPv4:ZU,nonSimpleDomain:IU}=C6(),{SCHEMES:jU,getSchemeHandler:yY}=uY();function VU(b,w){if(typeof b==="string")b=db(Xw(b,w),w);else if(typeof b==="object")b=Xw(db(b,w),w);return b}function NU(b,w,$){let W=$?Object.assign({scheme:"null"},$):{scheme:"null"},Q=hY(Xw(b,W),Xw(w,W),W,!0);return W.skipEscape=!0,db(Q,W)}function hY(b,w,$,W){let Q={};if(!W)b=Xw(db(b,$),$),w=Xw(db(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 EU(b,w,$){if(typeof b==="string")b=unescape(b),b=db(q$(Xw(b,$),!0),{...$,skipEscape:!0});else if(typeof b==="object")b=db(q$(b,!0),{...$,skipEscape:!0});if(typeof w==="string")w=unescape(w),w=db(q$(Xw(w,$),!0),{...$,skipEscape:!0});else if(typeof w==="object")w=db(q$(w,!0),{...$,skipEscape:!0});return b.toLowerCase()===w.toLowerCase()}function db(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=yY(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=MU($);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 TU=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\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(TU);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(ZU(W.host)===!1){let H=PU(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=yY($.scheme||W.scheme);if(!$.unicodeSupport&&(!X||!X.unicodeSupport)){if(W.host&&($.domainHost||X&&X.domainHost)&&Q===!1&&IU(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 y6={SCHEMES:jU,normalize:VU,resolve:NU,resolveComponent:hY,equal:EU,serialize:db,parse:Xw};L$.exports=y6;L$.exports.default=y6;L$.exports.fastUri=y6});var mY=I((cY)=>{Object.defineProperty(cY,"__esModule",{value:!0});var gY=fY();gY.code='require("ajv/dist/runtime/uri").default';cY.default=gY});var rY=I((Yw)=>{Object.defineProperty(Yw,"__esModule",{value:!0});Yw.CodeGen=Yw.Name=Yw.nil=Yw.stringify=Yw.str=Yw._=Yw.KeywordCxt=void 0;var SU=i1();Object.defineProperty(Yw,"KeywordCxt",{enumerable:!0,get:function(){return SU.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 RU=J$(),oY=p1(),vU=U6(),t1=z$(),kU=u(),r1=m1(),U$=c1(),f6=l(),nY=EY(),CU=mY(),dY=(b,w)=>new RegExp(b,w);dY.code="new RegExp";var xU=["removeAdditional","useDefaults","coerceTypes"],uU=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),yU={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."},hU={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},lY=200;function fU(b){var w,$,W,Q,G,X,Y,H,J,D,z,O,q,B,F,Z,M,v,S,h,R,ib,sb,p$,o$;let D1=b.strict,d$=(w=b.code)===null||w===void 0?void 0:w.optimize,vW=d$===!0||d$===void 0?1:d$||0,kW=(W=($=b.code)===null||$===void 0?void 0:$.regExp)!==null&&W!==void 0?W:dY,yz=(Q=b.uriResolver)!==null&&Q!==void 0?Q:CU.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:vW,regExp:kW}:{optimize:vW,regExp:kW},loopRequired:(F=b.loopRequired)!==null&&F!==void 0?F:lY,loopEnum:(Z=b.loopEnum)!==null&&Z!==void 0?Z:lY,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:(ib=b.validateSchema)!==null&&ib!==void 0?ib:!0,validateFormats:(sb=b.validateFormats)!==null&&sb!==void 0?sb:!0,unicodeRegExp:(p$=b.unicodeRegExp)!==null&&p$!==void 0?p$:!0,int32range:(o$=b.int32range)!==null&&o$!==void 0?o$:!0,uriResolver:yz}}class B${constructor(b={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,b=this.opts={...b,...fU(b)};let{es5:w,lines:$}=this.opts.code;this.scope=new kU.ValueScope({scope:{},prefixes:uU,es5:w,lines:$}),this.logger=iU(b.logger);let W=b.validateFormats;if(b.validateFormats=!1,this.RULES=(0,vU.getRules)(),iY.call(this,yU,b,"NOT SUPPORTED"),iY.call(this,hU,b,"DEPRECATED","warn"),this._metaOpts=nU.call(this),b.formats)cU.call(this);if(this._addVocabularies(),this._addDefaultMetaSchema(),b.keywords)mU.call(this,b.keywords);if(typeof b.meta=="object")this.addMetaSchema(b.meta);gU.call(this),b.validateFormats=W}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:b,meta:w,schemaId:$}=this.opts,W=nY;if($==="id")W={...nY},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 oY.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=pY.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=pY.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(oU.call(this,$,w),!w)return(0,f6.eachItem)($,(Q)=>h6.call(this,Q)),this;tU.call(this,w);let W={...w,type:(0,U$.getJSONTypes)(w.type),schemaType:(0,U$.getJSONTypes)(w.schemaType)};return(0,f6.eachItem)($,W.type.length===0?(Q)=>h6.call(this,Q,W):(Q)=>W.type.forEach((G)=>h6.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]=tY(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}}}B$.ValidationError=RU.default;B$.MissingRefError=oY.default;Yw.default=B$;function iY(b,w,$,W="error"){for(let Q in b){let G=Q;if(G in w)this.logger[W](`${$}: option ${Q}. ${b[G]}`)}}function pY(b){return b=(0,r1.normalizeId)(b),this.schemas[b]||this.refs[b]}function gU(){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 mU(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 nU(){let b={...this.opts};for(let w of xU)delete b[w];return b}var lU={log(){},warn(){},error(){}};function iU(b){if(b===!1)return lU;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 pU=/^[a-z_$][a-z0-9_$:-]*$/i;function oU(b,w){let{RULES:$}=this;if((0,f6.eachItem)(b,(W)=>{if($.keywords[W])throw Error(`Keyword ${W} is already defined`);if(!pU.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 h6(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,U$.getJSONTypes)(w.type),schemaType:(0,U$.getJSONTypes)(w.schemaType)}};if(w.before)dU.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 dU(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 tU(b){let{metaSchema:w}=b;if(w===void 0)return;if(b.$data&&this.opts.$data)w=tY(w);b.validateSchema=this.compile(w,!0)}var rU={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function tY(b){return{anyOf:[b,rU]}}});var sY=I((eY)=>{Object.defineProperty(eY,"__esModule",{value:!0});var aU={keyword:"id",code(){throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};eY.default=aU});var QH=I(($H)=>{Object.defineProperty($H,"__esModule",{value:!0});$H.callRef=$H.getValidate=void 0;var wB=p1(),aY=vb(),Zb=u(),aw=Qw(),bH=z$(),K$=l(),$B={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=bH.resolveRef.call(H,J,Q,$);if(D===void 0)throw new wB.default(W.opts.uriResolver,Q,$);if(D instanceof bH.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,Zb._`${B}.validate`,J,J.$async)}function O(B){let F=wH(b,B);F$(b,F,B,B.$async)}function q(B){let F=w.scopeValue("schema",Y.code.source===!0?{ref:B,code:(0,Zb.stringify)(B)}:{ref:B}),Z=w.name("valid"),M=b.subschema({schema:B,dataTypes:[],schemaPath:Zb.nil,topSchemaRef:F,errSchemaPath:$},Z);b.mergeEvaluated(M),b.ok(Z)}}};function wH(b,w){let{gen:$}=b;return w.validate?$.scopeValue("validate",{ref:w.validate}):Zb._`${$.scopeValue("wrapper",{ref:w})}.validate`}$H.getValidate=wH;function F$(b,w,$,W){let{gen:Q,it:G}=b,{allErrors:X,schemaEnv:Y,opts:H}=G,J=H.passContext?aw.default.this:Zb.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(Zb._`await ${(0,aY.callValidateCode)(b,w,J)}`),q(w),!X)Q.assign(B,!0)},(F)=>{if(Q.if(Zb._`!(${F} instanceof ${G.ValidationError})`,()=>Q.throw(F)),O(F),!X)Q.assign(B,!1)}),b.ok(B)}function z(){b.result((0,aY.callValidateCode)(b,w,J),()=>q(w),()=>O(w))}function O(B){let F=Zb._`${B}.errors`;Q.assign(aw.default.vErrors,Zb._`${aw.default.vErrors} === null ? ${F} : ${aw.default.vErrors}.concat(${F})`),Q.assign(aw.default.errors,Zb._`${aw.default.vErrors}.length`)}function q(B){var F;if(!G.opts.unevaluated)return;let Z=(F=$===null||$===void 0?void 0:$.validate)===null||F===void 0?void 0:F.evaluated;if(G.props!==!0)if(Z&&!Z.dynamicProps){if(Z.props!==void 0)G.props=K$.mergeEvaluated.props(Q,Z.props,G.props)}else{let M=Q.var("props",Zb._`${B}.evaluated.props`);G.props=K$.mergeEvaluated.props(Q,M,G.props,Zb.Name)}if(G.items!==!0)if(Z&&!Z.dynamicItems){if(Z.items!==void 0)G.items=K$.mergeEvaluated.items(Q,Z.items,G.items)}else{let M=Q.var("items",Zb._`${B}.evaluated.items`);G.items=K$.mergeEvaluated.items(Q,M,G.items,Zb.Name)}}}$H.callRef=F$;$H.default=$B});var XH=I((GH)=>{Object.defineProperty(GH,"__esModule",{value:!0});var GB=sY(),XB=QH(),YB=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",GB.default,XB.default];GH.default=YB});var HH=I((YH)=>{Object.defineProperty(YH,"__esModule",{value:!0});var P$=u(),Nw=P$.operators,M$={maximum:{okStr:"<=",ok:Nw.LTE,fail:Nw.GT},minimum:{okStr:">=",ok:Nw.GTE,fail:Nw.LT},exclusiveMaximum:{okStr:"<",ok:Nw.LT,fail:Nw.GTE},exclusiveMinimum:{okStr:">",ok:Nw.GT,fail:Nw.LTE}},JB={message:({keyword:b,schemaCode:w})=>P$.str`must be ${M$[b].okStr} ${w}`,params:({keyword:b,schemaCode:w})=>P$._`{comparison: ${M$[b].okStr}, limit: ${w}}`},DB={keyword:Object.keys(M$),type:"number",schemaType:"number",$data:!0,error:JB,code(b){let{keyword:w,data:$,schemaCode:W}=b;b.fail$data(P$._`${$} ${M$[w].fail} ${W} || isNaN(${$})`)}};YH.default=DB});var DH=I((JH)=>{Object.defineProperty(JH,"__esModule",{value:!0});var e1=u(),AB={message:({schemaCode:b})=>e1.str`must be multiple of ${b}`,params:({schemaCode:b})=>e1._`{multipleOf: ${b}}`},OB={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:AB,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}))`)}};JH.default=OB});var OH=I((AH)=>{Object.defineProperty(AH,"__esModule",{value:!0});function zH(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 $}AH.default=zH;zH.code='require("ajv/dist/runtime/ucs2length").default'});var LH=I((qH)=>{Object.defineProperty(qH,"__esModule",{value:!0});var uw=u(),UB=l(),BB=OH(),KB={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}}`},FB={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:KB,code(b){let{keyword:w,data:$,schemaCode:W,it:Q}=b,G=w==="maxLength"?uw.operators.GT:uw.operators.LT,X=Q.opts.unicode===!1?uw._`${$}.length`:uw._`${(0,UB.useFunc)(b.gen,BB.default)}(${$})`;b.fail$data(uw._`${X} ${G} ${W}`)}};qH.default=FB});var BH=I((UH)=>{Object.defineProperty(UH,"__esModule",{value:!0});var MB=vb(),Z$=u(),ZB={message:({schemaCode:b})=>Z$.str`must match pattern "${b}"`,params:({schemaCode:b})=>Z$._`{pattern: ${b}}`},IB={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:ZB,code(b){let{data:w,$data:$,schema:W,schemaCode:Q,it:G}=b,X=G.opts.unicodeRegExp?"u":"",Y=$?Z$._`(new RegExp(${Q}, ${X}))`:(0,MB.usePattern)(b,W);b.fail$data(Z$._`!${Y}.test(${w})`)}};UH.default=IB});var FH=I((KH)=>{Object.defineProperty(KH,"__esModule",{value:!0});var s1=u(),VB={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}}`},NB={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:VB,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}`)}};KH.default=NB});var MH=I((PH)=>{Object.defineProperty(PH,"__esModule",{value:!0});var a1=vb(),b0=u(),TB=l(),_B={message:({params:{missingProperty:b}})=>b0.str`must have required property '${b}'`,params:({params:{missingProperty:b}})=>b0._`{missingProperty: ${b}}`},SB={keyword:"required",type:"object",schemaType:"array",$data:!0,error:_B,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 F of $)if((q===null||q===void 0?void 0:q[F])===void 0&&!B.has(F)){let Z=X.schemaEnv.baseId+X.errSchemaPath,M=`required property "${F}" is not defined at "${Z}" (strictRequired)`;(0,TB.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)}}};PH.default=SB});var IH=I((ZH)=>{Object.defineProperty(ZH,"__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}}`},kB={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}`)}};ZH.default=kB});var I$=I((VH)=>{Object.defineProperty(VH,"__esModule",{value:!0});var jH=j6();jH.code='require("ajv/dist/runtime/equal").default';VH.default=jH});var EH=I((NH)=>{Object.defineProperty(NH,"__esModule",{value:!0});var g6=c1(),qb=u(),uB=l(),yB=I$(),hB={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}}`},fB={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:hB,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,g6.getSchemaTypes)(G.items):[];b.block$data(H,D,qb._`${X} === false`),b.ok(H);function D(){let B=w.let("i",qb._`${$}.length`),F=w.let("j");b.setParams({i:B,j:F}),w.assign(H,!0),w.if(qb._`${B} > 1`,()=>(z()?O:q)(B,F))}function z(){return J.length>0&&!J.some((B)=>B==="object"||B==="array")}function O(B,F){let Z=w.name("item"),M=(0,g6.checkDataTypes)(J,Z,Y.opts.strictNumbers,g6.DataType.Wrong),v=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 ${v}[${Z}] == "number"`,()=>{w.assign(F,qb._`${v}[${Z}]`),b.error(),w.assign(H,!1).break()}).code(qb._`${v}[${Z}] = ${B}`)})}function q(B,F){let Z=(0,uB.useFunc)(w,yB.default),M=w.name("outer");w.label(M).for(qb._`;${B}--;`,()=>w.for(qb._`${F} = ${B}; ${F}--;`,()=>w.if(qb._`${Z}(${$}[${B}], ${$}[${F}])`,()=>{b.error(),w.assign(H,!1).break(M)})))}}};NH.default=fB});var _H=I((TH)=>{Object.defineProperty(TH,"__esModule",{value:!0});var c6=u(),cB=l(),mB=I$(),nB={message:"must be equal to constant",params:({schemaCode:b})=>c6._`{allowedValue: ${b}}`},lB={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,cB.useFunc)(w,mB.default)}(${$}, ${Q})`);else b.fail(c6._`${G} !== ${$}`)}};TH.default=lB});var RH=I((SH)=>{Object.defineProperty(SH,"__esModule",{value:!0});var $0=u(),pB=l(),oB=I$(),dB={message:"must be equal to one of the allowed values",params:({schemaCode:b})=>$0._`{allowedValues: ${b}}`},tB={keyword:"enum",schemaType:"array",$data:!0,error:dB,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,pB.useFunc)(w,oB.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,F)=>O(q,F)))}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 F=Q[B];return typeof F==="object"&&F!==null?$0._`${J()}(${$}, ${q}[${B}])`:$0._`${$} === ${F}`}}};SH.default=tB});var kH=I((vH)=>{Object.defineProperty(vH,"__esModule",{value:!0});var eB=HH(),sB=DH(),aB=LH(),bK=BH(),wK=FH(),$K=MH(),WK=IH(),QK=EH(),GK=_H(),XK=RH(),YK=[eB.default,sB.default,aB.default,bK.default,wK.default,$K.default,WK.default,QK.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},GK.default,XK.default];vH.default=YK});var n6=I((xH)=>{Object.defineProperty(xH,"__esModule",{value:!0});xH.validateAdditionalItems=void 0;var yw=u(),m6=l(),JK={message:({params:{len:b}})=>yw.str`must NOT have more than ${b} items`,params:({params:{len:b}})=>yw._`{limit: ${b}}`},DK={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:JK,code(b){let{parentSchema:w,it:$}=b,{items:W}=w;if(!Array.isArray(W)){(0,m6.checkStrictMode)($,'"additionalItems" is ignored when "items" is not an array of schemas');return}CH(b,W)}};function CH(b,w){let{gen:$,schema:W,data:Q,keyword:G,it:X}=b;X.items=!0;let Y=$.const("len",yw._`${Q}.length`);if(W===!1)b.setParams({len:w.length}),b.pass(yw._`${Y} <= ${w.length}`);else if(typeof W=="object"&&!(0,m6.alwaysValidSchema)(X,W)){let J=$.var("valid",yw._`${Y} <= ${w.length}`);$.if((0,yw.not)(J),()=>H(J)),b.ok(J)}function H(J){$.forRange("i",w.length,Y,(D)=>{if(b.subschema({keyword:G,dataProp:D,dataPropType:m6.Type.Num},J),!X.allErrors)$.if((0,yw.not)(J),()=>$.break())})}}xH.validateAdditionalItems=CH;xH.default=DK});var l6=I((fH)=>{Object.defineProperty(fH,"__esModule",{value:!0});fH.validateTuple=void 0;var yH=u(),j$=l(),AK=vb(),OK={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(b){let{schema:w,it:$}=b;if(Array.isArray(w))return hH(b,"additionalItems",w);if($.items=!0,(0,j$.alwaysValidSchema)($,w))return;b.ok((0,AK.validateArray)(b))}};function hH(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",yH._`${G}.length`);$.forEach((z,O)=>{if((0,j$.alwaysValidSchema)(Y,z))return;W.if(yH._`${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,F=B===z.minItems&&(B===z.maxItems||z[w]===!1);if(O.strictTuples&&!F){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)}}}fH.validateTuple=hH;fH.default=OK});var mH=I((cH)=>{Object.defineProperty(cH,"__esModule",{value:!0});var LK=l6(),UK={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:(b)=>(0,LK.validateTuple)(b,"items")};cH.default=UK});var iH=I((lH)=>{Object.defineProperty(lH,"__esModule",{value:!0});var nH=u(),KK=l(),FK=vb(),PK=n6(),MK={message:({params:{len:b}})=>nH.str`must NOT have more than ${b} items`,params:({params:{len:b}})=>nH._`{limit: ${b}}`},ZK={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:MK,code(b){let{schema:w,parentSchema:$,it:W}=b,{prefixItems:Q}=$;if(W.items=!0,(0,KK.alwaysValidSchema)(W,w))return;if(Q)(0,PK.validateAdditionalItems)(b,Q);else b.ok((0,FK.validateArray)(b))}};lH.default=ZK});var oH=I((pH)=>{Object.defineProperty(pH,"__esModule",{value:!0});var kb=u(),V$=l(),jK={message:({params:{min:b,max:w}})=>w===void 0?kb.str`must contain at least ${b} valid item(s)`:kb.str`must contain at least ${b} and no more than ${w} valid item(s)`,params:({params:{min:b,max:w}})=>w===void 0?kb._`{minContains: ${b}}`:kb._`{minContains: ${b}, maxContains: ${w}}`},VK={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:jK,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",kb._`${Q}.length`);if(b.setParams({min:X,max:Y}),Y===void 0&&X===0){(0,V$.checkStrictMode)(G,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(Y!==void 0&&X>Y){(0,V$.checkStrictMode)(G,'"minContains" > "maxContains" is always invalid'),b.fail();return}if((0,V$.alwaysValidSchema)(G,$)){let F=kb._`${D} >= ${X}`;if(Y!==void 0)F=kb._`${F} && ${D} <= ${Y}`;b.pass(F);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(kb._`${Q}.length > 0`,O)}else w.let(z,!1),O();b.result(z,()=>b.reset());function O(){let F=w.name("_valid"),Z=w.let("count",0);q(F,()=>w.if(F,()=>B(Z)))}function q(F,Z){w.forRange("i",0,D,(M)=>{b.subschema({keyword:"contains",dataProp:M,dataPropType:V$.Type.Num,compositeRule:!0},F),Z()})}function B(F){if(w.code(kb._`${F}++`),Y===void 0)w.if(kb._`${F} >= ${X}`,()=>w.assign(z,!0).break());else if(w.if(kb._`${F} > ${Y}`,()=>w.assign(z,!1).break()),X===1)w.assign(z,!0);else w.if(kb._`${F} >= ${X}`,()=>w.assign(z,!0))}}};pH.default=VK});var aH=I((rH)=>{Object.defineProperty(rH,"__esModule",{value:!0});rH.validateSchemaDeps=rH.validatePropertyDeps=rH.error=void 0;var i6=u(),EK=l(),W0=vb();rH.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
+ || ${X} === "boolean" || ${Q} === null`).assign(Y,C._`[${Q}]`)}}}function wL({gen:b,parentData:w,parentDataProperty:$},W){b.if(C._`${w} !== undefined`,()=>b.assign(C._`${w}[${$}]`,W))}function F6(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)}}SX.checkDataType=F6;function K6(b,w,$,W){if(b.length===1)return F6(b[0],w,$,W);let Q,G=(0,EX.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,F6(X,w,$,W));return Q}SX.checkDataTypes=K6;var $L={message:({schema:b})=>`must be ${b}`,params:({schema:b,schemaValue:w})=>typeof b=="string"?C._`{type: ${b}}`:C._`{type: ${w}}`};function P6(b){let w=WL(b);(0,rq.reportError)(w,$L)}SX.reportTypeError=P6;function WL(b){let{gen:w,data:$,schema:W}=b,Q=(0,EX.schemaRefOrVal)(b,W,"type");return{gen:w,keyword:"type",data:$,schema:W.type,schemaCode:Q,schemaValue:Q,parentSchema:W,params:{},it:b}}});var xX=I((vX)=>{Object.defineProperty(vX,"__esModule",{value:!0});vX.assignDefaults=void 0;var rw=u(),DL=l();function zL(b,w){let{properties:$,items:W}=b.schema;if(w==="object"&&$)for(let Q in $)kX(b,Q,$[Q].default);else if(w==="array"&&Array.isArray(W))W.forEach((Q,G)=>kX(b,G,Q.default))}vX.assignDefaults=zL;function kX(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,DL.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((hX)=>{Object.defineProperty(hX,"__esModule",{value:!0});hX.validateUnion=hX.validateArray=hX.usePattern=hX.callValidateCode=hX.schemaProperties=hX.allSchemaProperties=hX.noPropertyInData=hX.propertyInData=hX.isOwnProperty=hX.hasPropFunc=hX.reportMissingProp=hX.checkMissingProp=hX.checkReportMissingProp=void 0;var a=u(),M6=l(),Vw=Qw(),AL=l();function OL(b,w){let{gen:$,data:W,it:Q}=b;$.if(I6($,W,w,Q.opts.ownProperties),()=>{b.setParams({missingProperty:a._`${w}`},!0),b.error()})}hX.checkReportMissingProp=OL;function qL({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}`)))}hX.checkMissingProp=qL;function LL(b,w){b.setParams({missingProperty:w},!0),b.error()}hX.reportMissingProp=LL;function uX(b){return b.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:a._`Object.prototype.hasOwnProperty`})}hX.hasPropFunc=uX;function Z6(b,w,$){return a._`${uX(b)}.call(${w}, ${$})`}hX.isOwnProperty=Z6;function UL(b,w,$,W){let Q=a._`${w}${(0,a.getProperty)($)} !== undefined`;return W?a._`${Q} && ${Z6(b,w,$)}`:Q}hX.propertyInData=UL;function I6(b,w,$,W){let Q=a._`${w}${(0,a.getProperty)($)} === undefined`;return W?(0,a.or)(Q,(0,a.not)(Z6(b,w,$))):Q}hX.noPropertyInData=I6;function yX(b){return b?Object.keys(b).filter((w)=>w!=="__proto__"):[]}hX.allSchemaProperties=yX;function BL(b,w){return yX(w).filter(($)=>!(0,M6.alwaysValidSchema)(b,w[$]))}hX.schemaProperties=BL;function FL({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=[[Vw.default.instancePath,(0,a.strConcat)(Vw.default.instancePath,G)],[Vw.default.parentData,X.parentData],[Vw.default.parentDataProperty,X.parentDataProperty],[Vw.default.rootData,Vw.default.rootData]];if(X.opts.dynamicRef)z.push([Vw.default.dynamicAnchors,Vw.default.dynamicAnchors]);let O=a._`${D}, ${$.object(...z)}`;return H!==a.nil?a._`${Y}.call(${H}, ${O})`:a._`${Y}(${O})`}hX.callValidateCode=FL;var KL=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"?KL:(0,AL.useFunc)(b,Q)}(${$}, ${W})`})}hX.usePattern=PL;function ML(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:M6.Type.Num},G),w.if((0,a.not)(G),Y)})}}hX.validateArray=ML;function ZL(b){let{gen:w,schema:$,keyword:W,it:Q}=b;if(!Array.isArray($))throw Error("ajv implementation error");if($.some((H)=>(0,M6.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))}hX.validateUnion=ZL});var lX=I((mX)=>{Object.defineProperty(mX,"__esModule",{value:!0});mX.validateKeywordUsage=mX.validSchemaType=mX.funcKeywordCode=mX.macroKeywordCode=void 0;var Fb=u(),Cw=Qw(),xL=vb(),uL=c1();function yL(b,w){let{gen:$,keyword:W,schema:Q,parentSchema:G,it:X}=b,Y=w.macro.call(X.self,Q,G,X),H=gX($,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))}mX.macroKeywordCode=yL;function hL(b,w){var $;let{gen:W,keyword:Q,schema:G,parentSchema:X,$data:Y,it:H}=b;cL(H,w);let J=!Y&&w.compile?w.compile.call(H.self,G,X,H):w.validate,D=gX(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)cX(b);Z(()=>b.error())}else{let M=w.async?q():B();if(w.modifying)cX(b);Z(()=>fL(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?Cw.default.this:Cw.default.self,S=!(("compile"in w)&&!Y||w.schema===!1);W.assign(z,Fb._`${M}${(0,xL.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)}}mX.funcKeywordCode=hL;function cX(b){let{gen:w,data:$,it:W}=b;w.if(W.parentData,()=>w.assign($,Fb._`${W.parentData}[${W.parentDataProperty}]`))}function fL(b,w){let{gen:$}=b;$.if(Fb._`Array.isArray(${w})`,()=>{$.assign(Cw.default.vErrors,Fb._`${Cw.default.vErrors} === null ? ${w} : ${Cw.default.vErrors}.concat(${w})`).assign(Cw.default.errors,Fb._`${Cw.default.vErrors}.length`),(0,uL.extendErrors)(b)},()=>b.error())}function cL({schemaEnv:b},w){if(w.async&&!b.$async)throw Error("async keyword in sync schema")}function gX(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 gL(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")}mX.validSchemaType=gL;function mL({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)}}}mX.validateKeywordUsage=mL});var dX=I((pX)=>{Object.defineProperty(pX,"__esModule",{value:!0});pX.extendSubschemaMode=pX.extendSubschemaData=pX.getSubschema=void 0;var ob=u(),iX=l();function pL(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:ob._`${b.schemaPath}${(0,ob.getProperty)(w)}`,errSchemaPath:`${b.errSchemaPath}/${w}`}:{schema:Y[$],schemaPath:ob._`${b.schemaPath}${(0,ob.getProperty)(w)}${(0,ob.getProperty)($)}`,errSchemaPath:`${b.errSchemaPath}/${w}/${(0,iX.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')}pX.getSubschema=pL;function oL(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",ob._`${w.data}${(0,ob.getProperty)($)}`,!0);H(O),b.errorPath=ob.str`${J}${(0,iX.getErrorPath)($,W,z.jsPropertySyntax)}`,b.parentDataProperty=ob._`${$}`,b.dataPathArr=[...D,b.parentDataProperty]}if(Q!==void 0){let J=Q instanceof ob.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]}}pX.extendSubschemaData=oL;function dL(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=$}pX.extendSubschemaMode=dL});var j6=I((gE,tX)=>{tX.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 eX=I((mE,rX)=>{var Nw=rX.exports=function(b,w,$){if(typeof w=="function")$=w,w={};$=w.cb||$;var W=typeof $=="function"?$:$.pre||function(){},Q=$.post||function(){};Y$(w,W,Q,b,"",b)};Nw.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Nw.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Nw.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Nw.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 Y$(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 Nw.arrayKeywords)for(var O=0;O<z.length;O++)Y$(b,w,$,z[O],Q+"/"+D+"/"+O,G,Q,D,W,O)}else if(D in Nw.propsKeywords){if(z&&typeof z=="object")for(var q in z)Y$(b,w,$,z[q],Q+"/"+D+"/"+eL(q),G,Q,D,W,q)}else if(D in Nw.keywords||b.allKeys&&!(D in Nw.skipKeywords))Y$(b,w,$,z,Q+"/"+D,G,Q,D,W)}$(W,Q,G,X,Y,H,J)}}function eL(b){return b.replace(/~/g,"~0").replace(/\//g,"~1")}});var m1=I((wY)=>{Object.defineProperty(wY,"__esModule",{value:!0});wY.getSchemaRefs=wY.resolveUrl=wY.normalizeId=wY._getFullPath=wY.getFullPath=wY.inlineRef=void 0;var sL=l(),aL=j6(),b3=eX(),w3=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function $3(b,w=!0){if(typeof b=="boolean")return!0;if(w===!0)return!V6(b);if(!w)return!1;return sX(b)<=w}wY.inlineRef=$3;var W3=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function V6(b){for(let w in b){if(W3.has(w))return!0;let $=b[w];if(Array.isArray($)&&$.some(V6))return!0;if(typeof $=="object"&&V6($))return!0}return!1}function sX(b){let w=0;for(let $ in b){if($==="$ref")return 1/0;if(w++,w3.has($))continue;if(typeof b[$]=="object")(0,sL.eachItem)(b[$],(W)=>w+=sX(W));if(w===1/0)return 1/0}return w}function aX(b,w="",$){if($!==!1)w=ew(w);let W=b.parse(w);return bY(b,W)}wY.getFullPath=aX;function bY(b,w){return b.serialize(w).split("#")[0]+"#"}wY._getFullPath=bY;var Q3=/#\/?$/;function ew(b){return b?b.replace(Q3,""):""}wY.normalizeId=ew;function G3(b,w,$){return $=ew($),b.resolve(w,$)}wY.resolveUrl=G3;var X3=/^[a-z_][-a-z0-9._]*$/i;function Y3(b,w){if(typeof b=="boolean")return{};let{schemaId:$,uriResolver:W}=this.opts,Q=ew(b[$]||w),G={"":Q},X=aX(W,Q,!1),Y={},H=new Set;return b3(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(!X3.test(S))throw Error(`invalid anchor "${S}"`);M.call(this,`#${S}`)}}}),Y;function J(z,O,q){if(O!==void 0&&!aL(z,O))throw D(q)}function D(z){return Error(`reference "${z}" resolves to more than one schema`)}}wY.getSchemaRefs=Y3});var i1=I((BY)=>{Object.defineProperty(BY,"__esModule",{value:!0});BY.getData=BY.KeywordCxt=BY.validateFunctionCode=void 0;var YY=PX(),WY=g1(),E6=B6(),H$=g1(),O3=xX(),l1=lX(),N6=dX(),E=u(),v=Qw(),q3=m1(),Gw=l(),n1=c1();function L3(b){if(DY(b)){if(zY(b),JY(b)){F3(b);return}}HY(b,()=>(0,YY.topBoolOrEmptySchema)(b))}BY.validateFunctionCode=L3;function HY({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"; ${QY($,Q)}`),B3(b,Q),b.code(G)});else b.func(w,E._`${v.default.data}, ${U3(Q)}`,W.$async,()=>b.code(QY($,Q)).code(G))}function U3(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 B3(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 F3(b){let{schema:w,opts:$,gen:W}=b;HY(b,()=>{if($.$comment&&w.$comment)OY(b);if(I3(b),W.let(v.default.vErrors,null),W.let(v.default.errors,0),$.unevaluated)K3(b);AY(b),N3(b)});return}function K3(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 QY(b,w){let $=typeof b=="object"&&b[w.schemaId];return $&&(w.code.source||w.code.process)?E._`/*# sourceURL=${$} */`:E.nil}function P3(b,w){if(DY(b)){if(zY(b),JY(b)){M3(b,w);return}}(0,YY.boolOrEmptySchema)(b,w)}function JY({schema:b,self:w}){if(typeof b=="boolean")return!b;for(let $ in b)if(w.RULES.all[$])return!0;return!1}function DY(b){return typeof b.schema!="boolean"}function M3(b,w){let{schema:$,gen:W,opts:Q}=b;if(Q.$comment&&$.$comment)OY(b);j3(b),V3(b);let G=W.const("_errs",v.default.errors);AY(b,G),W.var(w,E._`${G} === ${v.default.errors}`)}function zY(b){(0,Gw.checkUnknownRules)(b),Z3(b)}function AY(b,w){if(b.opts.jtd)return GY(b,[],!1,w);let $=(0,WY.getSchemaTypes)(b.schema),W=(0,WY.coerceAndCheckDataType)(b,$);GY(b,$,!W,w)}function Z3(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 I3(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 j3(b){let w=b.schema[b.opts.schemaId];if(w)b.baseId=(0,q3.resolveUrl)(b.opts.uriResolver,b.baseId,w)}function V3(b){if(b.schema.$async&&!b.schemaEnv.$async)throw Error("async schema in sync schema")}function OY({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 N3(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)E3(b);w.return(E._`${v.default.errors} === 0`)}}function E3({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 GY(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(()=>LY(b,"$ref",D.all.$ref.definition));return}if(!H.jtd)T3(b,w);Q.block(()=>{for(let O of D.rules)z(O);z(D.post)});function z(O){if(!(0,E6.shouldUseGroup)(G,O))return;if(O.type){if(Q.if((0,H$.checkDataType)(O.type,X,H.strictNumbers)),XY(b,O),w.length===1&&w[0]===O.type&&$)Q.else(),(0,H$.reportTypeError)(b);Q.endIf()}else XY(b,O);if(!Y)Q.if(E._`${v.default.errors} === ${W||0}`)}}function XY(b,w){let{gen:$,schema:W,opts:{useDefaults:Q}}=b;if(Q)(0,O3.assignDefaults)(b,w.type);$.block(()=>{for(let G of w.rules)if((0,E6.shouldUseRule)(W,G))LY(b,G.keyword,G.definition,w.type)})}function T3(b,w){if(b.schemaEnv.meta||!b.opts.strictTypes)return;if(_3(b,w),!b.opts.allowUnionTypes)S3(b,w);R3(b,b.dataTypes)}function _3(b,w){if(!w.length)return;if(!b.dataTypes.length){b.dataTypes=w;return}w.forEach(($)=>{if(!qY(b.dataTypes,$))T6(b,`type "${$}" not allowed by context "${b.dataTypes.join(",")}"`)}),v3(b,w)}function S3(b,w){if(w.length>1&&!(w.length===2&&w.includes("null")))T6(b,"use allowUnionTypes to allow union type keyword")}function R3(b,w){let $=b.self.RULES.all;for(let W in $){let Q=$[W];if(typeof Q=="object"&&(0,E6.shouldUseRule)(b.schema,Q)){let{type:G}=Q.definition;if(G.length&&!G.some((X)=>k3(w,X)))T6(b,`missing type "${G.join(",")}" for keyword "${W}"`)}}}function k3(b,w){return b.includes(w)||w==="number"&&b.includes("integer")}function qY(b,w){return b.includes(w)||w==="integer"&&b.includes("number")}function v3(b,w){let $=[];for(let W of b.dataTypes)if(qY(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 _6{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",UY(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,H$.checkDataTypes)(Y,w,Q.opts.strictNumbers,H$.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,N6.getSubschema)(this.it,b);(0,N6.extendSubschemaData)($,this.it,b),(0,N6.extendSubschemaMode)($,b);let W={...this.it,...$,items:void 0,props:void 0};return P3(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}}BY.KeywordCxt=_6;function LY(b,w,$,W){let Q=new _6(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 C3=/^\/(?:[^~]|~0|~1)*$/,x3=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function UY(b,{dataLevel:w,dataNames:$,dataPathArr:W}){let Q,G;if(b==="")return v.default.rootData;if(b[0]==="/"){if(!C3.test(b))throw Error(`Invalid JSON-pointer: ${b}`);Q=b,G=v.default.rootData}else{let J=x3.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}`}}BY.getData=UY});var J$=I((PY)=>{Object.defineProperty(PY,"__esModule",{value:!0});class KY extends Error{constructor(b){super("validation failed");this.errors=b,this.ajv=this.validation=!0}}PY.default=KY});var p1=I((ZY)=>{Object.defineProperty(ZY,"__esModule",{value:!0});var S6=m1();class MY extends Error{constructor(b,w,$,W){super(W||`can't resolve reference ${$} from id ${w}`);this.missingRef=(0,S6.resolveUrl)(b,w,$),this.missingSchema=(0,S6.normalizeId)((0,S6.getFullPath)(b,this.missingRef))}}ZY.default=MY});var z$=I((VY)=>{Object.defineProperty(VY,"__esModule",{value:!0});VY.resolveSchema=VY.getCompilingSchema=VY.resolveRef=VY.compileSchema=VY.SchemaEnv=void 0;var fb=u(),c3=J$(),xw=Qw(),cb=m1(),IY=l(),g3=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={}}}VY.SchemaEnv=o1;function k6(b){let w=jY.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:c3.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:xw.default.data,parentData:xw.default.parentData,parentDataProperty:xw.default.parentDataProperty,dataNames:[xw.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,g3.validateFunctionCode)(J),X.optimize(this.opts.code.optimize);let z=X.toString();if(D=`${X.scopeRefs(xw.default.scope)}return ${z}`,this.opts.code.process)D=this.opts.code.process(D,b);let q=Function(`${xw.default.self}`,`${xw.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)}}VY.compileSchema=k6;function m3(b,w,$){var W;$=(0,cb.resolveUrl)(this.opts.uriResolver,w,$);let Q=b.refs[$];if(Q)return Q;let G=i3.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[$]=n3.call(this,G)}VY.resolveRef=m3;function n3(b){if((0,cb.inlineRef)(b.schema,this.opts.inlineRefs))return b.schema;return b.validate?b:k6.call(this,b)}function jY(b){for(let w of this._compilations)if(l3(w,b))return w}VY.getCompilingSchema=jY;function l3(b,w){return b.schema===w.schema&&b.root===w.root&&b.baseId===w.baseId}function i3(b,w){let $;while(typeof($=this.refs[w])=="string")w=$;return $||this.schemas[w]||D$.call(this,b,w)}function D$(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 R6.call(this,$,b);let G=(0,cb.normalizeId)(W),X=this.refs[G]||this.schemas[G];if(typeof X=="string"){let Y=D$.call(this,b,X);if(typeof(Y===null||Y===void 0?void 0:Y.schema)!=="object")return;return R6.call(this,$,Y)}if(typeof(X===null||X===void 0?void 0:X.schema)!=="object")return;if(!X.validate)k6.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 R6.call(this,$,X)}VY.resolveSchema=D$;var p3=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function R6(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,IY.unescapeFragment)(Y)];if(H===void 0)return;$=H;let J=typeof $==="object"&&$[this.opts.schemaId];if(!p3.has(Y)&&J)w=(0,cb.resolveUrl)(this.opts.uriResolver,w,J)}let G;if(typeof $!="boolean"&&$.$ref&&!(0,IY.schemaHasRulesButRef)($,this.RULES)){let Y=(0,cb.resolveUrl)(this.opts.uriResolver,w,$.$ref);G=D$.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 EY=I((dE,e3)=>{e3.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 C6=I((tE,RY)=>{var s3=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),_Y=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 a3=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function TY(b){return b.length=0,!0}function bU(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 wU(b){let w=0,$={error:!1,address:"",zone:""},W=[],Q=[],G=!1,X=!1,Y=bU;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=TY}else{Q.push(J);continue}}if(Q.length)if(Y===TY)$.zone=Q.join("");else if(X)W.push(Q.join(""));else W.push(v6(Q));return $.address=W.join(""),$}function SY(b){if($U(b,":")<2)return{host:b,isIPV6:!1};let w=wU(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 $U(b,w){let $=0;for(let W=0;W<b.length;W++)if(b[W]===w)$++;return $}function WU(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 QU(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 GU(b){let w=[];if(b.userinfo!==void 0)w.push(b.userinfo),w.push("@");if(b.host!==void 0){let $=unescape(b.host);if(!_Y($)){let W=SY($);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}RY.exports={nonSimpleDomain:a3,recomposeAuthority:GU,normalizeComponentEncoding:QU,removeDotSegments:WU,isIPv4:_Y,isUUID:s3,normalizeIPv6:SY,stringArrayToHexStripped:v6}});var uY=I((rE,xY)=>{var{isUUID:XU}=C6(),YU=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,HU=["http","https","ws","wss","urn","urn:uuid"];function JU(b){return HU.indexOf(b)!==-1}function x6(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 kY(b){if(!b.host)b.error=b.error||"HTTP URIs must have a host.";return b}function vY(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 DU(b){return b.secure=x6(b),b.resourceName=(b.path||"/")+(b.query?"?"+b.query:""),b.path=void 0,b.query=void 0,b}function zU(b){if(b.port===(x6(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 AU(b,w){if(!b.path)return b.error="URN can not be parsed",b;let $=b.path.match(YU);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 OU(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 X=b,Y=b.nss;return X.path=`${W||w.nid}:${Y}`,w.skipEscape=!0,X}function qU(b,w){let $=b;if($.uuid=$.nss,$.nss=void 0,!w.tolerant&&(!$.uuid||!XU($.uuid)))$.error=$.error||"UUID is not valid.";return $}function LU(b){let w=b;return w.nss=(b.uuid||"").toLowerCase(),w}var CY={scheme:"http",domainHost:!0,parse:kY,serialize:vY},UU={scheme:"https",domainHost:CY.domainHost,parse:kY,serialize:vY},A$={scheme:"ws",domainHost:!0,parse:DU,serialize:zU},BU={scheme:"wss",domainHost:A$.domainHost,parse:A$.parse,serialize:A$.serialize},FU={scheme:"urn",parse:AU,serialize:OU,skipNormalize:!0},KU={scheme:"urn:uuid",parse:qU,serialize:LU,skipNormalize:!0},O$={http:CY,https:UU,ws:A$,wss:BU,urn:FU,"urn:uuid":KU};Object.setPrototypeOf(O$,null);function u6(b){return b&&(O$[b]||O$[b.toLowerCase()])||void 0}xY.exports={wsIsSecure:x6,SCHEMES:O$,isValidSchemeName:JU,getSchemeHandler:u6}});var fY=I((eE,L$)=>{var{normalizeIPv6:PU,removeDotSegments:d1,recomposeAuthority:MU,normalizeComponentEncoding:q$,isIPv4:ZU,nonSimpleDomain:IU}=C6(),{SCHEMES:jU,getSchemeHandler:yY}=uY();function VU(b,w){if(typeof b==="string")b=db(Xw(b,w),w);else if(typeof b==="object")b=Xw(db(b,w),w);return b}function NU(b,w,$){let W=$?Object.assign({scheme:"null"},$):{scheme:"null"},Q=hY(Xw(b,W),Xw(w,W),W,!0);return W.skipEscape=!0,db(Q,W)}function hY(b,w,$,W){let Q={};if(!W)b=Xw(db(b,$),$),w=Xw(db(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 EU(b,w,$){if(typeof b==="string")b=unescape(b),b=db(q$(Xw(b,$),!0),{...$,skipEscape:!0});else if(typeof b==="object")b=db(q$(b,!0),{...$,skipEscape:!0});if(typeof w==="string")w=unescape(w),w=db(q$(Xw(w,$),!0),{...$,skipEscape:!0});else if(typeof w==="object")w=db(q$(w,!0),{...$,skipEscape:!0});return b.toLowerCase()===w.toLowerCase()}function db(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=yY(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=MU($);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 TU=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\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(TU);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(ZU(W.host)===!1){let H=PU(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=yY($.scheme||W.scheme);if(!$.unicodeSupport&&(!X||!X.unicodeSupport)){if(W.host&&($.domainHost||X&&X.domainHost)&&Q===!1&&IU(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 y6={SCHEMES:jU,normalize:VU,resolve:NU,resolveComponent:hY,equal:EU,serialize:db,parse:Xw};L$.exports=y6;L$.exports.default=y6;L$.exports.fastUri=y6});var mY=I((gY)=>{Object.defineProperty(gY,"__esModule",{value:!0});var cY=fY();cY.code='require("ajv/dist/runtime/uri").default';gY.default=cY});var rY=I((Yw)=>{Object.defineProperty(Yw,"__esModule",{value:!0});Yw.CodeGen=Yw.Name=Yw.nil=Yw.stringify=Yw.str=Yw._=Yw.KeywordCxt=void 0;var SU=i1();Object.defineProperty(Yw,"KeywordCxt",{enumerable:!0,get:function(){return SU.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 RU=J$(),oY=p1(),kU=U6(),t1=z$(),vU=u(),r1=m1(),U$=g1(),f6=l(),nY=EY(),CU=mY(),dY=(b,w)=>new RegExp(b,w);dY.code="new RegExp";var xU=["removeAdditional","useDefaults","coerceTypes"],uU=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),yU={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."},hU={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},lY=200;function fU(b){var w,$,W,Q,G,X,Y,H,J,D,z,O,q,B,K,Z,M,k,S,h,R,ib,sb,p$,o$;let D1=b.strict,d$=(w=b.code)===null||w===void 0?void 0:w.optimize,kW=d$===!0||d$===void 0?1:d$||0,vW=(W=($=b.code)===null||$===void 0?void 0:$.regExp)!==null&&W!==void 0?W:dY,yz=(Q=b.uriResolver)!==null&&Q!==void 0?Q:CU.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:kW,regExp:vW}:{optimize:kW,regExp:vW},loopRequired:(K=b.loopRequired)!==null&&K!==void 0?K:lY,loopEnum:(Z=b.loopEnum)!==null&&Z!==void 0?Z:lY,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:(ib=b.validateSchema)!==null&&ib!==void 0?ib:!0,validateFormats:(sb=b.validateFormats)!==null&&sb!==void 0?sb:!0,unicodeRegExp:(p$=b.unicodeRegExp)!==null&&p$!==void 0?p$:!0,int32range:(o$=b.int32range)!==null&&o$!==void 0?o$:!0,uriResolver:yz}}class B${constructor(b={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,b=this.opts={...b,...fU(b)};let{es5:w,lines:$}=this.opts.code;this.scope=new vU.ValueScope({scope:{},prefixes:uU,es5:w,lines:$}),this.logger=iU(b.logger);let W=b.validateFormats;if(b.validateFormats=!1,this.RULES=(0,kU.getRules)(),iY.call(this,yU,b,"NOT SUPPORTED"),iY.call(this,hU,b,"DEPRECATED","warn"),this._metaOpts=nU.call(this),b.formats)gU.call(this);if(this._addVocabularies(),this._addDefaultMetaSchema(),b.keywords)mU.call(this,b.keywords);if(typeof b.meta=="object")this.addMetaSchema(b.meta);cU.call(this),b.validateFormats=W}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:b,meta:w,schemaId:$}=this.opts,W=nY;if($==="id")W={...nY},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 oY.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=pY.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=pY.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(oU.call(this,$,w),!w)return(0,f6.eachItem)($,(Q)=>h6.call(this,Q)),this;tU.call(this,w);let W={...w,type:(0,U$.getJSONTypes)(w.type),schemaType:(0,U$.getJSONTypes)(w.schemaType)};return(0,f6.eachItem)($,W.type.length===0?(Q)=>h6.call(this,Q,W):(Q)=>W.type.forEach((G)=>h6.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]=tY(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}}}B$.ValidationError=RU.default;B$.MissingRefError=oY.default;Yw.default=B$;function iY(b,w,$,W="error"){for(let Q in b){let G=Q;if(G in w)this.logger[W](`${$}: option ${Q}. ${b[G]}`)}}function pY(b){return b=(0,r1.normalizeId)(b),this.schemas[b]||this.refs[b]}function cU(){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 gU(){for(let b in this.opts.formats){let w=this.opts.formats[b];if(w)this.addFormat(b,w)}}function mU(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 nU(){let b={...this.opts};for(let w of xU)delete b[w];return b}var lU={log(){},warn(){},error(){}};function iU(b){if(b===!1)return lU;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 pU=/^[a-z_$][a-z0-9_$:-]*$/i;function oU(b,w){let{RULES:$}=this;if((0,f6.eachItem)(b,(W)=>{if($.keywords[W])throw Error(`Keyword ${W} is already defined`);if(!pU.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 h6(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,U$.getJSONTypes)(w.type),schemaType:(0,U$.getJSONTypes)(w.schemaType)}};if(w.before)dU.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 dU(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 tU(b){let{metaSchema:w}=b;if(w===void 0)return;if(b.$data&&this.opts.$data)w=tY(w);b.validateSchema=this.compile(w,!0)}var rU={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function tY(b){return{anyOf:[b,rU]}}});var sY=I((eY)=>{Object.defineProperty(eY,"__esModule",{value:!0});var aU={keyword:"id",code(){throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};eY.default=aU});var QH=I(($H)=>{Object.defineProperty($H,"__esModule",{value:!0});$H.callRef=$H.getValidate=void 0;var wB=p1(),aY=vb(),Ib=u(),aw=Qw(),bH=z$(),F$=l(),$B={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=bH.resolveRef.call(H,J,Q,$);if(D===void 0)throw new wB.default(W.opts.uriResolver,Q,$);if(D instanceof bH.SchemaEnv)return O(D);return q(D);function z(){if(G===J)return K$(b,X,G,G.$async);let B=w.scopeValue("root",{ref:J});return K$(b,Ib._`${B}.validate`,J,J.$async)}function O(B){let K=wH(b,B);K$(b,K,B,B.$async)}function q(B){let K=w.scopeValue("schema",Y.code.source===!0?{ref:B,code:(0,Ib.stringify)(B)}:{ref:B}),Z=w.name("valid"),M=b.subschema({schema:B,dataTypes:[],schemaPath:Ib.nil,topSchemaRef:K,errSchemaPath:$},Z);b.mergeEvaluated(M),b.ok(Z)}}};function wH(b,w){let{gen:$}=b;return w.validate?$.scopeValue("validate",{ref:w.validate}):Ib._`${$.scopeValue("wrapper",{ref:w})}.validate`}$H.getValidate=wH;function K$(b,w,$,W){let{gen:Q,it:G}=b,{allErrors:X,schemaEnv:Y,opts:H}=G,J=H.passContext?aw.default.this:Ib.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(Ib._`await ${(0,aY.callValidateCode)(b,w,J)}`),q(w),!X)Q.assign(B,!0)},(K)=>{if(Q.if(Ib._`!(${K} instanceof ${G.ValidationError})`,()=>Q.throw(K)),O(K),!X)Q.assign(B,!1)}),b.ok(B)}function z(){b.result((0,aY.callValidateCode)(b,w,J),()=>q(w),()=>O(w))}function O(B){let K=Ib._`${B}.errors`;Q.assign(aw.default.vErrors,Ib._`${aw.default.vErrors} === null ? ${K} : ${aw.default.vErrors}.concat(${K})`),Q.assign(aw.default.errors,Ib._`${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=F$.mergeEvaluated.props(Q,Z.props,G.props)}else{let M=Q.var("props",Ib._`${B}.evaluated.props`);G.props=F$.mergeEvaluated.props(Q,M,G.props,Ib.Name)}if(G.items!==!0)if(Z&&!Z.dynamicItems){if(Z.items!==void 0)G.items=F$.mergeEvaluated.items(Q,Z.items,G.items)}else{let M=Q.var("items",Ib._`${B}.evaluated.items`);G.items=F$.mergeEvaluated.items(Q,M,G.items,Ib.Name)}}}$H.callRef=K$;$H.default=$B});var XH=I((GH)=>{Object.defineProperty(GH,"__esModule",{value:!0});var GB=sY(),XB=QH(),YB=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",GB.default,XB.default];GH.default=YB});var HH=I((YH)=>{Object.defineProperty(YH,"__esModule",{value:!0});var P$=u(),Ew=P$.operators,M$={maximum:{okStr:"<=",ok:Ew.LTE,fail:Ew.GT},minimum:{okStr:">=",ok:Ew.GTE,fail:Ew.LT},exclusiveMaximum:{okStr:"<",ok:Ew.LT,fail:Ew.GTE},exclusiveMinimum:{okStr:">",ok:Ew.GT,fail:Ew.LTE}},JB={message:({keyword:b,schemaCode:w})=>P$.str`must be ${M$[b].okStr} ${w}`,params:({keyword:b,schemaCode:w})=>P$._`{comparison: ${M$[b].okStr}, limit: ${w}}`},DB={keyword:Object.keys(M$),type:"number",schemaType:"number",$data:!0,error:JB,code(b){let{keyword:w,data:$,schemaCode:W}=b;b.fail$data(P$._`${$} ${M$[w].fail} ${W} || isNaN(${$})`)}};YH.default=DB});var DH=I((JH)=>{Object.defineProperty(JH,"__esModule",{value:!0});var e1=u(),AB={message:({schemaCode:b})=>e1.str`must be multiple of ${b}`,params:({schemaCode:b})=>e1._`{multipleOf: ${b}}`},OB={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:AB,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}))`)}};JH.default=OB});var OH=I((AH)=>{Object.defineProperty(AH,"__esModule",{value:!0});function zH(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 $}AH.default=zH;zH.code='require("ajv/dist/runtime/ucs2length").default'});var LH=I((qH)=>{Object.defineProperty(qH,"__esModule",{value:!0});var uw=u(),UB=l(),BB=OH(),FB={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}}`},KB={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:FB,code(b){let{keyword:w,data:$,schemaCode:W,it:Q}=b,G=w==="maxLength"?uw.operators.GT:uw.operators.LT,X=Q.opts.unicode===!1?uw._`${$}.length`:uw._`${(0,UB.useFunc)(b.gen,BB.default)}(${$})`;b.fail$data(uw._`${X} ${G} ${W}`)}};qH.default=KB});var BH=I((UH)=>{Object.defineProperty(UH,"__esModule",{value:!0});var MB=vb(),Z$=u(),ZB={message:({schemaCode:b})=>Z$.str`must match pattern "${b}"`,params:({schemaCode:b})=>Z$._`{pattern: ${b}}`},IB={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:ZB,code(b){let{data:w,$data:$,schema:W,schemaCode:Q,it:G}=b,X=G.opts.unicodeRegExp?"u":"",Y=$?Z$._`(new RegExp(${Q}, ${X}))`:(0,MB.usePattern)(b,W);b.fail$data(Z$._`!${Y}.test(${w})`)}};UH.default=IB});var KH=I((FH)=>{Object.defineProperty(FH,"__esModule",{value:!0});var s1=u(),VB={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}}`},NB={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:VB,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}`)}};FH.default=NB});var MH=I((PH)=>{Object.defineProperty(PH,"__esModule",{value:!0});var a1=vb(),b0=u(),TB=l(),_B={message:({params:{missingProperty:b}})=>b0.str`must have required property '${b}'`,params:({params:{missingProperty:b}})=>b0._`{missingProperty: ${b}}`},SB={keyword:"required",type:"object",schemaType:"array",$data:!0,error:_B,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,TB.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)}}};PH.default=SB});var IH=I((ZH)=>{Object.defineProperty(ZH,"__esModule",{value:!0});var w0=u(),kB={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}}`},vB={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:kB,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}`)}};ZH.default=vB});var I$=I((VH)=>{Object.defineProperty(VH,"__esModule",{value:!0});var jH=j6();jH.code='require("ajv/dist/runtime/equal").default';VH.default=jH});var EH=I((NH)=>{Object.defineProperty(NH,"__esModule",{value:!0});var c6=g1(),qb=u(),uB=l(),yB=I$(),hB={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}}`},fB={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:hB,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,c6.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,c6.checkDataTypes)(J,Z,Y.opts.strictNumbers,c6.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,uB.useFunc)(w,yB.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)})))}}};NH.default=fB});var _H=I((TH)=>{Object.defineProperty(TH,"__esModule",{value:!0});var g6=u(),gB=l(),mB=I$(),nB={message:"must be equal to constant",params:({schemaCode:b})=>g6._`{allowedValue: ${b}}`},lB={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(g6._`!${(0,gB.useFunc)(w,mB.default)}(${$}, ${Q})`);else b.fail(g6._`${G} !== ${$}`)}};TH.default=lB});var RH=I((SH)=>{Object.defineProperty(SH,"__esModule",{value:!0});var $0=u(),pB=l(),oB=I$(),dB={message:"must be equal to one of the allowed values",params:({schemaCode:b})=>$0._`{allowedValues: ${b}}`},tB={keyword:"enum",schemaType:"array",$data:!0,error:dB,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,pB.useFunc)(w,oB.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}`}}};SH.default=tB});var vH=I((kH)=>{Object.defineProperty(kH,"__esModule",{value:!0});var eB=HH(),sB=DH(),aB=LH(),bF=BH(),wF=KH(),$F=MH(),WF=IH(),QF=EH(),GF=_H(),XF=RH(),YF=[eB.default,sB.default,aB.default,bF.default,wF.default,$F.default,WF.default,QF.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},GF.default,XF.default];kH.default=YF});var n6=I((xH)=>{Object.defineProperty(xH,"__esModule",{value:!0});xH.validateAdditionalItems=void 0;var yw=u(),m6=l(),JF={message:({params:{len:b}})=>yw.str`must NOT have more than ${b} items`,params:({params:{len:b}})=>yw._`{limit: ${b}}`},DF={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:JF,code(b){let{parentSchema:w,it:$}=b,{items:W}=w;if(!Array.isArray(W)){(0,m6.checkStrictMode)($,'"additionalItems" is ignored when "items" is not an array of schemas');return}CH(b,W)}};function CH(b,w){let{gen:$,schema:W,data:Q,keyword:G,it:X}=b;X.items=!0;let Y=$.const("len",yw._`${Q}.length`);if(W===!1)b.setParams({len:w.length}),b.pass(yw._`${Y} <= ${w.length}`);else if(typeof W=="object"&&!(0,m6.alwaysValidSchema)(X,W)){let J=$.var("valid",yw._`${Y} <= ${w.length}`);$.if((0,yw.not)(J),()=>H(J)),b.ok(J)}function H(J){$.forRange("i",w.length,Y,(D)=>{if(b.subschema({keyword:G,dataProp:D,dataPropType:m6.Type.Num},J),!X.allErrors)$.if((0,yw.not)(J),()=>$.break())})}}xH.validateAdditionalItems=CH;xH.default=DF});var l6=I((fH)=>{Object.defineProperty(fH,"__esModule",{value:!0});fH.validateTuple=void 0;var yH=u(),j$=l(),AF=vb(),OF={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(b){let{schema:w,it:$}=b;if(Array.isArray(w))return hH(b,"additionalItems",w);if($.items=!0,(0,j$.alwaysValidSchema)($,w))return;b.ok((0,AF.validateArray)(b))}};function hH(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",yH._`${G}.length`);$.forEach((z,O)=>{if((0,j$.alwaysValidSchema)(Y,z))return;W.if(yH._`${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)}}}fH.validateTuple=hH;fH.default=OF});var mH=I((gH)=>{Object.defineProperty(gH,"__esModule",{value:!0});var LF=l6(),UF={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:(b)=>(0,LF.validateTuple)(b,"items")};gH.default=UF});var iH=I((lH)=>{Object.defineProperty(lH,"__esModule",{value:!0});var nH=u(),FF=l(),KF=vb(),PF=n6(),MF={message:({params:{len:b}})=>nH.str`must NOT have more than ${b} items`,params:({params:{len:b}})=>nH._`{limit: ${b}}`},ZF={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:MF,code(b){let{schema:w,parentSchema:$,it:W}=b,{prefixItems:Q}=$;if(W.items=!0,(0,FF.alwaysValidSchema)(W,w))return;if(Q)(0,PF.validateAdditionalItems)(b,Q);else b.ok((0,KF.validateArray)(b))}};lH.default=ZF});var oH=I((pH)=>{Object.defineProperty(pH,"__esModule",{value:!0});var Cb=u(),V$=l(),jF={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}}`},VF={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:jF,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,V$.checkStrictMode)(G,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(Y!==void 0&&X>Y){(0,V$.checkStrictMode)(G,'"minContains" > "maxContains" is always invalid'),b.fail();return}if((0,V$.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:V$.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))}}};pH.default=VF});var aH=I((rH)=>{Object.defineProperty(rH,"__esModule",{value:!0});rH.validateSchemaDeps=rH.validatePropertyDeps=rH.error=void 0;var i6=u(),EF=l(),W0=vb();rH.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},
7
7
  missingProperty: ${W},
8
8
  depsCount: ${w},
9
- deps: ${$}}`};var TK={keyword:"dependencies",type:"object",schemaType:"object",error:rH.error,code(b){let[w,$]=_K(b);dH(b,w),tH(b,$)}};function _K({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 dH(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(i6._`${H} && (${(0,W0.checkMissingProp)(b,Y,G)})`),(0,W0.reportMissingProp)(b,G),$.else()}}rH.validatePropertyDeps=dH;function tH(b,w=b.schema){let{gen:$,data:W,keyword:Q,it:G}=b,X=$.name("valid");for(let Y in w){if((0,EK.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)}}rH.validateSchemaDeps=tH;rH.default=TK});var $J=I((wJ)=>{Object.defineProperty(wJ,"__esModule",{value:!0});var bJ=u(),vK=l(),kK={message:"property name must be valid",params:({params:b})=>bJ._`{propertyName: ${b.propertyName}}`},CK={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:kK,code(b){let{gen:w,schema:$,data:W,it:Q}=b;if((0,vK.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,bJ.not)(G),()=>{if(b.error(!0),!Q.allErrors)w.break()})}),b.ok(G)}};wJ.default=CK});var p6=I((WJ)=>{Object.defineProperty(WJ,"__esModule",{value:!0});var N$=vb(),cb=u(),uK=Qw(),E$=l(),yK={message:"must NOT have additional properties",params:({params:b})=>cb._`{additionalProperty: ${b.additionalProperty}}`},hK={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:yK,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,E$.alwaysValidSchema)(X,$))return;let J=(0,N$.allSchemaProperties)(W.properties),D=(0,N$.allSchemaProperties)(W.patternProperties);z(),b.ok(cb._`${G} === ${uK.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 v=(0,E$.schemaRefOrVal)(X,W.properties,"properties");M=(0,N$.isOwnProperty)(w,v,Z)}else if(J.length)M=(0,cb.or)(...J.map((v)=>cb._`${Z} === ${v}`));else M=cb.nil;if(D.length)M=(0,cb.or)(M,...D.map((v)=>cb._`${(0,N$.usePattern)(b,v)}.test(${Z})`));return(0,cb.not)(M)}function q(Z){w.code(cb._`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,E$.alwaysValidSchema)(X,$)){let M=w.name("valid");if(H.removeAdditional==="failing")F(Z,M,!1),w.if((0,cb.not)(M),()=>{b.reset(),q(Z)});else if(F(Z,M),!Y)w.if((0,cb.not)(M),()=>w.break())}}function F(Z,M,v){let S={keyword:"additionalProperties",dataProp:Z,dataPropType:E$.Type.Str};if(v===!1)Object.assign(S,{compositeRule:!0,createErrors:!1,allErrors:!1});b.subschema(S,M)}}};WJ.default=hK});var YJ=I((XJ)=>{Object.defineProperty(XJ,"__esModule",{value:!0});var gK=i1(),QJ=vb(),o6=l(),GJ=p6(),cK={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)GJ.default.code(new gK.KeywordCxt(G,GJ.default,"additionalProperties"));let X=(0,QJ.allSchemaProperties)($);for(let z of X)G.definedProperties.add(z);if(G.opts.unevaluated&&X.length&&G.props!==!0)G.props=o6.mergeEvaluated.props(w,(0,o6.toHash)(X),G.props);let Y=X.filter((z)=>!(0,o6.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,QJ.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)}}};XJ.default=cK});var AJ=I((zJ)=>{Object.defineProperty(zJ,"__esModule",{value:!0});var HJ=vb(),T$=u(),JJ=l(),DJ=l(),nK={keyword:"patternProperties",type:"object",schemaType:"object",code(b){let{gen:w,schema:$,data:W,parentSchema:Q,it:G}=b,{opts:X}=G,Y=(0,HJ.allSchemaProperties)($),H=Y.filter((F)=>(0,JJ.alwaysValidSchema)(G,$[F]));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,DJ.evaluatedPropsToName)(w,G.props);let{props:z}=G;O();function O(){for(let F of Y){if(J)q(F);if(G.allErrors)B(F);else w.var(D,!0),B(F),w.if(D)}}function q(F){for(let Z in J)if(new RegExp(F).test(Z))(0,JJ.checkStrictMode)(G,`property ${Z} matches pattern ${F} (use allowMatchingProperties)`)}function B(F){w.forIn("key",W,(Z)=>{w.if(T$._`${(0,HJ.usePattern)(b,F)}.test(${Z})`,()=>{let M=H.includes(F);if(!M)b.subschema({keyword:"patternProperties",schemaProp:F,dataProp:Z,dataPropType:DJ.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())})})}}};zJ.default=nK});var qJ=I((OJ)=>{Object.defineProperty(OJ,"__esModule",{value:!0});var iK=l(),pK={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(b){let{gen:w,schema:$,it:W}=b;if((0,iK.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"}};OJ.default=pK});var UJ=I((LJ)=>{Object.defineProperty(LJ,"__esModule",{value:!0});var dK=vb(),tK={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:dK.validateUnion,error:{message:"must match a schema in anyOf"}};LJ.default=tK});var KJ=I((BJ)=>{Object.defineProperty(BJ,"__esModule",{value:!0});var _$=u(),eK=l(),sK={message:"must match exactly one schema in oneOf",params:({params:b})=>_$._`{passingSchemas: ${b.passing}}`},aK={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:sK,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,eK.alwaysValidSchema)(Q,D))w.var(H,!0);else O=b.subschema({keyword:"oneOf",schemaProp:z,compositeRule:!0},H);if(z>0)w.if(_$._`${H} && ${X}`).assign(X,!1).assign(Y,_$._`[${Y}, ${z}]`).else();w.if(H,()=>{if(w.assign(X,!0),w.assign(Y,z),O)b.mergeEvaluated(O,_$.Name)})})}}};BJ.default=aK});var PJ=I((FJ)=>{Object.defineProperty(FJ,"__esModule",{value:!0});var wF=l(),$F={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,wF.alwaysValidSchema)(W,G))return;let Y=b.subschema({keyword:"allOf",schemaProp:X},Q);b.ok(Q),b.mergeEvaluated(Y)})}};FJ.default=$F});var jJ=I((IJ)=>{Object.defineProperty(IJ,"__esModule",{value:!0});var S$=u(),ZJ=l(),QF={message:({params:b})=>S$.str`must match "${b.ifClause}" schema`,params:({params:b})=>S$._`{failingKeyword: ${b.ifClause}}`},GF={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:QF,code(b){let{gen:w,parentSchema:$,it:W}=b;if($.then===void 0&&$.else===void 0)(0,ZJ.checkStrictMode)(W,'"if" without "then" and "else" is ignored');let Q=MJ(W,"then"),G=MJ(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,S$.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,S$._`${D}`);else b.setParams({ifClause:D})}}}};function MJ(b,w){let $=b.schema[w];return $!==void 0&&!(0,ZJ.alwaysValidSchema)(b,$)}IJ.default=GF});var NJ=I((VJ)=>{Object.defineProperty(VJ,"__esModule",{value:!0});var YF=l(),HF={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:b,parentSchema:w,it:$}){if(w.if===void 0)(0,YF.checkStrictMode)($,`"${b}" without "if" is ignored`)}};VJ.default=HF});var TJ=I((EJ)=>{Object.defineProperty(EJ,"__esModule",{value:!0});var DF=n6(),zF=mH(),AF=l6(),OF=iH(),qF=oH(),LF=aH(),UF=$J(),BF=p6(),KF=YJ(),FF=AJ(),PF=qJ(),MF=UJ(),ZF=KJ(),IF=PJ(),jF=jJ(),VF=NJ();function NF(b=!1){let w=[PF.default,MF.default,ZF.default,IF.default,jF.default,VF.default,UF.default,BF.default,LF.default,KF.default,FF.default];if(b)w.push(zF.default,OF.default);else w.push(DF.default,AF.default);return w.push(qF.default),w}EJ.default=NF});var SJ=I((_J)=>{Object.defineProperty(_J,"__esModule",{value:!0});var Gb=u(),TF={message:({schemaCode:b})=>Gb.str`must match format "${b}"`,params:({schemaCode:b})=>Gb._`{format: ${b}}`},_F={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:TF,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}),F=$.const("fDef",Gb._`${B}[${X}]`),Z=$.let("fType"),M=$.let("format");$.if(Gb._`typeof ${F} == "object" && !(${F} instanceof RegExp)`,()=>$.assign(Z,Gb._`${F}.type || "string"`).assign(M,Gb._`${F}.validate`),()=>$.assign(Z,Gb._`"string"`).assign(M,F)),b.fail$data((0,Gb.or)(v(),S()));function v(){if(H.strictSchema===!1)return Gb.nil;return Gb._`${X} && !${M}`}function S(){let h=D.$async?Gb._`(${F}.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){v();return}if(B===!0)return;let[F,Z,M]=S(B);if(F===w)b.pass(h());function v(){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 ib=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:ib});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})`}}}};_J.default=_F});var vJ=I((RJ)=>{Object.defineProperty(RJ,"__esModule",{value:!0});var RF=SJ(),vF=[RF.default];RJ.default=vF});var xJ=I((kJ)=>{Object.defineProperty(kJ,"__esModule",{value:!0});kJ.contentVocabulary=kJ.metadataVocabulary=void 0;kJ.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];kJ.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var hJ=I((yJ)=>{Object.defineProperty(yJ,"__esModule",{value:!0});var xF=XH(),uF=kH(),yF=TJ(),hF=vJ(),uJ=xJ(),fF=[xF.default,uF.default,(0,yF.default)(),hF.default,uJ.metadataVocabulary,uJ.contentVocabulary];yJ.default=fF});var mJ=I((gJ)=>{Object.defineProperty(gJ,"__esModule",{value:!0});gJ.DiscrError=void 0;var fJ;(function(b){b.Tag="tag",b.Mapping="mapping"})(fJ||(gJ.DiscrError=fJ={}))});var iJ=I((lJ)=>{Object.defineProperty(lJ,"__esModule",{value:!0});var b1=u(),d6=mJ(),nJ=z$(),cF=p1(),mF=l(),nF={message:({params:{discrError:b,tagName:w}})=>b===d6.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}}`},lF={keyword:"discriminator",type:"object",schemaType:"object",error:nF,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:d6.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:d6.DiscrError.Mapping,tag:J,tagName:Y}),w.endIf()}function z(q){let B=w.name("valid"),F=b.subschema({keyword:"oneOf",schemaProp:q},B);return b.mergeEvaluated(F,b1.Name),B}function O(){var q;let B={},F=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,mF.schemaHasRulesButRef)(R,G.self.RULES)){let sb=R.$ref;if(R=nJ.resolveRef.call(G.self,G.schemaEnv.root,G.baseId,sb),R instanceof nJ.SchemaEnv)R=R.schema;if(R===void 0)throw new cF.default(G.opts.uriResolver,G.baseId,sb)}let ib=(q=R===null||R===void 0?void 0:R.properties)===null||q===void 0?void 0:q[Y];if(typeof ib!="object")throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${Y}"`);Z=Z&&(F||M(R)),v(ib,h)}if(!Z)throw Error(`discriminator: "${Y}" must be required`);return B;function M({required:h}){return Array.isArray(h)&&h.includes(Y)}function v(h,R){if(h.const)S(h.const,R);else if(h.enum)for(let ib of h.enum)S(ib,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}}}};lJ.default=lF});var pJ=I((iT,pF)=>{pF.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 r6=I((Ib,t6)=>{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 oF=rY(),dF=hJ(),tF=iJ(),oJ=pJ(),rF=["/properties"],R$="http://json-schema.org/draft-07/schema";class Q0 extends oF.default{_addVocabularies(){if(super._addVocabularies(),dF.default.forEach((b)=>this.addVocabulary(b)),this.opts.discriminator)this.addKeyword(tF.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let b=this.opts.$data?this.$dataMetaSchema(oJ,rF):oJ;this.addMetaSchema(b,R$,!1),this.refs["http://json-schema.org/schema"]=R$}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(R$)?R$:void 0)}}Ib.Ajv=Q0;t6.exports=Ib=Q0;t6.exports.Ajv=Q0;Object.defineProperty(Ib,"__esModule",{value:!0});Ib.default=Q0;var eF=i1();Object.defineProperty(Ib,"KeywordCxt",{enumerable:!0,get:function(){return eF.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 sF=J$();Object.defineProperty(Ib,"ValidationError",{enumerable:!0,get:function(){return sF.default}});var aF=p1();Object.defineProperty(Ib,"MissingRefError",{enumerable:!0,get:function(){return aF.default}})});var WD=I((wD)=>{Object.defineProperty(wD,"__esModule",{value:!0});wD.formatNames=wD.fastFormats=wD.fullFormats=void 0;function tb(b,w){return{validate:b,compare:w}}wD.fullFormats={date:tb(eJ,bW),time:tb(s6(!0),wW),"date-time":tb(dJ(!0),aJ),"iso-time":tb(s6(),sJ),"iso-date-time":tb(dJ(),bD),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:YP,"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:qP,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:HP,int32:{type:"number",validate:zP},int64:{type:"number",validate:AP},float:{type:"number",validate:rJ},double:{type:"number",validate:rJ},password:!0,binary:!0};wD.fastFormats={...wD.fullFormats,date:tb(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,bW),time:tb(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,wW),"date-time":tb(/^\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,aJ),"iso-time":tb(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,sJ),"iso-date-time":tb(/^\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,bD),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};wD.formatNames=Object.keys(wD.fullFormats);function $P(b){return b%4===0&&(b%100!==0||b%400===0)}var WP=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,QP=[0,31,28,31,30,31,30,31,31,30,31,30,31];function eJ(b){let w=WP.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&&$P($)?29:QP[W])}function bW(b,w){if(!(b&&w))return;if(b>w)return 1;if(b<w)return-1;return 0}var e6=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function s6(b){return function($){let W=e6.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 wW(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 sJ(b,w){if(!(b&&w))return;let $=e6.exec(b),W=e6.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 a6=/t|\s/i;function dJ(b){let w=s6(b);return function(W){let Q=W.split(a6);return Q.length===2&&eJ(Q[0])&&w(Q[1])}}function aJ(b,w){if(!(b&&w))return;let $=new Date(b).valueOf(),W=new Date(w).valueOf();if(!($&&W))return;return $-W}function bD(b,w){if(!(b&&w))return;let[$,W]=b.split(a6),[Q,G]=w.split(a6),X=bW($,Q);if(X===void 0)return;return X||wW(W,G)}var GP=/\/|:/,XP=/^(?:[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 YP(b){return GP.test(b)&&XP.test(b)}var tJ=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function HP(b){return tJ.lastIndex=0,tJ.test(b)}var JP=-2147483648,DP=2147483647;function zP(b){return Number.isInteger(b)&&b<=DP&&b>=JP}function AP(b){return Number.isInteger(b)}function rJ(){return!0}var OP=/[^\\]\\Z/;function qP(b){if(OP.test(b))return!1;try{return new RegExp(b),!0}catch(w){return!1}}});var GD=I((QD)=>{Object.defineProperty(QD,"__esModule",{value:!0});QD.formatLimitDefinition=void 0;var UP=r6(),mb=u(),Ew=mb.operators,v$={formatMaximum:{okStr:"<=",ok:Ew.LTE,fail:Ew.GT},formatMinimum:{okStr:">=",ok:Ew.GTE,fail:Ew.LT},formatExclusiveMaximum:{okStr:"<",ok:Ew.LT,fail:Ew.GTE},formatExclusiveMinimum:{okStr:">",ok:Ew.GT,fail:Ew.LTE}},BP={message:({keyword:b,schemaCode:w})=>mb.str`should be ${v$[b].okStr} ${w}`,params:({keyword:b,schemaCode:w})=>mb._`{comparison: ${v$[b].okStr}, limit: ${w}}`};QD.formatLimitDefinition={keyword:Object.keys(v$),type:"string",schemaType:"string",$data:!0,error:BP,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 UP.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}) ${v$[Q].fail} 0`}},dependencies:["format"]};var KP=(b)=>{return b.addKeyword(QD.formatLimitDefinition),b};QD.default=KP});var JD=I((G0,HD)=>{Object.defineProperty(G0,"__esModule",{value:!0});var $1=WD(),PP=GD(),QW=u(),XD=new QW.Name("fullFormats"),MP=new QW.Name("fastFormats"),GW=(b,w={keywords:!0})=>{if(Array.isArray(w))return YD(b,w,$1.fullFormats,XD),b;let[$,W]=w.mode==="fast"?[$1.fastFormats,MP]:[$1.fullFormats,XD],Q=w.formats||$1.formatNames;if(YD(b,Q,$,W),w.keywords)(0,PP.default)(b);return b};GW.get=(b,w="full")=>{let W=(w==="fast"?$1.fastFormats:$1.fullFormats)[b];if(!W)throw Error(`Unknown format "${b}"`);return W};function YD(b,w,$,W){var Q,G;(Q=(G=b.opts.code).formats)!==null&&Q!==void 0||(G.formats=QW._`require("ajv-formats/dist/formats").${W}`);for(let X of w)b.addFormat(X,$[X])}HD.exports=G0=GW;Object.defineProperty(G0,"__esModule",{value:!0});G0.default=GW});import{AsyncLocalStorage as rz}from"node:async_hooks";class pb 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 oz(b){if(b instanceof pb)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 dz(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 tz(b){let w=oz(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=dz($);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 Aw(b){let w=tz(b);return[`Sequenzy MCP error: ${w.title}`,`Description: ${w.description}`,`How to fix: ${w.howToFix}`,`Docs: ${w.docsUrl}`,`Details: ${w.details}`].join(`
10
- `)}var ez="https://api.sequenzy.com",z1=new rz,uW=!1;function yW(){uW=!0}function z0(){return uW}var hW=null;function Ow(){let b=z1.getStore();if(b)return b.selectedCompanyId??null;return hW}function A0(b){let w=z1.getStore();if(w){w.selectedCompanyId=b;return}hW=b}function r$(b,w){return z1.run(b,w)}function fW(){return z1.getStore()?.apiUrl??process.env.SEQUENZY_API_URL??ez}function gW(){return z1.getStore()?.apiKey??process.env.SEQUENZY_API_KEY}function cW(b,w){let $=gW();if(!$)throw new pb("SEQUENZY_API_KEY environment variable is required",401,void 0,"MCP_AUTH_REQUIRED");let W={"Content-Type":b,Authorization:`Bearer ${$}`},Q=w??Ow();if(Q)W["x-company-id"]=Q;return W}function mW(){if(gW())return;console.error(Aw(new pb("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 sz(b){if(b===void 0)return;if(typeof b==="string")return b.trim()||void 0;return JSON.stringify(b)}function nW(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=sz(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=cW("application/json",W),G;try{G=await fetch(`${fW()}${w}`,{method:b,headers:Q,body:$?JSON.stringify($):void 0})}catch(X){throw new pb(X instanceof Error?X.message:"Failed to reach Sequenzy API",0,void 0,"NETWORK_ERROR")}if(!G.ok){let X=await G.text(),Y=nW(X);throw new pb(Y.message,G.status,Y.details??X,Y.code,Y.context)}return G.json()}async function lW(b,w,$,W){let Q=new URL(fW()).origin,G=new URL(b,`${Q}/`);if(G.origin!==Q)throw new pb("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:cW($,W),body:w})}catch(Y){throw new pb(Y instanceof Error?Y.message:"Failed to upload image bytes",0,void 0,"NETWORK_ERROR")}if(!X.ok){let Y=await X.text(),H=nW(Y);throw new pb(H.message,X.status,H.details??Y,H.code,H.context)}}var vM=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 kM=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 O0={};function _b(b){if(b)Object.assign(O0,b);return O0}var n={};xW(n,{unwrapMessage:()=>O1,uint8ArrayToHex:()=>I7,uint8ArrayToBase64url:()=>M7,uint8ArrayToBase64:()=>eW,stringifyPrimitive:()=>B0,shallowClone:()=>pW,safeExtend:()=>L7,required:()=>K7,randomString:()=>H7,propertyKeyTypes:()=>w4,promiseAllObject:()=>Y7,primitiveTypes:()=>oW,prefixIssues:()=>ww,pick:()=>A7,partial:()=>B7,optionalKeys:()=>$4,omit:()=>O7,objectClone:()=>Q7,numKeys:()=>J7,nullish:()=>q1,normalizeParams:()=>_,mergeDefs:()=>Lw,merge:()=>U7,jsonStringifyReplacer:()=>hw,joinValues:()=>q0,issue:()=>gw,isPlainObject:()=>Uw,isObject:()=>Sw,hexToUint8Array:()=>Z7,getSizableOrigin:()=>tW,getParsedType:()=>D7,getLengthableOrigin:()=>U1,getEnumValues:()=>s$,getElementAtPath:()=>X7,floatSafeRemainder:()=>a$,finalizeIssue:()=>ub,extend:()=>q7,escapeRegex:()=>bw,esc:()=>L0,defineLazy:()=>o,createTransparentProxy:()=>z7,cloneDef:()=>G7,clone:()=>xb,cleanRegex:()=>L1,cleanEnum:()=>F7,captureStackTrace:()=>U0,cached:()=>fw,base64urlToUint8Array:()=>P7,base64ToUint8Array:()=>rW,assignProp:()=>qw,assertNotEqual:()=>b7,assertNever:()=>$7,assertIs:()=>w7,assertEqual:()=>az,assert:()=>W7,allowsEval:()=>b4,aborted:()=>Bw,NUMBER_FORMAT_RANGES:()=>W4,Class:()=>sW,BIGINT_FORMAT_RANGES:()=>dW});function az(b){return b}function b7(b){return b}function w7(b){}function $7(b){throw Error()}function W7(b){}function s$(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 q0(b,w="|"){return b.map(($)=>B0($)).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 a$(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 iW=Symbol("evaluating");function o(b,w,$){let W=void 0;Object.defineProperty(b,w,{get(){if(W===iW)return;if(W===void 0)W=iW,W=$();return W},set(Q){Object.defineProperty(b,w,{value:Q})},configurable:!0})}function Q7(b){return Object.create(Object.getPrototypeOf(b),Object.getOwnPropertyDescriptors(b))}function qw(b,w,$){Object.defineProperty(b,w,{value:$,writable:!0,enumerable:!0,configurable:!0})}function Lw(...b){let w={};for(let $ of b){let W=Object.getOwnPropertyDescriptors($);Object.assign(w,W)}return Object.defineProperties({},w)}function G7(b){return Lw(b._zod.def)}function X7(b,w){if(!w)return b;return w.reduce(($,W)=>$?.[W],b)}function Y7(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 H7(b=10){let $="";for(let W=0;W<b;W++)$+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return $}function L0(b){return JSON.stringify(b)}var U0="captureStackTrace"in Error?Error.captureStackTrace:(...b)=>{};function Sw(b){return typeof b==="object"&&b!==null&&!Array.isArray(b)}var b4=fw(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(b){return!1}});function Uw(b){if(Sw(b)===!1)return!1;let w=b.constructor;if(w===void 0)return!0;let $=w.prototype;if(Sw($)===!1)return!1;if(Object.prototype.hasOwnProperty.call($,"isPrototypeOf")===!1)return!1;return!0}function pW(b){if(Uw(b))return{...b};if(Array.isArray(b))return[...b];return b}function J7(b){let w=0;for(let $ in b)if(Object.prototype.hasOwnProperty.call(b,$))w++;return w}var D7=(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}`)}},w4=new Set(["string","number","symbol"]),oW=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 z7(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 B0(b){if(typeof b==="bigint")return b.toString()+"n";if(typeof b==="string")return`"${b}"`;return`${b}`}function $4(b){return Object.keys(b).filter((w)=>{return b[w]._zod.optin==="optional"&&b[w]._zod.optout==="optional"})}var W4={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]},dW={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function A7(b,w){let $=b._zod.def,W=Lw(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 qw(this,"shape",Q),Q},checks:[]});return xb(b,W)}function O7(b,w){let $=b._zod.def,W=Lw(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 qw(this,"shape",Q),Q},checks:[]});return xb(b,W)}function q7(b,w){if(!Uw(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=Lw(b._zod.def,{get shape(){let G={...b._zod.def.shape,...w};return qw(this,"shape",G),G},checks:[]});return xb(b,Q)}function L7(b,w){if(!Uw(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 qw(this,"shape",W),W},checks:b._zod.def.checks};return xb(b,$)}function U7(b,w){let $=Lw(b._zod.def,{get shape(){let W={...b._zod.def.shape,...w._zod.def.shape};return qw(this,"shape",W),W},get catchall(){return w._zod.def.catchall},checks:[]});return xb(b,$)}function B7(b,w,$){let W=Lw(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 qw(this,"shape",G),G},checks:[]});return xb(w,W)}function K7(b,w,$){let W=Lw(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 qw(this,"shape",G),G},checks:[]});return xb(w,W)}function Bw(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 tW(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 gw(...b){let[w,$,W]=b;if(typeof w==="string")return{message:w,code:"custom",input:$,inst:W};return{...w}}function F7(b){return Object.entries(b).filter(([w,$])=>{return Number.isNaN(Number.parseInt(w,10))}).map((w)=>w[1])}function rW(b){let w=atob(b),$=new Uint8Array(w.length);for(let W=0;W<w.length;W++)$[W]=w.charCodeAt(W);return $}function eW(b){let w="";for(let $=0;$<b.length;$++)w+=String.fromCharCode(b[$]);return btoa(w)}function P7(b){let w=b.replace(/-/g,"+").replace(/_/g,"/"),$="=".repeat((4-w.length%4)%4);return rW(w+$)}function M7(b){return eW(b).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Z7(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 I7(b){return Array.from(b).map((w)=>w.toString(16).padStart(2,"0")).join("")}class sW{constructor(...b){}}var aW=(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})},K0=U("$ZodError",aW),Q4=U("$ZodError",aW,{Parent:Error});function bQ(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 wQ(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,_b())));throw U0(Y,Q?.callee),Y}return X.value};var P0=(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,_b())));throw U0(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??K0)(G.issues.map((X)=>ub(X,Q,_b())))}:{success:!0,data:G.value}},K1=B1(Q4),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((X)=>ub(X,Q,_b())))}:{success:!0,data:G.value}},M0=F1(Q4),$Q=(b)=>(w,$,W)=>{let Q=W?Object.assign(W,{direction:"backward"}):{direction:"backward"};return F0(b)(w,$,Q)};var WQ=(b)=>(w,$,W)=>{return F0(b)(w,$,W)};var QQ=(b)=>async(w,$,W)=>{let Q=W?Object.assign(W,{direction:"backward"}):{direction:"backward"};return P0(b)(w,$,Q)};var GQ=(b)=>async(w,$,W)=>{return P0(b)(w,$,W)};var XQ=(b)=>(w,$,W)=>{let Q=W?Object.assign(W,{direction:"backward"}):{direction:"backward"};return B1(b)(w,$,Q)};var YQ=(b)=>(w,$,W)=>{return B1(b)(w,$,W)};var HQ=(b)=>async(w,$,W)=>{let Q=W?Object.assign(W,{direction:"backward"}):{direction:"backward"};return F1(b)(w,$,Q)};var JQ=(b)=>async(w,$,W)=>{return F1(b)(w,$,W)};var DQ=/^[cC][^\s-]{8,}$/,zQ=/^[0-9a-z]+$/,AQ=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,OQ=/^[0-9a-vA-V]{20}$/,qQ=/^[A-Za-z0-9]{27}$/,LQ=/^[a-zA-Z0-9_-]{21}$/,UQ=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var BQ=/^([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})$/,G4=(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 KQ=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function FQ(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}var 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])$/,MQ=/^(([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}|:))$/,ZQ=/^((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])$/,IQ=/^(([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])$/,jQ=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,X4=/^[A-Za-z0-9_-]*$/,VQ=/^(?=.{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 NQ=/^\+(?:[0-9]){6,14}[0-9]$/,EQ="(?:(?:\\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])))",TQ=new RegExp(`^${EQ}$`);function _Q(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 SQ(b){return new RegExp(`^${_Q(b)}$`)}function RQ(b){let w=_Q({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(`^${EQ}T(?:${W})$`)}var vQ=(b)=>{let w=b?`[\\s\\S]{${b?.minimum??0},${b?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${w}$`)};var kQ=/^-?\d+$/,CQ=/^-?\d+(?:\.\d+)?/,xQ=/^(?:true|false)$/i,uQ=/^null$/i;var yQ=/^[^A-Z]*$/,hQ=/^[^a-z]*$/;var Jb=U("$ZodCheck",(b,w)=>{var $;b._zod??(b._zod={}),b._zod.def=w,($=b._zod).onattach??($.onattach=[])}),fQ={number:"number",bigint:"bigint",object:"date"},Y4=U("$ZodCheckLessThan",(b,w)=>{Jb.init(b,w);let $=fQ[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})}}),H4=U("$ZodCheckGreaterThan",(b,w)=>{Jb.init(b,w);let $=fQ[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})}}),gQ=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):a$($.value,w.value)===0)return;$.issues.push({origin:typeof $.value,code:"not_multiple_of",divisor:w.value,input:$.value,inst:b,continue:!w.abort})}}),cQ=U("$ZodCheckNumberFormat",(b,w)=>{Jb.init(b,w),w.format=w.format||"float64";let $=w.format?.includes("int"),W=$?"int":"number",[Q,G]=W4[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=kQ}),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 mQ=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})}}),nQ=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})}}),lQ=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=()=>{})}),iQ=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})}}),pQ=U("$ZodCheckLowerCase",(b,w)=>{w.pattern??(w.pattern=yQ),P1.init(b,w)}),oQ=U("$ZodCheckUpperCase",(b,w)=>{w.pattern??(w.pattern=hQ),P1.init(b,w)}),dQ=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})}}),tQ=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})}}),rQ=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 eQ=U("$ZodCheckOverwrite",(b,w)=>{Jb.init(b,w),b._zod.check=($)=>{$.value=w.tx($.value)}});class J4{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(`
9
+ deps: ${$}}`};var TF={keyword:"dependencies",type:"object",schemaType:"object",error:rH.error,code(b){let[w,$]=_F(b);dH(b,w),tH(b,$)}};function _F({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 dH(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(i6._`${H} && (${(0,W0.checkMissingProp)(b,Y,G)})`),(0,W0.reportMissingProp)(b,G),$.else()}}rH.validatePropertyDeps=dH;function tH(b,w=b.schema){let{gen:$,data:W,keyword:Q,it:G}=b,X=$.name("valid");for(let Y in w){if((0,EF.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)}}rH.validateSchemaDeps=tH;rH.default=TF});var $J=I((wJ)=>{Object.defineProperty(wJ,"__esModule",{value:!0});var bJ=u(),kF=l(),vF={message:"property name must be valid",params:({params:b})=>bJ._`{propertyName: ${b.propertyName}}`},CF={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:vF,code(b){let{gen:w,schema:$,data:W,it:Q}=b;if((0,kF.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,bJ.not)(G),()=>{if(b.error(!0),!Q.allErrors)w.break()})}),b.ok(G)}};wJ.default=CF});var p6=I((WJ)=>{Object.defineProperty(WJ,"__esModule",{value:!0});var N$=vb(),gb=u(),uF=Qw(),E$=l(),yF={message:"must NOT have additional properties",params:({params:b})=>gb._`{additionalProperty: ${b.additionalProperty}}`},hF={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:yF,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,E$.alwaysValidSchema)(X,$))return;let J=(0,N$.allSchemaProperties)(W.properties),D=(0,N$.allSchemaProperties)(W.patternProperties);z(),b.ok(gb._`${G} === ${uF.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,E$.schemaRefOrVal)(X,W.properties,"properties");M=(0,N$.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,N$.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,E$.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:E$.Type.Str};if(k===!1)Object.assign(S,{compositeRule:!0,createErrors:!1,allErrors:!1});b.subschema(S,M)}}};WJ.default=hF});var YJ=I((XJ)=>{Object.defineProperty(XJ,"__esModule",{value:!0});var cF=i1(),QJ=vb(),o6=l(),GJ=p6(),gF={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)GJ.default.code(new cF.KeywordCxt(G,GJ.default,"additionalProperties"));let X=(0,QJ.allSchemaProperties)($);for(let z of X)G.definedProperties.add(z);if(G.opts.unevaluated&&X.length&&G.props!==!0)G.props=o6.mergeEvaluated.props(w,(0,o6.toHash)(X),G.props);let Y=X.filter((z)=>!(0,o6.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,QJ.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)}}};XJ.default=gF});var AJ=I((zJ)=>{Object.defineProperty(zJ,"__esModule",{value:!0});var HJ=vb(),T$=u(),JJ=l(),DJ=l(),nF={keyword:"patternProperties",type:"object",schemaType:"object",code(b){let{gen:w,schema:$,data:W,parentSchema:Q,it:G}=b,{opts:X}=G,Y=(0,HJ.allSchemaProperties)($),H=Y.filter((K)=>(0,JJ.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,DJ.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,JJ.checkStrictMode)(G,`property ${Z} matches pattern ${K} (use allowMatchingProperties)`)}function B(K){w.forIn("key",W,(Z)=>{w.if(T$._`${(0,HJ.usePattern)(b,K)}.test(${Z})`,()=>{let M=H.includes(K);if(!M)b.subschema({keyword:"patternProperties",schemaProp:K,dataProp:Z,dataPropType:DJ.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())})})}}};zJ.default=nF});var qJ=I((OJ)=>{Object.defineProperty(OJ,"__esModule",{value:!0});var iF=l(),pF={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(b){let{gen:w,schema:$,it:W}=b;if((0,iF.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"}};OJ.default=pF});var UJ=I((LJ)=>{Object.defineProperty(LJ,"__esModule",{value:!0});var dF=vb(),tF={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:dF.validateUnion,error:{message:"must match a schema in anyOf"}};LJ.default=tF});var FJ=I((BJ)=>{Object.defineProperty(BJ,"__esModule",{value:!0});var _$=u(),eF=l(),sF={message:"must match exactly one schema in oneOf",params:({params:b})=>_$._`{passingSchemas: ${b.passing}}`},aF={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:sF,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,eF.alwaysValidSchema)(Q,D))w.var(H,!0);else O=b.subschema({keyword:"oneOf",schemaProp:z,compositeRule:!0},H);if(z>0)w.if(_$._`${H} && ${X}`).assign(X,!1).assign(Y,_$._`[${Y}, ${z}]`).else();w.if(H,()=>{if(w.assign(X,!0),w.assign(Y,z),O)b.mergeEvaluated(O,_$.Name)})})}}};BJ.default=aF});var PJ=I((KJ)=>{Object.defineProperty(KJ,"__esModule",{value:!0});var wK=l(),$K={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,wK.alwaysValidSchema)(W,G))return;let Y=b.subschema({keyword:"allOf",schemaProp:X},Q);b.ok(Q),b.mergeEvaluated(Y)})}};KJ.default=$K});var jJ=I((IJ)=>{Object.defineProperty(IJ,"__esModule",{value:!0});var S$=u(),ZJ=l(),QK={message:({params:b})=>S$.str`must match "${b.ifClause}" schema`,params:({params:b})=>S$._`{failingKeyword: ${b.ifClause}}`},GK={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:QK,code(b){let{gen:w,parentSchema:$,it:W}=b;if($.then===void 0&&$.else===void 0)(0,ZJ.checkStrictMode)(W,'"if" without "then" and "else" is ignored');let Q=MJ(W,"then"),G=MJ(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,S$.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,S$._`${D}`);else b.setParams({ifClause:D})}}}};function MJ(b,w){let $=b.schema[w];return $!==void 0&&!(0,ZJ.alwaysValidSchema)(b,$)}IJ.default=GK});var NJ=I((VJ)=>{Object.defineProperty(VJ,"__esModule",{value:!0});var YK=l(),HK={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:b,parentSchema:w,it:$}){if(w.if===void 0)(0,YK.checkStrictMode)($,`"${b}" without "if" is ignored`)}};VJ.default=HK});var TJ=I((EJ)=>{Object.defineProperty(EJ,"__esModule",{value:!0});var DK=n6(),zK=mH(),AK=l6(),OK=iH(),qK=oH(),LK=aH(),UK=$J(),BK=p6(),FK=YJ(),KK=AJ(),PK=qJ(),MK=UJ(),ZK=FJ(),IK=PJ(),jK=jJ(),VK=NJ();function NK(b=!1){let w=[PK.default,MK.default,ZK.default,IK.default,jK.default,VK.default,UK.default,BK.default,LK.default,FK.default,KK.default];if(b)w.push(zK.default,OK.default);else w.push(DK.default,AK.default);return w.push(qK.default),w}EJ.default=NK});var SJ=I((_J)=>{Object.defineProperty(_J,"__esModule",{value:!0});var Gb=u(),TK={message:({schemaCode:b})=>Gb.str`must match format "${b}"`,params:({schemaCode:b})=>Gb._`{format: ${b}}`},_K={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:TK,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 ib=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:ib});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})`}}}};_J.default=_K});var kJ=I((RJ)=>{Object.defineProperty(RJ,"__esModule",{value:!0});var RK=SJ(),kK=[RK.default];RJ.default=kK});var xJ=I((vJ)=>{Object.defineProperty(vJ,"__esModule",{value:!0});vJ.contentVocabulary=vJ.metadataVocabulary=void 0;vJ.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];vJ.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var hJ=I((yJ)=>{Object.defineProperty(yJ,"__esModule",{value:!0});var xK=XH(),uK=vH(),yK=TJ(),hK=kJ(),uJ=xJ(),fK=[xK.default,uK.default,(0,yK.default)(),hK.default,uJ.metadataVocabulary,uJ.contentVocabulary];yJ.default=fK});var mJ=I((cJ)=>{Object.defineProperty(cJ,"__esModule",{value:!0});cJ.DiscrError=void 0;var fJ;(function(b){b.Tag="tag",b.Mapping="mapping"})(fJ||(cJ.DiscrError=fJ={}))});var iJ=I((lJ)=>{Object.defineProperty(lJ,"__esModule",{value:!0});var b1=u(),d6=mJ(),nJ=z$(),gK=p1(),mK=l(),nK={message:({params:{discrError:b,tagName:w}})=>b===d6.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}}`},lK={keyword:"discriminator",type:"object",schemaType:"object",error:nK,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:d6.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:d6.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,mK.schemaHasRulesButRef)(R,G.self.RULES)){let sb=R.$ref;if(R=nJ.resolveRef.call(G.self,G.schemaEnv.root,G.baseId,sb),R instanceof nJ.SchemaEnv)R=R.schema;if(R===void 0)throw new gK.default(G.opts.uriResolver,G.baseId,sb)}let ib=(q=R===null||R===void 0?void 0:R.properties)===null||q===void 0?void 0:q[Y];if(typeof ib!="object")throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${Y}"`);Z=Z&&(K||M(R)),k(ib,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 ib of h.enum)S(ib,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}}}};lJ.default=lK});var pJ=I((iT,pK)=>{pK.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 r6=I((jb,t6)=>{Object.defineProperty(jb,"__esModule",{value:!0});jb.MissingRefError=jb.ValidationError=jb.CodeGen=jb.Name=jb.nil=jb.stringify=jb.str=jb._=jb.KeywordCxt=jb.Ajv=void 0;var oK=rY(),dK=hJ(),tK=iJ(),oJ=pJ(),rK=["/properties"],R$="http://json-schema.org/draft-07/schema";class Q0 extends oK.default{_addVocabularies(){if(super._addVocabularies(),dK.default.forEach((b)=>this.addVocabulary(b)),this.opts.discriminator)this.addKeyword(tK.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let b=this.opts.$data?this.$dataMetaSchema(oJ,rK):oJ;this.addMetaSchema(b,R$,!1),this.refs["http://json-schema.org/schema"]=R$}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(R$)?R$:void 0)}}jb.Ajv=Q0;t6.exports=jb=Q0;t6.exports.Ajv=Q0;Object.defineProperty(jb,"__esModule",{value:!0});jb.default=Q0;var eK=i1();Object.defineProperty(jb,"KeywordCxt",{enumerable:!0,get:function(){return eK.KeywordCxt}});var w1=u();Object.defineProperty(jb,"_",{enumerable:!0,get:function(){return w1._}});Object.defineProperty(jb,"str",{enumerable:!0,get:function(){return w1.str}});Object.defineProperty(jb,"stringify",{enumerable:!0,get:function(){return w1.stringify}});Object.defineProperty(jb,"nil",{enumerable:!0,get:function(){return w1.nil}});Object.defineProperty(jb,"Name",{enumerable:!0,get:function(){return w1.Name}});Object.defineProperty(jb,"CodeGen",{enumerable:!0,get:function(){return w1.CodeGen}});var sK=J$();Object.defineProperty(jb,"ValidationError",{enumerable:!0,get:function(){return sK.default}});var aK=p1();Object.defineProperty(jb,"MissingRefError",{enumerable:!0,get:function(){return aK.default}})});var WD=I((wD)=>{Object.defineProperty(wD,"__esModule",{value:!0});wD.formatNames=wD.fastFormats=wD.fullFormats=void 0;function tb(b,w){return{validate:b,compare:w}}wD.fullFormats={date:tb(eJ,bW),time:tb(s6(!0),wW),"date-time":tb(dJ(!0),aJ),"iso-time":tb(s6(),sJ),"iso-date-time":tb(dJ(),bD),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:YP,"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:qP,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:HP,int32:{type:"number",validate:zP},int64:{type:"number",validate:AP},float:{type:"number",validate:rJ},double:{type:"number",validate:rJ},password:!0,binary:!0};wD.fastFormats={...wD.fullFormats,date:tb(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,bW),time:tb(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,wW),"date-time":tb(/^\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,aJ),"iso-time":tb(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,sJ),"iso-date-time":tb(/^\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,bD),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};wD.formatNames=Object.keys(wD.fullFormats);function $P(b){return b%4===0&&(b%100!==0||b%400===0)}var WP=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,QP=[0,31,28,31,30,31,30,31,31,30,31,30,31];function eJ(b){let w=WP.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&&$P($)?29:QP[W])}function bW(b,w){if(!(b&&w))return;if(b>w)return 1;if(b<w)return-1;return 0}var e6=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function s6(b){return function($){let W=e6.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 wW(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 sJ(b,w){if(!(b&&w))return;let $=e6.exec(b),W=e6.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 a6=/t|\s/i;function dJ(b){let w=s6(b);return function(W){let Q=W.split(a6);return Q.length===2&&eJ(Q[0])&&w(Q[1])}}function aJ(b,w){if(!(b&&w))return;let $=new Date(b).valueOf(),W=new Date(w).valueOf();if(!($&&W))return;return $-W}function bD(b,w){if(!(b&&w))return;let[$,W]=b.split(a6),[Q,G]=w.split(a6),X=bW($,Q);if(X===void 0)return;return X||wW(W,G)}var GP=/\/|:/,XP=/^(?:[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 YP(b){return GP.test(b)&&XP.test(b)}var tJ=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function HP(b){return tJ.lastIndex=0,tJ.test(b)}var JP=-2147483648,DP=2147483647;function zP(b){return Number.isInteger(b)&&b<=DP&&b>=JP}function AP(b){return Number.isInteger(b)}function rJ(){return!0}var OP=/[^\\]\\Z/;function qP(b){if(OP.test(b))return!1;try{return new RegExp(b),!0}catch(w){return!1}}});var GD=I((QD)=>{Object.defineProperty(QD,"__esModule",{value:!0});QD.formatLimitDefinition=void 0;var UP=r6(),mb=u(),Tw=mb.operators,k$={formatMaximum:{okStr:"<=",ok:Tw.LTE,fail:Tw.GT},formatMinimum:{okStr:">=",ok:Tw.GTE,fail:Tw.LT},formatExclusiveMaximum:{okStr:"<",ok:Tw.LT,fail:Tw.GTE},formatExclusiveMinimum:{okStr:">",ok:Tw.GT,fail:Tw.LTE}},BP={message:({keyword:b,schemaCode:w})=>mb.str`should be ${k$[b].okStr} ${w}`,params:({keyword:b,schemaCode:w})=>mb._`{comparison: ${k$[b].okStr}, limit: ${w}}`};QD.formatLimitDefinition={keyword:Object.keys(k$),type:"string",schemaType:"string",$data:!0,error:BP,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 UP.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}) ${k$[Q].fail} 0`}},dependencies:["format"]};var FP=(b)=>{return b.addKeyword(QD.formatLimitDefinition),b};QD.default=FP});var JD=I((G0,HD)=>{Object.defineProperty(G0,"__esModule",{value:!0});var $1=WD(),PP=GD(),QW=u(),XD=new QW.Name("fullFormats"),MP=new QW.Name("fastFormats"),GW=(b,w={keywords:!0})=>{if(Array.isArray(w))return YD(b,w,$1.fullFormats,XD),b;let[$,W]=w.mode==="fast"?[$1.fastFormats,MP]:[$1.fullFormats,XD],Q=w.formats||$1.formatNames;if(YD(b,Q,$,W),w.keywords)(0,PP.default)(b);return b};GW.get=(b,w="full")=>{let W=(w==="fast"?$1.fastFormats:$1.fullFormats)[b];if(!W)throw Error(`Unknown format "${b}"`);return W};function YD(b,w,$,W){var Q,G;(Q=(G=b.opts.code).formats)!==null&&Q!==void 0||(G.formats=QW._`require("ajv-formats/dist/formats").${W}`);for(let X of w)b.addFormat(X,$[X])}HD.exports=G0=GW;Object.defineProperty(G0,"__esModule",{value:!0});G0.default=GW});import{AsyncLocalStorage as rz}from"node:async_hooks";class pb 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 oz(b){if(b instanceof pb)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 dz(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 tz(b){let w=oz(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=dz($);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 Ow(b){let w=tz(b);return[`Sequenzy MCP error: ${w.title}`,`Description: ${w.description}`,`How to fix: ${w.howToFix}`,`Docs: ${w.docsUrl}`,`Details: ${w.details}`].join(`
10
+ `)}var ez="https://api.sequenzy.com",z1=new rz,uW=!1;function yW(){uW=!0}function z0(){return uW}var hW=null;function qw(){let b=z1.getStore();if(b)return b.selectedCompanyId??null;return hW}function A0(b){let w=z1.getStore();if(w){w.selectedCompanyId=b;return}hW=b}function r$(b,w){return z1.run(b,w)}function fW(){return z1.getStore()?.apiUrl??process.env.SEQUENZY_API_URL??ez}function cW(){return z1.getStore()?.apiKey??process.env.SEQUENZY_API_KEY}function gW(b,w){let $=cW();if(!$)throw new pb("SEQUENZY_API_KEY environment variable is required",401,void 0,"MCP_AUTH_REQUIRED");let W={"Content-Type":b,Authorization:`Bearer ${$}`},Q=w??qw();if(Q)W["x-company-id"]=Q;return W}function mW(){if(cW())return;console.error(Ow(new pb("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 sz(b){if(b===void 0)return;if(typeof b==="string")return b.trim()||void 0;return JSON.stringify(b)}function nW(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=sz(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=gW("application/json",W),G;try{G=await fetch(`${fW()}${w}`,{method:b,headers:Q,body:$?JSON.stringify($):void 0})}catch(X){throw new pb(X instanceof Error?X.message:"Failed to reach Sequenzy API",0,void 0,"NETWORK_ERROR")}if(!G.ok){let X=await G.text(),Y=nW(X);throw new pb(Y.message,G.status,Y.details??X,Y.code,Y.context)}return G.json()}async function lW(b,w,$,W){let Q=new URL(fW()).origin,G=new URL(b,`${Q}/`);if(G.origin!==Q)throw new pb("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:gW($,W),body:w})}catch(Y){throw new pb(Y instanceof Error?Y.message:"Failed to upload image bytes",0,void 0,"NETWORK_ERROR")}if(!X.ok){let Y=await X.text(),H=nW(Y);throw new pb(H.message,X.status,H.details??Y,H.code,H.context)}}var kM=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 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 O0={};function Sb(b){if(b)Object.assign(O0,b);return O0}var n={};xW(n,{unwrapMessage:()=>O1,uint8ArrayToHex:()=>I7,uint8ArrayToBase64url:()=>M7,uint8ArrayToBase64:()=>eW,stringifyPrimitive:()=>B0,shallowClone:()=>pW,safeExtend:()=>L7,required:()=>F7,randomString:()=>H7,propertyKeyTypes:()=>w4,promiseAllObject:()=>Y7,primitiveTypes:()=>oW,prefixIssues:()=>ww,pick:()=>A7,partial:()=>B7,optionalKeys:()=>$4,omit:()=>O7,objectClone:()=>Q7,numKeys:()=>J7,nullish:()=>q1,normalizeParams:()=>_,mergeDefs:()=>Uw,merge:()=>U7,jsonStringifyReplacer:()=>hw,joinValues:()=>q0,issue:()=>cw,isPlainObject:()=>Bw,isObject:()=>Sw,hexToUint8Array:()=>Z7,getSizableOrigin:()=>tW,getParsedType:()=>D7,getLengthableOrigin:()=>U1,getEnumValues:()=>s$,getElementAtPath:()=>X7,floatSafeRemainder:()=>a$,finalizeIssue:()=>ub,extend:()=>q7,escapeRegex:()=>bw,esc:()=>L0,defineLazy:()=>o,createTransparentProxy:()=>z7,cloneDef:()=>G7,clone:()=>xb,cleanRegex:()=>L1,cleanEnum:()=>K7,captureStackTrace:()=>U0,cached:()=>fw,base64urlToUint8Array:()=>P7,base64ToUint8Array:()=>rW,assignProp:()=>Lw,assertNotEqual:()=>b7,assertNever:()=>$7,assertIs:()=>w7,assertEqual:()=>az,assert:()=>W7,allowsEval:()=>b4,aborted:()=>Fw,NUMBER_FORMAT_RANGES:()=>W4,Class:()=>sW,BIGINT_FORMAT_RANGES:()=>dW});function az(b){return b}function b7(b){return b}function w7(b){}function $7(b){throw Error()}function W7(b){}function s$(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 q0(b,w="|"){return b.map(($)=>B0($)).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 a$(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 iW=Symbol("evaluating");function o(b,w,$){let W=void 0;Object.defineProperty(b,w,{get(){if(W===iW)return;if(W===void 0)W=iW,W=$();return W},set(Q){Object.defineProperty(b,w,{value:Q})},configurable:!0})}function Q7(b){return Object.create(Object.getPrototypeOf(b),Object.getOwnPropertyDescriptors(b))}function Lw(b,w,$){Object.defineProperty(b,w,{value:$,writable:!0,enumerable:!0,configurable:!0})}function Uw(...b){let w={};for(let $ of b){let W=Object.getOwnPropertyDescriptors($);Object.assign(w,W)}return Object.defineProperties({},w)}function G7(b){return Uw(b._zod.def)}function X7(b,w){if(!w)return b;return w.reduce(($,W)=>$?.[W],b)}function Y7(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 H7(b=10){let $="";for(let W=0;W<b;W++)$+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return $}function L0(b){return JSON.stringify(b)}var U0="captureStackTrace"in Error?Error.captureStackTrace:(...b)=>{};function Sw(b){return typeof b==="object"&&b!==null&&!Array.isArray(b)}var b4=fw(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(b){return!1}});function Bw(b){if(Sw(b)===!1)return!1;let w=b.constructor;if(w===void 0)return!0;let $=w.prototype;if(Sw($)===!1)return!1;if(Object.prototype.hasOwnProperty.call($,"isPrototypeOf")===!1)return!1;return!0}function pW(b){if(Bw(b))return{...b};if(Array.isArray(b))return[...b];return b}function J7(b){let w=0;for(let $ in b)if(Object.prototype.hasOwnProperty.call(b,$))w++;return w}var D7=(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}`)}},w4=new Set(["string","number","symbol"]),oW=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 z7(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 B0(b){if(typeof b==="bigint")return b.toString()+"n";if(typeof b==="string")return`"${b}"`;return`${b}`}function $4(b){return Object.keys(b).filter((w)=>{return b[w]._zod.optin==="optional"&&b[w]._zod.optout==="optional"})}var W4={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]},dW={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function A7(b,w){let $=b._zod.def,W=Uw(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 Lw(this,"shape",Q),Q},checks:[]});return xb(b,W)}function O7(b,w){let $=b._zod.def,W=Uw(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 Lw(this,"shape",Q),Q},checks:[]});return xb(b,W)}function q7(b,w){if(!Bw(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=Uw(b._zod.def,{get shape(){let G={...b._zod.def.shape,...w};return Lw(this,"shape",G),G},checks:[]});return xb(b,Q)}function L7(b,w){if(!Bw(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 Lw(this,"shape",W),W},checks:b._zod.def.checks};return xb(b,$)}function U7(b,w){let $=Uw(b._zod.def,{get shape(){let W={...b._zod.def.shape,...w._zod.def.shape};return Lw(this,"shape",W),W},get catchall(){return w._zod.def.catchall},checks:[]});return xb(b,$)}function B7(b,w,$){let W=Uw(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 Lw(this,"shape",G),G},checks:[]});return xb(w,W)}function F7(b,w,$){let W=Uw(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 Lw(this,"shape",G),G},checks:[]});return xb(w,W)}function Fw(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 tW(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 K7(b){return Object.entries(b).filter(([w,$])=>{return Number.isNaN(Number.parseInt(w,10))}).map((w)=>w[1])}function rW(b){let w=atob(b),$=new Uint8Array(w.length);for(let W=0;W<w.length;W++)$[W]=w.charCodeAt(W);return $}function eW(b){let w="";for(let $=0;$<b.length;$++)w+=String.fromCharCode(b[$]);return btoa(w)}function P7(b){let w=b.replace(/-/g,"+").replace(/_/g,"/"),$="=".repeat((4-w.length%4)%4);return rW(w+$)}function M7(b){return eW(b).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Z7(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 I7(b){return Array.from(b).map((w)=>w.toString(16).padStart(2,"0")).join("")}class sW{constructor(...b){}}var aW=(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})},F0=U("$ZodError",aW),Q4=U("$ZodError",aW,{Parent:Error});function bQ(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 wQ(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 K0=(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 U0(Y,Q?.callee),Y}return X.value};var P0=(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 U0(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??F0)(G.issues.map((X)=>ub(X,Q,Sb())))}:{success:!0,data:G.value}},F1=B1(Q4),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}},M0=K1(Q4),$Q=(b)=>(w,$,W)=>{let Q=W?Object.assign(W,{direction:"backward"}):{direction:"backward"};return K0(b)(w,$,Q)};var WQ=(b)=>(w,$,W)=>{return K0(b)(w,$,W)};var QQ=(b)=>async(w,$,W)=>{let Q=W?Object.assign(W,{direction:"backward"}):{direction:"backward"};return P0(b)(w,$,Q)};var GQ=(b)=>async(w,$,W)=>{return P0(b)(w,$,W)};var XQ=(b)=>(w,$,W)=>{let Q=W?Object.assign(W,{direction:"backward"}):{direction:"backward"};return B1(b)(w,$,Q)};var YQ=(b)=>(w,$,W)=>{return B1(b)(w,$,W)};var HQ=(b)=>async(w,$,W)=>{let Q=W?Object.assign(W,{direction:"backward"}):{direction:"backward"};return K1(b)(w,$,Q)};var JQ=(b)=>async(w,$,W)=>{return K1(b)(w,$,W)};var DQ=/^[cC][^\s-]{8,}$/,zQ=/^[0-9a-z]+$/,AQ=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,OQ=/^[0-9a-vA-V]{20}$/,qQ=/^[A-Za-z0-9]{27}$/,LQ=/^[a-zA-Z0-9_-]{21}$/,UQ=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var BQ=/^([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})$/,G4=(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 FQ=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function KQ(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}var 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])$/,MQ=/^(([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}|:))$/,ZQ=/^((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])$/,IQ=/^(([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])$/,jQ=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,X4=/^[A-Za-z0-9_-]*$/,VQ=/^(?=.{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 NQ=/^\+(?:[0-9]){6,14}[0-9]$/,EQ="(?:(?:\\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])))",TQ=new RegExp(`^${EQ}$`);function _Q(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 SQ(b){return new RegExp(`^${_Q(b)}$`)}function RQ(b){let w=_Q({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(`^${EQ}T(?:${W})$`)}var kQ=(b)=>{let w=b?`[\\s\\S]{${b?.minimum??0},${b?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${w}$`)};var vQ=/^-?\d+$/,CQ=/^-?\d+(?:\.\d+)?/,xQ=/^(?:true|false)$/i,uQ=/^null$/i;var yQ=/^[^A-Z]*$/,hQ=/^[^a-z]*$/;var Jb=U("$ZodCheck",(b,w)=>{var $;b._zod??(b._zod={}),b._zod.def=w,($=b._zod).onattach??($.onattach=[])}),fQ={number:"number",bigint:"bigint",object:"date"},Y4=U("$ZodCheckLessThan",(b,w)=>{Jb.init(b,w);let $=fQ[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})}}),H4=U("$ZodCheckGreaterThan",(b,w)=>{Jb.init(b,w);let $=fQ[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})}}),cQ=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):a$($.value,w.value)===0)return;$.issues.push({origin:typeof $.value,code:"not_multiple_of",divisor:w.value,input:$.value,inst:b,continue:!w.abort})}}),gQ=U("$ZodCheckNumberFormat",(b,w)=>{Jb.init(b,w),w.format=w.format||"float64";let $=w.format?.includes("int"),W=$?"int":"number",[Q,G]=W4[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=vQ}),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 mQ=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})}}),nQ=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})}}),lQ=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=()=>{})}),iQ=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})}}),pQ=U("$ZodCheckLowerCase",(b,w)=>{w.pattern??(w.pattern=yQ),P1.init(b,w)}),oQ=U("$ZodCheckUpperCase",(b,w)=>{w.pattern??(w.pattern=hQ),P1.init(b,w)}),dQ=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})}}),tQ=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})}}),rQ=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 eQ=U("$ZodCheckOverwrite",(b,w)=>{Jb.init(b,w),b._zod.check=($)=>{$.value=w.tx($.value)}});class J4{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(`
11
11
  `).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(`
12
- `))}}var aQ={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=aQ;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=Bw(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=Bw(X,O)});else{if(X.issues.length===O)continue;if(!J)J=Bw(X,O)}}if(D)return D.then(()=>{return X});return X},G=(X,Y,H)=>{if(Bw(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=K1(b,Q);return G.success?{value:G.data}:{issues:G.error?.issues}}catch(G){return M0(b,Q).then((X)=>X.success?{value:X.data}:{issues:X.error?.issues})}},vendor:"zod",version:1}}),V0=U("$ZodString",(b,w)=>{e.init(b,w),b._zod.pattern=[...b?._zod.bag?.patterns??[]].pop()??vQ(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),V0.init(b,w)}),H9=U("$ZodGUID",(b,w)=>{w.pattern??(w.pattern=BQ),s.init(b,w)}),J9=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=G4(W))}else w.pattern??(w.pattern=G4());s.init(b,w)}),D9=U("$ZodEmail",(b,w)=>{w.pattern??(w.pattern=KQ),s.init(b,w)}),z9=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:VQ.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})}}}),A9=U("$ZodEmoji",(b,w)=>{w.pattern??(w.pattern=FQ()),s.init(b,w)}),O9=U("$ZodNanoID",(b,w)=>{w.pattern??(w.pattern=LQ),s.init(b,w)}),q9=U("$ZodCUID",(b,w)=>{w.pattern??(w.pattern=DQ),s.init(b,w)}),L9=U("$ZodCUID2",(b,w)=>{w.pattern??(w.pattern=zQ),s.init(b,w)}),U9=U("$ZodULID",(b,w)=>{w.pattern??(w.pattern=AQ),s.init(b,w)}),B9=U("$ZodXID",(b,w)=>{w.pattern??(w.pattern=OQ),s.init(b,w)}),K9=U("$ZodKSUID",(b,w)=>{w.pattern??(w.pattern=qQ),s.init(b,w)}),F9=U("$ZodISODateTime",(b,w)=>{w.pattern??(w.pattern=RQ(w)),s.init(b,w)}),P9=U("$ZodISODate",(b,w)=>{w.pattern??(w.pattern=TQ),s.init(b,w)}),M9=U("$ZodISOTime",(b,w)=>{w.pattern??(w.pattern=SQ(w)),s.init(b,w)}),Z9=U("$ZodISODuration",(b,w)=>{w.pattern??(w.pattern=UQ),s.init(b,w)}),I9=U("$ZodIPv4",(b,w)=>{w.pattern??(w.pattern=PQ),s.init(b,w),b._zod.onattach.push(($)=>{let W=$._zod.bag;W.format="ipv4"})}),j9=U("$ZodIPv6",(b,w)=>{w.pattern??(w.pattern=MQ),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})}}}),V9=U("$ZodCIDRv4",(b,w)=>{w.pattern??(w.pattern=ZQ),s.init(b,w)}),N9=U("$ZodCIDRv6",(b,w)=>{w.pattern??(w.pattern=IQ),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 E9(b){if(b==="")return!0;if(b.length%4!==0)return!1;try{return atob(b),!0}catch{return!1}}var T9=U("$ZodBase64",(b,w)=>{w.pattern??(w.pattern=jQ),s.init(b,w),b._zod.onattach.push(($)=>{$._zod.bag.contentEncoding="base64"}),b._zod.check=($)=>{if(E9($.value))return;$.issues.push({code:"invalid_format",format:"base64",input:$.value,inst:b,continue:!w.abort})}});function E7(b){if(!X4.test(b))return!1;let w=b.replace(/[-_]/g,(W)=>W==="-"?"+":"/"),$=w.padEnd(Math.ceil(w.length/4)*4,"=");return E9($)}var _9=U("$ZodBase64URL",(b,w)=>{w.pattern??(w.pattern=X4),s.init(b,w),b._zod.onattach.push(($)=>{$._zod.bag.contentEncoding="base64url"}),b._zod.check=($)=>{if(E7($.value))return;$.issues.push({code:"invalid_format",format:"base64url",input:$.value,inst:b,continue:!w.abort})}}),S9=U("$ZodE164",(b,w)=>{w.pattern??(w.pattern=NQ),s.init(b,w)});function T7(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 R9=U("$ZodJWT",(b,w)=>{s.init(b,w),b._zod.check=($)=>{if(T7($.value,w.alg))return;$.issues.push({code:"invalid_format",format:"jwt",input:$.value,inst:b,continue:!w.abort})}});var z4=U("$ZodNumber",(b,w)=>{e.init(b,w),b._zod.pattern=b._zod.bag.pattern??CQ,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}:{}}),$}}),v9=U("$ZodNumber",(b,w)=>{cQ.init(b,w),z4.init(b,w)}),k9=U("$ZodBoolean",(b,w)=>{e.init(b,w),b._zod.pattern=xQ,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 C9=U("$ZodNull",(b,w)=>{e.init(b,w),b._zod.pattern=uQ,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 x9=U("$ZodUnknown",(b,w)=>{e.init(b,w),b._zod.parse=($)=>$}),u9=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 b9(b,w,$){if(b.issues.length)w.issues.push(...ww($,b.issues));w.value[$]=b.value}var y9=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)=>b9(J,$,X)));else b9(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 h9(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 $=$4(b.shape);return{...b,keys:w,keySet:new Set(w),numKeys:w.length,optionalKeys:new Set($)}}function f9(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 _7=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(()=>h9(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=Sw,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((F)=>j0(F,Y,O,J)));else j0(B,Y,O,J)}if(!G)return D.length?Promise.all(D).then(()=>Y):Y;return f9(D,J,Y,H,W.value,b)}}),g9=U("$ZodObjectJIT",(b,w)=>{_7.init(b,w);let $=b._zod.parse,W=fw(()=>h9(w)),Q=(O)=>{let q=new J4(["shape","payload","ctx"]),B=W.value,F=(S)=>{let h=L0(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=L0(S);q.write(`const ${h} = ${F(S)};`),q.write(`
12
+ `))}}var aQ={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=aQ;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=Fw(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=Fw(X,O)});else{if(X.issues.length===O)continue;if(!J)J=Fw(X,O)}}if(D)return D.then(()=>{return X});return X},G=(X,Y,H)=>{if(Fw(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 M0(b,Q).then((X)=>X.success?{value:X.data}:{issues:X.error?.issues})}},vendor:"zod",version:1}}),V0=U("$ZodString",(b,w)=>{e.init(b,w),b._zod.pattern=[...b?._zod.bag?.patterns??[]].pop()??kQ(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),V0.init(b,w)}),H9=U("$ZodGUID",(b,w)=>{w.pattern??(w.pattern=BQ),s.init(b,w)}),J9=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=G4(W))}else w.pattern??(w.pattern=G4());s.init(b,w)}),D9=U("$ZodEmail",(b,w)=>{w.pattern??(w.pattern=FQ),s.init(b,w)}),z9=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:VQ.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})}}}),A9=U("$ZodEmoji",(b,w)=>{w.pattern??(w.pattern=KQ()),s.init(b,w)}),O9=U("$ZodNanoID",(b,w)=>{w.pattern??(w.pattern=LQ),s.init(b,w)}),q9=U("$ZodCUID",(b,w)=>{w.pattern??(w.pattern=DQ),s.init(b,w)}),L9=U("$ZodCUID2",(b,w)=>{w.pattern??(w.pattern=zQ),s.init(b,w)}),U9=U("$ZodULID",(b,w)=>{w.pattern??(w.pattern=AQ),s.init(b,w)}),B9=U("$ZodXID",(b,w)=>{w.pattern??(w.pattern=OQ),s.init(b,w)}),F9=U("$ZodKSUID",(b,w)=>{w.pattern??(w.pattern=qQ),s.init(b,w)}),K9=U("$ZodISODateTime",(b,w)=>{w.pattern??(w.pattern=RQ(w)),s.init(b,w)}),P9=U("$ZodISODate",(b,w)=>{w.pattern??(w.pattern=TQ),s.init(b,w)}),M9=U("$ZodISOTime",(b,w)=>{w.pattern??(w.pattern=SQ(w)),s.init(b,w)}),Z9=U("$ZodISODuration",(b,w)=>{w.pattern??(w.pattern=UQ),s.init(b,w)}),I9=U("$ZodIPv4",(b,w)=>{w.pattern??(w.pattern=PQ),s.init(b,w),b._zod.onattach.push(($)=>{let W=$._zod.bag;W.format="ipv4"})}),j9=U("$ZodIPv6",(b,w)=>{w.pattern??(w.pattern=MQ),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})}}}),V9=U("$ZodCIDRv4",(b,w)=>{w.pattern??(w.pattern=ZQ),s.init(b,w)}),N9=U("$ZodCIDRv6",(b,w)=>{w.pattern??(w.pattern=IQ),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 E9(b){if(b==="")return!0;if(b.length%4!==0)return!1;try{return atob(b),!0}catch{return!1}}var T9=U("$ZodBase64",(b,w)=>{w.pattern??(w.pattern=jQ),s.init(b,w),b._zod.onattach.push(($)=>{$._zod.bag.contentEncoding="base64"}),b._zod.check=($)=>{if(E9($.value))return;$.issues.push({code:"invalid_format",format:"base64",input:$.value,inst:b,continue:!w.abort})}});function E7(b){if(!X4.test(b))return!1;let w=b.replace(/[-_]/g,(W)=>W==="-"?"+":"/"),$=w.padEnd(Math.ceil(w.length/4)*4,"=");return E9($)}var _9=U("$ZodBase64URL",(b,w)=>{w.pattern??(w.pattern=X4),s.init(b,w),b._zod.onattach.push(($)=>{$._zod.bag.contentEncoding="base64url"}),b._zod.check=($)=>{if(E7($.value))return;$.issues.push({code:"invalid_format",format:"base64url",input:$.value,inst:b,continue:!w.abort})}}),S9=U("$ZodE164",(b,w)=>{w.pattern??(w.pattern=NQ),s.init(b,w)});function T7(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 R9=U("$ZodJWT",(b,w)=>{s.init(b,w),b._zod.check=($)=>{if(T7($.value,w.alg))return;$.issues.push({code:"invalid_format",format:"jwt",input:$.value,inst:b,continue:!w.abort})}});var z4=U("$ZodNumber",(b,w)=>{e.init(b,w),b._zod.pattern=b._zod.bag.pattern??CQ,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}:{}}),$}}),k9=U("$ZodNumber",(b,w)=>{gQ.init(b,w),z4.init(b,w)}),v9=U("$ZodBoolean",(b,w)=>{e.init(b,w),b._zod.pattern=xQ,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 C9=U("$ZodNull",(b,w)=>{e.init(b,w),b._zod.pattern=uQ,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 x9=U("$ZodUnknown",(b,w)=>{e.init(b,w),b._zod.parse=($)=>$}),u9=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 b9(b,w,$){if(b.issues.length)w.issues.push(...ww($,b.issues));w.value[$]=b.value}var y9=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)=>b9(J,$,X)));else b9(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 h9(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 $=$4(b.shape);return{...b,keys:w,keySet:new Set(w),numKeys:w.length,optionalKeys:new Set($)}}function f9(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 _7=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(()=>h9(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=Sw,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 f9(D,J,Y,H,W.value,b)}}),c9=U("$ZodObjectJIT",(b,w)=>{_7.init(b,w);let $=b._zod.parse,W=fw(()=>h9(w)),Q=(O)=>{let q=new J4(["shape","payload","ctx"]),B=W.value,K=(S)=>{let h=L0(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=L0(S);q.write(`const ${h} = ${K(S)};`),q.write(`
13
13
  if (${h}.issues.length) {
14
14
  payload.issues = payload.issues.concat(${h}.issues.map(iss => ({
15
15
  ...iss,
@@ -26,7 +26,7 @@ var hz=Object.create;var{getPrototypeOf:fz,defineProperty:t$,getOwnPropertyNames
26
26
  newResult[${R}] = ${h}.value;
27
27
  }
28
28
 
29
- `)}q.write("payload.value = newResult;"),q.write("return payload;");let v=q.compile();return(S,h)=>v(O,S,h)},G,X=Sw,Y=!O0.jitless,J=Y&&b4.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 f9([],B,O,q,z,b)}return $(O,q)}});function w9(b,w,$,W){for(let G of b)if(G.issues.length===0)return w.value=G.value,w;let Q=b.filter((G)=>!Bw(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,_b())))}),w}var A4=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 w9(Y,Q,b,G);return Promise.all(Y).then((H)=>{return w9(H,Q,b,G)})}}),c9=U("$ZodDiscriminatedUnion",(b,w)=>{A4.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(!Sw(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}}),m9=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 $9($,H,J)});return $9($,G,X)}});function D4(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(Uw(b)&&Uw(w)){let $=Object.keys(w),W=Object.keys(b).filter((G)=>$.indexOf(G)!==-1),Q={...b,...w};for(let G of W){let X=D4(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=D4(Q,G);if(!X.valid)return{valid:!1,mergeErrorPath:[W,...X.mergeErrorPath]};$.push(X.data)}return{valid:!0,data:$}}return{valid:!1,mergeErrorPath:[]}}function $9(b,w,$){if(w.issues.length)b.issues.push(...w.issues);if($.issues.length)b.issues.push(...$.issues);if(Bw(b))return b;let W=D4(w.value,$.value);if(!W.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(W.mergeErrorPath)}`);return b.value=W.data,b}var n9=U("$ZodRecord",(b,w)=>{e.init(b,w),b._zod.parse=($,W)=>{let Q=$.value;if(!Uw(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,_b())),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 l9=U("$ZodEnum",(b,w)=>{e.init(b,w);let $=s$(w.entries),W=new Set($);b._zod.values=W,b._zod.pattern=new RegExp(`^(${$.filter((Q)=>w4.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}}),i9=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 p9=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 W9(b,w){if(b.issues.length&&w===void 0)return{issues:[],value:void 0};return b}var o9=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)=>W9(G,$.value));return W9(Q,$.value)}if($.value===void 0)return $;return w.innerType._zod.run($,W)}}),d9=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)}}),t9=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)=>Q9(G,w));return Q9(Q,w)}});function Q9(b,w){if(b.value===void 0)b.value=w.defaultValue;return b}var r9=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)}}),e9=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)=>G9(G,b));return G9(Q,b)}});function G9(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 s9=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,_b()))},input:$.value}),$.issues=[];return $});if($.value=Q.value,Q.issues.length)$.value=w.catchValue({...$,error:{issues:Q.issues.map((G)=>ub(G,W,_b()))},input:$.value}),$.issues=[];return $}});var a9=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)=>I0(X,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 b8=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(X9);return X9(Q)}});function X9(b){return b.value=Object.freeze(b.value),b}var w8=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)=>Y9(G,$,W,b));Y9(Q,$,W,b);return}});function Y9(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(gw(Q))}}var S7=(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},R7=()=>{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 ${S7(W.input)}`;case"invalid_value":if(W.values.length===1)return`Invalid input: expected ${B0(W.values[0])}`;return`Invalid option: expected one of ${q0(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":""}: ${q0(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 O4(){return{localeError:R7()}}var oM=Symbol("ZodOutput"),dM=Symbol("ZodInput");class $8{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 $8}var M1=v7();function W8(b,w){return new b({type:"string",..._(w)})}function Q8(b,w){return new b({type:"string",format:"email",check:"string_format",abort:!1,..._(w)})}function q4(b,w){return new b({type:"string",format:"guid",check:"string_format",abort:!1,..._(w)})}function G8(b,w){return new b({type:"string",format:"uuid",check:"string_format",abort:!1,..._(w)})}function X8(b,w){return new b({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",..._(w)})}function Y8(b,w){return new b({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",..._(w)})}function H8(b,w){return new b({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",..._(w)})}function J8(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 z8(b,w){return new b({type:"string",format:"nanoid",check:"string_format",abort:!1,..._(w)})}function A8(b,w){return new b({type:"string",format:"cuid",check:"string_format",abort:!1,..._(w)})}function O8(b,w){return new b({type:"string",format:"cuid2",check:"string_format",abort:!1,..._(w)})}function q8(b,w){return new b({type:"string",format:"ulid",check:"string_format",abort:!1,..._(w)})}function L8(b,w){return new b({type:"string",format:"xid",check:"string_format",abort:!1,..._(w)})}function U8(b,w){return new b({type:"string",format:"ksuid",check:"string_format",abort:!1,..._(w)})}function B8(b,w){return new b({type:"string",format:"ipv4",check:"string_format",abort:!1,..._(w)})}function K8(b,w){return new b({type:"string",format:"ipv6",check:"string_format",abort:!1,..._(w)})}function F8(b,w){return new b({type:"string",format:"cidrv4",check:"string_format",abort:!1,..._(w)})}function P8(b,w){return new b({type:"string",format:"cidrv6",check:"string_format",abort:!1,..._(w)})}function M8(b,w){return new b({type:"string",format:"base64",check:"string_format",abort:!1,..._(w)})}function Z8(b,w){return new b({type:"string",format:"base64url",check:"string_format",abort:!1,..._(w)})}function I8(b,w){return new b({type:"string",format:"e164",check:"string_format",abort:!1,..._(w)})}function j8(b,w){return new b({type:"string",format:"jwt",check:"string_format",abort:!1,..._(w)})}function V8(b,w){return new b({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,..._(w)})}function N8(b,w){return new b({type:"string",format:"date",check:"string_format",..._(w)})}function E8(b,w){return new b({type:"string",format:"time",check:"string_format",precision:null,..._(w)})}function T8(b,w){return new b({type:"string",format:"duration",check:"string_format",..._(w)})}function _8(b,w){return new b({type:"number",checks:[],..._(w)})}function S8(b,w){return new b({type:"number",check:"number_format",abort:!1,format:"safeint",..._(w)})}function R8(b,w){return new b({type:"boolean",..._(w)})}function v8(b,w){return new b({type:"null",..._(w)})}function k8(b){return new b({type:"unknown"})}function C8(b,w){return new b({type:"never",..._(w)})}function N0(b,w){return new Y4({check:"less_than",..._(w),value:b,inclusive:!1})}function Z1(b,w){return new Y4({check:"less_than",..._(w),value:b,inclusive:!0})}function E0(b,w){return new H4({check:"greater_than",..._(w),value:b,inclusive:!1})}function I1(b,w){return new H4({check:"greater_than",..._(w),value:b,inclusive:!0})}function T0(b,w){return new gQ({check:"multiple_of",..._(w),value:b})}function _0(b,w){return new mQ({check:"max_length",..._(w),maximum:b})}function cw(b,w){return new nQ({check:"min_length",..._(w),minimum:b})}function S0(b,w){return new lQ({check:"length_equals",..._(w),length:b})}function L4(b,w){return new iQ({check:"string_format",format:"regex",..._(w),pattern:b})}function U4(b){return new pQ({check:"string_format",format:"lowercase",..._(b)})}function B4(b){return new oQ({check:"string_format",format:"uppercase",..._(b)})}function K4(b,w){return new dQ({check:"string_format",format:"includes",..._(w),includes:b})}function F4(b,w){return new tQ({check:"string_format",format:"starts_with",..._(w),prefix:b})}function P4(b,w){return new rQ({check:"string_format",format:"ends_with",..._(w),suffix:b})}function Rw(b){return new eQ({check:"overwrite",tx:b})}function M4(b){return Rw((w)=>w.normalize(b))}function Z4(){return Rw((b)=>b.trim())}function I4(){return Rw((b)=>b.toLowerCase())}function j4(){return Rw((b)=>b.toUpperCase())}function x8(b,w,$){return new b({type:"array",element:w,..._($)})}function u8(b,w,$){let W=_($);return W.abort??(W.abort=!0),new b({type:"custom",check:"custom",fn:w,...W})}function y8(b,w,$){return new b({type:"custom",check:"custom",fn:w,..._($)})}function h8(b){let w=k7(($)=>{return $.addIssue=(W)=>{if(typeof W==="string")$.issues.push(gw(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(gw(Q))}},b($.value,$)});return w}function k7(b,w){let $=new Jb({check:"custom",..._(w)});return $._zod.check=b,$}function mw(b){return!!b._zod}function Kw(b,w){if(mw(b))return K1(b,w);return b.safeParse(w)}function R0(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 f8(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={};xW(V1,{time:()=>E4,duration:()=>T4,datetime:()=>V4,date:()=>N4,ZodISOTime:()=>m8,ZodISODuration:()=>n8,ZodISODateTime:()=>g8,ZodISODate:()=>c8});var g8=U("ZodISODateTime",(b,w)=>{F9.init(b,w),bb.init(b,w)});function V4(b){return V8(g8,b)}var c8=U("ZodISODate",(b,w)=>{P9.init(b,w),bb.init(b,w)});function N4(b){return N8(c8,b)}var m8=U("ZodISOTime",(b,w)=>{M9.init(b,w),bb.init(b,w)});function E4(b){return E8(m8,b)}var n8=U("ZodISODuration",(b,w)=>{Z9.init(b,w),bb.init(b,w)});function T4(b){return T8(n8,b)}var l8=(b,w)=>{K0.init(b,w),b.name="ZodError",Object.defineProperties(b,{format:{value:($)=>wQ(b,$)},flatten:{value:($)=>bQ(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}}})},kZ=U("ZodError",l8),Eb=U("ZodError",l8,{Parent:Error});var i8=F0(Eb),p8=P0(Eb),o8=B1(Eb),d8=F1(Eb),t8=$Q(Eb),r8=WQ(Eb),e8=QQ(Eb),s8=GQ(Eb),a8=XQ(Eb),bG=YQ(Eb),wG=HQ(Eb),$G=JQ(Eb);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)=>i8(b,$,W,{callee:b.parse}),b.safeParse=($,W)=>o8(b,$,W),b.parseAsync=async($,W)=>p8(b,$,W,{callee:b.parseAsync}),b.safeParseAsync=async($,W)=>d8(b,$,W),b.spa=b.safeParseAsync,b.encode=($,W)=>t8(b,$,W),b.decode=($,W)=>r8(b,$,W),b.encodeAsync=async($,W)=>e8(b,$,W),b.decodeAsync=async($,W)=>s8(b,$,W),b.safeEncode=($,W)=>a8(b,$,W),b.safeDecode=($,W)=>bG(b,$,W),b.safeEncodeAsync=async($,W)=>wG(b,$,W),b.safeDecodeAsync=async($,W)=>$G(b,$,W),b.refine=($,W)=>b.check(_5($,W)),b.superRefine=($)=>b.check(S5($)),b.overwrite=($)=>b.check(Rw($)),b.optional=()=>Wb(b),b.nullable=()=>GG(b),b.nullish=()=>Wb(GG(b)),b.nonoptional=($)=>I5(b,$),b.array=()=>f(b),b.or=($)=>t([b,$]),b.and=($)=>k0(b,$),b.transform=($)=>S4(b,DG($)),b.default=($)=>P5(b,$),b.prefault=($)=>Z5(b,$),b.catch=($)=>V5(b,$),b.pipe=($)=>S4(b,$),b.readonly=()=>T5(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}),XG=U("_ZodString",(b,w)=>{V0.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(L4(...W)),b.includes=(...W)=>b.check(K4(...W)),b.startsWith=(...W)=>b.check(F4(...W)),b.endsWith=(...W)=>b.check(P4(...W)),b.min=(...W)=>b.check(cw(...W)),b.max=(...W)=>b.check(_0(...W)),b.length=(...W)=>b.check(S0(...W)),b.nonempty=(...W)=>b.check(cw(1,...W)),b.lowercase=(W)=>b.check(U4(W)),b.uppercase=(W)=>b.check(B4(W)),b.trim=()=>b.check(Z4()),b.normalize=(...W)=>b.check(M4(...W)),b.toLowerCase=()=>b.check(I4()),b.toUpperCase=()=>b.check(j4())}),m7=U("ZodString",(b,w)=>{V0.init(b,w),XG.init(b,w),b.email=($)=>b.check(Q8(n7,$)),b.url=($)=>b.check(J8(l7,$)),b.jwt=($)=>b.check(j8(G5,$)),b.emoji=($)=>b.check(D8(i7,$)),b.guid=($)=>b.check(q4(WG,$)),b.uuid=($)=>b.check(G8(v0,$)),b.uuidv4=($)=>b.check(X8(v0,$)),b.uuidv6=($)=>b.check(Y8(v0,$)),b.uuidv7=($)=>b.check(H8(v0,$)),b.nanoid=($)=>b.check(z8(p7,$)),b.guid=($)=>b.check(q4(WG,$)),b.cuid=($)=>b.check(A8(o7,$)),b.cuid2=($)=>b.check(O8(d7,$)),b.ulid=($)=>b.check(q8(t7,$)),b.base64=($)=>b.check(M8($5,$)),b.base64url=($)=>b.check(Z8(W5,$)),b.xid=($)=>b.check(L8(r7,$)),b.ksuid=($)=>b.check(U8(e7,$)),b.ipv4=($)=>b.check(B8(s7,$)),b.ipv6=($)=>b.check(K8(a7,$)),b.cidrv4=($)=>b.check(F8(b5,$)),b.cidrv6=($)=>b.check(P8(w5,$)),b.e164=($)=>b.check(I8(Q5,$)),b.datetime=($)=>b.check(V4($)),b.date=($)=>b.check(N4($)),b.time=($)=>b.check(E4($)),b.duration=($)=>b.check(T4($))});function L(b){return W8(m7,b)}var bb=U("ZodStringFormat",(b,w)=>{s.init(b,w),XG.init(b,w)}),n7=U("ZodEmail",(b,w)=>{D9.init(b,w),bb.init(b,w)});var WG=U("ZodGUID",(b,w)=>{H9.init(b,w),bb.init(b,w)});var v0=U("ZodUUID",(b,w)=>{J9.init(b,w),bb.init(b,w)});var l7=U("ZodURL",(b,w)=>{z9.init(b,w),bb.init(b,w)});var i7=U("ZodEmoji",(b,w)=>{A9.init(b,w),bb.init(b,w)});var p7=U("ZodNanoID",(b,w)=>{O9.init(b,w),bb.init(b,w)});var o7=U("ZodCUID",(b,w)=>{q9.init(b,w),bb.init(b,w)});var d7=U("ZodCUID2",(b,w)=>{L9.init(b,w),bb.init(b,w)});var t7=U("ZodULID",(b,w)=>{U9.init(b,w),bb.init(b,w)});var r7=U("ZodXID",(b,w)=>{B9.init(b,w),bb.init(b,w)});var e7=U("ZodKSUID",(b,w)=>{K9.init(b,w),bb.init(b,w)});var s7=U("ZodIPv4",(b,w)=>{I9.init(b,w),bb.init(b,w)});var a7=U("ZodIPv6",(b,w)=>{j9.init(b,w),bb.init(b,w)});var b5=U("ZodCIDRv4",(b,w)=>{V9.init(b,w),bb.init(b,w)});var w5=U("ZodCIDRv6",(b,w)=>{N9.init(b,w),bb.init(b,w)});var $5=U("ZodBase64",(b,w)=>{T9.init(b,w),bb.init(b,w)});var W5=U("ZodBase64URL",(b,w)=>{_9.init(b,w),bb.init(b,w)});var Q5=U("ZodE164",(b,w)=>{S9.init(b,w),bb.init(b,w)});var G5=U("ZodJWT",(b,w)=>{R9.init(b,w),bb.init(b,w)});var YG=U("ZodNumber",(b,w)=>{z4.init(b,w),Qb.init(b,w),b.gt=(W,Q)=>b.check(E0(W,Q)),b.gte=(W,Q)=>b.check(I1(W,Q)),b.min=(W,Q)=>b.check(I1(W,Q)),b.lt=(W,Q)=>b.check(N0(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(QG(W)),b.safe=(W)=>b.check(QG(W)),b.positive=(W)=>b.check(E0(0,W)),b.nonnegative=(W)=>b.check(I1(0,W)),b.negative=(W)=>b.check(N0(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 p(b){return _8(YG,b)}var X5=U("ZodNumberFormat",(b,w)=>{v9.init(b,w),YG.init(b,w)});function QG(b){return S8(X5,b)}var Y5=U("ZodBoolean",(b,w)=>{k9.init(b,w),Qb.init(b,w)});function Hb(b){return R8(Y5,b)}var H5=U("ZodNull",(b,w)=>{C9.init(b,w),Qb.init(b,w)});function R4(b){return v8(H5,b)}var J5=U("ZodUnknown",(b,w)=>{x9.init(b,w),Qb.init(b,w)});function wb(){return k8(J5)}var D5=U("ZodNever",(b,w)=>{u9.init(b,w),Qb.init(b,w)});function z5(b){return C8(D5,b)}var A5=U("ZodArray",(b,w)=>{y9.init(b,w),Qb.init(b,w),b.element=w.element,b.min=($,W)=>b.check(cw($,W)),b.nonempty=($)=>b.check(cw(1,$)),b.max=($,W)=>b.check(_0($,W)),b.length=($,W)=>b.check(S0($,W)),b.unwrap=()=>b.element});function f(b,w){return x8(A5,b,w)}var HG=U("ZodObject",(b,w)=>{g9.init(b,w),Qb.init(b,w),n.defineLazy(b,"shape",()=>{return w.shape}),b.keyof=()=>Fb(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:z5()}),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(zG,b,$[0]),b.required=(...$)=>n.required(AG,b,$[0])});function j(b,w){let $={type:"object",shape:b??{},...n.normalizeParams(w)};return new HG($)}function Ub(b,w){return new HG({type:"object",shape:b,catchall:wb(),...n.normalizeParams(w)})}var JG=U("ZodUnion",(b,w)=>{A4.init(b,w),Qb.init(b,w),b.options=w.options});function t(b,w){return new JG({type:"union",options:b,...n.normalizeParams(w)})}var O5=U("ZodDiscriminatedUnion",(b,w)=>{JG.init(b,w),c9.init(b,w)});function v4(b,w,$){return new O5({type:"union",options:w,discriminator:b,...n.normalizeParams($)})}var q5=U("ZodIntersection",(b,w)=>{m9.init(b,w),Qb.init(b,w)});function k0(b,w){return new q5({type:"intersection",left:b,right:w})}var L5=U("ZodRecord",(b,w)=>{n9.init(b,w),Qb.init(b,w),b.keyType=w.keyType,b.valueType=w.valueType});function $b(b,w,$){return new L5({type:"record",keyType:b,valueType:w,...n.normalizeParams($)})}var _4=U("ZodEnum",(b,w)=>{l9.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 _4({...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 _4({...w,checks:[],...n.normalizeParams(Q),entries:G})}});function Fb(b,w){let $=Array.isArray(b)?Object.fromEntries(b.map((W)=>[W,W])):b;return new _4({type:"enum",entries:$,...n.normalizeParams(w)})}var U5=U("ZodLiteral",(b,w)=>{i9.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 N(b,w){return new U5({type:"literal",values:Array.isArray(b)?b:[b],...n.normalizeParams(w)})}var B5=U("ZodTransform",(b,w)=>{p9.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 DG(b){return new B5({type:"transform",transform:b})}var zG=U("ZodOptional",(b,w)=>{o9.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType});function Wb(b){return new zG({type:"optional",innerType:b})}var K5=U("ZodNullable",(b,w)=>{d9.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType});function GG(b){return new K5({type:"nullable",innerType:b})}var F5=U("ZodDefault",(b,w)=>{t9.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType,b.removeDefault=b.unwrap});function P5(b,w){return new F5({type:"default",innerType:b,get defaultValue(){return typeof w==="function"?w():n.shallowClone(w)}})}var M5=U("ZodPrefault",(b,w)=>{r9.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType});function Z5(b,w){return new M5({type:"prefault",innerType:b,get defaultValue(){return typeof w==="function"?w():n.shallowClone(w)}})}var AG=U("ZodNonOptional",(b,w)=>{e9.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType});function I5(b,w){return new AG({type:"nonoptional",innerType:b,...n.normalizeParams(w)})}var j5=U("ZodCatch",(b,w)=>{s9.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType,b.removeCatch=b.unwrap});function V5(b,w){return new j5({type:"catch",innerType:b,catchValue:typeof w==="function"?w:()=>w})}var N5=U("ZodPipe",(b,w)=>{a9.init(b,w),Qb.init(b,w),b.in=w.in,b.out=w.out});function S4(b,w){return new N5({type:"pipe",in:b,out:w})}var E5=U("ZodReadonly",(b,w)=>{b8.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType});function T5(b){return new E5({type:"readonly",innerType:b})}var OG=U("ZodCustom",(b,w)=>{w8.init(b,w),Qb.init(b,w)});function qG(b,w){return u8(OG,b??(()=>!0),w)}function _5(b,w={}){return y8(OG,b,w)}function S5(b){return h8(b)}function k4(b,w){return S4(DG(b),w)}_b(O4());var C4="2025-11-25";var LG=[C4,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Fw="io.modelcontextprotocol/related-task",x0="2.0",Db=qG((b)=>b!==null&&(typeof b==="object"||typeof b==="function")),UG=t([L(),p().int()]),BG=L(),TI=Ub({ttl:t([p(),R4()]).optional(),pollInterval:p().optional()}),R5=j({ttl:p().optional()}),v5=j({taskId:L()}),x4=Ub({progressToken:UG.optional(),[Fw]:v5.optional()}),Tb=j({_meta:x4.optional()}),N1=Tb.extend({task:R5.optional()}),KG=(b)=>N1.safeParse(b).success,zb=j({method:L(),params:Tb.loose().optional()}),Sb=j({_meta:x4.optional()}),Rb=j({method:L(),params:Sb.loose().optional()}),Ab=Ub({_meta:x4.optional()}),u0=t([L(),p().int()]),FG=j({jsonrpc:N(x0),id:u0,...zb.shape}).strict(),u4=(b)=>FG.safeParse(b).success,PG=j({jsonrpc:N(x0),...Rb.shape}).strict(),MG=(b)=>PG.safeParse(b).success,y4=j({jsonrpc:N(x0),id:u0,result:Ab}).strict(),E1=(b)=>y4.safeParse(b).success;var g;(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"})(g||(g={}));var h4=j({jsonrpc:N(x0),id:u0.optional(),error:j({code:p().int(),message:L(),data:wb().optional()})}).strict();var ZG=(b)=>h4.safeParse(b).success;var IG=t([FG,PG,y4,h4]),_I=t([y4,h4]),y0=Ab.strict(),k5=Sb.extend({requestId:u0.optional(),reason:L().optional()}),h0=Rb.extend({method:N("notifications/cancelled"),params:k5}),C5=j({src:L(),mimeType:L().optional(),sizes:f(L()).optional(),theme:Fb(["light","dark"]).optional()}),T1=j({icons:f(C5).optional()}),nw=j({name:L(),title:L().optional()}),jG=nw.extend({...nw.shape,...T1.shape,version:L(),websiteUrl:L().optional(),description:L().optional()}),x5=k0(j({applyDefaults:Hb().optional()}),$b(L(),wb())),u5=k4((b)=>{if(b&&typeof b==="object"&&!Array.isArray(b)){if(Object.keys(b).length===0)return{form:{}}}return b},k0(j({form:x5.optional(),url:Db.optional()}),$b(L(),wb()).optional())),y5=Ub({list:Db.optional(),cancel:Db.optional(),requests:Ub({sampling:Ub({createMessage:Db.optional()}).optional(),elicitation:Ub({create:Db.optional()}).optional()}).optional()}),h5=Ub({list:Db.optional(),cancel:Db.optional(),requests:Ub({tools:Ub({call:Db.optional()}).optional()}).optional()}),f5=j({experimental:$b(L(),Db).optional(),sampling:j({context:Db.optional(),tools:Db.optional()}).optional(),elicitation:u5.optional(),roots:j({listChanged:Hb().optional()}).optional(),tasks:y5.optional()}),g5=Tb.extend({protocolVersion:L(),capabilities:f5,clientInfo:jG}),f4=zb.extend({method:N("initialize"),params:g5});var c5=j({experimental:$b(L(),Db).optional(),logging:Db.optional(),completions:Db.optional(),prompts:j({listChanged:Hb().optional()}).optional(),resources:j({subscribe:Hb().optional(),listChanged:Hb().optional()}).optional(),tools:j({listChanged:Hb().optional()}).optional(),tasks:h5.optional()}),m5=Ab.extend({protocolVersion:L(),capabilities:c5,serverInfo:jG,instructions:L().optional()}),g4=Rb.extend({method:N("notifications/initialized"),params:Sb.optional()});var f0=zb.extend({method:N("ping"),params:Tb.optional()}),n5=j({progress:p(),total:Wb(p()),message:Wb(L())}),l5=j({...Sb.shape,...n5.shape,progressToken:UG}),g0=Rb.extend({method:N("notifications/progress"),params:l5}),i5=Tb.extend({cursor:BG.optional()}),_1=zb.extend({params:i5.optional()}),S1=Ab.extend({nextCursor:BG.optional()}),p5=Fb(["working","input_required","completed","failed","cancelled"]),R1=j({taskId:L(),status:p5,ttl:t([p(),R4()]),createdAt:L(),lastUpdatedAt:L(),pollInterval:Wb(p()),statusMessage:Wb(L())}),lw=Ab.extend({task:R1}),o5=Sb.merge(R1),v1=Rb.extend({method:N("notifications/tasks/status"),params:o5}),c0=zb.extend({method:N("tasks/get"),params:Tb.extend({taskId:L()})}),m0=Ab.merge(R1),n0=zb.extend({method:N("tasks/result"),params:Tb.extend({taskId:L()})}),SI=Ab.loose(),l0=_1.extend({method:N("tasks/list")}),i0=S1.extend({tasks:f(R1)}),p0=zb.extend({method:N("tasks/cancel"),params:Tb.extend({taskId:L()})}),VG=Ab.merge(R1),NG=j({uri:L(),mimeType:Wb(L()),_meta:$b(L(),wb()).optional()}),EG=NG.extend({text:L()}),c4=L().refine((b)=>{try{return atob(b),!0}catch{return!1}},{message:"Invalid Base64 string"}),TG=NG.extend({blob:c4}),k1=Fb(["user","assistant"]),iw=j({audience:f(k1).optional(),priority:p().min(0).max(1).optional(),lastModified:V1.datetime({offset:!0}).optional()}),_G=j({...nw.shape,...T1.shape,uri:L(),description:Wb(L()),mimeType:Wb(L()),annotations:iw.optional(),_meta:Wb(Ub({}))}),d5=j({...nw.shape,...T1.shape,uriTemplate:L(),description:Wb(L()),mimeType:Wb(L()),annotations:iw.optional(),_meta:Wb(Ub({}))}),m4=_1.extend({method:N("resources/list")}),t5=S1.extend({resources:f(_G)}),r5=_1.extend({method:N("resources/templates/list")}),e5=S1.extend({resourceTemplates:f(d5)}),n4=Tb.extend({uri:L()}),s5=n4,l4=zb.extend({method:N("resources/read"),params:s5}),a5=Ab.extend({contents:f(t([EG,TG]))}),bA=Rb.extend({method:N("notifications/resources/list_changed"),params:Sb.optional()}),wA=n4,$A=zb.extend({method:N("resources/subscribe"),params:wA}),WA=n4,QA=zb.extend({method:N("resources/unsubscribe"),params:WA}),GA=Sb.extend({uri:L()}),XA=Rb.extend({method:N("notifications/resources/updated"),params:GA}),YA=j({name:L(),description:Wb(L()),required:Wb(Hb())}),HA=j({...nw.shape,...T1.shape,description:Wb(L()),arguments:Wb(f(YA)),_meta:Wb(Ub({}))}),JA=_1.extend({method:N("prompts/list")}),DA=S1.extend({prompts:f(HA)}),zA=Tb.extend({name:L(),arguments:$b(L(),L()).optional()}),AA=zb.extend({method:N("prompts/get"),params:zA}),i4=j({type:N("text"),text:L(),annotations:iw.optional(),_meta:$b(L(),wb()).optional()}),p4=j({type:N("image"),data:c4,mimeType:L(),annotations:iw.optional(),_meta:$b(L(),wb()).optional()}),o4=j({type:N("audio"),data:c4,mimeType:L(),annotations:iw.optional(),_meta:$b(L(),wb()).optional()}),OA=j({type:N("tool_use"),name:L(),id:L(),input:$b(L(),wb()),_meta:$b(L(),wb()).optional()}),qA=j({type:N("resource"),resource:t([EG,TG]),annotations:iw.optional(),_meta:$b(L(),wb()).optional()}),LA=_G.extend({type:N("resource_link")}),d4=t([i4,p4,o4,LA,qA]),UA=j({role:k1,content:d4}),BA=Ab.extend({description:L().optional(),messages:f(UA)}),KA=Rb.extend({method:N("notifications/prompts/list_changed"),params:Sb.optional()}),FA=j({title:L().optional(),readOnlyHint:Hb().optional(),destructiveHint:Hb().optional(),idempotentHint:Hb().optional(),openWorldHint:Hb().optional()}),PA=j({taskSupport:Fb(["required","optional","forbidden"]).optional()}),SG=j({...nw.shape,...T1.shape,description:L().optional(),inputSchema:j({type:N("object"),properties:$b(L(),Db).optional(),required:f(L()).optional()}).catchall(wb()),outputSchema:j({type:N("object"),properties:$b(L(),Db).optional(),required:f(L()).optional()}).catchall(wb()).optional(),annotations:FA.optional(),execution:PA.optional(),_meta:$b(L(),wb()).optional()}),t4=_1.extend({method:N("tools/list")}),MA=S1.extend({tools:f(SG)}),o0=Ab.extend({content:f(d4).default([]),structuredContent:$b(L(),wb()).optional(),isError:Hb().optional()}),RI=o0.or(Ab.extend({toolResult:wb()})),ZA=N1.extend({name:L(),arguments:$b(L(),wb()).optional()}),C1=zb.extend({method:N("tools/call"),params:ZA}),IA=Rb.extend({method:N("notifications/tools/list_changed"),params:Sb.optional()}),vI=j({autoRefresh:Hb().default(!0),debounceMs:p().int().nonnegative().default(300)}),x1=Fb(["debug","info","notice","warning","error","critical","alert","emergency"]),jA=Tb.extend({level:x1}),r4=zb.extend({method:N("logging/setLevel"),params:jA}),VA=Sb.extend({level:x1,logger:L().optional(),data:wb()}),NA=Rb.extend({method:N("notifications/message"),params:VA}),EA=j({name:L().optional()}),TA=j({hints:f(EA).optional(),costPriority:p().min(0).max(1).optional(),speedPriority:p().min(0).max(1).optional(),intelligencePriority:p().min(0).max(1).optional()}),_A=j({mode:Fb(["auto","required","none"]).optional()}),SA=j({type:N("tool_result"),toolUseId:L().describe("The unique identifier for the corresponding tool call."),content:f(d4).default([]),structuredContent:j({}).loose().optional(),isError:Hb().optional(),_meta:$b(L(),wb()).optional()}),RA=v4("type",[i4,p4,o4]),C0=v4("type",[i4,p4,o4,OA,SA]),vA=j({role:k1,content:t([C0,f(C0)]),_meta:$b(L(),wb()).optional()}),kA=N1.extend({messages:f(vA),modelPreferences:TA.optional(),systemPrompt:L().optional(),includeContext:Fb(["none","thisServer","allServers"]).optional(),temperature:p().optional(),maxTokens:p().int(),stopSequences:f(L()).optional(),metadata:Db.optional(),tools:f(SG).optional(),toolChoice:_A.optional()}),CA=zb.extend({method:N("sampling/createMessage"),params:kA}),e4=Ab.extend({model:L(),stopReason:Wb(Fb(["endTurn","stopSequence","maxTokens"]).or(L())),role:k1,content:RA}),s4=Ab.extend({model:L(),stopReason:Wb(Fb(["endTurn","stopSequence","maxTokens","toolUse"]).or(L())),role:k1,content:t([C0,f(C0)])}),xA=j({type:N("boolean"),title:L().optional(),description:L().optional(),default:Hb().optional()}),uA=j({type:N("string"),title:L().optional(),description:L().optional(),minLength:p().optional(),maxLength:p().optional(),format:Fb(["email","uri","date","date-time"]).optional(),default:L().optional()}),yA=j({type:Fb(["number","integer"]),title:L().optional(),description:L().optional(),minimum:p().optional(),maximum:p().optional(),default:p().optional()}),hA=j({type:N("string"),title:L().optional(),description:L().optional(),enum:f(L()),default:L().optional()}),fA=j({type:N("string"),title:L().optional(),description:L().optional(),oneOf:f(j({const:L(),title:L()})),default:L().optional()}),gA=j({type:N("string"),title:L().optional(),description:L().optional(),enum:f(L()),enumNames:f(L()).optional(),default:L().optional()}),cA=t([hA,fA]),mA=j({type:N("array"),title:L().optional(),description:L().optional(),minItems:p().optional(),maxItems:p().optional(),items:j({type:N("string"),enum:f(L())}),default:f(L()).optional()}),nA=j({type:N("array"),title:L().optional(),description:L().optional(),minItems:p().optional(),maxItems:p().optional(),items:j({anyOf:f(j({const:L(),title:L()}))}),default:f(L()).optional()}),lA=t([mA,nA]),iA=t([gA,cA,lA]),pA=t([iA,xA,uA,yA]),oA=N1.extend({mode:N("form").optional(),message:L(),requestedSchema:j({type:N("object"),properties:$b(L(),pA),required:f(L()).optional()})}),dA=N1.extend({mode:N("url"),message:L(),elicitationId:L(),url:L().url()}),tA=t([oA,dA]),rA=zb.extend({method:N("elicitation/create"),params:tA}),eA=Sb.extend({elicitationId:L()}),sA=Rb.extend({method:N("notifications/elicitation/complete"),params:eA}),d0=Ab.extend({action:Fb(["accept","decline","cancel"]),content:k4((b)=>b===null?void 0:b,$b(L(),t([L(),p(),Hb(),f(L())])).optional())}),aA=j({type:N("ref/resource"),uri:L()});var bO=j({type:N("ref/prompt"),name:L()}),wO=Tb.extend({ref:t([bO,aA]),argument:j({name:L(),value:L()}),context:j({arguments:$b(L(),L()).optional()}).optional()}),$O=zb.extend({method:N("completion/complete"),params:wO});var WO=Ab.extend({completion:Ub({values:f(L()).max(100),total:Wb(p().int()),hasMore:Wb(Hb())})}),QO=j({uri:L().startsWith("file://"),name:L().optional(),_meta:$b(L(),wb()).optional()}),GO=zb.extend({method:N("roots/list"),params:Tb.optional()}),a4=Ab.extend({roots:f(QO)}),XO=Rb.extend({method:N("notifications/roots/list_changed"),params:Sb.optional()}),kI=t([f0,f4,$O,r4,AA,JA,m4,r5,l4,$A,QA,C1,t4,c0,n0,l0,p0]),CI=t([h0,g0,g4,XO,v1]),xI=t([y0,e4,s4,d0,a4,m0,i0,lw]),uI=t([f0,CA,rA,GO,c0,n0,l0,p0]),yI=t([h0,g0,NA,XA,bA,IA,KA,v1,sA]),hI=t([y0,m5,WO,BA,DA,t5,e5,a5,o0,MA,m0,i0,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===g.UrlElicitationRequired&&$){let W=$;if(W.elicitations)return new RG(W.elicitations,w)}return new x(b,w,$)}}class RG extends x{constructor(b,w=`URL elicitation${b.length>1?"s":""} required`){super(g.UrlElicitationRequired,w,{elicitations:b})}get elicitations(){return this.data?.elicitations??[]}}function Pw(b){return b==="completed"||b==="failed"||b==="cancelled"}var YO=Symbol("Let zodToJsonSchema decide on which parser to use");var Bj=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function b6(b){let $=R0(b)?.method;if(!$)throw Error("Schema is missing a method literal");let W=f8($);if(typeof W!=="string")throw Error("Schema method literal must be a string");return W}function w6(b,w){let $=Kw(b,w);if(!$.success)throw $.error;return $.data}var OO=60000;class $6{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(h0,(w)=>{this._oncancel(w)}),this.setNotificationHandler(g0,(w)=>{this._onprogress(w)}),this.setRequestHandler(f0,(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(g.InvalidParams,"Failed to retrieve task: Task not found");return{...W}}),this.setRequestHandler(n0,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(g.InvalidParams,`Task not found: ${Q}`);if(!Pw(G.status))return await this._waitForTaskUpdate(Q,$.signal),await W();if(Pw(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(l0,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(g.InvalidParams,`Failed to list tasks: ${W instanceof Error?W.message:String(W)}`)}}),this.setRequestHandler(p0,async(w,$)=>{try{let W=await this._taskStore.getTask(w.params.taskId,$.sessionId);if(!W)throw new x(g.InvalidParams,`Task not found: ${w.params.taskId}`);if(Pw(W.status))throw new x(g.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(g.InvalidParams,`Task not found after cancellation: ${w.params.taskId}`);return{_meta:{},...Q}}catch(W){if(W instanceof x)throw W;throw new x(g.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(g.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),E1(Q)||ZG(Q))this._onresponse(Q);else if(u4(Q))this._onrequest(Q,G);else if(MG(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(g.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:g.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=KG(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:g.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),E1(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(E1(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(E1(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(g.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(g.InternalError,"Task creation did not return a task");while(!0){let X=await this.getTask({taskId:Q},$);if(yield{type:"taskStatus",task:X},Pw(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(g.InternalError,`Task ${Q} failed`)};else if(X.status==="cancelled")yield{type:"error",error:new x(g.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(g.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 v=M instanceof x?M:new x(g.RequestTimeout,String(M));J(v)};this._responseHandlers.set(z,(M)=>{if($?.signal?.aborted)return;if(M instanceof Error)return J(M);try{let v=Kw(w,M.result);if(!v.success)J(v.error);else H(v.data)}catch(v){J(v)}}),$?.signal?.addEventListener("abort",()=>{q($?.signal?.reason)});let B=$?.timeout??OO,F=()=>q(x.fromError(g.RequestTimeout,"Request timed out",{timeout:B}));this._setupTimeout(z,B,$?.maxTotalTimeout,F,$?.resetTimeoutOnProgress??!1);let Z=Y?.taskId;if(Z){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(Z,{type:"request",message:O,timestamp:Date.now()}).catch((v)=>{this._cleanupTimeout(z),J(v)})}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},m0,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},VG,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 $=b6(b);this.assertRequestHandlerCapability($),this._requestHandlers.set($,(W,Q)=>{let G=w6(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 $=b6(b);this._notificationHandlers.set($,(W)=>{let Q=w6(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 x(g.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(g.InvalidRequest,"Request cancelled"));return}let G=setTimeout(W,$);w.addEventListener("abort",()=>{clearTimeout(G),Q(new x(g.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(g.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=v1.parse({method:"notifications/tasks/status",params:X});if(await this.notification(Y),Pw(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(g.InvalidParams,`Task "${W}" not found - it may have been cleaned up`);if(Pw(X.status))throw new x(g.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=v1.parse({method:"notifications/tasks/status",params:Y});if(await this.notification(H),Pw(Y.status))this._cleanupTaskProgressHandler(W)}},listTasks:(W)=>{return $.listTasks(W,w)}}}}function vG(b){return b!==null&&typeof b==="object"&&!Array.isArray(b)}function kG(b,w){let $={...b};for(let W in w){let Q=W,G=w[Q];if(G===void 0)continue;let X=$[Q];if(vG(X)&&vG(G))$[Q]={...X,...G};else $[Q]=G}return $}var DD=CW(r6(),1),zD=CW(JD(),1);function ZP(){let b=new DD.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return zD.default(b),b}class XW{constructor(b){this._ajv=b??ZP()}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 YW{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 AD(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 OD(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 HW extends $6{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 XW,this.setRequestHandler(f4,($)=>this._oninitialize($)),this.setNotificationHandler(g4,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(r4,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 YW(this)};return this._experimental}registerCapabilities(b){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=kG(this._capabilities,b)}setRequestHandler(b,w){let W=R0(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=Kw(C1,Y);if(!J.success){let q=J.error instanceof Error?J.error.message:String(J.error);throw new x(g.InvalidParams,`Invalid tools/call request: ${q}`)}let{params:D}=J.data,z=await Promise.resolve(w(Y,H));if(D.task){let q=Kw(lw,z);if(!q.success){let B=q.error instanceof Error?q.error.message:String(q.error);throw new x(g.InvalidParams,`Invalid task creation result: ${B}`)}return q.data}let O=Kw(o0,z);if(!O.success){let q=O.error instanceof Error?O.error.message:String(O.error);throw new x(g.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){OD(this._clientCapabilities?.tasks?.requests,b,"Client")}assertTaskHandlerCapability(b){if(!this._capabilities)return;AD(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:LG.includes(w)?w:C4,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"},y0)}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},s4,w);return this.request({method:"sampling/createMessage",params:b},e4,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},d0,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},d0,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(g.InvalidParams,`Elicitation response content does not match requested schema: ${X.errorMessage}`)}catch(G){if(G instanceof x)throw G;throw new x(g.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},a4,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 qD={name:"@sequenzy/mcp",version:"0.0.107",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 JW=["product-info","domain","tracking","localization","integrations","products","events","tags","labels","goals","sync-rules","api-keys","widgets","team","danger"],LD={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 jP(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 rb(b){return encodeURIComponent(b)}function Xb(b,w){return`${b}${w}`}function Yb(b,w=""){return`/dashboard/company/${rb(b)}${w}`}function UD(b,w,$){return Xb(b,`${Yb(w,"/settings")}?tab=${encodeURIComponent($)}`)}function VP(b,w){let $=JW.map((W)=>[W,w?UD(b,w,W):""]);return Object.fromEntries($)}function Hw(b={},w){let $=jP(w),W=nb(b.companyId),Q={},G=VP($,W);if(!W)return{appUrl:$,routeTemplates:LD,settingsTabValues:JW,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/${rb(X)}`)),Q.campaignPreview=`${Q.campaign}?step=review`;let Y=nb(b.landingPageId);if(Y)Q.landingPage=Xb($,Yb(W,`/landing-pages/${rb(Y)}`));let H=nb(b.sequenceId);if(H)Q.sequence=Xb($,Yb(W,`/sequences/${rb(H)}`));let J=nb(b.emailId)??nb(b.templateId);if(J)Q.email=Xb($,Yb(W,`/emails/${rb(J)}`)),Q.template=Q.email;let D=nb(b.transactionalId);if(D)Q.transactionalEmail=Xb($,Yb(W,`/transactional/${rb(D)}`));let z=nb(b.emailSendId);if(z)Q.emailSend=Xb($,Yb(W,`/sent-emails/${rb(z)}`));let O=nb(b.domainId);if(O)Q.domain=Xb($,Yb(W,`/settings/domain/${rb(O)}`)),Q.domainVerify=`${Q.domain}/verify`;let q=nb(b.status);if(q)Q.campaignList=Xb($,Yb(W,`/campaign/list/${rb(q)}`)),Q.sequenceList=Xb($,Yb(W,`/sequences/list/${rb(q)}`));let B=nb(b.settingsTab);if(B)Q.settingsTab=UD($,W,B);return{appUrl:$,routeTemplates:LD,settingsTabValues:JW,urls:Q,settingsUrls:G}}var BD=[{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 KD(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=Ow()??$.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:Aw(w)}]}}}function y(b){return typeof b==="object"&&b!==null&&!Array.isArray(b)}function K(b,w){let $=b[w];if(typeof $!=="string")return;let W=$.trim();return W.length>0?W:void 0}function V(b,w,$){let W=K(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`.',_w='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 the transactional send `variables` or an automation `event` payload, use { "id": "c1", "field": "variable", "operator": "is", "value": "plan:pro" } where the text before the colon is a {{merge tag}} path (nested paths like "order.total" or "event.plan" work) and the text after it is the comparison value. `field` may also be "attribute" (same "name:value" form) or "email"/"firstName"/"lastName" (the value is the plain comparison string). Operators: is, is_not, contains, not_contains, gt, gte, lt, lte, is_empty, is_not_empty. 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 the transactional send `variables` or an automation `event` payload, use { "id": "c1", "field": "variable", "operator": "is", "value": "plan:pro" } where the text before the colon is a {{merge tag}} path (nested paths like "order.total" or "event.plan" work) and the text after it is the comparison value. `field` may also be "attribute" (same "name:value" form) or "email"/"firstName"/"lastName" (the value is the plain comparison string). Operators: is, is_not, contains, not_contains, gt, gte, lt, lte, is_empty, is_not_empty. 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 the transactional send `variables` or an automation `event` payload, use { "id": "c1", "field": "variable", "operator": "is", "value": "plan:pro" } where the text before the colon is a {{merge tag}} path (nested paths like "order.total" or "event.plan" work) and the text after it is the comparison value. `field` may also be "attribute" (same "name:value" form) or "email"/"firstName"/"lastName" (the value is the plain comparison string). Operators: is, is_not, contains, not_contains, gt, gte, lt, lte, is_empty, is_not_empty. 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.",FD="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.",DW=500,zW=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"],C$={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},NP={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:NP,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},AW={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},x$={type:"object",properties:{nodeId:{type:"string",description:"Existing node ID from get_sequence.sequence.nodes[].id."},changes:AW,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","sequence.finished","sequence.failed","poll.answered"];var EP=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_sequence","generate_subject_lines","generate_sms","get_sms_settings"]),TP=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","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","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"]),_P=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"]),SP=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 RP(b){let w=EP.has(b),$=TP.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:SP.has(b),openWorldHint:_P.has(b)}}function PD(b){return{...b,annotations:{...b.annotations,...RP(b.name)}}}var OW={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(OW).map(([b,w])=>`${b}: ${w.join(", ")}`).join("; "),qW={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},LW={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 y$(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(y$):[]}}function kP(b){let w=b.indexOf(":");return w!==-1&&b.substring(0,w).trim().length>0}function CP(b){let w=b.indexOf(":");return w!==-1&&b.substring(w+1).trim().length>0}function MD(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 xP(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&&MD(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&&MD(Q)?null:'Event filters must use "eventName:timeRange", like "saas.purchase:30d".'}function uP(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 yP(b){return b.trim().toLowerCase().replace(/[-\s]+/g,"_")}function hP(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 fP(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 gP(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}=uP($);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=yP(Q);if(hP(X))return w==="is"||w==="is_not"?null:"Stripe cancellation flag filters only support is and is_not operators.";if(!fP(b,X))return`Unsupported Stripe product subfilter "${Q}".`;if(!gP(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 mP=new Set(["shopify","woocommerce","api"]);function nP(b,w){let $=w.trim(),W=$.indexOf(":");if(W!==-1&&mP.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 lP(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 h$(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 OW))return`Unsupported segment filter field "${String($)}".`;if(typeof W!=="string")return`Segment filter "${$}" must include an operator.`;let G=OW[$];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(!kP(Q))return'Attribute filters must use "attributeName:value" or "attributeName:" for empty checks.';if(W!=="is_empty"&&W!=="is_not_empty"&&!CP(Q))return'Attribute filters must include a value after "attributeName:".'}if($==="event"&&typeof Q==="string"){let X=xP(W,Q);if(X)return X}if($==="pollResponse"&&typeof Q==="string"){let X=lP(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=nP(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 f$(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 $=h$(w);return $?[$]:[]}if(Array.isArray(w.children))return w.children.flatMap(f$);return[]}function Cb(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 jD(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=h$(Q);return G?[G]:[]}):f$(b.root);if(W.length>0)throw Error(W[0]??"Invalid segment filter in `create_segment`.")}function VD(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=h$(Q);return G?[G]:[]}):$?f$(b.root):[];if(W.length>0)throw Error(W[0]??"Invalid segment filter in `update_segment`.")}var UW=["name","description","logoUrl","founderName","primaryColor","brandColors","valueProps","testimonials","toneVoice","companyContext","emailLengthPreference","socialLinks","privacyPolicyUrl","termsUrl","address","language","pricing","fontFamily","emailDirection","fromEmail","fromName","replyTo","replyToName"];function BW(b,w,$){if(w[$]!==void 0&&!y(w[$]))throw Error(`\`${$}\` must be an object when calling \`${b}\`.`)}function ZD(b,w,$){if(w[$]!==void 0&&!Array.isArray(w[$]))throw Error(`\`${$}\` must be an array when calling \`${b}\`.`)}function ND(b){let w=new Set(["companyId",...UW]),$=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 UW)if(b[Q]!==void 0)W[Q]=b[Q];if(Object.keys(W).length===0)throw Error(`Provide at least one of ${UW.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(BW("update_company",b,"brandColors"),BW("update_company",b,"socialLinks"),BW("update_company",b,"pricing"),ZD("update_company",b,"valueProps"),ZD("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 ED=["senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName"];function iP(b){return ED.some((w)=>b[w]!==void 0)}function pP(b){if(typeof b.nodeType==="string")return b.nodeType==="action_email";return b.type===void 0||b.type==="email"}function g$(b,w,$){for(let W of ED){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(iP($)&&!pP($))throw Error(`Sender identity fields are only supported for email steps at ${w} when calling \`${b}\`.`);g$(b,w,$)}function ID(b,w,$){if(!Array.isArray($))return;$.forEach((W,Q)=>{if(y(W))g$(b,`${w}[${Q}]`,W)})}function KW(b,w,$){if(!Array.isArray($))return;$.forEach((W,Q)=>{if(y(W))FW(b,`${w}[${Q}]`,W)})}function oP(b){if(ID("update_sequence","emails",b.emails),ID("update_sequence","steps",b.steps),y(b.insertSteps))KW("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($))KW("update_sequence",`branch.branches[${W}].steps`,$.steps)});KW("update_sequence","branch.elseSteps",b.branch.elseSteps)}function TD(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.");oP(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 _D(b,w,$){let W=V(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=V(b,w,"expectedUpdatedAt");return{nodeId:W,changes:w.changes,expectedUpdatedAt:Q}}function SD(b){let w=_D("update_sequence_node",b,"the node update");return{...b.confirmLiveChange!==void 0&&{confirmLiveChange:b.confirmLiveChange},nodeUpdates:[w]}}function RD(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=_D("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 vD(b){let w=V("edit_sequence_graph",b,"action"),$=V("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=K(b,"nodeId"),G=K(b,"afterNodeId"),X=K(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=V("edit_sequence_graph",D,"sourceNodeId"),q=V("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 kD(b){let w=b.type==="sms",$;if(w){FW("insert_sequence_step","SMS step",b);let Q=K(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{Cb("insert_sequence_step",b,{requireContent:!0}),g$("insert_sequence_step","email step",b),$={subject:V("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 CD(b){let w=K(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=K(b,"fieldPath"),X=K(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 xD(b){Cb("create_campaign",b),H1("create_campaign",b);let w=K(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&&K(b,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_campaign`.")}function uD(b){Cb("create_template",b),H1("create_template",b);let w=K(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&&K(b,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_template`.")}function yD(b){if(K(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 hD(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 fD(b){Cb("create_transactional_email",b);let w=K(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&&K(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},PW={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."}},m$={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 gD(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 MW(b){return b.trim().toLowerCase().replace(/\s+/g,"-")}function dP(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 mD(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=dP({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 tP(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 zw(b,w){let $=tP(w);if(!$.email&&!$.externalId)throw Error(`Provide either \`email\` or \`externalId\` when calling \`${b}\`.`);return $}function n$(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 ZW(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",n$(b,$),void 0,w)}function jb(b,w,$,W){let Q=K(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=V(b,w,$);if(!W.includes(Q))throw Error(`\`${$}\` must be one of ${W.join(", ")} when calling \`${b}\`.`);return Q}function Dw(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 rP(b,w){let $=[],W=jb(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 IW(b,w){let $=new URLSearchParams,W=rP(b,w);if(W.length>0)$.set("eventTypes",W.join(","));let Q=jb(b,w,"period",["1h","24h","7d","30d","90d"]);if(Q)$.set("period",Q);let G=K(w,"start");if(G)$.set("start",G);let X=K(w,"end");if(X)$.set("end",X);let Y=Dw(b,w,"page",1,1e6);if(Y!==void 0)$.set("page",String(Y));let H=Dw(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 VW(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>DW)throw Error(`\`emails\` must include no more than ${DW} email addresses when calling \`${b}\`. Split larger batches into multiple calls.`);return $}function cD(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 nD(b){let $=cD("enroll_subscribers_in_sequence",b,"emails","email address"),W=cD("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>zW)throw Error(`\`emails\` and \`subscriberIds\` must include no more than ${zW} total targets when calling \`enroll_subscribers_in_sequence\`. Split larger batches into multiple calls.`);let G=K(b,"targetNodeId");return{...$!==void 0&&{emails:$},...W!==void 0&&{subscriberIds:W},...G!==void 0&&{targetNodeId:G}}}import{readFileSync as eP,statSync as sP}from"node:fs";import{basename as aP}from"node:path";var bM={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 wM(b){let w=b.split(".").pop()?.toLowerCase()??"";return bM[w]??null}var $M=104857600;async function lD(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 $=wM(b);if(!$)throw Error("Unsupported file type. Use PDF, ePub, ZIP, image, audio, video, or text files.");let W=sP(b).size;if(W>$M)throw Error(`File is too large (${Math.round(W/1048576)}MB). Delivery files must be 100MB or smaller.`);let Q=eP(b),G=await A("POST","/api/v1/products/delivery/upload-url",{filename:aP(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 l$(b){let w=K(b,"companyId");if(w)return w;let $=Ow();if($)return $;try{return(await A("GET","/api/v1/account")).currentCompanyId??void 0}catch{return}}async function iD(b,w){let $=await l$(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 pD(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=K(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 pD(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 WM(b){if(!Array.isArray(b))return b;return b.map((w)=>{if(!y(w))return w;let $=K(w,"id");if(!$)return w;let W=Hw({companyId:$});return{...w,url:W.urls.dashboard,settingsUrl:W.urls.settings}})}var NW=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","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","list_transactional_emails","get_transactional_email","create_transactional_email","update_transactional_email"]);async function oD(b,w,$){if(!y($)||!NW.has(b))return $;let W=y($.company)?$.company:void 0,G=K($,"selectedCompanyId")??K($,"currentCompanyId")??K($,"companyId")??(W?K(W,"id"):void 0)??(W?K(W,"companyId"):void 0)??await l$(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:K(w,"campaignId")??K($,"campaignId")??(X?K(X,"id"):void 0),landingPageId:K(w,"landingPageId")??K($,"landingPageId")??(H?K(H,"id"):void 0),sequenceId:K(w,"sequenceId")??K($,"sequenceId")??(Y?K(Y,"id"):void 0),emailId:K($,"templateId")??(J?K(J,"id"):void 0)??(D?K(D,"emailId"):void 0)??K(w,"templateId"),transactionalId:K(w,"transactionalId")??(D?K(D,"id"):void 0)??K(w,"idOrSlug"),emailSendId:K(w,"emailSendId")??K($,"emailSendId")??(y($.emailSend)?K($.emailSend,"id"):void 0),status:K(w,"status")},O=Hw(z),q=W?Hw({companyId:G}):void 0;return{...$,...Array.isArray($.companies)&&{companies:WM($.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:pD(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 QM,statSync as GM}from"node:fs";import{basename as XM,extname as tD}from"node:path";var TW=5242880,YM=Math.ceil(TW/3)*4,HM=Math.ceil(YM*1.05)+256,rD={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"},JM=new Set(Object.values(rD));function EW(b){return b?.split(";")[0]?.trim().toLowerCase()||void 0}function DM(b){return rD[tD(b).toLowerCase()]}function zM(b){let w=tD(b);return(w?b.slice(0,-w.length):b).replace(/[-_]+/g," ").trim()||"Image"}function AM(b){if(b.length>HM)throw Error("Image assets must be 5MB or smaller.")}function OM(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 qM(b){AM(b);let w=b.trim(),$=/^data:([^;,]+);base64,([\s\S]+)$/i.exec(w),W=$?.[2]??w;OM(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:EW($[1])}:{}}}function dD(b){if(b<=0)throw Error("The image file is empty.");if(b>TW)throw Error("Image assets must be 5MB or smaller.")}function LM(b){let w=DM(b.filename)??EW(b.explicitContentType)??EW(b.dataUrlContentType);if(!w||!JM.has(w))throw Error("Unsupported image type. Use PNG, JPEG, GIF, or WebP.");return w}function UM(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=GM(b.filePath).size;dD(G),w=QM(b.filePath),$=b.filename??XM(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=qM(b.imageBase64);w=G.bytes,W=G.dataUrlContentType,$=b.filename,dD(w.byteLength)}let Q=LM({filename:$,explicitContentType:b.contentType,dataUrlContentType:W});return{bytes:w,filename:$,contentType:Q,altText:b.altText??zM($)}}async function eD(b){let w=UM(b),$=w.bytes.byteLength,W=await A("POST","/api/v1/media/upload-url",{filename:w.filename,contentType:w.contentType,fileSizeBytes:$},b.companyId);return await lW(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 BM={type:"boolean",description:"Whether the Sequenzy operation succeeded."},KM={type:"string",description:"Human-readable status, confirmation, or next-step message."},FM={type:"string",description:"Additional context about the result."};function r(b){return{type:"object",description:b,additionalProperties:!0}}function PM(b){return{type:"array",description:b,items:r("One item in the returned collection.")}}function T(b){return{type:"string",description:b}}function Vb(b){return{type:"number",description:b}}function eb(b){return{type:"boolean",description:b}}function P(b){return r(`The ${b} record returned by Sequenzy.`)}function i(b){return PM(`List of ${b} records returned by Sequenzy.`)}var MM={appUrls:r("Dashboard URLs for relevant Sequenzy resources."),url:T("Primary dashboard URL for this result."),settingsUrl:T("Company settings URL when available.")},ZM={success:BM,message:KM,note:FM,items:{type:"array",description:"Fallback array wrapper used only when a tool returns a bare array.",items:r("One returned item.")},value:r("Fallback object wrapper used only when a tool returns a non-object value.")},IM={get_account:{account:P("account"),companies:i("company"),apiKeyPermissions:r("Current API key preset and scopes, whether common marketing work is discoverable, any missing marketing read scopes, and the API Keys management URL."),currentCompanyId:T("Company ID selected by the authenticated API key, when available."),selectedCompanyId:T("Company ID selected locally for subsequent MCP calls, when available.")},select_company:{companyId:T("Selected company ID."),companyName:T("Selected company name.")},get_app_urls:{dashboard:T("Company dashboard URL."),settings:T("Company settings URL."),campaign:T("Campaign editor URL."),landingPage:T("Landing page editor URL."),sequence:T("Sequence editor URL."),email:T("Email editor URL."),transactionalEmail:T("Transactional email URL."),emailSend:T("Sent email detail URL."),domain:T("Sending domain settings URL."),urls:r("All generated URLs keyed by resource type.")},create_company:{company:P("company"),autoSelected:eb("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:r("One sync rule.")},isDefault:eb("Whether the company still uses the platform default rules.")},update_sync_rules:{syncRules:{type:"array",description:"Effective sync rules after the update.",items:r("One sync rule.")},isDefault:eb("Whether the company now uses the platform default rules.")},get_shopify_automation_settings:{browseAbandonment:r("Effective browse-abandonment settings (defaults applied)."),priceDrop:r("Effective price-drop settings (defaults applied)."),shopDomain:T("Connected Shopify store domain.")},update_shopify_automation_settings:{browseAbandonment:r("Effective browse-abandonment settings after the update."),priceDrop:r("Effective price-drop settings after the update."),shopDomain:T("Connected Shopify store domain.")},create_api_key:{apiKey:r("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:T("Newly created API key if the API response uses the short key field.")},list_websites:{websites:i("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:eb("Whether the sender website is ready."),status:T("Current processing or verification status.")},verify_sending_domain:{website:P("Sending domain with current aggregate, SPF, DKIM, and MAIL FROM verification details."),verified:eb("Whether the sending domain passed the fresh verification check."),message:T("Verification result summary.")},get_integration_guide:{guide:P("integration guide"),code:T("Generated integration code or example."),steps:{type:"array",description:"Setup steps for the requested integration.",items:r("One setup step.")}},add_subscriber:{subscriber:P("subscriber")},update_subscriber:{subscriber:P("subscriber")},remove_subscriber:{subscriber:P("subscriber"),hardDeleted:eb("Whether the subscriber was permanently deleted.")},get_subscriber:{subscriber:P("subscriber")},list_subscriber_notes:{notes:i("subscriber note")},add_subscriber_note:{note:P("subscriber note")},delete_subscriber_note:{id:T("Deleted subscriber note ID."),deleted:eb("Whether the subscriber note was deleted.")},search_subscribers:{subscribers:i("subscriber"),pagination:r("Pagination metadata."),returned:Vb("Number of subscribers returned."),truncated:eb("Whether the result was truncated by the requested limit.")},list_products:{products:i("product")},upsert_products:{products:i("product"),created:Vb("Number of products created."),updated:Vb("Number of products updated.")},delete_product:{productId:T("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:r("Ready-to-insert Sequenzy image block using the hosted asset URL.")},sync_products:{job:P("product sync job"),jobId:T("Queued product sync job ID.")},list_tags:{tags:i("tag")},create_tag:{tag:P("tag")},update_tag:{tag:P("tag")},delete_tag:{tagId:T("Deleted tag ID.")},list_lists:{lists:i("list")},create_list:{list:P("list")},update_list:{list:P("list")},delete_list:{listId:T("Deleted list ID.")},add_subscribers_to_list:{list:P("list"),added:Vb("Number of subscribers added to the list."),skipped:Vb("Number of subscribers skipped.")},remove_subscribers_from_list:{list:P("list"),removed:Vb("Number of subscribers removed from the list."),skipped:Vb("Number of subscribers skipped.")},list_segments:{segments:i("segment")},create_segment:{segment:P("segment")},update_segment:{segment:P("segment")},delete_segment:{segmentId:T("Deleted segment ID.")},get_segment_count:{count:Vb("Number of subscribers matching the segment."),segmentId:T("Segment ID that was counted.")},list_audience_syncs:{audienceSyncs:i("audience sync")},list_ad_accounts:{adAccounts:i("ad account")},create_audience_sync:{audienceSync:P("audience sync")},update_audience_sync:{audienceSync:P("audience sync")},delete_audience_sync:{audienceSyncId:T("Deleted audience sync ID.")},sync_audience_now:{audienceSync:P("audience sync"),job:P("audience sync job"),jobId:T("Queued audience sync job ID.")},list_templates:{templates:i("email template")},get_template:{template:P("email template")},create_template:{template:P("email template")},update_template:{template:P("email template")},delete_template:{templateId:T("Deleted template ID.")},list_ab_tests:{abTests:i("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:T("Deleted A/B test variant ID.")},delete_ab_test:{abTestId:T("Deleted A/B test ID.")},list_campaigns:{campaigns:i("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:T("Scheduled send timestamp.")},send_test_email:{emailSend:P("test email send"),recipient:T("Test email recipient.")},send_test_sms:{smsSendId:T("Created test SMS send ID."),toPhone:T("Normalized E.164 destination phone.")},cancel_campaign:{campaign:P("campaign")},pause_campaign:{campaign:P("campaign")},resume_campaign:{campaign:P("campaign")},delete_campaign:{campaignId:T("Deleted campaign ID.")},duplicate_campaign:{campaign:P("duplicated campaign")},resend_campaign_to_non_openers:{campaign:P("non-opener resend draft campaign"),estimatedNonOpenerCount:Vb("Estimated number of subscribers who haven't opened the original campaign.")},list_landing_pages:{landingPages:i("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:T("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:T("Connected landing page domain.")},update_landing_page_domain_settings:{landingPage:P("landing page"),domain:T("Landing page domain.")},list_sequences:{sequences:i("sequence")},get_sequence:{sequence:P("sequence")},create_sequence:{sequence:P("sequence"),eventTrackingCode:T("Ready-to-adapt code for sending a custom trigger event, including any matching-field property."),eventTracking:r("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:T("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:T("Inserted automation node ID.")},insertedEmailIds:{type:"array",description:"Email template IDs created for the inserted step.",items:T("Inserted email template ID.")},insertedEmailCount:Vb("Number of email steps inserted.")},enable_sequence:{sequence:P("sequence")},disable_sequence:{sequence:P("sequence")},pause_sequence_enrollments:{sequenceId:T("Sequence ID."),enrollmentPaused:eb("Whether new sequence enrollments are paused.")},resume_sequence_enrollments:{sequenceId:T("Sequence ID."),enrollmentPaused:eb("Whether new sequence enrollments are paused.")},enroll_subscribers_in_sequence:{sequence:P("sequence"),enrollments:i("sequence enrollment"),enrolled:Vb("Number of subscribers enrolled."),skipped:Vb("Number of subscribers skipped.")},cancel_sequence_enrollments:{sequence:P("sequence"),cancelled:Vb("Number of enrollments cancelled."),skipped:Vb("Number of enrollments skipped.")},delete_sequence:{sequenceId:T("Deleted sequence ID.")},list_transactional_emails:{transactional:i("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"),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:r("One poll or NPS results summary.")}},get_sequence_stats:{sequence:P("sequence"),stats:P("sequence statistics")},list_campaign_events:{events:i("campaign email event"),pagination:r("Pagination metadata.")},list_sequence_events:{events:i("sequence email event"),pagination:r("Pagination metadata.")},get_subscriber_activity:{activity:i("subscriber activity event"),subscribers:i("subscriber"),pagination:r("Pagination metadata.")},list_team_members:{members:i("team member"),invitations:i("team invitation")},invite_team_member:{invitation:P("team invitation")},cancel_team_invitation:{invitationId:T("Cancelled invitation ID.")},list_conversations:{conversations:i("inbox conversation"),pagination:r("Pagination metadata.")},get_conversation:{conversation:P("inbox conversation"),messages:i("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:i("outbound webhook")},create_webhook:{webhook:P("outbound webhook")},update_webhook:{webhook:P("outbound webhook")},delete_webhook:{webhookId:T("Deleted outbound webhook ID.")},test_webhook:{webhook:P("outbound webhook"),delivery:P("test webhook delivery")},list_webhook_deliveries:{deliveries:i("webhook delivery")},replay_webhook_delivery:{delivery:P("webhook delivery"),job:P("webhook replay job")},generate_email:{email:P("generated email"),html:T("Generated HTML email body."),blocks:{type:"array",description:"Generated Sequenzy email blocks, wrapped with company branding (logo + footer) unless applyBranding was false.",items:r("One generated email block.")},subject:T("Generated subject line."),previewText:T("Generated inbox preview text.")},generate_sequence:{sequence:P("generated sequence"),steps:i("generated sequence step")},generate_subject_lines:{subjectLines:{type:"array",description:"Generated subject line variants.",items:T("One generated subject line.")},variants:i("generated subject line variant")},generate_sms:{prompt:T("The prompt the messages were generated for."),messages:{type:"array",description:"Generated SMS message variants with encoding and segment counts.",items:r("One generated SMS message.")}},get_sms_settings:{sms:r("SMS add-on status: enabled, planEligible, creditsBalance, brandPrefix, numbers, readyToSend (paid plan or credits plus an active number).")},submit_feedback:{}};function jM(b){let w=IM[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:{...ZM,...w,...NW.has(b)?MM:{}},additionalProperties:!0}}function sD(b){return{...b,outputSchema:jM(b.name)}}function aD(b){if(y(b))return b;if(Array.isArray(b))return{items:b};return{value:b}}var bz=[{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 wz=[{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
+ `)}q.write("payload.value = newResult;"),q.write("return payload;");let k=q.compile();return(S,h)=>k(O,S,h)},G,X=Sw,Y=!O0.jitless,J=Y&&b4.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 f9([],B,O,q,z,b)}return $(O,q)}});function w9(b,w,$,W){for(let G of b)if(G.issues.length===0)return w.value=G.value,w;let Q=b.filter((G)=>!Fw(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 A4=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 w9(Y,Q,b,G);return Promise.all(Y).then((H)=>{return w9(H,Q,b,G)})}}),g9=U("$ZodDiscriminatedUnion",(b,w)=>{A4.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(!Sw(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}}),m9=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 $9($,H,J)});return $9($,G,X)}});function D4(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(Bw(b)&&Bw(w)){let $=Object.keys(w),W=Object.keys(b).filter((G)=>$.indexOf(G)!==-1),Q={...b,...w};for(let G of W){let X=D4(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=D4(Q,G);if(!X.valid)return{valid:!1,mergeErrorPath:[W,...X.mergeErrorPath]};$.push(X.data)}return{valid:!0,data:$}}return{valid:!1,mergeErrorPath:[]}}function $9(b,w,$){if(w.issues.length)b.issues.push(...w.issues);if($.issues.length)b.issues.push(...$.issues);if(Fw(b))return b;let W=D4(w.value,$.value);if(!W.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(W.mergeErrorPath)}`);return b.value=W.data,b}var n9=U("$ZodRecord",(b,w)=>{e.init(b,w),b._zod.parse=($,W)=>{let Q=$.value;if(!Bw(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 l9=U("$ZodEnum",(b,w)=>{e.init(b,w);let $=s$(w.entries),W=new Set($);b._zod.values=W,b._zod.pattern=new RegExp(`^(${$.filter((Q)=>w4.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}}),i9=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 p9=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 W9(b,w){if(b.issues.length&&w===void 0)return{issues:[],value:void 0};return b}var o9=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)=>W9(G,$.value));return W9(Q,$.value)}if($.value===void 0)return $;return w.innerType._zod.run($,W)}}),d9=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)}}),t9=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)=>Q9(G,w));return Q9(Q,w)}});function Q9(b,w){if(b.value===void 0)b.value=w.defaultValue;return b}var r9=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)}}),e9=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)=>G9(G,b));return G9(Q,b)}});function G9(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 s9=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 a9=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)=>I0(X,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 b8=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(X9);return X9(Q)}});function X9(b){return b.value=Object.freeze(b.value),b}var w8=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)=>Y9(G,$,W,b));Y9(Q,$,W,b);return}});function Y9(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 S7=(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},R7=()=>{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 ${S7(W.input)}`;case"invalid_value":if(W.values.length===1)return`Invalid input: expected ${B0(W.values[0])}`;return`Invalid option: expected one of ${q0(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":""}: ${q0(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 O4(){return{localeError:R7()}}var oM=Symbol("ZodOutput"),dM=Symbol("ZodInput");class $8{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 k7(){return new $8}var M1=k7();function W8(b,w){return new b({type:"string",..._(w)})}function Q8(b,w){return new b({type:"string",format:"email",check:"string_format",abort:!1,..._(w)})}function q4(b,w){return new b({type:"string",format:"guid",check:"string_format",abort:!1,..._(w)})}function G8(b,w){return new b({type:"string",format:"uuid",check:"string_format",abort:!1,..._(w)})}function X8(b,w){return new b({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",..._(w)})}function Y8(b,w){return new b({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",..._(w)})}function H8(b,w){return new b({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",..._(w)})}function J8(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 z8(b,w){return new b({type:"string",format:"nanoid",check:"string_format",abort:!1,..._(w)})}function A8(b,w){return new b({type:"string",format:"cuid",check:"string_format",abort:!1,..._(w)})}function O8(b,w){return new b({type:"string",format:"cuid2",check:"string_format",abort:!1,..._(w)})}function q8(b,w){return new b({type:"string",format:"ulid",check:"string_format",abort:!1,..._(w)})}function L8(b,w){return new b({type:"string",format:"xid",check:"string_format",abort:!1,..._(w)})}function U8(b,w){return new b({type:"string",format:"ksuid",check:"string_format",abort:!1,..._(w)})}function B8(b,w){return new b({type:"string",format:"ipv4",check:"string_format",abort:!1,..._(w)})}function F8(b,w){return new b({type:"string",format:"ipv6",check:"string_format",abort:!1,..._(w)})}function K8(b,w){return new b({type:"string",format:"cidrv4",check:"string_format",abort:!1,..._(w)})}function P8(b,w){return new b({type:"string",format:"cidrv6",check:"string_format",abort:!1,..._(w)})}function M8(b,w){return new b({type:"string",format:"base64",check:"string_format",abort:!1,..._(w)})}function Z8(b,w){return new b({type:"string",format:"base64url",check:"string_format",abort:!1,..._(w)})}function I8(b,w){return new b({type:"string",format:"e164",check:"string_format",abort:!1,..._(w)})}function j8(b,w){return new b({type:"string",format:"jwt",check:"string_format",abort:!1,..._(w)})}function V8(b,w){return new b({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,..._(w)})}function N8(b,w){return new b({type:"string",format:"date",check:"string_format",..._(w)})}function E8(b,w){return new b({type:"string",format:"time",check:"string_format",precision:null,..._(w)})}function T8(b,w){return new b({type:"string",format:"duration",check:"string_format",..._(w)})}function _8(b,w){return new b({type:"number",checks:[],..._(w)})}function S8(b,w){return new b({type:"number",check:"number_format",abort:!1,format:"safeint",..._(w)})}function R8(b,w){return new b({type:"boolean",..._(w)})}function k8(b,w){return new b({type:"null",..._(w)})}function v8(b){return new b({type:"unknown"})}function C8(b,w){return new b({type:"never",..._(w)})}function N0(b,w){return new Y4({check:"less_than",..._(w),value:b,inclusive:!1})}function Z1(b,w){return new Y4({check:"less_than",..._(w),value:b,inclusive:!0})}function E0(b,w){return new H4({check:"greater_than",..._(w),value:b,inclusive:!1})}function I1(b,w){return new H4({check:"greater_than",..._(w),value:b,inclusive:!0})}function T0(b,w){return new cQ({check:"multiple_of",..._(w),value:b})}function _0(b,w){return new mQ({check:"max_length",..._(w),maximum:b})}function gw(b,w){return new nQ({check:"min_length",..._(w),minimum:b})}function S0(b,w){return new lQ({check:"length_equals",..._(w),length:b})}function L4(b,w){return new iQ({check:"string_format",format:"regex",..._(w),pattern:b})}function U4(b){return new pQ({check:"string_format",format:"lowercase",..._(b)})}function B4(b){return new oQ({check:"string_format",format:"uppercase",..._(b)})}function F4(b,w){return new dQ({check:"string_format",format:"includes",..._(w),includes:b})}function K4(b,w){return new tQ({check:"string_format",format:"starts_with",..._(w),prefix:b})}function P4(b,w){return new rQ({check:"string_format",format:"ends_with",..._(w),suffix:b})}function Rw(b){return new eQ({check:"overwrite",tx:b})}function M4(b){return Rw((w)=>w.normalize(b))}function Z4(){return Rw((b)=>b.trim())}function I4(){return Rw((b)=>b.toLowerCase())}function j4(){return Rw((b)=>b.toUpperCase())}function x8(b,w,$){return new b({type:"array",element:w,..._($)})}function u8(b,w,$){let W=_($);return W.abort??(W.abort=!0),new b({type:"custom",check:"custom",fn:w,...W})}function y8(b,w,$){return new b({type:"custom",check:"custom",fn:w,..._($)})}function h8(b){let w=v7(($)=>{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 v7(b,w){let $=new Jb({check:"custom",..._(w)});return $._zod.check=b,$}function mw(b){return!!b._zod}function Kw(b,w){if(mw(b))return F1(b,w);return b.safeParse(w)}function R0(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 f8(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={};xW(V1,{time:()=>E4,duration:()=>T4,datetime:()=>V4,date:()=>N4,ZodISOTime:()=>m8,ZodISODuration:()=>n8,ZodISODateTime:()=>c8,ZodISODate:()=>g8});var c8=U("ZodISODateTime",(b,w)=>{K9.init(b,w),bb.init(b,w)});function V4(b){return V8(c8,b)}var g8=U("ZodISODate",(b,w)=>{P9.init(b,w),bb.init(b,w)});function N4(b){return N8(g8,b)}var m8=U("ZodISOTime",(b,w)=>{M9.init(b,w),bb.init(b,w)});function E4(b){return E8(m8,b)}var n8=U("ZodISODuration",(b,w)=>{Z9.init(b,w),bb.init(b,w)});function T4(b){return T8(n8,b)}var l8=(b,w)=>{F0.init(b,w),b.name="ZodError",Object.defineProperties(b,{format:{value:($)=>wQ(b,$)},flatten:{value:($)=>bQ(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}}})},vZ=U("ZodError",l8),Eb=U("ZodError",l8,{Parent:Error});var i8=K0(Eb),p8=P0(Eb),o8=B1(Eb),d8=K1(Eb),t8=$Q(Eb),r8=WQ(Eb),e8=QQ(Eb),s8=GQ(Eb),a8=XQ(Eb),bG=YQ(Eb),wG=HQ(Eb),$G=JQ(Eb);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)=>i8(b,$,W,{callee:b.parse}),b.safeParse=($,W)=>o8(b,$,W),b.parseAsync=async($,W)=>p8(b,$,W,{callee:b.parseAsync}),b.safeParseAsync=async($,W)=>d8(b,$,W),b.spa=b.safeParseAsync,b.encode=($,W)=>t8(b,$,W),b.decode=($,W)=>r8(b,$,W),b.encodeAsync=async($,W)=>e8(b,$,W),b.decodeAsync=async($,W)=>s8(b,$,W),b.safeEncode=($,W)=>a8(b,$,W),b.safeDecode=($,W)=>bG(b,$,W),b.safeEncodeAsync=async($,W)=>wG(b,$,W),b.safeDecodeAsync=async($,W)=>$G(b,$,W),b.refine=($,W)=>b.check(_5($,W)),b.superRefine=($)=>b.check(S5($)),b.overwrite=($)=>b.check(Rw($)),b.optional=()=>Wb(b),b.nullable=()=>GG(b),b.nullish=()=>Wb(GG(b)),b.nonoptional=($)=>I5(b,$),b.array=()=>f(b),b.or=($)=>r([b,$]),b.and=($)=>v0(b,$),b.transform=($)=>S4(b,DG($)),b.default=($)=>P5(b,$),b.prefault=($)=>Z5(b,$),b.catch=($)=>V5(b,$),b.pipe=($)=>S4(b,$),b.readonly=()=>T5(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}),XG=U("_ZodString",(b,w)=>{V0.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(L4(...W)),b.includes=(...W)=>b.check(F4(...W)),b.startsWith=(...W)=>b.check(K4(...W)),b.endsWith=(...W)=>b.check(P4(...W)),b.min=(...W)=>b.check(gw(...W)),b.max=(...W)=>b.check(_0(...W)),b.length=(...W)=>b.check(S0(...W)),b.nonempty=(...W)=>b.check(gw(1,...W)),b.lowercase=(W)=>b.check(U4(W)),b.uppercase=(W)=>b.check(B4(W)),b.trim=()=>b.check(Z4()),b.normalize=(...W)=>b.check(M4(...W)),b.toLowerCase=()=>b.check(I4()),b.toUpperCase=()=>b.check(j4())}),m7=U("ZodString",(b,w)=>{V0.init(b,w),XG.init(b,w),b.email=($)=>b.check(Q8(n7,$)),b.url=($)=>b.check(J8(l7,$)),b.jwt=($)=>b.check(j8(G5,$)),b.emoji=($)=>b.check(D8(i7,$)),b.guid=($)=>b.check(q4(WG,$)),b.uuid=($)=>b.check(G8(k0,$)),b.uuidv4=($)=>b.check(X8(k0,$)),b.uuidv6=($)=>b.check(Y8(k0,$)),b.uuidv7=($)=>b.check(H8(k0,$)),b.nanoid=($)=>b.check(z8(p7,$)),b.guid=($)=>b.check(q4(WG,$)),b.cuid=($)=>b.check(A8(o7,$)),b.cuid2=($)=>b.check(O8(d7,$)),b.ulid=($)=>b.check(q8(t7,$)),b.base64=($)=>b.check(M8($5,$)),b.base64url=($)=>b.check(Z8(W5,$)),b.xid=($)=>b.check(L8(r7,$)),b.ksuid=($)=>b.check(U8(e7,$)),b.ipv4=($)=>b.check(B8(s7,$)),b.ipv6=($)=>b.check(F8(a7,$)),b.cidrv4=($)=>b.check(K8(b5,$)),b.cidrv6=($)=>b.check(P8(w5,$)),b.e164=($)=>b.check(I8(Q5,$)),b.datetime=($)=>b.check(V4($)),b.date=($)=>b.check(N4($)),b.time=($)=>b.check(E4($)),b.duration=($)=>b.check(T4($))});function L(b){return W8(m7,b)}var bb=U("ZodStringFormat",(b,w)=>{s.init(b,w),XG.init(b,w)}),n7=U("ZodEmail",(b,w)=>{D9.init(b,w),bb.init(b,w)});var WG=U("ZodGUID",(b,w)=>{H9.init(b,w),bb.init(b,w)});var k0=U("ZodUUID",(b,w)=>{J9.init(b,w),bb.init(b,w)});var l7=U("ZodURL",(b,w)=>{z9.init(b,w),bb.init(b,w)});var i7=U("ZodEmoji",(b,w)=>{A9.init(b,w),bb.init(b,w)});var p7=U("ZodNanoID",(b,w)=>{O9.init(b,w),bb.init(b,w)});var o7=U("ZodCUID",(b,w)=>{q9.init(b,w),bb.init(b,w)});var d7=U("ZodCUID2",(b,w)=>{L9.init(b,w),bb.init(b,w)});var t7=U("ZodULID",(b,w)=>{U9.init(b,w),bb.init(b,w)});var r7=U("ZodXID",(b,w)=>{B9.init(b,w),bb.init(b,w)});var e7=U("ZodKSUID",(b,w)=>{F9.init(b,w),bb.init(b,w)});var s7=U("ZodIPv4",(b,w)=>{I9.init(b,w),bb.init(b,w)});var a7=U("ZodIPv6",(b,w)=>{j9.init(b,w),bb.init(b,w)});var b5=U("ZodCIDRv4",(b,w)=>{V9.init(b,w),bb.init(b,w)});var w5=U("ZodCIDRv6",(b,w)=>{N9.init(b,w),bb.init(b,w)});var $5=U("ZodBase64",(b,w)=>{T9.init(b,w),bb.init(b,w)});var W5=U("ZodBase64URL",(b,w)=>{_9.init(b,w),bb.init(b,w)});var Q5=U("ZodE164",(b,w)=>{S9.init(b,w),bb.init(b,w)});var G5=U("ZodJWT",(b,w)=>{R9.init(b,w),bb.init(b,w)});var YG=U("ZodNumber",(b,w)=>{z4.init(b,w),Qb.init(b,w),b.gt=(W,Q)=>b.check(E0(W,Q)),b.gte=(W,Q)=>b.check(I1(W,Q)),b.min=(W,Q)=>b.check(I1(W,Q)),b.lt=(W,Q)=>b.check(N0(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(QG(W)),b.safe=(W)=>b.check(QG(W)),b.positive=(W)=>b.check(E0(0,W)),b.nonnegative=(W)=>b.check(I1(0,W)),b.negative=(W)=>b.check(N0(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 p(b){return _8(YG,b)}var X5=U("ZodNumberFormat",(b,w)=>{k9.init(b,w),YG.init(b,w)});function QG(b){return S8(X5,b)}var Y5=U("ZodBoolean",(b,w)=>{v9.init(b,w),Qb.init(b,w)});function Hb(b){return R8(Y5,b)}var H5=U("ZodNull",(b,w)=>{C9.init(b,w),Qb.init(b,w)});function R4(b){return k8(H5,b)}var J5=U("ZodUnknown",(b,w)=>{x9.init(b,w),Qb.init(b,w)});function wb(){return v8(J5)}var D5=U("ZodNever",(b,w)=>{u9.init(b,w),Qb.init(b,w)});function z5(b){return C8(D5,b)}var A5=U("ZodArray",(b,w)=>{y9.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(_0($,W)),b.length=($,W)=>b.check(S0($,W)),b.unwrap=()=>b.element});function f(b,w){return x8(A5,b,w)}var HG=U("ZodObject",(b,w)=>{c9.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:z5()}),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(zG,b,$[0]),b.required=(...$)=>n.required(AG,b,$[0])});function V(b,w){let $={type:"object",shape:b??{},...n.normalizeParams(w)};return new HG($)}function Ub(b,w){return new HG({type:"object",shape:b,catchall:wb(),...n.normalizeParams(w)})}var JG=U("ZodUnion",(b,w)=>{A4.init(b,w),Qb.init(b,w),b.options=w.options});function r(b,w){return new JG({type:"union",options:b,...n.normalizeParams(w)})}var O5=U("ZodDiscriminatedUnion",(b,w)=>{JG.init(b,w),g9.init(b,w)});function k4(b,w,$){return new O5({type:"union",options:w,discriminator:b,...n.normalizeParams($)})}var q5=U("ZodIntersection",(b,w)=>{m9.init(b,w),Qb.init(b,w)});function v0(b,w){return new q5({type:"intersection",left:b,right:w})}var L5=U("ZodRecord",(b,w)=>{n9.init(b,w),Qb.init(b,w),b.keyType=w.keyType,b.valueType=w.valueType});function $b(b,w,$){return new L5({type:"record",keyType:b,valueType:w,...n.normalizeParams($)})}var _4=U("ZodEnum",(b,w)=>{l9.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 _4({...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 _4({...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 _4({type:"enum",entries:$,...n.normalizeParams(w)})}var U5=U("ZodLiteral",(b,w)=>{i9.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 N(b,w){return new U5({type:"literal",values:Array.isArray(b)?b:[b],...n.normalizeParams(w)})}var B5=U("ZodTransform",(b,w)=>{p9.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 DG(b){return new B5({type:"transform",transform:b})}var zG=U("ZodOptional",(b,w)=>{o9.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType});function Wb(b){return new zG({type:"optional",innerType:b})}var F5=U("ZodNullable",(b,w)=>{d9.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType});function GG(b){return new F5({type:"nullable",innerType:b})}var K5=U("ZodDefault",(b,w)=>{t9.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType,b.removeDefault=b.unwrap});function P5(b,w){return new K5({type:"default",innerType:b,get defaultValue(){return typeof w==="function"?w():n.shallowClone(w)}})}var M5=U("ZodPrefault",(b,w)=>{r9.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType});function Z5(b,w){return new M5({type:"prefault",innerType:b,get defaultValue(){return typeof w==="function"?w():n.shallowClone(w)}})}var AG=U("ZodNonOptional",(b,w)=>{e9.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType});function I5(b,w){return new AG({type:"nonoptional",innerType:b,...n.normalizeParams(w)})}var j5=U("ZodCatch",(b,w)=>{s9.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType,b.removeCatch=b.unwrap});function V5(b,w){return new j5({type:"catch",innerType:b,catchValue:typeof w==="function"?w:()=>w})}var N5=U("ZodPipe",(b,w)=>{a9.init(b,w),Qb.init(b,w),b.in=w.in,b.out=w.out});function S4(b,w){return new N5({type:"pipe",in:b,out:w})}var E5=U("ZodReadonly",(b,w)=>{b8.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType});function T5(b){return new E5({type:"readonly",innerType:b})}var OG=U("ZodCustom",(b,w)=>{w8.init(b,w),Qb.init(b,w)});function qG(b,w){return u8(OG,b??(()=>!0),w)}function _5(b,w={}){return y8(OG,b,w)}function S5(b){return h8(b)}function v4(b,w){return S4(DG(b),w)}Sb(O4());var C4="2025-11-25";var LG=[C4,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Pw="io.modelcontextprotocol/related-task",x0="2.0",Db=qG((b)=>b!==null&&(typeof b==="object"||typeof b==="function")),UG=r([L(),p().int()]),BG=L(),TI=Ub({ttl:r([p(),R4()]).optional(),pollInterval:p().optional()}),R5=V({ttl:p().optional()}),k5=V({taskId:L()}),x4=Ub({progressToken:UG.optional(),[Pw]:k5.optional()}),Tb=V({_meta:x4.optional()}),N1=Tb.extend({task:R5.optional()}),FG=(b)=>N1.safeParse(b).success,zb=V({method:L(),params:Tb.loose().optional()}),Rb=V({_meta:x4.optional()}),kb=V({method:L(),params:Rb.loose().optional()}),Ab=Ub({_meta:x4.optional()}),u0=r([L(),p().int()]),KG=V({jsonrpc:N(x0),id:u0,...zb.shape}).strict(),u4=(b)=>KG.safeParse(b).success,PG=V({jsonrpc:N(x0),...kb.shape}).strict(),MG=(b)=>PG.safeParse(b).success,y4=V({jsonrpc:N(x0),id:u0,result:Ab}).strict(),E1=(b)=>y4.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 h4=V({jsonrpc:N(x0),id:u0.optional(),error:V({code:p().int(),message:L(),data:wb().optional()})}).strict();var ZG=(b)=>h4.safeParse(b).success;var IG=r([KG,PG,y4,h4]),_I=r([y4,h4]),y0=Ab.strict(),v5=Rb.extend({requestId:u0.optional(),reason:L().optional()}),h0=kb.extend({method:N("notifications/cancelled"),params:v5}),C5=V({src:L(),mimeType:L().optional(),sizes:f(L()).optional(),theme:Pb(["light","dark"]).optional()}),T1=V({icons:f(C5).optional()}),nw=V({name:L(),title:L().optional()}),jG=nw.extend({...nw.shape,...T1.shape,version:L(),websiteUrl:L().optional(),description:L().optional()}),x5=v0(V({applyDefaults:Hb().optional()}),$b(L(),wb())),u5=v4((b)=>{if(b&&typeof b==="object"&&!Array.isArray(b)){if(Object.keys(b).length===0)return{form:{}}}return b},v0(V({form:x5.optional(),url:Db.optional()}),$b(L(),wb()).optional())),y5=Ub({list:Db.optional(),cancel:Db.optional(),requests:Ub({sampling:Ub({createMessage:Db.optional()}).optional(),elicitation:Ub({create:Db.optional()}).optional()}).optional()}),h5=Ub({list:Db.optional(),cancel:Db.optional(),requests:Ub({tools:Ub({call:Db.optional()}).optional()}).optional()}),f5=V({experimental:$b(L(),Db).optional(),sampling:V({context:Db.optional(),tools:Db.optional()}).optional(),elicitation:u5.optional(),roots:V({listChanged:Hb().optional()}).optional(),tasks:y5.optional()}),c5=Tb.extend({protocolVersion:L(),capabilities:f5,clientInfo:jG}),f4=zb.extend({method:N("initialize"),params:c5});var g5=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:h5.optional()}),m5=Ab.extend({protocolVersion:L(),capabilities:g5,serverInfo:jG,instructions:L().optional()}),c4=kb.extend({method:N("notifications/initialized"),params:Rb.optional()});var f0=zb.extend({method:N("ping"),params:Tb.optional()}),n5=V({progress:p(),total:Wb(p()),message:Wb(L())}),l5=V({...Rb.shape,...n5.shape,progressToken:UG}),c0=kb.extend({method:N("notifications/progress"),params:l5}),i5=Tb.extend({cursor:BG.optional()}),_1=zb.extend({params:i5.optional()}),S1=Ab.extend({nextCursor:BG.optional()}),p5=Pb(["working","input_required","completed","failed","cancelled"]),R1=V({taskId:L(),status:p5,ttl:r([p(),R4()]),createdAt:L(),lastUpdatedAt:L(),pollInterval:Wb(p()),statusMessage:Wb(L())}),lw=Ab.extend({task:R1}),o5=Rb.merge(R1),k1=kb.extend({method:N("notifications/tasks/status"),params:o5}),g0=zb.extend({method:N("tasks/get"),params:Tb.extend({taskId:L()})}),m0=Ab.merge(R1),n0=zb.extend({method:N("tasks/result"),params:Tb.extend({taskId:L()})}),SI=Ab.loose(),l0=_1.extend({method:N("tasks/list")}),i0=S1.extend({tasks:f(R1)}),p0=zb.extend({method:N("tasks/cancel"),params:Tb.extend({taskId:L()})}),VG=Ab.merge(R1),NG=V({uri:L(),mimeType:Wb(L()),_meta:$b(L(),wb()).optional()}),EG=NG.extend({text:L()}),g4=L().refine((b)=>{try{return atob(b),!0}catch{return!1}},{message:"Invalid Base64 string"}),TG=NG.extend({blob:g4}),v1=Pb(["user","assistant"]),iw=V({audience:f(v1).optional(),priority:p().min(0).max(1).optional(),lastModified:V1.datetime({offset:!0}).optional()}),_G=V({...nw.shape,...T1.shape,uri:L(),description:Wb(L()),mimeType:Wb(L()),annotations:iw.optional(),_meta:Wb(Ub({}))}),d5=V({...nw.shape,...T1.shape,uriTemplate:L(),description:Wb(L()),mimeType:Wb(L()),annotations:iw.optional(),_meta:Wb(Ub({}))}),m4=_1.extend({method:N("resources/list")}),t5=S1.extend({resources:f(_G)}),r5=_1.extend({method:N("resources/templates/list")}),e5=S1.extend({resourceTemplates:f(d5)}),n4=Tb.extend({uri:L()}),s5=n4,l4=zb.extend({method:N("resources/read"),params:s5}),a5=Ab.extend({contents:f(r([EG,TG]))}),bA=kb.extend({method:N("notifications/resources/list_changed"),params:Rb.optional()}),wA=n4,$A=zb.extend({method:N("resources/subscribe"),params:wA}),WA=n4,QA=zb.extend({method:N("resources/unsubscribe"),params:WA}),GA=Rb.extend({uri:L()}),XA=kb.extend({method:N("notifications/resources/updated"),params:GA}),YA=V({name:L(),description:Wb(L()),required:Wb(Hb())}),HA=V({...nw.shape,...T1.shape,description:Wb(L()),arguments:Wb(f(YA)),_meta:Wb(Ub({}))}),JA=_1.extend({method:N("prompts/list")}),DA=S1.extend({prompts:f(HA)}),zA=Tb.extend({name:L(),arguments:$b(L(),L()).optional()}),AA=zb.extend({method:N("prompts/get"),params:zA}),i4=V({type:N("text"),text:L(),annotations:iw.optional(),_meta:$b(L(),wb()).optional()}),p4=V({type:N("image"),data:g4,mimeType:L(),annotations:iw.optional(),_meta:$b(L(),wb()).optional()}),o4=V({type:N("audio"),data:g4,mimeType:L(),annotations:iw.optional(),_meta:$b(L(),wb()).optional()}),OA=V({type:N("tool_use"),name:L(),id:L(),input:$b(L(),wb()),_meta:$b(L(),wb()).optional()}),qA=V({type:N("resource"),resource:r([EG,TG]),annotations:iw.optional(),_meta:$b(L(),wb()).optional()}),LA=_G.extend({type:N("resource_link")}),d4=r([i4,p4,o4,LA,qA]),UA=V({role:v1,content:d4}),BA=Ab.extend({description:L().optional(),messages:f(UA)}),FA=kb.extend({method:N("notifications/prompts/list_changed"),params:Rb.optional()}),KA=V({title:L().optional(),readOnlyHint:Hb().optional(),destructiveHint:Hb().optional(),idempotentHint:Hb().optional(),openWorldHint:Hb().optional()}),PA=V({taskSupport:Pb(["required","optional","forbidden"]).optional()}),SG=V({...nw.shape,...T1.shape,description:L().optional(),inputSchema:V({type:N("object"),properties:$b(L(),Db).optional(),required:f(L()).optional()}).catchall(wb()),outputSchema:V({type:N("object"),properties:$b(L(),Db).optional(),required:f(L()).optional()}).catchall(wb()).optional(),annotations:KA.optional(),execution:PA.optional(),_meta:$b(L(),wb()).optional()}),t4=_1.extend({method:N("tools/list")}),MA=S1.extend({tools:f(SG)}),o0=Ab.extend({content:f(d4).default([]),structuredContent:$b(L(),wb()).optional(),isError:Hb().optional()}),RI=o0.or(Ab.extend({toolResult:wb()})),ZA=N1.extend({name:L(),arguments:$b(L(),wb()).optional()}),C1=zb.extend({method:N("tools/call"),params:ZA}),IA=kb.extend({method:N("notifications/tools/list_changed"),params:Rb.optional()}),kI=V({autoRefresh:Hb().default(!0),debounceMs:p().int().nonnegative().default(300)}),x1=Pb(["debug","info","notice","warning","error","critical","alert","emergency"]),jA=Tb.extend({level:x1}),r4=zb.extend({method:N("logging/setLevel"),params:jA}),VA=Rb.extend({level:x1,logger:L().optional(),data:wb()}),NA=kb.extend({method:N("notifications/message"),params:VA}),EA=V({name:L().optional()}),TA=V({hints:f(EA).optional(),costPriority:p().min(0).max(1).optional(),speedPriority:p().min(0).max(1).optional(),intelligencePriority:p().min(0).max(1).optional()}),_A=V({mode:Pb(["auto","required","none"]).optional()}),SA=V({type:N("tool_result"),toolUseId:L().describe("The unique identifier for the corresponding tool call."),content:f(d4).default([]),structuredContent:V({}).loose().optional(),isError:Hb().optional(),_meta:$b(L(),wb()).optional()}),RA=k4("type",[i4,p4,o4]),C0=k4("type",[i4,p4,o4,OA,SA]),kA=V({role:v1,content:r([C0,f(C0)]),_meta:$b(L(),wb()).optional()}),vA=N1.extend({messages:f(kA),modelPreferences:TA.optional(),systemPrompt:L().optional(),includeContext:Pb(["none","thisServer","allServers"]).optional(),temperature:p().optional(),maxTokens:p().int(),stopSequences:f(L()).optional(),metadata:Db.optional(),tools:f(SG).optional(),toolChoice:_A.optional()}),CA=zb.extend({method:N("sampling/createMessage"),params:vA}),e4=Ab.extend({model:L(),stopReason:Wb(Pb(["endTurn","stopSequence","maxTokens"]).or(L())),role:v1,content:RA}),s4=Ab.extend({model:L(),stopReason:Wb(Pb(["endTurn","stopSequence","maxTokens","toolUse"]).or(L())),role:v1,content:r([C0,f(C0)])}),xA=V({type:N("boolean"),title:L().optional(),description:L().optional(),default:Hb().optional()}),uA=V({type:N("string"),title:L().optional(),description:L().optional(),minLength:p().optional(),maxLength:p().optional(),format:Pb(["email","uri","date","date-time"]).optional(),default:L().optional()}),yA=V({type:Pb(["number","integer"]),title:L().optional(),description:L().optional(),minimum:p().optional(),maximum:p().optional(),default:p().optional()}),hA=V({type:N("string"),title:L().optional(),description:L().optional(),enum:f(L()),default:L().optional()}),fA=V({type:N("string"),title:L().optional(),description:L().optional(),oneOf:f(V({const:L(),title:L()})),default:L().optional()}),cA=V({type:N("string"),title:L().optional(),description:L().optional(),enum:f(L()),enumNames:f(L()).optional(),default:L().optional()}),gA=r([hA,fA]),mA=V({type:N("array"),title:L().optional(),description:L().optional(),minItems:p().optional(),maxItems:p().optional(),items:V({type:N("string"),enum:f(L())}),default:f(L()).optional()}),nA=V({type:N("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()}),lA=r([mA,nA]),iA=r([cA,gA,lA]),pA=r([iA,xA,uA,yA]),oA=N1.extend({mode:N("form").optional(),message:L(),requestedSchema:V({type:N("object"),properties:$b(L(),pA),required:f(L()).optional()})}),dA=N1.extend({mode:N("url"),message:L(),elicitationId:L(),url:L().url()}),tA=r([oA,dA]),rA=zb.extend({method:N("elicitation/create"),params:tA}),eA=Rb.extend({elicitationId:L()}),sA=kb.extend({method:N("notifications/elicitation/complete"),params:eA}),d0=Ab.extend({action:Pb(["accept","decline","cancel"]),content:v4((b)=>b===null?void 0:b,$b(L(),r([L(),p(),Hb(),f(L())])).optional())}),aA=V({type:N("ref/resource"),uri:L()});var bO=V({type:N("ref/prompt"),name:L()}),wO=Tb.extend({ref:r([bO,aA]),argument:V({name:L(),value:L()}),context:V({arguments:$b(L(),L()).optional()}).optional()}),$O=zb.extend({method:N("completion/complete"),params:wO});var WO=Ab.extend({completion:Ub({values:f(L()).max(100),total:Wb(p().int()),hasMore:Wb(Hb())})}),QO=V({uri:L().startsWith("file://"),name:L().optional(),_meta:$b(L(),wb()).optional()}),GO=zb.extend({method:N("roots/list"),params:Tb.optional()}),a4=Ab.extend({roots:f(QO)}),XO=kb.extend({method:N("notifications/roots/list_changed"),params:Rb.optional()}),vI=r([f0,f4,$O,r4,AA,JA,m4,r5,l4,$A,QA,C1,t4,g0,n0,l0,p0]),CI=r([h0,c0,c4,XO,k1]),xI=r([y0,e4,s4,d0,a4,m0,i0,lw]),uI=r([f0,CA,rA,GO,g0,n0,l0,p0]),yI=r([h0,c0,NA,XA,bA,IA,FA,k1,sA]),hI=r([y0,m5,WO,BA,DA,t5,e5,a5,o0,MA,m0,i0,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 RG(W.elicitations,w)}return new x(b,w,$)}}class RG 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 Mw(b){return b==="completed"||b==="failed"||b==="cancelled"}var YO=Symbol("Let zodToJsonSchema decide on which parser to use");var Bj=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function b6(b){let $=R0(b)?.method;if(!$)throw Error("Schema is missing a method literal");let W=f8($);if(typeof W!=="string")throw Error("Schema method literal must be a string");return W}function w6(b,w){let $=Kw(b,w);if(!$.success)throw $.error;return $.data}var OO=60000;class $6{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(h0,(w)=>{this._oncancel(w)}),this.setNotificationHandler(c0,(w)=>{this._onprogress(w)}),this.setRequestHandler(f0,(w)=>({})),this._taskStore=b?.taskStore,this._taskMessageQueue=b?.taskMessageQueue,this._taskStore)this.setRequestHandler(g0,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(n0,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(!Mw(G.status))return await this._waitForTaskUpdate(Q,$.signal),await W();if(Mw(G.status)){let X=await this._taskStore.getTaskResult(Q,$.sessionId);return this._clearTaskQueue(Q),{...X,_meta:{...X._meta,[Pw]:{taskId:Q}}}}return await W()};return await W()}),this.setRequestHandler(l0,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(p0,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(Mw(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),E1(Q)||ZG(Q))this._onresponse(Q);else if(u4(Q))this._onrequest(Q,G);else if(MG(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?.[Pw]?.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=FG(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),E1(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(E1(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(E1(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},Mw(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||{},[Pw]: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=Kw(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??OO,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},m0,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},VG,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||{},[Pw]: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||{},[Pw]: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||{},[Pw]:w.relatedTask}}};await this._transport.send(G,w)}setRequestHandler(b,w){let $=b6(b);this.assertRequestHandlerCapability($),this._requestHandlers.set($,(W,Q)=>{let G=w6(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 $=b6(b);this._notificationHandlers.set($,(W)=>{let Q=w6(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 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),Mw(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(Mw(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),Mw(Y.status))this._cleanupTaskProgressHandler(W)}},listTasks:(W)=>{return $.listTasks(W,w)}}}}function kG(b){return b!==null&&typeof b==="object"&&!Array.isArray(b)}function vG(b,w){let $={...b};for(let W in w){let Q=W,G=w[Q];if(G===void 0)continue;let X=$[Q];if(kG(X)&&kG(G))$[Q]={...X,...G};else $[Q]=G}return $}var DD=CW(r6(),1),zD=CW(JD(),1);function ZP(){let b=new DD.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return zD.default(b),b}class XW{constructor(b){this._ajv=b??ZP()}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 YW{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 AD(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 OD(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 HW extends $6{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 XW,this.setRequestHandler(f4,($)=>this._oninitialize($)),this.setNotificationHandler(c4,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(r4,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 YW(this)};return this._experimental}registerCapabilities(b){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=vG(this._capabilities,b)}setRequestHandler(b,w){let W=R0(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=Kw(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=Kw(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=Kw(o0,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){OD(this._clientCapabilities?.tasks?.requests,b,"Client")}assertTaskHandlerCapability(b){if(!this._capabilities)return;AD(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:LG.includes(w)?w:C4,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"},y0)}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},s4,w);return this.request({method:"sampling/createMessage",params:b},e4,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},d0,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},d0,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},a4,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 qD={name:"@sequenzy/mcp",version:"0.0.109",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 JW=["product-info","domain","tracking","localization","integrations","products","events","tags","labels","goals","sync-rules","api-keys","widgets","team","danger"],LD={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 jP(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 rb(b){return encodeURIComponent(b)}function Xb(b,w){return`${b}${w}`}function Yb(b,w=""){return`/dashboard/company/${rb(b)}${w}`}function UD(b,w,$){return Xb(b,`${Yb(w,"/settings")}?tab=${encodeURIComponent($)}`)}function VP(b,w){let $=JW.map((W)=>[W,w?UD(b,w,W):""]);return Object.fromEntries($)}function Hw(b={},w){let $=jP(w),W=nb(b.companyId),Q={},G=VP($,W);if(!W)return{appUrl:$,routeTemplates:LD,settingsTabValues:JW,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/${rb(X)}`)),Q.campaignPreview=`${Q.campaign}?step=review`;let Y=nb(b.landingPageId);if(Y)Q.landingPage=Xb($,Yb(W,`/landing-pages/${rb(Y)}`));let H=nb(b.sequenceId);if(H)Q.sequence=Xb($,Yb(W,`/sequences/${rb(H)}`));let J=nb(b.emailId)??nb(b.templateId);if(J)Q.email=Xb($,Yb(W,`/emails/${rb(J)}`)),Q.template=Q.email;let D=nb(b.transactionalId);if(D)Q.transactionalEmail=Xb($,Yb(W,`/transactional/${rb(D)}`));let z=nb(b.emailSendId);if(z)Q.emailSend=Xb($,Yb(W,`/sent-emails/${rb(z)}`));let O=nb(b.domainId);if(O)Q.domain=Xb($,Yb(W,`/settings/domain/${rb(O)}`)),Q.domainVerify=`${Q.domain}/verify`;let q=nb(b.status);if(q)Q.campaignList=Xb($,Yb(W,`/campaign/list/${rb(q)}`)),Q.sequenceList=Xb($,Yb(W,`/sequences/list/${rb(q)}`));let B=nb(b.settingsTab);if(B)Q.settingsTab=UD($,W,B);return{appUrl:$,routeTemplates:LD,settingsTabValues:JW,urls:Q,settingsUrls:G}}var BD=[{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 FD(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=qw()??$.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:Ow(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 _w='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 the transactional send `variables` or an automation `event` payload, use { "id": "c1", "field": "variable", "operator": "is", "value": "plan:pro" } where the text before the colon is a {{merge tag}} path (nested paths like "order.total" or "event.plan" work) and the text after it is the comparison value. `field` may also be "attribute" (same "name:value" form) or "email"/"firstName"/"lastName" (the value is the plain comparison string). Operators: is, is_not, contains, not_contains, gt, gte, lt, lte, is_empty, is_not_empty. 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 the transactional send `variables` or an automation `event` payload, use { "id": "c1", "field": "variable", "operator": "is", "value": "plan:pro" } where the text before the colon is a {{merge tag}} path (nested paths like "order.total" or "event.plan" work) and the text after it is the comparison value. `field` may also be "attribute" (same "name:value" form) or "email"/"firstName"/"lastName" (the value is the plain comparison string). Operators: is, is_not, contains, not_contains, gt, gte, lt, lte, is_empty, is_not_empty. 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 the transactional send `variables` or an automation `event` payload, use { "id": "c1", "field": "variable", "operator": "is", "value": "plan:pro" } where the text before the colon is a {{merge tag}} path (nested paths like "order.total" or "event.plan" work) and the text after it is the comparison value. `field` may also be "attribute" (same "name:value" form) or "email"/"firstName"/"lastName" (the value is the plain comparison string). Operators: is, is_not, contains, not_contains, gt, gte, lt, lte, is_empty, is_not_empty. 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.",KD="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.",DW=500,zW=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"],C$={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},NP={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:NP,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},AW={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},x$={type:"object",properties:{nodeId:{type:"string",description:"Existing node ID from get_sequence.sequence.nodes[].id."},changes:AW,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","sequence.finished","sequence.failed","poll.answered"];var EP=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_sequence","generate_subject_lines","generate_sms","get_sms_settings"]),TP=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","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"]),_P=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"]),SP=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 RP(b){let w=EP.has(b),$=TP.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:SP.has(b),openWorldHint:_P.has(b)}}function PD(b){return{...b,annotations:{...b.annotations,...RP(b.name)}}}var OW={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"]},kP=Object.entries(OW).map(([b,w])=>`${b}: ${w.join(", ")}`).join("; "),qW={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. ${_w}`},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: ${kP}.`},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). ${_w}`}},required:["field","operator","value"],additionalProperties:!1},LW={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 y$(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(y$):[]}}function vP(b){let w=b.indexOf(":");return w!==-1&&b.substring(0,w).trim().length>0}function CP(b){let w=b.indexOf(":");return w!==-1&&b.substring(w+1).trim().length>0}function MD(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 xP(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&&MD(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&&MD(Q)?null:'Event filters must use "eventName:timeRange", like "saas.purchase:30d".'}function uP(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 yP(b){return b.trim().toLowerCase().replace(/[-\s]+/g,"_")}function hP(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 fP(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 cP(b){return["is","is_not","gte","lte","gt","lt"].includes(b)}function gP(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}=uP($);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=yP(Q);if(hP(X))return w==="is"||w==="is_not"?null:"Stripe cancellation flag filters only support is and is_not operators.";if(!fP(b,X))return`Unsupported Stripe product subfilter "${Q}".`;if(!cP(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 mP=new Set(["shopify","woocommerce","api"]);function nP(b,w){let $=w.trim(),W=$.indexOf(":");if(W!==-1&&mP.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 lP(b){let w;try{w=JSON.parse(b)}catch{return`Poll response filters must use valid JSON. ${_w}`}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. ${_w}`;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. ${_w}`}function h$(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 OW))return`Unsupported segment filter field "${String($)}".`;if(typeof W!=="string")return`Segment filter "${$}" must include an operator.`;let G=OW[$];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(!vP(Q))return'Attribute filters must use "attributeName:value" or "attributeName:" for empty checks.';if(W!=="is_empty"&&W!=="is_not_empty"&&!CP(Q))return'Attribute filters must include a value after "attributeName:".'}if($==="event"&&typeof Q==="string"){let X=xP(W,Q);if(X)return X}if($==="pollResponse"&&typeof Q==="string"){let X=lP(Q);if(X)return X}if(($==="stripeProduct"||$==="stripeCurrentProduct"||$==="stripeTrialProduct")&&typeof Q==="string"){let X=gP($,W,Q);if(X)return X}if($==="commerceProduct"&&typeof Q==="string"){let X=nP(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 f$(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 $=h$(w);return $?[$]:[]}if(Array.isArray(w.children))return w.children.flatMap(f$);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 jD(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=h$(Q);return G?[G]:[]}):f$(b.root);if(W.length>0)throw Error(W[0]??"Invalid segment filter in `create_segment`.")}function VD(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=h$(Q);return G?[G]:[]}):$?f$(b.root):[];if(W.length>0)throw Error(W[0]??"Invalid segment filter in `update_segment`.")}var UW=["name","description","logoUrl","founderName","primaryColor","brandColors","valueProps","testimonials","toneVoice","companyContext","emailLengthPreference","socialLinks","privacyPolicyUrl","termsUrl","address","language","pricing","fontFamily","emailDirection","fromEmail","fromName","replyTo","replyToName"];function BW(b,w,$){if(w[$]!==void 0&&!y(w[$]))throw Error(`\`${$}\` must be an object when calling \`${b}\`.`)}function ZD(b,w,$){if(w[$]!==void 0&&!Array.isArray(w[$]))throw Error(`\`${$}\` must be an array when calling \`${b}\`.`)}function ND(b){let w=new Set(["companyId",...UW]),$=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 UW)if(b[Q]!==void 0)W[Q]=b[Q];if(Object.keys(W).length===0)throw Error(`Provide at least one of ${UW.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(BW("update_company",b,"brandColors"),BW("update_company",b,"socialLinks"),BW("update_company",b,"pricing"),ZD("update_company",b,"valueProps"),ZD("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 ED=["senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName"];function iP(b){return ED.some((w)=>b[w]!==void 0)}function pP(b){if(typeof b.nodeType==="string")return b.nodeType==="action_email";return b.type===void 0||b.type==="email"}function c$(b,w,$){for(let W of ED){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 KW(b,w,$){if(iP($)&&!pP($))throw Error(`Sender identity fields are only supported for email steps at ${w} when calling \`${b}\`.`);c$(b,w,$)}function ID(b,w,$){if(!Array.isArray($))return;$.forEach((W,Q)=>{if(y(W))c$(b,`${w}[${Q}]`,W)})}function FW(b,w,$){if(!Array.isArray($))return;$.forEach((W,Q)=>{if(y(W))KW(b,`${w}[${Q}]`,W)})}function oP(b){if(ID("update_sequence","emails",b.emails),ID("update_sequence","steps",b.steps),y(b.insertSteps))FW("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($))FW("update_sequence",`branch.branches[${W}].steps`,$.steps)});FW("update_sequence","branch.elseSteps",b.branch.elseSteps)}function TD(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.");oP(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 _D(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 SD(b){let w=_D("update_sequence_node",b,"the node update");return{...b.confirmLiveChange!==void 0&&{confirmLiveChange:b.confirmLiveChange},nodeUpdates:[w]}}function RD(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=_D("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 kD(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 vD(b){let w=b.type==="sms",$;if(w){KW("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}),c$("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 CD(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 xD(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 uD(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 yD(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 g$(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 hD(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 fD(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},PW={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."}},m$={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 cD(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 MW(b){return b.trim().toLowerCase().replace(/\s+/g,"-")}function dP(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 mD(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=dP({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 tP(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 $=tP(w);if(!$.email&&!$.externalId)throw Error(`Provide either \`email\` or \`externalId\` when calling \`${b}\`.`);return $}function n$(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 ZW(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",n$(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 rP(b,w){let $=[],W=Vb(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 X=Q.trim();if(!v$.includes(X))throw Error(`\`eventTypes\` item ${G+1} must be one of ${v$.join(", ")} when calling \`${b}\`.`);$.push(X)})}return[...new Set($)]}function IW(b,w){let $=new URLSearchParams,W=rP(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 VW(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>DW)throw Error(`\`emails\` must include no more than ${DW} email addresses when calling \`${b}\`. Split larger batches into multiple calls.`);return $}function gD(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 nD(b){let $=gD("enroll_subscribers_in_sequence",b,"emails","email address"),W=gD("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>zW)throw Error(`\`emails\` and \`subscriberIds\` must include no more than ${zW} 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 eP,statSync as sP}from"node:fs";import{basename as aP}from"node:path";var bM={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 wM(b){let w=b.split(".").pop()?.toLowerCase()??"";return bM[w]??null}var $M=104857600;async function lD(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 $=wM(b);if(!$)throw Error("Unsupported file type. Use PDF, ePub, ZIP, image, audio, video, or text files.");let W=sP(b).size;if(W>$M)throw Error(`File is too large (${Math.round(W/1048576)}MB). Delivery files must be 100MB or smaller.`);let Q=eP(b),G=await A("POST","/api/v1/products/delivery/upload-url",{filename:aP(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 l$(b){let w=F(b,"companyId");if(w)return w;let $=qw();if($)return $;try{return(await A("GET","/api/v1/account")).currentCompanyId??void 0}catch{return}}async function iD(b,w){let $=await l$(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 pD(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 pD(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 WM(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 NW=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","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 oD(b,w,$){if(!y($)||!NW.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 l$(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:WM($.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:pD(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 QM,statSync as GM}from"node:fs";import{basename as XM,extname as tD}from"node:path";var TW=5242880,YM=Math.ceil(TW/3)*4,HM=Math.ceil(YM*1.05)+256,rD={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"},JM=new Set(Object.values(rD));function EW(b){return b?.split(";")[0]?.trim().toLowerCase()||void 0}function DM(b){return rD[tD(b).toLowerCase()]}function zM(b){let w=tD(b);return(w?b.slice(0,-w.length):b).replace(/[-_]+/g," ").trim()||"Image"}function AM(b){if(b.length>HM)throw Error("Image assets must be 5MB or smaller.")}function OM(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 qM(b){AM(b);let w=b.trim(),$=/^data:([^;,]+);base64,([\s\S]+)$/i.exec(w),W=$?.[2]??w;OM(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:EW($[1])}:{}}}function dD(b){if(b<=0)throw Error("The image file is empty.");if(b>TW)throw Error("Image assets must be 5MB or smaller.")}function LM(b){let w=DM(b.filename)??EW(b.explicitContentType)??EW(b.dataUrlContentType);if(!w||!JM.has(w))throw Error("Unsupported image type. Use PNG, JPEG, GIF, or WebP.");return w}function UM(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=GM(b.filePath).size;dD(G),w=QM(b.filePath),$=b.filename??XM(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=qM(b.imageBase64);w=G.bytes,W=G.dataUrlContentType,$=b.filename,dD(w.byteLength)}let Q=LM({filename:$,explicitContentType:b.contentType,dataUrlContentType:W});return{bytes:w,filename:$,contentType:Q,altText:b.altText??zM($)}}async function eD(b){let w=UM(b),$=w.bytes.byteLength,W=await A("POST","/api/v1/media/upload-url",{filename:w.filename,contentType:w.contentType,fileSizeBytes:$},b.companyId);return await lW(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 BM={type:"boolean",description:"Whether the Sequenzy operation succeeded."},FM={type:"string",description:"Human-readable status, confirmation, or next-step message."},KM={type:"string",description:"Additional context about the result."};function t(b){return{type:"object",description:b,additionalProperties:!0}}function PM(b){return{type:"array",description:b,items:t("One item in the returned collection.")}}function T(b){return{type:"string",description:b}}function Kb(b){return{type:"number",description:b}}function eb(b){return{type:"boolean",description:b}}function P(b){return t(`The ${b} record returned by Sequenzy.`)}function i(b){return PM(`List of ${b} records returned by Sequenzy.`)}var MM={appUrls:t("Dashboard URLs for relevant Sequenzy resources."),url:T("Primary dashboard URL for this result."),settingsUrl:T("Company settings URL when available.")},ZM={success:BM,message:FM,note:KM,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.")},IM={get_account:{account:P("account"),companies:i("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:T("Company ID selected by the authenticated API key, when available."),selectedCompanyId:T("Company ID selected locally for subsequent MCP calls, when available.")},select_company:{companyId:T("Selected company ID."),companyName:T("Selected company name.")},get_app_urls:{dashboard:T("Company dashboard URL."),settings:T("Company settings URL."),campaign:T("Campaign editor URL."),landingPage:T("Landing page editor URL."),sequence:T("Sequence editor URL."),email:T("Email editor URL."),transactionalEmail:T("Transactional email URL."),emailSend:T("Sent email detail URL."),domain:T("Sending domain settings URL."),urls:t("All generated URLs keyed by resource type.")},create_company:{company:P("company"),autoSelected:eb("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:eb("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:eb("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:T("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:T("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:T("Newly created API key if the API response uses the short key field.")},list_websites:{websites:i("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:eb("Whether the sender website is ready."),status:T("Current processing or verification status.")},verify_sending_domain:{website:P("Sending domain with current aggregate, SPF, DKIM, and MAIL FROM verification details."),verified:eb("Whether the sending domain passed the fresh verification check."),message:T("Verification result summary.")},get_integration_guide:{guide:P("integration guide"),code:T("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:eb("Whether the subscriber was permanently deleted.")},get_subscriber:{subscriber:P("subscriber")},list_subscriber_notes:{notes:i("subscriber note")},add_subscriber_note:{note:P("subscriber note")},delete_subscriber_note:{id:T("Deleted subscriber note ID."),deleted:eb("Whether the subscriber note was deleted.")},search_subscribers:{subscribers:i("subscriber"),pagination:t("Pagination metadata."),returned:Kb("Number of subscribers returned."),truncated:eb("Whether the result was truncated by the requested limit.")},list_products:{products:i("product")},upsert_products:{products:i("product"),created:Kb("Number of products created."),updated:Kb("Number of products updated.")},delete_product:{productId:T("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:T("Queued product sync job ID.")},list_tags:{tags:i("tag")},create_tag:{tag:P("tag")},update_tag:{tag:P("tag")},delete_tag:{tagId:T("Deleted tag ID.")},list_lists:{lists:i("list")},create_list:{list:P("list")},update_list:{list:P("list")},delete_list:{listId:T("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:i("segment")},create_segment:{segment:P("segment")},update_segment:{segment:P("segment")},delete_segment:{segmentId:T("Deleted segment ID.")},get_segment_count:{count:Kb("Number of subscribers matching the segment."),segmentId:T("Segment ID that was counted.")},list_audience_syncs:{audienceSyncs:i("audience sync")},list_ad_accounts:{adAccounts:i("ad account")},create_audience_sync:{audienceSync:P("audience sync")},update_audience_sync:{audienceSync:P("audience sync")},delete_audience_sync:{audienceSyncId:T("Deleted audience sync ID.")},sync_audience_now:{audienceSync:P("audience sync"),job:P("audience sync job"),jobId:T("Queued audience sync job ID.")},list_templates:{templates:i("email template")},get_template:{template:P("email template")},create_template:{template:P("email template")},update_template:{template:P("email template")},set_template_localization:{templateId:T("Localized template ID."),localization:P("template localization")},sync_template_localizations:{templateId:T("Template ID queued for localization."),queuedLocales:{type:"array",description:"Locale codes queued for AI translation.",items:T("One queued locale code.")},queuedVariantCount:Kb("Number of localized variants queued for translation.")},delete_template:{templateId:T("Deleted template ID.")},list_ab_tests:{abTests:i("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:T("Deleted A/B test variant ID.")},delete_ab_test:{abTestId:T("Deleted A/B test ID.")},list_campaigns:{campaigns:i("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:T("Scheduled send timestamp.")},send_test_email:{emailSend:P("test email send"),recipient:T("Test email recipient.")},send_test_sms:{smsSendId:T("Created test SMS send ID."),toPhone:T("Normalized E.164 destination phone.")},cancel_campaign:{campaign:P("campaign")},pause_campaign:{campaign:P("campaign")},resume_campaign:{campaign:P("campaign")},delete_campaign:{campaignId:T("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:i("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:T("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:T("Connected landing page domain.")},update_landing_page_domain_settings:{landingPage:P("landing page"),domain:T("Landing page domain.")},list_sequences:{sequences:i("sequence")},get_sequence:{sequence:P("sequence")},create_sequence:{sequence:P("sequence"),eventTrackingCode:T("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:T("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:T("Inserted automation node ID.")},insertedEmailIds:{type:"array",description:"Email template IDs created for the inserted step.",items:T("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:T("Sequence ID."),enrollmentPaused:eb("Whether new sequence enrollments are paused.")},resume_sequence_enrollments:{sequenceId:T("Sequence ID."),enrollmentPaused:eb("Whether new sequence enrollments are paused.")},enroll_subscribers_in_sequence:{sequence:P("sequence"),enrollments:i("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:T("Deleted sequence ID.")},list_transactional_emails:{transactional:i("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. ${_w} 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:i("campaign email event"),pagination:t("Pagination metadata.")},list_sequence_events:{events:i("sequence email event"),pagination:t("Pagination metadata.")},get_subscriber_activity:{activity:i("subscriber activity event"),subscribers:i("subscriber"),pagination:t("Pagination metadata.")},list_team_members:{members:i("team member"),invitations:i("team invitation")},invite_team_member:{invitation:P("team invitation")},cancel_team_invitation:{invitationId:T("Cancelled invitation ID.")},list_conversations:{conversations:i("inbox conversation"),pagination:t("Pagination metadata.")},get_conversation:{conversation:P("inbox conversation"),messages:i("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:i("outbound webhook")},create_webhook:{webhook:P("outbound webhook")},update_webhook:{webhook:P("outbound webhook")},delete_webhook:{webhookId:T("Deleted outbound webhook ID.")},test_webhook:{webhook:P("outbound webhook"),delivery:P("test webhook delivery")},list_webhook_deliveries:{deliveries:i("webhook delivery")},replay_webhook_delivery:{delivery:P("webhook delivery"),job:P("webhook replay job")},generate_email:{email:P("generated email"),html:T("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:T("Generated subject line."),previewText:T("Generated inbox preview text.")},generate_sequence:{sequence:P("generated sequence"),steps:i("generated sequence step")},generate_subject_lines:{subjectLines:{type:"array",description:"Generated subject line variants.",items:T("One generated subject line.")},variants:i("generated subject line variant")},generate_sms:{prompt:T("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 jM(b){let w=IM[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:{...ZM,...w,...NW.has(b)?MM:{}},additionalProperties:!0}}function sD(b){return{...b,outputSchema:jM(b.name)}}function aD(b){if(y(b))return b;if(Array.isArray(b))return{items:b};return{value:b}}var bz=[{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 wz=[{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:
30
30
  1. Call select_company first to choose which company to work with, OR
31
31
  2. Pass companyId explicitly in each tool call
32
32
 
@@ -48,7 +48,7 @@ Use cases:
48
48
  - 'event_tracking': Tracking CUSTOM events only (not payment events - those come from the integration)
49
49
  - 'ecommerce': Connecting a custom e-commerce platform via the Commerce API (sync products, push orders/checkouts, power abandoned cart + back-in-stock automations)
50
50
 
51
- 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 $z=[{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 - Use create_sequence instead] Generate a multi-email sequence from a goal. Note: create_sequence now handles AI generation automatically.",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')"},emailCount:{type:"number",description:"Number of emails in the sequence (default: 5, max: 10)"},durationDays:{type:"number",description:"Total duration in days (default: 14)"}},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 Wz=[{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), 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 Qz=[{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 Gz=[{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:_w,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:_w,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 Xz=[{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 Yz=[{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 Hz=[{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 Jz=[{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:FD},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 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 zz=[{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 a new email sequence. For net-new natural-language sequence content, provide goal and emailCount so Sequenzy generates it. Use explicit steps only for finished caller-supplied content, exact workflows, or migrations. Explicit steps can include email content, native SMS steps (type: 'sms' with 'text'; check get_sms_settings first and generate copy with generate_sms), and create_discount actions that dynamically create a provider discount/code when each subscriber reaches the step; emails after a discount action can use merge tags such as {{discount.code}} and {{discount.percentOff}}. For AI-generated sequences, the tool polls until emails are generated (typically 30-60 seconds).
51
+ 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 $z=[{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 - Use create_sequence instead] Generate a multi-email sequence from a goal. Note: create_sequence now handles AI generation automatically.",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')"},emailCount:{type:"number",description:"Number of emails in the sequence (default: 5, max: 10)"},durationDays:{type:"number",description:"Total duration in days (default: 14)"}},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 Wz=[{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 Qz=[{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 Gz=[{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 Xz=[{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 Yz=[{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 Hz=[{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 Jz=[{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:KD},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 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 zz=[{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 a new email sequence. For net-new natural-language sequence content, provide goal and emailCount so Sequenzy generates it. Use explicit steps only for finished caller-supplied content, exact workflows, or migrations. Explicit steps can include email content, native SMS steps (type: 'sms' with 'text'; check get_sms_settings first and generate copy with generate_sms), and create_discount actions that dynamically create a provider discount/code when each subscriber reaches the step; emails after a discount action can use merge tags such as {{discount.code}} and {{discount.percentOff}}. For AI-generated sequences, the tool polls until emails are generated (typically 30-60 seconds).
52
52
 
53
53
  MIGRATIONS: When moving sequences or flows from Brevo, Mailchimp, Klaviyo, MailerLite, or another provider, pass the exact provider HTML in each email step's html field and pass fixed waits as delay or delayMs. Use waitUntil when a wait should resolve from the trigger event payload, for example { "field": "renews_at", "direction": "before", "offset": { "days": 1 } }. The API stores provider HTML as raw HTML blocks and creates real logic_delay nodes for waits.
54
54
 
@@ -187,7 +187,7 @@ BUILT-IN EVENTS (auto-fired by payment integrations):
187
187
 
188
188
  OTHER BUILT-IN EVENTS:
189
189
  - email.opened, email.clicked, email.replied, email.bounced, email.unsubscribed
190
- - contact.subscribed, contact.unsubscribed`,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:C$,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 Az=[{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:C$,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:m$}},required:["conditionType"]}},elseSteps:{type:"array",description:"Steps to create inside the else fallback path. Required by default so the else arm is usable.",items:m$},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:m$}},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"}},...PW}}},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"}},...PW}}},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:x$.properties.nodeId,changes:AW,expectedUpdatedAt:x$.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:x$},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 Oz=[{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 qz=[{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:qW,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:{...LW,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:qW,minItems:1,description:"Replacement segment filters. Same shape and validation rules as create_segment. Mutually exclusive with `root`."},root:{...LW,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 Lz=[{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 Uz=[{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:_w,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:_w,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:"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 Bz=[{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:`${_w} 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:"Send a transactional email to a single recipient",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 (required if not using templateId)"},html:{type:"string",description:"Email HTML content (required if not using templateId)"},templateId:{type:"string",description:"Template ID to use (alternative to html)"},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"]}}];var Kz=[{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 Fz=[...wz,...Oz,...Dz,...qz,...Qz,...Uz,...bz,...Gz,...Jz,...Yz,...zz,...Az,...Bz,...Wz,...Lz,...Hz,...Kz,...$z,...Xz];async function Pz(b,w){let $;switch(b){case"get_account":{let W=await A("GET","/api/v1/account"),Q=Ow();$={...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"}`);A0(W),$={success:!0,message:`Switched to company: ${G.name}`,companyId:G.id,companyName:G.name};break}case"get_app_urls":{let W=await l$(w);$={...Hw({companyId:W,campaignId:K(w,"campaignId"),landingPageId:K(w,"landingPageId"),sequenceId:K(w,"sequenceId"),emailId:K(w,"emailId")??K(w,"templateId"),transactionalId:K(w,"transactionalId"),emailSendId:K(w,"emailSendId"),domainId:K(w,"domainId"),status:K(w,"status"),settingsTab:K(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}A0(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 iD("update_company",w),Q=ND(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 Mz(b,w){let $;switch(b){case"generate_email":{let W=w.companyId;$=await A("POST","/api/v1/generate/email",w,W);break}case"generate_sequence":{let W=w.companyId;$=await A("POST","/api/v1/generate/sequence",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:V("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:V("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 Zz(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(", ")}.`);fD(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(Cb("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;$=await A("POST","/api/v1/transactional/send",w,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=V("list_campaign_events",w,"campaignId"),X=IW("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=V("list_sequence_events",w,"sequenceId"),X=IW("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=zw("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 Iz(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=V("create_tag",w,"name"),G=jb("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=V("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=V("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=V("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&&K(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:K(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=V("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=V("add_subscribers_to_list",w,"listId"),G=VW("add_subscribers_to_list",w),X=jb("add_subscribers_to_list",w,"duplicateStrategy",["skip","merge","overwrite"])??"skip",Y=jb("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=V("remove_subscribers_from_list",w,"listId"),G=VW("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":{jD(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:y$(w.root)}:{}},W);break}case"update_segment":{VD(w);let W=w.companyId,Q=V("update_segment",w,"segmentId"),G=K(w,"name"),X=jb("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:u$(w.filters)}:{},...w.root!==void 0?{root:y$(w.root)}:{}},W);break}case"delete_segment":{let W=w.companyId,Q=V("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=K(w,"segmentId"),G=K(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:V("create_audience_sync",w,"adAccountId"),audienceName:V("create_audience_sync",w,"audienceName"),...w.frequency!==void 0?{frequency:w.frequency}:{}},W);break}case"update_audience_sync":{let W=w.companyId,Q=V("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=V("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=V("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 jz(b,w){let $;switch(b){case"list_templates":{let W=w.companyId,Q=new URLSearchParams,G=K(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;uD(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(Cb("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"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=K(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=K(w,"period"),X=K(w,"start"),Y=K(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=K(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:K(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(Cb("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=V("create_ab_test",w,"campaignId"),G=K(w,"name"),X=Dw("create_ab_test",w,"testPercentage",5,50),Y=Dw("create_ab_test",w,"testDurationMinutes",15,1440),H=jb("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=V("add_ab_test_variant",w,"abTestId"),G=V("add_ab_test_variant",w,"subject"),X=K(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=V("delete_ab_test_variant",w,"abTestId"),G=V("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=V("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=K(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(xD(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(Cb("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(", ")}.`);yD(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=V("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=V("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=V("resume_campaign",w,"campaignId"),G=Dw("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=V("delete_campaign",w,"campaignId");$=await A("DELETE",`/api/v1/campaigns/${encodeURIComponent(Q)}`,void 0,W);break}case"duplicate_campaign":{let W=w.companyId,Q=V("duplicate_campaign",w,"campaignId"),G=jb("duplicate_campaign",w,"mode",["campaign","ab_test","variant"]),X=K(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=V("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 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 Vz(b,w){if(b!=="upload_image_asset")return{handled:!1,result:void 0};let $=K(w,"filePath"),W=K(w,"imageBase64");if($===void 0===(W===void 0))throw Error("Provide either `filePath` or `imageBase64` (not both) when calling `upload_image_asset`.");let Q=K(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),X=i$(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=i$(w,"displayWidthPercent",1,100,!1)??100,H=i$(w,"cropHeight",1,2000,!0),J=K(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=K(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 eD({companyId:K(w,"companyId"),filePath:$,imageBase64:W,filename:Q,contentType:K(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 Nz(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=hD(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 Ez(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=V("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=V("attach_product_file",w,"productId"),G=K(w,"url"),X=K(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 lD(X,W);Y={url:H.url,source:"upload",fileName:K(w,"fileName")??H.fileName,fileSizeBytes:H.fileSizeBytes,mimeType:H.mimeType}}else{Y={url:G};let H=K(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=V("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:$}}async function Tz(b,w){let $;switch(b){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=6,H=0,J="pending";while(J!=="complete"&&H<Y){await new Promise((O)=>setTimeout(O,20000)),H++;let z=await A("GET",`/api/v1/sequences/${X}`,void 0,W);if(z.success)J=z.sequence.enrichmentStatus}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=TD(w);$=await A("PUT",`/api/v1/sequences/${w.sequenceId}`,Q,W);break}case"update_sequence_node":{let W=w.companyId,Q=V("update_sequence_node",w,"sequenceId"),G=SD(w);$=await A("PUT",`/api/v1/sequences/${Q}`,G,W);break}case"update_sequence_nodes":{let W=w.companyId,Q=V("update_sequence_nodes",w,"sequenceId"),G=RD(w);$=await A("PUT",`/api/v1/sequences/${Q}`,G,W);break}case"edit_sequence_graph":{let W=w.companyId,Q=vD(w);$=await A("PUT",`/api/v1/sequences/${w.sequenceId}`,Q,W);break}case"insert_sequence_step":{let W=w.companyId,Q=kD(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=V("enroll_subscribers_in_sequence",w,"sequenceId"),G=nD(w);$=await A("POST",`/api/v1/sequences/${encodeURIComponent(Q)}/enroll`,G,W);break}case"cancel_sequence_enrollments":{let W=w.companyId,Q=CD(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 _z(b,w){let $;switch(b){case"add_subscriber":{let W=w.companyId,Q=zw("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=zw("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(MW):[],H=new Set(Array.isArray(w.removeTags)?w.removeTags.filter((z)=>typeof z==="string"&&z.trim()!=="").map(MW):[]),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",n$(Q),D,W);break}case"remove_subscriber":{let W=w.companyId,Q=zw("remove_subscriber",w),G=n$(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=zw("get_subscriber",w);$=await H0(Q,W,{includeMachineEngagement:w.includeMachineEngagement===!0});break}case"list_subscriber_notes":{let W=w.companyId,Q=zw("list_subscriber_notes",w);$=await A("GET",ZW(Q),void 0,W);break}case"add_subscriber_note":{let W=w.companyId,Q=zw("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",ZW(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 mD(w,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}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=V("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=V("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=jb("list_conversations",w,"status",["open","closed","all"]);if(G)Q.set("status",G);let X=K(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=Dw("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=V("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=V("reply_to_conversation",w,"conversationId"),G=jb("reply_to_conversation",w,"type",["outbound","note"])??"outbound",X=K(w,"subject"),Y=K(w,"bodyText"),H=K(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=V("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=V("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=V("create_webhook",w,"name"),G=V("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=V("update_webhook",w,"webhookId"),G=K(w,"name"),X=K(w,"url"),Y=jW("update_webhook",w),H=jb("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=V("delete_webhook",w,"webhookId");$=await A("DELETE",`/api/v1/webhooks/${encodeURIComponent(Q)}`,void 0,W);break}case"test_webhook":{let W=w.companyId,Q=V("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=V("list_webhook_deliveries",w,"webhookId"),G=Dw("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=V("replay_webhook_delivery",w,"webhookId"),G=V("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,_z,Ez,Iz,jz,Nz,Vz,Tz,Zz,Sz,Mz];var vz=Fz.map(sD).map(PD);async function kz(b,w){try{let $,W=!1;for(let G of Rz){let X=await G(b,w);if(X.handled){$=X.result,W=!0;break}}if(!W)throw Error(`Unknown tool: ${b}`);let Q=gD($);if(Q)throw Q;return $=await oD(b,w,$),{structuredContent:aD($),content:[{type:"text",text:JSON.stringify($,null,2)}]}}catch($){return{isError:!0,content:[{type:"text",text:Aw($)}]}}}async function Cz(b,w,$){let W=w.getRequestContext?.(b)??{};try{return await r$(W,$)}finally{await w.onRequestContextUpdated?.(W,b)}}function _W(b={}){let w=new HW({name:"sequenzy",version:qD.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(`
191
- `)});return w.setRequestHandler(t4,async()=>{return{tools:vz}}),w.setRequestHandler(C1,async($,W)=>{let{name:Q,arguments:G}=$.params;return Cz(W,b,()=>kz(Q,G??{}))}),w.setRequestHandler(m4,async()=>{return{resources:BD}}),w.setRequestHandler(l4,async($,W)=>{let{uri:Q}=$.params;return Cz(W,b,()=>KD(Q))}),w}import uz from"node:process";class SW{append(b){this._buffer=this._buffer?Buffer.concat([this._buffer,b]):b}readMessage(){if(!this._buffer)return null;let b=this._buffer.indexOf(`
190
+ - contact.subscribed, contact.unsubscribed`,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:C$,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 Az=[{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:C$,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:m$}},required:["conditionType"]}},elseSteps:{type:"array",description:"Steps to create inside the else fallback path. Required by default so the else arm is usable.",items:m$},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:m$}},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"}},...PW}}},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"}},...PW}}},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:x$.properties.nodeId,changes:AW,expectedUpdatedAt:x$.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:x$},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 Oz=[{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 qz=[{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:qW,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:{...LW,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:qW,minItems:1,description:"Replacement segment filters. Same shape and validation rules as create_segment. Mutually exclusive with `root`."},root:{...LW,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 Lz=[{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 Uz=[{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 Bz=[{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 a transactional email to a single recipient",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 (required if not using templateId)"},html:{type:"string",description:"Email HTML content (required if not using templateId)"},templateId:{type:"string",description:"Template ID to use (alternative to html)"},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"]}}];var Fz=[{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 Kz=[...wz,...Oz,...Dz,...qz,...Qz,...Uz,...bz,...Gz,...Jz,...Yz,...zz,...Az,...Bz,...Wz,...Lz,...Hz,...Fz,...$z,...Xz];async function Pz(b,w){let $;switch(b){case"get_account":{let W=await A("GET","/api/v1/account"),Q=qw();$={...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"}`);A0(W),$={success:!0,message:`Switched to company: ${G.name}`,companyId:G.id,companyName:G.name};break}case"get_app_urls":{let W=await l$(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}A0(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 iD("update_company",w),Q=ND(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 Mz(b,w){let $;switch(b){case"generate_email":{let W=w.companyId;$=await A("POST","/api/v1/generate/email",w,W);break}case"generate_sequence":{let W=w.companyId;$=await A("POST","/api/v1/generate/sequence",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 Zz(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(", ")}.`);fD(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;$=await A("POST","/api/v1/transactional/send",w,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=IW("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=IW("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 Iz(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=VW("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=VW("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":{jD(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:y$(w.root)}:{}},W);break}case"update_segment":{VD(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:u$(w.filters)}:{},...w.root!==void 0?{root:y$(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 jz(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;uD(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(xD(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(", ")}.`);yD(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 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 Vz(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=i$(w,"sourceWidth",1,20000,!0),X=i$(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=i$(w,"displayWidthPercent",1,100,!1)??100,H=i$(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 eD({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 Nz(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=g$("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=g$("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=g$("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=hD(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 Ez(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 lD(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:$}}async function Tz(b,w){let $;switch(b){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=6,H=0,J="pending";while(J!=="complete"&&H<Y){await new Promise((O)=>setTimeout(O,20000)),H++;let z=await A("GET",`/api/v1/sequences/${X}`,void 0,W);if(z.success)J=z.sequence.enrichmentStatus}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=TD(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=SD(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=RD(w);$=await A("PUT",`/api/v1/sequences/${Q}`,G,W);break}case"edit_sequence_graph":{let W=w.companyId,Q=kD(w);$=await A("PUT",`/api/v1/sequences/${w.sequenceId}`,Q,W);break}case"insert_sequence_step":{let W=w.companyId,Q=vD(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=nD(w);$=await A("POST",`/api/v1/sequences/${encodeURIComponent(Q)}/enroll`,G,W);break}case"cancel_sequence_enrollments":{let W=w.companyId,Q=CD(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 _z(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(MW):[],H=new Set(Array.isArray(w.removeTags)?w.removeTags.filter((z)=>typeof z==="string"&&z.trim()!=="").map(MW):[]),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",n$(Q),D,W);break}case"remove_subscriber":{let W=w.companyId,Q=Aw("remove_subscriber",w),G=n$(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",ZW(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",ZW(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 mD(w,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}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=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 Rz=[Pz,_z,Ez,Iz,jz,Nz,Vz,Tz,Zz,Sz,Mz];var kz=Kz.map(sD).map(PD);async function vz(b,w){try{let $,W=!1;for(let G of Rz){let X=await G(b,w);if(X.handled){$=X.result,W=!0;break}}if(!W)throw Error(`Unknown tool: ${b}`);let Q=cD($);if(Q)throw Q;return $=await oD(b,w,$),{structuredContent:aD($),content:[{type:"text",text:JSON.stringify($,null,2)}]}}catch($){return{isError:!0,content:[{type:"text",text:Ow($)}]}}}async function Cz(b,w,$){let W=w.getRequestContext?.(b)??{};try{return await r$(W,$)}finally{await w.onRequestContextUpdated?.(W,b)}}function _W(b={}){let w=new HW({name:"sequenzy",version:qD.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(`
191
+ `)});return w.setRequestHandler(t4,async()=>{return{tools:kz}}),w.setRequestHandler(C1,async($,W)=>{let{name:Q,arguments:G}=$.params;return Cz(W,b,()=>vz(Q,G??{}))}),w.setRequestHandler(m4,async()=>{return{resources:BD}}),w.setRequestHandler(l4,async($,W)=>{let{uri:Q}=$.params;return Cz(W,b,()=>FD(Q))}),w}import uz from"node:process";class SW{append(b){this._buffer=this._buffer?Buffer.concat([this._buffer,b]):b}readMessage(){if(!this._buffer)return null;let b=this._buffer.indexOf(`
192
192
  `);if(b===-1)return null;let w=this._buffer.toString("utf8",0,b).replace(/\r$/,"");return this._buffer=this._buffer.subarray(b+1),VM(w)}clear(){this._buffer=void 0}}function VM(b){return IG.parse(JSON.parse(b))}function xz(b){return JSON.stringify(b)+`
193
- `}class RW{constructor(b=uz.stdin,w=uz.stdout){this._stdin=b,this._stdout=w,this._readBuffer=new SW,this._started=!1,this._ondata=($)=>{this._readBuffer.append($),this.processReadBuffer()},this._onerror=($)=>{this.onerror?.($)}}async start(){if(this._started)throw Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){while(!0)try{let b=this._readBuffer.readMessage();if(b===null)break;this.onmessage?.(b)}catch(b){this.onerror?.(b)}}async close(){if(this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0)this._stdin.pause();this._readBuffer.clear(),this.onclose?.()}send(b){return new Promise((w)=>{let $=xz(b);if(this._stdout.write($))w();else this._stdout.once("drain",w)})}}async function NM(){mW(),yW();let b=_W(),w=new RW;await b.connect(w),console.error("Sequenzy MCP server running on stdio")}NM().catch((b)=>{console.error(Aw(b)),process.exit(1)});export{r$ as withMcpRequestContext,A0 as setSelectedCompanyId,Ow as getSelectedCompanyId,_W as createSequenzyMcpServer,A as apiRequest};
193
+ `}class RW{constructor(b=uz.stdin,w=uz.stdout){this._stdin=b,this._stdout=w,this._readBuffer=new SW,this._started=!1,this._ondata=($)=>{this._readBuffer.append($),this.processReadBuffer()},this._onerror=($)=>{this.onerror?.($)}}async start(){if(this._started)throw Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){while(!0)try{let b=this._readBuffer.readMessage();if(b===null)break;this.onmessage?.(b)}catch(b){this.onerror?.(b)}}async close(){if(this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0)this._stdin.pause();this._readBuffer.clear(),this.onclose?.()}send(b){return new Promise((w)=>{let $=xz(b);if(this._stdout.write($))w();else this._stdout.once("drain",w)})}}async function NM(){mW(),yW();let b=_W(),w=new RW;await b.connect(w),console.error("Sequenzy MCP server running on stdio")}NM().catch((b)=>{console.error(Ow(b)),process.exit(1)});export{r$ as withMcpRequestContext,A0 as setSelectedCompanyId,qw as getSelectedCompanyId,_W as createSequenzyMcpServer,A as apiRequest};