@sequenzy/mcp 0.0.142 → 0.0.143

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.js CHANGED
@@ -1,31 +1,31 @@
1
- var kz=Object.create;var{getPrototypeOf:_z,defineProperty:L4,getOwnPropertyNames:xz}=Object;var hz=Object.prototype.hasOwnProperty;function yz(w){return this[w]}var fz,uz,zW=(w,b,$)=>{var W=w!=null&&typeof w==="object";if(W){var Q=b?fz??=new WeakMap:uz??=new WeakMap,X=Q.get(w);if(X)return X}$=w!=null?kz(_z(w)):{};let J=b||!w||!w.__esModule?L4($,"default",{value:w,enumerable:!0}):$;for(let G of xz(w))if(!hz.call(J,G))L4(J,G,{get:yz.bind(w,G),enumerable:!0});if(W)Q.set(w,J);return J};var N=(w,b)=>()=>(b||w((b={exports:{}}).exports,b),b.exports);var cz=(w)=>w;function mz(w,b){this[w]=cz.bind(null,b)}var BW=(w,b)=>{for(var $ in b)L4(w,$,{get:b[$],enumerable:!0,configurable:!0,set:mz.bind(b,$)})};var s0=N((zJ)=>{Object.defineProperty(zJ,"__esModule",{value:!0});zJ.regexpCode=zJ.getEsmExportName=zJ.getProperty=zJ.safeStringify=zJ.stringify=zJ.strConcat=zJ.addCodeArg=zJ.str=zJ._=zJ.nil=zJ._Code=zJ.Name=zJ.IDENTIFIER=zJ._CodeOrName=void 0;class z6{}zJ._CodeOrName=z6;zJ.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class $0 extends z6{constructor(w){super();if(!zJ.IDENTIFIER.test(w))throw Error("CodeGen: name must be a valid identifier");this.str=w}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}zJ.Name=$0;class lw extends z6{constructor(w){super();this._items=typeof w==="string"?[w]:w}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let w=this._items[0];return w===""||w==='""'}get str(){var w;return(w=this._str)!==null&&w!==void 0?w:this._str=this._items.reduce((b,$)=>`${b}${$}`,"")}get names(){var w;return(w=this._names)!==null&&w!==void 0?w:this._names=this._items.reduce((b,$)=>{if($ instanceof $0)b[$.str]=(b[$.str]||0)+1;return b},{})}}zJ._Code=lw;zJ.nil=new lw("");function YJ(w,...b){let $=[w[0]],W=0;while(W<b.length)q$($,b[W]),$.push(w[++W]);return new lw($)}zJ._=YJ;var j$=new lw("+");function HJ(w,...b){let $=[r0(w[0])],W=0;while(W<b.length)$.push(j$),q$($,b[W]),$.push(j$,r0(w[++W]));return zA($),new lw($)}zJ.str=HJ;function q$(w,b){if(b instanceof lw)w.push(...b._items);else if(b instanceof $0)w.push(b);else w.push(AA(b))}zJ.addCodeArg=q$;function zA(w){let b=1;while(b<w.length-1){if(w[b]===j$){let $=BA(w[b-1],w[b+1]);if($!==void 0){w.splice(b-1,3,$);continue}w[b++]="+"}b++}}function BA(w,b){if(b==='""')return w;if(w==='""')return b;if(typeof w=="string"){if(b instanceof $0||w[w.length-1]!=='"')return;if(typeof b!="string")return`${w.slice(0,-1)}${b}"`;if(b[0]==='"')return w.slice(0,-1)+b.slice(1);return}if(typeof b=="string"&&b[0]==='"'&&!(w instanceof $0))return`"${w}${b.slice(1)}`;return}function DA(w,b){return b.emptyStr()?w:w.emptyStr()?b:HJ`${w}${b}`}zJ.strConcat=DA;function AA(w){return typeof w=="number"||typeof w=="boolean"||w===null?w:r0(Array.isArray(w)?w.join(","):w)}function LA(w){return new lw(r0(w))}zJ.stringify=LA;function r0(w){return JSON.stringify(w).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}zJ.safeStringify=r0;function UA(w){return typeof w=="string"&&zJ.IDENTIFIER.test(w)?new lw(`.${w}`):YJ`[${w}]`}zJ.getProperty=UA;function FA(w){if(typeof w=="string"&&zJ.IDENTIFIER.test(w))return new lw(`${w}`);throw Error(`CodeGen: invalid export name: ${w}, use explicit $id name mapping`)}zJ.getEsmExportName=FA;function KA(w){return new lw(w.toString())}zJ.regexpCode=KA});var E$=N((LJ)=>{Object.defineProperty(LJ,"__esModule",{value:!0});LJ.ValueScope=LJ.ValueScopeName=LJ.Scope=LJ.varKinds=LJ.UsedValueState=void 0;var Nw=s0();class DJ extends Error{constructor(w){super(`CodeGen: "code" for ${w} not defined`);this.value=w.value}}var D6;(function(w){w[w.Started=0]="Started",w[w.Completed=1]="Completed"})(D6||(LJ.UsedValueState=D6={}));LJ.varKinds={const:new Nw.Name("const"),let:new Nw.Name("let"),var:new Nw.Name("var")};class I${constructor({prefixes:w,parent:b}={}){this._names={},this._prefixes=w,this._parent=b}toName(w){return w instanceof Nw.Name?w:this.name(w)}name(w){return new Nw.Name(this._newName(w))}_newName(w){let b=this._names[w]||this._nameGroup(w);return`${w}${b.index++}`}_nameGroup(w){var b,$;if((($=(b=this._parent)===null||b===void 0?void 0:b._prefixes)===null||$===void 0?void 0:$.has(w))||this._prefixes&&!this._prefixes.has(w))throw Error(`CodeGen: prefix "${w}" is not allowed in this scope`);return this._names[w]={prefix:w,index:0}}}LJ.Scope=I$;class N$ extends Nw.Name{constructor(w,b){super(b);this.prefix=w}setValue(w,{property:b,itemIndex:$}){this.value=w,this.scopePath=Nw._`.${new Nw.Name(b)}[${$}]`}}LJ.ValueScopeName=N$;var SA=Nw._`\n`;class AJ extends I${constructor(w){super(w);this._values={},this._scope=w.scope,this.opts={...w,_n:w.lines?SA:Nw.nil}}get(){return this._scope}name(w){return new N$(w,this._newName(w))}value(w,b){var $;if(b.ref===void 0)throw Error("CodeGen: ref must be passed in value");let W=this.toName(w),{prefix:Q}=W,X=($=b.key)!==null&&$!==void 0?$:b.ref,J=this._values[Q];if(J){let H=J.get(X);if(H)return H}else J=this._values[Q]=new Map;J.set(X,W);let G=this._scope[Q]||(this._scope[Q]=[]),Y=G.length;return G[Y]=b.ref,W.setValue(b,{property:Q,itemIndex:Y}),W}getValue(w,b){let $=this._values[w];if(!$)return;return $.get(b)}scopeRefs(w,b=this._values){return this._reduceValues(b,($)=>{if($.scopePath===void 0)throw Error(`CodeGen: name "${$}" has no value`);return Nw._`${w}${$.scopePath}`})}scopeCode(w=this._values,b,$){return this._reduceValues(w,(W)=>{if(W.value===void 0)throw Error(`CodeGen: name "${W}" has no value`);return W.value.code},b,$)}_reduceValues(w,b,$={},W){let Q=Nw.nil;for(let X in w){let J=w[X];if(!J)continue;let G=$[X]=$[X]||new Map;J.forEach((Y)=>{if(G.has(Y))return;G.set(Y,D6.Started);let H=b(Y);if(H){let z=this.opts.es5?LJ.varKinds.var:LJ.varKinds.const;Q=Nw._`${Q}${z} ${Y} = ${H};${this.opts._n}`}else if(H=W===null||W===void 0?void 0:W(Y))Q=Nw._`${Q}${H}${this.opts._n}`;else throw new DJ(Y);G.set(Y,D6.Completed)})}return Q}}LJ.ValueScope=AJ});var c=N((Ew)=>{Object.defineProperty(Ew,"__esModule",{value:!0});Ew.or=Ew.and=Ew.not=Ew.CodeGen=Ew.operators=Ew.varKinds=Ew.ValueScopeName=Ew.ValueScope=Ew.Scope=Ew.Name=Ew.regexpCode=Ew.stringify=Ew.getProperty=Ew.nil=Ew.strConcat=Ew.str=Ew._=void 0;var n=s0(),gw=E$(),P1=s0();Object.defineProperty(Ew,"_",{enumerable:!0,get:function(){return P1._}});Object.defineProperty(Ew,"str",{enumerable:!0,get:function(){return P1.str}});Object.defineProperty(Ew,"strConcat",{enumerable:!0,get:function(){return P1.strConcat}});Object.defineProperty(Ew,"nil",{enumerable:!0,get:function(){return P1.nil}});Object.defineProperty(Ew,"getProperty",{enumerable:!0,get:function(){return P1.getProperty}});Object.defineProperty(Ew,"stringify",{enumerable:!0,get:function(){return P1.stringify}});Object.defineProperty(Ew,"regexpCode",{enumerable:!0,get:function(){return P1.regexpCode}});Object.defineProperty(Ew,"Name",{enumerable:!0,get:function(){return P1.Name}});var O6=E$();Object.defineProperty(Ew,"Scope",{enumerable:!0,get:function(){return O6.Scope}});Object.defineProperty(Ew,"ValueScope",{enumerable:!0,get:function(){return O6.ValueScope}});Object.defineProperty(Ew,"ValueScopeName",{enumerable:!0,get:function(){return O6.ValueScopeName}});Object.defineProperty(Ew,"varKinds",{enumerable:!0,get:function(){return O6.varKinds}});Ew.operators={GT:new n._Code(">"),GTE:new n._Code(">="),LT:new n._Code("<"),LTE:new n._Code("<="),EQ:new n._Code("==="),NEQ:new n._Code("!=="),NOT:new n._Code("!"),OR:new n._Code("||"),AND:new n._Code("&&"),ADD:new n._Code("+")};class I1{optimizeNodes(){return this}optimizeNames(w,b){return this}}class FJ extends I1{constructor(w,b,$){super();this.varKind=w,this.name=b,this.rhs=$}render({es5:w,_n:b}){let $=w?gw.varKinds.var:this.varKind,W=this.rhs===void 0?"":` = ${this.rhs}`;return`${$} ${this.name}${W};`+b}optimizeNames(w,b){if(!w[this.name.str])return;if(this.rhs)this.rhs=Q0(this.rhs,w,b);return this}get names(){return this.rhs instanceof n._CodeOrName?this.rhs.names:{}}}class S$ extends I1{constructor(w,b,$){super();this.lhs=w,this.rhs=b,this.sideEffects=$}render({_n:w}){return`${this.lhs} = ${this.rhs};`+w}optimizeNames(w,b){if(this.lhs instanceof n.Name&&!w[this.lhs.str]&&!this.sideEffects)return;return this.rhs=Q0(this.rhs,w,b),this}get names(){let w=this.lhs instanceof n.Name?{}:{...this.lhs.names};return K6(w,this.rhs)}}class KJ extends S${constructor(w,b,$,W){super(w,$,W);this.op=b}render({_n:w}){return`${this.lhs} ${this.op}= ${this.rhs};`+w}}class OJ extends I1{constructor(w){super();this.label=w,this.names={}}render({_n:w}){return`${this.label}:`+w}}class ZJ extends I1{constructor(w){super();this.label=w,this.names={}}render({_n:w}){return`break${this.label?` ${this.label}`:""};`+w}}class MJ extends I1{constructor(w){super();this.error=w}render({_n:w}){return`throw ${this.error};`+w}get names(){return this.error.names}}class VJ extends I1{constructor(w){super();this.code=w}render({_n:w}){return`${this.code};`+w}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(w,b){return this.code=Q0(this.code,w,b),this}get names(){return this.code instanceof n._CodeOrName?this.code.names:{}}}class Z6 extends I1{constructor(w=[]){super();this.nodes=w}render(w){return this.nodes.reduce((b,$)=>b+$.render(w),"")}optimizeNodes(){let{nodes:w}=this,b=w.length;while(b--){let $=w[b].optimizeNodes();if(Array.isArray($))w.splice(b,1,...$);else if($)w[b]=$;else w.splice(b,1)}return w.length>0?this:void 0}optimizeNames(w,b){let{nodes:$}=this,W=$.length;while(W--){let Q=$[W];if(Q.optimizeNames(w,b))continue;_A(w,Q.names),$.splice(W,1)}return $.length>0?this:void 0}get names(){return this.nodes.reduce((w,b)=>h1(w,b.names),{})}}class N1 extends Z6{render(w){return"{"+w._n+super.render(w)+"}"+w._n}}class jJ extends Z6{}class e0 extends N1{}e0.kind="else";class G1 extends N1{constructor(w,b){super(b);this.condition=w}render(w){let b=`if(${this.condition})`+super.render(w);if(this.else)b+="else "+this.else.render(w);return b}optimizeNodes(){super.optimizeNodes();let w=this.condition;if(w===!0)return this.nodes;let b=this.else;if(b){let $=b.optimizeNodes();b=this.else=Array.isArray($)?new e0($):$}if(b){if(w===!1)return b instanceof G1?b:b.nodes;if(this.nodes.length)return this;return new G1(EJ(w),b instanceof G1?[b]:b.nodes)}if(w===!1||!this.nodes.length)return;return this}optimizeNames(w,b){var $;if(this.else=($=this.else)===null||$===void 0?void 0:$.optimizeNames(w,b),!(super.optimizeNames(w,b)||this.else))return;return this.condition=Q0(this.condition,w,b),this}get names(){let w=super.names;if(K6(w,this.condition),this.else)h1(w,this.else.names);return w}}G1.kind="if";class W0 extends N1{}W0.kind="for";class qJ extends W0{constructor(w){super();this.iteration=w}render(w){return`for(${this.iteration})`+super.render(w)}optimizeNames(w,b){if(!super.optimizeNames(w,b))return;return this.iteration=Q0(this.iteration,w,b),this}get names(){return h1(super.names,this.iteration.names)}}class PJ extends W0{constructor(w,b,$,W){super();this.varKind=w,this.name=b,this.from=$,this.to=W}render(w){let b=w.es5?gw.varKinds.var:this.varKind,{name:$,from:W,to:Q}=this;return`for(${b} ${$}=${W}; ${$}<${Q}; ${$}++)`+super.render(w)}get names(){let w=K6(super.names,this.from);return K6(w,this.to)}}class T$ extends W0{constructor(w,b,$,W){super();this.loop=w,this.varKind=b,this.name=$,this.iterable=W}render(w){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(w)}optimizeNames(w,b){if(!super.optimizeNames(w,b))return;return this.iterable=Q0(this.iterable,w,b),this}get names(){return h1(super.names,this.iterable.names)}}class A6 extends N1{constructor(w,b,$){super();this.name=w,this.args=b,this.async=$}render(w){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(w)}}A6.kind="func";class L6 extends Z6{render(w){return"return "+super.render(w)}}L6.kind="return";class IJ extends N1{render(w){let b="try"+super.render(w);if(this.catch)b+=this.catch.render(w);if(this.finally)b+=this.finally.render(w);return b}optimizeNodes(){var w,b;return super.optimizeNodes(),(w=this.catch)===null||w===void 0||w.optimizeNodes(),(b=this.finally)===null||b===void 0||b.optimizeNodes(),this}optimizeNames(w,b){var $,W;return super.optimizeNames(w,b),($=this.catch)===null||$===void 0||$.optimizeNames(w,b),(W=this.finally)===null||W===void 0||W.optimizeNames(w,b),this}get names(){let w=super.names;if(this.catch)h1(w,this.catch.names);if(this.finally)h1(w,this.finally.names);return w}}class U6 extends N1{constructor(w){super();this.error=w}render(w){return`catch(${this.error})`+super.render(w)}}U6.kind="catch";class F6 extends N1{render(w){return"finally"+super.render(w)}}F6.kind="finally";class NJ{constructor(w,b={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...b,_n:b.lines?`
2
- `:""},this._extScope=w,this._scope=new gw.Scope({parent:w}),this._nodes=[new jJ]}toString(){return this._root.render(this.opts)}name(w){return this._scope.name(w)}scopeName(w){return this._extScope.name(w)}scopeValue(w,b){let $=this._extScope.value(w,b);return(this._values[$.prefix]||(this._values[$.prefix]=new Set)).add($),$}getScopeValue(w,b){return this._extScope.getValue(w,b)}scopeRefs(w){return this._extScope.scopeRefs(w,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(w,b,$,W){let Q=this._scope.toName(b);if($!==void 0&&W)this._constants[Q.str]=$;return this._leafNode(new FJ(w,Q,$)),Q}const(w,b,$){return this._def(gw.varKinds.const,w,b,$)}let(w,b,$){return this._def(gw.varKinds.let,w,b,$)}var(w,b,$){return this._def(gw.varKinds.var,w,b,$)}assign(w,b,$){return this._leafNode(new S$(w,b,$))}add(w,b){return this._leafNode(new KJ(w,Ew.operators.ADD,b))}code(w){if(typeof w=="function")w();else if(w!==n.nil)this._leafNode(new VJ(w));return this}object(...w){let b=["{"];for(let[$,W]of w){if(b.length>1)b.push(",");if(b.push($),$!==W||this.opts.es5)b.push(":"),(0,n.addCodeArg)(b,W)}return b.push("}"),new n._Code(b)}if(w,b,$){if(this._blockNode(new G1(w)),b&&$)this.code(b).else().code($).endIf();else if(b)this.code(b).endIf();else if($)throw Error('CodeGen: "else" body without "then" body');return this}elseIf(w){return this._elseNode(new G1(w))}else(){return this._elseNode(new e0)}endIf(){return this._endBlockNode(G1,e0)}_for(w,b){if(this._blockNode(w),b)this.code(b).endFor();return this}for(w,b){return this._for(new qJ(w),b)}forRange(w,b,$,W,Q=this.opts.es5?gw.varKinds.var:gw.varKinds.let){let X=this._scope.toName(w);return this._for(new PJ(Q,X,b,$),()=>W(X))}forOf(w,b,$,W=gw.varKinds.const){let Q=this._scope.toName(w);if(this.opts.es5){let X=b instanceof n.Name?b:this.var("_arr",b);return this.forRange("_i",0,n._`${X}.length`,(J)=>{this.var(Q,n._`${X}[${J}]`),$(Q)})}return this._for(new T$("of",W,Q,b),()=>$(Q))}forIn(w,b,$,W=this.opts.es5?gw.varKinds.var:gw.varKinds.const){if(this.opts.ownProperties)return this.forOf(w,n._`Object.keys(${b})`,$);let Q=this._scope.toName(w);return this._for(new T$("in",W,Q,b),()=>$(Q))}endFor(){return this._endBlockNode(W0)}label(w){return this._leafNode(new OJ(w))}break(w){return this._leafNode(new ZJ(w))}return(w){let b=new L6;if(this._blockNode(b),this.code(w),b.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(L6)}try(w,b,$){if(!b&&!$)throw Error('CodeGen: "try" without "catch" and "finally"');let W=new IJ;if(this._blockNode(W),this.code(w),b){let Q=this.name("e");this._currNode=W.catch=new U6(Q),b(Q)}if($)this._currNode=W.finally=new F6,this.code($);return this._endBlockNode(U6,F6)}throw(w){return this._leafNode(new MJ(w))}block(w,b){if(this._blockStarts.push(this._nodes.length),w)this.code(w).endBlock(b);return this}endBlock(w){let b=this._blockStarts.pop();if(b===void 0)throw Error("CodeGen: not in self-balancing block");let $=this._nodes.length-b;if($<0||w!==void 0&&$!==w)throw Error(`CodeGen: wrong number of nodes: ${$} vs ${w} expected`);return this._nodes.length=b,this}func(w,b=n.nil,$,W){if(this._blockNode(new A6(w,b,$)),W)this.code(W).endFunc();return this}endFunc(){return this._endBlockNode(A6)}optimize(w=1){while(w-- >0)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(w){return this._currNode.nodes.push(w),this}_blockNode(w){this._currNode.nodes.push(w),this._nodes.push(w)}_endBlockNode(w,b){let $=this._currNode;if($ instanceof w||b&&$ instanceof b)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${b?`${w.kind}/${b.kind}`:w.kind}"`)}_elseNode(w){let b=this._currNode;if(!(b instanceof G1))throw Error('CodeGen: "else" without "if"');return this._currNode=b.else=w,this}get _root(){return this._nodes[0]}get _currNode(){let w=this._nodes;return w[w.length-1]}set _currNode(w){let b=this._nodes;b[b.length-1]=w}}Ew.CodeGen=NJ;function h1(w,b){for(let $ in b)w[$]=(w[$]||0)+(b[$]||0);return w}function K6(w,b){return b instanceof n._CodeOrName?h1(w,b.names):w}function Q0(w,b,$){if(w instanceof n.Name)return W(w);if(!Q(w))return w;return new n._Code(w._items.reduce((X,J)=>{if(J instanceof n.Name)J=W(J);if(J instanceof n._Code)X.push(...J._items);else X.push(J);return X},[]));function W(X){let J=$[X.str];if(J===void 0||b[X.str]!==1)return X;return delete b[X.str],J}function Q(X){return X instanceof n._Code&&X._items.some((J)=>J instanceof n.Name&&b[J.str]===1&&$[J.str]!==void 0)}}function _A(w,b){for(let $ in b)w[$]=(w[$]||0)-(b[$]||0)}function EJ(w){return typeof w=="boolean"||typeof w=="number"||w===null?!w:n._`!${R$(w)}`}Ew.not=EJ;var xA=TJ(Ew.operators.AND);function hA(...w){return w.reduce(xA)}Ew.and=hA;var yA=TJ(Ew.operators.OR);function fA(...w){return w.reduce(yA)}Ew.or=fA;function TJ(w){return(b,$)=>b===n.nil?$:$===n.nil?b:n._`${R$(b)} ${w} ${R$($)}`}function R$(w){return w instanceof n.Name?w:n._`(${w})`}});var t=N((yJ)=>{Object.defineProperty(yJ,"__esModule",{value:!0});yJ.checkStrictMode=yJ.getErrorPath=yJ.Type=yJ.useFunc=yJ.setEvaluated=yJ.evaluatedPropsToName=yJ.mergeEvaluated=yJ.eachItem=yJ.unescapeJsonPointer=yJ.escapeJsonPointer=yJ.escapeFragment=yJ.unescapeFragment=yJ.schemaRefOrVal=yJ.schemaHasRulesButRef=yJ.schemaHasRules=yJ.checkUnknownRules=yJ.alwaysValidSchema=yJ.toHash=void 0;var e=c(),lA=s0();function gA(w){let b={};for(let $ of w)b[$]=!0;return b}yJ.toHash=gA;function iA(w,b){if(typeof b=="boolean")return b;if(Object.keys(b).length===0)return!0;return CJ(w,b),!kJ(b,w.self.RULES.all)}yJ.alwaysValidSchema=iA;function CJ(w,b=w.schema){let{opts:$,self:W}=w;if(!$.strictSchema)return;if(typeof b==="boolean")return;let Q=W.RULES.keywords;for(let X in b)if(!Q[X])hJ(w,`unknown keyword: "${X}"`)}yJ.checkUnknownRules=CJ;function kJ(w,b){if(typeof w=="boolean")return!w;for(let $ in w)if(b[$])return!0;return!1}yJ.schemaHasRules=kJ;function nA(w,b){if(typeof w=="boolean")return!w;for(let $ in w)if($!=="$ref"&&b.all[$])return!0;return!1}yJ.schemaHasRulesButRef=nA;function pA({topSchemaRef:w,schemaPath:b},$,W,Q){if(!Q){if(typeof $=="number"||typeof $=="boolean")return $;if(typeof $=="string")return e._`${$}`}return e._`${w}${b}${(0,e.getProperty)(W)}`}yJ.schemaRefOrVal=pA;function dA(w){return _J(decodeURIComponent(w))}yJ.unescapeFragment=dA;function oA(w){return encodeURIComponent(C$(w))}yJ.escapeFragment=oA;function C$(w){if(typeof w=="number")return`${w}`;return w.replace(/~/g,"~0").replace(/\//g,"~1")}yJ.escapeJsonPointer=C$;function _J(w){return w.replace(/~1/g,"/").replace(/~0/g,"~")}yJ.unescapeJsonPointer=_J;function tA(w,b){if(Array.isArray(w))for(let $ of w)b($);else b(w)}yJ.eachItem=tA;function SJ({mergeNames:w,mergeToName:b,mergeValues:$,resultToName:W}){return(Q,X,J,G)=>{let Y=J===void 0?X:J instanceof e.Name?(X instanceof e.Name?w(Q,X,J):b(Q,X,J),J):X instanceof e.Name?(b(Q,J,X),X):$(X,J);return G===e.Name&&!(Y instanceof e.Name)?W(Q,Y):Y}}yJ.mergeEvaluated={props:SJ({mergeNames:(w,b,$)=>w.if(e._`${$} !== true && ${b} !== undefined`,()=>{w.if(e._`${b} === true`,()=>w.assign($,!0),()=>w.assign($,e._`${$} || {}`).code(e._`Object.assign(${$}, ${b})`))}),mergeToName:(w,b,$)=>w.if(e._`${$} !== true`,()=>{if(b===!0)w.assign($,!0);else w.assign($,e._`${$} || {}`),k$(w,$,b)}),mergeValues:(w,b)=>w===!0?!0:{...w,...b},resultToName:xJ}),items:SJ({mergeNames:(w,b,$)=>w.if(e._`${$} !== true && ${b} !== undefined`,()=>w.assign($,e._`${b} === true ? true : ${$} > ${b} ? ${$} : ${b}`)),mergeToName:(w,b,$)=>w.if(e._`${$} !== true`,()=>w.assign($,b===!0?!0:e._`${$} > ${b} ? ${$} : ${b}`)),mergeValues:(w,b)=>w===!0?!0:Math.max(w,b),resultToName:(w,b)=>w.var("items",b)})};function xJ(w,b){if(b===!0)return w.var("props",!0);let $=w.var("props",e._`{}`);if(b!==void 0)k$(w,$,b);return $}yJ.evaluatedPropsToName=xJ;function k$(w,b,$){Object.keys($).forEach((W)=>w.assign(e._`${b}${(0,e.getProperty)(W)}`,!0))}yJ.setEvaluated=k$;var vJ={};function rA(w,b){return w.scopeValue("func",{ref:b,code:vJ[b.code]||(vJ[b.code]=new lA._Code(b.code))})}yJ.useFunc=rA;var v$;(function(w){w[w.Num=0]="Num",w[w.Str=1]="Str"})(v$||(yJ.Type=v$={}));function sA(w,b,$){if(w instanceof e.Name){let W=b===v$.Num;return $?W?e._`"[" + ${w} + "]"`:e._`"['" + ${w} + "']"`:W?e._`"/" + ${w}`:e._`"/" + ${w}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return $?(0,e.getProperty)(w).toString():"/"+C$(w)}yJ.getErrorPath=sA;function hJ(w,b,$=w.opts.strictSchema){if(!$)return;if(b=`strict mode: ${b}`,$===!0)throw Error(b);w.self.logger.warn(b)}yJ.checkStrictMode=hJ});var Y1=N((uJ)=>{Object.defineProperty(uJ,"__esModule",{value:!0});var Vw=c(),UL={data:new Vw.Name("data"),valCxt:new Vw.Name("valCxt"),instancePath:new Vw.Name("instancePath"),parentData:new Vw.Name("parentData"),parentDataProperty:new Vw.Name("parentDataProperty"),rootData:new Vw.Name("rootData"),dynamicAnchors:new Vw.Name("dynamicAnchors"),vErrors:new Vw.Name("vErrors"),errors:new Vw.Name("errors"),this:new Vw.Name("this"),self:new Vw.Name("self"),scope:new Vw.Name("scope"),json:new Vw.Name("json"),jsonPos:new Vw.Name("jsonPos"),jsonLen:new Vw.Name("jsonLen"),jsonPart:new Vw.Name("jsonPart")};uJ.default=UL});var a0=N((gJ)=>{Object.defineProperty(gJ,"__esModule",{value:!0});gJ.extendErrors=gJ.resetErrorsCount=gJ.reportExtraError=gJ.reportError=gJ.keyword$DataError=gJ.keywordError=void 0;var p=c(),V6=t(),qw=Y1();gJ.keywordError={message:({keyword:w})=>p.str`must pass "${w}" keyword validation`};gJ.keyword$DataError={message:({keyword:w,schemaType:b})=>b?p.str`"${w}" keyword must be ${b} ($data)`:p.str`"${w}" keyword is invalid ($data)`};function KL(w,b=gJ.keywordError,$,W){let{it:Q}=w,{gen:X,compositeRule:J,allErrors:G}=Q,Y=lJ(w,b,$);if(W!==null&&W!==void 0?W:J||G)cJ(X,Y);else mJ(Q,p._`[${Y}]`)}gJ.reportError=KL;function OL(w,b=gJ.keywordError,$){let{it:W}=w,{gen:Q,compositeRule:X,allErrors:J}=W,G=lJ(w,b,$);if(cJ(Q,G),!(X||J))mJ(W,qw.default.vErrors)}gJ.reportExtraError=OL;function ZL(w,b){w.assign(qw.default.errors,b),w.if(p._`${qw.default.vErrors} !== null`,()=>w.if(b,()=>w.assign(p._`${qw.default.vErrors}.length`,b),()=>w.assign(qw.default.vErrors,null)))}gJ.resetErrorsCount=ZL;function ML({gen:w,keyword:b,schemaValue:$,data:W,errsCount:Q,it:X}){if(Q===void 0)throw Error("ajv implementation error");let J=w.name("err");w.forRange("i",Q,qw.default.errors,(G)=>{if(w.const(J,p._`${qw.default.vErrors}[${G}]`),w.if(p._`${J}.instancePath === undefined`,()=>w.assign(p._`${J}.instancePath`,(0,p.strConcat)(qw.default.instancePath,X.errorPath))),w.assign(p._`${J}.schemaPath`,p.str`${X.errSchemaPath}/${b}`),X.opts.verbose)w.assign(p._`${J}.schema`,$),w.assign(p._`${J}.data`,W)})}gJ.extendErrors=ML;function cJ(w,b){let $=w.const("err",b);w.if(p._`${qw.default.vErrors} === null`,()=>w.assign(qw.default.vErrors,p._`[${$}]`),p._`${qw.default.vErrors}.push(${$})`),w.code(p._`${qw.default.errors}++`)}function mJ(w,b){let{gen:$,validateName:W,schemaEnv:Q}=w;if(Q.$async)$.throw(p._`new ${w.ValidationError}(${b})`);else $.assign(p._`${W}.errors`,b),$.return(!1)}var y1={keyword:new p.Name("keyword"),schemaPath:new p.Name("schemaPath"),params:new p.Name("params"),propertyName:new p.Name("propertyName"),message:new p.Name("message"),schema:new p.Name("schema"),parentSchema:new p.Name("parentSchema")};function lJ(w,b,$){let{createErrors:W}=w.it;if(W===!1)return p._`{}`;return VL(w,b,$)}function VL(w,b,$={}){let{gen:W,it:Q}=w,X=[jL(Q,$),qL(w,$)];return PL(w,b,X),W.object(...X)}function jL({errorPath:w},{instancePath:b}){let $=b?p.str`${w}${(0,V6.getErrorPath)(b,V6.Type.Str)}`:w;return[qw.default.instancePath,(0,p.strConcat)(qw.default.instancePath,$)]}function qL({keyword:w,it:{errSchemaPath:b}},{schemaPath:$,parentSchema:W}){let Q=W?b:p.str`${b}/${w}`;if($)Q=p.str`${Q}${(0,V6.getErrorPath)($,V6.Type.Str)}`;return[y1.schemaPath,Q]}function PL(w,{params:b,message:$},W){let{keyword:Q,data:X,schemaValue:J,it:G}=w,{opts:Y,propertyName:H,topSchemaRef:z,schemaPath:D}=G;if(W.push([y1.keyword,Q],[y1.params,typeof b=="function"?b(w):b||p._`{}`]),Y.messages)W.push([y1.message,typeof $=="function"?$(w):$]);if(Y.verbose)W.push([y1.schema,J],[y1.parentSchema,p._`${z}${D}`],[qw.default.data,X]);if(H)W.push([y1.propertyName,H])}});var oJ=N((pJ)=>{Object.defineProperty(pJ,"__esModule",{value:!0});pJ.boolOrEmptySchema=pJ.topBoolOrEmptySchema=void 0;var RL=a0(),SL=c(),vL=Y1(),CL={message:"boolean schema is false"};function kL(w){let{gen:b,schema:$,validateName:W}=w;if($===!1)nJ(w,!1);else if(typeof $=="object"&&$.$async===!0)b.return(vL.default.data);else b.assign(SL._`${W}.errors`,null),b.return(!0)}pJ.topBoolOrEmptySchema=kL;function _L(w,b){let{gen:$,schema:W}=w;if(W===!1)$.var(b,!1),nJ(w);else $.var(b,!0)}pJ.boolOrEmptySchema=_L;function nJ(w,b){let{gen:$,data:W}=w,Q={gen:$,keyword:"false schema",data:W,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:w};(0,RL.reportError)(Q,CL,void 0,b)}});var x$=N((tJ)=>{Object.defineProperty(tJ,"__esModule",{value:!0});tJ.getRules=tJ.isJSONType=void 0;var hL=["string","number","integer","boolean","null","object","array"],yL=new Set(hL);function fL(w){return typeof w=="string"&&yL.has(w)}tJ.isJSONType=fL;function uL(){let w={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...w,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},w.number,w.string,w.array,w.object],post:{rules:[]},all:{},keywords:{}}}tJ.getRules=uL});var h$=N((aJ)=>{Object.defineProperty(aJ,"__esModule",{value:!0});aJ.shouldUseRule=aJ.shouldUseGroup=aJ.schemaHasRulesForType=void 0;function mL({schema:w,self:b},$){let W=b.RULES.types[$];return W&&W!==!0&&sJ(w,W)}aJ.schemaHasRulesForType=mL;function sJ(w,b){return b.rules.some(($)=>eJ(w,$))}aJ.shouldUseGroup=sJ;function eJ(w,b){var $;return w[b.keyword]!==void 0||(($=b.definition.implements)===null||$===void 0?void 0:$.some((W)=>w[W]!==void 0))}aJ.shouldUseRule=eJ});var wb=N((QG)=>{Object.defineProperty(QG,"__esModule",{value:!0});QG.reportTypeError=QG.checkDataTypes=QG.checkDataType=QG.coerceAndCheckDataType=QG.getJSONTypes=QG.getSchemaTypes=QG.DataType=void 0;var iL=x$(),nL=h$(),pL=a0(),f=c(),bG=t(),X0;(function(w){w[w.Correct=0]="Correct",w[w.Wrong=1]="Wrong"})(X0||(QG.DataType=X0={}));function dL(w){let b=$G(w.type);if(b.includes("null")){if(w.nullable===!1)throw Error("type: null contradicts nullable: false")}else{if(!b.length&&w.nullable!==void 0)throw Error('"nullable" cannot be used without "type"');if(w.nullable===!0)b.push("null")}return b}QG.getSchemaTypes=dL;function $G(w){let b=Array.isArray(w)?w:w?[w]:[];if(b.every(iL.isJSONType))return b;throw Error("type must be JSONType or JSONType[]: "+b.join(","))}QG.getJSONTypes=$G;function oL(w,b){let{gen:$,data:W,opts:Q}=w,X=tL(b,Q.coerceTypes),J=b.length>0&&!(X.length===0&&b.length===1&&(0,nL.schemaHasRulesForType)(w,b[0]));if(J){let G=f$(b,W,Q.strictNumbers,X0.Wrong);$.if(G,()=>{if(X.length)rL(w,b,X);else u$(w)})}return J}QG.coerceAndCheckDataType=oL;var WG=new Set(["string","number","integer","boolean","null"]);function tL(w,b){return b?w.filter(($)=>WG.has($)||b==="array"&&$==="array"):[]}function rL(w,b,$){let{gen:W,data:Q,opts:X}=w,J=W.let("dataType",f._`typeof ${Q}`),G=W.let("coerced",f._`undefined`);if(X.coerceTypes==="array")W.if(f._`${J} == 'object' && Array.isArray(${Q}) && ${Q}.length == 1`,()=>W.assign(Q,f._`${Q}[0]`).assign(J,f._`typeof ${Q}`).if(f$(b,Q,X.strictNumbers),()=>W.assign(G,Q)));W.if(f._`${G} !== undefined`);for(let H of $)if(WG.has(H)||H==="array"&&X.coerceTypes==="array")Y(H);W.else(),u$(w),W.endIf(),W.if(f._`${G} !== undefined`,()=>{W.assign(Q,G),sL(w,G)});function Y(H){switch(H){case"string":W.elseIf(f._`${J} == "number" || ${J} == "boolean"`).assign(G,f._`"" + ${Q}`).elseIf(f._`${Q} === null`).assign(G,f._`""`);return;case"number":W.elseIf(f._`${J} == "boolean" || ${Q} === null
3
- || (${J} == "string" && ${Q} && ${Q} == +${Q})`).assign(G,f._`+${Q}`);return;case"integer":W.elseIf(f._`${J} === "boolean" || ${Q} === null
4
- || (${J} === "string" && ${Q} && ${Q} == +${Q} && !(${Q} % 1))`).assign(G,f._`+${Q}`);return;case"boolean":W.elseIf(f._`${Q} === "false" || ${Q} === 0 || ${Q} === null`).assign(G,!1).elseIf(f._`${Q} === "true" || ${Q} === 1`).assign(G,!0);return;case"null":W.elseIf(f._`${Q} === "" || ${Q} === 0 || ${Q} === false`),W.assign(G,null);return;case"array":W.elseIf(f._`${J} === "string" || ${J} === "number"
5
- || ${J} === "boolean" || ${Q} === null`).assign(G,f._`[${Q}]`)}}}function sL({gen:w,parentData:b,parentDataProperty:$},W){w.if(f._`${b} !== undefined`,()=>w.assign(f._`${b}[${$}]`,W))}function y$(w,b,$,W=X0.Correct){let Q=W===X0.Correct?f.operators.EQ:f.operators.NEQ,X;switch(w){case"null":return f._`${b} ${Q} null`;case"array":X=f._`Array.isArray(${b})`;break;case"object":X=f._`${b} && typeof ${b} == "object" && !Array.isArray(${b})`;break;case"integer":X=J(f._`!(${b} % 1) && !isNaN(${b})`);break;case"number":X=J();break;default:return f._`typeof ${b} ${Q} ${w}`}return W===X0.Correct?X:(0,f.not)(X);function J(G=f.nil){return(0,f.and)(f._`typeof ${b} == "number"`,G,$?f._`isFinite(${b})`:f.nil)}}QG.checkDataType=y$;function f$(w,b,$,W){if(w.length===1)return y$(w[0],b,$,W);let Q,X=(0,bG.toHash)(w);if(X.array&&X.object){let J=f._`typeof ${b} != "object"`;Q=X.null?J:f._`!${b} || ${J}`,delete X.null,delete X.array,delete X.object}else Q=f.nil;if(X.number)delete X.integer;for(let J in X)Q=(0,f.and)(Q,y$(J,b,$,W));return Q}QG.checkDataTypes=f$;var eL={message:({schema:w})=>`must be ${w}`,params:({schema:w,schemaValue:b})=>typeof w=="string"?f._`{type: ${w}}`:f._`{type: ${b}}`};function u$(w){let b=aL(w);(0,pL.reportError)(b,eL)}QG.reportTypeError=u$;function aL(w){let{gen:b,data:$,schema:W}=w,Q=(0,bG.schemaRefOrVal)(w,W,"type");return{gen:b,keyword:"type",data:$,schema:W.type,schemaCode:Q,schemaValue:Q,parentSchema:W,params:{},it:w}}});var HG=N((GG)=>{Object.defineProperty(GG,"__esModule",{value:!0});GG.assignDefaults=void 0;var J0=c(),JU=t();function GU(w,b){let{properties:$,items:W}=w.schema;if(b==="object"&&$)for(let Q in $)JG(w,Q,$[Q].default);else if(b==="array"&&Array.isArray(W))W.forEach((Q,X)=>JG(w,X,Q.default))}GG.assignDefaults=GU;function JG(w,b,$){let{gen:W,compositeRule:Q,data:X,opts:J}=w;if($===void 0)return;let G=J0._`${X}${(0,J0.getProperty)(b)}`;if(Q){(0,JU.checkStrictMode)(w,`default is ignored for: ${G}`);return}let Y=J0._`${G} === undefined`;if(J.useDefaults==="empty")Y=J0._`${Y} || ${G} === null || ${G} === ""`;W.if(Y,J0._`${G} = ${(0,J0.stringify)($)}`)}});var fw=N((DG)=>{Object.defineProperty(DG,"__esModule",{value:!0});DG.validateUnion=DG.validateArray=DG.usePattern=DG.callValidateCode=DG.schemaProperties=DG.allSchemaProperties=DG.noPropertyInData=DG.propertyInData=DG.isOwnProperty=DG.hasPropFunc=DG.reportMissingProp=DG.checkMissingProp=DG.checkReportMissingProp=void 0;var $w=c(),c$=t(),E1=Y1(),YU=t();function HU(w,b){let{gen:$,data:W,it:Q}=w;$.if(l$($,W,b,Q.opts.ownProperties),()=>{w.setParams({missingProperty:$w._`${b}`},!0),w.error()})}DG.checkReportMissingProp=HU;function zU({gen:w,data:b,it:{opts:$}},W,Q){return(0,$w.or)(...W.map((X)=>(0,$w.and)(l$(w,b,X,$.ownProperties),$w._`${Q} = ${X}`)))}DG.checkMissingProp=zU;function BU(w,b){w.setParams({missingProperty:b},!0),w.error()}DG.reportMissingProp=BU;function zG(w){return w.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:$w._`Object.prototype.hasOwnProperty`})}DG.hasPropFunc=zG;function m$(w,b,$){return $w._`${zG(w)}.call(${b}, ${$})`}DG.isOwnProperty=m$;function DU(w,b,$,W){let Q=$w._`${b}${(0,$w.getProperty)($)} !== undefined`;return W?$w._`${Q} && ${m$(w,b,$)}`:Q}DG.propertyInData=DU;function l$(w,b,$,W){let Q=$w._`${b}${(0,$w.getProperty)($)} === undefined`;return W?(0,$w.or)(Q,(0,$w.not)(m$(w,b,$))):Q}DG.noPropertyInData=l$;function BG(w){return w?Object.keys(w).filter((b)=>b!=="__proto__"):[]}DG.allSchemaProperties=BG;function AU(w,b){return BG(b).filter(($)=>!(0,c$.alwaysValidSchema)(w,b[$]))}DG.schemaProperties=AU;function LU({schemaCode:w,data:b,it:{gen:$,topSchemaRef:W,schemaPath:Q,errorPath:X},it:J},G,Y,H){let z=H?$w._`${w}, ${b}, ${W}${Q}`:b,D=[[E1.default.instancePath,(0,$w.strConcat)(E1.default.instancePath,X)],[E1.default.parentData,J.parentData],[E1.default.parentDataProperty,J.parentDataProperty],[E1.default.rootData,E1.default.rootData]];if(J.opts.dynamicRef)D.push([E1.default.dynamicAnchors,E1.default.dynamicAnchors]);let A=$w._`${z}, ${$.object(...D)}`;return Y!==$w.nil?$w._`${G}.call(${Y}, ${A})`:$w._`${G}(${A})`}DG.callValidateCode=LU;var UU=$w._`new RegExp`;function FU({gen:w,it:{opts:b}},$){let W=b.unicodeRegExp?"u":"",{regExp:Q}=b.code,X=Q($,W);return w.scopeValue("pattern",{key:X.toString(),ref:X,code:$w._`${Q.code==="new RegExp"?UU:(0,YU.useFunc)(w,Q)}(${$}, ${W})`})}DG.usePattern=FU;function KU(w){let{gen:b,data:$,keyword:W,it:Q}=w,X=b.name("valid");if(Q.allErrors){let G=b.let("valid",!0);return J(()=>b.assign(G,!1)),G}return b.var(X,!0),J(()=>b.break()),X;function J(G){let Y=b.const("len",$w._`${$}.length`);b.forRange("i",0,Y,(H)=>{w.subschema({keyword:W,dataProp:H,dataPropType:c$.Type.Num},X),b.if((0,$w.not)(X),G)})}}DG.validateArray=KU;function OU(w){let{gen:b,schema:$,keyword:W,it:Q}=w;if(!Array.isArray($))throw Error("ajv implementation error");if($.some((Y)=>(0,c$.alwaysValidSchema)(Q,Y))&&!Q.opts.unevaluated)return;let J=b.let("valid",!1),G=b.name("_valid");b.block(()=>$.forEach((Y,H)=>{let z=w.subschema({keyword:W,schemaProp:H,compositeRule:!0},G);if(b.assign(J,$w._`${J} || ${G}`),!w.mergeValidEvaluated(z,G))b.if((0,$w.not)(J))})),w.result(J,()=>w.reset(),()=>w.error(!0))}DG.validateUnion=OU});var OG=N((FG)=>{Object.defineProperty(FG,"__esModule",{value:!0});FG.validateKeywordUsage=FG.validSchemaType=FG.funcKeywordCode=FG.macroKeywordCode=void 0;var Pw=c(),f1=Y1(),vU=fw(),CU=a0();function kU(w,b){let{gen:$,keyword:W,schema:Q,parentSchema:X,it:J}=w,G=b.macro.call(J.self,Q,X,J),Y=UG($,W,G);if(J.opts.validateSchema!==!1)J.self.validateSchema(G,!0);let H=$.name("valid");w.subschema({schema:G,schemaPath:Pw.nil,errSchemaPath:`${J.errSchemaPath}/${W}`,topSchemaRef:Y,compositeRule:!0},H),w.pass(H,()=>w.error(!0))}FG.macroKeywordCode=kU;function _U(w,b){var $;let{gen:W,keyword:Q,schema:X,parentSchema:J,$data:G,it:Y}=w;hU(Y,b);let H=!G&&b.compile?b.compile.call(Y.self,X,J,Y):b.validate,z=UG(W,Q,H),D=W.let("valid");w.block$data(D,A),w.ok(($=b.valid)!==null&&$!==void 0?$:D);function A(){if(b.errors===!1){if(V(),b.modifying)LG(w);q(()=>w.error())}else{let P=b.async?L():F();if(b.modifying)LG(w);q(()=>xU(w,P))}}function L(){let P=W.let("ruleErrs",null);return W.try(()=>V(Pw._`await `),(k)=>W.assign(D,!1).if(Pw._`${k} instanceof ${Y.ValidationError}`,()=>W.assign(P,Pw._`${k}.errors`),()=>W.throw(k))),P}function F(){let P=Pw._`${z}.errors`;return W.assign(P,null),V(Pw.nil),P}function V(P=b.async?Pw._`await `:Pw.nil){let k=Y.opts.passContext?f1.default.this:f1.default.self,S=!(("compile"in b)&&!G||b.schema===!1);W.assign(D,Pw._`${P}${(0,vU.callValidateCode)(w,z,k,S)}`,b.modifying)}function q(P){var k;W.if((0,Pw.not)((k=b.valid)!==null&&k!==void 0?k:D),P)}}FG.funcKeywordCode=_U;function LG(w){let{gen:b,data:$,it:W}=w;b.if(W.parentData,()=>b.assign($,Pw._`${W.parentData}[${W.parentDataProperty}]`))}function xU(w,b){let{gen:$}=w;$.if(Pw._`Array.isArray(${b})`,()=>{$.assign(f1.default.vErrors,Pw._`${f1.default.vErrors} === null ? ${b} : ${f1.default.vErrors}.concat(${b})`).assign(f1.default.errors,Pw._`${f1.default.vErrors}.length`),(0,CU.extendErrors)(w)},()=>w.error())}function hU({schemaEnv:w},b){if(b.async&&!w.$async)throw Error("async keyword in sync schema")}function UG(w,b,$){if($===void 0)throw Error(`keyword "${b}" failed to compile`);return w.scopeValue("keyword",typeof $=="function"?{ref:$}:{ref:$,code:(0,Pw.stringify)($)})}function yU(w,b,$=!1){return!b.length||b.some((W)=>W==="array"?Array.isArray(w):W==="object"?w&&typeof w=="object"&&!Array.isArray(w):typeof w==W||$&&typeof w>"u")}FG.validSchemaType=yU;function fU({schema:w,opts:b,self:$,errSchemaPath:W},Q,X){if(Array.isArray(Q.keyword)?!Q.keyword.includes(X):Q.keyword!==X)throw Error("ajv implementation error");let J=Q.dependencies;if(J===null||J===void 0?void 0:J.some((G)=>!Object.prototype.hasOwnProperty.call(w,G)))throw Error(`parent schema must have dependencies of ${X}: ${J.join(",")}`);if(Q.validateSchema){if(!Q.validateSchema(w[X])){let Y=`keyword "${X}" value is invalid at path "${W}": `+$.errorsText(Q.validateSchema.errors);if(b.validateSchema==="log")$.logger.error(Y);else throw Error(Y)}}}FG.validateKeywordUsage=fU});var jG=N((MG)=>{Object.defineProperty(MG,"__esModule",{value:!0});MG.extendSubschemaMode=MG.extendSubschemaData=MG.getSubschema=void 0;var ew=c(),ZG=t();function lU(w,{keyword:b,schemaProp:$,schema:W,schemaPath:Q,errSchemaPath:X,topSchemaRef:J}){if(b!==void 0&&W!==void 0)throw Error('both "keyword" and "schema" passed, only one allowed');if(b!==void 0){let G=w.schema[b];return $===void 0?{schema:G,schemaPath:ew._`${w.schemaPath}${(0,ew.getProperty)(b)}`,errSchemaPath:`${w.errSchemaPath}/${b}`}:{schema:G[$],schemaPath:ew._`${w.schemaPath}${(0,ew.getProperty)(b)}${(0,ew.getProperty)($)}`,errSchemaPath:`${w.errSchemaPath}/${b}/${(0,ZG.escapeFragment)($)}`}}if(W!==void 0){if(Q===void 0||X===void 0||J===void 0)throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:W,schemaPath:Q,topSchemaRef:J,errSchemaPath:X}}throw Error('either "keyword" or "schema" must be passed')}MG.getSubschema=lU;function gU(w,b,{dataProp:$,dataPropType:W,data:Q,dataTypes:X,propertyName:J}){if(Q!==void 0&&$!==void 0)throw Error('both "data" and "dataProp" passed, only one allowed');let{gen:G}=b;if($!==void 0){let{errorPath:H,dataPathArr:z,opts:D}=b,A=G.let("data",ew._`${b.data}${(0,ew.getProperty)($)}`,!0);Y(A),w.errorPath=ew.str`${H}${(0,ZG.getErrorPath)($,W,D.jsPropertySyntax)}`,w.parentDataProperty=ew._`${$}`,w.dataPathArr=[...z,w.parentDataProperty]}if(Q!==void 0){let H=Q instanceof ew.Name?Q:G.let("data",Q,!0);if(Y(H),J!==void 0)w.propertyName=J}if(X)w.dataTypes=X;function Y(H){w.data=H,w.dataLevel=b.dataLevel+1,w.dataTypes=[],b.definedProperties=new Set,w.parentData=b.data,w.dataNames=[...b.dataNames,H]}}MG.extendSubschemaData=gU;function iU(w,{jtdDiscriminator:b,jtdMetadata:$,compositeRule:W,createErrors:Q,allErrors:X}){if(W!==void 0)w.compositeRule=W;if(Q!==void 0)w.createErrors=Q;if(X!==void 0)w.allErrors=X;w.jtdDiscriminator=b,w.jtdMetadata=$}MG.extendSubschemaMode=iU});var g$=N((pT,qG)=>{qG.exports=function w(b,$){if(b===$)return!0;if(b&&$&&typeof b=="object"&&typeof $=="object"){if(b.constructor!==$.constructor)return!1;var W,Q,X;if(Array.isArray(b)){if(W=b.length,W!=$.length)return!1;for(Q=W;Q--!==0;)if(!w(b[Q],$[Q]))return!1;return!0}if(b.constructor===RegExp)return b.source===$.source&&b.flags===$.flags;if(b.valueOf!==Object.prototype.valueOf)return b.valueOf()===$.valueOf();if(b.toString!==Object.prototype.toString)return b.toString()===$.toString();if(X=Object.keys(b),W=X.length,W!==Object.keys($).length)return!1;for(Q=W;Q--!==0;)if(!Object.prototype.hasOwnProperty.call($,X[Q]))return!1;for(Q=W;Q--!==0;){var J=X[Q];if(!w(b[J],$[J]))return!1}return!0}return b!==b&&$!==$}});var IG=N((dT,PG)=>{var T1=PG.exports=function(w,b,$){if(typeof b=="function")$=b,b={};$=b.cb||$;var W=typeof $=="function"?$:$.pre||function(){},Q=$.post||function(){};j6(b,W,Q,w,"",w)};T1.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};T1.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};T1.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};T1.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 j6(w,b,$,W,Q,X,J,G,Y,H){if(W&&typeof W=="object"&&!Array.isArray(W)){b(W,Q,X,J,G,Y,H);for(var z in W){var D=W[z];if(Array.isArray(D)){if(z in T1.arrayKeywords)for(var A=0;A<D.length;A++)j6(w,b,$,D[A],Q+"/"+z+"/"+A,X,Q,z,W,A)}else if(z in T1.propsKeywords){if(D&&typeof D=="object")for(var L in D)j6(w,b,$,D[L],Q+"/"+z+"/"+dU(L),X,Q,z,W,L)}else if(z in T1.keywords||w.allKeys&&!(z in T1.skipKeywords))j6(w,b,$,D,Q+"/"+z,X,Q,z,W)}$(W,Q,X,J,G,Y,H)}}function dU(w){return w.replace(/~/g,"~0").replace(/\//g,"~1")}});var bb=N((RG)=>{Object.defineProperty(RG,"__esModule",{value:!0});RG.getSchemaRefs=RG.resolveUrl=RG.normalizeId=RG._getFullPath=RG.getFullPath=RG.inlineRef=void 0;var oU=t(),tU=g$(),rU=IG(),sU=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function eU(w,b=!0){if(typeof w=="boolean")return!0;if(b===!0)return!i$(w);if(!b)return!1;return NG(w)<=b}RG.inlineRef=eU;var aU=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function i$(w){for(let b in w){if(aU.has(b))return!0;let $=w[b];if(Array.isArray($)&&$.some(i$))return!0;if(typeof $=="object"&&i$($))return!0}return!1}function NG(w){let b=0;for(let $ in w){if($==="$ref")return 1/0;if(b++,sU.has($))continue;if(typeof w[$]=="object")(0,oU.eachItem)(w[$],(W)=>b+=NG(W));if(b===1/0)return 1/0}return b}function EG(w,b="",$){if($!==!1)b=G0(b);let W=w.parse(b);return TG(w,W)}RG.getFullPath=EG;function TG(w,b){return w.serialize(b).split("#")[0]+"#"}RG._getFullPath=TG;var wF=/#\/?$/;function G0(w){return w?w.replace(wF,""):""}RG.normalizeId=G0;function bF(w,b,$){return $=G0($),w.resolve(b,$)}RG.resolveUrl=bF;var $F=/^[a-z_][-a-z0-9._]*$/i;function WF(w,b){if(typeof w=="boolean")return{};let{schemaId:$,uriResolver:W}=this.opts,Q=G0(w[$]||b),X={"":Q},J=EG(W,Q,!1),G={},Y=new Set;return rU(w,{allKeys:!0},(D,A,L,F)=>{if(F===void 0)return;let V=J+A,q=X[F];if(typeof D[$]=="string")q=P.call(this,D[$]);k.call(this,D.$anchor),k.call(this,D.$dynamicAnchor),X[A]=q;function P(S){let l=this.opts.uriResolver.resolve;if(S=G0(q?l(q,S):S),Y.has(S))throw z(S);Y.add(S);let _=this.refs[S];if(typeof _=="string")_=this.refs[_];if(typeof _=="object")H(D,_.schema,S);else if(S!==G0(V))if(S[0]==="#")H(D,G[S],S),G[S]=D;else this.refs[S]=V;return S}function k(S){if(typeof S=="string"){if(!$F.test(S))throw Error(`invalid anchor "${S}"`);P.call(this,`#${S}`)}}}),G;function H(D,A,L){if(A!==void 0&&!tU(D,A))throw z(L)}function z(D){return Error(`reference "${D}" resolves to more than one schema`)}}RG.getSchemaRefs=WF});var Qb=N((nG)=>{Object.defineProperty(nG,"__esModule",{value:!0});nG.getData=nG.KeywordCxt=nG.validateFunctionCode=void 0;var xG=oJ(),vG=wb(),p$=h$(),q6=wb(),HF=HG(),Wb=OG(),n$=jG(),R=c(),x=Y1(),zF=bb(),H1=t(),$b=a0();function BF(w){if(fG(w)){if(uG(w),yG(w)){LF(w);return}}hG(w,()=>(0,xG.topBoolOrEmptySchema)(w))}nG.validateFunctionCode=BF;function hG({gen:w,validateName:b,schema:$,schemaEnv:W,opts:Q},X){if(Q.code.es5)w.func(b,R._`${x.default.data}, ${x.default.valCxt}`,W.$async,()=>{w.code(R._`"use strict"; ${CG($,Q)}`),AF(w,Q),w.code(X)});else w.func(b,R._`${x.default.data}, ${DF(Q)}`,W.$async,()=>w.code(CG($,Q)).code(X))}function DF(w){return R._`{${x.default.instancePath}="", ${x.default.parentData}, ${x.default.parentDataProperty}, ${x.default.rootData}=${x.default.data}${w.dynamicRef?R._`, ${x.default.dynamicAnchors}={}`:R.nil}}={}`}function AF(w,b){w.if(x.default.valCxt,()=>{if(w.var(x.default.instancePath,R._`${x.default.valCxt}.${x.default.instancePath}`),w.var(x.default.parentData,R._`${x.default.valCxt}.${x.default.parentData}`),w.var(x.default.parentDataProperty,R._`${x.default.valCxt}.${x.default.parentDataProperty}`),w.var(x.default.rootData,R._`${x.default.valCxt}.${x.default.rootData}`),b.dynamicRef)w.var(x.default.dynamicAnchors,R._`${x.default.valCxt}.${x.default.dynamicAnchors}`)},()=>{if(w.var(x.default.instancePath,R._`""`),w.var(x.default.parentData,R._`undefined`),w.var(x.default.parentDataProperty,R._`undefined`),w.var(x.default.rootData,x.default.data),b.dynamicRef)w.var(x.default.dynamicAnchors,R._`{}`)})}function LF(w){let{schema:b,opts:$,gen:W}=w;hG(w,()=>{if($.$comment&&b.$comment)mG(w);if(ZF(w),W.let(x.default.vErrors,null),W.let(x.default.errors,0),$.unevaluated)UF(w);cG(w),jF(w)});return}function UF(w){let{gen:b,validateName:$}=w;w.evaluated=b.const("evaluated",R._`${$}.evaluated`),b.if(R._`${w.evaluated}.dynamicProps`,()=>b.assign(R._`${w.evaluated}.props`,R._`undefined`)),b.if(R._`${w.evaluated}.dynamicItems`,()=>b.assign(R._`${w.evaluated}.items`,R._`undefined`))}function CG(w,b){let $=typeof w=="object"&&w[b.schemaId];return $&&(b.code.source||b.code.process)?R._`/*# sourceURL=${$} */`:R.nil}function FF(w,b){if(fG(w)){if(uG(w),yG(w)){KF(w,b);return}}(0,xG.boolOrEmptySchema)(w,b)}function yG({schema:w,self:b}){if(typeof w=="boolean")return!w;for(let $ in w)if(b.RULES.all[$])return!0;return!1}function fG(w){return typeof w.schema!="boolean"}function KF(w,b){let{schema:$,gen:W,opts:Q}=w;if(Q.$comment&&$.$comment)mG(w);MF(w),VF(w);let X=W.const("_errs",x.default.errors);cG(w,X),W.var(b,R._`${X} === ${x.default.errors}`)}function uG(w){(0,H1.checkUnknownRules)(w),OF(w)}function cG(w,b){if(w.opts.jtd)return kG(w,[],!1,b);let $=(0,vG.getSchemaTypes)(w.schema),W=(0,vG.coerceAndCheckDataType)(w,$);kG(w,$,!W,b)}function OF(w){let{schema:b,errSchemaPath:$,opts:W,self:Q}=w;if(b.$ref&&W.ignoreKeywordsWithRef&&(0,H1.schemaHasRulesButRef)(b,Q.RULES))Q.logger.warn(`$ref: keywords ignored in schema at path "${$}"`)}function ZF(w){let{schema:b,opts:$}=w;if(b.default!==void 0&&$.useDefaults&&$.strictSchema)(0,H1.checkStrictMode)(w,"default is ignored in the schema root")}function MF(w){let b=w.schema[w.opts.schemaId];if(b)w.baseId=(0,zF.resolveUrl)(w.opts.uriResolver,w.baseId,b)}function VF(w){if(w.schema.$async&&!w.schemaEnv.$async)throw Error("async schema in sync schema")}function mG({gen:w,schemaEnv:b,schema:$,errSchemaPath:W,opts:Q}){let X=$.$comment;if(Q.$comment===!0)w.code(R._`${x.default.self}.logger.log(${X})`);else if(typeof Q.$comment=="function"){let J=R.str`${W}/$comment`,G=w.scopeValue("root",{ref:b.root});w.code(R._`${x.default.self}.opts.$comment(${X}, ${J}, ${G}.schema)`)}}function jF(w){let{gen:b,schemaEnv:$,validateName:W,ValidationError:Q,opts:X}=w;if($.$async)b.if(R._`${x.default.errors} === 0`,()=>b.return(x.default.data),()=>b.throw(R._`new ${Q}(${x.default.vErrors})`));else{if(b.assign(R._`${W}.errors`,x.default.vErrors),X.unevaluated)qF(w);b.return(R._`${x.default.errors} === 0`)}}function qF({gen:w,evaluated:b,props:$,items:W}){if($ instanceof R.Name)w.assign(R._`${b}.props`,$);if(W instanceof R.Name)w.assign(R._`${b}.items`,W)}function kG(w,b,$,W){let{gen:Q,schema:X,data:J,allErrors:G,opts:Y,self:H}=w,{RULES:z}=H;if(X.$ref&&(Y.ignoreKeywordsWithRef||!(0,H1.schemaHasRulesButRef)(X,z))){Q.block(()=>gG(w,"$ref",z.all.$ref.definition));return}if(!Y.jtd)PF(w,b);Q.block(()=>{for(let A of z.rules)D(A);D(z.post)});function D(A){if(!(0,p$.shouldUseGroup)(X,A))return;if(A.type){if(Q.if((0,q6.checkDataType)(A.type,J,Y.strictNumbers)),_G(w,A),b.length===1&&b[0]===A.type&&$)Q.else(),(0,q6.reportTypeError)(w);Q.endIf()}else _G(w,A);if(!G)Q.if(R._`${x.default.errors} === ${W||0}`)}}function _G(w,b){let{gen:$,schema:W,opts:{useDefaults:Q}}=w;if(Q)(0,HF.assignDefaults)(w,b.type);$.block(()=>{for(let X of b.rules)if((0,p$.shouldUseRule)(W,X))gG(w,X.keyword,X.definition,b.type)})}function PF(w,b){if(w.schemaEnv.meta||!w.opts.strictTypes)return;if(IF(w,b),!w.opts.allowUnionTypes)NF(w,b);EF(w,w.dataTypes)}function IF(w,b){if(!b.length)return;if(!w.dataTypes.length){w.dataTypes=b;return}b.forEach(($)=>{if(!lG(w.dataTypes,$))d$(w,`type "${$}" not allowed by context "${w.dataTypes.join(",")}"`)}),RF(w,b)}function NF(w,b){if(b.length>1&&!(b.length===2&&b.includes("null")))d$(w,"use allowUnionTypes to allow union type keyword")}function EF(w,b){let $=w.self.RULES.all;for(let W in $){let Q=$[W];if(typeof Q=="object"&&(0,p$.shouldUseRule)(w.schema,Q)){let{type:X}=Q.definition;if(X.length&&!X.some((J)=>TF(b,J)))d$(w,`missing type "${X.join(",")}" for keyword "${W}"`)}}}function TF(w,b){return w.includes(b)||b==="number"&&w.includes("integer")}function lG(w,b){return w.includes(b)||b==="integer"&&w.includes("number")}function RF(w,b){let $=[];for(let W of w.dataTypes)if(lG(b,W))$.push(W);else if(b.includes("integer")&&W==="number")$.push("integer");w.dataTypes=$}function d$(w,b){let $=w.schemaEnv.baseId+w.errSchemaPath;b+=` at "${$}" (strictTypes)`,(0,H1.checkStrictMode)(w,b,w.opts.strictTypes)}class o${constructor(w,b,$){if((0,Wb.validateKeywordUsage)(w,b,$),this.gen=w.gen,this.allErrors=w.allErrors,this.keyword=$,this.data=w.data,this.schema=w.schema[$],this.$data=b.$data&&w.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,H1.schemaRefOrVal)(w,this.schema,$,this.$data),this.schemaType=b.schemaType,this.parentSchema=w.schema,this.params={},this.it=w,this.def=b,this.$data)this.schemaCode=w.gen.const("vSchema",iG(this.$data,w));else if(this.schemaCode=this.schemaValue,!(0,Wb.validSchemaType)(this.schema,b.schemaType,b.allowUndefined))throw Error(`${$} value must be ${JSON.stringify(b.schemaType)}`);if("code"in b?b.trackErrors:b.errors!==!1)this.errsCount=w.gen.const("_errs",x.default.errors)}result(w,b,$){this.failResult((0,R.not)(w),b,$)}failResult(w,b,$){if(this.gen.if(w),$)$();else this.error();if(b){if(this.gen.else(),b(),this.allErrors)this.gen.endIf()}else if(this.allErrors)this.gen.endIf();else this.gen.else()}pass(w,b){this.failResult((0,R.not)(w),void 0,b)}fail(w){if(w===void 0){if(this.error(),!this.allErrors)this.gen.if(!1);return}if(this.gen.if(w),this.error(),this.allErrors)this.gen.endIf();else this.gen.else()}fail$data(w){if(!this.$data)return this.fail(w);let{schemaCode:b}=this;this.fail(R._`${b} !== undefined && (${(0,R.or)(this.invalid$data(),w)})`)}error(w,b,$){if(b){this.setParams(b),this._error(w,$),this.setParams({});return}this._error(w,$)}_error(w,b){(w?$b.reportExtraError:$b.reportError)(this,this.def.error,b)}$dataError(){(0,$b.reportError)(this,this.def.$dataError||$b.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error('add "trackErrors" to keyword definition');(0,$b.resetErrorsCount)(this.gen,this.errsCount)}ok(w){if(!this.allErrors)this.gen.if(w)}setParams(w,b){if(b)Object.assign(this.params,w);else this.params=w}block$data(w,b,$=R.nil){this.gen.block(()=>{this.check$data(w,$),b()})}check$data(w=R.nil,b=R.nil){if(!this.$data)return;let{gen:$,schemaCode:W,schemaType:Q,def:X}=this;if($.if((0,R.or)(R._`${W} === undefined`,b)),w!==R.nil)$.assign(w,!0);if(Q.length||X.validateSchema){if($.elseIf(this.invalid$data()),this.$dataError(),w!==R.nil)$.assign(w,!1)}$.else()}invalid$data(){let{gen:w,schemaCode:b,schemaType:$,def:W,it:Q}=this;return(0,R.or)(X(),J());function X(){if($.length){if(!(b instanceof R.Name))throw Error("ajv implementation error");let G=Array.isArray($)?$:[$];return R._`${(0,q6.checkDataTypes)(G,b,Q.opts.strictNumbers,q6.DataType.Wrong)}`}return R.nil}function J(){if(W.validateSchema){let G=w.scopeValue("validate$data",{ref:W.validateSchema});return R._`!${G}(${b})`}return R.nil}}subschema(w,b){let $=(0,n$.getSubschema)(this.it,w);(0,n$.extendSubschemaData)($,this.it,w),(0,n$.extendSubschemaMode)($,w);let W={...this.it,...$,items:void 0,props:void 0};return FF(W,b),W}mergeEvaluated(w,b){let{it:$,gen:W}=this;if(!$.opts.unevaluated)return;if($.props!==!0&&w.props!==void 0)$.props=H1.mergeEvaluated.props(W,w.props,$.props,b);if($.items!==!0&&w.items!==void 0)$.items=H1.mergeEvaluated.items(W,w.items,$.items,b)}mergeValidEvaluated(w,b){let{it:$,gen:W}=this;if($.opts.unevaluated&&($.props!==!0||$.items!==!0))return W.if(b,()=>this.mergeEvaluated(w,R.Name)),!0}}nG.KeywordCxt=o$;function gG(w,b,$,W){let Q=new o$(w,$,b);if("code"in $)$.code(Q,W);else if(Q.$data&&$.validate)(0,Wb.funcKeywordCode)(Q,$);else if("macro"in $)(0,Wb.macroKeywordCode)(Q,$);else if($.compile||$.validate)(0,Wb.funcKeywordCode)(Q,$)}var SF=/^\/(?:[^~]|~0|~1)*$/,vF=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function iG(w,{dataLevel:b,dataNames:$,dataPathArr:W}){let Q,X;if(w==="")return x.default.rootData;if(w[0]==="/"){if(!SF.test(w))throw Error(`Invalid JSON-pointer: ${w}`);Q=w,X=x.default.rootData}else{let H=vF.exec(w);if(!H)throw Error(`Invalid JSON-pointer: ${w}`);let z=+H[1];if(Q=H[2],Q==="#"){if(z>=b)throw Error(Y("property/index",z));return W[b-z]}if(z>b)throw Error(Y("data",z));if(X=$[b-z],!Q)return X}let J=X,G=Q.split("/");for(let H of G)if(H)X=R._`${X}${(0,R.getProperty)((0,H1.unescapeJsonPointer)(H))}`,J=R._`${J} && ${X}`;return J;function Y(H,z){return`Cannot access ${H} ${z} levels up, current level is ${b}`}}nG.getData=iG});var P6=N((oG)=>{Object.defineProperty(oG,"__esModule",{value:!0});class dG extends Error{constructor(w){super("validation failed");this.errors=w,this.ajv=this.validation=!0}}oG.default=dG});var Xb=N((rG)=>{Object.defineProperty(rG,"__esModule",{value:!0});var t$=bb();class tG extends Error{constructor(w,b,$,W){super(W||`can't resolve reference ${$} from id ${b}`);this.missingRef=(0,t$.resolveUrl)(w,b,$),this.missingSchema=(0,t$.normalizeId)((0,t$.getFullPath)(w,this.missingRef))}}rG.default=tG});var N6=N((aG)=>{Object.defineProperty(aG,"__esModule",{value:!0});aG.resolveSchema=aG.getCompilingSchema=aG.resolveRef=aG.compileSchema=aG.SchemaEnv=void 0;var iw=c(),hF=P6(),u1=Y1(),nw=bb(),sG=t(),yF=Qb();class Jb{constructor(w){var b;this.refs={},this.dynamicAnchors={};let $;if(typeof w.schema=="object")$=w.schema;this.schema=w.schema,this.schemaId=w.schemaId,this.root=w.root||this,this.baseId=(b=w.baseId)!==null&&b!==void 0?b:(0,nw.normalizeId)($===null||$===void 0?void 0:$[w.schemaId||"$id"]),this.schemaPath=w.schemaPath,this.localRefs=w.localRefs,this.meta=w.meta,this.$async=$===null||$===void 0?void 0:$.$async,this.refs={}}}aG.SchemaEnv=Jb;function s$(w){let b=eG.call(this,w);if(b)return b;let $=(0,nw.getFullPath)(this.opts.uriResolver,w.root.baseId),{es5:W,lines:Q}=this.opts.code,{ownProperties:X}=this.opts,J=new iw.CodeGen(this.scope,{es5:W,lines:Q,ownProperties:X}),G;if(w.$async)G=J.scopeValue("Error",{ref:hF.default,code:iw._`require("ajv/dist/runtime/validation_error").default`});let Y=J.scopeName("validate");w.validateName=Y;let H={gen:J,allErrors:this.opts.allErrors,data:u1.default.data,parentData:u1.default.parentData,parentDataProperty:u1.default.parentDataProperty,dataNames:[u1.default.data],dataPathArr:[iw.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:J.scopeValue("schema",this.opts.code.source===!0?{ref:w.schema,code:(0,iw.stringify)(w.schema)}:{ref:w.schema}),validateName:Y,ValidationError:G,schema:w.schema,schemaEnv:w,rootId:$,baseId:w.baseId||$,schemaPath:iw.nil,errSchemaPath:w.schemaPath||(this.opts.jtd?"":"#"),errorPath:iw._`""`,opts:this.opts,self:this},z;try{this._compilations.add(w),(0,yF.validateFunctionCode)(H),J.optimize(this.opts.code.optimize);let D=J.toString();if(z=`${J.scopeRefs(u1.default.scope)}return ${D}`,this.opts.code.process)z=this.opts.code.process(z,w);let L=Function(`${u1.default.self}`,`${u1.default.scope}`,z)(this,this.scope.get());if(this.scope.value(Y,{ref:L}),L.errors=null,L.schema=w.schema,L.schemaEnv=w,w.$async)L.$async=!0;if(this.opts.code.source===!0)L.source={validateName:Y,validateCode:D,scopeValues:J._values};if(this.opts.unevaluated){let{props:F,items:V}=H;if(L.evaluated={props:F instanceof iw.Name?void 0:F,items:V instanceof iw.Name?void 0:V,dynamicProps:F instanceof iw.Name,dynamicItems:V instanceof iw.Name},L.source)L.source.evaluated=(0,iw.stringify)(L.evaluated)}return w.validate=L,w}catch(D){if(delete w.validate,delete w.validateName,z)this.logger.error("Error compiling schema, function code:",z);throw D}finally{this._compilations.delete(w)}}aG.compileSchema=s$;function fF(w,b,$){var W;$=(0,nw.resolveUrl)(this.opts.uriResolver,b,$);let Q=w.refs[$];if(Q)return Q;let X=mF.call(this,w,$);if(X===void 0){let J=(W=w.localRefs)===null||W===void 0?void 0:W[$],{schemaId:G}=this.opts;if(J)X=new Jb({schema:J,schemaId:G,root:w,baseId:b})}if(X===void 0)return;return w.refs[$]=uF.call(this,X)}aG.resolveRef=fF;function uF(w){if((0,nw.inlineRef)(w.schema,this.opts.inlineRefs))return w.schema;return w.validate?w:s$.call(this,w)}function eG(w){for(let b of this._compilations)if(cF(b,w))return b}aG.getCompilingSchema=eG;function cF(w,b){return w.schema===b.schema&&w.root===b.root&&w.baseId===b.baseId}function mF(w,b){let $;while(typeof($=this.refs[b])=="string")b=$;return $||this.schemas[b]||I6.call(this,w,b)}function I6(w,b){let $=this.opts.uriResolver.parse(b),W=(0,nw._getFullPath)(this.opts.uriResolver,$),Q=(0,nw.getFullPath)(this.opts.uriResolver,w.baseId,void 0);if(Object.keys(w.schema).length>0&&W===Q)return r$.call(this,$,w);let X=(0,nw.normalizeId)(W),J=this.refs[X]||this.schemas[X];if(typeof J=="string"){let G=I6.call(this,w,J);if(typeof(G===null||G===void 0?void 0:G.schema)!=="object")return;return r$.call(this,$,G)}if(typeof(J===null||J===void 0?void 0:J.schema)!=="object")return;if(!J.validate)s$.call(this,J);if(X===(0,nw.normalizeId)(b)){let{schema:G}=J,{schemaId:Y}=this.opts,H=G[Y];if(H)Q=(0,nw.resolveUrl)(this.opts.uriResolver,Q,H);return new Jb({schema:G,schemaId:Y,root:w,baseId:Q})}return r$.call(this,$,J)}aG.resolveSchema=I6;var lF=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function r$(w,{baseId:b,schema:$,root:W}){var Q;if(((Q=w.fragment)===null||Q===void 0?void 0:Q[0])!=="/")return;for(let G of w.fragment.slice(1).split("/")){if(typeof $==="boolean")return;let Y=$[(0,sG.unescapeFragment)(G)];if(Y===void 0)return;$=Y;let H=typeof $==="object"&&$[this.opts.schemaId];if(!lF.has(G)&&H)b=(0,nw.resolveUrl)(this.opts.uriResolver,b,H)}let X;if(typeof $!="boolean"&&$.$ref&&!(0,sG.schemaHasRulesButRef)($,this.RULES)){let G=(0,nw.resolveUrl)(this.opts.uriResolver,b,$.$ref);X=I6.call(this,W,G)}let{schemaId:J}=this.opts;if(X=X||new Jb({schema:$,schemaId:J,root:W,baseId:b}),X.schema!==X.root.schema)return X;return}});var bY=N((aT,dF)=>{dF.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 a$=N((wR,XY)=>{var oF=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),WY=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 e$(w){let b="",$=0,W=0;for(W=0;W<w.length;W++){if($=w[W].charCodeAt(0),$===48)continue;if(!($>=48&&$<=57||$>=65&&$<=70||$>=97&&$<=102))return"";b+=w[W];break}for(W+=1;W<w.length;W++){if($=w[W].charCodeAt(0),!($>=48&&$<=57||$>=65&&$<=70||$>=97&&$<=102))return"";b+=w[W]}return b}var tF=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function $Y(w){return w.length=0,!0}function rF(w,b,$){if(w.length){let W=e$(w);if(W!=="")b.push(W);else return $.error=!0,!1;w.length=0}return!0}function sF(w){let b=0,$={error:!1,address:"",zone:""},W=[],Q=[],X=!1,J=!1,G=rF;for(let Y=0;Y<w.length;Y++){let H=w[Y];if(H==="["||H==="]")continue;if(H===":"){if(X===!0)J=!0;if(!G(Q,W,$))break;if(++b>7){$.error=!0;break}if(Y>0&&w[Y-1]===":")X=!0;W.push(":");continue}else if(H==="%"){if(!G(Q,W,$))break;G=$Y}else{Q.push(H);continue}}if(Q.length)if(G===$Y)$.zone=Q.join("");else if(J)W.push(Q.join(""));else W.push(e$(Q));return $.address=W.join(""),$}function QY(w){if(eF(w,":")<2)return{host:w,isIPV6:!1};let b=sF(w);if(!b.error){let{address:$,address:W}=b;if(b.zone)$+="%"+b.zone,W+="%25"+b.zone;return{host:$,isIPV6:!0,escapedHost:W}}else return{host:w,isIPV6:!1}}function eF(w,b){let $=0;for(let W=0;W<w.length;W++)if(w[W]===b)$++;return $}function aF(w){let b=w,$=[],W=-1,Q=0;while(Q=b.length){if(Q===1)if(b===".")break;else if(b==="/"){$.push("/");break}else{$.push(b);break}else if(Q===2){if(b[0]==="."){if(b[1]===".")break;else if(b[1]==="/"){b=b.slice(2);continue}}else if(b[0]==="/"){if(b[1]==="."||b[1]==="/"){$.push("/");break}}}else if(Q===3){if(b==="/.."){if($.length!==0)$.pop();$.push("/");break}}if(b[0]==="."){if(b[1]==="."){if(b[2]==="/"){b=b.slice(3);continue}}else if(b[1]==="/"){b=b.slice(2);continue}}else if(b[0]==="/"){if(b[1]==="."){if(b[2]==="/"){b=b.slice(2);continue}else if(b[2]==="."){if(b[3]==="/"){if(b=b.slice(3),$.length!==0)$.pop();continue}}}}if((W=b.indexOf("/",1))===-1){$.push(b);break}else $.push(b.slice(0,W)),b=b.slice(W)}return $.join("")}function wK(w,b){let $=b!==!0?escape:unescape;if(w.scheme!==void 0)w.scheme=$(w.scheme);if(w.userinfo!==void 0)w.userinfo=$(w.userinfo);if(w.host!==void 0)w.host=$(w.host);if(w.path!==void 0)w.path=$(w.path);if(w.query!==void 0)w.query=$(w.query);if(w.fragment!==void 0)w.fragment=$(w.fragment);return w}function bK(w){let b=[];if(w.userinfo!==void 0)b.push(w.userinfo),b.push("@");if(w.host!==void 0){let $=unescape(w.host);if(!WY($)){let W=QY($);if(W.isIPV6===!0)$=`[${W.escapedHost}]`;else $=w.host}b.push($)}if(typeof w.port==="number"||typeof w.port==="string")b.push(":"),b.push(String(w.port));return b.length?b.join(""):void 0}XY.exports={nonSimpleDomain:tF,recomposeAuthority:bK,normalizeComponentEncoding:wK,removeDotSegments:aF,isIPv4:WY,isUUID:oF,normalizeIPv6:QY,stringArrayToHexStripped:e$}});var zY=N((bR,HY)=>{var{isUUID:$K}=a$(),WK=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,QK=["http","https","ws","wss","urn","urn:uuid"];function XK(w){return QK.indexOf(w)!==-1}function w9(w){if(w.secure===!0)return!0;else if(w.secure===!1)return!1;else if(w.scheme)return w.scheme.length===3&&(w.scheme[0]==="w"||w.scheme[0]==="W")&&(w.scheme[1]==="s"||w.scheme[1]==="S")&&(w.scheme[2]==="s"||w.scheme[2]==="S");else return!1}function JY(w){if(!w.host)w.error=w.error||"HTTP URIs must have a host.";return w}function GY(w){let b=String(w.scheme).toLowerCase()==="https";if(w.port===(b?443:80)||w.port==="")w.port=void 0;if(!w.path)w.path="/";return w}function JK(w){return w.secure=w9(w),w.resourceName=(w.path||"/")+(w.query?"?"+w.query:""),w.path=void 0,w.query=void 0,w}function GK(w){if(w.port===(w9(w)?443:80)||w.port==="")w.port=void 0;if(typeof w.secure==="boolean")w.scheme=w.secure?"wss":"ws",w.secure=void 0;if(w.resourceName){let[b,$]=w.resourceName.split("?");w.path=b&&b!=="/"?b:void 0,w.query=$,w.resourceName=void 0}return w.fragment=void 0,w}function YK(w,b){if(!w.path)return w.error="URN can not be parsed",w;let $=w.path.match(WK);if($){let W=b.scheme||w.scheme||"urn";w.nid=$[1].toLowerCase(),w.nss=$[2];let Q=`${W}:${b.nid||w.nid}`,X=b9(Q);if(w.path=void 0,X)w=X.parse(w,b)}else w.error=w.error||"URN can not be parsed.";return w}function HK(w,b){if(w.nid===void 0)throw Error("URN without nid cannot be serialized");let $=b.scheme||w.scheme||"urn",W=w.nid.toLowerCase(),Q=`${$}:${b.nid||W}`,X=b9(Q);if(X)w=X.serialize(w,b);let J=w,G=w.nss;return J.path=`${W||b.nid}:${G}`,b.skipEscape=!0,J}function zK(w,b){let $=w;if($.uuid=$.nss,$.nss=void 0,!b.tolerant&&(!$.uuid||!$K($.uuid)))$.error=$.error||"UUID is not valid.";return $}function BK(w){let b=w;return b.nss=(w.uuid||"").toLowerCase(),b}var YY={scheme:"http",domainHost:!0,parse:JY,serialize:GY},DK={scheme:"https",domainHost:YY.domainHost,parse:JY,serialize:GY},E6={scheme:"ws",domainHost:!0,parse:JK,serialize:GK},AK={scheme:"wss",domainHost:E6.domainHost,parse:E6.parse,serialize:E6.serialize},LK={scheme:"urn",parse:YK,serialize:HK,skipNormalize:!0},UK={scheme:"urn:uuid",parse:zK,serialize:BK,skipNormalize:!0},T6={http:YY,https:DK,ws:E6,wss:AK,urn:LK,"urn:uuid":UK};Object.setPrototypeOf(T6,null);function b9(w){return w&&(T6[w]||T6[w.toLowerCase()])||void 0}HY.exports={wsIsSecure:w9,SCHEMES:T6,isValidSchemeName:XK,getSchemeHandler:b9}});var AY=N(($R,S6)=>{var{normalizeIPv6:FK,removeDotSegments:Gb,recomposeAuthority:KK,normalizeComponentEncoding:R6,isIPv4:OK,nonSimpleDomain:ZK}=a$(),{SCHEMES:MK,getSchemeHandler:BY}=zY();function VK(w,b){if(typeof w==="string")w=aw(z1(w,b),b);else if(typeof w==="object")w=z1(aw(w,b),b);return w}function jK(w,b,$){let W=$?Object.assign({scheme:"null"},$):{scheme:"null"},Q=DY(z1(w,W),z1(b,W),W,!0);return W.skipEscape=!0,aw(Q,W)}function DY(w,b,$,W){let Q={};if(!W)w=z1(aw(w,$),$),b=z1(aw(b,$),$);if($=$||{},!$.tolerant&&b.scheme)Q.scheme=b.scheme,Q.userinfo=b.userinfo,Q.host=b.host,Q.port=b.port,Q.path=Gb(b.path||""),Q.query=b.query;else{if(b.userinfo!==void 0||b.host!==void 0||b.port!==void 0)Q.userinfo=b.userinfo,Q.host=b.host,Q.port=b.port,Q.path=Gb(b.path||""),Q.query=b.query;else{if(!b.path)if(Q.path=w.path,b.query!==void 0)Q.query=b.query;else Q.query=w.query;else{if(b.path[0]==="/")Q.path=Gb(b.path);else{if((w.userinfo!==void 0||w.host!==void 0||w.port!==void 0)&&!w.path)Q.path="/"+b.path;else if(!w.path)Q.path=b.path;else Q.path=w.path.slice(0,w.path.lastIndexOf("/")+1)+b.path;Q.path=Gb(Q.path)}Q.query=b.query}Q.userinfo=w.userinfo,Q.host=w.host,Q.port=w.port}Q.scheme=w.scheme}return Q.fragment=b.fragment,Q}function qK(w,b,$){if(typeof w==="string")w=unescape(w),w=aw(R6(z1(w,$),!0),{...$,skipEscape:!0});else if(typeof w==="object")w=aw(R6(w,!0),{...$,skipEscape:!0});if(typeof b==="string")b=unescape(b),b=aw(R6(z1(b,$),!0),{...$,skipEscape:!0});else if(typeof b==="object")b=aw(R6(b,!0),{...$,skipEscape:!0});return w.toLowerCase()===b.toLowerCase()}function aw(w,b){let $={host:w.host,scheme:w.scheme,userinfo:w.userinfo,port:w.port,path:w.path,query:w.query,nid:w.nid,nss:w.nss,uuid:w.uuid,fragment:w.fragment,reference:w.reference,resourceName:w.resourceName,secure:w.secure,error:""},W=Object.assign({},b),Q=[],X=BY(W.scheme||$.scheme);if(X&&X.serialize)X.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 J=KK($);if(J!==void 0){if(W.reference!=="suffix")Q.push("//");if(Q.push(J),$.path&&$.path[0]!=="/")Q.push("/")}if($.path!==void 0){let G=$.path;if(!W.absolutePath&&(!X||!X.absolutePath))G=Gb(G);if(J===void 0&&G[0]==="/"&&G[1]==="/")G="/%2F"+G.slice(2);Q.push(G)}if($.query!==void 0)Q.push("?",$.query);if($.fragment!==void 0)Q.push("#",$.fragment);return Q.join("")}var PK=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function z1(w,b){let $=Object.assign({},b),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)w=$.scheme+":"+w;else w="//"+w;let X=w.match(PK);if(X){if(W.scheme=X[1],W.userinfo=X[3],W.host=X[4],W.port=parseInt(X[5],10),W.path=X[6]||"",W.query=X[7],W.fragment=X[8],isNaN(W.port))W.port=X[5];if(W.host)if(OK(W.host)===!1){let Y=FK(W.host);W.host=Y.host.toLowerCase(),Q=Y.isIPV6}else Q=!0;if(W.scheme===void 0&&W.userinfo===void 0&&W.host===void 0&&W.port===void 0&&W.query===void 0&&!W.path)W.reference="same-document";else if(W.scheme===void 0)W.reference="relative";else if(W.fragment===void 0)W.reference="absolute";else W.reference="uri";if($.reference&&$.reference!=="suffix"&&$.reference!==W.reference)W.error=W.error||"URI is not a "+$.reference+" reference.";let J=BY($.scheme||W.scheme);if(!$.unicodeSupport&&(!J||!J.unicodeSupport)){if(W.host&&($.domainHost||J&&J.domainHost)&&Q===!1&&ZK(W.host))try{W.host=URL.domainToASCII(W.host.toLowerCase())}catch(G){W.error=W.error||"Host's domain name can not be converted to ASCII: "+G}}if(!J||J&&!J.skipNormalize){if(w.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(J&&J.parse)J.parse(W,$)}else W.error=W.error||"URI can not be parsed.";return W}var $9={SCHEMES:MK,normalize:VK,resolve:jK,resolveComponent:DY,equal:qK,serialize:aw,parse:z1};S6.exports=$9;S6.exports.default=$9;S6.exports.fastUri=$9});var FY=N((UY)=>{Object.defineProperty(UY,"__esModule",{value:!0});var LY=AY();LY.code='require("ajv/dist/runtime/uri").default';UY.default=LY});var PY=N((B1)=>{Object.defineProperty(B1,"__esModule",{value:!0});B1.CodeGen=B1.Name=B1.nil=B1.stringify=B1.str=B1._=B1.KeywordCxt=void 0;var NK=Qb();Object.defineProperty(B1,"KeywordCxt",{enumerable:!0,get:function(){return NK.KeywordCxt}});var Y0=c();Object.defineProperty(B1,"_",{enumerable:!0,get:function(){return Y0._}});Object.defineProperty(B1,"str",{enumerable:!0,get:function(){return Y0.str}});Object.defineProperty(B1,"stringify",{enumerable:!0,get:function(){return Y0.stringify}});Object.defineProperty(B1,"nil",{enumerable:!0,get:function(){return Y0.nil}});Object.defineProperty(B1,"Name",{enumerable:!0,get:function(){return Y0.Name}});Object.defineProperty(B1,"CodeGen",{enumerable:!0,get:function(){return Y0.CodeGen}});var EK=P6(),VY=Xb(),TK=x$(),Yb=N6(),RK=c(),Hb=bb(),v6=wb(),Q9=t(),KY=bY(),SK=FY(),jY=(w,b)=>new RegExp(w,b);jY.code="new RegExp";var vK=["removeAdditional","useDefaults","coerceTypes"],CK=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),kK={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."},_K={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},OY=200;function xK(w){var b,$,W,Q,X,J,G,Y,H,z,D,A,L,F,V,q,P,k,S,l,_,rw,$1,B4,D4;let q0=w.strict,A4=(b=w.code)===null||b===void 0?void 0:b.optimize,YW=A4===!0||A4===void 0?1:A4||0,HW=(W=($=w.code)===null||$===void 0?void 0:$.regExp)!==null&&W!==void 0?W:jY,Cz=(Q=w.uriResolver)!==null&&Q!==void 0?Q:SK.default;return{strictSchema:(J=(X=w.strictSchema)!==null&&X!==void 0?X:q0)!==null&&J!==void 0?J:!0,strictNumbers:(Y=(G=w.strictNumbers)!==null&&G!==void 0?G:q0)!==null&&Y!==void 0?Y:!0,strictTypes:(z=(H=w.strictTypes)!==null&&H!==void 0?H:q0)!==null&&z!==void 0?z:"log",strictTuples:(A=(D=w.strictTuples)!==null&&D!==void 0?D:q0)!==null&&A!==void 0?A:"log",strictRequired:(F=(L=w.strictRequired)!==null&&L!==void 0?L:q0)!==null&&F!==void 0?F:!1,code:w.code?{...w.code,optimize:YW,regExp:HW}:{optimize:YW,regExp:HW},loopRequired:(V=w.loopRequired)!==null&&V!==void 0?V:OY,loopEnum:(q=w.loopEnum)!==null&&q!==void 0?q:OY,meta:(P=w.meta)!==null&&P!==void 0?P:!0,messages:(k=w.messages)!==null&&k!==void 0?k:!0,inlineRefs:(S=w.inlineRefs)!==null&&S!==void 0?S:!0,schemaId:(l=w.schemaId)!==null&&l!==void 0?l:"$id",addUsedSchema:(_=w.addUsedSchema)!==null&&_!==void 0?_:!0,validateSchema:(rw=w.validateSchema)!==null&&rw!==void 0?rw:!0,validateFormats:($1=w.validateFormats)!==null&&$1!==void 0?$1:!0,unicodeRegExp:(B4=w.unicodeRegExp)!==null&&B4!==void 0?B4:!0,int32range:(D4=w.int32range)!==null&&D4!==void 0?D4:!0,uriResolver:Cz}}class C6{constructor(w={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,w=this.opts={...w,...xK(w)};let{es5:b,lines:$}=this.opts.code;this.scope=new RK.ValueScope({scope:{},prefixes:CK,es5:b,lines:$}),this.logger=mK(w.logger);let W=w.validateFormats;if(w.validateFormats=!1,this.RULES=(0,TK.getRules)(),ZY.call(this,kK,w,"NOT SUPPORTED"),ZY.call(this,_K,w,"DEPRECATED","warn"),this._metaOpts=uK.call(this),w.formats)yK.call(this);if(this._addVocabularies(),this._addDefaultMetaSchema(),w.keywords)fK.call(this,w.keywords);if(typeof w.meta=="object")this.addMetaSchema(w.meta);hK.call(this),w.validateFormats=W}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:w,meta:b,schemaId:$}=this.opts,W=KY;if($==="id")W={...KY},W.id=W.$id,delete W.$id;if(b&&w)this.addMetaSchema(W,W[$],!1)}defaultMeta(){let{meta:w,schemaId:b}=this.opts;return this.opts.defaultMeta=typeof w=="object"?w[b]||w:void 0}validate(w,b){let $;if(typeof w=="string"){if($=this.getSchema(w),!$)throw Error(`no schema with key or ref "${w}"`)}else $=this.compile(w);let W=$(b);if(!("$async"in $))this.errors=$.errors;return W}compile(w,b){let $=this._addSchema(w,b);return $.validate||this._compileSchemaEnv($)}compileAsync(w,b){if(typeof this.opts.loadSchema!="function")throw Error("options.loadSchema should be a function");let{loadSchema:$}=this.opts;return W.call(this,w,b);async function W(H,z){await Q.call(this,H.$schema);let D=this._addSchema(H,z);return D.validate||X.call(this,D)}async function Q(H){if(H&&!this.getSchema(H))await W.call(this,{$ref:H},!0)}async function X(H){try{return this._compileSchemaEnv(H)}catch(z){if(!(z instanceof VY.default))throw z;return J.call(this,z),await G.call(this,z.missingSchema),X.call(this,H)}}function J({missingSchema:H,missingRef:z}){if(this.refs[H])throw Error(`AnySchema ${H} is loaded but ${z} cannot be resolved`)}async function G(H){let z=await Y.call(this,H);if(!this.refs[H])await Q.call(this,z.$schema);if(!this.refs[H])this.addSchema(z,H,b)}async function Y(H){let z=this._loading[H];if(z)return z;try{return await(this._loading[H]=$(H))}finally{delete this._loading[H]}}}addSchema(w,b,$,W=this.opts.validateSchema){if(Array.isArray(w)){for(let X of w)this.addSchema(X,void 0,$,W);return this}let Q;if(typeof w==="object"){let{schemaId:X}=this.opts;if(Q=w[X],Q!==void 0&&typeof Q!="string")throw Error(`schema ${X} must be string`)}return b=(0,Hb.normalizeId)(b||Q),this._checkUnique(b),this.schemas[b]=this._addSchema(w,$,b,W,!0),this}addMetaSchema(w,b,$=this.opts.validateSchema){return this.addSchema(w,b,!0,$),this}validateSchema(w,b){if(typeof w=="boolean")return!0;let $;if($=w.$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($,w);if(!W&&b){let Q="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(Q);else throw Error(Q)}return W}getSchema(w){let b;while(typeof(b=MY.call(this,w))=="string")w=b;if(b===void 0){let{schemaId:$}=this.opts,W=new Yb.SchemaEnv({schema:{},schemaId:$});if(b=Yb.resolveSchema.call(this,W,w),!b)return;this.refs[w]=b}return b.validate||this._compileSchemaEnv(b)}removeSchema(w){if(w instanceof RegExp)return this._removeAllSchemas(this.schemas,w),this._removeAllSchemas(this.refs,w),this;switch(typeof w){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let b=MY.call(this,w);if(typeof b=="object")this._cache.delete(b.schema);return delete this.schemas[w],delete this.refs[w],this}case"object":{let b=w;this._cache.delete(b);let $=w[this.opts.schemaId];if($)$=(0,Hb.normalizeId)($),delete this.schemas[$],delete this.refs[$];return this}default:throw Error("ajv.removeSchema: invalid parameter")}}addVocabulary(w){for(let b of w)this.addKeyword(b);return this}addKeyword(w,b){let $;if(typeof w=="string"){if($=w,typeof b=="object")this.logger.warn("these parameters are deprecated, see docs for addKeyword"),b.keyword=$}else if(typeof w=="object"&&b===void 0){if(b=w,$=b.keyword,Array.isArray($)&&!$.length)throw Error("addKeywords: keyword must be string or non-empty array")}else throw Error("invalid addKeywords parameters");if(gK.call(this,$,b),!b)return(0,Q9.eachItem)($,(Q)=>W9.call(this,Q)),this;nK.call(this,b);let W={...b,type:(0,v6.getJSONTypes)(b.type),schemaType:(0,v6.getJSONTypes)(b.schemaType)};return(0,Q9.eachItem)($,W.type.length===0?(Q)=>W9.call(this,Q,W):(Q)=>W.type.forEach((X)=>W9.call(this,Q,W,X))),this}getKeyword(w){let b=this.RULES.all[w];return typeof b=="object"?b.definition:!!b}removeKeyword(w){let{RULES:b}=this;delete b.keywords[w],delete b.all[w];for(let $ of b.rules){let W=$.rules.findIndex((Q)=>Q.keyword===w);if(W>=0)$.rules.splice(W,1)}return this}addFormat(w,b){if(typeof b=="string")b=new RegExp(b);return this.formats[w]=b,this}errorsText(w=this.errors,{separator:b=", ",dataVar:$="data"}={}){if(!w||w.length===0)return"No errors";return w.map((W)=>`${$}${W.instancePath} ${W.message}`).reduce((W,Q)=>W+b+Q)}$dataMetaSchema(w,b){let $=this.RULES.all;w=JSON.parse(JSON.stringify(w));for(let W of b){let Q=W.split("/").slice(1),X=w;for(let J of Q)X=X[J];for(let J in $){let G=$[J];if(typeof G!="object")continue;let{$data:Y}=G.definition,H=X[J];if(Y&&H)X[J]=qY(H)}}return w}_removeAllSchemas(w,b){for(let $ in w){let W=w[$];if(!b||b.test($)){if(typeof W=="string")delete w[$];else if(W&&!W.meta)this._cache.delete(W.schema),delete w[$]}}}_addSchema(w,b,$,W=this.opts.validateSchema,Q=this.opts.addUsedSchema){let X,{schemaId:J}=this.opts;if(typeof w=="object")X=w[J];else if(this.opts.jtd)throw Error("schema must be object");else if(typeof w!="boolean")throw Error("schema must be object or boolean");let G=this._cache.get(w);if(G!==void 0)return G;$=(0,Hb.normalizeId)(X||$);let Y=Hb.getSchemaRefs.call(this,w,$);if(G=new Yb.SchemaEnv({schema:w,schemaId:J,meta:b,baseId:$,localRefs:Y}),this._cache.set(G.schema,G),Q&&!$.startsWith("#")){if($)this._checkUnique($);this.refs[$]=G}if(W)this.validateSchema(w,!0);return G}_checkUnique(w){if(this.schemas[w]||this.refs[w])throw Error(`schema with key or id "${w}" already exists`)}_compileSchemaEnv(w){if(w.meta)this._compileMetaSchema(w);else Yb.compileSchema.call(this,w);if(!w.validate)throw Error("ajv implementation error");return w.validate}_compileMetaSchema(w){let b=this.opts;this.opts=this._metaOpts;try{Yb.compileSchema.call(this,w)}finally{this.opts=b}}}C6.ValidationError=EK.default;C6.MissingRefError=VY.default;B1.default=C6;function ZY(w,b,$,W="error"){for(let Q in w){let X=Q;if(X in b)this.logger[W](`${$}: option ${Q}. ${w[X]}`)}}function MY(w){return w=(0,Hb.normalizeId)(w),this.schemas[w]||this.refs[w]}function hK(){let w=this.opts.schemas;if(!w)return;if(Array.isArray(w))this.addSchema(w);else for(let b in w)this.addSchema(w[b],b)}function yK(){for(let w in this.opts.formats){let b=this.opts.formats[w];if(b)this.addFormat(w,b)}}function fK(w){if(Array.isArray(w)){this.addVocabulary(w);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let b in w){let $=w[b];if(!$.keyword)$.keyword=b;this.addKeyword($)}}function uK(){let w={...this.opts};for(let b of vK)delete w[b];return w}var cK={log(){},warn(){},error(){}};function mK(w){if(w===!1)return cK;if(w===void 0)return console;if(w.log&&w.warn&&w.error)return w;throw Error("logger must implement log, warn and error methods")}var lK=/^[a-z_$][a-z0-9_$:-]*$/i;function gK(w,b){let{RULES:$}=this;if((0,Q9.eachItem)(w,(W)=>{if($.keywords[W])throw Error(`Keyword ${W} is already defined`);if(!lK.test(W))throw Error(`Keyword ${W} has invalid name`)}),!b)return;if(b.$data&&!(("code"in b)||("validate"in b)))throw Error('$data keyword must have "code" or "validate" function')}function W9(w,b,$){var W;let Q=b===null||b===void 0?void 0:b.post;if($&&Q)throw Error('keyword with "post" flag cannot have "type"');let{RULES:X}=this,J=Q?X.post:X.rules.find(({type:Y})=>Y===$);if(!J)J={type:$,rules:[]},X.rules.push(J);if(X.keywords[w]=!0,!b)return;let G={keyword:w,definition:{...b,type:(0,v6.getJSONTypes)(b.type),schemaType:(0,v6.getJSONTypes)(b.schemaType)}};if(b.before)iK.call(this,J,G,b.before);else J.rules.push(G);X.all[w]=G,(W=b.implements)===null||W===void 0||W.forEach((Y)=>this.addKeyword(Y))}function iK(w,b,$){let W=w.rules.findIndex((Q)=>Q.keyword===$);if(W>=0)w.rules.splice(W,0,b);else w.rules.push(b),this.logger.warn(`rule ${$} is not defined`)}function nK(w){let{metaSchema:b}=w;if(b===void 0)return;if(w.$data&&this.opts.$data)b=qY(b);w.validateSchema=this.compile(b,!0)}var pK={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function qY(w){return{anyOf:[w,pK]}}});var NY=N((IY)=>{Object.defineProperty(IY,"__esModule",{value:!0});var tK={keyword:"id",code(){throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};IY.default=tK});var CY=N((SY)=>{Object.defineProperty(SY,"__esModule",{value:!0});SY.callRef=SY.getValidate=void 0;var sK=Xb(),EY=fw(),Tw=c(),H0=Y1(),TY=N6(),k6=t(),eK={keyword:"$ref",schemaType:"string",code(w){let{gen:b,schema:$,it:W}=w,{baseId:Q,schemaEnv:X,validateName:J,opts:G,self:Y}=W,{root:H}=X;if(($==="#"||$==="#/")&&Q===H.baseId)return D();let z=TY.resolveRef.call(Y,H,Q,$);if(z===void 0)throw new sK.default(W.opts.uriResolver,Q,$);if(z instanceof TY.SchemaEnv)return A(z);return L(z);function D(){if(X===H)return _6(w,J,X,X.$async);let F=b.scopeValue("root",{ref:H});return _6(w,Tw._`${F}.validate`,H,H.$async)}function A(F){let V=RY(w,F);_6(w,V,F,F.$async)}function L(F){let V=b.scopeValue("schema",G.code.source===!0?{ref:F,code:(0,Tw.stringify)(F)}:{ref:F}),q=b.name("valid"),P=w.subschema({schema:F,dataTypes:[],schemaPath:Tw.nil,topSchemaRef:V,errSchemaPath:$},q);w.mergeEvaluated(P),w.ok(q)}}};function RY(w,b){let{gen:$}=w;return b.validate?$.scopeValue("validate",{ref:b.validate}):Tw._`${$.scopeValue("wrapper",{ref:b})}.validate`}SY.getValidate=RY;function _6(w,b,$,W){let{gen:Q,it:X}=w,{allErrors:J,schemaEnv:G,opts:Y}=X,H=Y.passContext?H0.default.this:Tw.nil;if(W)z();else D();function z(){if(!G.$async)throw Error("async schema referenced by sync schema");let F=Q.let("valid");Q.try(()=>{if(Q.code(Tw._`await ${(0,EY.callValidateCode)(w,b,H)}`),L(b),!J)Q.assign(F,!0)},(V)=>{if(Q.if(Tw._`!(${V} instanceof ${X.ValidationError})`,()=>Q.throw(V)),A(V),!J)Q.assign(F,!1)}),w.ok(F)}function D(){w.result((0,EY.callValidateCode)(w,b,H),()=>L(b),()=>A(b))}function A(F){let V=Tw._`${F}.errors`;Q.assign(H0.default.vErrors,Tw._`${H0.default.vErrors} === null ? ${V} : ${H0.default.vErrors}.concat(${V})`),Q.assign(H0.default.errors,Tw._`${H0.default.vErrors}.length`)}function L(F){var V;if(!X.opts.unevaluated)return;let q=(V=$===null||$===void 0?void 0:$.validate)===null||V===void 0?void 0:V.evaluated;if(X.props!==!0)if(q&&!q.dynamicProps){if(q.props!==void 0)X.props=k6.mergeEvaluated.props(Q,q.props,X.props)}else{let P=Q.var("props",Tw._`${F}.evaluated.props`);X.props=k6.mergeEvaluated.props(Q,P,X.props,Tw.Name)}if(X.items!==!0)if(q&&!q.dynamicItems){if(q.items!==void 0)X.items=k6.mergeEvaluated.items(Q,q.items,X.items)}else{let P=Q.var("items",Tw._`${F}.evaluated.items`);X.items=k6.mergeEvaluated.items(Q,P,X.items,Tw.Name)}}}SY.callRef=_6;SY.default=eK});var _Y=N((kY)=>{Object.defineProperty(kY,"__esModule",{value:!0});var bO=NY(),$O=CY(),WO=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",bO.default,$O.default];kY.default=WO});var hY=N((xY)=>{Object.defineProperty(xY,"__esModule",{value:!0});var x6=c(),R1=x6.operators,h6={maximum:{okStr:"<=",ok:R1.LTE,fail:R1.GT},minimum:{okStr:">=",ok:R1.GTE,fail:R1.LT},exclusiveMaximum:{okStr:"<",ok:R1.LT,fail:R1.GTE},exclusiveMinimum:{okStr:">",ok:R1.GT,fail:R1.LTE}},XO={message:({keyword:w,schemaCode:b})=>x6.str`must be ${h6[w].okStr} ${b}`,params:({keyword:w,schemaCode:b})=>x6._`{comparison: ${h6[w].okStr}, limit: ${b}}`},JO={keyword:Object.keys(h6),type:"number",schemaType:"number",$data:!0,error:XO,code(w){let{keyword:b,data:$,schemaCode:W}=w;w.fail$data(x6._`${$} ${h6[b].fail} ${W} || isNaN(${$})`)}};xY.default=JO});var fY=N((yY)=>{Object.defineProperty(yY,"__esModule",{value:!0});var zb=c(),YO={message:({schemaCode:w})=>zb.str`must be multiple of ${w}`,params:({schemaCode:w})=>zb._`{multipleOf: ${w}}`},HO={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:YO,code(w){let{gen:b,data:$,schemaCode:W,it:Q}=w,X=Q.opts.multipleOfPrecision,J=b.let("res"),G=X?zb._`Math.abs(Math.round(${J}) - ${J}) > 1e-${X}`:zb._`${J} !== parseInt(${J})`;w.fail$data(zb._`(${W} === 0 || (${J} = ${$}/${W}, ${G}))`)}};yY.default=HO});var mY=N((cY)=>{Object.defineProperty(cY,"__esModule",{value:!0});function uY(w){let b=w.length,$=0,W=0,Q;while(W<b)if($++,Q=w.charCodeAt(W++),Q>=55296&&Q<=56319&&W<b){if(Q=w.charCodeAt(W),(Q&64512)===56320)W++}return $}cY.default=uY;uY.code='require("ajv/dist/runtime/ucs2length").default'});var gY=N((lY)=>{Object.defineProperty(lY,"__esModule",{value:!0});var c1=c(),DO=t(),AO=mY(),LO={message({keyword:w,schemaCode:b}){let $=w==="maxLength"?"more":"fewer";return c1.str`must NOT have ${$} than ${b} characters`},params:({schemaCode:w})=>c1._`{limit: ${w}}`},UO={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:LO,code(w){let{keyword:b,data:$,schemaCode:W,it:Q}=w,X=b==="maxLength"?c1.operators.GT:c1.operators.LT,J=Q.opts.unicode===!1?c1._`${$}.length`:c1._`${(0,DO.useFunc)(w.gen,AO.default)}(${$})`;w.fail$data(c1._`${J} ${X} ${W}`)}};lY.default=UO});var nY=N((iY)=>{Object.defineProperty(iY,"__esModule",{value:!0});var KO=fw(),y6=c(),OO={message:({schemaCode:w})=>y6.str`must match pattern "${w}"`,params:({schemaCode:w})=>y6._`{pattern: ${w}}`},ZO={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:OO,code(w){let{data:b,$data:$,schema:W,schemaCode:Q,it:X}=w,J=X.opts.unicodeRegExp?"u":"",G=$?y6._`(new RegExp(${Q}, ${J}))`:(0,KO.usePattern)(w,W);w.fail$data(y6._`!${G}.test(${b})`)}};iY.default=ZO});var dY=N((pY)=>{Object.defineProperty(pY,"__esModule",{value:!0});var Bb=c(),VO={message({keyword:w,schemaCode:b}){let $=w==="maxProperties"?"more":"fewer";return Bb.str`must NOT have ${$} than ${b} properties`},params:({schemaCode:w})=>Bb._`{limit: ${w}}`},jO={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:VO,code(w){let{keyword:b,data:$,schemaCode:W}=w,Q=b==="maxProperties"?Bb.operators.GT:Bb.operators.LT;w.fail$data(Bb._`Object.keys(${$}).length ${Q} ${W}`)}};pY.default=jO});var tY=N((oY)=>{Object.defineProperty(oY,"__esModule",{value:!0});var Db=fw(),Ab=c(),PO=t(),IO={message:({params:{missingProperty:w}})=>Ab.str`must have required property '${w}'`,params:({params:{missingProperty:w}})=>Ab._`{missingProperty: ${w}}`},NO={keyword:"required",type:"object",schemaType:"array",$data:!0,error:IO,code(w){let{gen:b,schema:$,schemaCode:W,data:Q,$data:X,it:J}=w,{opts:G}=J;if(!X&&$.length===0)return;let Y=$.length>=G.loopRequired;if(J.allErrors)H();else z();if(G.strictRequired){let L=w.parentSchema.properties,{definedProperties:F}=w.it;for(let V of $)if((L===null||L===void 0?void 0:L[V])===void 0&&!F.has(V)){let q=J.schemaEnv.baseId+J.errSchemaPath,P=`required property "${V}" is not defined at "${q}" (strictRequired)`;(0,PO.checkStrictMode)(J,P,J.opts.strictRequired)}}function H(){if(Y||X)w.block$data(Ab.nil,D);else for(let L of $)(0,Db.checkReportMissingProp)(w,L)}function z(){let L=b.let("missing");if(Y||X){let F=b.let("valid",!0);w.block$data(F,()=>A(L,F)),w.ok(F)}else b.if((0,Db.checkMissingProp)(w,$,L)),(0,Db.reportMissingProp)(w,L),b.else()}function D(){b.forOf("prop",W,(L)=>{w.setParams({missingProperty:L}),b.if((0,Db.noPropertyInData)(b,Q,L,G.ownProperties),()=>w.error())})}function A(L,F){w.setParams({missingProperty:L}),b.forOf(L,W,()=>{b.assign(F,(0,Db.propertyInData)(b,Q,L,G.ownProperties)),b.if((0,Ab.not)(F),()=>{w.error(),b.break()})},Ab.nil)}}};oY.default=NO});var sY=N((rY)=>{Object.defineProperty(rY,"__esModule",{value:!0});var Lb=c(),TO={message({keyword:w,schemaCode:b}){let $=w==="maxItems"?"more":"fewer";return Lb.str`must NOT have ${$} than ${b} items`},params:({schemaCode:w})=>Lb._`{limit: ${w}}`},RO={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:TO,code(w){let{keyword:b,data:$,schemaCode:W}=w,Q=b==="maxItems"?Lb.operators.GT:Lb.operators.LT;w.fail$data(Lb._`${$}.length ${Q} ${W}`)}};rY.default=RO});var f6=N((aY)=>{Object.defineProperty(aY,"__esModule",{value:!0});var eY=g$();eY.code='require("ajv/dist/runtime/equal").default';aY.default=eY});var b7=N((w7)=>{Object.defineProperty(w7,"__esModule",{value:!0});var X9=wb(),Mw=c(),CO=t(),kO=f6(),_O={message:({params:{i:w,j:b}})=>Mw.str`must NOT have duplicate items (items ## ${b} and ${w} are identical)`,params:({params:{i:w,j:b}})=>Mw._`{i: ${w}, j: ${b}}`},xO={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:_O,code(w){let{gen:b,data:$,$data:W,schema:Q,parentSchema:X,schemaCode:J,it:G}=w;if(!W&&!Q)return;let Y=b.let("valid"),H=X.items?(0,X9.getSchemaTypes)(X.items):[];w.block$data(Y,z,Mw._`${J} === false`),w.ok(Y);function z(){let F=b.let("i",Mw._`${$}.length`),V=b.let("j");w.setParams({i:F,j:V}),b.assign(Y,!0),b.if(Mw._`${F} > 1`,()=>(D()?A:L)(F,V))}function D(){return H.length>0&&!H.some((F)=>F==="object"||F==="array")}function A(F,V){let q=b.name("item"),P=(0,X9.checkDataTypes)(H,q,G.opts.strictNumbers,X9.DataType.Wrong),k=b.const("indices",Mw._`{}`);b.for(Mw._`;${F}--;`,()=>{if(b.let(q,Mw._`${$}[${F}]`),b.if(P,Mw._`continue`),H.length>1)b.if(Mw._`typeof ${q} == "string"`,Mw._`${q} += "_"`);b.if(Mw._`typeof ${k}[${q}] == "number"`,()=>{b.assign(V,Mw._`${k}[${q}]`),w.error(),b.assign(Y,!1).break()}).code(Mw._`${k}[${q}] = ${F}`)})}function L(F,V){let q=(0,CO.useFunc)(b,kO.default),P=b.name("outer");b.label(P).for(Mw._`;${F}--;`,()=>b.for(Mw._`${V} = ${F}; ${V}--;`,()=>b.if(Mw._`${q}(${$}[${F}], ${$}[${V}])`,()=>{w.error(),b.assign(Y,!1).break(P)})))}}};w7.default=xO});var W7=N(($7)=>{Object.defineProperty($7,"__esModule",{value:!0});var J9=c(),yO=t(),fO=f6(),uO={message:"must be equal to constant",params:({schemaCode:w})=>J9._`{allowedValue: ${w}}`},cO={keyword:"const",$data:!0,error:uO,code(w){let{gen:b,data:$,$data:W,schemaCode:Q,schema:X}=w;if(W||X&&typeof X=="object")w.fail$data(J9._`!${(0,yO.useFunc)(b,fO.default)}(${$}, ${Q})`);else w.fail(J9._`${X} !== ${$}`)}};$7.default=cO});var X7=N((Q7)=>{Object.defineProperty(Q7,"__esModule",{value:!0});var Ub=c(),lO=t(),gO=f6(),iO={message:"must be equal to one of the allowed values",params:({schemaCode:w})=>Ub._`{allowedValues: ${w}}`},nO={keyword:"enum",schemaType:"array",$data:!0,error:iO,code(w){let{gen:b,data:$,$data:W,schema:Q,schemaCode:X,it:J}=w;if(!W&&Q.length===0)throw Error("enum must have non-empty array");let G=Q.length>=J.opts.loopEnum,Y,H=()=>Y!==null&&Y!==void 0?Y:Y=(0,lO.useFunc)(b,gO.default),z;if(G||W)z=b.let("valid"),w.block$data(z,D);else{if(!Array.isArray(Q))throw Error("ajv implementation error");let L=b.const("vSchema",X);z=(0,Ub.or)(...Q.map((F,V)=>A(L,V)))}w.pass(z);function D(){b.assign(z,!1),b.forOf("v",X,(L)=>b.if(Ub._`${H()}(${$}, ${L})`,()=>b.assign(z,!0).break()))}function A(L,F){let V=Q[F];return typeof V==="object"&&V!==null?Ub._`${H()}(${$}, ${L}[${F}])`:Ub._`${$} === ${V}`}}};Q7.default=nO});var G7=N((J7)=>{Object.defineProperty(J7,"__esModule",{value:!0});var dO=hY(),oO=fY(),tO=gY(),rO=nY(),sO=dY(),eO=tY(),aO=sY(),wZ=b7(),bZ=W7(),$Z=X7(),WZ=[dO.default,oO.default,tO.default,rO.default,sO.default,eO.default,aO.default,wZ.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},bZ.default,$Z.default];J7.default=WZ});var Y9=N((H7)=>{Object.defineProperty(H7,"__esModule",{value:!0});H7.validateAdditionalItems=void 0;var m1=c(),G9=t(),XZ={message:({params:{len:w}})=>m1.str`must NOT have more than ${w} items`,params:({params:{len:w}})=>m1._`{limit: ${w}}`},JZ={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:XZ,code(w){let{parentSchema:b,it:$}=w,{items:W}=b;if(!Array.isArray(W)){(0,G9.checkStrictMode)($,'"additionalItems" is ignored when "items" is not an array of schemas');return}Y7(w,W)}};function Y7(w,b){let{gen:$,schema:W,data:Q,keyword:X,it:J}=w;J.items=!0;let G=$.const("len",m1._`${Q}.length`);if(W===!1)w.setParams({len:b.length}),w.pass(m1._`${G} <= ${b.length}`);else if(typeof W=="object"&&!(0,G9.alwaysValidSchema)(J,W)){let H=$.var("valid",m1._`${G} <= ${b.length}`);$.if((0,m1.not)(H),()=>Y(H)),w.ok(H)}function Y(H){$.forRange("i",b.length,G,(z)=>{if(w.subschema({keyword:X,dataProp:z,dataPropType:G9.Type.Num},H),!J.allErrors)$.if((0,m1.not)(H),()=>$.break())})}}H7.validateAdditionalItems=Y7;H7.default=JZ});var H9=N((A7)=>{Object.defineProperty(A7,"__esModule",{value:!0});A7.validateTuple=void 0;var B7=c(),u6=t(),YZ=fw(),HZ={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(w){let{schema:b,it:$}=w;if(Array.isArray(b))return D7(w,"additionalItems",b);if($.items=!0,(0,u6.alwaysValidSchema)($,b))return;w.ok((0,YZ.validateArray)(w))}};function D7(w,b,$=w.schema){let{gen:W,parentSchema:Q,data:X,keyword:J,it:G}=w;if(z(Q),G.opts.unevaluated&&$.length&&G.items!==!0)G.items=u6.mergeEvaluated.items(W,$.length,G.items);let Y=W.name("valid"),H=W.const("len",B7._`${X}.length`);$.forEach((D,A)=>{if((0,u6.alwaysValidSchema)(G,D))return;W.if(B7._`${H} > ${A}`,()=>w.subschema({keyword:J,schemaProp:A,dataProp:A},Y)),w.ok(Y)});function z(D){let{opts:A,errSchemaPath:L}=G,F=$.length,V=F===D.minItems&&(F===D.maxItems||D[b]===!1);if(A.strictTuples&&!V){let q=`"${J}" is ${F}-tuple, but minItems or maxItems/${b} are not specified or different at path "${L}"`;(0,u6.checkStrictMode)(G,q,A.strictTuples)}}}A7.validateTuple=D7;A7.default=HZ});var F7=N((U7)=>{Object.defineProperty(U7,"__esModule",{value:!0});var BZ=H9(),DZ={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:(w)=>(0,BZ.validateTuple)(w,"items")};U7.default=DZ});var Z7=N((O7)=>{Object.defineProperty(O7,"__esModule",{value:!0});var K7=c(),LZ=t(),UZ=fw(),FZ=Y9(),KZ={message:({params:{len:w}})=>K7.str`must NOT have more than ${w} items`,params:({params:{len:w}})=>K7._`{limit: ${w}}`},OZ={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:KZ,code(w){let{schema:b,parentSchema:$,it:W}=w,{prefixItems:Q}=$;if(W.items=!0,(0,LZ.alwaysValidSchema)(W,b))return;if(Q)(0,FZ.validateAdditionalItems)(w,Q);else w.ok((0,UZ.validateArray)(w))}};O7.default=OZ});var V7=N((M7)=>{Object.defineProperty(M7,"__esModule",{value:!0});var uw=c(),c6=t(),MZ={message:({params:{min:w,max:b}})=>b===void 0?uw.str`must contain at least ${w} valid item(s)`:uw.str`must contain at least ${w} and no more than ${b} valid item(s)`,params:({params:{min:w,max:b}})=>b===void 0?uw._`{minContains: ${w}}`:uw._`{minContains: ${w}, maxContains: ${b}}`},VZ={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:MZ,code(w){let{gen:b,schema:$,parentSchema:W,data:Q,it:X}=w,J,G,{minContains:Y,maxContains:H}=W;if(X.opts.next)J=Y===void 0?1:Y,G=H;else J=1;let z=b.const("len",uw._`${Q}.length`);if(w.setParams({min:J,max:G}),G===void 0&&J===0){(0,c6.checkStrictMode)(X,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(G!==void 0&&J>G){(0,c6.checkStrictMode)(X,'"minContains" > "maxContains" is always invalid'),w.fail();return}if((0,c6.alwaysValidSchema)(X,$)){let V=uw._`${z} >= ${J}`;if(G!==void 0)V=uw._`${V} && ${z} <= ${G}`;w.pass(V);return}X.items=!0;let D=b.name("valid");if(G===void 0&&J===1)L(D,()=>b.if(D,()=>b.break()));else if(J===0){if(b.let(D,!0),G!==void 0)b.if(uw._`${Q}.length > 0`,A)}else b.let(D,!1),A();w.result(D,()=>w.reset());function A(){let V=b.name("_valid"),q=b.let("count",0);L(V,()=>b.if(V,()=>F(q)))}function L(V,q){b.forRange("i",0,z,(P)=>{w.subschema({keyword:"contains",dataProp:P,dataPropType:c6.Type.Num,compositeRule:!0},V),q()})}function F(V){if(b.code(uw._`${V}++`),G===void 0)b.if(uw._`${V} >= ${J}`,()=>b.assign(D,!0).break());else if(b.if(uw._`${V} > ${G}`,()=>b.assign(D,!1).break()),J===1)b.assign(D,!0);else b.if(uw._`${V} >= ${J}`,()=>b.assign(D,!0))}}};M7.default=VZ});var E7=N((P7)=>{Object.defineProperty(P7,"__esModule",{value:!0});P7.validateSchemaDeps=P7.validatePropertyDeps=P7.error=void 0;var z9=c(),qZ=t(),Fb=fw();P7.error={message:({params:{property:w,depsCount:b,deps:$}})=>{let W=b===1?"property":"properties";return z9.str`must have ${W} ${$} when property ${w} is present`},params:({params:{property:w,depsCount:b,deps:$,missingProperty:W}})=>z9._`{property: ${w},
6
- missingProperty: ${W},
1
+ var g3=Object.create;var{getPrototypeOf:i3,defineProperty:Z4,getOwnPropertyNames:n3}=Object;var p3=Object.prototype.hasOwnProperty;function d3(w){return this[w]}var o3,t3,KQ=(w,b,$)=>{var Q=w!=null&&typeof w==="object";if(Q){var W=b?o3??=new WeakMap:t3??=new WeakMap,X=W.get(w);if(X)return X}$=w!=null?g3(i3(w)):{};let J=b||!w||!w.__esModule?Z4($,"default",{value:w,enumerable:!0}):$;for(let Y of n3(w))if(!p3.call(J,Y))Z4(J,Y,{get:d3.bind(w,Y),enumerable:!0});if(Q)W.set(w,J);return J};var E=(w,b)=>()=>(b||w((b={exports:{}}).exports,b),b.exports);var r3=(w)=>w;function s3(w,b){this[w]=r3.bind(null,b)}var OQ=(w,b)=>{for(var $ in b)Z4(w,$,{get:b[$],enumerable:!0,configurable:!0,set:s3.bind(b,$)})};var $b=E((KJ)=>{Object.defineProperty(KJ,"__esModule",{value:!0});KJ.regexpCode=KJ.getEsmExportName=KJ.getProperty=KJ.safeStringify=KJ.stringify=KJ.strConcat=KJ.addCodeArg=KJ.str=KJ._=KJ.nil=KJ._Code=KJ.Name=KJ.IDENTIFIER=KJ._CodeOrName=void 0;class U6{}KJ._CodeOrName=U6;KJ.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class Jw extends U6{constructor(w){super();if(!KJ.IDENTIFIER.test(w))throw Error("CodeGen: name must be a valid identifier");this.str=w}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}KJ.Name=Jw;class p1 extends U6{constructor(w){super();this._items=typeof w==="string"?[w]:w}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let w=this._items[0];return w===""||w==='""'}get str(){var w;return(w=this._str)!==null&&w!==void 0?w:this._str=this._items.reduce((b,$)=>`${b}${$}`,"")}get names(){var w;return(w=this._names)!==null&&w!==void 0?w:this._names=this._items.reduce((b,$)=>{if($ instanceof Jw)b[$.str]=(b[$.str]||0)+1;return b},{})}}KJ._Code=p1;KJ.nil=new p1("");function UJ(w,...b){let $=[w[0]],Q=0;while(Q<b.length)T$($,b[Q]),$.push(w[++Q]);return new p1($)}KJ._=UJ;var N$=new p1("+");function AJ(w,...b){let $=[bb(w[0])],Q=0;while(Q<b.length)$.push(N$),T$($,b[Q]),$.push(N$,bb(w[++Q]));return jL($),new p1($)}KJ.str=AJ;function T$(w,b){if(b instanceof p1)w.push(...b._items);else if(b instanceof Jw)w.push(b);else w.push(PL(b))}KJ.addCodeArg=T$;function jL(w){let b=1;while(b<w.length-1){if(w[b]===N$){let $=ML(w[b-1],w[b+1]);if($!==void 0){w.splice(b-1,3,$);continue}w[b++]="+"}b++}}function ML(w,b){if(b==='""')return w;if(w==='""')return b;if(typeof w=="string"){if(b instanceof Jw||w[w.length-1]!=='"')return;if(typeof b!="string")return`${w.slice(0,-1)}${b}"`;if(b[0]==='"')return w.slice(0,-1)+b.slice(1);return}if(typeof b=="string"&&b[0]==='"'&&!(w instanceof Jw))return`"${w}${b.slice(1)}`;return}function VL(w,b){return b.emptyStr()?w:w.emptyStr()?b:AJ`${w}${b}`}KJ.strConcat=VL;function PL(w){return typeof w=="number"||typeof w=="boolean"||w===null?w:bb(Array.isArray(w)?w.join(","):w)}function qL(w){return new p1(bb(w))}KJ.stringify=qL;function bb(w){return JSON.stringify(w).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}KJ.safeStringify=bb;function IL(w){return typeof w=="string"&&KJ.IDENTIFIER.test(w)?new p1(`.${w}`):UJ`[${w}]`}KJ.getProperty=IL;function EL(w){if(typeof w=="string"&&KJ.IDENTIFIER.test(w))return new p1(`${w}`);throw Error(`CodeGen: invalid export name: ${w}, use explicit $id name mapping`)}KJ.getEsmExportName=EL;function NL(w){return new p1(w.toString())}KJ.regexpCode=NL});var C$=E((MJ)=>{Object.defineProperty(MJ,"__esModule",{value:!0});MJ.ValueScope=MJ.ValueScopeName=MJ.Scope=MJ.varKinds=MJ.UsedValueState=void 0;var E1=$b();class ZJ extends Error{constructor(w){super(`CodeGen: "code" for ${w} not defined`);this.value=w.value}}var K6;(function(w){w[w.Started=0]="Started",w[w.Completed=1]="Completed"})(K6||(MJ.UsedValueState=K6={}));MJ.varKinds={const:new E1.Name("const"),let:new E1.Name("let"),var:new E1.Name("var")};class S${constructor({prefixes:w,parent:b}={}){this._names={},this._prefixes=w,this._parent=b}toName(w){return w instanceof E1.Name?w:this.name(w)}name(w){return new E1.Name(this._newName(w))}_newName(w){let b=this._names[w]||this._nameGroup(w);return`${w}${b.index++}`}_nameGroup(w){var b,$;if((($=(b=this._parent)===null||b===void 0?void 0:b._prefixes)===null||$===void 0?void 0:$.has(w))||this._prefixes&&!this._prefixes.has(w))throw Error(`CodeGen: prefix "${w}" is not allowed in this scope`);return this._names[w]={prefix:w,index:0}}}MJ.Scope=S$;class v$ extends E1.Name{constructor(w,b){super(b);this.prefix=w}setValue(w,{property:b,itemIndex:$}){this.value=w,this.scopePath=E1._`.${new E1.Name(b)}[${$}]`}}MJ.ValueScopeName=v$;var cL=E1._`\n`;class jJ extends S${constructor(w){super(w);this._values={},this._scope=w.scope,this.opts={...w,_n:w.lines?cL:E1.nil}}get(){return this._scope}name(w){return new v$(w,this._newName(w))}value(w,b){var $;if(b.ref===void 0)throw Error("CodeGen: ref must be passed in value");let Q=this.toName(w),{prefix:W}=Q,X=($=b.key)!==null&&$!==void 0?$:b.ref,J=this._values[W];if(J){let H=J.get(X);if(H)return H}else J=this._values[W]=new Map;J.set(X,Q);let Y=this._scope[W]||(this._scope[W]=[]),G=Y.length;return Y[G]=b.ref,Q.setValue(b,{property:W,itemIndex:G}),Q}getValue(w,b){let $=this._values[w];if(!$)return;return $.get(b)}scopeRefs(w,b=this._values){return this._reduceValues(b,($)=>{if($.scopePath===void 0)throw Error(`CodeGen: name "${$}" has no value`);return E1._`${w}${$.scopePath}`})}scopeCode(w=this._values,b,$){return this._reduceValues(w,(Q)=>{if(Q.value===void 0)throw Error(`CodeGen: name "${Q}" has no value`);return Q.value.code},b,$)}_reduceValues(w,b,$={},Q){let W=E1.nil;for(let X in w){let J=w[X];if(!J)continue;let Y=$[X]=$[X]||new Map;J.forEach((G)=>{if(Y.has(G))return;Y.set(G,K6.Started);let H=b(G);if(H){let z=this.opts.es5?MJ.varKinds.var:MJ.varKinds.const;W=E1._`${W}${z} ${G} = ${H};${this.opts._n}`}else if(H=Q===null||Q===void 0?void 0:Q(G))W=E1._`${W}${H}${this.opts._n}`;else throw new ZJ(G);Y.set(G,K6.Completed)})}return W}}MJ.ValueScope=jJ});var m=E((N1)=>{Object.defineProperty(N1,"__esModule",{value:!0});N1.or=N1.and=N1.not=N1.CodeGen=N1.operators=N1.varKinds=N1.ValueScopeName=N1.ValueScope=N1.Scope=N1.Name=N1.regexpCode=N1.stringify=N1.getProperty=N1.nil=N1.strConcat=N1.str=N1._=void 0;var n=$b(),d1=C$(),N0=$b();Object.defineProperty(N1,"_",{enumerable:!0,get:function(){return N0._}});Object.defineProperty(N1,"str",{enumerable:!0,get:function(){return N0.str}});Object.defineProperty(N1,"strConcat",{enumerable:!0,get:function(){return N0.strConcat}});Object.defineProperty(N1,"nil",{enumerable:!0,get:function(){return N0.nil}});Object.defineProperty(N1,"getProperty",{enumerable:!0,get:function(){return N0.getProperty}});Object.defineProperty(N1,"stringify",{enumerable:!0,get:function(){return N0.stringify}});Object.defineProperty(N1,"regexpCode",{enumerable:!0,get:function(){return N0.regexpCode}});Object.defineProperty(N1,"Name",{enumerable:!0,get:function(){return N0.Name}});var P6=C$();Object.defineProperty(N1,"Scope",{enumerable:!0,get:function(){return P6.Scope}});Object.defineProperty(N1,"ValueScope",{enumerable:!0,get:function(){return P6.ValueScope}});Object.defineProperty(N1,"ValueScopeName",{enumerable:!0,get:function(){return P6.ValueScopeName}});Object.defineProperty(N1,"varKinds",{enumerable:!0,get:function(){return P6.varKinds}});N1.operators={GT:new n._Code(">"),GTE:new n._Code(">="),LT:new n._Code("<"),LTE:new n._Code("<="),EQ:new n._Code("==="),NEQ:new n._Code("!=="),NOT:new n._Code("!"),OR:new n._Code("||"),AND:new n._Code("&&"),ADD:new n._Code("+")};class T0{optimizeNodes(){return this}optimizeNames(w,b){return this}}class PJ extends T0{constructor(w,b,$){super();this.varKind=w,this.name=b,this.rhs=$}render({es5:w,_n:b}){let $=w?d1.varKinds.var:this.varKind,Q=this.rhs===void 0?"":` = ${this.rhs}`;return`${$} ${this.name}${Q};`+b}optimizeNames(w,b){if(!w[this.name.str])return;if(this.rhs)this.rhs=Gw(this.rhs,w,b);return this}get names(){return this.rhs instanceof n._CodeOrName?this.rhs.names:{}}}class x$ extends T0{constructor(w,b,$){super();this.lhs=w,this.rhs=b,this.sideEffects=$}render({_n:w}){return`${this.lhs} = ${this.rhs};`+w}optimizeNames(w,b){if(this.lhs instanceof n.Name&&!w[this.lhs.str]&&!this.sideEffects)return;return this.rhs=Gw(this.rhs,w,b),this}get names(){let w=this.lhs instanceof n.Name?{}:{...this.lhs.names};return V6(w,this.rhs)}}class qJ extends x${constructor(w,b,$,Q){super(w,$,Q);this.op=b}render({_n:w}){return`${this.lhs} ${this.op}= ${this.rhs};`+w}}class IJ extends T0{constructor(w){super();this.label=w,this.names={}}render({_n:w}){return`${this.label}:`+w}}class EJ extends T0{constructor(w){super();this.label=w,this.names={}}render({_n:w}){return`break${this.label?` ${this.label}`:""};`+w}}class NJ extends T0{constructor(w){super();this.error=w}render({_n:w}){return`throw ${this.error};`+w}get names(){return this.error.names}}class TJ extends T0{constructor(w){super();this.code=w}render({_n:w}){return`${this.code};`+w}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(w,b){return this.code=Gw(this.code,w,b),this}get names(){return this.code instanceof n._CodeOrName?this.code.names:{}}}class q6 extends T0{constructor(w=[]){super();this.nodes=w}render(w){return this.nodes.reduce((b,$)=>b+$.render(w),"")}optimizeNodes(){let{nodes:w}=this,b=w.length;while(b--){let $=w[b].optimizeNodes();if(Array.isArray($))w.splice(b,1,...$);else if($)w[b]=$;else w.splice(b,1)}return w.length>0?this:void 0}optimizeNames(w,b){let{nodes:$}=this,Q=$.length;while(Q--){let W=$[Q];if(W.optimizeNames(w,b))continue;iL(w,W.names),$.splice(Q,1)}return $.length>0?this:void 0}get names(){return this.nodes.reduce((w,b)=>u0(w,b.names),{})}}class R0 extends q6{render(w){return"{"+w._n+super.render(w)+"}"+w._n}}class RJ extends q6{}class Qb extends R0{}Qb.kind="else";class H0 extends R0{constructor(w,b){super(b);this.condition=w}render(w){let b=`if(${this.condition})`+super.render(w);if(this.else)b+="else "+this.else.render(w);return b}optimizeNodes(){super.optimizeNodes();let w=this.condition;if(w===!0)return this.nodes;let b=this.else;if(b){let $=b.optimizeNodes();b=this.else=Array.isArray($)?new Qb($):$}if(b){if(w===!1)return b instanceof H0?b:b.nodes;if(this.nodes.length)return this;return new H0(_J(w),b instanceof H0?[b]:b.nodes)}if(w===!1||!this.nodes.length)return;return this}optimizeNames(w,b){var $;if(this.else=($=this.else)===null||$===void 0?void 0:$.optimizeNames(w,b),!(super.optimizeNames(w,b)||this.else))return;return this.condition=Gw(this.condition,w,b),this}get names(){let w=super.names;if(V6(w,this.condition),this.else)u0(w,this.else.names);return w}}H0.kind="if";class Yw extends R0{}Yw.kind="for";class SJ extends Yw{constructor(w){super();this.iteration=w}render(w){return`for(${this.iteration})`+super.render(w)}optimizeNames(w,b){if(!super.optimizeNames(w,b))return;return this.iteration=Gw(this.iteration,w,b),this}get names(){return u0(super.names,this.iteration.names)}}class vJ extends Yw{constructor(w,b,$,Q){super();this.varKind=w,this.name=b,this.from=$,this.to=Q}render(w){let b=w.es5?d1.varKinds.var:this.varKind,{name:$,from:Q,to:W}=this;return`for(${b} ${$}=${Q}; ${$}<${W}; ${$}++)`+super.render(w)}get names(){let w=V6(super.names,this.from);return V6(w,this.to)}}class k$ extends Yw{constructor(w,b,$,Q){super();this.loop=w,this.varKind=b,this.name=$,this.iterable=Q}render(w){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(w)}optimizeNames(w,b){if(!super.optimizeNames(w,b))return;return this.iterable=Gw(this.iterable,w,b),this}get names(){return u0(super.names,this.iterable.names)}}class O6 extends R0{constructor(w,b,$){super();this.name=w,this.args=b,this.async=$}render(w){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(w)}}O6.kind="func";class Z6 extends q6{render(w){return"return "+super.render(w)}}Z6.kind="return";class CJ extends R0{render(w){let b="try"+super.render(w);if(this.catch)b+=this.catch.render(w);if(this.finally)b+=this.finally.render(w);return b}optimizeNodes(){var w,b;return super.optimizeNodes(),(w=this.catch)===null||w===void 0||w.optimizeNodes(),(b=this.finally)===null||b===void 0||b.optimizeNodes(),this}optimizeNames(w,b){var $,Q;return super.optimizeNames(w,b),($=this.catch)===null||$===void 0||$.optimizeNames(w,b),(Q=this.finally)===null||Q===void 0||Q.optimizeNames(w,b),this}get names(){let w=super.names;if(this.catch)u0(w,this.catch.names);if(this.finally)u0(w,this.finally.names);return w}}class j6 extends R0{constructor(w){super();this.error=w}render(w){return`catch(${this.error})`+super.render(w)}}j6.kind="catch";class M6 extends R0{render(w){return"finally"+super.render(w)}}M6.kind="finally";class kJ{constructor(w,b={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...b,_n:b.lines?`
2
+ `:""},this._extScope=w,this._scope=new d1.Scope({parent:w}),this._nodes=[new RJ]}toString(){return this._root.render(this.opts)}name(w){return this._scope.name(w)}scopeName(w){return this._extScope.name(w)}scopeValue(w,b){let $=this._extScope.value(w,b);return(this._values[$.prefix]||(this._values[$.prefix]=new Set)).add($),$}getScopeValue(w,b){return this._extScope.getValue(w,b)}scopeRefs(w){return this._extScope.scopeRefs(w,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(w,b,$,Q){let W=this._scope.toName(b);if($!==void 0&&Q)this._constants[W.str]=$;return this._leafNode(new PJ(w,W,$)),W}const(w,b,$){return this._def(d1.varKinds.const,w,b,$)}let(w,b,$){return this._def(d1.varKinds.let,w,b,$)}var(w,b,$){return this._def(d1.varKinds.var,w,b,$)}assign(w,b,$){return this._leafNode(new x$(w,b,$))}add(w,b){return this._leafNode(new qJ(w,N1.operators.ADD,b))}code(w){if(typeof w=="function")w();else if(w!==n.nil)this._leafNode(new TJ(w));return this}object(...w){let b=["{"];for(let[$,Q]of w){if(b.length>1)b.push(",");if(b.push($),$!==Q||this.opts.es5)b.push(":"),(0,n.addCodeArg)(b,Q)}return b.push("}"),new n._Code(b)}if(w,b,$){if(this._blockNode(new H0(w)),b&&$)this.code(b).else().code($).endIf();else if(b)this.code(b).endIf();else if($)throw Error('CodeGen: "else" body without "then" body');return this}elseIf(w){return this._elseNode(new H0(w))}else(){return this._elseNode(new Qb)}endIf(){return this._endBlockNode(H0,Qb)}_for(w,b){if(this._blockNode(w),b)this.code(b).endFor();return this}for(w,b){return this._for(new SJ(w),b)}forRange(w,b,$,Q,W=this.opts.es5?d1.varKinds.var:d1.varKinds.let){let X=this._scope.toName(w);return this._for(new vJ(W,X,b,$),()=>Q(X))}forOf(w,b,$,Q=d1.varKinds.const){let W=this._scope.toName(w);if(this.opts.es5){let X=b instanceof n.Name?b:this.var("_arr",b);return this.forRange("_i",0,n._`${X}.length`,(J)=>{this.var(W,n._`${X}[${J}]`),$(W)})}return this._for(new k$("of",Q,W,b),()=>$(W))}forIn(w,b,$,Q=this.opts.es5?d1.varKinds.var:d1.varKinds.const){if(this.opts.ownProperties)return this.forOf(w,n._`Object.keys(${b})`,$);let W=this._scope.toName(w);return this._for(new k$("in",Q,W,b),()=>$(W))}endFor(){return this._endBlockNode(Yw)}label(w){return this._leafNode(new IJ(w))}break(w){return this._leafNode(new EJ(w))}return(w){let b=new Z6;if(this._blockNode(b),this.code(w),b.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(Z6)}try(w,b,$){if(!b&&!$)throw Error('CodeGen: "try" without "catch" and "finally"');let Q=new CJ;if(this._blockNode(Q),this.code(w),b){let W=this.name("e");this._currNode=Q.catch=new j6(W),b(W)}if($)this._currNode=Q.finally=new M6,this.code($);return this._endBlockNode(j6,M6)}throw(w){return this._leafNode(new NJ(w))}block(w,b){if(this._blockStarts.push(this._nodes.length),w)this.code(w).endBlock(b);return this}endBlock(w){let b=this._blockStarts.pop();if(b===void 0)throw Error("CodeGen: not in self-balancing block");let $=this._nodes.length-b;if($<0||w!==void 0&&$!==w)throw Error(`CodeGen: wrong number of nodes: ${$} vs ${w} expected`);return this._nodes.length=b,this}func(w,b=n.nil,$,Q){if(this._blockNode(new O6(w,b,$)),Q)this.code(Q).endFunc();return this}endFunc(){return this._endBlockNode(O6)}optimize(w=1){while(w-- >0)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(w){return this._currNode.nodes.push(w),this}_blockNode(w){this._currNode.nodes.push(w),this._nodes.push(w)}_endBlockNode(w,b){let $=this._currNode;if($ instanceof w||b&&$ instanceof b)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${b?`${w.kind}/${b.kind}`:w.kind}"`)}_elseNode(w){let b=this._currNode;if(!(b instanceof H0))throw Error('CodeGen: "else" without "if"');return this._currNode=b.else=w,this}get _root(){return this._nodes[0]}get _currNode(){let w=this._nodes;return w[w.length-1]}set _currNode(w){let b=this._nodes;b[b.length-1]=w}}N1.CodeGen=kJ;function u0(w,b){for(let $ in b)w[$]=(w[$]||0)+(b[$]||0);return w}function V6(w,b){return b instanceof n._CodeOrName?u0(w,b.names):w}function Gw(w,b,$){if(w instanceof n.Name)return Q(w);if(!W(w))return w;return new n._Code(w._items.reduce((X,J)=>{if(J instanceof n.Name)J=Q(J);if(J instanceof n._Code)X.push(...J._items);else X.push(J);return X},[]));function Q(X){let J=$[X.str];if(J===void 0||b[X.str]!==1)return X;return delete b[X.str],J}function W(X){return X instanceof n._Code&&X._items.some((J)=>J instanceof n.Name&&b[J.str]===1&&$[J.str]!==void 0)}}function iL(w,b){for(let $ in b)w[$]=(w[$]||0)-(b[$]||0)}function _J(w){return typeof w=="boolean"||typeof w=="number"||w===null?!w:n._`!${_$(w)}`}N1.not=_J;var nL=xJ(N1.operators.AND);function pL(...w){return w.reduce(nL)}N1.and=pL;var dL=xJ(N1.operators.OR);function oL(...w){return w.reduce(dL)}N1.or=oL;function xJ(w){return(b,$)=>b===n.nil?$:$===n.nil?b:n._`${_$(b)} ${w} ${_$($)}`}function _$(w){return w instanceof n.Name?w:n._`(${w})`}});var t=E((iJ)=>{Object.defineProperty(iJ,"__esModule",{value:!0});iJ.checkStrictMode=iJ.getErrorPath=iJ.Type=iJ.useFunc=iJ.setEvaluated=iJ.evaluatedPropsToName=iJ.mergeEvaluated=iJ.eachItem=iJ.unescapeJsonPointer=iJ.escapeJsonPointer=iJ.escapeFragment=iJ.unescapeFragment=iJ.schemaRefOrVal=iJ.schemaHasRulesButRef=iJ.schemaHasRules=iJ.checkUnknownRules=iJ.alwaysValidSchema=iJ.toHash=void 0;var e=m(),eL=$b();function aL(w){let b={};for(let $ of w)b[$]=!0;return b}iJ.toHash=aL;function wF(w,b){if(typeof b=="boolean")return b;if(Object.keys(b).length===0)return!0;return uJ(w,b),!cJ(b,w.self.RULES.all)}iJ.alwaysValidSchema=wF;function uJ(w,b=w.schema){let{opts:$,self:Q}=w;if(!$.strictSchema)return;if(typeof b==="boolean")return;let W=Q.RULES.keywords;for(let X in b)if(!W[X])gJ(w,`unknown keyword: "${X}"`)}iJ.checkUnknownRules=uJ;function cJ(w,b){if(typeof w=="boolean")return!w;for(let $ in w)if(b[$])return!0;return!1}iJ.schemaHasRules=cJ;function bF(w,b){if(typeof w=="boolean")return!w;for(let $ in w)if($!=="$ref"&&b.all[$])return!0;return!1}iJ.schemaHasRulesButRef=bF;function $F({topSchemaRef:w,schemaPath:b},$,Q,W){if(!W){if(typeof $=="number"||typeof $=="boolean")return $;if(typeof $=="string")return e._`${$}`}return e._`${w}${b}${(0,e.getProperty)(Q)}`}iJ.schemaRefOrVal=$F;function QF(w){return mJ(decodeURIComponent(w))}iJ.unescapeFragment=QF;function WF(w){return encodeURIComponent(y$(w))}iJ.escapeFragment=WF;function y$(w){if(typeof w=="number")return`${w}`;return w.replace(/~/g,"~0").replace(/\//g,"~1")}iJ.escapeJsonPointer=y$;function mJ(w){return w.replace(/~1/g,"/").replace(/~0/g,"~")}iJ.unescapeJsonPointer=mJ;function XF(w,b){if(Array.isArray(w))for(let $ of w)b($);else b(w)}iJ.eachItem=XF;function yJ({mergeNames:w,mergeToName:b,mergeValues:$,resultToName:Q}){return(W,X,J,Y)=>{let G=J===void 0?X:J instanceof e.Name?(X instanceof e.Name?w(W,X,J):b(W,X,J),J):X instanceof e.Name?(b(W,J,X),X):$(X,J);return Y===e.Name&&!(G instanceof e.Name)?Q(W,G):G}}iJ.mergeEvaluated={props:yJ({mergeNames:(w,b,$)=>w.if(e._`${$} !== true && ${b} !== undefined`,()=>{w.if(e._`${b} === true`,()=>w.assign($,!0),()=>w.assign($,e._`${$} || {}`).code(e._`Object.assign(${$}, ${b})`))}),mergeToName:(w,b,$)=>w.if(e._`${$} !== true`,()=>{if(b===!0)w.assign($,!0);else w.assign($,e._`${$} || {}`),f$(w,$,b)}),mergeValues:(w,b)=>w===!0?!0:{...w,...b},resultToName:lJ}),items:yJ({mergeNames:(w,b,$)=>w.if(e._`${$} !== true && ${b} !== undefined`,()=>w.assign($,e._`${b} === true ? true : ${$} > ${b} ? ${$} : ${b}`)),mergeToName:(w,b,$)=>w.if(e._`${$} !== true`,()=>w.assign($,b===!0?!0:e._`${$} > ${b} ? ${$} : ${b}`)),mergeValues:(w,b)=>w===!0?!0:Math.max(w,b),resultToName:(w,b)=>w.var("items",b)})};function lJ(w,b){if(b===!0)return w.var("props",!0);let $=w.var("props",e._`{}`);if(b!==void 0)f$(w,$,b);return $}iJ.evaluatedPropsToName=lJ;function f$(w,b,$){Object.keys($).forEach((Q)=>w.assign(e._`${b}${(0,e.getProperty)(Q)}`,!0))}iJ.setEvaluated=f$;var fJ={};function JF(w,b){return w.scopeValue("func",{ref:b,code:fJ[b.code]||(fJ[b.code]=new eL._Code(b.code))})}iJ.useFunc=JF;var h$;(function(w){w[w.Num=0]="Num",w[w.Str=1]="Str"})(h$||(iJ.Type=h$={}));function YF(w,b,$){if(w instanceof e.Name){let Q=b===h$.Num;return $?Q?e._`"[" + ${w} + "]"`:e._`"['" + ${w} + "']"`:Q?e._`"/" + ${w}`:e._`"/" + ${w}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return $?(0,e.getProperty)(w).toString():"/"+y$(w)}iJ.getErrorPath=YF;function gJ(w,b,$=w.opts.strictSchema){if(!$)return;if(b=`strict mode: ${b}`,$===!0)throw Error(b);w.self.logger.warn(b)}iJ.checkStrictMode=gJ});var z0=E((pJ)=>{Object.defineProperty(pJ,"__esModule",{value:!0});var M1=m(),IF={data:new M1.Name("data"),valCxt:new M1.Name("valCxt"),instancePath:new M1.Name("instancePath"),parentData:new M1.Name("parentData"),parentDataProperty:new M1.Name("parentDataProperty"),rootData:new M1.Name("rootData"),dynamicAnchors:new M1.Name("dynamicAnchors"),vErrors:new M1.Name("vErrors"),errors:new M1.Name("errors"),this:new M1.Name("this"),self:new M1.Name("self"),scope:new M1.Name("scope"),json:new M1.Name("json"),jsonPos:new M1.Name("jsonPos"),jsonLen:new M1.Name("jsonLen"),jsonPart:new M1.Name("jsonPart")};pJ.default=IF});var Wb=E((rJ)=>{Object.defineProperty(rJ,"__esModule",{value:!0});rJ.extendErrors=rJ.resetErrorsCount=rJ.reportExtraError=rJ.reportError=rJ.keyword$DataError=rJ.keywordError=void 0;var p=m(),E6=t(),P1=z0();rJ.keywordError={message:({keyword:w})=>p.str`must pass "${w}" keyword validation`};rJ.keyword$DataError={message:({keyword:w,schemaType:b})=>b?p.str`"${w}" keyword must be ${b} ($data)`:p.str`"${w}" keyword is invalid ($data)`};function NF(w,b=rJ.keywordError,$,Q){let{it:W}=w,{gen:X,compositeRule:J,allErrors:Y}=W,G=tJ(w,b,$);if(Q!==null&&Q!==void 0?Q:J||Y)dJ(X,G);else oJ(W,p._`[${G}]`)}rJ.reportError=NF;function TF(w,b=rJ.keywordError,$){let{it:Q}=w,{gen:W,compositeRule:X,allErrors:J}=Q,Y=tJ(w,b,$);if(dJ(W,Y),!(X||J))oJ(Q,P1.default.vErrors)}rJ.reportExtraError=TF;function RF(w,b){w.assign(P1.default.errors,b),w.if(p._`${P1.default.vErrors} !== null`,()=>w.if(b,()=>w.assign(p._`${P1.default.vErrors}.length`,b),()=>w.assign(P1.default.vErrors,null)))}rJ.resetErrorsCount=RF;function SF({gen:w,keyword:b,schemaValue:$,data:Q,errsCount:W,it:X}){if(W===void 0)throw Error("ajv implementation error");let J=w.name("err");w.forRange("i",W,P1.default.errors,(Y)=>{if(w.const(J,p._`${P1.default.vErrors}[${Y}]`),w.if(p._`${J}.instancePath === undefined`,()=>w.assign(p._`${J}.instancePath`,(0,p.strConcat)(P1.default.instancePath,X.errorPath))),w.assign(p._`${J}.schemaPath`,p.str`${X.errSchemaPath}/${b}`),X.opts.verbose)w.assign(p._`${J}.schema`,$),w.assign(p._`${J}.data`,Q)})}rJ.extendErrors=SF;function dJ(w,b){let $=w.const("err",b);w.if(p._`${P1.default.vErrors} === null`,()=>w.assign(P1.default.vErrors,p._`[${$}]`),p._`${P1.default.vErrors}.push(${$})`),w.code(p._`${P1.default.errors}++`)}function oJ(w,b){let{gen:$,validateName:Q,schemaEnv:W}=w;if(W.$async)$.throw(p._`new ${w.ValidationError}(${b})`);else $.assign(p._`${Q}.errors`,b),$.return(!1)}var c0={keyword:new p.Name("keyword"),schemaPath:new p.Name("schemaPath"),params:new p.Name("params"),propertyName:new p.Name("propertyName"),message:new p.Name("message"),schema:new p.Name("schema"),parentSchema:new p.Name("parentSchema")};function tJ(w,b,$){let{createErrors:Q}=w.it;if(Q===!1)return p._`{}`;return vF(w,b,$)}function vF(w,b,$={}){let{gen:Q,it:W}=w,X=[CF(W,$),kF(w,$)];return _F(w,b,X),Q.object(...X)}function CF({errorPath:w},{instancePath:b}){let $=b?p.str`${w}${(0,E6.getErrorPath)(b,E6.Type.Str)}`:w;return[P1.default.instancePath,(0,p.strConcat)(P1.default.instancePath,$)]}function kF({keyword:w,it:{errSchemaPath:b}},{schemaPath:$,parentSchema:Q}){let W=Q?b:p.str`${b}/${w}`;if($)W=p.str`${W}${(0,E6.getErrorPath)($,E6.Type.Str)}`;return[c0.schemaPath,W]}function _F(w,{params:b,message:$},Q){let{keyword:W,data:X,schemaValue:J,it:Y}=w,{opts:G,propertyName:H,topSchemaRef:z,schemaPath:B}=Y;if(Q.push([c0.keyword,W],[c0.params,typeof b=="function"?b(w):b||p._`{}`]),G.messages)Q.push([c0.message,typeof $=="function"?$(w):$]);if(G.verbose)Q.push([c0.schema,J],[c0.parentSchema,p._`${z}${B}`],[P1.default.data,X]);if(H)Q.push([c0.propertyName,H])}});var bY=E((aJ)=>{Object.defineProperty(aJ,"__esModule",{value:!0});aJ.boolOrEmptySchema=aJ.topBoolOrEmptySchema=void 0;var uF=Wb(),cF=m(),mF=z0(),lF={message:"boolean schema is false"};function gF(w){let{gen:b,schema:$,validateName:Q}=w;if($===!1)eJ(w,!1);else if(typeof $=="object"&&$.$async===!0)b.return(mF.default.data);else b.assign(cF._`${Q}.errors`,null),b.return(!0)}aJ.topBoolOrEmptySchema=gF;function iF(w,b){let{gen:$,schema:Q}=w;if(Q===!1)$.var(b,!1),eJ(w);else $.var(b,!0)}aJ.boolOrEmptySchema=iF;function eJ(w,b){let{gen:$,data:Q}=w,W={gen:$,keyword:"false schema",data:Q,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:w};(0,uF.reportError)(W,lF,void 0,b)}});var c$=E(($Y)=>{Object.defineProperty($Y,"__esModule",{value:!0});$Y.getRules=$Y.isJSONType=void 0;var pF=["string","number","integer","boolean","null","object","array"],dF=new Set(pF);function oF(w){return typeof w=="string"&&dF.has(w)}$Y.isJSONType=oF;function tF(){let w={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...w,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},w.number,w.string,w.array,w.object],post:{rules:[]},all:{},keywords:{}}}$Y.getRules=tF});var m$=E((JY)=>{Object.defineProperty(JY,"__esModule",{value:!0});JY.shouldUseRule=JY.shouldUseGroup=JY.schemaHasRulesForType=void 0;function sF({schema:w,self:b},$){let Q=b.RULES.types[$];return Q&&Q!==!0&&WY(w,Q)}JY.schemaHasRulesForType=sF;function WY(w,b){return b.rules.some(($)=>XY(w,$))}JY.shouldUseGroup=WY;function XY(w,b){var $;return w[b.keyword]!==void 0||(($=b.definition.implements)===null||$===void 0?void 0:$.some((Q)=>w[Q]!==void 0))}JY.shouldUseRule=XY});var Xb=E((DY)=>{Object.defineProperty(DY,"__esModule",{value:!0});DY.reportTypeError=DY.checkDataTypes=DY.checkDataType=DY.coerceAndCheckDataType=DY.getJSONTypes=DY.getSchemaTypes=DY.DataType=void 0;var wU=c$(),bU=m$(),$U=Wb(),f=m(),GY=t(),Hw;(function(w){w[w.Correct=0]="Correct",w[w.Wrong=1]="Wrong"})(Hw||(DY.DataType=Hw={}));function QU(w){let b=HY(w.type);if(b.includes("null")){if(w.nullable===!1)throw Error("type: null contradicts nullable: false")}else{if(!b.length&&w.nullable!==void 0)throw Error('"nullable" cannot be used without "type"');if(w.nullable===!0)b.push("null")}return b}DY.getSchemaTypes=QU;function HY(w){let b=Array.isArray(w)?w:w?[w]:[];if(b.every(wU.isJSONType))return b;throw Error("type must be JSONType or JSONType[]: "+b.join(","))}DY.getJSONTypes=HY;function WU(w,b){let{gen:$,data:Q,opts:W}=w,X=XU(b,W.coerceTypes),J=b.length>0&&!(X.length===0&&b.length===1&&(0,bU.schemaHasRulesForType)(w,b[0]));if(J){let Y=g$(b,Q,W.strictNumbers,Hw.Wrong);$.if(Y,()=>{if(X.length)JU(w,b,X);else i$(w)})}return J}DY.coerceAndCheckDataType=WU;var zY=new Set(["string","number","integer","boolean","null"]);function XU(w,b){return b?w.filter(($)=>zY.has($)||b==="array"&&$==="array"):[]}function JU(w,b,$){let{gen:Q,data:W,opts:X}=w,J=Q.let("dataType",f._`typeof ${W}`),Y=Q.let("coerced",f._`undefined`);if(X.coerceTypes==="array")Q.if(f._`${J} == 'object' && Array.isArray(${W}) && ${W}.length == 1`,()=>Q.assign(W,f._`${W}[0]`).assign(J,f._`typeof ${W}`).if(g$(b,W,X.strictNumbers),()=>Q.assign(Y,W)));Q.if(f._`${Y} !== undefined`);for(let H of $)if(zY.has(H)||H==="array"&&X.coerceTypes==="array")G(H);Q.else(),i$(w),Q.endIf(),Q.if(f._`${Y} !== undefined`,()=>{Q.assign(W,Y),YU(w,Y)});function G(H){switch(H){case"string":Q.elseIf(f._`${J} == "number" || ${J} == "boolean"`).assign(Y,f._`"" + ${W}`).elseIf(f._`${W} === null`).assign(Y,f._`""`);return;case"number":Q.elseIf(f._`${J} == "boolean" || ${W} === null
3
+ || (${J} == "string" && ${W} && ${W} == +${W})`).assign(Y,f._`+${W}`);return;case"integer":Q.elseIf(f._`${J} === "boolean" || ${W} === null
4
+ || (${J} === "string" && ${W} && ${W} == +${W} && !(${W} % 1))`).assign(Y,f._`+${W}`);return;case"boolean":Q.elseIf(f._`${W} === "false" || ${W} === 0 || ${W} === null`).assign(Y,!1).elseIf(f._`${W} === "true" || ${W} === 1`).assign(Y,!0);return;case"null":Q.elseIf(f._`${W} === "" || ${W} === 0 || ${W} === false`),Q.assign(Y,null);return;case"array":Q.elseIf(f._`${J} === "string" || ${J} === "number"
5
+ || ${J} === "boolean" || ${W} === null`).assign(Y,f._`[${W}]`)}}}function YU({gen:w,parentData:b,parentDataProperty:$},Q){w.if(f._`${b} !== undefined`,()=>w.assign(f._`${b}[${$}]`,Q))}function l$(w,b,$,Q=Hw.Correct){let W=Q===Hw.Correct?f.operators.EQ:f.operators.NEQ,X;switch(w){case"null":return f._`${b} ${W} null`;case"array":X=f._`Array.isArray(${b})`;break;case"object":X=f._`${b} && typeof ${b} == "object" && !Array.isArray(${b})`;break;case"integer":X=J(f._`!(${b} % 1) && !isNaN(${b})`);break;case"number":X=J();break;default:return f._`typeof ${b} ${W} ${w}`}return Q===Hw.Correct?X:(0,f.not)(X);function J(Y=f.nil){return(0,f.and)(f._`typeof ${b} == "number"`,Y,$?f._`isFinite(${b})`:f.nil)}}DY.checkDataType=l$;function g$(w,b,$,Q){if(w.length===1)return l$(w[0],b,$,Q);let W,X=(0,GY.toHash)(w);if(X.array&&X.object){let J=f._`typeof ${b} != "object"`;W=X.null?J:f._`!${b} || ${J}`,delete X.null,delete X.array,delete X.object}else W=f.nil;if(X.number)delete X.integer;for(let J in X)W=(0,f.and)(W,l$(J,b,$,Q));return W}DY.checkDataTypes=g$;var GU={message:({schema:w})=>`must be ${w}`,params:({schema:w,schemaValue:b})=>typeof w=="string"?f._`{type: ${w}}`:f._`{type: ${b}}`};function i$(w){let b=HU(w);(0,$U.reportError)(b,GU)}DY.reportTypeError=i$;function HU(w){let{gen:b,data:$,schema:Q}=w,W=(0,GY.schemaRefOrVal)(w,Q,"type");return{gen:b,keyword:"type",data:$,schema:Q.type,schemaCode:W,schemaValue:W,parentSchema:Q,params:{},it:w}}});var AY=E((FY)=>{Object.defineProperty(FY,"__esModule",{value:!0});FY.assignDefaults=void 0;var zw=m(),AU=t();function KU(w,b){let{properties:$,items:Q}=w.schema;if(b==="object"&&$)for(let W in $)LY(w,W,$[W].default);else if(b==="array"&&Array.isArray(Q))Q.forEach((W,X)=>LY(w,X,W.default))}FY.assignDefaults=KU;function LY(w,b,$){let{gen:Q,compositeRule:W,data:X,opts:J}=w;if($===void 0)return;let Y=zw._`${X}${(0,zw.getProperty)(b)}`;if(W){(0,AU.checkStrictMode)(w,`default is ignored for: ${Y}`);return}let G=zw._`${Y} === undefined`;if(J.useDefaults==="empty")G=zw._`${G} || ${Y} === null || ${Y} === ""`;Q.if(G,zw._`${Y} = ${(0,zw.stringify)($)}`)}});var c1=E((ZY)=>{Object.defineProperty(ZY,"__esModule",{value:!0});ZY.validateUnion=ZY.validateArray=ZY.usePattern=ZY.callValidateCode=ZY.schemaProperties=ZY.allSchemaProperties=ZY.noPropertyInData=ZY.propertyInData=ZY.isOwnProperty=ZY.hasPropFunc=ZY.reportMissingProp=ZY.checkMissingProp=ZY.checkReportMissingProp=void 0;var $1=m(),n$=t(),S0=z0(),OU=t();function ZU(w,b){let{gen:$,data:Q,it:W}=w;$.if(d$($,Q,b,W.opts.ownProperties),()=>{w.setParams({missingProperty:$1._`${b}`},!0),w.error()})}ZY.checkReportMissingProp=ZU;function jU({gen:w,data:b,it:{opts:$}},Q,W){return(0,$1.or)(...Q.map((X)=>(0,$1.and)(d$(w,b,X,$.ownProperties),$1._`${W} = ${X}`)))}ZY.checkMissingProp=jU;function MU(w,b){w.setParams({missingProperty:b},!0),w.error()}ZY.reportMissingProp=MU;function KY(w){return w.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:$1._`Object.prototype.hasOwnProperty`})}ZY.hasPropFunc=KY;function p$(w,b,$){return $1._`${KY(w)}.call(${b}, ${$})`}ZY.isOwnProperty=p$;function VU(w,b,$,Q){let W=$1._`${b}${(0,$1.getProperty)($)} !== undefined`;return Q?$1._`${W} && ${p$(w,b,$)}`:W}ZY.propertyInData=VU;function d$(w,b,$,Q){let W=$1._`${b}${(0,$1.getProperty)($)} === undefined`;return Q?(0,$1.or)(W,(0,$1.not)(p$(w,b,$))):W}ZY.noPropertyInData=d$;function OY(w){return w?Object.keys(w).filter((b)=>b!=="__proto__"):[]}ZY.allSchemaProperties=OY;function PU(w,b){return OY(b).filter(($)=>!(0,n$.alwaysValidSchema)(w,b[$]))}ZY.schemaProperties=PU;function qU({schemaCode:w,data:b,it:{gen:$,topSchemaRef:Q,schemaPath:W,errorPath:X},it:J},Y,G,H){let z=H?$1._`${w}, ${b}, ${Q}${W}`:b,B=[[S0.default.instancePath,(0,$1.strConcat)(S0.default.instancePath,X)],[S0.default.parentData,J.parentData],[S0.default.parentDataProperty,J.parentDataProperty],[S0.default.rootData,S0.default.rootData]];if(J.opts.dynamicRef)B.push([S0.default.dynamicAnchors,S0.default.dynamicAnchors]);let L=$1._`${z}, ${$.object(...B)}`;return G!==$1.nil?$1._`${Y}.call(${G}, ${L})`:$1._`${Y}(${L})`}ZY.callValidateCode=qU;var IU=$1._`new RegExp`;function EU({gen:w,it:{opts:b}},$){let Q=b.unicodeRegExp?"u":"",{regExp:W}=b.code,X=W($,Q);return w.scopeValue("pattern",{key:X.toString(),ref:X,code:$1._`${W.code==="new RegExp"?IU:(0,OU.useFunc)(w,W)}(${$}, ${Q})`})}ZY.usePattern=EU;function NU(w){let{gen:b,data:$,keyword:Q,it:W}=w,X=b.name("valid");if(W.allErrors){let Y=b.let("valid",!0);return J(()=>b.assign(Y,!1)),Y}return b.var(X,!0),J(()=>b.break()),X;function J(Y){let G=b.const("len",$1._`${$}.length`);b.forRange("i",0,G,(H)=>{w.subschema({keyword:Q,dataProp:H,dataPropType:n$.Type.Num},X),b.if((0,$1.not)(X),Y)})}}ZY.validateArray=NU;function TU(w){let{gen:b,schema:$,keyword:Q,it:W}=w;if(!Array.isArray($))throw Error("ajv implementation error");if($.some((G)=>(0,n$.alwaysValidSchema)(W,G))&&!W.opts.unevaluated)return;let J=b.let("valid",!1),Y=b.name("_valid");b.block(()=>$.forEach((G,H)=>{let z=w.subschema({keyword:Q,schemaProp:H,compositeRule:!0},Y);if(b.assign(J,$1._`${J} || ${Y}`),!w.mergeValidEvaluated(z,Y))b.if((0,$1.not)(J))})),w.result(J,()=>w.reset(),()=>w.error(!0))}ZY.validateUnion=TU});var IY=E((PY)=>{Object.defineProperty(PY,"__esModule",{value:!0});PY.validateKeywordUsage=PY.validSchemaType=PY.funcKeywordCode=PY.macroKeywordCode=void 0;var q1=m(),m0=z0(),mU=c1(),lU=Wb();function gU(w,b){let{gen:$,keyword:Q,schema:W,parentSchema:X,it:J}=w,Y=b.macro.call(J.self,W,X,J),G=VY($,Q,Y);if(J.opts.validateSchema!==!1)J.self.validateSchema(Y,!0);let H=$.name("valid");w.subschema({schema:Y,schemaPath:q1.nil,errSchemaPath:`${J.errSchemaPath}/${Q}`,topSchemaRef:G,compositeRule:!0},H),w.pass(H,()=>w.error(!0))}PY.macroKeywordCode=gU;function iU(w,b){var $;let{gen:Q,keyword:W,schema:X,parentSchema:J,$data:Y,it:G}=w;pU(G,b);let H=!Y&&b.compile?b.compile.call(G.self,X,J,G):b.validate,z=VY(Q,W,H),B=Q.let("valid");w.block$data(B,L),w.ok(($=b.valid)!==null&&$!==void 0?$:B);function L(){if(b.errors===!1){if(j(),b.modifying)MY(w);q(()=>w.error())}else{let P=b.async?F():A();if(b.modifying)MY(w);q(()=>nU(w,P))}}function F(){let P=Q.let("ruleErrs",null);return Q.try(()=>j(q1._`await `),(v)=>Q.assign(B,!1).if(q1._`${v} instanceof ${G.ValidationError}`,()=>Q.assign(P,q1._`${v}.errors`),()=>Q.throw(v))),P}function A(){let P=q1._`${z}.errors`;return Q.assign(P,null),j(q1.nil),P}function j(P=b.async?q1._`await `:q1.nil){let v=G.opts.passContext?m0.default.this:m0.default.self,S=!(("compile"in b)&&!Y||b.schema===!1);Q.assign(B,q1._`${P}${(0,mU.callValidateCode)(w,z,v,S)}`,b.modifying)}function q(P){var v;Q.if((0,q1.not)((v=b.valid)!==null&&v!==void 0?v:B),P)}}PY.funcKeywordCode=iU;function MY(w){let{gen:b,data:$,it:Q}=w;b.if(Q.parentData,()=>b.assign($,q1._`${Q.parentData}[${Q.parentDataProperty}]`))}function nU(w,b){let{gen:$}=w;$.if(q1._`Array.isArray(${b})`,()=>{$.assign(m0.default.vErrors,q1._`${m0.default.vErrors} === null ? ${b} : ${m0.default.vErrors}.concat(${b})`).assign(m0.default.errors,q1._`${m0.default.vErrors}.length`),(0,lU.extendErrors)(w)},()=>w.error())}function pU({schemaEnv:w},b){if(b.async&&!w.$async)throw Error("async keyword in sync schema")}function VY(w,b,$){if($===void 0)throw Error(`keyword "${b}" failed to compile`);return w.scopeValue("keyword",typeof $=="function"?{ref:$}:{ref:$,code:(0,q1.stringify)($)})}function dU(w,b,$=!1){return!b.length||b.some((Q)=>Q==="array"?Array.isArray(w):Q==="object"?w&&typeof w=="object"&&!Array.isArray(w):typeof w==Q||$&&typeof w>"u")}PY.validSchemaType=dU;function oU({schema:w,opts:b,self:$,errSchemaPath:Q},W,X){if(Array.isArray(W.keyword)?!W.keyword.includes(X):W.keyword!==X)throw Error("ajv implementation error");let J=W.dependencies;if(J===null||J===void 0?void 0:J.some((Y)=>!Object.prototype.hasOwnProperty.call(w,Y)))throw Error(`parent schema must have dependencies of ${X}: ${J.join(",")}`);if(W.validateSchema){if(!W.validateSchema(w[X])){let G=`keyword "${X}" value is invalid at path "${Q}": `+$.errorsText(W.validateSchema.errors);if(b.validateSchema==="log")$.logger.error(G);else throw Error(G)}}}PY.validateKeywordUsage=oU});var RY=E((NY)=>{Object.defineProperty(NY,"__esModule",{value:!0});NY.extendSubschemaMode=NY.extendSubschemaData=NY.getSubschema=void 0;var b0=m(),EY=t();function eU(w,{keyword:b,schemaProp:$,schema:Q,schemaPath:W,errSchemaPath:X,topSchemaRef:J}){if(b!==void 0&&Q!==void 0)throw Error('both "keyword" and "schema" passed, only one allowed');if(b!==void 0){let Y=w.schema[b];return $===void 0?{schema:Y,schemaPath:b0._`${w.schemaPath}${(0,b0.getProperty)(b)}`,errSchemaPath:`${w.errSchemaPath}/${b}`}:{schema:Y[$],schemaPath:b0._`${w.schemaPath}${(0,b0.getProperty)(b)}${(0,b0.getProperty)($)}`,errSchemaPath:`${w.errSchemaPath}/${b}/${(0,EY.escapeFragment)($)}`}}if(Q!==void 0){if(W===void 0||X===void 0||J===void 0)throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:Q,schemaPath:W,topSchemaRef:J,errSchemaPath:X}}throw Error('either "keyword" or "schema" must be passed')}NY.getSubschema=eU;function aU(w,b,{dataProp:$,dataPropType:Q,data:W,dataTypes:X,propertyName:J}){if(W!==void 0&&$!==void 0)throw Error('both "data" and "dataProp" passed, only one allowed');let{gen:Y}=b;if($!==void 0){let{errorPath:H,dataPathArr:z,opts:B}=b,L=Y.let("data",b0._`${b.data}${(0,b0.getProperty)($)}`,!0);G(L),w.errorPath=b0.str`${H}${(0,EY.getErrorPath)($,Q,B.jsPropertySyntax)}`,w.parentDataProperty=b0._`${$}`,w.dataPathArr=[...z,w.parentDataProperty]}if(W!==void 0){let H=W instanceof b0.Name?W:Y.let("data",W,!0);if(G(H),J!==void 0)w.propertyName=J}if(X)w.dataTypes=X;function G(H){w.data=H,w.dataLevel=b.dataLevel+1,w.dataTypes=[],b.definedProperties=new Set,w.parentData=b.data,w.dataNames=[...b.dataNames,H]}}NY.extendSubschemaData=aU;function wA(w,{jtdDiscriminator:b,jtdMetadata:$,compositeRule:Q,createErrors:W,allErrors:X}){if(Q!==void 0)w.compositeRule=Q;if(W!==void 0)w.createErrors=W;if(X!==void 0)w.allErrors=X;w.jtdDiscriminator=b,w.jtdMetadata=$}NY.extendSubschemaMode=wA});var o$=E((JR,SY)=>{SY.exports=function w(b,$){if(b===$)return!0;if(b&&$&&typeof b=="object"&&typeof $=="object"){if(b.constructor!==$.constructor)return!1;var Q,W,X;if(Array.isArray(b)){if(Q=b.length,Q!=$.length)return!1;for(W=Q;W--!==0;)if(!w(b[W],$[W]))return!1;return!0}if(b.constructor===RegExp)return b.source===$.source&&b.flags===$.flags;if(b.valueOf!==Object.prototype.valueOf)return b.valueOf()===$.valueOf();if(b.toString!==Object.prototype.toString)return b.toString()===$.toString();if(X=Object.keys(b),Q=X.length,Q!==Object.keys($).length)return!1;for(W=Q;W--!==0;)if(!Object.prototype.hasOwnProperty.call($,X[W]))return!1;for(W=Q;W--!==0;){var J=X[W];if(!w(b[J],$[J]))return!1}return!0}return b!==b&&$!==$}});var CY=E((YR,vY)=>{var v0=vY.exports=function(w,b,$){if(typeof b=="function")$=b,b={};$=b.cb||$;var Q=typeof $=="function"?$:$.pre||function(){},W=$.post||function(){};N6(b,Q,W,w,"",w)};v0.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};v0.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};v0.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};v0.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 N6(w,b,$,Q,W,X,J,Y,G,H){if(Q&&typeof Q=="object"&&!Array.isArray(Q)){b(Q,W,X,J,Y,G,H);for(var z in Q){var B=Q[z];if(Array.isArray(B)){if(z in v0.arrayKeywords)for(var L=0;L<B.length;L++)N6(w,b,$,B[L],W+"/"+z+"/"+L,X,W,z,Q,L)}else if(z in v0.propsKeywords){if(B&&typeof B=="object")for(var F in B)N6(w,b,$,B[F],W+"/"+z+"/"+QA(F),X,W,z,Q,F)}else if(z in v0.keywords||w.allKeys&&!(z in v0.skipKeywords))N6(w,b,$,B,W+"/"+z,X,W,z,Q)}$(Q,W,X,J,Y,G,H)}}function QA(w){return w.replace(/~/g,"~0").replace(/\//g,"~1")}});var Jb=E((hY)=>{Object.defineProperty(hY,"__esModule",{value:!0});hY.getSchemaRefs=hY.resolveUrl=hY.normalizeId=hY._getFullPath=hY.getFullPath=hY.inlineRef=void 0;var WA=t(),XA=o$(),JA=CY(),YA=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function GA(w,b=!0){if(typeof w=="boolean")return!0;if(b===!0)return!t$(w);if(!b)return!1;return kY(w)<=b}hY.inlineRef=GA;var HA=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function t$(w){for(let b in w){if(HA.has(b))return!0;let $=w[b];if(Array.isArray($)&&$.some(t$))return!0;if(typeof $=="object"&&t$($))return!0}return!1}function kY(w){let b=0;for(let $ in w){if($==="$ref")return 1/0;if(b++,YA.has($))continue;if(typeof w[$]=="object")(0,WA.eachItem)(w[$],(Q)=>b+=kY(Q));if(b===1/0)return 1/0}return b}function _Y(w,b="",$){if($!==!1)b=Dw(b);let Q=w.parse(b);return xY(w,Q)}hY.getFullPath=_Y;function xY(w,b){return w.serialize(b).split("#")[0]+"#"}hY._getFullPath=xY;var zA=/#\/?$/;function Dw(w){return w?w.replace(zA,""):""}hY.normalizeId=Dw;function DA(w,b,$){return $=Dw($),w.resolve(b,$)}hY.resolveUrl=DA;var BA=/^[a-z_][-a-z0-9._]*$/i;function LA(w,b){if(typeof w=="boolean")return{};let{schemaId:$,uriResolver:Q}=this.opts,W=Dw(w[$]||b),X={"":W},J=_Y(Q,W,!1),Y={},G=new Set;return JA(w,{allKeys:!0},(B,L,F,A)=>{if(A===void 0)return;let j=J+L,q=X[A];if(typeof B[$]=="string")q=P.call(this,B[$]);v.call(this,B.$anchor),v.call(this,B.$dynamicAnchor),X[L]=q;function P(S){let u=this.opts.uriResolver.resolve;if(S=Dw(q?u(q,S):S),G.has(S))throw z(S);G.add(S);let _=this.refs[S];if(typeof _=="string")_=this.refs[_];if(typeof _=="object")H(B,_.schema,S);else if(S!==Dw(j))if(S[0]==="#")H(B,Y[S],S),Y[S]=B;else this.refs[S]=j;return S}function v(S){if(typeof S=="string"){if(!BA.test(S))throw Error(`invalid anchor "${S}"`);P.call(this,`#${S}`)}}}),Y;function H(B,L,F){if(L!==void 0&&!XA(B,L))throw z(F)}function z(B){return Error(`reference "${B}" resolves to more than one schema`)}}hY.getSchemaRefs=LA});var Hb=E((eY)=>{Object.defineProperty(eY,"__esModule",{value:!0});eY.getData=eY.KeywordCxt=eY.validateFunctionCode=void 0;var lY=bY(),fY=Xb(),s$=m$(),T6=Xb(),ZA=AY(),Gb=IY(),r$=RY(),R=m(),x=z0(),jA=Jb(),D0=t(),Yb=Wb();function MA(w){if(nY(w)){if(pY(w),iY(w)){qA(w);return}}gY(w,()=>(0,lY.topBoolOrEmptySchema)(w))}eY.validateFunctionCode=MA;function gY({gen:w,validateName:b,schema:$,schemaEnv:Q,opts:W},X){if(W.code.es5)w.func(b,R._`${x.default.data}, ${x.default.valCxt}`,Q.$async,()=>{w.code(R._`"use strict"; ${uY($,W)}`),PA(w,W),w.code(X)});else w.func(b,R._`${x.default.data}, ${VA(W)}`,Q.$async,()=>w.code(uY($,W)).code(X))}function VA(w){return R._`{${x.default.instancePath}="", ${x.default.parentData}, ${x.default.parentDataProperty}, ${x.default.rootData}=${x.default.data}${w.dynamicRef?R._`, ${x.default.dynamicAnchors}={}`:R.nil}}={}`}function PA(w,b){w.if(x.default.valCxt,()=>{if(w.var(x.default.instancePath,R._`${x.default.valCxt}.${x.default.instancePath}`),w.var(x.default.parentData,R._`${x.default.valCxt}.${x.default.parentData}`),w.var(x.default.parentDataProperty,R._`${x.default.valCxt}.${x.default.parentDataProperty}`),w.var(x.default.rootData,R._`${x.default.valCxt}.${x.default.rootData}`),b.dynamicRef)w.var(x.default.dynamicAnchors,R._`${x.default.valCxt}.${x.default.dynamicAnchors}`)},()=>{if(w.var(x.default.instancePath,R._`""`),w.var(x.default.parentData,R._`undefined`),w.var(x.default.parentDataProperty,R._`undefined`),w.var(x.default.rootData,x.default.data),b.dynamicRef)w.var(x.default.dynamicAnchors,R._`{}`)})}function qA(w){let{schema:b,opts:$,gen:Q}=w;gY(w,()=>{if($.$comment&&b.$comment)oY(w);if(RA(w),Q.let(x.default.vErrors,null),Q.let(x.default.errors,0),$.unevaluated)IA(w);dY(w),CA(w)});return}function IA(w){let{gen:b,validateName:$}=w;w.evaluated=b.const("evaluated",R._`${$}.evaluated`),b.if(R._`${w.evaluated}.dynamicProps`,()=>b.assign(R._`${w.evaluated}.props`,R._`undefined`)),b.if(R._`${w.evaluated}.dynamicItems`,()=>b.assign(R._`${w.evaluated}.items`,R._`undefined`))}function uY(w,b){let $=typeof w=="object"&&w[b.schemaId];return $&&(b.code.source||b.code.process)?R._`/*# sourceURL=${$} */`:R.nil}function EA(w,b){if(nY(w)){if(pY(w),iY(w)){NA(w,b);return}}(0,lY.boolOrEmptySchema)(w,b)}function iY({schema:w,self:b}){if(typeof w=="boolean")return!w;for(let $ in w)if(b.RULES.all[$])return!0;return!1}function nY(w){return typeof w.schema!="boolean"}function NA(w,b){let{schema:$,gen:Q,opts:W}=w;if(W.$comment&&$.$comment)oY(w);SA(w),vA(w);let X=Q.const("_errs",x.default.errors);dY(w,X),Q.var(b,R._`${X} === ${x.default.errors}`)}function pY(w){(0,D0.checkUnknownRules)(w),TA(w)}function dY(w,b){if(w.opts.jtd)return cY(w,[],!1,b);let $=(0,fY.getSchemaTypes)(w.schema),Q=(0,fY.coerceAndCheckDataType)(w,$);cY(w,$,!Q,b)}function TA(w){let{schema:b,errSchemaPath:$,opts:Q,self:W}=w;if(b.$ref&&Q.ignoreKeywordsWithRef&&(0,D0.schemaHasRulesButRef)(b,W.RULES))W.logger.warn(`$ref: keywords ignored in schema at path "${$}"`)}function RA(w){let{schema:b,opts:$}=w;if(b.default!==void 0&&$.useDefaults&&$.strictSchema)(0,D0.checkStrictMode)(w,"default is ignored in the schema root")}function SA(w){let b=w.schema[w.opts.schemaId];if(b)w.baseId=(0,jA.resolveUrl)(w.opts.uriResolver,w.baseId,b)}function vA(w){if(w.schema.$async&&!w.schemaEnv.$async)throw Error("async schema in sync schema")}function oY({gen:w,schemaEnv:b,schema:$,errSchemaPath:Q,opts:W}){let X=$.$comment;if(W.$comment===!0)w.code(R._`${x.default.self}.logger.log(${X})`);else if(typeof W.$comment=="function"){let J=R.str`${Q}/$comment`,Y=w.scopeValue("root",{ref:b.root});w.code(R._`${x.default.self}.opts.$comment(${X}, ${J}, ${Y}.schema)`)}}function CA(w){let{gen:b,schemaEnv:$,validateName:Q,ValidationError:W,opts:X}=w;if($.$async)b.if(R._`${x.default.errors} === 0`,()=>b.return(x.default.data),()=>b.throw(R._`new ${W}(${x.default.vErrors})`));else{if(b.assign(R._`${Q}.errors`,x.default.vErrors),X.unevaluated)kA(w);b.return(R._`${x.default.errors} === 0`)}}function kA({gen:w,evaluated:b,props:$,items:Q}){if($ instanceof R.Name)w.assign(R._`${b}.props`,$);if(Q instanceof R.Name)w.assign(R._`${b}.items`,Q)}function cY(w,b,$,Q){let{gen:W,schema:X,data:J,allErrors:Y,opts:G,self:H}=w,{RULES:z}=H;if(X.$ref&&(G.ignoreKeywordsWithRef||!(0,D0.schemaHasRulesButRef)(X,z))){W.block(()=>rY(w,"$ref",z.all.$ref.definition));return}if(!G.jtd)_A(w,b);W.block(()=>{for(let L of z.rules)B(L);B(z.post)});function B(L){if(!(0,s$.shouldUseGroup)(X,L))return;if(L.type){if(W.if((0,T6.checkDataType)(L.type,J,G.strictNumbers)),mY(w,L),b.length===1&&b[0]===L.type&&$)W.else(),(0,T6.reportTypeError)(w);W.endIf()}else mY(w,L);if(!Y)W.if(R._`${x.default.errors} === ${Q||0}`)}}function mY(w,b){let{gen:$,schema:Q,opts:{useDefaults:W}}=w;if(W)(0,ZA.assignDefaults)(w,b.type);$.block(()=>{for(let X of b.rules)if((0,s$.shouldUseRule)(Q,X))rY(w,X.keyword,X.definition,b.type)})}function _A(w,b){if(w.schemaEnv.meta||!w.opts.strictTypes)return;if(xA(w,b),!w.opts.allowUnionTypes)hA(w,b);yA(w,w.dataTypes)}function xA(w,b){if(!b.length)return;if(!w.dataTypes.length){w.dataTypes=b;return}b.forEach(($)=>{if(!tY(w.dataTypes,$))e$(w,`type "${$}" not allowed by context "${w.dataTypes.join(",")}"`)}),uA(w,b)}function hA(w,b){if(b.length>1&&!(b.length===2&&b.includes("null")))e$(w,"use allowUnionTypes to allow union type keyword")}function yA(w,b){let $=w.self.RULES.all;for(let Q in $){let W=$[Q];if(typeof W=="object"&&(0,s$.shouldUseRule)(w.schema,W)){let{type:X}=W.definition;if(X.length&&!X.some((J)=>fA(b,J)))e$(w,`missing type "${X.join(",")}" for keyword "${Q}"`)}}}function fA(w,b){return w.includes(b)||b==="number"&&w.includes("integer")}function tY(w,b){return w.includes(b)||b==="integer"&&w.includes("number")}function uA(w,b){let $=[];for(let Q of w.dataTypes)if(tY(b,Q))$.push(Q);else if(b.includes("integer")&&Q==="number")$.push("integer");w.dataTypes=$}function e$(w,b){let $=w.schemaEnv.baseId+w.errSchemaPath;b+=` at "${$}" (strictTypes)`,(0,D0.checkStrictMode)(w,b,w.opts.strictTypes)}class a${constructor(w,b,$){if((0,Gb.validateKeywordUsage)(w,b,$),this.gen=w.gen,this.allErrors=w.allErrors,this.keyword=$,this.data=w.data,this.schema=w.schema[$],this.$data=b.$data&&w.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,D0.schemaRefOrVal)(w,this.schema,$,this.$data),this.schemaType=b.schemaType,this.parentSchema=w.schema,this.params={},this.it=w,this.def=b,this.$data)this.schemaCode=w.gen.const("vSchema",sY(this.$data,w));else if(this.schemaCode=this.schemaValue,!(0,Gb.validSchemaType)(this.schema,b.schemaType,b.allowUndefined))throw Error(`${$} value must be ${JSON.stringify(b.schemaType)}`);if("code"in b?b.trackErrors:b.errors!==!1)this.errsCount=w.gen.const("_errs",x.default.errors)}result(w,b,$){this.failResult((0,R.not)(w),b,$)}failResult(w,b,$){if(this.gen.if(w),$)$();else this.error();if(b){if(this.gen.else(),b(),this.allErrors)this.gen.endIf()}else if(this.allErrors)this.gen.endIf();else this.gen.else()}pass(w,b){this.failResult((0,R.not)(w),void 0,b)}fail(w){if(w===void 0){if(this.error(),!this.allErrors)this.gen.if(!1);return}if(this.gen.if(w),this.error(),this.allErrors)this.gen.endIf();else this.gen.else()}fail$data(w){if(!this.$data)return this.fail(w);let{schemaCode:b}=this;this.fail(R._`${b} !== undefined && (${(0,R.or)(this.invalid$data(),w)})`)}error(w,b,$){if(b){this.setParams(b),this._error(w,$),this.setParams({});return}this._error(w,$)}_error(w,b){(w?Yb.reportExtraError:Yb.reportError)(this,this.def.error,b)}$dataError(){(0,Yb.reportError)(this,this.def.$dataError||Yb.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error('add "trackErrors" to keyword definition');(0,Yb.resetErrorsCount)(this.gen,this.errsCount)}ok(w){if(!this.allErrors)this.gen.if(w)}setParams(w,b){if(b)Object.assign(this.params,w);else this.params=w}block$data(w,b,$=R.nil){this.gen.block(()=>{this.check$data(w,$),b()})}check$data(w=R.nil,b=R.nil){if(!this.$data)return;let{gen:$,schemaCode:Q,schemaType:W,def:X}=this;if($.if((0,R.or)(R._`${Q} === undefined`,b)),w!==R.nil)$.assign(w,!0);if(W.length||X.validateSchema){if($.elseIf(this.invalid$data()),this.$dataError(),w!==R.nil)$.assign(w,!1)}$.else()}invalid$data(){let{gen:w,schemaCode:b,schemaType:$,def:Q,it:W}=this;return(0,R.or)(X(),J());function X(){if($.length){if(!(b instanceof R.Name))throw Error("ajv implementation error");let Y=Array.isArray($)?$:[$];return R._`${(0,T6.checkDataTypes)(Y,b,W.opts.strictNumbers,T6.DataType.Wrong)}`}return R.nil}function J(){if(Q.validateSchema){let Y=w.scopeValue("validate$data",{ref:Q.validateSchema});return R._`!${Y}(${b})`}return R.nil}}subschema(w,b){let $=(0,r$.getSubschema)(this.it,w);(0,r$.extendSubschemaData)($,this.it,w),(0,r$.extendSubschemaMode)($,w);let Q={...this.it,...$,items:void 0,props:void 0};return EA(Q,b),Q}mergeEvaluated(w,b){let{it:$,gen:Q}=this;if(!$.opts.unevaluated)return;if($.props!==!0&&w.props!==void 0)$.props=D0.mergeEvaluated.props(Q,w.props,$.props,b);if($.items!==!0&&w.items!==void 0)$.items=D0.mergeEvaluated.items(Q,w.items,$.items,b)}mergeValidEvaluated(w,b){let{it:$,gen:Q}=this;if($.opts.unevaluated&&($.props!==!0||$.items!==!0))return Q.if(b,()=>this.mergeEvaluated(w,R.Name)),!0}}eY.KeywordCxt=a$;function rY(w,b,$,Q){let W=new a$(w,$,b);if("code"in $)$.code(W,Q);else if(W.$data&&$.validate)(0,Gb.funcKeywordCode)(W,$);else if("macro"in $)(0,Gb.macroKeywordCode)(W,$);else if($.compile||$.validate)(0,Gb.funcKeywordCode)(W,$)}var cA=/^\/(?:[^~]|~0|~1)*$/,mA=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function sY(w,{dataLevel:b,dataNames:$,dataPathArr:Q}){let W,X;if(w==="")return x.default.rootData;if(w[0]==="/"){if(!cA.test(w))throw Error(`Invalid JSON-pointer: ${w}`);W=w,X=x.default.rootData}else{let H=mA.exec(w);if(!H)throw Error(`Invalid JSON-pointer: ${w}`);let z=+H[1];if(W=H[2],W==="#"){if(z>=b)throw Error(G("property/index",z));return Q[b-z]}if(z>b)throw Error(G("data",z));if(X=$[b-z],!W)return X}let J=X,Y=W.split("/");for(let H of Y)if(H)X=R._`${X}${(0,R.getProperty)((0,D0.unescapeJsonPointer)(H))}`,J=R._`${J} && ${X}`;return J;function G(H,z){return`Cannot access ${H} ${z} levels up, current level is ${b}`}}eY.getData=sY});var R6=E((bG)=>{Object.defineProperty(bG,"__esModule",{value:!0});class wG extends Error{constructor(w){super("validation failed");this.errors=w,this.ajv=this.validation=!0}}bG.default=wG});var zb=E((QG)=>{Object.defineProperty(QG,"__esModule",{value:!0});var w9=Jb();class $G extends Error{constructor(w,b,$,Q){super(Q||`can't resolve reference ${$} from id ${b}`);this.missingRef=(0,w9.resolveUrl)(w,b,$),this.missingSchema=(0,w9.normalizeId)((0,w9.getFullPath)(w,this.missingRef))}}QG.default=$G});var v6=E((JG)=>{Object.defineProperty(JG,"__esModule",{value:!0});JG.resolveSchema=JG.getCompilingSchema=JG.resolveRef=JG.compileSchema=JG.SchemaEnv=void 0;var o1=m(),pA=R6(),l0=z0(),t1=Jb(),WG=t(),dA=Hb();class Db{constructor(w){var b;this.refs={},this.dynamicAnchors={};let $;if(typeof w.schema=="object")$=w.schema;this.schema=w.schema,this.schemaId=w.schemaId,this.root=w.root||this,this.baseId=(b=w.baseId)!==null&&b!==void 0?b:(0,t1.normalizeId)($===null||$===void 0?void 0:$[w.schemaId||"$id"]),this.schemaPath=w.schemaPath,this.localRefs=w.localRefs,this.meta=w.meta,this.$async=$===null||$===void 0?void 0:$.$async,this.refs={}}}JG.SchemaEnv=Db;function $9(w){let b=XG.call(this,w);if(b)return b;let $=(0,t1.getFullPath)(this.opts.uriResolver,w.root.baseId),{es5:Q,lines:W}=this.opts.code,{ownProperties:X}=this.opts,J=new o1.CodeGen(this.scope,{es5:Q,lines:W,ownProperties:X}),Y;if(w.$async)Y=J.scopeValue("Error",{ref:pA.default,code:o1._`require("ajv/dist/runtime/validation_error").default`});let G=J.scopeName("validate");w.validateName=G;let H={gen:J,allErrors:this.opts.allErrors,data:l0.default.data,parentData:l0.default.parentData,parentDataProperty:l0.default.parentDataProperty,dataNames:[l0.default.data],dataPathArr:[o1.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:J.scopeValue("schema",this.opts.code.source===!0?{ref:w.schema,code:(0,o1.stringify)(w.schema)}:{ref:w.schema}),validateName:G,ValidationError:Y,schema:w.schema,schemaEnv:w,rootId:$,baseId:w.baseId||$,schemaPath:o1.nil,errSchemaPath:w.schemaPath||(this.opts.jtd?"":"#"),errorPath:o1._`""`,opts:this.opts,self:this},z;try{this._compilations.add(w),(0,dA.validateFunctionCode)(H),J.optimize(this.opts.code.optimize);let B=J.toString();if(z=`${J.scopeRefs(l0.default.scope)}return ${B}`,this.opts.code.process)z=this.opts.code.process(z,w);let F=Function(`${l0.default.self}`,`${l0.default.scope}`,z)(this,this.scope.get());if(this.scope.value(G,{ref:F}),F.errors=null,F.schema=w.schema,F.schemaEnv=w,w.$async)F.$async=!0;if(this.opts.code.source===!0)F.source={validateName:G,validateCode:B,scopeValues:J._values};if(this.opts.unevaluated){let{props:A,items:j}=H;if(F.evaluated={props:A instanceof o1.Name?void 0:A,items:j instanceof o1.Name?void 0:j,dynamicProps:A instanceof o1.Name,dynamicItems:j instanceof o1.Name},F.source)F.source.evaluated=(0,o1.stringify)(F.evaluated)}return w.validate=F,w}catch(B){if(delete w.validate,delete w.validateName,z)this.logger.error("Error compiling schema, function code:",z);throw B}finally{this._compilations.delete(w)}}JG.compileSchema=$9;function oA(w,b,$){var Q;$=(0,t1.resolveUrl)(this.opts.uriResolver,b,$);let W=w.refs[$];if(W)return W;let X=sA.call(this,w,$);if(X===void 0){let J=(Q=w.localRefs)===null||Q===void 0?void 0:Q[$],{schemaId:Y}=this.opts;if(J)X=new Db({schema:J,schemaId:Y,root:w,baseId:b})}if(X===void 0)return;return w.refs[$]=tA.call(this,X)}JG.resolveRef=oA;function tA(w){if((0,t1.inlineRef)(w.schema,this.opts.inlineRefs))return w.schema;return w.validate?w:$9.call(this,w)}function XG(w){for(let b of this._compilations)if(rA(b,w))return b}JG.getCompilingSchema=XG;function rA(w,b){return w.schema===b.schema&&w.root===b.root&&w.baseId===b.baseId}function sA(w,b){let $;while(typeof($=this.refs[b])=="string")b=$;return $||this.schemas[b]||S6.call(this,w,b)}function S6(w,b){let $=this.opts.uriResolver.parse(b),Q=(0,t1._getFullPath)(this.opts.uriResolver,$),W=(0,t1.getFullPath)(this.opts.uriResolver,w.baseId,void 0);if(Object.keys(w.schema).length>0&&Q===W)return b9.call(this,$,w);let X=(0,t1.normalizeId)(Q),J=this.refs[X]||this.schemas[X];if(typeof J=="string"){let Y=S6.call(this,w,J);if(typeof(Y===null||Y===void 0?void 0:Y.schema)!=="object")return;return b9.call(this,$,Y)}if(typeof(J===null||J===void 0?void 0:J.schema)!=="object")return;if(!J.validate)$9.call(this,J);if(X===(0,t1.normalizeId)(b)){let{schema:Y}=J,{schemaId:G}=this.opts,H=Y[G];if(H)W=(0,t1.resolveUrl)(this.opts.uriResolver,W,H);return new Db({schema:Y,schemaId:G,root:w,baseId:W})}return b9.call(this,$,J)}JG.resolveSchema=S6;var eA=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function b9(w,{baseId:b,schema:$,root:Q}){var W;if(((W=w.fragment)===null||W===void 0?void 0:W[0])!=="/")return;for(let Y of w.fragment.slice(1).split("/")){if(typeof $==="boolean")return;let G=$[(0,WG.unescapeFragment)(Y)];if(G===void 0)return;$=G;let H=typeof $==="object"&&$[this.opts.schemaId];if(!eA.has(Y)&&H)b=(0,t1.resolveUrl)(this.opts.uriResolver,b,H)}let X;if(typeof $!="boolean"&&$.$ref&&!(0,WG.schemaHasRulesButRef)($,this.RULES)){let Y=(0,t1.resolveUrl)(this.opts.uriResolver,b,$.$ref);X=S6.call(this,Q,Y)}let{schemaId:J}=this.opts;if(X=X||new Db({schema:$,schemaId:J,root:Q,baseId:b}),X.schema!==X.root.schema)return X;return}});var GG=E((LR,QK)=>{QK.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 W9=E((FR,BG)=>{var WK=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),zG=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 Q9(w){let b="",$=0,Q=0;for(Q=0;Q<w.length;Q++){if($=w[Q].charCodeAt(0),$===48)continue;if(!($>=48&&$<=57||$>=65&&$<=70||$>=97&&$<=102))return"";b+=w[Q];break}for(Q+=1;Q<w.length;Q++){if($=w[Q].charCodeAt(0),!($>=48&&$<=57||$>=65&&$<=70||$>=97&&$<=102))return"";b+=w[Q]}return b}var XK=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function HG(w){return w.length=0,!0}function JK(w,b,$){if(w.length){let Q=Q9(w);if(Q!=="")b.push(Q);else return $.error=!0,!1;w.length=0}return!0}function YK(w){let b=0,$={error:!1,address:"",zone:""},Q=[],W=[],X=!1,J=!1,Y=JK;for(let G=0;G<w.length;G++){let H=w[G];if(H==="["||H==="]")continue;if(H===":"){if(X===!0)J=!0;if(!Y(W,Q,$))break;if(++b>7){$.error=!0;break}if(G>0&&w[G-1]===":")X=!0;Q.push(":");continue}else if(H==="%"){if(!Y(W,Q,$))break;Y=HG}else{W.push(H);continue}}if(W.length)if(Y===HG)$.zone=W.join("");else if(J)Q.push(W.join(""));else Q.push(Q9(W));return $.address=Q.join(""),$}function DG(w){if(GK(w,":")<2)return{host:w,isIPV6:!1};let b=YK(w);if(!b.error){let{address:$,address:Q}=b;if(b.zone)$+="%"+b.zone,Q+="%25"+b.zone;return{host:$,isIPV6:!0,escapedHost:Q}}else return{host:w,isIPV6:!1}}function GK(w,b){let $=0;for(let Q=0;Q<w.length;Q++)if(w[Q]===b)$++;return $}function HK(w){let b=w,$=[],Q=-1,W=0;while(W=b.length){if(W===1)if(b===".")break;else if(b==="/"){$.push("/");break}else{$.push(b);break}else if(W===2){if(b[0]==="."){if(b[1]===".")break;else if(b[1]==="/"){b=b.slice(2);continue}}else if(b[0]==="/"){if(b[1]==="."||b[1]==="/"){$.push("/");break}}}else if(W===3){if(b==="/.."){if($.length!==0)$.pop();$.push("/");break}}if(b[0]==="."){if(b[1]==="."){if(b[2]==="/"){b=b.slice(3);continue}}else if(b[1]==="/"){b=b.slice(2);continue}}else if(b[0]==="/"){if(b[1]==="."){if(b[2]==="/"){b=b.slice(2);continue}else if(b[2]==="."){if(b[3]==="/"){if(b=b.slice(3),$.length!==0)$.pop();continue}}}}if((Q=b.indexOf("/",1))===-1){$.push(b);break}else $.push(b.slice(0,Q)),b=b.slice(Q)}return $.join("")}function zK(w,b){let $=b!==!0?escape:unescape;if(w.scheme!==void 0)w.scheme=$(w.scheme);if(w.userinfo!==void 0)w.userinfo=$(w.userinfo);if(w.host!==void 0)w.host=$(w.host);if(w.path!==void 0)w.path=$(w.path);if(w.query!==void 0)w.query=$(w.query);if(w.fragment!==void 0)w.fragment=$(w.fragment);return w}function DK(w){let b=[];if(w.userinfo!==void 0)b.push(w.userinfo),b.push("@");if(w.host!==void 0){let $=unescape(w.host);if(!zG($)){let Q=DG($);if(Q.isIPV6===!0)$=`[${Q.escapedHost}]`;else $=w.host}b.push($)}if(typeof w.port==="number"||typeof w.port==="string")b.push(":"),b.push(String(w.port));return b.length?b.join(""):void 0}BG.exports={nonSimpleDomain:XK,recomposeAuthority:DK,normalizeComponentEncoding:zK,removeDotSegments:HK,isIPv4:zG,isUUID:WK,normalizeIPv6:DG,stringArrayToHexStripped:Q9}});var KG=E((UR,AG)=>{var{isUUID:BK}=W9(),LK=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,FK=["http","https","ws","wss","urn","urn:uuid"];function UK(w){return FK.indexOf(w)!==-1}function X9(w){if(w.secure===!0)return!0;else if(w.secure===!1)return!1;else if(w.scheme)return w.scheme.length===3&&(w.scheme[0]==="w"||w.scheme[0]==="W")&&(w.scheme[1]==="s"||w.scheme[1]==="S")&&(w.scheme[2]==="s"||w.scheme[2]==="S");else return!1}function LG(w){if(!w.host)w.error=w.error||"HTTP URIs must have a host.";return w}function FG(w){let b=String(w.scheme).toLowerCase()==="https";if(w.port===(b?443:80)||w.port==="")w.port=void 0;if(!w.path)w.path="/";return w}function AK(w){return w.secure=X9(w),w.resourceName=(w.path||"/")+(w.query?"?"+w.query:""),w.path=void 0,w.query=void 0,w}function KK(w){if(w.port===(X9(w)?443:80)||w.port==="")w.port=void 0;if(typeof w.secure==="boolean")w.scheme=w.secure?"wss":"ws",w.secure=void 0;if(w.resourceName){let[b,$]=w.resourceName.split("?");w.path=b&&b!=="/"?b:void 0,w.query=$,w.resourceName=void 0}return w.fragment=void 0,w}function OK(w,b){if(!w.path)return w.error="URN can not be parsed",w;let $=w.path.match(LK);if($){let Q=b.scheme||w.scheme||"urn";w.nid=$[1].toLowerCase(),w.nss=$[2];let W=`${Q}:${b.nid||w.nid}`,X=J9(W);if(w.path=void 0,X)w=X.parse(w,b)}else w.error=w.error||"URN can not be parsed.";return w}function ZK(w,b){if(w.nid===void 0)throw Error("URN without nid cannot be serialized");let $=b.scheme||w.scheme||"urn",Q=w.nid.toLowerCase(),W=`${$}:${b.nid||Q}`,X=J9(W);if(X)w=X.serialize(w,b);let J=w,Y=w.nss;return J.path=`${Q||b.nid}:${Y}`,b.skipEscape=!0,J}function jK(w,b){let $=w;if($.uuid=$.nss,$.nss=void 0,!b.tolerant&&(!$.uuid||!BK($.uuid)))$.error=$.error||"UUID is not valid.";return $}function MK(w){let b=w;return b.nss=(w.uuid||"").toLowerCase(),b}var UG={scheme:"http",domainHost:!0,parse:LG,serialize:FG},VK={scheme:"https",domainHost:UG.domainHost,parse:LG,serialize:FG},C6={scheme:"ws",domainHost:!0,parse:AK,serialize:KK},PK={scheme:"wss",domainHost:C6.domainHost,parse:C6.parse,serialize:C6.serialize},qK={scheme:"urn",parse:OK,serialize:ZK,skipNormalize:!0},IK={scheme:"urn:uuid",parse:jK,serialize:MK,skipNormalize:!0},k6={http:UG,https:VK,ws:C6,wss:PK,urn:qK,"urn:uuid":IK};Object.setPrototypeOf(k6,null);function J9(w){return w&&(k6[w]||k6[w.toLowerCase()])||void 0}AG.exports={wsIsSecure:X9,SCHEMES:k6,isValidSchemeName:UK,getSchemeHandler:J9}});var jG=E((AR,x6)=>{var{normalizeIPv6:EK,removeDotSegments:Bb,recomposeAuthority:NK,normalizeComponentEncoding:_6,isIPv4:TK,nonSimpleDomain:RK}=W9(),{SCHEMES:SK,getSchemeHandler:OG}=KG();function vK(w,b){if(typeof w==="string")w=$0(B0(w,b),b);else if(typeof w==="object")w=B0($0(w,b),b);return w}function CK(w,b,$){let Q=$?Object.assign({scheme:"null"},$):{scheme:"null"},W=ZG(B0(w,Q),B0(b,Q),Q,!0);return Q.skipEscape=!0,$0(W,Q)}function ZG(w,b,$,Q){let W={};if(!Q)w=B0($0(w,$),$),b=B0($0(b,$),$);if($=$||{},!$.tolerant&&b.scheme)W.scheme=b.scheme,W.userinfo=b.userinfo,W.host=b.host,W.port=b.port,W.path=Bb(b.path||""),W.query=b.query;else{if(b.userinfo!==void 0||b.host!==void 0||b.port!==void 0)W.userinfo=b.userinfo,W.host=b.host,W.port=b.port,W.path=Bb(b.path||""),W.query=b.query;else{if(!b.path)if(W.path=w.path,b.query!==void 0)W.query=b.query;else W.query=w.query;else{if(b.path[0]==="/")W.path=Bb(b.path);else{if((w.userinfo!==void 0||w.host!==void 0||w.port!==void 0)&&!w.path)W.path="/"+b.path;else if(!w.path)W.path=b.path;else W.path=w.path.slice(0,w.path.lastIndexOf("/")+1)+b.path;W.path=Bb(W.path)}W.query=b.query}W.userinfo=w.userinfo,W.host=w.host,W.port=w.port}W.scheme=w.scheme}return W.fragment=b.fragment,W}function kK(w,b,$){if(typeof w==="string")w=unescape(w),w=$0(_6(B0(w,$),!0),{...$,skipEscape:!0});else if(typeof w==="object")w=$0(_6(w,!0),{...$,skipEscape:!0});if(typeof b==="string")b=unescape(b),b=$0(_6(B0(b,$),!0),{...$,skipEscape:!0});else if(typeof b==="object")b=$0(_6(b,!0),{...$,skipEscape:!0});return w.toLowerCase()===b.toLowerCase()}function $0(w,b){let $={host:w.host,scheme:w.scheme,userinfo:w.userinfo,port:w.port,path:w.path,query:w.query,nid:w.nid,nss:w.nss,uuid:w.uuid,fragment:w.fragment,reference:w.reference,resourceName:w.resourceName,secure:w.secure,error:""},Q=Object.assign({},b),W=[],X=OG(Q.scheme||$.scheme);if(X&&X.serialize)X.serialize($,Q);if($.path!==void 0)if(!Q.skipEscape){if($.path=escape($.path),$.scheme!==void 0)$.path=$.path.split("%3A").join(":")}else $.path=unescape($.path);if(Q.reference!=="suffix"&&$.scheme)W.push($.scheme,":");let J=NK($);if(J!==void 0){if(Q.reference!=="suffix")W.push("//");if(W.push(J),$.path&&$.path[0]!=="/")W.push("/")}if($.path!==void 0){let Y=$.path;if(!Q.absolutePath&&(!X||!X.absolutePath))Y=Bb(Y);if(J===void 0&&Y[0]==="/"&&Y[1]==="/")Y="/%2F"+Y.slice(2);W.push(Y)}if($.query!==void 0)W.push("?",$.query);if($.fragment!==void 0)W.push("#",$.fragment);return W.join("")}var _K=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function B0(w,b){let $=Object.assign({},b),Q={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},W=!1;if($.reference==="suffix")if($.scheme)w=$.scheme+":"+w;else w="//"+w;let X=w.match(_K);if(X){if(Q.scheme=X[1],Q.userinfo=X[3],Q.host=X[4],Q.port=parseInt(X[5],10),Q.path=X[6]||"",Q.query=X[7],Q.fragment=X[8],isNaN(Q.port))Q.port=X[5];if(Q.host)if(TK(Q.host)===!1){let G=EK(Q.host);Q.host=G.host.toLowerCase(),W=G.isIPV6}else W=!0;if(Q.scheme===void 0&&Q.userinfo===void 0&&Q.host===void 0&&Q.port===void 0&&Q.query===void 0&&!Q.path)Q.reference="same-document";else if(Q.scheme===void 0)Q.reference="relative";else if(Q.fragment===void 0)Q.reference="absolute";else Q.reference="uri";if($.reference&&$.reference!=="suffix"&&$.reference!==Q.reference)Q.error=Q.error||"URI is not a "+$.reference+" reference.";let J=OG($.scheme||Q.scheme);if(!$.unicodeSupport&&(!J||!J.unicodeSupport)){if(Q.host&&($.domainHost||J&&J.domainHost)&&W===!1&&RK(Q.host))try{Q.host=URL.domainToASCII(Q.host.toLowerCase())}catch(Y){Q.error=Q.error||"Host's domain name can not be converted to ASCII: "+Y}}if(!J||J&&!J.skipNormalize){if(w.indexOf("%")!==-1){if(Q.scheme!==void 0)Q.scheme=unescape(Q.scheme);if(Q.host!==void 0)Q.host=unescape(Q.host)}if(Q.path)Q.path=escape(unescape(Q.path));if(Q.fragment)Q.fragment=encodeURI(decodeURIComponent(Q.fragment))}if(J&&J.parse)J.parse(Q,$)}else Q.error=Q.error||"URI can not be parsed.";return Q}var Y9={SCHEMES:SK,normalize:vK,resolve:CK,resolveComponent:ZG,equal:kK,serialize:$0,parse:B0};x6.exports=Y9;x6.exports.default=Y9;x6.exports.fastUri=Y9});var PG=E((VG)=>{Object.defineProperty(VG,"__esModule",{value:!0});var MG=jG();MG.code='require("ajv/dist/runtime/uri").default';VG.default=MG});var vG=E((L0)=>{Object.defineProperty(L0,"__esModule",{value:!0});L0.CodeGen=L0.Name=L0.nil=L0.stringify=L0.str=L0._=L0.KeywordCxt=void 0;var hK=Hb();Object.defineProperty(L0,"KeywordCxt",{enumerable:!0,get:function(){return hK.KeywordCxt}});var Bw=m();Object.defineProperty(L0,"_",{enumerable:!0,get:function(){return Bw._}});Object.defineProperty(L0,"str",{enumerable:!0,get:function(){return Bw.str}});Object.defineProperty(L0,"stringify",{enumerable:!0,get:function(){return Bw.stringify}});Object.defineProperty(L0,"nil",{enumerable:!0,get:function(){return Bw.nil}});Object.defineProperty(L0,"Name",{enumerable:!0,get:function(){return Bw.Name}});Object.defineProperty(L0,"CodeGen",{enumerable:!0,get:function(){return Bw.CodeGen}});var yK=R6(),TG=zb(),fK=c$(),Lb=v6(),uK=m(),Fb=Jb(),h6=Xb(),H9=t(),qG=GG(),cK=PG(),RG=(w,b)=>new RegExp(w,b);RG.code="new RegExp";var mK=["removeAdditional","useDefaults","coerceTypes"],lK=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),gK={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."},iK={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},IG=200;function nK(w){var b,$,Q,W,X,J,Y,G,H,z,B,L,F,A,j,q,P,v,S,u,_,S1,l1,v1,r0;let g1=w.strict,Tw=(b=w.code)===null||b===void 0?void 0:b.optimize,Z0=Tw===!0||Tw===void 0?1:Tw||0,AQ=(Q=($=w.code)===null||$===void 0?void 0:$.regExp)!==null&&Q!==void 0?Q:RG,l3=(W=w.uriResolver)!==null&&W!==void 0?W:cK.default;return{strictSchema:(J=(X=w.strictSchema)!==null&&X!==void 0?X:g1)!==null&&J!==void 0?J:!0,strictNumbers:(G=(Y=w.strictNumbers)!==null&&Y!==void 0?Y:g1)!==null&&G!==void 0?G:!0,strictTypes:(z=(H=w.strictTypes)!==null&&H!==void 0?H:g1)!==null&&z!==void 0?z:"log",strictTuples:(L=(B=w.strictTuples)!==null&&B!==void 0?B:g1)!==null&&L!==void 0?L:"log",strictRequired:(A=(F=w.strictRequired)!==null&&F!==void 0?F:g1)!==null&&A!==void 0?A:!1,code:w.code?{...w.code,optimize:Z0,regExp:AQ}:{optimize:Z0,regExp:AQ},loopRequired:(j=w.loopRequired)!==null&&j!==void 0?j:IG,loopEnum:(q=w.loopEnum)!==null&&q!==void 0?q:IG,meta:(P=w.meta)!==null&&P!==void 0?P:!0,messages:(v=w.messages)!==null&&v!==void 0?v:!0,inlineRefs:(S=w.inlineRefs)!==null&&S!==void 0?S:!0,schemaId:(u=w.schemaId)!==null&&u!==void 0?u:"$id",addUsedSchema:(_=w.addUsedSchema)!==null&&_!==void 0?_:!0,validateSchema:(S1=w.validateSchema)!==null&&S1!==void 0?S1:!0,validateFormats:(l1=w.validateFormats)!==null&&l1!==void 0?l1:!0,unicodeRegExp:(v1=w.unicodeRegExp)!==null&&v1!==void 0?v1:!0,int32range:(r0=w.int32range)!==null&&r0!==void 0?r0:!0,uriResolver:l3}}class y6{constructor(w={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,w=this.opts={...w,...nK(w)};let{es5:b,lines:$}=this.opts.code;this.scope=new uK.ValueScope({scope:{},prefixes:lK,es5:b,lines:$}),this.logger=sK(w.logger);let Q=w.validateFormats;if(w.validateFormats=!1,this.RULES=(0,fK.getRules)(),EG.call(this,gK,w,"NOT SUPPORTED"),EG.call(this,iK,w,"DEPRECATED","warn"),this._metaOpts=tK.call(this),w.formats)dK.call(this);if(this._addVocabularies(),this._addDefaultMetaSchema(),w.keywords)oK.call(this,w.keywords);if(typeof w.meta=="object")this.addMetaSchema(w.meta);pK.call(this),w.validateFormats=Q}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:w,meta:b,schemaId:$}=this.opts,Q=qG;if($==="id")Q={...qG},Q.id=Q.$id,delete Q.$id;if(b&&w)this.addMetaSchema(Q,Q[$],!1)}defaultMeta(){let{meta:w,schemaId:b}=this.opts;return this.opts.defaultMeta=typeof w=="object"?w[b]||w:void 0}validate(w,b){let $;if(typeof w=="string"){if($=this.getSchema(w),!$)throw Error(`no schema with key or ref "${w}"`)}else $=this.compile(w);let Q=$(b);if(!("$async"in $))this.errors=$.errors;return Q}compile(w,b){let $=this._addSchema(w,b);return $.validate||this._compileSchemaEnv($)}compileAsync(w,b){if(typeof this.opts.loadSchema!="function")throw Error("options.loadSchema should be a function");let{loadSchema:$}=this.opts;return Q.call(this,w,b);async function Q(H,z){await W.call(this,H.$schema);let B=this._addSchema(H,z);return B.validate||X.call(this,B)}async function W(H){if(H&&!this.getSchema(H))await Q.call(this,{$ref:H},!0)}async function X(H){try{return this._compileSchemaEnv(H)}catch(z){if(!(z instanceof TG.default))throw z;return J.call(this,z),await Y.call(this,z.missingSchema),X.call(this,H)}}function J({missingSchema:H,missingRef:z}){if(this.refs[H])throw Error(`AnySchema ${H} is loaded but ${z} cannot be resolved`)}async function Y(H){let z=await G.call(this,H);if(!this.refs[H])await W.call(this,z.$schema);if(!this.refs[H])this.addSchema(z,H,b)}async function G(H){let z=this._loading[H];if(z)return z;try{return await(this._loading[H]=$(H))}finally{delete this._loading[H]}}}addSchema(w,b,$,Q=this.opts.validateSchema){if(Array.isArray(w)){for(let X of w)this.addSchema(X,void 0,$,Q);return this}let W;if(typeof w==="object"){let{schemaId:X}=this.opts;if(W=w[X],W!==void 0&&typeof W!="string")throw Error(`schema ${X} must be string`)}return b=(0,Fb.normalizeId)(b||W),this._checkUnique(b),this.schemas[b]=this._addSchema(w,$,b,Q,!0),this}addMetaSchema(w,b,$=this.opts.validateSchema){return this.addSchema(w,b,!0,$),this}validateSchema(w,b){if(typeof w=="boolean")return!0;let $;if($=w.$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 Q=this.validate($,w);if(!Q&&b){let W="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(W);else throw Error(W)}return Q}getSchema(w){let b;while(typeof(b=NG.call(this,w))=="string")w=b;if(b===void 0){let{schemaId:$}=this.opts,Q=new Lb.SchemaEnv({schema:{},schemaId:$});if(b=Lb.resolveSchema.call(this,Q,w),!b)return;this.refs[w]=b}return b.validate||this._compileSchemaEnv(b)}removeSchema(w){if(w instanceof RegExp)return this._removeAllSchemas(this.schemas,w),this._removeAllSchemas(this.refs,w),this;switch(typeof w){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let b=NG.call(this,w);if(typeof b=="object")this._cache.delete(b.schema);return delete this.schemas[w],delete this.refs[w],this}case"object":{let b=w;this._cache.delete(b);let $=w[this.opts.schemaId];if($)$=(0,Fb.normalizeId)($),delete this.schemas[$],delete this.refs[$];return this}default:throw Error("ajv.removeSchema: invalid parameter")}}addVocabulary(w){for(let b of w)this.addKeyword(b);return this}addKeyword(w,b){let $;if(typeof w=="string"){if($=w,typeof b=="object")this.logger.warn("these parameters are deprecated, see docs for addKeyword"),b.keyword=$}else if(typeof w=="object"&&b===void 0){if(b=w,$=b.keyword,Array.isArray($)&&!$.length)throw Error("addKeywords: keyword must be string or non-empty array")}else throw Error("invalid addKeywords parameters");if(aK.call(this,$,b),!b)return(0,H9.eachItem)($,(W)=>G9.call(this,W)),this;bO.call(this,b);let Q={...b,type:(0,h6.getJSONTypes)(b.type),schemaType:(0,h6.getJSONTypes)(b.schemaType)};return(0,H9.eachItem)($,Q.type.length===0?(W)=>G9.call(this,W,Q):(W)=>Q.type.forEach((X)=>G9.call(this,W,Q,X))),this}getKeyword(w){let b=this.RULES.all[w];return typeof b=="object"?b.definition:!!b}removeKeyword(w){let{RULES:b}=this;delete b.keywords[w],delete b.all[w];for(let $ of b.rules){let Q=$.rules.findIndex((W)=>W.keyword===w);if(Q>=0)$.rules.splice(Q,1)}return this}addFormat(w,b){if(typeof b=="string")b=new RegExp(b);return this.formats[w]=b,this}errorsText(w=this.errors,{separator:b=", ",dataVar:$="data"}={}){if(!w||w.length===0)return"No errors";return w.map((Q)=>`${$}${Q.instancePath} ${Q.message}`).reduce((Q,W)=>Q+b+W)}$dataMetaSchema(w,b){let $=this.RULES.all;w=JSON.parse(JSON.stringify(w));for(let Q of b){let W=Q.split("/").slice(1),X=w;for(let J of W)X=X[J];for(let J in $){let Y=$[J];if(typeof Y!="object")continue;let{$data:G}=Y.definition,H=X[J];if(G&&H)X[J]=SG(H)}}return w}_removeAllSchemas(w,b){for(let $ in w){let Q=w[$];if(!b||b.test($)){if(typeof Q=="string")delete w[$];else if(Q&&!Q.meta)this._cache.delete(Q.schema),delete w[$]}}}_addSchema(w,b,$,Q=this.opts.validateSchema,W=this.opts.addUsedSchema){let X,{schemaId:J}=this.opts;if(typeof w=="object")X=w[J];else if(this.opts.jtd)throw Error("schema must be object");else if(typeof w!="boolean")throw Error("schema must be object or boolean");let Y=this._cache.get(w);if(Y!==void 0)return Y;$=(0,Fb.normalizeId)(X||$);let G=Fb.getSchemaRefs.call(this,w,$);if(Y=new Lb.SchemaEnv({schema:w,schemaId:J,meta:b,baseId:$,localRefs:G}),this._cache.set(Y.schema,Y),W&&!$.startsWith("#")){if($)this._checkUnique($);this.refs[$]=Y}if(Q)this.validateSchema(w,!0);return Y}_checkUnique(w){if(this.schemas[w]||this.refs[w])throw Error(`schema with key or id "${w}" already exists`)}_compileSchemaEnv(w){if(w.meta)this._compileMetaSchema(w);else Lb.compileSchema.call(this,w);if(!w.validate)throw Error("ajv implementation error");return w.validate}_compileMetaSchema(w){let b=this.opts;this.opts=this._metaOpts;try{Lb.compileSchema.call(this,w)}finally{this.opts=b}}}y6.ValidationError=yK.default;y6.MissingRefError=TG.default;L0.default=y6;function EG(w,b,$,Q="error"){for(let W in w){let X=W;if(X in b)this.logger[Q](`${$}: option ${W}. ${w[X]}`)}}function NG(w){return w=(0,Fb.normalizeId)(w),this.schemas[w]||this.refs[w]}function pK(){let w=this.opts.schemas;if(!w)return;if(Array.isArray(w))this.addSchema(w);else for(let b in w)this.addSchema(w[b],b)}function dK(){for(let w in this.opts.formats){let b=this.opts.formats[w];if(b)this.addFormat(w,b)}}function oK(w){if(Array.isArray(w)){this.addVocabulary(w);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let b in w){let $=w[b];if(!$.keyword)$.keyword=b;this.addKeyword($)}}function tK(){let w={...this.opts};for(let b of mK)delete w[b];return w}var rK={log(){},warn(){},error(){}};function sK(w){if(w===!1)return rK;if(w===void 0)return console;if(w.log&&w.warn&&w.error)return w;throw Error("logger must implement log, warn and error methods")}var eK=/^[a-z_$][a-z0-9_$:-]*$/i;function aK(w,b){let{RULES:$}=this;if((0,H9.eachItem)(w,(Q)=>{if($.keywords[Q])throw Error(`Keyword ${Q} is already defined`);if(!eK.test(Q))throw Error(`Keyword ${Q} has invalid name`)}),!b)return;if(b.$data&&!(("code"in b)||("validate"in b)))throw Error('$data keyword must have "code" or "validate" function')}function G9(w,b,$){var Q;let W=b===null||b===void 0?void 0:b.post;if($&&W)throw Error('keyword with "post" flag cannot have "type"');let{RULES:X}=this,J=W?X.post:X.rules.find(({type:G})=>G===$);if(!J)J={type:$,rules:[]},X.rules.push(J);if(X.keywords[w]=!0,!b)return;let Y={keyword:w,definition:{...b,type:(0,h6.getJSONTypes)(b.type),schemaType:(0,h6.getJSONTypes)(b.schemaType)}};if(b.before)wO.call(this,J,Y,b.before);else J.rules.push(Y);X.all[w]=Y,(Q=b.implements)===null||Q===void 0||Q.forEach((G)=>this.addKeyword(G))}function wO(w,b,$){let Q=w.rules.findIndex((W)=>W.keyword===$);if(Q>=0)w.rules.splice(Q,0,b);else w.rules.push(b),this.logger.warn(`rule ${$} is not defined`)}function bO(w){let{metaSchema:b}=w;if(b===void 0)return;if(w.$data&&this.opts.$data)b=SG(b);w.validateSchema=this.compile(b,!0)}var $O={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function SG(w){return{anyOf:[w,$O]}}});var kG=E((CG)=>{Object.defineProperty(CG,"__esModule",{value:!0});var XO={keyword:"id",code(){throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};CG.default=XO});var uG=E((yG)=>{Object.defineProperty(yG,"__esModule",{value:!0});yG.callRef=yG.getValidate=void 0;var YO=zb(),_G=c1(),T1=m(),Lw=z0(),xG=v6(),f6=t(),GO={keyword:"$ref",schemaType:"string",code(w){let{gen:b,schema:$,it:Q}=w,{baseId:W,schemaEnv:X,validateName:J,opts:Y,self:G}=Q,{root:H}=X;if(($==="#"||$==="#/")&&W===H.baseId)return B();let z=xG.resolveRef.call(G,H,W,$);if(z===void 0)throw new YO.default(Q.opts.uriResolver,W,$);if(z instanceof xG.SchemaEnv)return L(z);return F(z);function B(){if(X===H)return u6(w,J,X,X.$async);let A=b.scopeValue("root",{ref:H});return u6(w,T1._`${A}.validate`,H,H.$async)}function L(A){let j=hG(w,A);u6(w,j,A,A.$async)}function F(A){let j=b.scopeValue("schema",Y.code.source===!0?{ref:A,code:(0,T1.stringify)(A)}:{ref:A}),q=b.name("valid"),P=w.subschema({schema:A,dataTypes:[],schemaPath:T1.nil,topSchemaRef:j,errSchemaPath:$},q);w.mergeEvaluated(P),w.ok(q)}}};function hG(w,b){let{gen:$}=w;return b.validate?$.scopeValue("validate",{ref:b.validate}):T1._`${$.scopeValue("wrapper",{ref:b})}.validate`}yG.getValidate=hG;function u6(w,b,$,Q){let{gen:W,it:X}=w,{allErrors:J,schemaEnv:Y,opts:G}=X,H=G.passContext?Lw.default.this:T1.nil;if(Q)z();else B();function z(){if(!Y.$async)throw Error("async schema referenced by sync schema");let A=W.let("valid");W.try(()=>{if(W.code(T1._`await ${(0,_G.callValidateCode)(w,b,H)}`),F(b),!J)W.assign(A,!0)},(j)=>{if(W.if(T1._`!(${j} instanceof ${X.ValidationError})`,()=>W.throw(j)),L(j),!J)W.assign(A,!1)}),w.ok(A)}function B(){w.result((0,_G.callValidateCode)(w,b,H),()=>F(b),()=>L(b))}function L(A){let j=T1._`${A}.errors`;W.assign(Lw.default.vErrors,T1._`${Lw.default.vErrors} === null ? ${j} : ${Lw.default.vErrors}.concat(${j})`),W.assign(Lw.default.errors,T1._`${Lw.default.vErrors}.length`)}function F(A){var j;if(!X.opts.unevaluated)return;let q=(j=$===null||$===void 0?void 0:$.validate)===null||j===void 0?void 0:j.evaluated;if(X.props!==!0)if(q&&!q.dynamicProps){if(q.props!==void 0)X.props=f6.mergeEvaluated.props(W,q.props,X.props)}else{let P=W.var("props",T1._`${A}.evaluated.props`);X.props=f6.mergeEvaluated.props(W,P,X.props,T1.Name)}if(X.items!==!0)if(q&&!q.dynamicItems){if(q.items!==void 0)X.items=f6.mergeEvaluated.items(W,q.items,X.items)}else{let P=W.var("items",T1._`${A}.evaluated.items`);X.items=f6.mergeEvaluated.items(W,P,X.items,T1.Name)}}}yG.callRef=u6;yG.default=GO});var mG=E((cG)=>{Object.defineProperty(cG,"__esModule",{value:!0});var DO=kG(),BO=uG(),LO=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",DO.default,BO.default];cG.default=LO});var gG=E((lG)=>{Object.defineProperty(lG,"__esModule",{value:!0});var c6=m(),C0=c6.operators,m6={maximum:{okStr:"<=",ok:C0.LTE,fail:C0.GT},minimum:{okStr:">=",ok:C0.GTE,fail:C0.LT},exclusiveMaximum:{okStr:"<",ok:C0.LT,fail:C0.GTE},exclusiveMinimum:{okStr:">",ok:C0.GT,fail:C0.LTE}},UO={message:({keyword:w,schemaCode:b})=>c6.str`must be ${m6[w].okStr} ${b}`,params:({keyword:w,schemaCode:b})=>c6._`{comparison: ${m6[w].okStr}, limit: ${b}}`},AO={keyword:Object.keys(m6),type:"number",schemaType:"number",$data:!0,error:UO,code(w){let{keyword:b,data:$,schemaCode:Q}=w;w.fail$data(c6._`${$} ${m6[b].fail} ${Q} || isNaN(${$})`)}};lG.default=AO});var nG=E((iG)=>{Object.defineProperty(iG,"__esModule",{value:!0});var Ub=m(),OO={message:({schemaCode:w})=>Ub.str`must be multiple of ${w}`,params:({schemaCode:w})=>Ub._`{multipleOf: ${w}}`},ZO={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:OO,code(w){let{gen:b,data:$,schemaCode:Q,it:W}=w,X=W.opts.multipleOfPrecision,J=b.let("res"),Y=X?Ub._`Math.abs(Math.round(${J}) - ${J}) > 1e-${X}`:Ub._`${J} !== parseInt(${J})`;w.fail$data(Ub._`(${Q} === 0 || (${J} = ${$}/${Q}, ${Y}))`)}};iG.default=ZO});var oG=E((dG)=>{Object.defineProperty(dG,"__esModule",{value:!0});function pG(w){let b=w.length,$=0,Q=0,W;while(Q<b)if($++,W=w.charCodeAt(Q++),W>=55296&&W<=56319&&Q<b){if(W=w.charCodeAt(Q),(W&64512)===56320)Q++}return $}dG.default=pG;pG.code='require("ajv/dist/runtime/ucs2length").default'});var rG=E((tG)=>{Object.defineProperty(tG,"__esModule",{value:!0});var g0=m(),VO=t(),PO=oG(),qO={message({keyword:w,schemaCode:b}){let $=w==="maxLength"?"more":"fewer";return g0.str`must NOT have ${$} than ${b} characters`},params:({schemaCode:w})=>g0._`{limit: ${w}}`},IO={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:qO,code(w){let{keyword:b,data:$,schemaCode:Q,it:W}=w,X=b==="maxLength"?g0.operators.GT:g0.operators.LT,J=W.opts.unicode===!1?g0._`${$}.length`:g0._`${(0,VO.useFunc)(w.gen,PO.default)}(${$})`;w.fail$data(g0._`${J} ${X} ${Q}`)}};tG.default=IO});var eG=E((sG)=>{Object.defineProperty(sG,"__esModule",{value:!0});var NO=c1(),l6=m(),TO={message:({schemaCode:w})=>l6.str`must match pattern "${w}"`,params:({schemaCode:w})=>l6._`{pattern: ${w}}`},RO={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:TO,code(w){let{data:b,$data:$,schema:Q,schemaCode:W,it:X}=w,J=X.opts.unicodeRegExp?"u":"",Y=$?l6._`(new RegExp(${W}, ${J}))`:(0,NO.usePattern)(w,Q);w.fail$data(l6._`!${Y}.test(${b})`)}};sG.default=RO});var w7=E((aG)=>{Object.defineProperty(aG,"__esModule",{value:!0});var Ab=m(),vO={message({keyword:w,schemaCode:b}){let $=w==="maxProperties"?"more":"fewer";return Ab.str`must NOT have ${$} than ${b} properties`},params:({schemaCode:w})=>Ab._`{limit: ${w}}`},CO={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:vO,code(w){let{keyword:b,data:$,schemaCode:Q}=w,W=b==="maxProperties"?Ab.operators.GT:Ab.operators.LT;w.fail$data(Ab._`Object.keys(${$}).length ${W} ${Q}`)}};aG.default=CO});var $7=E((b7)=>{Object.defineProperty(b7,"__esModule",{value:!0});var Kb=c1(),Ob=m(),_O=t(),xO={message:({params:{missingProperty:w}})=>Ob.str`must have required property '${w}'`,params:({params:{missingProperty:w}})=>Ob._`{missingProperty: ${w}}`},hO={keyword:"required",type:"object",schemaType:"array",$data:!0,error:xO,code(w){let{gen:b,schema:$,schemaCode:Q,data:W,$data:X,it:J}=w,{opts:Y}=J;if(!X&&$.length===0)return;let G=$.length>=Y.loopRequired;if(J.allErrors)H();else z();if(Y.strictRequired){let F=w.parentSchema.properties,{definedProperties:A}=w.it;for(let j of $)if((F===null||F===void 0?void 0:F[j])===void 0&&!A.has(j)){let q=J.schemaEnv.baseId+J.errSchemaPath,P=`required property "${j}" is not defined at "${q}" (strictRequired)`;(0,_O.checkStrictMode)(J,P,J.opts.strictRequired)}}function H(){if(G||X)w.block$data(Ob.nil,B);else for(let F of $)(0,Kb.checkReportMissingProp)(w,F)}function z(){let F=b.let("missing");if(G||X){let A=b.let("valid",!0);w.block$data(A,()=>L(F,A)),w.ok(A)}else b.if((0,Kb.checkMissingProp)(w,$,F)),(0,Kb.reportMissingProp)(w,F),b.else()}function B(){b.forOf("prop",Q,(F)=>{w.setParams({missingProperty:F}),b.if((0,Kb.noPropertyInData)(b,W,F,Y.ownProperties),()=>w.error())})}function L(F,A){w.setParams({missingProperty:F}),b.forOf(F,Q,()=>{b.assign(A,(0,Kb.propertyInData)(b,W,F,Y.ownProperties)),b.if((0,Ob.not)(A),()=>{w.error(),b.break()})},Ob.nil)}}};b7.default=hO});var W7=E((Q7)=>{Object.defineProperty(Q7,"__esModule",{value:!0});var Zb=m(),fO={message({keyword:w,schemaCode:b}){let $=w==="maxItems"?"more":"fewer";return Zb.str`must NOT have ${$} than ${b} items`},params:({schemaCode:w})=>Zb._`{limit: ${w}}`},uO={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:fO,code(w){let{keyword:b,data:$,schemaCode:Q}=w,W=b==="maxItems"?Zb.operators.GT:Zb.operators.LT;w.fail$data(Zb._`${$}.length ${W} ${Q}`)}};Q7.default=uO});var g6=E((J7)=>{Object.defineProperty(J7,"__esModule",{value:!0});var X7=o$();X7.code='require("ajv/dist/runtime/equal").default';J7.default=X7});var G7=E((Y7)=>{Object.defineProperty(Y7,"__esModule",{value:!0});var z9=Xb(),j1=m(),lO=t(),gO=g6(),iO={message:({params:{i:w,j:b}})=>j1.str`must NOT have duplicate items (items ## ${b} and ${w} are identical)`,params:({params:{i:w,j:b}})=>j1._`{i: ${w}, j: ${b}}`},nO={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:iO,code(w){let{gen:b,data:$,$data:Q,schema:W,parentSchema:X,schemaCode:J,it:Y}=w;if(!Q&&!W)return;let G=b.let("valid"),H=X.items?(0,z9.getSchemaTypes)(X.items):[];w.block$data(G,z,j1._`${J} === false`),w.ok(G);function z(){let A=b.let("i",j1._`${$}.length`),j=b.let("j");w.setParams({i:A,j}),b.assign(G,!0),b.if(j1._`${A} > 1`,()=>(B()?L:F)(A,j))}function B(){return H.length>0&&!H.some((A)=>A==="object"||A==="array")}function L(A,j){let q=b.name("item"),P=(0,z9.checkDataTypes)(H,q,Y.opts.strictNumbers,z9.DataType.Wrong),v=b.const("indices",j1._`{}`);b.for(j1._`;${A}--;`,()=>{if(b.let(q,j1._`${$}[${A}]`),b.if(P,j1._`continue`),H.length>1)b.if(j1._`typeof ${q} == "string"`,j1._`${q} += "_"`);b.if(j1._`typeof ${v}[${q}] == "number"`,()=>{b.assign(j,j1._`${v}[${q}]`),w.error(),b.assign(G,!1).break()}).code(j1._`${v}[${q}] = ${A}`)})}function F(A,j){let q=(0,lO.useFunc)(b,gO.default),P=b.name("outer");b.label(P).for(j1._`;${A}--;`,()=>b.for(j1._`${j} = ${A}; ${j}--;`,()=>b.if(j1._`${q}(${$}[${A}], ${$}[${j}])`,()=>{w.error(),b.assign(G,!1).break(P)})))}}};Y7.default=nO});var z7=E((H7)=>{Object.defineProperty(H7,"__esModule",{value:!0});var D9=m(),dO=t(),oO=g6(),tO={message:"must be equal to constant",params:({schemaCode:w})=>D9._`{allowedValue: ${w}}`},rO={keyword:"const",$data:!0,error:tO,code(w){let{gen:b,data:$,$data:Q,schemaCode:W,schema:X}=w;if(Q||X&&typeof X=="object")w.fail$data(D9._`!${(0,dO.useFunc)(b,oO.default)}(${$}, ${W})`);else w.fail(D9._`${X} !== ${$}`)}};H7.default=rO});var B7=E((D7)=>{Object.defineProperty(D7,"__esModule",{value:!0});var jb=m(),eO=t(),aO=g6(),wZ={message:"must be equal to one of the allowed values",params:({schemaCode:w})=>jb._`{allowedValues: ${w}}`},bZ={keyword:"enum",schemaType:"array",$data:!0,error:wZ,code(w){let{gen:b,data:$,$data:Q,schema:W,schemaCode:X,it:J}=w;if(!Q&&W.length===0)throw Error("enum must have non-empty array");let Y=W.length>=J.opts.loopEnum,G,H=()=>G!==null&&G!==void 0?G:G=(0,eO.useFunc)(b,aO.default),z;if(Y||Q)z=b.let("valid"),w.block$data(z,B);else{if(!Array.isArray(W))throw Error("ajv implementation error");let F=b.const("vSchema",X);z=(0,jb.or)(...W.map((A,j)=>L(F,j)))}w.pass(z);function B(){b.assign(z,!1),b.forOf("v",X,(F)=>b.if(jb._`${H()}(${$}, ${F})`,()=>b.assign(z,!0).break()))}function L(F,A){let j=W[A];return typeof j==="object"&&j!==null?jb._`${H()}(${$}, ${F}[${A}])`:jb._`${$} === ${j}`}}};D7.default=bZ});var F7=E((L7)=>{Object.defineProperty(L7,"__esModule",{value:!0});var QZ=gG(),WZ=nG(),XZ=rG(),JZ=eG(),YZ=w7(),GZ=$7(),HZ=W7(),zZ=G7(),DZ=z7(),BZ=B7(),LZ=[QZ.default,WZ.default,XZ.default,JZ.default,YZ.default,GZ.default,HZ.default,zZ.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},DZ.default,BZ.default];L7.default=LZ});var L9=E((A7)=>{Object.defineProperty(A7,"__esModule",{value:!0});A7.validateAdditionalItems=void 0;var i0=m(),B9=t(),UZ={message:({params:{len:w}})=>i0.str`must NOT have more than ${w} items`,params:({params:{len:w}})=>i0._`{limit: ${w}}`},AZ={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:UZ,code(w){let{parentSchema:b,it:$}=w,{items:Q}=b;if(!Array.isArray(Q)){(0,B9.checkStrictMode)($,'"additionalItems" is ignored when "items" is not an array of schemas');return}U7(w,Q)}};function U7(w,b){let{gen:$,schema:Q,data:W,keyword:X,it:J}=w;J.items=!0;let Y=$.const("len",i0._`${W}.length`);if(Q===!1)w.setParams({len:b.length}),w.pass(i0._`${Y} <= ${b.length}`);else if(typeof Q=="object"&&!(0,B9.alwaysValidSchema)(J,Q)){let H=$.var("valid",i0._`${Y} <= ${b.length}`);$.if((0,i0.not)(H),()=>G(H)),w.ok(H)}function G(H){$.forRange("i",b.length,Y,(z)=>{if(w.subschema({keyword:X,dataProp:z,dataPropType:B9.Type.Num},H),!J.allErrors)$.if((0,i0.not)(H),()=>$.break())})}}A7.validateAdditionalItems=U7;A7.default=AZ});var F9=E((j7)=>{Object.defineProperty(j7,"__esModule",{value:!0});j7.validateTuple=void 0;var O7=m(),i6=t(),OZ=c1(),ZZ={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(w){let{schema:b,it:$}=w;if(Array.isArray(b))return Z7(w,"additionalItems",b);if($.items=!0,(0,i6.alwaysValidSchema)($,b))return;w.ok((0,OZ.validateArray)(w))}};function Z7(w,b,$=w.schema){let{gen:Q,parentSchema:W,data:X,keyword:J,it:Y}=w;if(z(W),Y.opts.unevaluated&&$.length&&Y.items!==!0)Y.items=i6.mergeEvaluated.items(Q,$.length,Y.items);let G=Q.name("valid"),H=Q.const("len",O7._`${X}.length`);$.forEach((B,L)=>{if((0,i6.alwaysValidSchema)(Y,B))return;Q.if(O7._`${H} > ${L}`,()=>w.subschema({keyword:J,schemaProp:L,dataProp:L},G)),w.ok(G)});function z(B){let{opts:L,errSchemaPath:F}=Y,A=$.length,j=A===B.minItems&&(A===B.maxItems||B[b]===!1);if(L.strictTuples&&!j){let q=`"${J}" is ${A}-tuple, but minItems or maxItems/${b} are not specified or different at path "${F}"`;(0,i6.checkStrictMode)(Y,q,L.strictTuples)}}}j7.validateTuple=Z7;j7.default=ZZ});var P7=E((V7)=>{Object.defineProperty(V7,"__esModule",{value:!0});var MZ=F9(),VZ={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:(w)=>(0,MZ.validateTuple)(w,"items")};V7.default=VZ});var E7=E((I7)=>{Object.defineProperty(I7,"__esModule",{value:!0});var q7=m(),qZ=t(),IZ=c1(),EZ=L9(),NZ={message:({params:{len:w}})=>q7.str`must NOT have more than ${w} items`,params:({params:{len:w}})=>q7._`{limit: ${w}}`},TZ={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:NZ,code(w){let{schema:b,parentSchema:$,it:Q}=w,{prefixItems:W}=$;if(Q.items=!0,(0,qZ.alwaysValidSchema)(Q,b))return;if(W)(0,EZ.validateAdditionalItems)(w,W);else w.ok((0,IZ.validateArray)(w))}};I7.default=TZ});var T7=E((N7)=>{Object.defineProperty(N7,"__esModule",{value:!0});var m1=m(),n6=t(),SZ={message:({params:{min:w,max:b}})=>b===void 0?m1.str`must contain at least ${w} valid item(s)`:m1.str`must contain at least ${w} and no more than ${b} valid item(s)`,params:({params:{min:w,max:b}})=>b===void 0?m1._`{minContains: ${w}}`:m1._`{minContains: ${w}, maxContains: ${b}}`},vZ={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:SZ,code(w){let{gen:b,schema:$,parentSchema:Q,data:W,it:X}=w,J,Y,{minContains:G,maxContains:H}=Q;if(X.opts.next)J=G===void 0?1:G,Y=H;else J=1;let z=b.const("len",m1._`${W}.length`);if(w.setParams({min:J,max:Y}),Y===void 0&&J===0){(0,n6.checkStrictMode)(X,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(Y!==void 0&&J>Y){(0,n6.checkStrictMode)(X,'"minContains" > "maxContains" is always invalid'),w.fail();return}if((0,n6.alwaysValidSchema)(X,$)){let j=m1._`${z} >= ${J}`;if(Y!==void 0)j=m1._`${j} && ${z} <= ${Y}`;w.pass(j);return}X.items=!0;let B=b.name("valid");if(Y===void 0&&J===1)F(B,()=>b.if(B,()=>b.break()));else if(J===0){if(b.let(B,!0),Y!==void 0)b.if(m1._`${W}.length > 0`,L)}else b.let(B,!1),L();w.result(B,()=>w.reset());function L(){let j=b.name("_valid"),q=b.let("count",0);F(j,()=>b.if(j,()=>A(q)))}function F(j,q){b.forRange("i",0,z,(P)=>{w.subschema({keyword:"contains",dataProp:P,dataPropType:n6.Type.Num,compositeRule:!0},j),q()})}function A(j){if(b.code(m1._`${j}++`),Y===void 0)b.if(m1._`${j} >= ${J}`,()=>b.assign(B,!0).break());else if(b.if(m1._`${j} > ${Y}`,()=>b.assign(B,!1).break()),J===1)b.assign(B,!0);else b.if(m1._`${j} >= ${J}`,()=>b.assign(B,!0))}}};N7.default=vZ});var _7=E((v7)=>{Object.defineProperty(v7,"__esModule",{value:!0});v7.validateSchemaDeps=v7.validatePropertyDeps=v7.error=void 0;var U9=m(),kZ=t(),Mb=c1();v7.error={message:({params:{property:w,depsCount:b,deps:$}})=>{let Q=b===1?"property":"properties";return U9.str`must have ${Q} ${$} when property ${w} is present`},params:({params:{property:w,depsCount:b,deps:$,missingProperty:Q}})=>U9._`{property: ${w},
6
+ missingProperty: ${Q},
7
7
  depsCount: ${b},
8
- deps: ${$}}`};var PZ={keyword:"dependencies",type:"object",schemaType:"object",error:P7.error,code(w){let[b,$]=IZ(w);j7(w,b),q7(w,$)}};function IZ({schema:w}){let b={},$={};for(let W in w){if(W==="__proto__")continue;let Q=Array.isArray(w[W])?b:$;Q[W]=w[W]}return[b,$]}function j7(w,b=w.schema){let{gen:$,data:W,it:Q}=w;if(Object.keys(b).length===0)return;let X=$.let("missing");for(let J in b){let G=b[J];if(G.length===0)continue;let Y=(0,Fb.propertyInData)($,W,J,Q.opts.ownProperties);if(w.setParams({property:J,depsCount:G.length,deps:G.join(", ")}),Q.allErrors)$.if(Y,()=>{for(let H of G)(0,Fb.checkReportMissingProp)(w,H)});else $.if(z9._`${Y} && (${(0,Fb.checkMissingProp)(w,G,X)})`),(0,Fb.reportMissingProp)(w,X),$.else()}}P7.validatePropertyDeps=j7;function q7(w,b=w.schema){let{gen:$,data:W,keyword:Q,it:X}=w,J=$.name("valid");for(let G in b){if((0,qZ.alwaysValidSchema)(X,b[G]))continue;$.if((0,Fb.propertyInData)($,W,G,X.opts.ownProperties),()=>{let Y=w.subschema({keyword:Q,schemaProp:G},J);w.mergeValidEvaluated(Y,J)},()=>$.var(J,!0)),w.ok(J)}}P7.validateSchemaDeps=q7;P7.default=PZ});var S7=N((R7)=>{Object.defineProperty(R7,"__esModule",{value:!0});var T7=c(),TZ=t(),RZ={message:"property name must be valid",params:({params:w})=>T7._`{propertyName: ${w.propertyName}}`},SZ={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:RZ,code(w){let{gen:b,schema:$,data:W,it:Q}=w;if((0,TZ.alwaysValidSchema)(Q,$))return;let X=b.name("valid");b.forIn("key",W,(J)=>{w.setParams({propertyName:J}),w.subschema({keyword:"propertyNames",data:J,dataTypes:["string"],propertyName:J,compositeRule:!0},X),b.if((0,T7.not)(X),()=>{if(w.error(!0),!Q.allErrors)b.break()})}),w.ok(X)}};R7.default=SZ});var B9=N((v7)=>{Object.defineProperty(v7,"__esModule",{value:!0});var m6=fw(),pw=c(),CZ=Y1(),l6=t(),kZ={message:"must NOT have additional properties",params:({params:w})=>pw._`{additionalProperty: ${w.additionalProperty}}`},_Z={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:kZ,code(w){let{gen:b,schema:$,parentSchema:W,data:Q,errsCount:X,it:J}=w;if(!X)throw Error("ajv implementation error");let{allErrors:G,opts:Y}=J;if(J.props=!0,Y.removeAdditional!=="all"&&(0,l6.alwaysValidSchema)(J,$))return;let H=(0,m6.allSchemaProperties)(W.properties),z=(0,m6.allSchemaProperties)(W.patternProperties);D(),w.ok(pw._`${X} === ${CZ.default.errors}`);function D(){b.forIn("key",Q,(q)=>{if(!H.length&&!z.length)F(q);else b.if(A(q),()=>F(q))})}function A(q){let P;if(H.length>8){let k=(0,l6.schemaRefOrVal)(J,W.properties,"properties");P=(0,m6.isOwnProperty)(b,k,q)}else if(H.length)P=(0,pw.or)(...H.map((k)=>pw._`${q} === ${k}`));else P=pw.nil;if(z.length)P=(0,pw.or)(P,...z.map((k)=>pw._`${(0,m6.usePattern)(w,k)}.test(${q})`));return(0,pw.not)(P)}function L(q){b.code(pw._`delete ${Q}[${q}]`)}function F(q){if(Y.removeAdditional==="all"||Y.removeAdditional&&$===!1){L(q);return}if($===!1){if(w.setParams({additionalProperty:q}),w.error(),!G)b.break();return}if(typeof $=="object"&&!(0,l6.alwaysValidSchema)(J,$)){let P=b.name("valid");if(Y.removeAdditional==="failing")V(q,P,!1),b.if((0,pw.not)(P),()=>{w.reset(),L(q)});else if(V(q,P),!G)b.if((0,pw.not)(P),()=>b.break())}}function V(q,P,k){let S={keyword:"additionalProperties",dataProp:q,dataPropType:l6.Type.Str};if(k===!1)Object.assign(S,{compositeRule:!0,createErrors:!1,allErrors:!1});w.subschema(S,P)}}};v7.default=_Z});var x7=N((_7)=>{Object.defineProperty(_7,"__esModule",{value:!0});var hZ=Qb(),C7=fw(),D9=t(),k7=B9(),yZ={keyword:"properties",type:"object",schemaType:"object",code(w){let{gen:b,schema:$,parentSchema:W,data:Q,it:X}=w;if(X.opts.removeAdditional==="all"&&W.additionalProperties===void 0)k7.default.code(new hZ.KeywordCxt(X,k7.default,"additionalProperties"));let J=(0,C7.allSchemaProperties)($);for(let D of J)X.definedProperties.add(D);if(X.opts.unevaluated&&J.length&&X.props!==!0)X.props=D9.mergeEvaluated.props(b,(0,D9.toHash)(J),X.props);let G=J.filter((D)=>!(0,D9.alwaysValidSchema)(X,$[D]));if(G.length===0)return;let Y=b.name("valid");for(let D of G){if(H(D))z(D);else{if(b.if((0,C7.propertyInData)(b,Q,D,X.opts.ownProperties)),z(D),!X.allErrors)b.else().var(Y,!0);b.endIf()}w.it.definedProperties.add(D),w.ok(Y)}function H(D){return X.opts.useDefaults&&!X.compositeRule&&$[D].default!==void 0}function z(D){w.subschema({keyword:"properties",schemaProp:D,dataProp:D},Y)}}};_7.default=yZ});var c7=N((u7)=>{Object.defineProperty(u7,"__esModule",{value:!0});var h7=fw(),g6=c(),y7=t(),f7=t(),uZ={keyword:"patternProperties",type:"object",schemaType:"object",code(w){let{gen:b,schema:$,data:W,parentSchema:Q,it:X}=w,{opts:J}=X,G=(0,h7.allSchemaProperties)($),Y=G.filter((V)=>(0,y7.alwaysValidSchema)(X,$[V]));if(G.length===0||Y.length===G.length&&(!X.opts.unevaluated||X.props===!0))return;let H=J.strictSchema&&!J.allowMatchingProperties&&Q.properties,z=b.name("valid");if(X.props!==!0&&!(X.props instanceof g6.Name))X.props=(0,f7.evaluatedPropsToName)(b,X.props);let{props:D}=X;A();function A(){for(let V of G){if(H)L(V);if(X.allErrors)F(V);else b.var(z,!0),F(V),b.if(z)}}function L(V){for(let q in H)if(new RegExp(V).test(q))(0,y7.checkStrictMode)(X,`property ${q} matches pattern ${V} (use allowMatchingProperties)`)}function F(V){b.forIn("key",W,(q)=>{b.if(g6._`${(0,h7.usePattern)(w,V)}.test(${q})`,()=>{let P=Y.includes(V);if(!P)w.subschema({keyword:"patternProperties",schemaProp:V,dataProp:q,dataPropType:f7.Type.Str},z);if(X.opts.unevaluated&&D!==!0)b.assign(g6._`${D}[${q}]`,!0);else if(!P&&!X.allErrors)b.if((0,g6.not)(z),()=>b.break())})})}}};u7.default=uZ});var l7=N((m7)=>{Object.defineProperty(m7,"__esModule",{value:!0});var mZ=t(),lZ={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(w){let{gen:b,schema:$,it:W}=w;if((0,mZ.alwaysValidSchema)(W,$)){w.fail();return}let Q=b.name("valid");w.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},Q),w.failResult(Q,()=>w.reset(),()=>w.error())},error:{message:"must NOT be valid"}};m7.default=lZ});var i7=N((g7)=>{Object.defineProperty(g7,"__esModule",{value:!0});var iZ=fw(),nZ={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:iZ.validateUnion,error:{message:"must match a schema in anyOf"}};g7.default=nZ});var p7=N((n7)=>{Object.defineProperty(n7,"__esModule",{value:!0});var i6=c(),dZ=t(),oZ={message:"must match exactly one schema in oneOf",params:({params:w})=>i6._`{passingSchemas: ${w.passing}}`},tZ={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:oZ,code(w){let{gen:b,schema:$,parentSchema:W,it:Q}=w;if(!Array.isArray($))throw Error("ajv implementation error");if(Q.opts.discriminator&&W.discriminator)return;let X=$,J=b.let("valid",!1),G=b.let("passing",null),Y=b.name("_valid");w.setParams({passing:G}),b.block(H),w.result(J,()=>w.reset(),()=>w.error(!0));function H(){X.forEach((z,D)=>{let A;if((0,dZ.alwaysValidSchema)(Q,z))b.var(Y,!0);else A=w.subschema({keyword:"oneOf",schemaProp:D,compositeRule:!0},Y);if(D>0)b.if(i6._`${Y} && ${J}`).assign(J,!1).assign(G,i6._`[${G}, ${D}]`).else();b.if(Y,()=>{if(b.assign(J,!0),b.assign(G,D),A)w.mergeEvaluated(A,i6.Name)})})}}};n7.default=tZ});var o7=N((d7)=>{Object.defineProperty(d7,"__esModule",{value:!0});var sZ=t(),eZ={keyword:"allOf",schemaType:"array",code(w){let{gen:b,schema:$,it:W}=w;if(!Array.isArray($))throw Error("ajv implementation error");let Q=b.name("valid");$.forEach((X,J)=>{if((0,sZ.alwaysValidSchema)(W,X))return;let G=w.subschema({keyword:"allOf",schemaProp:J},Q);w.ok(Q),w.mergeEvaluated(G)})}};d7.default=eZ});var e7=N((s7)=>{Object.defineProperty(s7,"__esModule",{value:!0});var n6=c(),r7=t(),wM={message:({params:w})=>n6.str`must match "${w.ifClause}" schema`,params:({params:w})=>n6._`{failingKeyword: ${w.ifClause}}`},bM={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:wM,code(w){let{gen:b,parentSchema:$,it:W}=w;if($.then===void 0&&$.else===void 0)(0,r7.checkStrictMode)(W,'"if" without "then" and "else" is ignored');let Q=t7(W,"then"),X=t7(W,"else");if(!Q&&!X)return;let J=b.let("valid",!0),G=b.name("_valid");if(Y(),w.reset(),Q&&X){let z=b.let("ifClause");w.setParams({ifClause:z}),b.if(G,H("then",z),H("else",z))}else if(Q)b.if(G,H("then"));else b.if((0,n6.not)(G),H("else"));w.pass(J,()=>w.error(!0));function Y(){let z=w.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},G);w.mergeEvaluated(z)}function H(z,D){return()=>{let A=w.subschema({keyword:z},G);if(b.assign(J,G),w.mergeValidEvaluated(A,J),D)b.assign(D,n6._`${z}`);else w.setParams({ifClause:z})}}}};function t7(w,b){let $=w.schema[b];return $!==void 0&&!(0,r7.alwaysValidSchema)(w,$)}s7.default=bM});var wH=N((a7)=>{Object.defineProperty(a7,"__esModule",{value:!0});var WM=t(),QM={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:w,parentSchema:b,it:$}){if(b.if===void 0)(0,WM.checkStrictMode)($,`"${w}" without "if" is ignored`)}};a7.default=QM});var $H=N((bH)=>{Object.defineProperty(bH,"__esModule",{value:!0});var JM=Y9(),GM=F7(),YM=H9(),HM=Z7(),zM=V7(),BM=E7(),DM=S7(),AM=B9(),LM=x7(),UM=c7(),FM=l7(),KM=i7(),OM=p7(),ZM=o7(),MM=e7(),VM=wH();function jM(w=!1){let b=[FM.default,KM.default,OM.default,ZM.default,MM.default,VM.default,DM.default,AM.default,BM.default,LM.default,UM.default];if(w)b.push(GM.default,HM.default);else b.push(JM.default,YM.default);return b.push(zM.default),b}bH.default=jM});var QH=N((WH)=>{Object.defineProperty(WH,"__esModule",{value:!0});var zw=c(),PM={message:({schemaCode:w})=>zw.str`must match format "${w}"`,params:({schemaCode:w})=>zw._`{format: ${w}}`},IM={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:PM,code(w,b){let{gen:$,data:W,$data:Q,schema:X,schemaCode:J,it:G}=w,{opts:Y,errSchemaPath:H,schemaEnv:z,self:D}=G;if(!Y.validateFormats)return;if(Q)A();else L();function A(){let F=$.scopeValue("formats",{ref:D.formats,code:Y.code.formats}),V=$.const("fDef",zw._`${F}[${J}]`),q=$.let("fType"),P=$.let("format");$.if(zw._`typeof ${V} == "object" && !(${V} instanceof RegExp)`,()=>$.assign(q,zw._`${V}.type || "string"`).assign(P,zw._`${V}.validate`),()=>$.assign(q,zw._`"string"`).assign(P,V)),w.fail$data((0,zw.or)(k(),S()));function k(){if(Y.strictSchema===!1)return zw.nil;return zw._`${J} && !${P}`}function S(){let l=z.$async?zw._`(${V}.async ? await ${P}(${W}) : ${P}(${W}))`:zw._`${P}(${W})`,_=zw._`(typeof ${P} == "function" ? ${l} : ${P}.test(${W}))`;return zw._`${P} && ${P} !== true && ${q} === ${b} && !${_}`}}function L(){let F=D.formats[X];if(!F){k();return}if(F===!0)return;let[V,q,P]=S(F);if(V===b)w.pass(l());function k(){if(Y.strictSchema===!1){D.logger.warn(_());return}throw Error(_());function _(){return`unknown format "${X}" ignored in schema at path "${H}"`}}function S(_){let rw=_ instanceof RegExp?(0,zw.regexpCode)(_):Y.code.formats?zw._`${Y.code.formats}${(0,zw.getProperty)(X)}`:void 0,$1=$.scopeValue("formats",{key:X,ref:_,code:rw});if(typeof _=="object"&&!(_ instanceof RegExp))return[_.type||"string",_.validate,zw._`${$1}.validate`];return["string",_,$1]}function l(){if(typeof F=="object"&&!(F instanceof RegExp)&&F.async){if(!z.$async)throw Error("async format in sync schema");return zw._`await ${P}(${W})`}return typeof q=="function"?zw._`${P}(${W})`:zw._`${P}.test(${W})`}}}};WH.default=IM});var JH=N((XH)=>{Object.defineProperty(XH,"__esModule",{value:!0});var EM=QH(),TM=[EM.default];XH.default=TM});var HH=N((GH)=>{Object.defineProperty(GH,"__esModule",{value:!0});GH.contentVocabulary=GH.metadataVocabulary=void 0;GH.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];GH.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var DH=N((BH)=>{Object.defineProperty(BH,"__esModule",{value:!0});var vM=_Y(),CM=G7(),kM=$H(),_M=JH(),zH=HH(),xM=[vM.default,CM.default,(0,kM.default)(),_M.default,zH.metadataVocabulary,zH.contentVocabulary];BH.default=xM});var FH=N((LH)=>{Object.defineProperty(LH,"__esModule",{value:!0});LH.DiscrError=void 0;var AH;(function(w){w.Tag="tag",w.Mapping="mapping"})(AH||(LH.DiscrError=AH={}))});var ZH=N((OH)=>{Object.defineProperty(OH,"__esModule",{value:!0});var z0=c(),A9=FH(),KH=N6(),yM=Xb(),fM=t(),uM={message:({params:{discrError:w,tagName:b}})=>w===A9.DiscrError.Tag?`tag "${b}" must be string`:`value of tag "${b}" must be in oneOf`,params:({params:{discrError:w,tag:b,tagName:$}})=>z0._`{error: ${w}, tag: ${$}, tagValue: ${b}}`},cM={keyword:"discriminator",type:"object",schemaType:"object",error:uM,code(w){let{gen:b,data:$,schema:W,parentSchema:Q,it:X}=w,{oneOf:J}=Q;if(!X.opts.discriminator)throw Error("discriminator: requires discriminator option");let G=W.propertyName;if(typeof G!="string")throw Error("discriminator: requires propertyName");if(W.mapping)throw Error("discriminator: mapping is not supported");if(!J)throw Error("discriminator: requires oneOf keyword");let Y=b.let("valid",!1),H=b.const("tag",z0._`${$}${(0,z0.getProperty)(G)}`);b.if(z0._`typeof ${H} == "string"`,()=>z(),()=>w.error(!1,{discrError:A9.DiscrError.Tag,tag:H,tagName:G})),w.ok(Y);function z(){let L=A();b.if(!1);for(let F in L)b.elseIf(z0._`${H} === ${F}`),b.assign(Y,D(L[F]));b.else(),w.error(!1,{discrError:A9.DiscrError.Mapping,tag:H,tagName:G}),b.endIf()}function D(L){let F=b.name("valid"),V=w.subschema({keyword:"oneOf",schemaProp:L},F);return w.mergeEvaluated(V,z0.Name),F}function A(){var L;let F={},V=P(Q),q=!0;for(let l=0;l<J.length;l++){let _=J[l];if((_===null||_===void 0?void 0:_.$ref)&&!(0,fM.schemaHasRulesButRef)(_,X.self.RULES)){let $1=_.$ref;if(_=KH.resolveRef.call(X.self,X.schemaEnv.root,X.baseId,$1),_ instanceof KH.SchemaEnv)_=_.schema;if(_===void 0)throw new yM.default(X.opts.uriResolver,X.baseId,$1)}let rw=(L=_===null||_===void 0?void 0:_.properties)===null||L===void 0?void 0:L[G];if(typeof rw!="object")throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${G}"`);q=q&&(V||P(_)),k(rw,l)}if(!q)throw Error(`discriminator: "${G}" must be required`);return F;function P({required:l}){return Array.isArray(l)&&l.includes(G)}function k(l,_){if(l.const)S(l.const,_);else if(l.enum)for(let rw of l.enum)S(rw,_);else throw Error(`discriminator: "properties/${G}" must have "const" or "enum"`)}function S(l,_){if(typeof l!="string"||l in F)throw Error(`discriminator: "${G}" values must be unique strings`);F[l]=_}}}};OH.default=cM});var MH=N((rR,lM)=>{lM.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 U9=N((Rw,L9)=>{Object.defineProperty(Rw,"__esModule",{value:!0});Rw.MissingRefError=Rw.ValidationError=Rw.CodeGen=Rw.Name=Rw.nil=Rw.stringify=Rw.str=Rw._=Rw.KeywordCxt=Rw.Ajv=void 0;var gM=PY(),iM=DH(),nM=ZH(),VH=MH(),pM=["/properties"],p6="http://json-schema.org/draft-07/schema";class Kb extends gM.default{_addVocabularies(){if(super._addVocabularies(),iM.default.forEach((w)=>this.addVocabulary(w)),this.opts.discriminator)this.addKeyword(nM.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let w=this.opts.$data?this.$dataMetaSchema(VH,pM):VH;this.addMetaSchema(w,p6,!1),this.refs["http://json-schema.org/schema"]=p6}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(p6)?p6:void 0)}}Rw.Ajv=Kb;L9.exports=Rw=Kb;L9.exports.Ajv=Kb;Object.defineProperty(Rw,"__esModule",{value:!0});Rw.default=Kb;var dM=Qb();Object.defineProperty(Rw,"KeywordCxt",{enumerable:!0,get:function(){return dM.KeywordCxt}});var B0=c();Object.defineProperty(Rw,"_",{enumerable:!0,get:function(){return B0._}});Object.defineProperty(Rw,"str",{enumerable:!0,get:function(){return B0.str}});Object.defineProperty(Rw,"stringify",{enumerable:!0,get:function(){return B0.stringify}});Object.defineProperty(Rw,"nil",{enumerable:!0,get:function(){return B0.nil}});Object.defineProperty(Rw,"Name",{enumerable:!0,get:function(){return B0.Name}});Object.defineProperty(Rw,"CodeGen",{enumerable:!0,get:function(){return B0.CodeGen}});var oM=P6();Object.defineProperty(Rw,"ValidationError",{enumerable:!0,get:function(){return oM.default}});var tM=Xb();Object.defineProperty(Rw,"MissingRefError",{enumerable:!0,get:function(){return tM.default}})});var vH=N((RH)=>{Object.defineProperty(RH,"__esModule",{value:!0});RH.formatNames=RH.fastFormats=RH.fullFormats=void 0;function w1(w,b){return{validate:w,compare:b}}RH.fullFormats={date:w1(IH,Z9),time:w1(K9(!0),M9),"date-time":w1(jH(!0),EH),"iso-time":w1(K9(),NH),"iso-date-time":w1(jH(),TH),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:WV,"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:zV,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:QV,int32:{type:"number",validate:GV},int64:{type:"number",validate:YV},float:{type:"number",validate:PH},double:{type:"number",validate:PH},password:!0,binary:!0};RH.fastFormats={...RH.fullFormats,date:w1(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Z9),time:w1(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,M9),"date-time":w1(/^\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,EH),"iso-time":w1(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,NH),"iso-date-time":w1(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,TH),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};RH.formatNames=Object.keys(RH.fullFormats);function eM(w){return w%4===0&&(w%100!==0||w%400===0)}var aM=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,wV=[0,31,28,31,30,31,30,31,31,30,31,30,31];function IH(w){let b=aM.exec(w);if(!b)return!1;let $=+b[1],W=+b[2],Q=+b[3];return W>=1&&W<=12&&Q>=1&&Q<=(W===2&&eM($)?29:wV[W])}function Z9(w,b){if(!(w&&b))return;if(w>b)return 1;if(w<b)return-1;return 0}var F9=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function K9(w){return function($){let W=F9.exec($);if(!W)return!1;let Q=+W[1],X=+W[2],J=+W[3],G=W[4],Y=W[5]==="-"?-1:1,H=+(W[6]||0),z=+(W[7]||0);if(H>23||z>59||w&&!G)return!1;if(Q<=23&&X<=59&&J<60)return!0;let D=X-z*Y,A=Q-H*Y-(D<0?1:0);return(A===23||A===-1)&&(D===59||D===-1)&&J<61}}function M9(w,b){if(!(w&&b))return;let $=new Date("2020-01-01T"+w).valueOf(),W=new Date("2020-01-01T"+b).valueOf();if(!($&&W))return;return $-W}function NH(w,b){if(!(w&&b))return;let $=F9.exec(w),W=F9.exec(b);if(!($&&W))return;if(w=$[1]+$[2]+$[3],b=W[1]+W[2]+W[3],w>b)return 1;if(w<b)return-1;return 0}var O9=/t|\s/i;function jH(w){let b=K9(w);return function(W){let Q=W.split(O9);return Q.length===2&&IH(Q[0])&&b(Q[1])}}function EH(w,b){if(!(w&&b))return;let $=new Date(w).valueOf(),W=new Date(b).valueOf();if(!($&&W))return;return $-W}function TH(w,b){if(!(w&&b))return;let[$,W]=w.split(O9),[Q,X]=b.split(O9),J=Z9($,Q);if(J===void 0)return;return J||M9(W,X)}var bV=/\/|:/,$V=/^(?:[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 WV(w){return bV.test(w)&&$V.test(w)}var qH=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function QV(w){return qH.lastIndex=0,qH.test(w)}var XV=-2147483648,JV=2147483647;function GV(w){return Number.isInteger(w)&&w<=JV&&w>=XV}function YV(w){return Number.isInteger(w)}function PH(){return!0}var HV=/[^\\]\\Z/;function zV(w){if(HV.test(w))return!1;try{return new RegExp(w),!0}catch(b){return!1}}});var kH=N((CH)=>{Object.defineProperty(CH,"__esModule",{value:!0});CH.formatLimitDefinition=void 0;var DV=U9(),dw=c(),S1=dw.operators,d6={formatMaximum:{okStr:"<=",ok:S1.LTE,fail:S1.GT},formatMinimum:{okStr:">=",ok:S1.GTE,fail:S1.LT},formatExclusiveMaximum:{okStr:"<",ok:S1.LT,fail:S1.GTE},formatExclusiveMinimum:{okStr:">",ok:S1.GT,fail:S1.LTE}},AV={message:({keyword:w,schemaCode:b})=>dw.str`should be ${d6[w].okStr} ${b}`,params:({keyword:w,schemaCode:b})=>dw._`{comparison: ${d6[w].okStr}, limit: ${b}}`};CH.formatLimitDefinition={keyword:Object.keys(d6),type:"string",schemaType:"string",$data:!0,error:AV,code(w){let{gen:b,data:$,schemaCode:W,keyword:Q,it:X}=w,{opts:J,self:G}=X;if(!J.validateFormats)return;let Y=new DV.KeywordCxt(X,G.RULES.all.format.definition,"format");if(Y.$data)H();else z();function H(){let A=b.scopeValue("formats",{ref:G.formats,code:J.code.formats}),L=b.const("fmt",dw._`${A}[${Y.schemaCode}]`);w.fail$data((0,dw.or)(dw._`typeof ${L} != "object"`,dw._`${L} instanceof RegExp`,dw._`typeof ${L}.compare != "function"`,D(L)))}function z(){let A=Y.schema,L=G.formats[A];if(!L||L===!0)return;if(typeof L!="object"||L instanceof RegExp||typeof L.compare!="function")throw Error(`"${Q}": format "${A}" does not define "compare" function`);let F=b.scopeValue("formats",{key:A,ref:L,code:J.code.formats?dw._`${J.code.formats}${(0,dw.getProperty)(A)}`:void 0});w.fail$data(D(F))}function D(A){return dw._`${A}.compare(${$}, ${W}) ${d6[Q].fail} 0`}},dependencies:["format"]};var LV=(w)=>{return w.addKeyword(CH.formatLimitDefinition),w};CH.default=LV});var yH=N((Ob,hH)=>{Object.defineProperty(Ob,"__esModule",{value:!0});var D0=vH(),FV=kH(),q9=c(),_H=new q9.Name("fullFormats"),KV=new q9.Name("fastFormats"),P9=(w,b={keywords:!0})=>{if(Array.isArray(b))return xH(w,b,D0.fullFormats,_H),w;let[$,W]=b.mode==="fast"?[D0.fastFormats,KV]:[D0.fullFormats,_H],Q=b.formats||D0.formatNames;if(xH(w,Q,$,W),b.keywords)(0,FV.default)(w);return w};P9.get=(w,b="full")=>{let W=(b==="fast"?D0.fastFormats:D0.fullFormats)[w];if(!W)throw Error(`Unknown format "${w}"`);return W};function xH(w,b,$,W){var Q,X;(Q=(X=w.opts.code).formats)!==null&&Q!==void 0||(X.formats=q9._`require("ajv-formats/dist/formats").${W}`);for(let J of b)w.addFormat(J,$[J])}hH.exports=Ob=P9;Object.defineProperty(Ob,"__esModule",{value:!0});Ob.default=P9});import{AsyncLocalStorage as nz}from"node:async_hooks";class sw extends Error{statusCode;rawDetails;code;context;constructor(w,b,$,W,Q){super(w);this.statusCode=b;this.rawDetails=$;this.code=W;this.context=Q;this.name="McpApiError"}}function lz(w){if(w instanceof sw)return{message:w.message,statusCode:w.statusCode,code:w.code,rawDetails:w.rawDetails,context:w.context};if(w instanceof Error)return{message:w.message};return{message:String(w)}}function gz(w){let b=w.match(/api key is missing required scopes?:\s*(.+)$/i);if(!b?.[1])return[];return[...new Set(b[1].match(/[a-z_]+:[a-z_]+/gi)??[])]}function iz(w){let b=lz(w),$=b.message.trim()||"Unknown error",W=$.toLowerCase(),Q=b.rawDetails?.trim()||$;if(b.context?.title||b.context?.description||b.context?.howToFix||b.context?.docsUrl)return{title:b.context.title??(b.statusCode===409?"Request conflict":"API request failed"),description:b.context.description??$,howToFix:b.context.howToFix??"Review the details below, adjust the tool input, and retry.",docsUrl:b.context.docsUrl??"https://docs.sequenzy.com/concepts/mcp",details:Q};if(b.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(b.statusCode===401||b.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 X=gz($);if(X.length>0){let J=X.map((Y)=>`\`${Y}\``).join(", "),G=X.every((Y)=>Y.endsWith(":read"))?"the Read-only or Safer agent access preset":"Safer agent access when it covers the task, or Custom permissions";return{title:"API key permission required",description:`The current API key is valid, but this operation requires the missing ${X.length===1?"scope":"scopes"}: ${J}.`,howToFix:`Permissions can be widened on the key you are already using - no replacement key and no client restart. Call \`get_account\` to read \`apiKeyPermissions\`, then have the key owner open \`apiKeyPermissions.manageUrl\`, edit the key identified by \`apiKeyPermissions.activeKey\`, and enable ${J}. The URL opens Account → API Keys for a \`personal\` key and workspace Settings → API Keys for a \`company\` key. If \`get_account\` also requires \`account:read\`, open ${"https://sequenzy.com/dashboard"} directly and choose the matching API Keys page. When \`apiKeyPermissions.activeKey.type\` is \`company\` and the key holds \`api_keys:manage\`, the agent can instead call \`update_api_key\` with \`apiKeyId\` from \`apiKeyPermissions.activeKey.id\`. Personal keys cannot be changed through \`update_api_key\`. \`scopes\` and \`preset\` REPLACE the whole selection, so pass every scope in \`apiKeyPermissions.scopes\` plus ${J}, or a preset covering all of them (${G}). Then retry the same tool call - the API reloads the key's permissions on a denied request, so the retry succeeds without reconnecting. Issuing a replacement key and swapping \`SEQUENZY_API_KEY\`, or reauthorizing a hosted OAuth connection with wider permissions, also works but is not required.`,docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q}}if(b.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(b.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.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(b.statusCode===409)return{title:"Request conflict",description:"Sequenzy rejected this request because the resource changed or an operation is already in progress.",howToFix:"Refresh the resource state, choose the lifecycle action allowed by its current status, and retry at most once.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(b.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(b.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(b.statusCode&&b.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 d1(w){let b=iz(w);return[`Sequenzy MCP error: ${b.title}`,`Description: ${b.description}`,`How to fix: ${b.howToFix}`,`Docs: ${b.docsUrl}`,`Details: ${b.details}`].join(`
9
- `)}var pz="https://api.sequenzy.com",dz=new Set(["/api/v1/media/upload-bytes","/v1/media/upload-bytes"]),P0=new nz,DW=!1;function kj(){DW=!0}function Eb(){return DW}var AW=null;function k1(){let w=P0.getStore();if(w)return w.selectedCompanyId??null;return AW}function U4(w){let b=P0.getStore();if(b){b.selectedCompanyId=w;return}AW=w}function LW(w,b){return P0.run(w,b)}function UW(){return P0.getStore()?.apiUrl??process.env.SEQUENZY_API_URL??pz}function FW(){return P0.getStore()?.apiKey??process.env.SEQUENZY_API_KEY}function KW(w,b){let $=FW();if(!$)throw new sw("SEQUENZY_API_KEY environment variable is required",401,void 0,"MCP_AUTH_REQUIRED");let W={"Content-Type":w,Authorization:`Bearer ${$}`},Q=b??k1();if(Q)W["x-company-id"]=Q;return W}function _j(){if(FW())return;console.error(d1(new sw("SEQUENZY_API_KEY environment variable is required",401,void 0,"MCP_AUTH_REQUIRED"))),process.exit(1)}function Sw(w,b){let $=w[b];return typeof $==="string"&&$.trim()!==""?$.trim():void 0}function oz(w){if(w===void 0)return;if(typeof w==="string")return w.trim()||void 0;return JSON.stringify(w)}function OW(w){if(!w.trim())return{message:"Request failed"};try{let b=JSON.parse(w);if(typeof b==="string")return{message:b};let $=typeof b.error==="object"&&b.error!==null?b.error:void 0,W=Sw(b,"code")??($?Sw($,"code"):void 0),Q=(typeof b.error==="string"?b.error:void 0)??($?Sw($,"message"):void 0)??Sw(b,"message")??Sw(b,"error")??w,X=Sw(b,"howToFix")??Sw(b,"resolution"),J={...Sw(b,"title")?{title:Sw(b,"title")}:{},...Sw(b,"description")?{description:Sw(b,"description")}:{},...X?{howToFix:X}:{},...Sw(b,"docsUrl")?{docsUrl:Sw(b,"docsUrl")}:{}},G=oz(b.details);if(Object.keys(J).length>0||G)return{message:Q,...W?{code:W}:{},...G?{details:G}:{},...Object.keys(J).length>0?{context:J}:{}};if(typeof b.error==="string")return{message:b.error,...W?{code:W}:{}};if($)return{message:Q,...W?{code:W}:{}};return{message:Q,...W?{code:W}:{}}}catch{return{message:w}}}async function B(w,b,$,W){let Q=KW("application/json",W),X;try{X=await fetch(`${UW()}${b}`,{method:w,headers:Q,body:$?JSON.stringify($):void 0})}catch(J){throw new sw(J instanceof Error?J.message:"Failed to reach Sequenzy API",0,void 0,"NETWORK_ERROR")}if(!X.ok){let J=await X.text(),G=OW(J);throw new sw(G.message,X.status,G.details??J,G.code,G.context)}return X.json()}async function ZW(w,b,$,W){let Q=new URL(UW()).origin,X=new URL(w,`${Q}/`);if(X.origin!==Q){if(!dz.has(X.pathname))throw new sw("The image upload URL did not point to the configured Sequenzy API.",500,void 0,"INVALID_UPLOAD_URL");X=new URL(`${X.pathname}${X.search}`,`${Q}/`)}let J;try{J=await fetch(X,{method:"PUT",headers:KW($,W),body:b})}catch(G){throw new sw(G instanceof Error?G.message:"Failed to upload image bytes",0,void 0,"NETWORK_ERROR")}if(!J.ok){let G=await J.text(),Y=OW(G);throw new sw(Y.message,J.status,Y.details??G,Y.code,Y.context)}}var hj=Object.freeze({status:"aborted"});function O(w,b,$){function W(G,Y){var H;Object.defineProperty(G,"_zod",{value:G._zod??{},enumerable:!1}),(H=G._zod).traits??(H.traits=new Set),G._zod.traits.add(w),b(G,Y);for(let z in J.prototype)if(!(z in G))Object.defineProperty(G,z,{value:J.prototype[z].bind(G)});G._zod.constr=J,G._zod.def=Y}let Q=$?.Parent??Object;class X extends Q{}Object.defineProperty(X,"name",{value:w});function J(G){var Y;let H=$?.Parent?new X:this;W(H,G),(Y=H._zod).deferred??(Y.deferred=[]);for(let z of H._zod.deferred)z();return H}return Object.defineProperty(J,"init",{value:W}),Object.defineProperty(J,Symbol.hasInstance,{value:(G)=>{if($?.Parent&&G instanceof $.Parent)return!0;return G?._zod?.traits?.has(w)}}),Object.defineProperty(J,"name",{value:w}),J}var yj=Symbol("zod_brand");class W1 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class I0 extends Error{constructor(w){super(`Encountered unidirectional transform during encode: ${w}`);this.name="ZodEncodeError"}}var Tb={};function xw(w){if(w)Object.assign(Tb,w);return Tb}var o={};BW(o,{unwrapMessage:()=>N0,uint8ArrayToHex:()=>Z3,uint8ArrayToBase64url:()=>K3,uint8ArrayToBase64:()=>NW,stringifyPrimitive:()=>Cb,shallowClone:()=>VW,safeExtend:()=>B3,required:()=>L3,randomString:()=>Q3,propertyKeyTypes:()=>M4,promiseAllObject:()=>W3,primitiveTypes:()=>jW,prefixIssues:()=>X1,pick:()=>Y3,partial:()=>A3,optionalKeys:()=>V4,omit:()=>H3,objectClone:()=>w3,numKeys:()=>X3,nullish:()=>E0,normalizeParams:()=>v,mergeDefs:()=>O1,merge:()=>D3,jsonStringifyReplacer:()=>o1,joinValues:()=>Rb,issue:()=>r1,isPlainObject:()=>Z1,isObject:()=>_1,hexToUint8Array:()=>O3,getSizableOrigin:()=>PW,getParsedType:()=>J3,getLengthableOrigin:()=>R0,getEnumValues:()=>K4,getElementAtPath:()=>$3,floatSafeRemainder:()=>O4,finalizeIssue:()=>mw,extend:()=>z3,escapeRegex:()=>Q1,esc:()=>Sb,defineLazy:()=>s,createTransparentProxy:()=>G3,cloneDef:()=>b3,clone:()=>cw,cleanRegex:()=>T0,cleanEnum:()=>U3,captureStackTrace:()=>vb,cached:()=>t1,base64urlToUint8Array:()=>F3,base64ToUint8Array:()=>IW,assignProp:()=>K1,assertNotEqual:()=>rz,assertNever:()=>ez,assertIs:()=>sz,assertEqual:()=>tz,assert:()=>az,allowsEval:()=>Z4,aborted:()=>M1,NUMBER_FORMAT_RANGES:()=>j4,Class:()=>EW,BIGINT_FORMAT_RANGES:()=>qW});function tz(w){return w}function rz(w){return w}function sz(w){}function ez(w){throw Error()}function az(w){}function K4(w){let b=Object.values(w).filter((W)=>typeof W==="number");return Object.entries(w).filter(([W,Q])=>b.indexOf(+W)===-1).map(([W,Q])=>Q)}function Rb(w,b="|"){return w.map(($)=>Cb($)).join(b)}function o1(w,b){if(typeof b==="bigint")return b.toString();return b}function t1(w){return{get value(){{let $=w();return Object.defineProperty(this,"value",{value:$}),$}throw Error("cached value already set")}}}function E0(w){return w===null||w===void 0}function T0(w){let b=w.startsWith("^")?1:0,$=w.endsWith("$")?w.length-1:w.length;return w.slice(b,$)}function O4(w,b){let $=(w.toString().split(".")[1]||"").length,W=b.toString(),Q=(W.split(".")[1]||"").length;if(Q===0&&/\d?e-\d?/.test(W)){let Y=W.match(/\d?e-(\d?)/);if(Y?.[1])Q=Number.parseInt(Y[1])}let X=$>Q?$:Q,J=Number.parseInt(w.toFixed(X).replace(".","")),G=Number.parseInt(b.toFixed(X).replace(".",""));return J%G/10**X}var MW=Symbol("evaluating");function s(w,b,$){let W=void 0;Object.defineProperty(w,b,{get(){if(W===MW)return;if(W===void 0)W=MW,W=$();return W},set(Q){Object.defineProperty(w,b,{value:Q})},configurable:!0})}function w3(w){return Object.create(Object.getPrototypeOf(w),Object.getOwnPropertyDescriptors(w))}function K1(w,b,$){Object.defineProperty(w,b,{value:$,writable:!0,enumerable:!0,configurable:!0})}function O1(...w){let b={};for(let $ of w){let W=Object.getOwnPropertyDescriptors($);Object.assign(b,W)}return Object.defineProperties({},b)}function b3(w){return O1(w._zod.def)}function $3(w,b){if(!b)return w;return b.reduce(($,W)=>$?.[W],w)}function W3(w){let b=Object.keys(w),$=b.map((W)=>w[W]);return Promise.all($).then((W)=>{let Q={};for(let X=0;X<b.length;X++)Q[b[X]]=W[X];return Q})}function Q3(w=10){let $="";for(let W=0;W<w;W++)$+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return $}function Sb(w){return JSON.stringify(w)}var vb="captureStackTrace"in Error?Error.captureStackTrace:(...w)=>{};function _1(w){return typeof w==="object"&&w!==null&&!Array.isArray(w)}var Z4=t1(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(w){return!1}});function Z1(w){if(_1(w)===!1)return!1;let b=w.constructor;if(b===void 0)return!0;let $=b.prototype;if(_1($)===!1)return!1;if(Object.prototype.hasOwnProperty.call($,"isPrototypeOf")===!1)return!1;return!0}function VW(w){if(Z1(w))return{...w};if(Array.isArray(w))return[...w];return w}function X3(w){let b=0;for(let $ in w)if(Object.prototype.hasOwnProperty.call(w,$))b++;return b}var J3=(w)=>{let b=typeof w;switch(b){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(w)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(w))return"array";if(w===null)return"null";if(w.then&&typeof w.then==="function"&&w.catch&&typeof w.catch==="function")return"promise";if(typeof Map<"u"&&w instanceof Map)return"map";if(typeof Set<"u"&&w instanceof Set)return"set";if(typeof Date<"u"&&w instanceof Date)return"date";if(typeof File<"u"&&w instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${b}`)}},M4=new Set(["string","number","symbol"]),jW=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Q1(w){return w.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function cw(w,b,$){let W=new w._zod.constr(b??w._zod.def);if(!b||$?.parent)W._zod.parent=w;return W}function v(w){let b=w;if(!b)return{};if(typeof b==="string")return{error:()=>b};if(b?.message!==void 0){if(b?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");b.error=b.message}if(delete b.message,typeof b.error==="string")return{...b,error:()=>b.error};return b}function G3(w){let b;return new Proxy({},{get($,W,Q){return b??(b=w()),Reflect.get(b,W,Q)},set($,W,Q,X){return b??(b=w()),Reflect.set(b,W,Q,X)},has($,W){return b??(b=w()),Reflect.has(b,W)},deleteProperty($,W){return b??(b=w()),Reflect.deleteProperty(b,W)},ownKeys($){return b??(b=w()),Reflect.ownKeys(b)},getOwnPropertyDescriptor($,W){return b??(b=w()),Reflect.getOwnPropertyDescriptor(b,W)},defineProperty($,W,Q){return b??(b=w()),Reflect.defineProperty(b,W,Q)}})}function Cb(w){if(typeof w==="bigint")return w.toString()+"n";if(typeof w==="string")return`"${w}"`;return`${w}`}function V4(w){return Object.keys(w).filter((b)=>{return w[b]._zod.optin==="optional"&&w[b]._zod.optout==="optional"})}var j4={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]},qW={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function Y3(w,b){let $=w._zod.def,W=O1(w._zod.def,{get shape(){let Q={};for(let X in b){if(!(X in $.shape))throw Error(`Unrecognized key: "${X}"`);if(!b[X])continue;Q[X]=$.shape[X]}return K1(this,"shape",Q),Q},checks:[]});return cw(w,W)}function H3(w,b){let $=w._zod.def,W=O1(w._zod.def,{get shape(){let Q={...w._zod.def.shape};for(let X in b){if(!(X in $.shape))throw Error(`Unrecognized key: "${X}"`);if(!b[X])continue;delete Q[X]}return K1(this,"shape",Q),Q},checks:[]});return cw(w,W)}function z3(w,b){if(!Z1(b))throw Error("Invalid input to extend: expected a plain object");let $=w._zod.def.checks;if($&&$.length>0)throw Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");let Q=O1(w._zod.def,{get shape(){let X={...w._zod.def.shape,...b};return K1(this,"shape",X),X},checks:[]});return cw(w,Q)}function B3(w,b){if(!Z1(b))throw Error("Invalid input to safeExtend: expected a plain object");let $={...w._zod.def,get shape(){let W={...w._zod.def.shape,...b};return K1(this,"shape",W),W},checks:w._zod.def.checks};return cw(w,$)}function D3(w,b){let $=O1(w._zod.def,{get shape(){let W={...w._zod.def.shape,...b._zod.def.shape};return K1(this,"shape",W),W},get catchall(){return b._zod.def.catchall},checks:[]});return cw(w,$)}function A3(w,b,$){let W=O1(b._zod.def,{get shape(){let Q=b._zod.def.shape,X={...Q};if($)for(let J in $){if(!(J in Q))throw Error(`Unrecognized key: "${J}"`);if(!$[J])continue;X[J]=w?new w({type:"optional",innerType:Q[J]}):Q[J]}else for(let J in Q)X[J]=w?new w({type:"optional",innerType:Q[J]}):Q[J];return K1(this,"shape",X),X},checks:[]});return cw(b,W)}function L3(w,b,$){let W=O1(b._zod.def,{get shape(){let Q=b._zod.def.shape,X={...Q};if($)for(let J in $){if(!(J in X))throw Error(`Unrecognized key: "${J}"`);if(!$[J])continue;X[J]=new w({type:"nonoptional",innerType:Q[J]})}else for(let J in Q)X[J]=new w({type:"nonoptional",innerType:Q[J]});return K1(this,"shape",X),X},checks:[]});return cw(b,W)}function M1(w,b=0){if(w.aborted===!0)return!0;for(let $=b;$<w.issues.length;$++)if(w.issues[$]?.continue!==!0)return!0;return!1}function X1(w,b){return b.map(($)=>{var W;return(W=$).path??(W.path=[]),$.path.unshift(w),$})}function N0(w){return typeof w==="string"?w:w?.message}function mw(w,b,$){let W={...w,path:w.path??[]};if(!w.message){let Q=N0(w.inst?._zod.def?.error?.(w))??N0(b?.error?.(w))??N0($.customError?.(w))??N0($.localeError?.(w))??"Invalid input";W.message=Q}if(delete W.inst,delete W.continue,!b?.reportInput)delete W.input;return W}function PW(w){if(w instanceof Set)return"set";if(w instanceof Map)return"map";if(w instanceof File)return"file";return"unknown"}function R0(w){if(Array.isArray(w))return"array";if(typeof w==="string")return"string";return"unknown"}function r1(...w){let[b,$,W]=w;if(typeof b==="string")return{message:b,code:"custom",input:$,inst:W};return{...b}}function U3(w){return Object.entries(w).filter(([b,$])=>{return Number.isNaN(Number.parseInt(b,10))}).map((b)=>b[1])}function IW(w){let b=atob(w),$=new Uint8Array(b.length);for(let W=0;W<b.length;W++)$[W]=b.charCodeAt(W);return $}function NW(w){let b="";for(let $=0;$<w.length;$++)b+=String.fromCharCode(w[$]);return btoa(b)}function F3(w){let b=w.replace(/-/g,"+").replace(/_/g,"/"),$="=".repeat((4-b.length%4)%4);return IW(b+$)}function K3(w){return NW(w).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function O3(w){let b=w.replace(/^0x/,"");if(b.length%2!==0)throw Error("Invalid hex string length");let $=new Uint8Array(b.length/2);for(let W=0;W<b.length;W+=2)$[W/2]=Number.parseInt(b.slice(W,W+2),16);return $}function Z3(w){return Array.from(w).map((b)=>b.toString(16).padStart(2,"0")).join("")}class EW{constructor(...w){}}var TW=(w,b)=>{w.name="$ZodError",Object.defineProperty(w,"_zod",{value:w._zod,enumerable:!1}),Object.defineProperty(w,"issues",{value:b,enumerable:!1}),w.message=JSON.stringify(b,o1,2),Object.defineProperty(w,"toString",{value:()=>w.message,enumerable:!1})},kb=O("$ZodError",TW),q4=O("$ZodError",TW,{Parent:Error});function RW(w,b=($)=>$.message){let $={},W=[];for(let Q of w.issues)if(Q.path.length>0)$[Q.path[0]]=$[Q.path[0]]||[],$[Q.path[0]].push(b(Q));else W.push(b(Q));return{formErrors:W,fieldErrors:$}}function SW(w,b=($)=>$.message){let $={_errors:[]},W=(Q)=>{for(let X of Q.issues)if(X.code==="invalid_union"&&X.errors.length)X.errors.map((J)=>W({issues:J}));else if(X.code==="invalid_key")W({issues:X.issues});else if(X.code==="invalid_element")W({issues:X.issues});else if(X.path.length===0)$._errors.push(b(X));else{let J=$,G=0;while(G<X.path.length){let Y=X.path[G];if(G!==X.path.length-1)J[Y]=J[Y]||{_errors:[]};else J[Y]=J[Y]||{_errors:[]},J[Y]._errors.push(b(X));J=J[Y],G++}}};return W(w),$}var _b=(w)=>(b,$,W,Q)=>{let X=W?Object.assign(W,{async:!1}):{async:!1},J=b._zod.run({value:$,issues:[]},X);if(J instanceof Promise)throw new W1;if(J.issues.length){let G=new(Q?.Err??w)(J.issues.map((Y)=>mw(Y,X,xw())));throw vb(G,Q?.callee),G}return J.value};var xb=(w)=>async(b,$,W,Q)=>{let X=W?Object.assign(W,{async:!0}):{async:!0},J=b._zod.run({value:$,issues:[]},X);if(J instanceof Promise)J=await J;if(J.issues.length){let G=new(Q?.Err??w)(J.issues.map((Y)=>mw(Y,X,xw())));throw vb(G,Q?.callee),G}return J.value};var S0=(w)=>(b,$,W)=>{let Q=W?{...W,async:!1}:{async:!1},X=b._zod.run({value:$,issues:[]},Q);if(X instanceof Promise)throw new W1;return X.issues.length?{success:!1,error:new(w??kb)(X.issues.map((J)=>mw(J,Q,xw())))}:{success:!0,data:X.value}},v0=S0(q4),C0=(w)=>async(b,$,W)=>{let Q=W?Object.assign(W,{async:!0}):{async:!0},X=b._zod.run({value:$,issues:[]},Q);if(X instanceof Promise)X=await X;return X.issues.length?{success:!1,error:new w(X.issues.map((J)=>mw(J,Q,xw())))}:{success:!0,data:X.value}},hb=C0(q4),vW=(w)=>(b,$,W)=>{let Q=W?Object.assign(W,{direction:"backward"}):{direction:"backward"};return _b(w)(b,$,Q)};var CW=(w)=>(b,$,W)=>{return _b(w)(b,$,W)};var kW=(w)=>async(b,$,W)=>{let Q=W?Object.assign(W,{direction:"backward"}):{direction:"backward"};return xb(w)(b,$,Q)};var _W=(w)=>async(b,$,W)=>{return xb(w)(b,$,W)};var xW=(w)=>(b,$,W)=>{let Q=W?Object.assign(W,{direction:"backward"}):{direction:"backward"};return S0(w)(b,$,Q)};var hW=(w)=>(b,$,W)=>{return S0(w)(b,$,W)};var yW=(w)=>async(b,$,W)=>{let Q=W?Object.assign(W,{direction:"backward"}):{direction:"backward"};return C0(w)(b,$,Q)};var fW=(w)=>async(b,$,W)=>{return C0(w)(b,$,W)};var uW=/^[cC][^\s-]{8,}$/,cW=/^[0-9a-z]+$/,mW=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,lW=/^[0-9a-vA-V]{20}$/,gW=/^[A-Za-z0-9]{27}$/,iW=/^[a-zA-Z0-9_-]{21}$/,nW=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var pW=/^([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})$/,P4=(w)=>{if(!w)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}-${w}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)};var dW=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function oW(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}var tW=/^(?:(?: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])$/,rW=/^(([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}|:))$/,sW=/^((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])$/,eW=/^(([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])$/,aW=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,I4=/^[A-Za-z0-9_-]*$/,wQ=/^(?=.{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 bQ=/^\+(?:[0-9]){6,14}[0-9]$/,$Q="(?:(?:\\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])))",WQ=new RegExp(`^${$Q}$`);function QQ(w){return typeof w.precision==="number"?w.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":w.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{${w.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function XQ(w){return new RegExp(`^${QQ(w)}$`)}function JQ(w){let b=QQ({precision:w.precision}),$=["Z"];if(w.local)$.push("");if(w.offset)$.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let W=`${b}(?:${$.join("|")})`;return new RegExp(`^${$Q}T(?:${W})$`)}var GQ=(w)=>{let b=w?`[\\s\\S]{${w?.minimum??0},${w?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${b}$`)};var YQ=/^-?\d+$/,HQ=/^-?\d+(?:\.\d+)?/,zQ=/^(?:true|false)$/i,BQ=/^null$/i;var DQ=/^[^A-Z]*$/,AQ=/^[^a-z]*$/;var Uw=O("$ZodCheck",(w,b)=>{var $;w._zod??(w._zod={}),w._zod.def=b,($=w._zod).onattach??($.onattach=[])}),LQ={number:"number",bigint:"bigint",object:"date"},N4=O("$ZodCheckLessThan",(w,b)=>{Uw.init(w,b);let $=LQ[typeof b.value];w._zod.onattach.push((W)=>{let Q=W._zod.bag,X=(b.inclusive?Q.maximum:Q.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(b.value<X)if(b.inclusive)Q.maximum=b.value;else Q.exclusiveMaximum=b.value}),w._zod.check=(W)=>{if(b.inclusive?W.value<=b.value:W.value<b.value)return;W.issues.push({origin:$,code:"too_big",maximum:b.value,input:W.value,inclusive:b.inclusive,inst:w,continue:!b.abort})}}),E4=O("$ZodCheckGreaterThan",(w,b)=>{Uw.init(w,b);let $=LQ[typeof b.value];w._zod.onattach.push((W)=>{let Q=W._zod.bag,X=(b.inclusive?Q.minimum:Q.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(b.value>X)if(b.inclusive)Q.minimum=b.value;else Q.exclusiveMinimum=b.value}),w._zod.check=(W)=>{if(b.inclusive?W.value>=b.value:W.value>b.value)return;W.issues.push({origin:$,code:"too_small",minimum:b.value,input:W.value,inclusive:b.inclusive,inst:w,continue:!b.abort})}}),UQ=O("$ZodCheckMultipleOf",(w,b)=>{Uw.init(w,b),w._zod.onattach.push(($)=>{var W;(W=$._zod.bag).multipleOf??(W.multipleOf=b.value)}),w._zod.check=($)=>{if(typeof $.value!==typeof b.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof $.value==="bigint"?$.value%b.value===BigInt(0):O4($.value,b.value)===0)return;$.issues.push({origin:typeof $.value,code:"not_multiple_of",divisor:b.value,input:$.value,inst:w,continue:!b.abort})}}),FQ=O("$ZodCheckNumberFormat",(w,b)=>{Uw.init(w,b),b.format=b.format||"float64";let $=b.format?.includes("int"),W=$?"int":"number",[Q,X]=j4[b.format];w._zod.onattach.push((J)=>{let G=J._zod.bag;if(G.format=b.format,G.minimum=Q,G.maximum=X,$)G.pattern=YQ}),w._zod.check=(J)=>{let G=J.value;if($){if(!Number.isInteger(G)){J.issues.push({expected:W,format:b.format,code:"invalid_type",continue:!1,input:G,inst:w});return}if(!Number.isSafeInteger(G)){if(G>0)J.issues.push({input:G,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:w,origin:W,continue:!b.abort});else J.issues.push({input:G,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:w,origin:W,continue:!b.abort});return}}if(G<Q)J.issues.push({origin:"number",input:G,code:"too_small",minimum:Q,inclusive:!0,inst:w,continue:!b.abort});if(G>X)J.issues.push({origin:"number",input:G,code:"too_big",maximum:X,inst:w})}});var KQ=O("$ZodCheckMaxLength",(w,b)=>{var $;Uw.init(w,b),($=w._zod.def).when??($.when=(W)=>{let Q=W.value;return!E0(Q)&&Q.length!==void 0}),w._zod.onattach.push((W)=>{let Q=W._zod.bag.maximum??Number.POSITIVE_INFINITY;if(b.maximum<Q)W._zod.bag.maximum=b.maximum}),w._zod.check=(W)=>{let Q=W.value;if(Q.length<=b.maximum)return;let J=R0(Q);W.issues.push({origin:J,code:"too_big",maximum:b.maximum,inclusive:!0,input:Q,inst:w,continue:!b.abort})}}),OQ=O("$ZodCheckMinLength",(w,b)=>{var $;Uw.init(w,b),($=w._zod.def).when??($.when=(W)=>{let Q=W.value;return!E0(Q)&&Q.length!==void 0}),w._zod.onattach.push((W)=>{let Q=W._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(b.minimum>Q)W._zod.bag.minimum=b.minimum}),w._zod.check=(W)=>{let Q=W.value;if(Q.length>=b.minimum)return;let J=R0(Q);W.issues.push({origin:J,code:"too_small",minimum:b.minimum,inclusive:!0,input:Q,inst:w,continue:!b.abort})}}),ZQ=O("$ZodCheckLengthEquals",(w,b)=>{var $;Uw.init(w,b),($=w._zod.def).when??($.when=(W)=>{let Q=W.value;return!E0(Q)&&Q.length!==void 0}),w._zod.onattach.push((W)=>{let Q=W._zod.bag;Q.minimum=b.length,Q.maximum=b.length,Q.length=b.length}),w._zod.check=(W)=>{let Q=W.value,X=Q.length;if(X===b.length)return;let J=R0(Q),G=X>b.length;W.issues.push({origin:J,...G?{code:"too_big",maximum:b.length}:{code:"too_small",minimum:b.length},inclusive:!0,exact:!0,input:W.value,inst:w,continue:!b.abort})}}),k0=O("$ZodCheckStringFormat",(w,b)=>{var $,W;if(Uw.init(w,b),w._zod.onattach.push((Q)=>{let X=Q._zod.bag;if(X.format=b.format,b.pattern)X.patterns??(X.patterns=new Set),X.patterns.add(b.pattern)}),b.pattern)($=w._zod).check??($.check=(Q)=>{if(b.pattern.lastIndex=0,b.pattern.test(Q.value))return;Q.issues.push({origin:"string",code:"invalid_format",format:b.format,input:Q.value,...b.pattern?{pattern:b.pattern.toString()}:{},inst:w,continue:!b.abort})});else(W=w._zod).check??(W.check=()=>{})}),MQ=O("$ZodCheckRegex",(w,b)=>{k0.init(w,b),w._zod.check=($)=>{if(b.pattern.lastIndex=0,b.pattern.test($.value))return;$.issues.push({origin:"string",code:"invalid_format",format:"regex",input:$.value,pattern:b.pattern.toString(),inst:w,continue:!b.abort})}}),VQ=O("$ZodCheckLowerCase",(w,b)=>{b.pattern??(b.pattern=DQ),k0.init(w,b)}),jQ=O("$ZodCheckUpperCase",(w,b)=>{b.pattern??(b.pattern=AQ),k0.init(w,b)}),qQ=O("$ZodCheckIncludes",(w,b)=>{Uw.init(w,b);let $=Q1(b.includes),W=new RegExp(typeof b.position==="number"?`^.{${b.position}}${$}`:$);b.pattern=W,w._zod.onattach.push((Q)=>{let X=Q._zod.bag;X.patterns??(X.patterns=new Set),X.patterns.add(W)}),w._zod.check=(Q)=>{if(Q.value.includes(b.includes,b.position))return;Q.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:b.includes,input:Q.value,inst:w,continue:!b.abort})}}),PQ=O("$ZodCheckStartsWith",(w,b)=>{Uw.init(w,b);let $=new RegExp(`^${Q1(b.prefix)}.*`);b.pattern??(b.pattern=$),w._zod.onattach.push((W)=>{let Q=W._zod.bag;Q.patterns??(Q.patterns=new Set),Q.patterns.add($)}),w._zod.check=(W)=>{if(W.value.startsWith(b.prefix))return;W.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:b.prefix,input:W.value,inst:w,continue:!b.abort})}}),IQ=O("$ZodCheckEndsWith",(w,b)=>{Uw.init(w,b);let $=new RegExp(`.*${Q1(b.suffix)}$`);b.pattern??(b.pattern=$),w._zod.onattach.push((W)=>{let Q=W._zod.bag;Q.patterns??(Q.patterns=new Set),Q.patterns.add($)}),w._zod.check=(W)=>{if(W.value.endsWith(b.suffix))return;W.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:b.suffix,input:W.value,inst:w,continue:!b.abort})}});var NQ=O("$ZodCheckOverwrite",(w,b)=>{Uw.init(w,b),w._zod.check=($)=>{$.value=b.tx($.value)}});class T4{constructor(w=[]){if(this.content=[],this.indent=0,this)this.args=w}indented(w){this.indent+=1,w(this),this.indent-=1}write(w){if(typeof w==="function"){w(this,{execution:"sync"}),w(this,{execution:"async"});return}let $=w.split(`
10
- `).filter((X)=>X),W=Math.min(...$.map((X)=>X.length-X.trimStart().length)),Q=$.map((X)=>X.slice(W)).map((X)=>" ".repeat(this.indent*2)+X);for(let X of Q)this.content.push(X)}compile(){let w=Function,b=this?.args,W=[...(this?.content??[""]).map((Q)=>` ${Q}`)];return new w(...b,W.join(`
11
- `))}}var TQ={major:4,minor:1,patch:12};var ww=O("$ZodType",(w,b)=>{var $;w??(w={}),w._zod.def=b,w._zod.bag=w._zod.bag||{},w._zod.version=TQ;let W=[...w._zod.def.checks??[]];if(w._zod.traits.has("$ZodCheck"))W.unshift(w);for(let Q of W)for(let X of Q._zod.onattach)X(w);if(W.length===0)($=w._zod).deferred??($.deferred=[]),w._zod.deferred?.push(()=>{w._zod.run=w._zod.parse});else{let Q=(J,G,Y)=>{let H=M1(J),z;for(let D of G){if(D._zod.def.when){if(!D._zod.def.when(J))continue}else if(H)continue;let A=J.issues.length,L=D._zod.check(J);if(L instanceof Promise&&Y?.async===!1)throw new W1;if(z||L instanceof Promise)z=(z??Promise.resolve()).then(async()=>{if(await L,J.issues.length===A)return;if(!H)H=M1(J,A)});else{if(J.issues.length===A)continue;if(!H)H=M1(J,A)}}if(z)return z.then(()=>{return J});return J},X=(J,G,Y)=>{if(M1(J))return J.aborted=!0,J;let H=Q(G,W,Y);if(H instanceof Promise){if(Y.async===!1)throw new W1;return H.then((z)=>w._zod.parse(z,Y))}return w._zod.parse(H,Y)};w._zod.run=(J,G)=>{if(G.skipChecks)return w._zod.parse(J,G);if(G.direction==="backward"){let H=w._zod.parse({value:J.value,issues:[]},{...G,skipChecks:!0});if(H instanceof Promise)return H.then((z)=>{return X(z,J,G)});return X(H,J,G)}let Y=w._zod.parse(J,G);if(Y instanceof Promise){if(G.async===!1)throw new W1;return Y.then((H)=>Q(H,W,G))}return Q(Y,W,G)}}w["~standard"]={validate:(Q)=>{try{let X=v0(w,Q);return X.success?{value:X.data}:{issues:X.error?.issues}}catch(X){return hb(w,Q).then((J)=>J.success?{value:J.data}:{issues:J.error?.issues})}},vendor:"zod",version:1}}),cb=O("$ZodString",(w,b)=>{ww.init(w,b),w._zod.pattern=[...w?._zod.bag?.patterns??[]].pop()??GQ(w._zod.bag),w._zod.parse=($,W)=>{if(b.coerce)try{$.value=String($.value)}catch(Q){}if(typeof $.value==="string")return $;return $.issues.push({expected:"string",code:"invalid_type",input:$.value,inst:w}),$}}),bw=O("$ZodStringFormat",(w,b)=>{k0.init(w,b),cb.init(w,b)}),yQ=O("$ZodGUID",(w,b)=>{b.pattern??(b.pattern=pW),bw.init(w,b)}),fQ=O("$ZodUUID",(w,b)=>{if(b.version){let W={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[b.version];if(W===void 0)throw Error(`Invalid UUID version: "${b.version}"`);b.pattern??(b.pattern=P4(W))}else b.pattern??(b.pattern=P4());bw.init(w,b)}),uQ=O("$ZodEmail",(w,b)=>{b.pattern??(b.pattern=dW),bw.init(w,b)}),cQ=O("$ZodURL",(w,b)=>{bw.init(w,b),w._zod.check=($)=>{try{let W=$.value.trim(),Q=new URL(W);if(b.hostname){if(b.hostname.lastIndex=0,!b.hostname.test(Q.hostname))$.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:wQ.source,input:$.value,inst:w,continue:!b.abort})}if(b.protocol){if(b.protocol.lastIndex=0,!b.protocol.test(Q.protocol.endsWith(":")?Q.protocol.slice(0,-1):Q.protocol))$.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:b.protocol.source,input:$.value,inst:w,continue:!b.abort})}if(b.normalize)$.value=Q.href;else $.value=W;return}catch(W){$.issues.push({code:"invalid_format",format:"url",input:$.value,inst:w,continue:!b.abort})}}}),mQ=O("$ZodEmoji",(w,b)=>{b.pattern??(b.pattern=oW()),bw.init(w,b)}),lQ=O("$ZodNanoID",(w,b)=>{b.pattern??(b.pattern=iW),bw.init(w,b)}),gQ=O("$ZodCUID",(w,b)=>{b.pattern??(b.pattern=uW),bw.init(w,b)}),iQ=O("$ZodCUID2",(w,b)=>{b.pattern??(b.pattern=cW),bw.init(w,b)}),nQ=O("$ZodULID",(w,b)=>{b.pattern??(b.pattern=mW),bw.init(w,b)}),pQ=O("$ZodXID",(w,b)=>{b.pattern??(b.pattern=lW),bw.init(w,b)}),dQ=O("$ZodKSUID",(w,b)=>{b.pattern??(b.pattern=gW),bw.init(w,b)}),oQ=O("$ZodISODateTime",(w,b)=>{b.pattern??(b.pattern=JQ(b)),bw.init(w,b)}),tQ=O("$ZodISODate",(w,b)=>{b.pattern??(b.pattern=WQ),bw.init(w,b)}),rQ=O("$ZodISOTime",(w,b)=>{b.pattern??(b.pattern=XQ(b)),bw.init(w,b)}),sQ=O("$ZodISODuration",(w,b)=>{b.pattern??(b.pattern=nW),bw.init(w,b)}),eQ=O("$ZodIPv4",(w,b)=>{b.pattern??(b.pattern=tW),bw.init(w,b),w._zod.onattach.push(($)=>{let W=$._zod.bag;W.format="ipv4"})}),aQ=O("$ZodIPv6",(w,b)=>{b.pattern??(b.pattern=rW),bw.init(w,b),w._zod.onattach.push(($)=>{let W=$._zod.bag;W.format="ipv6"}),w._zod.check=($)=>{try{new URL(`http://[${$.value}]`)}catch{$.issues.push({code:"invalid_format",format:"ipv6",input:$.value,inst:w,continue:!b.abort})}}}),w8=O("$ZodCIDRv4",(w,b)=>{b.pattern??(b.pattern=sW),bw.init(w,b)}),b8=O("$ZodCIDRv6",(w,b)=>{b.pattern??(b.pattern=eW),bw.init(w,b),w._zod.check=($)=>{let W=$.value.split("/");try{if(W.length!==2)throw Error();let[Q,X]=W;if(!X)throw Error();let J=Number(X);if(`${J}`!==X)throw Error();if(J<0||J>128)throw Error();new URL(`http://[${Q}]`)}catch{$.issues.push({code:"invalid_format",format:"cidrv6",input:$.value,inst:w,continue:!b.abort})}}});function $8(w){if(w==="")return!0;if(w.length%4!==0)return!1;try{return atob(w),!0}catch{return!1}}var W8=O("$ZodBase64",(w,b)=>{b.pattern??(b.pattern=aW),bw.init(w,b),w._zod.onattach.push(($)=>{$._zod.bag.contentEncoding="base64"}),w._zod.check=($)=>{if($8($.value))return;$.issues.push({code:"invalid_format",format:"base64",input:$.value,inst:w,continue:!b.abort})}});function q3(w){if(!I4.test(w))return!1;let b=w.replace(/[-_]/g,(W)=>W==="-"?"+":"/"),$=b.padEnd(Math.ceil(b.length/4)*4,"=");return $8($)}var Q8=O("$ZodBase64URL",(w,b)=>{b.pattern??(b.pattern=I4),bw.init(w,b),w._zod.onattach.push(($)=>{$._zod.bag.contentEncoding="base64url"}),w._zod.check=($)=>{if(q3($.value))return;$.issues.push({code:"invalid_format",format:"base64url",input:$.value,inst:w,continue:!b.abort})}}),X8=O("$ZodE164",(w,b)=>{b.pattern??(b.pattern=bQ),bw.init(w,b)});function P3(w,b=null){try{let $=w.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(b&&(!("alg"in Q)||Q.alg!==b))return!1;return!0}catch{return!1}}var J8=O("$ZodJWT",(w,b)=>{bw.init(w,b),w._zod.check=($)=>{if(P3($.value,b.alg))return;$.issues.push({code:"invalid_format",format:"jwt",input:$.value,inst:w,continue:!b.abort})}});var S4=O("$ZodNumber",(w,b)=>{ww.init(w,b),w._zod.pattern=w._zod.bag.pattern??HQ,w._zod.parse=($,W)=>{if(b.coerce)try{$.value=Number($.value)}catch(J){}let Q=$.value;if(typeof Q==="number"&&!Number.isNaN(Q)&&Number.isFinite(Q))return $;let X=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:w,...X?{received:X}:{}}),$}}),G8=O("$ZodNumber",(w,b)=>{FQ.init(w,b),S4.init(w,b)}),Y8=O("$ZodBoolean",(w,b)=>{ww.init(w,b),w._zod.pattern=zQ,w._zod.parse=($,W)=>{if(b.coerce)try{$.value=Boolean($.value)}catch(X){}let Q=$.value;if(typeof Q==="boolean")return $;return $.issues.push({expected:"boolean",code:"invalid_type",input:Q,inst:w}),$}});var H8=O("$ZodNull",(w,b)=>{ww.init(w,b),w._zod.pattern=BQ,w._zod.values=new Set([null]),w._zod.parse=($,W)=>{let Q=$.value;if(Q===null)return $;return $.issues.push({expected:"null",code:"invalid_type",input:Q,inst:w}),$}});var z8=O("$ZodUnknown",(w,b)=>{ww.init(w,b),w._zod.parse=($)=>$}),B8=O("$ZodNever",(w,b)=>{ww.init(w,b),w._zod.parse=($,W)=>{return $.issues.push({expected:"never",code:"invalid_type",input:$.value,inst:w}),$}});function RQ(w,b,$){if(w.issues.length)b.issues.push(...X1($,w.issues));b.value[$]=w.value}var D8=O("$ZodArray",(w,b)=>{ww.init(w,b),w._zod.parse=($,W)=>{let Q=$.value;if(!Array.isArray(Q))return $.issues.push({expected:"array",code:"invalid_type",input:Q,inst:w}),$;$.value=Array(Q.length);let X=[];for(let J=0;J<Q.length;J++){let G=Q[J],Y=b.element._zod.run({value:G,issues:[]},W);if(Y instanceof Promise)X.push(Y.then((H)=>RQ(H,$,J)));else RQ(Y,$,J)}if(X.length)return Promise.all(X).then(()=>$);return $}});function ub(w,b,$,W){if(w.issues.length)b.issues.push(...X1($,w.issues));if(w.value===void 0){if($ in W)b.value[$]=void 0}else b.value[$]=w.value}function A8(w){let b=Object.keys(w.shape);for(let W of b)if(!w.shape?.[W]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${W}": expected a Zod schema`);let $=V4(w.shape);return{...w,keys:b,keySet:new Set(b),numKeys:b.length,optionalKeys:new Set($)}}function L8(w,b,$,W,Q,X){let J=[],G=Q.keySet,Y=Q.catchall._zod,H=Y.def.type;for(let z of Object.keys(b)){if(G.has(z))continue;if(H==="never"){J.push(z);continue}let D=Y.run({value:b[z],issues:[]},W);if(D instanceof Promise)w.push(D.then((A)=>ub(A,$,z,b)));else ub(D,$,z,b)}if(J.length)$.issues.push({code:"unrecognized_keys",keys:J,input:b,inst:X});if(!w.length)return $;return Promise.all(w).then(()=>{return $})}var I3=O("$ZodObject",(w,b)=>{if(ww.init(w,b),!Object.getOwnPropertyDescriptor(b,"shape")?.get){let G=b.shape;Object.defineProperty(b,"shape",{get:()=>{let Y={...G};return Object.defineProperty(b,"shape",{value:Y}),Y}})}let W=t1(()=>A8(b));s(w._zod,"propValues",()=>{let G=b.shape,Y={};for(let H in G){let z=G[H]._zod;if(z.values){Y[H]??(Y[H]=new Set);for(let D of z.values)Y[H].add(D)}}return Y});let Q=_1,X=b.catchall,J;w._zod.parse=(G,Y)=>{J??(J=W.value);let H=G.value;if(!Q(H))return G.issues.push({expected:"object",code:"invalid_type",input:H,inst:w}),G;G.value={};let z=[],D=J.shape;for(let A of J.keys){let F=D[A]._zod.run({value:H[A],issues:[]},Y);if(F instanceof Promise)z.push(F.then((V)=>ub(V,G,A,H)));else ub(F,G,A,H)}if(!X)return z.length?Promise.all(z).then(()=>G):G;return L8(z,H,G,Y,W.value,w)}}),U8=O("$ZodObjectJIT",(w,b)=>{I3.init(w,b);let $=w._zod.parse,W=t1(()=>A8(b)),Q=(A)=>{let L=new T4(["shape","payload","ctx"]),F=W.value,V=(S)=>{let l=Sb(S);return`shape[${l}]._zod.run({ value: input[${l}], issues: [] }, ctx)`};L.write("const input = payload.value;");let q=Object.create(null),P=0;for(let S of F.keys)q[S]=`key_${P++}`;L.write("const newResult = {};");for(let S of F.keys){let l=q[S],_=Sb(S);L.write(`const ${l} = ${V(S)};`),L.write(`
12
- if (${l}.issues.length) {
13
- payload.issues = payload.issues.concat(${l}.issues.map(iss => ({
8
+ deps: ${$}}`};var _Z={keyword:"dependencies",type:"object",schemaType:"object",error:v7.error,code(w){let[b,$]=xZ(w);R7(w,b),S7(w,$)}};function xZ({schema:w}){let b={},$={};for(let Q in w){if(Q==="__proto__")continue;let W=Array.isArray(w[Q])?b:$;W[Q]=w[Q]}return[b,$]}function R7(w,b=w.schema){let{gen:$,data:Q,it:W}=w;if(Object.keys(b).length===0)return;let X=$.let("missing");for(let J in b){let Y=b[J];if(Y.length===0)continue;let G=(0,Mb.propertyInData)($,Q,J,W.opts.ownProperties);if(w.setParams({property:J,depsCount:Y.length,deps:Y.join(", ")}),W.allErrors)$.if(G,()=>{for(let H of Y)(0,Mb.checkReportMissingProp)(w,H)});else $.if(U9._`${G} && (${(0,Mb.checkMissingProp)(w,Y,X)})`),(0,Mb.reportMissingProp)(w,X),$.else()}}v7.validatePropertyDeps=R7;function S7(w,b=w.schema){let{gen:$,data:Q,keyword:W,it:X}=w,J=$.name("valid");for(let Y in b){if((0,kZ.alwaysValidSchema)(X,b[Y]))continue;$.if((0,Mb.propertyInData)($,Q,Y,X.opts.ownProperties),()=>{let G=w.subschema({keyword:W,schemaProp:Y},J);w.mergeValidEvaluated(G,J)},()=>$.var(J,!0)),w.ok(J)}}v7.validateSchemaDeps=S7;v7.default=_Z});var y7=E((h7)=>{Object.defineProperty(h7,"__esModule",{value:!0});var x7=m(),fZ=t(),uZ={message:"property name must be valid",params:({params:w})=>x7._`{propertyName: ${w.propertyName}}`},cZ={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:uZ,code(w){let{gen:b,schema:$,data:Q,it:W}=w;if((0,fZ.alwaysValidSchema)(W,$))return;let X=b.name("valid");b.forIn("key",Q,(J)=>{w.setParams({propertyName:J}),w.subschema({keyword:"propertyNames",data:J,dataTypes:["string"],propertyName:J,compositeRule:!0},X),b.if((0,x7.not)(X),()=>{if(w.error(!0),!W.allErrors)b.break()})}),w.ok(X)}};h7.default=cZ});var A9=E((f7)=>{Object.defineProperty(f7,"__esModule",{value:!0});var p6=c1(),r1=m(),lZ=z0(),d6=t(),gZ={message:"must NOT have additional properties",params:({params:w})=>r1._`{additionalProperty: ${w.additionalProperty}}`},iZ={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:gZ,code(w){let{gen:b,schema:$,parentSchema:Q,data:W,errsCount:X,it:J}=w;if(!X)throw Error("ajv implementation error");let{allErrors:Y,opts:G}=J;if(J.props=!0,G.removeAdditional!=="all"&&(0,d6.alwaysValidSchema)(J,$))return;let H=(0,p6.allSchemaProperties)(Q.properties),z=(0,p6.allSchemaProperties)(Q.patternProperties);B(),w.ok(r1._`${X} === ${lZ.default.errors}`);function B(){b.forIn("key",W,(q)=>{if(!H.length&&!z.length)A(q);else b.if(L(q),()=>A(q))})}function L(q){let P;if(H.length>8){let v=(0,d6.schemaRefOrVal)(J,Q.properties,"properties");P=(0,p6.isOwnProperty)(b,v,q)}else if(H.length)P=(0,r1.or)(...H.map((v)=>r1._`${q} === ${v}`));else P=r1.nil;if(z.length)P=(0,r1.or)(P,...z.map((v)=>r1._`${(0,p6.usePattern)(w,v)}.test(${q})`));return(0,r1.not)(P)}function F(q){b.code(r1._`delete ${W}[${q}]`)}function A(q){if(G.removeAdditional==="all"||G.removeAdditional&&$===!1){F(q);return}if($===!1){if(w.setParams({additionalProperty:q}),w.error(),!Y)b.break();return}if(typeof $=="object"&&!(0,d6.alwaysValidSchema)(J,$)){let P=b.name("valid");if(G.removeAdditional==="failing")j(q,P,!1),b.if((0,r1.not)(P),()=>{w.reset(),F(q)});else if(j(q,P),!Y)b.if((0,r1.not)(P),()=>b.break())}}function j(q,P,v){let S={keyword:"additionalProperties",dataProp:q,dataPropType:d6.Type.Str};if(v===!1)Object.assign(S,{compositeRule:!0,createErrors:!1,allErrors:!1});w.subschema(S,P)}}};f7.default=iZ});var l7=E((m7)=>{Object.defineProperty(m7,"__esModule",{value:!0});var pZ=Hb(),u7=c1(),K9=t(),c7=A9(),dZ={keyword:"properties",type:"object",schemaType:"object",code(w){let{gen:b,schema:$,parentSchema:Q,data:W,it:X}=w;if(X.opts.removeAdditional==="all"&&Q.additionalProperties===void 0)c7.default.code(new pZ.KeywordCxt(X,c7.default,"additionalProperties"));let J=(0,u7.allSchemaProperties)($);for(let B of J)X.definedProperties.add(B);if(X.opts.unevaluated&&J.length&&X.props!==!0)X.props=K9.mergeEvaluated.props(b,(0,K9.toHash)(J),X.props);let Y=J.filter((B)=>!(0,K9.alwaysValidSchema)(X,$[B]));if(Y.length===0)return;let G=b.name("valid");for(let B of Y){if(H(B))z(B);else{if(b.if((0,u7.propertyInData)(b,W,B,X.opts.ownProperties)),z(B),!X.allErrors)b.else().var(G,!0);b.endIf()}w.it.definedProperties.add(B),w.ok(G)}function H(B){return X.opts.useDefaults&&!X.compositeRule&&$[B].default!==void 0}function z(B){w.subschema({keyword:"properties",schemaProp:B,dataProp:B},G)}}};m7.default=dZ});var d7=E((p7)=>{Object.defineProperty(p7,"__esModule",{value:!0});var g7=c1(),o6=m(),i7=t(),n7=t(),tZ={keyword:"patternProperties",type:"object",schemaType:"object",code(w){let{gen:b,schema:$,data:Q,parentSchema:W,it:X}=w,{opts:J}=X,Y=(0,g7.allSchemaProperties)($),G=Y.filter((j)=>(0,i7.alwaysValidSchema)(X,$[j]));if(Y.length===0||G.length===Y.length&&(!X.opts.unevaluated||X.props===!0))return;let H=J.strictSchema&&!J.allowMatchingProperties&&W.properties,z=b.name("valid");if(X.props!==!0&&!(X.props instanceof o6.Name))X.props=(0,n7.evaluatedPropsToName)(b,X.props);let{props:B}=X;L();function L(){for(let j of Y){if(H)F(j);if(X.allErrors)A(j);else b.var(z,!0),A(j),b.if(z)}}function F(j){for(let q in H)if(new RegExp(j).test(q))(0,i7.checkStrictMode)(X,`property ${q} matches pattern ${j} (use allowMatchingProperties)`)}function A(j){b.forIn("key",Q,(q)=>{b.if(o6._`${(0,g7.usePattern)(w,j)}.test(${q})`,()=>{let P=G.includes(j);if(!P)w.subschema({keyword:"patternProperties",schemaProp:j,dataProp:q,dataPropType:n7.Type.Str},z);if(X.opts.unevaluated&&B!==!0)b.assign(o6._`${B}[${q}]`,!0);else if(!P&&!X.allErrors)b.if((0,o6.not)(z),()=>b.break())})})}}};p7.default=tZ});var t7=E((o7)=>{Object.defineProperty(o7,"__esModule",{value:!0});var sZ=t(),eZ={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(w){let{gen:b,schema:$,it:Q}=w;if((0,sZ.alwaysValidSchema)(Q,$)){w.fail();return}let W=b.name("valid");w.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},W),w.failResult(W,()=>w.reset(),()=>w.error())},error:{message:"must NOT be valid"}};o7.default=eZ});var s7=E((r7)=>{Object.defineProperty(r7,"__esModule",{value:!0});var wj=c1(),bj={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:wj.validateUnion,error:{message:"must match a schema in anyOf"}};r7.default=bj});var a7=E((e7)=>{Object.defineProperty(e7,"__esModule",{value:!0});var t6=m(),Qj=t(),Wj={message:"must match exactly one schema in oneOf",params:({params:w})=>t6._`{passingSchemas: ${w.passing}}`},Xj={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:Wj,code(w){let{gen:b,schema:$,parentSchema:Q,it:W}=w;if(!Array.isArray($))throw Error("ajv implementation error");if(W.opts.discriminator&&Q.discriminator)return;let X=$,J=b.let("valid",!1),Y=b.let("passing",null),G=b.name("_valid");w.setParams({passing:Y}),b.block(H),w.result(J,()=>w.reset(),()=>w.error(!0));function H(){X.forEach((z,B)=>{let L;if((0,Qj.alwaysValidSchema)(W,z))b.var(G,!0);else L=w.subschema({keyword:"oneOf",schemaProp:B,compositeRule:!0},G);if(B>0)b.if(t6._`${G} && ${J}`).assign(J,!1).assign(Y,t6._`[${Y}, ${B}]`).else();b.if(G,()=>{if(b.assign(J,!0),b.assign(Y,B),L)w.mergeEvaluated(L,t6.Name)})})}}};e7.default=Xj});var bH=E((wH)=>{Object.defineProperty(wH,"__esModule",{value:!0});var Yj=t(),Gj={keyword:"allOf",schemaType:"array",code(w){let{gen:b,schema:$,it:Q}=w;if(!Array.isArray($))throw Error("ajv implementation error");let W=b.name("valid");$.forEach((X,J)=>{if((0,Yj.alwaysValidSchema)(Q,X))return;let Y=w.subschema({keyword:"allOf",schemaProp:J},W);w.ok(W),w.mergeEvaluated(Y)})}};wH.default=Gj});var XH=E((WH)=>{Object.defineProperty(WH,"__esModule",{value:!0});var r6=m(),QH=t(),zj={message:({params:w})=>r6.str`must match "${w.ifClause}" schema`,params:({params:w})=>r6._`{failingKeyword: ${w.ifClause}}`},Dj={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:zj,code(w){let{gen:b,parentSchema:$,it:Q}=w;if($.then===void 0&&$.else===void 0)(0,QH.checkStrictMode)(Q,'"if" without "then" and "else" is ignored');let W=$H(Q,"then"),X=$H(Q,"else");if(!W&&!X)return;let J=b.let("valid",!0),Y=b.name("_valid");if(G(),w.reset(),W&&X){let z=b.let("ifClause");w.setParams({ifClause:z}),b.if(Y,H("then",z),H("else",z))}else if(W)b.if(Y,H("then"));else b.if((0,r6.not)(Y),H("else"));w.pass(J,()=>w.error(!0));function G(){let z=w.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},Y);w.mergeEvaluated(z)}function H(z,B){return()=>{let L=w.subschema({keyword:z},Y);if(b.assign(J,Y),w.mergeValidEvaluated(L,J),B)b.assign(B,r6._`${z}`);else w.setParams({ifClause:z})}}}};function $H(w,b){let $=w.schema[b];return $!==void 0&&!(0,QH.alwaysValidSchema)(w,$)}WH.default=Dj});var YH=E((JH)=>{Object.defineProperty(JH,"__esModule",{value:!0});var Lj=t(),Fj={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:w,parentSchema:b,it:$}){if(b.if===void 0)(0,Lj.checkStrictMode)($,`"${w}" without "if" is ignored`)}};JH.default=Fj});var HH=E((GH)=>{Object.defineProperty(GH,"__esModule",{value:!0});var Aj=L9(),Kj=P7(),Oj=F9(),Zj=E7(),jj=T7(),Mj=_7(),Vj=y7(),Pj=A9(),qj=l7(),Ij=d7(),Ej=t7(),Nj=s7(),Tj=a7(),Rj=bH(),Sj=XH(),vj=YH();function Cj(w=!1){let b=[Ej.default,Nj.default,Tj.default,Rj.default,Sj.default,vj.default,Vj.default,Pj.default,Mj.default,qj.default,Ij.default];if(w)b.push(Kj.default,Zj.default);else b.push(Aj.default,Oj.default);return b.push(jj.default),b}GH.default=Cj});var DH=E((zH)=>{Object.defineProperty(zH,"__esModule",{value:!0});var z1=m(),_j={message:({schemaCode:w})=>z1.str`must match format "${w}"`,params:({schemaCode:w})=>z1._`{format: ${w}}`},xj={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:_j,code(w,b){let{gen:$,data:Q,$data:W,schema:X,schemaCode:J,it:Y}=w,{opts:G,errSchemaPath:H,schemaEnv:z,self:B}=Y;if(!G.validateFormats)return;if(W)L();else F();function L(){let A=$.scopeValue("formats",{ref:B.formats,code:G.code.formats}),j=$.const("fDef",z1._`${A}[${J}]`),q=$.let("fType"),P=$.let("format");$.if(z1._`typeof ${j} == "object" && !(${j} instanceof RegExp)`,()=>$.assign(q,z1._`${j}.type || "string"`).assign(P,z1._`${j}.validate`),()=>$.assign(q,z1._`"string"`).assign(P,j)),w.fail$data((0,z1.or)(v(),S()));function v(){if(G.strictSchema===!1)return z1.nil;return z1._`${J} && !${P}`}function S(){let u=z.$async?z1._`(${j}.async ? await ${P}(${Q}) : ${P}(${Q}))`:z1._`${P}(${Q})`,_=z1._`(typeof ${P} == "function" ? ${u} : ${P}.test(${Q}))`;return z1._`${P} && ${P} !== true && ${q} === ${b} && !${_}`}}function F(){let A=B.formats[X];if(!A){v();return}if(A===!0)return;let[j,q,P]=S(A);if(j===b)w.pass(u());function v(){if(G.strictSchema===!1){B.logger.warn(_());return}throw Error(_());function _(){return`unknown format "${X}" ignored in schema at path "${H}"`}}function S(_){let S1=_ instanceof RegExp?(0,z1.regexpCode)(_):G.code.formats?z1._`${G.code.formats}${(0,z1.getProperty)(X)}`:void 0,l1=$.scopeValue("formats",{key:X,ref:_,code:S1});if(typeof _=="object"&&!(_ instanceof RegExp))return[_.type||"string",_.validate,z1._`${l1}.validate`];return["string",_,l1]}function u(){if(typeof A=="object"&&!(A instanceof RegExp)&&A.async){if(!z.$async)throw Error("async format in sync schema");return z1._`await ${P}(${Q})`}return typeof q=="function"?z1._`${P}(${Q})`:z1._`${P}.test(${Q})`}}}};zH.default=xj});var LH=E((BH)=>{Object.defineProperty(BH,"__esModule",{value:!0});var yj=DH(),fj=[yj.default];BH.default=fj});var AH=E((FH)=>{Object.defineProperty(FH,"__esModule",{value:!0});FH.contentVocabulary=FH.metadataVocabulary=void 0;FH.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];FH.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var ZH=E((OH)=>{Object.defineProperty(OH,"__esModule",{value:!0});var mj=mG(),lj=F7(),gj=HH(),ij=LH(),KH=AH(),nj=[mj.default,lj.default,(0,gj.default)(),ij.default,KH.metadataVocabulary,KH.contentVocabulary];OH.default=nj});var PH=E((MH)=>{Object.defineProperty(MH,"__esModule",{value:!0});MH.DiscrError=void 0;var jH;(function(w){w.Tag="tag",w.Mapping="mapping"})(jH||(MH.DiscrError=jH={}))});var EH=E((IH)=>{Object.defineProperty(IH,"__esModule",{value:!0});var Fw=m(),O9=PH(),qH=v6(),dj=zb(),oj=t(),tj={message:({params:{discrError:w,tagName:b}})=>w===O9.DiscrError.Tag?`tag "${b}" must be string`:`value of tag "${b}" must be in oneOf`,params:({params:{discrError:w,tag:b,tagName:$}})=>Fw._`{error: ${w}, tag: ${$}, tagValue: ${b}}`},rj={keyword:"discriminator",type:"object",schemaType:"object",error:tj,code(w){let{gen:b,data:$,schema:Q,parentSchema:W,it:X}=w,{oneOf:J}=W;if(!X.opts.discriminator)throw Error("discriminator: requires discriminator option");let Y=Q.propertyName;if(typeof Y!="string")throw Error("discriminator: requires propertyName");if(Q.mapping)throw Error("discriminator: mapping is not supported");if(!J)throw Error("discriminator: requires oneOf keyword");let G=b.let("valid",!1),H=b.const("tag",Fw._`${$}${(0,Fw.getProperty)(Y)}`);b.if(Fw._`typeof ${H} == "string"`,()=>z(),()=>w.error(!1,{discrError:O9.DiscrError.Tag,tag:H,tagName:Y})),w.ok(G);function z(){let F=L();b.if(!1);for(let A in F)b.elseIf(Fw._`${H} === ${A}`),b.assign(G,B(F[A]));b.else(),w.error(!1,{discrError:O9.DiscrError.Mapping,tag:H,tagName:Y}),b.endIf()}function B(F){let A=b.name("valid"),j=w.subschema({keyword:"oneOf",schemaProp:F},A);return w.mergeEvaluated(j,Fw.Name),A}function L(){var F;let A={},j=P(W),q=!0;for(let u=0;u<J.length;u++){let _=J[u];if((_===null||_===void 0?void 0:_.$ref)&&!(0,oj.schemaHasRulesButRef)(_,X.self.RULES)){let l1=_.$ref;if(_=qH.resolveRef.call(X.self,X.schemaEnv.root,X.baseId,l1),_ instanceof qH.SchemaEnv)_=_.schema;if(_===void 0)throw new dj.default(X.opts.uriResolver,X.baseId,l1)}let S1=(F=_===null||_===void 0?void 0:_.properties)===null||F===void 0?void 0:F[Y];if(typeof S1!="object")throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${Y}"`);q=q&&(j||P(_)),v(S1,u)}if(!q)throw Error(`discriminator: "${Y}" must be required`);return A;function P({required:u}){return Array.isArray(u)&&u.includes(Y)}function v(u,_){if(u.const)S(u.const,_);else if(u.enum)for(let S1 of u.enum)S(S1,_);else throw Error(`discriminator: "properties/${Y}" must have "const" or "enum"`)}function S(u,_){if(typeof u!="string"||u in A)throw Error(`discriminator: "${Y}" values must be unique strings`);A[u]=_}}}};IH.default=rj});var NH=E((zS,ej)=>{ej.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 j9=E((R1,Z9)=>{Object.defineProperty(R1,"__esModule",{value:!0});R1.MissingRefError=R1.ValidationError=R1.CodeGen=R1.Name=R1.nil=R1.stringify=R1.str=R1._=R1.KeywordCxt=R1.Ajv=void 0;var aj=vG(),wM=ZH(),bM=EH(),TH=NH(),$M=["/properties"],s6="http://json-schema.org/draft-07/schema";class Vb extends aj.default{_addVocabularies(){if(super._addVocabularies(),wM.default.forEach((w)=>this.addVocabulary(w)),this.opts.discriminator)this.addKeyword(bM.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let w=this.opts.$data?this.$dataMetaSchema(TH,$M):TH;this.addMetaSchema(w,s6,!1),this.refs["http://json-schema.org/schema"]=s6}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(s6)?s6:void 0)}}R1.Ajv=Vb;Z9.exports=R1=Vb;Z9.exports.Ajv=Vb;Object.defineProperty(R1,"__esModule",{value:!0});R1.default=Vb;var QM=Hb();Object.defineProperty(R1,"KeywordCxt",{enumerable:!0,get:function(){return QM.KeywordCxt}});var Uw=m();Object.defineProperty(R1,"_",{enumerable:!0,get:function(){return Uw._}});Object.defineProperty(R1,"str",{enumerable:!0,get:function(){return Uw.str}});Object.defineProperty(R1,"stringify",{enumerable:!0,get:function(){return Uw.stringify}});Object.defineProperty(R1,"nil",{enumerable:!0,get:function(){return Uw.nil}});Object.defineProperty(R1,"Name",{enumerable:!0,get:function(){return Uw.Name}});Object.defineProperty(R1,"CodeGen",{enumerable:!0,get:function(){return Uw.CodeGen}});var WM=R6();Object.defineProperty(R1,"ValidationError",{enumerable:!0,get:function(){return WM.default}});var XM=zb();Object.defineProperty(R1,"MissingRefError",{enumerable:!0,get:function(){return XM.default}})});var fH=E((hH)=>{Object.defineProperty(hH,"__esModule",{value:!0});hH.formatNames=hH.fastFormats=hH.fullFormats=void 0;function Q0(w,b){return{validate:w,compare:b}}hH.fullFormats={date:Q0(CH,q9),time:Q0(V9(!0),I9),"date-time":Q0(RH(!0),_H),"iso-time":Q0(V9(),kH),"iso-date-time":Q0(RH(),xH),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:LM,"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:jM,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:FM,int32:{type:"number",validate:KM},int64:{type:"number",validate:OM},float:{type:"number",validate:vH},double:{type:"number",validate:vH},password:!0,binary:!0};hH.fastFormats={...hH.fullFormats,date:Q0(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,q9),time:Q0(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,I9),"date-time":Q0(/^\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,_H),"iso-time":Q0(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,kH),"iso-date-time":Q0(/^\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,xH),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};hH.formatNames=Object.keys(hH.fullFormats);function GM(w){return w%4===0&&(w%100!==0||w%400===0)}var HM=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,zM=[0,31,28,31,30,31,30,31,31,30,31,30,31];function CH(w){let b=HM.exec(w);if(!b)return!1;let $=+b[1],Q=+b[2],W=+b[3];return Q>=1&&Q<=12&&W>=1&&W<=(Q===2&&GM($)?29:zM[Q])}function q9(w,b){if(!(w&&b))return;if(w>b)return 1;if(w<b)return-1;return 0}var M9=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function V9(w){return function($){let Q=M9.exec($);if(!Q)return!1;let W=+Q[1],X=+Q[2],J=+Q[3],Y=Q[4],G=Q[5]==="-"?-1:1,H=+(Q[6]||0),z=+(Q[7]||0);if(H>23||z>59||w&&!Y)return!1;if(W<=23&&X<=59&&J<60)return!0;let B=X-z*G,L=W-H*G-(B<0?1:0);return(L===23||L===-1)&&(B===59||B===-1)&&J<61}}function I9(w,b){if(!(w&&b))return;let $=new Date("2020-01-01T"+w).valueOf(),Q=new Date("2020-01-01T"+b).valueOf();if(!($&&Q))return;return $-Q}function kH(w,b){if(!(w&&b))return;let $=M9.exec(w),Q=M9.exec(b);if(!($&&Q))return;if(w=$[1]+$[2]+$[3],b=Q[1]+Q[2]+Q[3],w>b)return 1;if(w<b)return-1;return 0}var P9=/t|\s/i;function RH(w){let b=V9(w);return function(Q){let W=Q.split(P9);return W.length===2&&CH(W[0])&&b(W[1])}}function _H(w,b){if(!(w&&b))return;let $=new Date(w).valueOf(),Q=new Date(b).valueOf();if(!($&&Q))return;return $-Q}function xH(w,b){if(!(w&&b))return;let[$,Q]=w.split(P9),[W,X]=b.split(P9),J=q9($,W);if(J===void 0)return;return J||I9(Q,X)}var DM=/\/|:/,BM=/^(?:[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 LM(w){return DM.test(w)&&BM.test(w)}var SH=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function FM(w){return SH.lastIndex=0,SH.test(w)}var UM=-2147483648,AM=2147483647;function KM(w){return Number.isInteger(w)&&w<=AM&&w>=UM}function OM(w){return Number.isInteger(w)}function vH(){return!0}var ZM=/[^\\]\\Z/;function jM(w){if(ZM.test(w))return!1;try{return new RegExp(w),!0}catch(b){return!1}}});var cH=E((uH)=>{Object.defineProperty(uH,"__esModule",{value:!0});uH.formatLimitDefinition=void 0;var VM=j9(),s1=m(),k0=s1.operators,e6={formatMaximum:{okStr:"<=",ok:k0.LTE,fail:k0.GT},formatMinimum:{okStr:">=",ok:k0.GTE,fail:k0.LT},formatExclusiveMaximum:{okStr:"<",ok:k0.LT,fail:k0.GTE},formatExclusiveMinimum:{okStr:">",ok:k0.GT,fail:k0.LTE}},PM={message:({keyword:w,schemaCode:b})=>s1.str`should be ${e6[w].okStr} ${b}`,params:({keyword:w,schemaCode:b})=>s1._`{comparison: ${e6[w].okStr}, limit: ${b}}`};uH.formatLimitDefinition={keyword:Object.keys(e6),type:"string",schemaType:"string",$data:!0,error:PM,code(w){let{gen:b,data:$,schemaCode:Q,keyword:W,it:X}=w,{opts:J,self:Y}=X;if(!J.validateFormats)return;let G=new VM.KeywordCxt(X,Y.RULES.all.format.definition,"format");if(G.$data)H();else z();function H(){let L=b.scopeValue("formats",{ref:Y.formats,code:J.code.formats}),F=b.const("fmt",s1._`${L}[${G.schemaCode}]`);w.fail$data((0,s1.or)(s1._`typeof ${F} != "object"`,s1._`${F} instanceof RegExp`,s1._`typeof ${F}.compare != "function"`,B(F)))}function z(){let L=G.schema,F=Y.formats[L];if(!F||F===!0)return;if(typeof F!="object"||F instanceof RegExp||typeof F.compare!="function")throw Error(`"${W}": format "${L}" does not define "compare" function`);let A=b.scopeValue("formats",{key:L,ref:F,code:J.code.formats?s1._`${J.code.formats}${(0,s1.getProperty)(L)}`:void 0});w.fail$data(B(A))}function B(L){return s1._`${L}.compare(${$}, ${Q}) ${e6[W].fail} 0`}},dependencies:["format"]};var qM=(w)=>{return w.addKeyword(uH.formatLimitDefinition),w};uH.default=qM});var iH=E((Pb,gH)=>{Object.defineProperty(Pb,"__esModule",{value:!0});var Aw=fH(),EM=cH(),T9=m(),mH=new T9.Name("fullFormats"),NM=new T9.Name("fastFormats"),R9=(w,b={keywords:!0})=>{if(Array.isArray(b))return lH(w,b,Aw.fullFormats,mH),w;let[$,Q]=b.mode==="fast"?[Aw.fastFormats,NM]:[Aw.fullFormats,mH],W=b.formats||Aw.formatNames;if(lH(w,W,$,Q),b.keywords)(0,EM.default)(w);return w};R9.get=(w,b="full")=>{let Q=(b==="fast"?Aw.fastFormats:Aw.fullFormats)[w];if(!Q)throw Error(`Unknown format "${w}"`);return Q};function lH(w,b,$,Q){var W,X;(W=(X=w.opts.code).formats)!==null&&W!==void 0||(X.formats=T9._`require("ajv-formats/dist/formats").${Q}`);for(let J of b)w.addFormat(J,$[J])}gH.exports=Pb=R9;Object.defineProperty(Pb,"__esModule",{value:!0});Pb.default=R9});import{AsyncLocalStorage as bz}from"node:async_hooks";class w0 extends Error{statusCode;rawDetails;code;context;constructor(w,b,$,Q,W){super(w);this.statusCode=b;this.rawDetails=$;this.code=Q;this.context=W;this.name="McpApiError"}}function e3(w){if(w instanceof w0)return{message:w.message,statusCode:w.statusCode,code:w.code,rawDetails:w.rawDetails,context:w.context};if(w instanceof Error)return{message:w.message};return{message:String(w)}}function a3(w){let b=w.match(/api key is missing required scopes?:\s*(.+)$/i);if(!b?.[1])return[];return[...new Set(b[1].match(/[a-z_]+:[a-z_]+/gi)??[])]}function wz(w){let b=e3(w),$=b.message.trim()||"Unknown error",Q=$.toLowerCase(),W=b.rawDetails?.trim()||$;if(b.context?.title||b.context?.description||b.context?.howToFix||b.context?.docsUrl)return{title:b.context.title??(b.statusCode===409?"Request conflict":"API request failed"),description:b.context.description??$,howToFix:b.context.howToFix??"Review the details below, adjust the tool input, and retry.",docsUrl:b.context.docsUrl??"https://docs.sequenzy.com/concepts/mcp",details:W};if(b.code==="MCP_AUTH_REQUIRED"||Q.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:W};if(b.statusCode===401||b.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:W};let X=a3($);if(X.length>0){let J=X.map((G)=>`\`${G}\``).join(", "),Y=X.every((G)=>G.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 ${X.length===1?"scope":"scopes"}: ${J}.`,howToFix:`Permissions can be widened on the key you are already using - no replacement key and no client restart. Call \`get_account\` to read \`apiKeyPermissions\`, then have the key owner open \`apiKeyPermissions.manageUrl\`, edit the key identified by \`apiKeyPermissions.activeKey\`, and enable ${J}. The URL opens Account → API Keys for a \`personal\` key and workspace Settings → API Keys for a \`company\` key. If \`get_account\` also requires \`account:read\`, open ${"https://sequenzy.com/dashboard"} directly and choose the matching API Keys page. When \`apiKeyPermissions.activeKey.type\` is \`company\` and the key holds \`api_keys:manage\`, the agent can instead call \`update_api_key\` with \`apiKeyId\` from \`apiKeyPermissions.activeKey.id\`. Personal keys cannot be changed through \`update_api_key\`. \`scopes\` and \`preset\` REPLACE the whole selection, so pass every scope in \`apiKeyPermissions.scopes\` plus ${J}, or a preset covering all of them (${Y}). Then retry the same tool call - the API reloads the key's permissions on a denied request, so the retry succeeds without reconnecting. Issuing a replacement key and swapping \`SEQUENZY_API_KEY\`, or reauthorizing a hosted OAuth connection with wider permissions, also works but is not required.`,docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:W}}if(b.statusCode===403||Q.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:W};if(Q.includes("no company available")||Q.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:W};if(b.statusCode===404||Q.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:W};if(Q.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:W};if(b.statusCode===409)return{title:"Request conflict",description:"Sequenzy rejected this request because the resource changed or an operation is already in progress.",howToFix:"Refresh the resource state, choose the lifecycle action allowed by its current status, and retry at most once.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:W};if(b.statusCode===429||Q.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:W};if(b.code==="NETWORK_ERROR"||Q.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:W};if(Q.includes("unknown tool")||Q.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:W};if(Q.includes("is required")||Q.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:W};if(b.statusCode&&b.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:W};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:W}}function s0(w){let b=wz(w);return[`Sequenzy MCP error: ${b.title}`,`Description: ${b.description}`,`How to fix: ${b.howToFix}`,`Docs: ${b.docsUrl}`,`Details: ${b.details}`].join(`
9
+ `)}var $z="https://api.sequenzy.com",Qz=new Set(["/api/v1/media/upload-bytes","/v1/media/upload-bytes"]),Rw=new bz,ZQ=!1;function dV(){ZQ=!0}function Cb(){return ZQ}var jQ=null;function h0(){let w=Rw.getStore();if(w)return w.selectedCompanyId??null;return jQ}function j4(w){let b=Rw.getStore();if(b){b.selectedCompanyId=w;return}jQ=w}function MQ(w,b){return Rw.run(w,b)}function VQ(){return Rw.getStore()?.apiUrl??process.env.SEQUENZY_API_URL??$z}function PQ(){return Rw.getStore()?.apiKey??process.env.SEQUENZY_API_KEY}function qQ(w,b){let $=PQ();if(!$)throw new w0("SEQUENZY_API_KEY environment variable is required",401,void 0,"MCP_AUTH_REQUIRED");let Q={"Content-Type":w,Authorization:`Bearer ${$}`},W=b??h0();if(W)Q["x-company-id"]=W;return Q}function oV(){if(PQ())return;console.error(s0(new w0("SEQUENZY_API_KEY environment variable is required",401,void 0,"MCP_AUTH_REQUIRED"))),process.exit(1)}function C1(w,b){let $=w[b];return typeof $==="string"&&$.trim()!==""?$.trim():void 0}function Wz(w){if(w===void 0)return;if(typeof w==="string")return w.trim()||void 0;return JSON.stringify(w)}function IQ(w){if(!w.trim())return{message:"Request failed"};try{let b=JSON.parse(w);if(typeof b==="string")return{message:b};let $=typeof b.error==="object"&&b.error!==null?b.error:void 0,Q=C1(b,"code")??($?C1($,"code"):void 0),W=(typeof b.error==="string"?b.error:void 0)??($?C1($,"message"):void 0)??C1(b,"message")??C1(b,"error")??w,X=C1(b,"howToFix")??C1(b,"resolution"),J={...C1(b,"title")?{title:C1(b,"title")}:{},...C1(b,"description")?{description:C1(b,"description")}:{},...X?{howToFix:X}:{},...C1(b,"docsUrl")?{docsUrl:C1(b,"docsUrl")}:{}},Y=Wz(b.details);if(Object.keys(J).length>0||Y)return{message:W,...Q?{code:Q}:{},...Y?{details:Y}:{},...Object.keys(J).length>0?{context:J}:{}};if(typeof b.error==="string")return{message:b.error,...Q?{code:Q}:{}};if($)return{message:W,...Q?{code:Q}:{}};return{message:W,...Q?{code:Q}:{}}}catch{return{message:w}}}async function D(w,b,$,Q){let W=qQ("application/json",Q),X;try{X=await fetch(`${VQ()}${b}`,{method:w,headers:W,body:$?JSON.stringify($):void 0})}catch(J){throw new w0(J instanceof Error?J.message:"Failed to reach Sequenzy API",0,void 0,"NETWORK_ERROR")}if(!X.ok){let J=await X.text(),Y=IQ(J);throw new w0(Y.message,X.status,Y.details??J,Y.code,Y.context)}return X.json()}async function EQ(w,b,$,Q){let W=new URL(VQ()).origin,X=new URL(w,`${W}/`);if(X.origin!==W){if(!Qz.has(X.pathname))throw new w0("The image upload URL did not point to the configured Sequenzy API.",500,void 0,"INVALID_UPLOAD_URL");X=new URL(`${X.pathname}${X.search}`,`${W}/`)}let J;try{J=await fetch(X,{method:"PUT",headers:qQ($,Q),body:b})}catch(Y){throw new w0(Y instanceof Error?Y.message:"Failed to upload image bytes",0,void 0,"NETWORK_ERROR")}if(!J.ok){let Y=await J.text(),G=IQ(Y);throw new w0(G.message,J.status,G.details??Y,G.code,G.context)}}var rV=Object.freeze({status:"aborted"});function O(w,b,$){function Q(Y,G){var H;Object.defineProperty(Y,"_zod",{value:Y._zod??{},enumerable:!1}),(H=Y._zod).traits??(H.traits=new Set),Y._zod.traits.add(w),b(Y,G);for(let z in J.prototype)if(!(z in Y))Object.defineProperty(Y,z,{value:J.prototype[z].bind(Y)});Y._zod.constr=J,Y._zod.def=G}let W=$?.Parent??Object;class X extends W{}Object.defineProperty(X,"name",{value:w});function J(Y){var G;let H=$?.Parent?new X:this;Q(H,Y),(G=H._zod).deferred??(G.deferred=[]);for(let z of H._zod.deferred)z();return H}return Object.defineProperty(J,"init",{value:Q}),Object.defineProperty(J,Symbol.hasInstance,{value:(Y)=>{if($?.Parent&&Y instanceof $.Parent)return!0;return Y?._zod?.traits?.has(w)}}),Object.defineProperty(J,"name",{value:w}),J}var sV=Symbol("zod_brand");class X0 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class Sw extends Error{constructor(w){super(`Encountered unidirectional transform during encode: ${w}`);this.name="ZodEncodeError"}}var kb={};function y1(w){if(w)Object.assign(kb,w);return kb}var o={};OQ(o,{unwrapMessage:()=>vw,uint8ArrayToHex:()=>Rz,uint8ArrayToBase64url:()=>Nz,uint8ArrayToBase64:()=>kQ,stringifyPrimitive:()=>yb,shallowClone:()=>TQ,safeExtend:()=>Mz,required:()=>qz,randomString:()=>Fz,propertyKeyTypes:()=>I4,promiseAllObject:()=>Lz,primitiveTypes:()=>RQ,prefixIssues:()=>Y0,pick:()=>Oz,partial:()=>Pz,optionalKeys:()=>E4,omit:()=>Zz,objectClone:()=>zz,numKeys:()=>Uz,nullish:()=>Cw,normalizeParams:()=>C,mergeDefs:()=>M0,merge:()=>Vz,jsonStringifyReplacer:()=>e0,joinValues:()=>_b,issue:()=>ww,isPlainObject:()=>V0,isObject:()=>y0,hexToUint8Array:()=>Tz,getSizableOrigin:()=>vQ,getParsedType:()=>Az,getLengthableOrigin:()=>_w,getEnumValues:()=>V4,getElementAtPath:()=>Bz,floatSafeRemainder:()=>P4,finalizeIssue:()=>n1,extend:()=>jz,escapeRegex:()=>J0,esc:()=>xb,defineLazy:()=>s,createTransparentProxy:()=>Kz,cloneDef:()=>Dz,clone:()=>i1,cleanRegex:()=>kw,cleanEnum:()=>Iz,captureStackTrace:()=>hb,cached:()=>a0,base64urlToUint8Array:()=>Ez,base64ToUint8Array:()=>CQ,assignProp:()=>j0,assertNotEqual:()=>Jz,assertNever:()=>Gz,assertIs:()=>Yz,assertEqual:()=>Xz,assert:()=>Hz,allowsEval:()=>q4,aborted:()=>P0,NUMBER_FORMAT_RANGES:()=>N4,Class:()=>_Q,BIGINT_FORMAT_RANGES:()=>SQ});function Xz(w){return w}function Jz(w){return w}function Yz(w){}function Gz(w){throw Error()}function Hz(w){}function V4(w){let b=Object.values(w).filter((Q)=>typeof Q==="number");return Object.entries(w).filter(([Q,W])=>b.indexOf(+Q)===-1).map(([Q,W])=>W)}function _b(w,b="|"){return w.map(($)=>yb($)).join(b)}function e0(w,b){if(typeof b==="bigint")return b.toString();return b}function a0(w){return{get value(){{let $=w();return Object.defineProperty(this,"value",{value:$}),$}throw Error("cached value already set")}}}function Cw(w){return w===null||w===void 0}function kw(w){let b=w.startsWith("^")?1:0,$=w.endsWith("$")?w.length-1:w.length;return w.slice(b,$)}function P4(w,b){let $=(w.toString().split(".")[1]||"").length,Q=b.toString(),W=(Q.split(".")[1]||"").length;if(W===0&&/\d?e-\d?/.test(Q)){let G=Q.match(/\d?e-(\d?)/);if(G?.[1])W=Number.parseInt(G[1])}let X=$>W?$:W,J=Number.parseInt(w.toFixed(X).replace(".","")),Y=Number.parseInt(b.toFixed(X).replace(".",""));return J%Y/10**X}var NQ=Symbol("evaluating");function s(w,b,$){let Q=void 0;Object.defineProperty(w,b,{get(){if(Q===NQ)return;if(Q===void 0)Q=NQ,Q=$();return Q},set(W){Object.defineProperty(w,b,{value:W})},configurable:!0})}function zz(w){return Object.create(Object.getPrototypeOf(w),Object.getOwnPropertyDescriptors(w))}function j0(w,b,$){Object.defineProperty(w,b,{value:$,writable:!0,enumerable:!0,configurable:!0})}function M0(...w){let b={};for(let $ of w){let Q=Object.getOwnPropertyDescriptors($);Object.assign(b,Q)}return Object.defineProperties({},b)}function Dz(w){return M0(w._zod.def)}function Bz(w,b){if(!b)return w;return b.reduce(($,Q)=>$?.[Q],w)}function Lz(w){let b=Object.keys(w),$=b.map((Q)=>w[Q]);return Promise.all($).then((Q)=>{let W={};for(let X=0;X<b.length;X++)W[b[X]]=Q[X];return W})}function Fz(w=10){let $="";for(let Q=0;Q<w;Q++)$+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return $}function xb(w){return JSON.stringify(w)}var hb="captureStackTrace"in Error?Error.captureStackTrace:(...w)=>{};function y0(w){return typeof w==="object"&&w!==null&&!Array.isArray(w)}var q4=a0(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(w){return!1}});function V0(w){if(y0(w)===!1)return!1;let b=w.constructor;if(b===void 0)return!0;let $=b.prototype;if(y0($)===!1)return!1;if(Object.prototype.hasOwnProperty.call($,"isPrototypeOf")===!1)return!1;return!0}function TQ(w){if(V0(w))return{...w};if(Array.isArray(w))return[...w];return w}function Uz(w){let b=0;for(let $ in w)if(Object.prototype.hasOwnProperty.call(w,$))b++;return b}var Az=(w)=>{let b=typeof w;switch(b){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(w)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(w))return"array";if(w===null)return"null";if(w.then&&typeof w.then==="function"&&w.catch&&typeof w.catch==="function")return"promise";if(typeof Map<"u"&&w instanceof Map)return"map";if(typeof Set<"u"&&w instanceof Set)return"set";if(typeof Date<"u"&&w instanceof Date)return"date";if(typeof File<"u"&&w instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${b}`)}},I4=new Set(["string","number","symbol"]),RQ=new Set(["string","number","bigint","boolean","symbol","undefined"]);function J0(w){return w.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function i1(w,b,$){let Q=new w._zod.constr(b??w._zod.def);if(!b||$?.parent)Q._zod.parent=w;return Q}function C(w){let b=w;if(!b)return{};if(typeof b==="string")return{error:()=>b};if(b?.message!==void 0){if(b?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");b.error=b.message}if(delete b.message,typeof b.error==="string")return{...b,error:()=>b.error};return b}function Kz(w){let b;return new Proxy({},{get($,Q,W){return b??(b=w()),Reflect.get(b,Q,W)},set($,Q,W,X){return b??(b=w()),Reflect.set(b,Q,W,X)},has($,Q){return b??(b=w()),Reflect.has(b,Q)},deleteProperty($,Q){return b??(b=w()),Reflect.deleteProperty(b,Q)},ownKeys($){return b??(b=w()),Reflect.ownKeys(b)},getOwnPropertyDescriptor($,Q){return b??(b=w()),Reflect.getOwnPropertyDescriptor(b,Q)},defineProperty($,Q,W){return b??(b=w()),Reflect.defineProperty(b,Q,W)}})}function yb(w){if(typeof w==="bigint")return w.toString()+"n";if(typeof w==="string")return`"${w}"`;return`${w}`}function E4(w){return Object.keys(w).filter((b)=>{return w[b]._zod.optin==="optional"&&w[b]._zod.optout==="optional"})}var N4={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]},SQ={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function Oz(w,b){let $=w._zod.def,Q=M0(w._zod.def,{get shape(){let W={};for(let X in b){if(!(X in $.shape))throw Error(`Unrecognized key: "${X}"`);if(!b[X])continue;W[X]=$.shape[X]}return j0(this,"shape",W),W},checks:[]});return i1(w,Q)}function Zz(w,b){let $=w._zod.def,Q=M0(w._zod.def,{get shape(){let W={...w._zod.def.shape};for(let X in b){if(!(X in $.shape))throw Error(`Unrecognized key: "${X}"`);if(!b[X])continue;delete W[X]}return j0(this,"shape",W),W},checks:[]});return i1(w,Q)}function jz(w,b){if(!V0(b))throw Error("Invalid input to extend: expected a plain object");let $=w._zod.def.checks;if($&&$.length>0)throw Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");let W=M0(w._zod.def,{get shape(){let X={...w._zod.def.shape,...b};return j0(this,"shape",X),X},checks:[]});return i1(w,W)}function Mz(w,b){if(!V0(b))throw Error("Invalid input to safeExtend: expected a plain object");let $={...w._zod.def,get shape(){let Q={...w._zod.def.shape,...b};return j0(this,"shape",Q),Q},checks:w._zod.def.checks};return i1(w,$)}function Vz(w,b){let $=M0(w._zod.def,{get shape(){let Q={...w._zod.def.shape,...b._zod.def.shape};return j0(this,"shape",Q),Q},get catchall(){return b._zod.def.catchall},checks:[]});return i1(w,$)}function Pz(w,b,$){let Q=M0(b._zod.def,{get shape(){let W=b._zod.def.shape,X={...W};if($)for(let J in $){if(!(J in W))throw Error(`Unrecognized key: "${J}"`);if(!$[J])continue;X[J]=w?new w({type:"optional",innerType:W[J]}):W[J]}else for(let J in W)X[J]=w?new w({type:"optional",innerType:W[J]}):W[J];return j0(this,"shape",X),X},checks:[]});return i1(b,Q)}function qz(w,b,$){let Q=M0(b._zod.def,{get shape(){let W=b._zod.def.shape,X={...W};if($)for(let J in $){if(!(J in X))throw Error(`Unrecognized key: "${J}"`);if(!$[J])continue;X[J]=new w({type:"nonoptional",innerType:W[J]})}else for(let J in W)X[J]=new w({type:"nonoptional",innerType:W[J]});return j0(this,"shape",X),X},checks:[]});return i1(b,Q)}function P0(w,b=0){if(w.aborted===!0)return!0;for(let $=b;$<w.issues.length;$++)if(w.issues[$]?.continue!==!0)return!0;return!1}function Y0(w,b){return b.map(($)=>{var Q;return(Q=$).path??(Q.path=[]),$.path.unshift(w),$})}function vw(w){return typeof w==="string"?w:w?.message}function n1(w,b,$){let Q={...w,path:w.path??[]};if(!w.message){let W=vw(w.inst?._zod.def?.error?.(w))??vw(b?.error?.(w))??vw($.customError?.(w))??vw($.localeError?.(w))??"Invalid input";Q.message=W}if(delete Q.inst,delete Q.continue,!b?.reportInput)delete Q.input;return Q}function vQ(w){if(w instanceof Set)return"set";if(w instanceof Map)return"map";if(w instanceof File)return"file";return"unknown"}function _w(w){if(Array.isArray(w))return"array";if(typeof w==="string")return"string";return"unknown"}function ww(...w){let[b,$,Q]=w;if(typeof b==="string")return{message:b,code:"custom",input:$,inst:Q};return{...b}}function Iz(w){return Object.entries(w).filter(([b,$])=>{return Number.isNaN(Number.parseInt(b,10))}).map((b)=>b[1])}function CQ(w){let b=atob(w),$=new Uint8Array(b.length);for(let Q=0;Q<b.length;Q++)$[Q]=b.charCodeAt(Q);return $}function kQ(w){let b="";for(let $=0;$<w.length;$++)b+=String.fromCharCode(w[$]);return btoa(b)}function Ez(w){let b=w.replace(/-/g,"+").replace(/_/g,"/"),$="=".repeat((4-b.length%4)%4);return CQ(b+$)}function Nz(w){return kQ(w).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Tz(w){let b=w.replace(/^0x/,"");if(b.length%2!==0)throw Error("Invalid hex string length");let $=new Uint8Array(b.length/2);for(let Q=0;Q<b.length;Q+=2)$[Q/2]=Number.parseInt(b.slice(Q,Q+2),16);return $}function Rz(w){return Array.from(w).map((b)=>b.toString(16).padStart(2,"0")).join("")}class _Q{constructor(...w){}}var xQ=(w,b)=>{w.name="$ZodError",Object.defineProperty(w,"_zod",{value:w._zod,enumerable:!1}),Object.defineProperty(w,"issues",{value:b,enumerable:!1}),w.message=JSON.stringify(b,e0,2),Object.defineProperty(w,"toString",{value:()=>w.message,enumerable:!1})},fb=O("$ZodError",xQ),T4=O("$ZodError",xQ,{Parent:Error});function hQ(w,b=($)=>$.message){let $={},Q=[];for(let W of w.issues)if(W.path.length>0)$[W.path[0]]=$[W.path[0]]||[],$[W.path[0]].push(b(W));else Q.push(b(W));return{formErrors:Q,fieldErrors:$}}function yQ(w,b=($)=>$.message){let $={_errors:[]},Q=(W)=>{for(let X of W.issues)if(X.code==="invalid_union"&&X.errors.length)X.errors.map((J)=>Q({issues:J}));else if(X.code==="invalid_key")Q({issues:X.issues});else if(X.code==="invalid_element")Q({issues:X.issues});else if(X.path.length===0)$._errors.push(b(X));else{let J=$,Y=0;while(Y<X.path.length){let G=X.path[Y];if(Y!==X.path.length-1)J[G]=J[G]||{_errors:[]};else J[G]=J[G]||{_errors:[]},J[G]._errors.push(b(X));J=J[G],Y++}}};return Q(w),$}var ub=(w)=>(b,$,Q,W)=>{let X=Q?Object.assign(Q,{async:!1}):{async:!1},J=b._zod.run({value:$,issues:[]},X);if(J instanceof Promise)throw new X0;if(J.issues.length){let Y=new(W?.Err??w)(J.issues.map((G)=>n1(G,X,y1())));throw hb(Y,W?.callee),Y}return J.value};var cb=(w)=>async(b,$,Q,W)=>{let X=Q?Object.assign(Q,{async:!0}):{async:!0},J=b._zod.run({value:$,issues:[]},X);if(J instanceof Promise)J=await J;if(J.issues.length){let Y=new(W?.Err??w)(J.issues.map((G)=>n1(G,X,y1())));throw hb(Y,W?.callee),Y}return J.value};var xw=(w)=>(b,$,Q)=>{let W=Q?{...Q,async:!1}:{async:!1},X=b._zod.run({value:$,issues:[]},W);if(X instanceof Promise)throw new X0;return X.issues.length?{success:!1,error:new(w??fb)(X.issues.map((J)=>n1(J,W,y1())))}:{success:!0,data:X.value}},hw=xw(T4),yw=(w)=>async(b,$,Q)=>{let W=Q?Object.assign(Q,{async:!0}):{async:!0},X=b._zod.run({value:$,issues:[]},W);if(X instanceof Promise)X=await X;return X.issues.length?{success:!1,error:new w(X.issues.map((J)=>n1(J,W,y1())))}:{success:!0,data:X.value}},mb=yw(T4),fQ=(w)=>(b,$,Q)=>{let W=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return ub(w)(b,$,W)};var uQ=(w)=>(b,$,Q)=>{return ub(w)(b,$,Q)};var cQ=(w)=>async(b,$,Q)=>{let W=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return cb(w)(b,$,W)};var mQ=(w)=>async(b,$,Q)=>{return cb(w)(b,$,Q)};var lQ=(w)=>(b,$,Q)=>{let W=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return xw(w)(b,$,W)};var gQ=(w)=>(b,$,Q)=>{return xw(w)(b,$,Q)};var iQ=(w)=>async(b,$,Q)=>{let W=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return yw(w)(b,$,W)};var nQ=(w)=>async(b,$,Q)=>{return yw(w)(b,$,Q)};var pQ=/^[cC][^\s-]{8,}$/,dQ=/^[0-9a-z]+$/,oQ=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,tQ=/^[0-9a-vA-V]{20}$/,rQ=/^[A-Za-z0-9]{27}$/,sQ=/^[a-zA-Z0-9_-]{21}$/,eQ=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var aQ=/^([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})$/,R4=(w)=>{if(!w)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}-${w}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)};var w8=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function b8(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}var $8=/^(?:(?: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])$/,Q8=/^(([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}|:))$/,W8=/^((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])$/,X8=/^(([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])$/,J8=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,S4=/^[A-Za-z0-9_-]*$/,Y8=/^(?=.{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 G8=/^\+(?:[0-9]){6,14}[0-9]$/,H8="(?:(?:\\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])))",z8=new RegExp(`^${H8}$`);function D8(w){return typeof w.precision==="number"?w.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":w.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{${w.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function B8(w){return new RegExp(`^${D8(w)}$`)}function L8(w){let b=D8({precision:w.precision}),$=["Z"];if(w.local)$.push("");if(w.offset)$.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let Q=`${b}(?:${$.join("|")})`;return new RegExp(`^${H8}T(?:${Q})$`)}var F8=(w)=>{let b=w?`[\\s\\S]{${w?.minimum??0},${w?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${b}$`)};var U8=/^-?\d+$/,A8=/^-?\d+(?:\.\d+)?/,K8=/^(?:true|false)$/i,O8=/^null$/i;var Z8=/^[^A-Z]*$/,j8=/^[^a-z]*$/;var U1=O("$ZodCheck",(w,b)=>{var $;w._zod??(w._zod={}),w._zod.def=b,($=w._zod).onattach??($.onattach=[])}),M8={number:"number",bigint:"bigint",object:"date"},v4=O("$ZodCheckLessThan",(w,b)=>{U1.init(w,b);let $=M8[typeof b.value];w._zod.onattach.push((Q)=>{let W=Q._zod.bag,X=(b.inclusive?W.maximum:W.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(b.value<X)if(b.inclusive)W.maximum=b.value;else W.exclusiveMaximum=b.value}),w._zod.check=(Q)=>{if(b.inclusive?Q.value<=b.value:Q.value<b.value)return;Q.issues.push({origin:$,code:"too_big",maximum:b.value,input:Q.value,inclusive:b.inclusive,inst:w,continue:!b.abort})}}),C4=O("$ZodCheckGreaterThan",(w,b)=>{U1.init(w,b);let $=M8[typeof b.value];w._zod.onattach.push((Q)=>{let W=Q._zod.bag,X=(b.inclusive?W.minimum:W.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(b.value>X)if(b.inclusive)W.minimum=b.value;else W.exclusiveMinimum=b.value}),w._zod.check=(Q)=>{if(b.inclusive?Q.value>=b.value:Q.value>b.value)return;Q.issues.push({origin:$,code:"too_small",minimum:b.value,input:Q.value,inclusive:b.inclusive,inst:w,continue:!b.abort})}}),V8=O("$ZodCheckMultipleOf",(w,b)=>{U1.init(w,b),w._zod.onattach.push(($)=>{var Q;(Q=$._zod.bag).multipleOf??(Q.multipleOf=b.value)}),w._zod.check=($)=>{if(typeof $.value!==typeof b.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof $.value==="bigint"?$.value%b.value===BigInt(0):P4($.value,b.value)===0)return;$.issues.push({origin:typeof $.value,code:"not_multiple_of",divisor:b.value,input:$.value,inst:w,continue:!b.abort})}}),P8=O("$ZodCheckNumberFormat",(w,b)=>{U1.init(w,b),b.format=b.format||"float64";let $=b.format?.includes("int"),Q=$?"int":"number",[W,X]=N4[b.format];w._zod.onattach.push((J)=>{let Y=J._zod.bag;if(Y.format=b.format,Y.minimum=W,Y.maximum=X,$)Y.pattern=U8}),w._zod.check=(J)=>{let Y=J.value;if($){if(!Number.isInteger(Y)){J.issues.push({expected:Q,format:b.format,code:"invalid_type",continue:!1,input:Y,inst:w});return}if(!Number.isSafeInteger(Y)){if(Y>0)J.issues.push({input:Y,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:w,origin:Q,continue:!b.abort});else J.issues.push({input:Y,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:w,origin:Q,continue:!b.abort});return}}if(Y<W)J.issues.push({origin:"number",input:Y,code:"too_small",minimum:W,inclusive:!0,inst:w,continue:!b.abort});if(Y>X)J.issues.push({origin:"number",input:Y,code:"too_big",maximum:X,inst:w})}});var q8=O("$ZodCheckMaxLength",(w,b)=>{var $;U1.init(w,b),($=w._zod.def).when??($.when=(Q)=>{let W=Q.value;return!Cw(W)&&W.length!==void 0}),w._zod.onattach.push((Q)=>{let W=Q._zod.bag.maximum??Number.POSITIVE_INFINITY;if(b.maximum<W)Q._zod.bag.maximum=b.maximum}),w._zod.check=(Q)=>{let W=Q.value;if(W.length<=b.maximum)return;let J=_w(W);Q.issues.push({origin:J,code:"too_big",maximum:b.maximum,inclusive:!0,input:W,inst:w,continue:!b.abort})}}),I8=O("$ZodCheckMinLength",(w,b)=>{var $;U1.init(w,b),($=w._zod.def).when??($.when=(Q)=>{let W=Q.value;return!Cw(W)&&W.length!==void 0}),w._zod.onattach.push((Q)=>{let W=Q._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(b.minimum>W)Q._zod.bag.minimum=b.minimum}),w._zod.check=(Q)=>{let W=Q.value;if(W.length>=b.minimum)return;let J=_w(W);Q.issues.push({origin:J,code:"too_small",minimum:b.minimum,inclusive:!0,input:W,inst:w,continue:!b.abort})}}),E8=O("$ZodCheckLengthEquals",(w,b)=>{var $;U1.init(w,b),($=w._zod.def).when??($.when=(Q)=>{let W=Q.value;return!Cw(W)&&W.length!==void 0}),w._zod.onattach.push((Q)=>{let W=Q._zod.bag;W.minimum=b.length,W.maximum=b.length,W.length=b.length}),w._zod.check=(Q)=>{let W=Q.value,X=W.length;if(X===b.length)return;let J=_w(W),Y=X>b.length;Q.issues.push({origin:J,...Y?{code:"too_big",maximum:b.length}:{code:"too_small",minimum:b.length},inclusive:!0,exact:!0,input:Q.value,inst:w,continue:!b.abort})}}),fw=O("$ZodCheckStringFormat",(w,b)=>{var $,Q;if(U1.init(w,b),w._zod.onattach.push((W)=>{let X=W._zod.bag;if(X.format=b.format,b.pattern)X.patterns??(X.patterns=new Set),X.patterns.add(b.pattern)}),b.pattern)($=w._zod).check??($.check=(W)=>{if(b.pattern.lastIndex=0,b.pattern.test(W.value))return;W.issues.push({origin:"string",code:"invalid_format",format:b.format,input:W.value,...b.pattern?{pattern:b.pattern.toString()}:{},inst:w,continue:!b.abort})});else(Q=w._zod).check??(Q.check=()=>{})}),N8=O("$ZodCheckRegex",(w,b)=>{fw.init(w,b),w._zod.check=($)=>{if(b.pattern.lastIndex=0,b.pattern.test($.value))return;$.issues.push({origin:"string",code:"invalid_format",format:"regex",input:$.value,pattern:b.pattern.toString(),inst:w,continue:!b.abort})}}),T8=O("$ZodCheckLowerCase",(w,b)=>{b.pattern??(b.pattern=Z8),fw.init(w,b)}),R8=O("$ZodCheckUpperCase",(w,b)=>{b.pattern??(b.pattern=j8),fw.init(w,b)}),S8=O("$ZodCheckIncludes",(w,b)=>{U1.init(w,b);let $=J0(b.includes),Q=new RegExp(typeof b.position==="number"?`^.{${b.position}}${$}`:$);b.pattern=Q,w._zod.onattach.push((W)=>{let X=W._zod.bag;X.patterns??(X.patterns=new Set),X.patterns.add(Q)}),w._zod.check=(W)=>{if(W.value.includes(b.includes,b.position))return;W.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:b.includes,input:W.value,inst:w,continue:!b.abort})}}),v8=O("$ZodCheckStartsWith",(w,b)=>{U1.init(w,b);let $=new RegExp(`^${J0(b.prefix)}.*`);b.pattern??(b.pattern=$),w._zod.onattach.push((Q)=>{let W=Q._zod.bag;W.patterns??(W.patterns=new Set),W.patterns.add($)}),w._zod.check=(Q)=>{if(Q.value.startsWith(b.prefix))return;Q.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:b.prefix,input:Q.value,inst:w,continue:!b.abort})}}),C8=O("$ZodCheckEndsWith",(w,b)=>{U1.init(w,b);let $=new RegExp(`.*${J0(b.suffix)}$`);b.pattern??(b.pattern=$),w._zod.onattach.push((Q)=>{let W=Q._zod.bag;W.patterns??(W.patterns=new Set),W.patterns.add($)}),w._zod.check=(Q)=>{if(Q.value.endsWith(b.suffix))return;Q.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:b.suffix,input:Q.value,inst:w,continue:!b.abort})}});var k8=O("$ZodCheckOverwrite",(w,b)=>{U1.init(w,b),w._zod.check=($)=>{$.value=b.tx($.value)}});class k4{constructor(w=[]){if(this.content=[],this.indent=0,this)this.args=w}indented(w){this.indent+=1,w(this),this.indent-=1}write(w){if(typeof w==="function"){w(this,{execution:"sync"}),w(this,{execution:"async"});return}let $=w.split(`
10
+ `).filter((X)=>X),Q=Math.min(...$.map((X)=>X.length-X.trimStart().length)),W=$.map((X)=>X.slice(Q)).map((X)=>" ".repeat(this.indent*2)+X);for(let X of W)this.content.push(X)}compile(){let w=Function,b=this?.args,Q=[...(this?.content??[""]).map((W)=>` ${W}`)];return new w(...b,Q.join(`
11
+ `))}}var x8={major:4,minor:1,patch:12};var w1=O("$ZodType",(w,b)=>{var $;w??(w={}),w._zod.def=b,w._zod.bag=w._zod.bag||{},w._zod.version=x8;let Q=[...w._zod.def.checks??[]];if(w._zod.traits.has("$ZodCheck"))Q.unshift(w);for(let W of Q)for(let X of W._zod.onattach)X(w);if(Q.length===0)($=w._zod).deferred??($.deferred=[]),w._zod.deferred?.push(()=>{w._zod.run=w._zod.parse});else{let W=(J,Y,G)=>{let H=P0(J),z;for(let B of Y){if(B._zod.def.when){if(!B._zod.def.when(J))continue}else if(H)continue;let L=J.issues.length,F=B._zod.check(J);if(F instanceof Promise&&G?.async===!1)throw new X0;if(z||F instanceof Promise)z=(z??Promise.resolve()).then(async()=>{if(await F,J.issues.length===L)return;if(!H)H=P0(J,L)});else{if(J.issues.length===L)continue;if(!H)H=P0(J,L)}}if(z)return z.then(()=>{return J});return J},X=(J,Y,G)=>{if(P0(J))return J.aborted=!0,J;let H=W(Y,Q,G);if(H instanceof Promise){if(G.async===!1)throw new X0;return H.then((z)=>w._zod.parse(z,G))}return w._zod.parse(H,G)};w._zod.run=(J,Y)=>{if(Y.skipChecks)return w._zod.parse(J,Y);if(Y.direction==="backward"){let H=w._zod.parse({value:J.value,issues:[]},{...Y,skipChecks:!0});if(H instanceof Promise)return H.then((z)=>{return X(z,J,Y)});return X(H,J,Y)}let G=w._zod.parse(J,Y);if(G instanceof Promise){if(Y.async===!1)throw new X0;return G.then((H)=>W(H,Q,Y))}return W(G,Q,Y)}}w["~standard"]={validate:(W)=>{try{let X=hw(w,W);return X.success?{value:X.data}:{issues:X.error?.issues}}catch(X){return mb(w,W).then((J)=>J.success?{value:J.data}:{issues:J.error?.issues})}},vendor:"zod",version:1}}),nb=O("$ZodString",(w,b)=>{w1.init(w,b),w._zod.pattern=[...w?._zod.bag?.patterns??[]].pop()??F8(w._zod.bag),w._zod.parse=($,Q)=>{if(b.coerce)try{$.value=String($.value)}catch(W){}if(typeof $.value==="string")return $;return $.issues.push({expected:"string",code:"invalid_type",input:$.value,inst:w}),$}}),b1=O("$ZodStringFormat",(w,b)=>{fw.init(w,b),nb.init(w,b)}),i8=O("$ZodGUID",(w,b)=>{b.pattern??(b.pattern=aQ),b1.init(w,b)}),n8=O("$ZodUUID",(w,b)=>{if(b.version){let Q={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[b.version];if(Q===void 0)throw Error(`Invalid UUID version: "${b.version}"`);b.pattern??(b.pattern=R4(Q))}else b.pattern??(b.pattern=R4());b1.init(w,b)}),p8=O("$ZodEmail",(w,b)=>{b.pattern??(b.pattern=w8),b1.init(w,b)}),d8=O("$ZodURL",(w,b)=>{b1.init(w,b),w._zod.check=($)=>{try{let Q=$.value.trim(),W=new URL(Q);if(b.hostname){if(b.hostname.lastIndex=0,!b.hostname.test(W.hostname))$.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:Y8.source,input:$.value,inst:w,continue:!b.abort})}if(b.protocol){if(b.protocol.lastIndex=0,!b.protocol.test(W.protocol.endsWith(":")?W.protocol.slice(0,-1):W.protocol))$.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:b.protocol.source,input:$.value,inst:w,continue:!b.abort})}if(b.normalize)$.value=W.href;else $.value=Q;return}catch(Q){$.issues.push({code:"invalid_format",format:"url",input:$.value,inst:w,continue:!b.abort})}}}),o8=O("$ZodEmoji",(w,b)=>{b.pattern??(b.pattern=b8()),b1.init(w,b)}),t8=O("$ZodNanoID",(w,b)=>{b.pattern??(b.pattern=sQ),b1.init(w,b)}),r8=O("$ZodCUID",(w,b)=>{b.pattern??(b.pattern=pQ),b1.init(w,b)}),s8=O("$ZodCUID2",(w,b)=>{b.pattern??(b.pattern=dQ),b1.init(w,b)}),e8=O("$ZodULID",(w,b)=>{b.pattern??(b.pattern=oQ),b1.init(w,b)}),a8=O("$ZodXID",(w,b)=>{b.pattern??(b.pattern=tQ),b1.init(w,b)}),wW=O("$ZodKSUID",(w,b)=>{b.pattern??(b.pattern=rQ),b1.init(w,b)}),bW=O("$ZodISODateTime",(w,b)=>{b.pattern??(b.pattern=L8(b)),b1.init(w,b)}),$W=O("$ZodISODate",(w,b)=>{b.pattern??(b.pattern=z8),b1.init(w,b)}),QW=O("$ZodISOTime",(w,b)=>{b.pattern??(b.pattern=B8(b)),b1.init(w,b)}),WW=O("$ZodISODuration",(w,b)=>{b.pattern??(b.pattern=eQ),b1.init(w,b)}),XW=O("$ZodIPv4",(w,b)=>{b.pattern??(b.pattern=$8),b1.init(w,b),w._zod.onattach.push(($)=>{let Q=$._zod.bag;Q.format="ipv4"})}),JW=O("$ZodIPv6",(w,b)=>{b.pattern??(b.pattern=Q8),b1.init(w,b),w._zod.onattach.push(($)=>{let Q=$._zod.bag;Q.format="ipv6"}),w._zod.check=($)=>{try{new URL(`http://[${$.value}]`)}catch{$.issues.push({code:"invalid_format",format:"ipv6",input:$.value,inst:w,continue:!b.abort})}}}),YW=O("$ZodCIDRv4",(w,b)=>{b.pattern??(b.pattern=W8),b1.init(w,b)}),GW=O("$ZodCIDRv6",(w,b)=>{b.pattern??(b.pattern=X8),b1.init(w,b),w._zod.check=($)=>{let Q=$.value.split("/");try{if(Q.length!==2)throw Error();let[W,X]=Q;if(!X)throw Error();let J=Number(X);if(`${J}`!==X)throw Error();if(J<0||J>128)throw Error();new URL(`http://[${W}]`)}catch{$.issues.push({code:"invalid_format",format:"cidrv6",input:$.value,inst:w,continue:!b.abort})}}});function HW(w){if(w==="")return!0;if(w.length%4!==0)return!1;try{return atob(w),!0}catch{return!1}}var zW=O("$ZodBase64",(w,b)=>{b.pattern??(b.pattern=J8),b1.init(w,b),w._zod.onattach.push(($)=>{$._zod.bag.contentEncoding="base64"}),w._zod.check=($)=>{if(HW($.value))return;$.issues.push({code:"invalid_format",format:"base64",input:$.value,inst:w,continue:!b.abort})}});function kz(w){if(!S4.test(w))return!1;let b=w.replace(/[-_]/g,(Q)=>Q==="-"?"+":"/"),$=b.padEnd(Math.ceil(b.length/4)*4,"=");return HW($)}var DW=O("$ZodBase64URL",(w,b)=>{b.pattern??(b.pattern=S4),b1.init(w,b),w._zod.onattach.push(($)=>{$._zod.bag.contentEncoding="base64url"}),w._zod.check=($)=>{if(kz($.value))return;$.issues.push({code:"invalid_format",format:"base64url",input:$.value,inst:w,continue:!b.abort})}}),BW=O("$ZodE164",(w,b)=>{b.pattern??(b.pattern=G8),b1.init(w,b)});function _z(w,b=null){try{let $=w.split(".");if($.length!==3)return!1;let[Q]=$;if(!Q)return!1;let W=JSON.parse(atob(Q));if("typ"in W&&W?.typ!=="JWT")return!1;if(!W.alg)return!1;if(b&&(!("alg"in W)||W.alg!==b))return!1;return!0}catch{return!1}}var LW=O("$ZodJWT",(w,b)=>{b1.init(w,b),w._zod.check=($)=>{if(_z($.value,b.alg))return;$.issues.push({code:"invalid_format",format:"jwt",input:$.value,inst:w,continue:!b.abort})}});var x4=O("$ZodNumber",(w,b)=>{w1.init(w,b),w._zod.pattern=w._zod.bag.pattern??A8,w._zod.parse=($,Q)=>{if(b.coerce)try{$.value=Number($.value)}catch(J){}let W=$.value;if(typeof W==="number"&&!Number.isNaN(W)&&Number.isFinite(W))return $;let X=typeof W==="number"?Number.isNaN(W)?"NaN":!Number.isFinite(W)?"Infinity":void 0:void 0;return $.issues.push({expected:"number",code:"invalid_type",input:W,inst:w,...X?{received:X}:{}}),$}}),FW=O("$ZodNumber",(w,b)=>{P8.init(w,b),x4.init(w,b)}),UW=O("$ZodBoolean",(w,b)=>{w1.init(w,b),w._zod.pattern=K8,w._zod.parse=($,Q)=>{if(b.coerce)try{$.value=Boolean($.value)}catch(X){}let W=$.value;if(typeof W==="boolean")return $;return $.issues.push({expected:"boolean",code:"invalid_type",input:W,inst:w}),$}});var AW=O("$ZodNull",(w,b)=>{w1.init(w,b),w._zod.pattern=O8,w._zod.values=new Set([null]),w._zod.parse=($,Q)=>{let W=$.value;if(W===null)return $;return $.issues.push({expected:"null",code:"invalid_type",input:W,inst:w}),$}});var KW=O("$ZodUnknown",(w,b)=>{w1.init(w,b),w._zod.parse=($)=>$}),OW=O("$ZodNever",(w,b)=>{w1.init(w,b),w._zod.parse=($,Q)=>{return $.issues.push({expected:"never",code:"invalid_type",input:$.value,inst:w}),$}});function h8(w,b,$){if(w.issues.length)b.issues.push(...Y0($,w.issues));b.value[$]=w.value}var ZW=O("$ZodArray",(w,b)=>{w1.init(w,b),w._zod.parse=($,Q)=>{let W=$.value;if(!Array.isArray(W))return $.issues.push({expected:"array",code:"invalid_type",input:W,inst:w}),$;$.value=Array(W.length);let X=[];for(let J=0;J<W.length;J++){let Y=W[J],G=b.element._zod.run({value:Y,issues:[]},Q);if(G instanceof Promise)X.push(G.then((H)=>h8(H,$,J)));else h8(G,$,J)}if(X.length)return Promise.all(X).then(()=>$);return $}});function ib(w,b,$,Q){if(w.issues.length)b.issues.push(...Y0($,w.issues));if(w.value===void 0){if($ in Q)b.value[$]=void 0}else b.value[$]=w.value}function jW(w){let b=Object.keys(w.shape);for(let Q of b)if(!w.shape?.[Q]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${Q}": expected a Zod schema`);let $=E4(w.shape);return{...w,keys:b,keySet:new Set(b),numKeys:b.length,optionalKeys:new Set($)}}function MW(w,b,$,Q,W,X){let J=[],Y=W.keySet,G=W.catchall._zod,H=G.def.type;for(let z of Object.keys(b)){if(Y.has(z))continue;if(H==="never"){J.push(z);continue}let B=G.run({value:b[z],issues:[]},Q);if(B instanceof Promise)w.push(B.then((L)=>ib(L,$,z,b)));else ib(B,$,z,b)}if(J.length)$.issues.push({code:"unrecognized_keys",keys:J,input:b,inst:X});if(!w.length)return $;return Promise.all(w).then(()=>{return $})}var xz=O("$ZodObject",(w,b)=>{if(w1.init(w,b),!Object.getOwnPropertyDescriptor(b,"shape")?.get){let Y=b.shape;Object.defineProperty(b,"shape",{get:()=>{let G={...Y};return Object.defineProperty(b,"shape",{value:G}),G}})}let Q=a0(()=>jW(b));s(w._zod,"propValues",()=>{let Y=b.shape,G={};for(let H in Y){let z=Y[H]._zod;if(z.values){G[H]??(G[H]=new Set);for(let B of z.values)G[H].add(B)}}return G});let W=y0,X=b.catchall,J;w._zod.parse=(Y,G)=>{J??(J=Q.value);let H=Y.value;if(!W(H))return Y.issues.push({expected:"object",code:"invalid_type",input:H,inst:w}),Y;Y.value={};let z=[],B=J.shape;for(let L of J.keys){let A=B[L]._zod.run({value:H[L],issues:[]},G);if(A instanceof Promise)z.push(A.then((j)=>ib(j,Y,L,H)));else ib(A,Y,L,H)}if(!X)return z.length?Promise.all(z).then(()=>Y):Y;return MW(z,H,Y,G,Q.value,w)}}),VW=O("$ZodObjectJIT",(w,b)=>{xz.init(w,b);let $=w._zod.parse,Q=a0(()=>jW(b)),W=(L)=>{let F=new k4(["shape","payload","ctx"]),A=Q.value,j=(S)=>{let u=xb(S);return`shape[${u}]._zod.run({ value: input[${u}], issues: [] }, ctx)`};F.write("const input = payload.value;");let q=Object.create(null),P=0;for(let S of A.keys)q[S]=`key_${P++}`;F.write("const newResult = {};");for(let S of A.keys){let u=q[S],_=xb(S);F.write(`const ${u} = ${j(S)};`),F.write(`
12
+ if (${u}.issues.length) {
13
+ payload.issues = payload.issues.concat(${u}.issues.map(iss => ({
14
14
  ...iss,
15
15
  path: iss.path ? [${_}, ...iss.path] : [${_}]
16
16
  })));
17
17
  }
18
18
 
19
19
 
20
- if (${l}.value === undefined) {
20
+ if (${u}.value === undefined) {
21
21
  if (${_} in input) {
22
22
  newResult[${_}] = undefined;
23
23
  }
24
24
  } else {
25
- newResult[${_}] = ${l}.value;
25
+ newResult[${_}] = ${u}.value;
26
26
  }
27
27
 
28
- `)}L.write("payload.value = newResult;"),L.write("return payload;");let k=L.compile();return(S,l)=>k(A,S,l)},X,J=_1,G=!Tb.jitless,H=G&&Z4.value,z=b.catchall,D;w._zod.parse=(A,L)=>{D??(D=W.value);let F=A.value;if(!J(F))return A.issues.push({expected:"object",code:"invalid_type",input:F,inst:w}),A;if(G&&H&&L?.async===!1&&L.jitless!==!0){if(!X)X=Q(b.shape);if(A=X(A,L),!z)return A;return L8([],F,A,L,D,w)}return $(A,L)}});function SQ(w,b,$,W){for(let X of w)if(X.issues.length===0)return b.value=X.value,b;let Q=w.filter((X)=>!M1(X));if(Q.length===1)return b.value=Q[0].value,Q[0];return b.issues.push({code:"invalid_union",input:b.value,inst:$,errors:w.map((X)=>X.issues.map((J)=>mw(J,W,xw())))}),b}var v4=O("$ZodUnion",(w,b)=>{ww.init(w,b),s(w._zod,"optin",()=>b.options.some((Q)=>Q._zod.optin==="optional")?"optional":void 0),s(w._zod,"optout",()=>b.options.some((Q)=>Q._zod.optout==="optional")?"optional":void 0),s(w._zod,"values",()=>{if(b.options.every((Q)=>Q._zod.values))return new Set(b.options.flatMap((Q)=>Array.from(Q._zod.values)));return}),s(w._zod,"pattern",()=>{if(b.options.every((Q)=>Q._zod.pattern)){let Q=b.options.map((X)=>X._zod.pattern);return new RegExp(`^(${Q.map((X)=>T0(X.source)).join("|")})$`)}return});let $=b.options.length===1,W=b.options[0]._zod.run;w._zod.parse=(Q,X)=>{if($)return W(Q,X);let J=!1,G=[];for(let Y of b.options){let H=Y._zod.run({value:Q.value,issues:[]},X);if(H instanceof Promise)G.push(H),J=!0;else{if(H.issues.length===0)return H;G.push(H)}}if(!J)return SQ(G,Q,w,X);return Promise.all(G).then((Y)=>{return SQ(Y,Q,w,X)})}}),F8=O("$ZodDiscriminatedUnion",(w,b)=>{v4.init(w,b);let $=w._zod.parse;s(w._zod,"propValues",()=>{let Q={};for(let X of b.options){let J=X._zod.propValues;if(!J||Object.keys(J).length===0)throw Error(`Invalid discriminated union option at index "${b.options.indexOf(X)}"`);for(let[G,Y]of Object.entries(J)){if(!Q[G])Q[G]=new Set;for(let H of Y)Q[G].add(H)}}return Q});let W=t1(()=>{let Q=b.options,X=new Map;for(let J of Q){let G=J._zod.propValues?.[b.discriminator];if(!G||G.size===0)throw Error(`Invalid discriminated union option at index "${b.options.indexOf(J)}"`);for(let Y of G){if(X.has(Y))throw Error(`Duplicate discriminator value "${String(Y)}"`);X.set(Y,J)}}return X});w._zod.parse=(Q,X)=>{let J=Q.value;if(!_1(J))return Q.issues.push({code:"invalid_type",expected:"object",input:J,inst:w}),Q;let G=W.value.get(J?.[b.discriminator]);if(G)return G._zod.run(Q,X);if(b.unionFallback)return $(Q,X);return Q.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:b.discriminator,input:J,path:[b.discriminator],inst:w}),Q}}),K8=O("$ZodIntersection",(w,b)=>{ww.init(w,b),w._zod.parse=($,W)=>{let Q=$.value,X=b.left._zod.run({value:Q,issues:[]},W),J=b.right._zod.run({value:Q,issues:[]},W);if(X instanceof Promise||J instanceof Promise)return Promise.all([X,J]).then(([Y,H])=>{return vQ($,Y,H)});return vQ($,X,J)}});function R4(w,b){if(w===b)return{valid:!0,data:w};if(w instanceof Date&&b instanceof Date&&+w===+b)return{valid:!0,data:w};if(Z1(w)&&Z1(b)){let $=Object.keys(b),W=Object.keys(w).filter((X)=>$.indexOf(X)!==-1),Q={...w,...b};for(let X of W){let J=R4(w[X],b[X]);if(!J.valid)return{valid:!1,mergeErrorPath:[X,...J.mergeErrorPath]};Q[X]=J.data}return{valid:!0,data:Q}}if(Array.isArray(w)&&Array.isArray(b)){if(w.length!==b.length)return{valid:!1,mergeErrorPath:[]};let $=[];for(let W=0;W<w.length;W++){let Q=w[W],X=b[W],J=R4(Q,X);if(!J.valid)return{valid:!1,mergeErrorPath:[W,...J.mergeErrorPath]};$.push(J.data)}return{valid:!0,data:$}}return{valid:!1,mergeErrorPath:[]}}function vQ(w,b,$){if(b.issues.length)w.issues.push(...b.issues);if($.issues.length)w.issues.push(...$.issues);if(M1(w))return w;let W=R4(b.value,$.value);if(!W.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(W.mergeErrorPath)}`);return w.value=W.data,w}var O8=O("$ZodRecord",(w,b)=>{ww.init(w,b),w._zod.parse=($,W)=>{let Q=$.value;if(!Z1(Q))return $.issues.push({expected:"record",code:"invalid_type",input:Q,inst:w}),$;let X=[];if(b.keyType._zod.values){let J=b.keyType._zod.values;$.value={};for(let Y of J)if(typeof Y==="string"||typeof Y==="number"||typeof Y==="symbol"){let H=b.valueType._zod.run({value:Q[Y],issues:[]},W);if(H instanceof Promise)X.push(H.then((z)=>{if(z.issues.length)$.issues.push(...X1(Y,z.issues));$.value[Y]=z.value}));else{if(H.issues.length)$.issues.push(...X1(Y,H.issues));$.value[Y]=H.value}}let G;for(let Y in Q)if(!J.has(Y))G=G??[],G.push(Y);if(G&&G.length>0)$.issues.push({code:"unrecognized_keys",input:Q,inst:w,keys:G})}else{$.value={};for(let J of Reflect.ownKeys(Q)){if(J==="__proto__")continue;let G=b.keyType._zod.run({value:J,issues:[]},W);if(G instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(G.issues.length){$.issues.push({code:"invalid_key",origin:"record",issues:G.issues.map((H)=>mw(H,W,xw())),input:J,path:[J],inst:w}),$.value[G.value]=G.value;continue}let Y=b.valueType._zod.run({value:Q[J],issues:[]},W);if(Y instanceof Promise)X.push(Y.then((H)=>{if(H.issues.length)$.issues.push(...X1(J,H.issues));$.value[G.value]=H.value}));else{if(Y.issues.length)$.issues.push(...X1(J,Y.issues));$.value[G.value]=Y.value}}}if(X.length)return Promise.all(X).then(()=>$);return $}});var Z8=O("$ZodEnum",(w,b)=>{ww.init(w,b);let $=K4(b.entries),W=new Set($);w._zod.values=W,w._zod.pattern=new RegExp(`^(${$.filter((Q)=>M4.has(typeof Q)).map((Q)=>typeof Q==="string"?Q1(Q):Q.toString()).join("|")})$`),w._zod.parse=(Q,X)=>{let J=Q.value;if(W.has(J))return Q;return Q.issues.push({code:"invalid_value",values:$,input:J,inst:w}),Q}}),M8=O("$ZodLiteral",(w,b)=>{if(ww.init(w,b),b.values.length===0)throw Error("Cannot create literal schema with no valid values");w._zod.values=new Set(b.values),w._zod.pattern=new RegExp(`^(${b.values.map(($)=>typeof $==="string"?Q1($):$?Q1($.toString()):String($)).join("|")})$`),w._zod.parse=($,W)=>{let Q=$.value;if(w._zod.values.has(Q))return $;return $.issues.push({code:"invalid_value",values:b.values,input:Q,inst:w}),$}});var V8=O("$ZodTransform",(w,b)=>{ww.init(w,b),w._zod.parse=($,W)=>{if(W.direction==="backward")throw new I0(w.constructor.name);let Q=b.transform($.value,$);if(W.async)return(Q instanceof Promise?Q:Promise.resolve(Q)).then((J)=>{return $.value=J,$});if(Q instanceof Promise)throw new W1;return $.value=Q,$}});function CQ(w,b){if(w.issues.length&&b===void 0)return{issues:[],value:void 0};return w}var j8=O("$ZodOptional",(w,b)=>{ww.init(w,b),w._zod.optin="optional",w._zod.optout="optional",s(w._zod,"values",()=>{return b.innerType._zod.values?new Set([...b.innerType._zod.values,void 0]):void 0}),s(w._zod,"pattern",()=>{let $=b.innerType._zod.pattern;return $?new RegExp(`^(${T0($.source)})?$`):void 0}),w._zod.parse=($,W)=>{if(b.innerType._zod.optin==="optional"){let Q=b.innerType._zod.run($,W);if(Q instanceof Promise)return Q.then((X)=>CQ(X,$.value));return CQ(Q,$.value)}if($.value===void 0)return $;return b.innerType._zod.run($,W)}}),q8=O("$ZodNullable",(w,b)=>{ww.init(w,b),s(w._zod,"optin",()=>b.innerType._zod.optin),s(w._zod,"optout",()=>b.innerType._zod.optout),s(w._zod,"pattern",()=>{let $=b.innerType._zod.pattern;return $?new RegExp(`^(${T0($.source)}|null)$`):void 0}),s(w._zod,"values",()=>{return b.innerType._zod.values?new Set([...b.innerType._zod.values,null]):void 0}),w._zod.parse=($,W)=>{if($.value===null)return $;return b.innerType._zod.run($,W)}}),P8=O("$ZodDefault",(w,b)=>{ww.init(w,b),w._zod.optin="optional",s(w._zod,"values",()=>b.innerType._zod.values),w._zod.parse=($,W)=>{if(W.direction==="backward")return b.innerType._zod.run($,W);if($.value===void 0)return $.value=b.defaultValue,$;let Q=b.innerType._zod.run($,W);if(Q instanceof Promise)return Q.then((X)=>kQ(X,b));return kQ(Q,b)}});function kQ(w,b){if(w.value===void 0)w.value=b.defaultValue;return w}var I8=O("$ZodPrefault",(w,b)=>{ww.init(w,b),w._zod.optin="optional",s(w._zod,"values",()=>b.innerType._zod.values),w._zod.parse=($,W)=>{if(W.direction==="backward")return b.innerType._zod.run($,W);if($.value===void 0)$.value=b.defaultValue;return b.innerType._zod.run($,W)}}),N8=O("$ZodNonOptional",(w,b)=>{ww.init(w,b),s(w._zod,"values",()=>{let $=b.innerType._zod.values;return $?new Set([...$].filter((W)=>W!==void 0)):void 0}),w._zod.parse=($,W)=>{let Q=b.innerType._zod.run($,W);if(Q instanceof Promise)return Q.then((X)=>_Q(X,w));return _Q(Q,w)}});function _Q(w,b){if(!w.issues.length&&w.value===void 0)w.issues.push({code:"invalid_type",expected:"nonoptional",input:w.value,inst:b});return w}var E8=O("$ZodCatch",(w,b)=>{ww.init(w,b),s(w._zod,"optin",()=>b.innerType._zod.optin),s(w._zod,"optout",()=>b.innerType._zod.optout),s(w._zod,"values",()=>b.innerType._zod.values),w._zod.parse=($,W)=>{if(W.direction==="backward")return b.innerType._zod.run($,W);let Q=b.innerType._zod.run($,W);if(Q instanceof Promise)return Q.then((X)=>{if($.value=X.value,X.issues.length)$.value=b.catchValue({...$,error:{issues:X.issues.map((J)=>mw(J,W,xw()))},input:$.value}),$.issues=[];return $});if($.value=Q.value,Q.issues.length)$.value=b.catchValue({...$,error:{issues:Q.issues.map((X)=>mw(X,W,xw()))},input:$.value}),$.issues=[];return $}});var T8=O("$ZodPipe",(w,b)=>{ww.init(w,b),s(w._zod,"values",()=>b.in._zod.values),s(w._zod,"optin",()=>b.in._zod.optin),s(w._zod,"optout",()=>b.out._zod.optout),s(w._zod,"propValues",()=>b.in._zod.propValues),w._zod.parse=($,W)=>{if(W.direction==="backward"){let X=b.out._zod.run($,W);if(X instanceof Promise)return X.then((J)=>fb(J,b.in,W));return fb(X,b.in,W)}let Q=b.in._zod.run($,W);if(Q instanceof Promise)return Q.then((X)=>fb(X,b.out,W));return fb(Q,b.out,W)}});function fb(w,b,$){if(w.issues.length)return w.aborted=!0,w;return b._zod.run({value:w.value,issues:w.issues},$)}var R8=O("$ZodReadonly",(w,b)=>{ww.init(w,b),s(w._zod,"propValues",()=>b.innerType._zod.propValues),s(w._zod,"values",()=>b.innerType._zod.values),s(w._zod,"optin",()=>b.innerType._zod.optin),s(w._zod,"optout",()=>b.innerType._zod.optout),w._zod.parse=($,W)=>{if(W.direction==="backward")return b.innerType._zod.run($,W);let Q=b.innerType._zod.run($,W);if(Q instanceof Promise)return Q.then(xQ);return xQ(Q)}});function xQ(w){return w.value=Object.freeze(w.value),w}var S8=O("$ZodCustom",(w,b)=>{Uw.init(w,b),ww.init(w,b),w._zod.parse=($,W)=>{return $},w._zod.check=($)=>{let W=$.value,Q=b.fn(W);if(Q instanceof Promise)return Q.then((X)=>hQ(X,$,W,w));hQ(Q,$,W,w);return}});function hQ(w,b,$,W){if(!w){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;b.issues.push(r1(Q))}}var N3=(w)=>{let b=typeof w;switch(b){case"number":return Number.isNaN(w)?"NaN":"number";case"object":{if(Array.isArray(w))return"array";if(w===null)return"null";if(Object.getPrototypeOf(w)!==Object.prototype&&w.constructor)return w.constructor.name}}return b},E3=()=>{let w={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 b(W){return w[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 ${N3(W.input)}`;case"invalid_value":if(W.values.length===1)return`Invalid input: expected ${Cb(W.values[0])}`;return`Invalid option: expected one of ${Rb(W.values,"|")}`;case"too_big":{let Q=W.inclusive?"<=":"<",X=b(W.origin);if(X)return`Too big: expected ${W.origin??"value"} to have ${Q}${W.maximum.toString()} ${X.unit??"elements"}`;return`Too big: expected ${W.origin??"value"} to be ${Q}${W.maximum.toString()}`}case"too_small":{let Q=W.inclusive?">=":">",X=b(W.origin);if(X)return`Too small: expected ${W.origin} to have ${Q}${W.minimum.toString()} ${X.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":""}: ${Rb(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 C4(){return{localeError:E3()}}var sj=Symbol("ZodOutput"),ej=Symbol("ZodInput");class v8{constructor(){this._map=new WeakMap,this._idmap=new Map}add(w,...b){let $=b[0];if(this._map.set(w,$),$&&typeof $==="object"&&"id"in $){if(this._idmap.has($.id))throw Error(`ID ${$.id} already exists in the registry`);this._idmap.set($.id,w)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(w){let b=this._map.get(w);if(b&&typeof b==="object"&&"id"in b)this._idmap.delete(b.id);return this._map.delete(w),this}get(w){let b=w._zod.parent;if(b){let $={...this.get(b)??{}};delete $.id;let W={...$,...this._map.get(w)};return Object.keys(W).length?W:void 0}return this._map.get(w)}has(w){return this._map.has(w)}}function T3(){return new v8}var _0=T3();function C8(w,b){return new w({type:"string",...v(b)})}function k8(w,b){return new w({type:"string",format:"email",check:"string_format",abort:!1,...v(b)})}function k4(w,b){return new w({type:"string",format:"guid",check:"string_format",abort:!1,...v(b)})}function _8(w,b){return new w({type:"string",format:"uuid",check:"string_format",abort:!1,...v(b)})}function x8(w,b){return new w({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...v(b)})}function h8(w,b){return new w({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...v(b)})}function y8(w,b){return new w({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...v(b)})}function f8(w,b){return new w({type:"string",format:"url",check:"string_format",abort:!1,...v(b)})}function u8(w,b){return new w({type:"string",format:"emoji",check:"string_format",abort:!1,...v(b)})}function c8(w,b){return new w({type:"string",format:"nanoid",check:"string_format",abort:!1,...v(b)})}function m8(w,b){return new w({type:"string",format:"cuid",check:"string_format",abort:!1,...v(b)})}function l8(w,b){return new w({type:"string",format:"cuid2",check:"string_format",abort:!1,...v(b)})}function g8(w,b){return new w({type:"string",format:"ulid",check:"string_format",abort:!1,...v(b)})}function i8(w,b){return new w({type:"string",format:"xid",check:"string_format",abort:!1,...v(b)})}function n8(w,b){return new w({type:"string",format:"ksuid",check:"string_format",abort:!1,...v(b)})}function p8(w,b){return new w({type:"string",format:"ipv4",check:"string_format",abort:!1,...v(b)})}function d8(w,b){return new w({type:"string",format:"ipv6",check:"string_format",abort:!1,...v(b)})}function o8(w,b){return new w({type:"string",format:"cidrv4",check:"string_format",abort:!1,...v(b)})}function t8(w,b){return new w({type:"string",format:"cidrv6",check:"string_format",abort:!1,...v(b)})}function r8(w,b){return new w({type:"string",format:"base64",check:"string_format",abort:!1,...v(b)})}function s8(w,b){return new w({type:"string",format:"base64url",check:"string_format",abort:!1,...v(b)})}function e8(w,b){return new w({type:"string",format:"e164",check:"string_format",abort:!1,...v(b)})}function a8(w,b){return new w({type:"string",format:"jwt",check:"string_format",abort:!1,...v(b)})}function wX(w,b){return new w({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...v(b)})}function bX(w,b){return new w({type:"string",format:"date",check:"string_format",...v(b)})}function $X(w,b){return new w({type:"string",format:"time",check:"string_format",precision:null,...v(b)})}function WX(w,b){return new w({type:"string",format:"duration",check:"string_format",...v(b)})}function QX(w,b){return new w({type:"number",checks:[],...v(b)})}function XX(w,b){return new w({type:"number",check:"number_format",abort:!1,format:"safeint",...v(b)})}function JX(w,b){return new w({type:"boolean",...v(b)})}function GX(w,b){return new w({type:"null",...v(b)})}function YX(w){return new w({type:"unknown"})}function HX(w,b){return new w({type:"never",...v(b)})}function mb(w,b){return new N4({check:"less_than",...v(b),value:w,inclusive:!1})}function x0(w,b){return new N4({check:"less_than",...v(b),value:w,inclusive:!0})}function lb(w,b){return new E4({check:"greater_than",...v(b),value:w,inclusive:!1})}function h0(w,b){return new E4({check:"greater_than",...v(b),value:w,inclusive:!0})}function gb(w,b){return new UQ({check:"multiple_of",...v(b),value:w})}function ib(w,b){return new KQ({check:"max_length",...v(b),maximum:w})}function s1(w,b){return new OQ({check:"min_length",...v(b),minimum:w})}function nb(w,b){return new ZQ({check:"length_equals",...v(b),length:w})}function _4(w,b){return new MQ({check:"string_format",format:"regex",...v(b),pattern:w})}function x4(w){return new VQ({check:"string_format",format:"lowercase",...v(w)})}function h4(w){return new jQ({check:"string_format",format:"uppercase",...v(w)})}function y4(w,b){return new qQ({check:"string_format",format:"includes",...v(b),includes:w})}function f4(w,b){return new PQ({check:"string_format",format:"starts_with",...v(b),prefix:w})}function u4(w,b){return new IQ({check:"string_format",format:"ends_with",...v(b),suffix:w})}function x1(w){return new NQ({check:"overwrite",tx:w})}function c4(w){return x1((b)=>b.normalize(w))}function m4(){return x1((w)=>w.trim())}function l4(){return x1((w)=>w.toLowerCase())}function g4(){return x1((w)=>w.toUpperCase())}function zX(w,b,$){return new w({type:"array",element:b,...v($)})}function BX(w,b,$){let W=v($);return W.abort??(W.abort=!0),new w({type:"custom",check:"custom",fn:b,...W})}function DX(w,b,$){return new w({type:"custom",check:"custom",fn:b,...v($)})}function AX(w){let b=R3(($)=>{return $.addIssue=(W)=>{if(typeof W==="string")$.issues.push(r1(W,$.value,b._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=b),Q.continue??(Q.continue=!b._zod.def.abort),$.issues.push(r1(Q))}},w($.value,$)});return b}function R3(w,b){let $=new Uw({check:"custom",...v(b)});return $._zod.check=w,$}function e1(w){return!!w._zod}function V1(w,b){if(e1(w))return v0(w,b);return w.safeParse(b)}function pb(w){if(!w)return;let b;if(e1(w))b=w._zod?.def?.shape;else b=w.shape;if(!b)return;if(typeof b==="function")try{return b()}catch{return}return b}function LX(w){if(e1(w)){let X=w._zod?.def;if(X){if(X.value!==void 0)return X.value;if(Array.isArray(X.values)&&X.values.length>0)return X.values[0]}}let $=w._def;if($){if($.value!==void 0)return $.value;if(Array.isArray($.values)&&$.values.length>0)return $.values[0]}let W=w.value;if(W!==void 0)return W;return}var f0={};BW(f0,{time:()=>p4,duration:()=>d4,datetime:()=>i4,date:()=>n4,ZodISOTime:()=>KX,ZodISODuration:()=>OX,ZodISODateTime:()=>UX,ZodISODate:()=>FX});var UX=O("ZodISODateTime",(w,b)=>{oQ.init(w,b),Ww.init(w,b)});function i4(w){return wX(UX,w)}var FX=O("ZodISODate",(w,b)=>{tQ.init(w,b),Ww.init(w,b)});function n4(w){return bX(FX,w)}var KX=O("ZodISOTime",(w,b)=>{rQ.init(w,b),Ww.init(w,b)});function p4(w){return $X(KX,w)}var OX=O("ZodISODuration",(w,b)=>{sQ.init(w,b),Ww.init(w,b)});function d4(w){return WX(OX,w)}var ZX=(w,b)=>{kb.init(w,b),w.name="ZodError",Object.defineProperties(w,{format:{value:($)=>SW(w,$)},flatten:{value:($)=>RW(w,$)},addIssue:{value:($)=>{w.issues.push($),w.message=JSON.stringify(w.issues,o1,2)}},addIssues:{value:($)=>{w.issues.push(...$),w.message=JSON.stringify(w.issues,o1,2)}},isEmpty:{get(){return w.issues.length===0}}})},yq=O("ZodError",ZX),vw=O("ZodError",ZX,{Parent:Error});var MX=_b(vw),VX=xb(vw),jX=S0(vw),qX=C0(vw),PX=vW(vw),IX=CW(vw),NX=kW(vw),EX=_W(vw),TX=xW(vw),RX=hW(vw),SX=yW(vw),vX=fW(vw);var Gw=O("ZodType",(w,b)=>{return ww.init(w,b),w.def=b,w.type=b.type,Object.defineProperty(w,"_def",{value:b}),w.check=(...$)=>{return w.clone(o.mergeDefs(b,{checks:[...b.checks??[],...$.map((W)=>typeof W==="function"?{_zod:{check:W,def:{check:"custom"},onattach:[]}}:W)]}))},w.clone=($,W)=>cw(w,$,W),w.brand=()=>w,w.register=($,W)=>{return $.add(w,W),w},w.parse=($,W)=>MX(w,$,W,{callee:w.parse}),w.safeParse=($,W)=>jX(w,$,W),w.parseAsync=async($,W)=>VX(w,$,W,{callee:w.parseAsync}),w.safeParseAsync=async($,W)=>qX(w,$,W),w.spa=w.safeParseAsync,w.encode=($,W)=>PX(w,$,W),w.decode=($,W)=>IX(w,$,W),w.encodeAsync=async($,W)=>NX(w,$,W),w.decodeAsync=async($,W)=>EX(w,$,W),w.safeEncode=($,W)=>TX(w,$,W),w.safeDecode=($,W)=>RX(w,$,W),w.safeEncodeAsync=async($,W)=>SX(w,$,W),w.safeDecodeAsync=async($,W)=>vX(w,$,W),w.refine=($,W)=>w.check(IB($,W)),w.superRefine=($)=>w.check(NB($)),w.overwrite=($)=>w.check(x1($)),w.optional=()=>Jw(w),w.nullable=()=>_X(w),w.nullish=()=>Jw(_X(w)),w.nonoptional=($)=>ZB(w,$),w.array=()=>g(w),w.or=($)=>a([w,$]),w.and=($)=>ob(w,$),w.transform=($)=>t4(w,uX($)),w.default=($)=>FB(w,$),w.prefault=($)=>OB(w,$),w.catch=($)=>VB(w,$),w.pipe=($)=>t4(w,$),w.readonly=()=>PB(w),w.describe=($)=>{let W=w.clone();return _0.add(W,{description:$}),W},Object.defineProperty(w,"description",{get(){return _0.get(w)?.description},configurable:!0}),w.meta=(...$)=>{if($.length===0)return _0.get(w);let W=w.clone();return _0.add(W,$[0]),W},w.isOptional=()=>w.safeParse(void 0).success,w.isNullable=()=>w.safeParse(null).success,w}),xX=O("_ZodString",(w,b)=>{cb.init(w,b),Gw.init(w,b);let $=w._zod.bag;w.format=$.format??null,w.minLength=$.minimum??null,w.maxLength=$.maximum??null,w.regex=(...W)=>w.check(_4(...W)),w.includes=(...W)=>w.check(y4(...W)),w.startsWith=(...W)=>w.check(f4(...W)),w.endsWith=(...W)=>w.check(u4(...W)),w.min=(...W)=>w.check(s1(...W)),w.max=(...W)=>w.check(ib(...W)),w.length=(...W)=>w.check(nb(...W)),w.nonempty=(...W)=>w.check(s1(1,...W)),w.lowercase=(W)=>w.check(x4(W)),w.uppercase=(W)=>w.check(h4(W)),w.trim=()=>w.check(m4()),w.normalize=(...W)=>w.check(c4(...W)),w.toLowerCase=()=>w.check(l4()),w.toUpperCase=()=>w.check(g4())}),f3=O("ZodString",(w,b)=>{cb.init(w,b),xX.init(w,b),w.email=($)=>w.check(k8(u3,$)),w.url=($)=>w.check(f8(c3,$)),w.jwt=($)=>w.check(a8(bB,$)),w.emoji=($)=>w.check(u8(m3,$)),w.guid=($)=>w.check(k4(CX,$)),w.uuid=($)=>w.check(_8(db,$)),w.uuidv4=($)=>w.check(x8(db,$)),w.uuidv6=($)=>w.check(h8(db,$)),w.uuidv7=($)=>w.check(y8(db,$)),w.nanoid=($)=>w.check(c8(l3,$)),w.guid=($)=>w.check(k4(CX,$)),w.cuid=($)=>w.check(m8(g3,$)),w.cuid2=($)=>w.check(l8(i3,$)),w.ulid=($)=>w.check(g8(n3,$)),w.base64=($)=>w.check(r8(e3,$)),w.base64url=($)=>w.check(s8(a3,$)),w.xid=($)=>w.check(i8(p3,$)),w.ksuid=($)=>w.check(n8(d3,$)),w.ipv4=($)=>w.check(p8(o3,$)),w.ipv6=($)=>w.check(d8(t3,$)),w.cidrv4=($)=>w.check(o8(r3,$)),w.cidrv6=($)=>w.check(t8(s3,$)),w.e164=($)=>w.check(e8(wB,$)),w.datetime=($)=>w.check(i4($)),w.date=($)=>w.check(n4($)),w.time=($)=>w.check(p4($)),w.duration=($)=>w.check(d4($))});function K(w){return C8(f3,w)}var Ww=O("ZodStringFormat",(w,b)=>{bw.init(w,b),xX.init(w,b)}),u3=O("ZodEmail",(w,b)=>{uQ.init(w,b),Ww.init(w,b)});var CX=O("ZodGUID",(w,b)=>{yQ.init(w,b),Ww.init(w,b)});var db=O("ZodUUID",(w,b)=>{fQ.init(w,b),Ww.init(w,b)});var c3=O("ZodURL",(w,b)=>{cQ.init(w,b),Ww.init(w,b)});var m3=O("ZodEmoji",(w,b)=>{mQ.init(w,b),Ww.init(w,b)});var l3=O("ZodNanoID",(w,b)=>{lQ.init(w,b),Ww.init(w,b)});var g3=O("ZodCUID",(w,b)=>{gQ.init(w,b),Ww.init(w,b)});var i3=O("ZodCUID2",(w,b)=>{iQ.init(w,b),Ww.init(w,b)});var n3=O("ZodULID",(w,b)=>{nQ.init(w,b),Ww.init(w,b)});var p3=O("ZodXID",(w,b)=>{pQ.init(w,b),Ww.init(w,b)});var d3=O("ZodKSUID",(w,b)=>{dQ.init(w,b),Ww.init(w,b)});var o3=O("ZodIPv4",(w,b)=>{eQ.init(w,b),Ww.init(w,b)});var t3=O("ZodIPv6",(w,b)=>{aQ.init(w,b),Ww.init(w,b)});var r3=O("ZodCIDRv4",(w,b)=>{w8.init(w,b),Ww.init(w,b)});var s3=O("ZodCIDRv6",(w,b)=>{b8.init(w,b),Ww.init(w,b)});var e3=O("ZodBase64",(w,b)=>{W8.init(w,b),Ww.init(w,b)});var a3=O("ZodBase64URL",(w,b)=>{Q8.init(w,b),Ww.init(w,b)});var wB=O("ZodE164",(w,b)=>{X8.init(w,b),Ww.init(w,b)});var bB=O("ZodJWT",(w,b)=>{J8.init(w,b),Ww.init(w,b)});var hX=O("ZodNumber",(w,b)=>{S4.init(w,b),Gw.init(w,b),w.gt=(W,Q)=>w.check(lb(W,Q)),w.gte=(W,Q)=>w.check(h0(W,Q)),w.min=(W,Q)=>w.check(h0(W,Q)),w.lt=(W,Q)=>w.check(mb(W,Q)),w.lte=(W,Q)=>w.check(x0(W,Q)),w.max=(W,Q)=>w.check(x0(W,Q)),w.int=(W)=>w.check(kX(W)),w.safe=(W)=>w.check(kX(W)),w.positive=(W)=>w.check(lb(0,W)),w.nonnegative=(W)=>w.check(h0(0,W)),w.negative=(W)=>w.check(mb(0,W)),w.nonpositive=(W)=>w.check(x0(0,W)),w.multipleOf=(W,Q)=>w.check(gb(W,Q)),w.step=(W,Q)=>w.check(gb(W,Q)),w.finite=()=>w;let $=w._zod.bag;w.minValue=Math.max($.minimum??Number.NEGATIVE_INFINITY,$.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,w.maxValue=Math.min($.maximum??Number.POSITIVE_INFINITY,$.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,w.isInt=($.format??"").includes("int")||Number.isSafeInteger($.multipleOf??0.5),w.isFinite=!0,w.format=$.format??null});function r(w){return QX(hX,w)}var $B=O("ZodNumberFormat",(w,b)=>{G8.init(w,b),hX.init(w,b)});function kX(w){return XX($B,w)}var WB=O("ZodBoolean",(w,b)=>{Y8.init(w,b),Gw.init(w,b)});function Aw(w){return JX(WB,w)}var QB=O("ZodNull",(w,b)=>{H8.init(w,b),Gw.init(w,b)});function r4(w){return GX(QB,w)}var XB=O("ZodUnknown",(w,b)=>{z8.init(w,b),Gw.init(w,b)});function Qw(){return YX(XB)}var JB=O("ZodNever",(w,b)=>{B8.init(w,b),Gw.init(w,b)});function GB(w){return HX(JB,w)}var YB=O("ZodArray",(w,b)=>{D8.init(w,b),Gw.init(w,b),w.element=b.element,w.min=($,W)=>w.check(s1($,W)),w.nonempty=($)=>w.check(s1(1,$)),w.max=($,W)=>w.check(ib($,W)),w.length=($,W)=>w.check(nb($,W)),w.unwrap=()=>w.element});function g(w,b){return zX(YB,w,b)}var yX=O("ZodObject",(w,b)=>{U8.init(w,b),Gw.init(w,b),o.defineLazy(w,"shape",()=>{return b.shape}),w.keyof=()=>Iw(Object.keys(w._zod.def.shape)),w.catchall=($)=>w.clone({...w._zod.def,catchall:$}),w.passthrough=()=>w.clone({...w._zod.def,catchall:Qw()}),w.loose=()=>w.clone({...w._zod.def,catchall:Qw()}),w.strict=()=>w.clone({...w._zod.def,catchall:GB()}),w.strip=()=>w.clone({...w._zod.def,catchall:void 0}),w.extend=($)=>{return o.extend(w,$)},w.safeExtend=($)=>{return o.safeExtend(w,$)},w.merge=($)=>o.merge(w,$),w.pick=($)=>o.pick(w,$),w.omit=($)=>o.omit(w,$),w.partial=(...$)=>o.partial(cX,w,$[0]),w.required=(...$)=>o.required(mX,w,$[0])});function E(w,b){let $={type:"object",shape:w??{},...o.normalizeParams(b)};return new yX($)}function jw(w,b){return new yX({type:"object",shape:w,catchall:Qw(),...o.normalizeParams(b)})}var fX=O("ZodUnion",(w,b)=>{v4.init(w,b),Gw.init(w,b),w.options=b.options});function a(w,b){return new fX({type:"union",options:w,...o.normalizeParams(b)})}var HB=O("ZodDiscriminatedUnion",(w,b)=>{fX.init(w,b),F8.init(w,b)});function s4(w,b,$){return new HB({type:"union",options:b,discriminator:w,...o.normalizeParams($)})}var zB=O("ZodIntersection",(w,b)=>{K8.init(w,b),Gw.init(w,b)});function ob(w,b){return new zB({type:"intersection",left:w,right:b})}var BB=O("ZodRecord",(w,b)=>{O8.init(w,b),Gw.init(w,b),w.keyType=b.keyType,w.valueType=b.valueType});function Xw(w,b,$){return new BB({type:"record",keyType:w,valueType:b,...o.normalizeParams($)})}var o4=O("ZodEnum",(w,b)=>{Z8.init(w,b),Gw.init(w,b),w.enum=b.entries,w.options=Object.values(b.entries);let $=new Set(Object.keys(b.entries));w.extract=(W,Q)=>{let X={};for(let J of W)if($.has(J))X[J]=b.entries[J];else throw Error(`Key ${J} not found in enum`);return new o4({...b,checks:[],...o.normalizeParams(Q),entries:X})},w.exclude=(W,Q)=>{let X={...b.entries};for(let J of W)if($.has(J))delete X[J];else throw Error(`Key ${J} not found in enum`);return new o4({...b,checks:[],...o.normalizeParams(Q),entries:X})}});function Iw(w,b){let $=Array.isArray(w)?Object.fromEntries(w.map((W)=>[W,W])):w;return new o4({type:"enum",entries:$,...o.normalizeParams(b)})}var DB=O("ZodLiteral",(w,b)=>{M8.init(w,b),Gw.init(w,b),w.values=new Set(b.values),Object.defineProperty(w,"value",{get(){if(b.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return b.values[0]}})});function T(w,b){return new DB({type:"literal",values:Array.isArray(w)?w:[w],...o.normalizeParams(b)})}var AB=O("ZodTransform",(w,b)=>{V8.init(w,b),Gw.init(w,b),w._zod.parse=($,W)=>{if(W.direction==="backward")throw new I0(w.constructor.name);$.addIssue=(X)=>{if(typeof X==="string")$.issues.push(o.issue(X,$.value,b));else{let J=X;if(J.fatal)J.continue=!1;J.code??(J.code="custom"),J.input??(J.input=$.value),J.inst??(J.inst=w),$.issues.push(o.issue(J))}};let Q=b.transform($.value,$);if(Q instanceof Promise)return Q.then((X)=>{return $.value=X,$});return $.value=Q,$}});function uX(w){return new AB({type:"transform",transform:w})}var cX=O("ZodOptional",(w,b)=>{j8.init(w,b),Gw.init(w,b),w.unwrap=()=>w._zod.def.innerType});function Jw(w){return new cX({type:"optional",innerType:w})}var LB=O("ZodNullable",(w,b)=>{q8.init(w,b),Gw.init(w,b),w.unwrap=()=>w._zod.def.innerType});function _X(w){return new LB({type:"nullable",innerType:w})}var UB=O("ZodDefault",(w,b)=>{P8.init(w,b),Gw.init(w,b),w.unwrap=()=>w._zod.def.innerType,w.removeDefault=w.unwrap});function FB(w,b){return new UB({type:"default",innerType:w,get defaultValue(){return typeof b==="function"?b():o.shallowClone(b)}})}var KB=O("ZodPrefault",(w,b)=>{I8.init(w,b),Gw.init(w,b),w.unwrap=()=>w._zod.def.innerType});function OB(w,b){return new KB({type:"prefault",innerType:w,get defaultValue(){return typeof b==="function"?b():o.shallowClone(b)}})}var mX=O("ZodNonOptional",(w,b)=>{N8.init(w,b),Gw.init(w,b),w.unwrap=()=>w._zod.def.innerType});function ZB(w,b){return new mX({type:"nonoptional",innerType:w,...o.normalizeParams(b)})}var MB=O("ZodCatch",(w,b)=>{E8.init(w,b),Gw.init(w,b),w.unwrap=()=>w._zod.def.innerType,w.removeCatch=w.unwrap});function VB(w,b){return new MB({type:"catch",innerType:w,catchValue:typeof b==="function"?b:()=>b})}var jB=O("ZodPipe",(w,b)=>{T8.init(w,b),Gw.init(w,b),w.in=b.in,w.out=b.out});function t4(w,b){return new jB({type:"pipe",in:w,out:b})}var qB=O("ZodReadonly",(w,b)=>{R8.init(w,b),Gw.init(w,b),w.unwrap=()=>w._zod.def.innerType});function PB(w){return new qB({type:"readonly",innerType:w})}var lX=O("ZodCustom",(w,b)=>{S8.init(w,b),Gw.init(w,b)});function gX(w,b){return BX(lX,w??(()=>!0),b)}function IB(w,b={}){return DX(lX,w,b)}function NB(w){return AX(w)}function e4(w,b){return t4(uX(w),b)}xw(C4());var a4="2025-11-25";var iX=[a4,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],j1="io.modelcontextprotocol/related-task",rb="2.0",Fw=gX((w)=>w!==null&&(typeof w==="object"||typeof w==="function")),nX=a([K(),r().int()]),pX=K(),CP=jw({ttl:a([r(),r4()]).optional(),pollInterval:r().optional()}),EB=E({ttl:r().optional()}),TB=E({taskId:K()}),w$=jw({progressToken:nX.optional(),[j1]:TB.optional()}),Cw=E({_meta:w$.optional()}),u0=Cw.extend({task:EB.optional()}),dX=(w)=>u0.safeParse(w).success,Kw=E({method:K(),params:Cw.loose().optional()}),hw=E({_meta:w$.optional()}),yw=E({method:K(),params:hw.loose().optional()}),Ow=jw({_meta:w$.optional()}),sb=a([K(),r().int()]),oX=E({jsonrpc:T(rb),id:sb,...Kw.shape}).strict(),b$=(w)=>oX.safeParse(w).success,tX=E({jsonrpc:T(rb),...yw.shape}).strict(),rX=(w)=>tX.safeParse(w).success,$$=E({jsonrpc:T(rb),id:sb,result:Ow}).strict(),c0=(w)=>$$.safeParse(w).success;var i;(function(w){w[w.ConnectionClosed=-32000]="ConnectionClosed",w[w.RequestTimeout=-32001]="RequestTimeout",w[w.ParseError=-32700]="ParseError",w[w.InvalidRequest=-32600]="InvalidRequest",w[w.MethodNotFound=-32601]="MethodNotFound",w[w.InvalidParams=-32602]="InvalidParams",w[w.InternalError=-32603]="InternalError",w[w.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(i||(i={}));var W$=E({jsonrpc:T(rb),id:sb.optional(),error:E({code:r().int(),message:K(),data:Qw().optional()})}).strict();var sX=(w)=>W$.safeParse(w).success;var kP=a([oX,tX,$$,W$]),_P=a([$$,W$]),eb=Ow.strict(),RB=hw.extend({requestId:sb.optional(),reason:K().optional()}),ab=yw.extend({method:T("notifications/cancelled"),params:RB}),SB=E({src:K(),mimeType:K().optional(),sizes:g(K()).optional(),theme:Iw(["light","dark"]).optional()}),m0=E({icons:g(SB).optional()}),a1=E({name:K(),title:K().optional()}),eX=a1.extend({...a1.shape,...m0.shape,version:K(),websiteUrl:K().optional(),description:K().optional()}),vB=ob(E({applyDefaults:Aw().optional()}),Xw(K(),Qw())),CB=e4((w)=>{if(w&&typeof w==="object"&&!Array.isArray(w)){if(Object.keys(w).length===0)return{form:{}}}return w},ob(E({form:vB.optional(),url:Fw.optional()}),Xw(K(),Qw()).optional())),kB=jw({list:Fw.optional(),cancel:Fw.optional(),requests:jw({sampling:jw({createMessage:Fw.optional()}).optional(),elicitation:jw({create:Fw.optional()}).optional()}).optional()}),_B=jw({list:Fw.optional(),cancel:Fw.optional(),requests:jw({tools:jw({call:Fw.optional()}).optional()}).optional()}),xB=E({experimental:Xw(K(),Fw).optional(),sampling:E({context:Fw.optional(),tools:Fw.optional()}).optional(),elicitation:CB.optional(),roots:E({listChanged:Aw().optional()}).optional(),tasks:kB.optional()}),hB=Cw.extend({protocolVersion:K(),capabilities:xB,clientInfo:eX}),Q$=Kw.extend({method:T("initialize"),params:hB});var yB=E({experimental:Xw(K(),Fw).optional(),logging:Fw.optional(),completions:Fw.optional(),prompts:E({listChanged:Aw().optional()}).optional(),resources:E({subscribe:Aw().optional(),listChanged:Aw().optional()}).optional(),tools:E({listChanged:Aw().optional()}).optional(),tasks:_B.optional()}),fB=Ow.extend({protocolVersion:K(),capabilities:yB,serverInfo:eX,instructions:K().optional()}),X$=yw.extend({method:T("notifications/initialized"),params:hw.optional()});var w6=Kw.extend({method:T("ping"),params:Cw.optional()}),uB=E({progress:r(),total:Jw(r()),message:Jw(K())}),cB=E({...hw.shape,...uB.shape,progressToken:nX}),b6=yw.extend({method:T("notifications/progress"),params:cB}),mB=Cw.extend({cursor:pX.optional()}),l0=Kw.extend({params:mB.optional()}),g0=Ow.extend({nextCursor:pX.optional()}),lB=Iw(["working","input_required","completed","failed","cancelled"]),i0=E({taskId:K(),status:lB,ttl:a([r(),r4()]),createdAt:K(),lastUpdatedAt:K(),pollInterval:Jw(r()),statusMessage:Jw(K())}),w0=Ow.extend({task:i0}),gB=hw.merge(i0),n0=yw.extend({method:T("notifications/tasks/status"),params:gB}),$6=Kw.extend({method:T("tasks/get"),params:Cw.extend({taskId:K()})}),W6=Ow.merge(i0),Q6=Kw.extend({method:T("tasks/result"),params:Cw.extend({taskId:K()})}),xP=Ow.loose(),X6=l0.extend({method:T("tasks/list")}),J6=g0.extend({tasks:g(i0)}),G6=Kw.extend({method:T("tasks/cancel"),params:Cw.extend({taskId:K()})}),aX=Ow.merge(i0),wJ=E({uri:K(),mimeType:Jw(K()),_meta:Xw(K(),Qw()).optional()}),bJ=wJ.extend({text:K()}),J$=K().refine((w)=>{try{return atob(w),!0}catch{return!1}},{message:"Invalid Base64 string"}),$J=wJ.extend({blob:J$}),p0=Iw(["user","assistant"]),b0=E({audience:g(p0).optional(),priority:r().min(0).max(1).optional(),lastModified:f0.datetime({offset:!0}).optional()}),WJ=E({...a1.shape,...m0.shape,uri:K(),description:Jw(K()),mimeType:Jw(K()),annotations:b0.optional(),_meta:Jw(jw({}))}),iB=E({...a1.shape,...m0.shape,uriTemplate:K(),description:Jw(K()),mimeType:Jw(K()),annotations:b0.optional(),_meta:Jw(jw({}))}),G$=l0.extend({method:T("resources/list")}),nB=g0.extend({resources:g(WJ)}),pB=l0.extend({method:T("resources/templates/list")}),dB=g0.extend({resourceTemplates:g(iB)}),Y$=Cw.extend({uri:K()}),oB=Y$,H$=Kw.extend({method:T("resources/read"),params:oB}),tB=Ow.extend({contents:g(a([bJ,$J]))}),rB=yw.extend({method:T("notifications/resources/list_changed"),params:hw.optional()}),sB=Y$,eB=Kw.extend({method:T("resources/subscribe"),params:sB}),aB=Y$,wD=Kw.extend({method:T("resources/unsubscribe"),params:aB}),bD=hw.extend({uri:K()}),$D=yw.extend({method:T("notifications/resources/updated"),params:bD}),WD=E({name:K(),description:Jw(K()),required:Jw(Aw())}),QD=E({...a1.shape,...m0.shape,description:Jw(K()),arguments:Jw(g(WD)),_meta:Jw(jw({}))}),XD=l0.extend({method:T("prompts/list")}),JD=g0.extend({prompts:g(QD)}),GD=Cw.extend({name:K(),arguments:Xw(K(),K()).optional()}),YD=Kw.extend({method:T("prompts/get"),params:GD}),z$=E({type:T("text"),text:K(),annotations:b0.optional(),_meta:Xw(K(),Qw()).optional()}),B$=E({type:T("image"),data:J$,mimeType:K(),annotations:b0.optional(),_meta:Xw(K(),Qw()).optional()}),D$=E({type:T("audio"),data:J$,mimeType:K(),annotations:b0.optional(),_meta:Xw(K(),Qw()).optional()}),HD=E({type:T("tool_use"),name:K(),id:K(),input:Xw(K(),Qw()),_meta:Xw(K(),Qw()).optional()}),zD=E({type:T("resource"),resource:a([bJ,$J]),annotations:b0.optional(),_meta:Xw(K(),Qw()).optional()}),BD=WJ.extend({type:T("resource_link")}),A$=a([z$,B$,D$,BD,zD]),DD=E({role:p0,content:A$}),AD=Ow.extend({description:K().optional(),messages:g(DD)}),LD=yw.extend({method:T("notifications/prompts/list_changed"),params:hw.optional()}),UD=E({title:K().optional(),readOnlyHint:Aw().optional(),destructiveHint:Aw().optional(),idempotentHint:Aw().optional(),openWorldHint:Aw().optional()}),FD=E({taskSupport:Iw(["required","optional","forbidden"]).optional()}),QJ=E({...a1.shape,...m0.shape,description:K().optional(),inputSchema:E({type:T("object"),properties:Xw(K(),Fw).optional(),required:g(K()).optional()}).catchall(Qw()),outputSchema:E({type:T("object"),properties:Xw(K(),Fw).optional(),required:g(K()).optional()}).catchall(Qw()).optional(),annotations:UD.optional(),execution:FD.optional(),_meta:Xw(K(),Qw()).optional()}),L$=l0.extend({method:T("tools/list")}),KD=g0.extend({tools:g(QJ)}),Y6=Ow.extend({content:g(A$).default([]),structuredContent:Xw(K(),Qw()).optional(),isError:Aw().optional()}),hP=Y6.or(Ow.extend({toolResult:Qw()})),OD=u0.extend({name:K(),arguments:Xw(K(),Qw()).optional()}),d0=Kw.extend({method:T("tools/call"),params:OD}),ZD=yw.extend({method:T("notifications/tools/list_changed"),params:hw.optional()}),yP=E({autoRefresh:Aw().default(!0),debounceMs:r().int().nonnegative().default(300)}),o0=Iw(["debug","info","notice","warning","error","critical","alert","emergency"]),MD=Cw.extend({level:o0}),U$=Kw.extend({method:T("logging/setLevel"),params:MD}),VD=hw.extend({level:o0,logger:K().optional(),data:Qw()}),jD=yw.extend({method:T("notifications/message"),params:VD}),qD=E({name:K().optional()}),PD=E({hints:g(qD).optional(),costPriority:r().min(0).max(1).optional(),speedPriority:r().min(0).max(1).optional(),intelligencePriority:r().min(0).max(1).optional()}),ID=E({mode:Iw(["auto","required","none"]).optional()}),ND=E({type:T("tool_result"),toolUseId:K().describe("The unique identifier for the corresponding tool call."),content:g(A$).default([]),structuredContent:E({}).loose().optional(),isError:Aw().optional(),_meta:Xw(K(),Qw()).optional()}),ED=s4("type",[z$,B$,D$]),tb=s4("type",[z$,B$,D$,HD,ND]),TD=E({role:p0,content:a([tb,g(tb)]),_meta:Xw(K(),Qw()).optional()}),RD=u0.extend({messages:g(TD),modelPreferences:PD.optional(),systemPrompt:K().optional(),includeContext:Iw(["none","thisServer","allServers"]).optional(),temperature:r().optional(),maxTokens:r().int(),stopSequences:g(K()).optional(),metadata:Fw.optional(),tools:g(QJ).optional(),toolChoice:ID.optional()}),SD=Kw.extend({method:T("sampling/createMessage"),params:RD}),F$=Ow.extend({model:K(),stopReason:Jw(Iw(["endTurn","stopSequence","maxTokens"]).or(K())),role:p0,content:ED}),K$=Ow.extend({model:K(),stopReason:Jw(Iw(["endTurn","stopSequence","maxTokens","toolUse"]).or(K())),role:p0,content:a([tb,g(tb)])}),vD=E({type:T("boolean"),title:K().optional(),description:K().optional(),default:Aw().optional()}),CD=E({type:T("string"),title:K().optional(),description:K().optional(),minLength:r().optional(),maxLength:r().optional(),format:Iw(["email","uri","date","date-time"]).optional(),default:K().optional()}),kD=E({type:Iw(["number","integer"]),title:K().optional(),description:K().optional(),minimum:r().optional(),maximum:r().optional(),default:r().optional()}),_D=E({type:T("string"),title:K().optional(),description:K().optional(),enum:g(K()),default:K().optional()}),xD=E({type:T("string"),title:K().optional(),description:K().optional(),oneOf:g(E({const:K(),title:K()})),default:K().optional()}),hD=E({type:T("string"),title:K().optional(),description:K().optional(),enum:g(K()),enumNames:g(K()).optional(),default:K().optional()}),yD=a([_D,xD]),fD=E({type:T("array"),title:K().optional(),description:K().optional(),minItems:r().optional(),maxItems:r().optional(),items:E({type:T("string"),enum:g(K())}),default:g(K()).optional()}),uD=E({type:T("array"),title:K().optional(),description:K().optional(),minItems:r().optional(),maxItems:r().optional(),items:E({anyOf:g(E({const:K(),title:K()}))}),default:g(K()).optional()}),cD=a([fD,uD]),mD=a([hD,yD,cD]),lD=a([mD,vD,CD,kD]),gD=u0.extend({mode:T("form").optional(),message:K(),requestedSchema:E({type:T("object"),properties:Xw(K(),lD),required:g(K()).optional()})}),iD=u0.extend({mode:T("url"),message:K(),elicitationId:K(),url:K().url()}),nD=a([gD,iD]),pD=Kw.extend({method:T("elicitation/create"),params:nD}),dD=hw.extend({elicitationId:K()}),oD=yw.extend({method:T("notifications/elicitation/complete"),params:dD}),H6=Ow.extend({action:Iw(["accept","decline","cancel"]),content:e4((w)=>w===null?void 0:w,Xw(K(),a([K(),r(),Aw(),g(K())])).optional())}),tD=E({type:T("ref/resource"),uri:K()});var rD=E({type:T("ref/prompt"),name:K()}),sD=Cw.extend({ref:a([rD,tD]),argument:E({name:K(),value:K()}),context:E({arguments:Xw(K(),K()).optional()}).optional()}),eD=Kw.extend({method:T("completion/complete"),params:sD});var aD=Ow.extend({completion:jw({values:g(K()).max(100),total:Jw(r().int()),hasMore:Jw(Aw())})}),wA=E({uri:K().startsWith("file://"),name:K().optional(),_meta:Xw(K(),Qw()).optional()}),bA=Kw.extend({method:T("roots/list"),params:Cw.optional()}),O$=Ow.extend({roots:g(wA)}),$A=yw.extend({method:T("notifications/roots/list_changed"),params:hw.optional()}),fP=a([w6,Q$,eD,U$,YD,XD,G$,pB,H$,eB,wD,d0,L$,$6,Q6,X6,G6]),uP=a([ab,b6,X$,$A,n0]),cP=a([eb,F$,K$,H6,O$,W6,J6,w0]),mP=a([w6,SD,pD,bA,$6,Q6,X6,G6]),lP=a([ab,b6,jD,$D,rB,ZD,LD,n0,oD]),gP=a([eb,fB,aD,AD,JD,nB,dB,tB,Y6,KD,W6,J6,w0]);class u extends Error{constructor(w,b,$){super(`MCP error ${w}: ${b}`);this.code=w,this.data=$,this.name="McpError"}static fromError(w,b,$){if(w===i.UrlElicitationRequired&&$){let W=$;if(W.elicitations)return new XJ(W.elicitations,b)}return new u(w,b,$)}}class XJ extends u{constructor(w,b=`URL elicitation${w.length>1?"s":""} required`){super(i.UrlElicitationRequired,b,{elicitations:w})}get elicitations(){return this.data?.elicitations??[]}}function q1(w){return w==="completed"||w==="failed"||w==="cancelled"}var WA=Symbol("Let zodToJsonSchema decide on which parser to use");var jI=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Z$(w){let $=pb(w)?.method;if(!$)throw Error("Schema is missing a method literal");let W=LX($);if(typeof W!=="string")throw Error("Schema method literal must be a string");return W}function M$(w,b){let $=V1(w,b);if(!$.success)throw $.error;return $.data}var HA=60000;class V${constructor(w){if(this._options=w,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(ab,(b)=>{this._oncancel(b)}),this.setNotificationHandler(b6,(b)=>{this._onprogress(b)}),this.setRequestHandler(w6,(b)=>({})),this._taskStore=w?.taskStore,this._taskMessageQueue=w?.taskMessageQueue,this._taskStore)this.setRequestHandler($6,async(b,$)=>{let W=await this._taskStore.getTask(b.params.taskId,$.sessionId);if(!W)throw new u(i.InvalidParams,"Failed to retrieve task: Task not found");return{...W}}),this.setRequestHandler(Q6,async(b,$)=>{let W=async()=>{let Q=b.params.taskId;if(this._taskMessageQueue){let J;while(J=await this._taskMessageQueue.dequeue(Q,$.sessionId)){if(J.type==="response"||J.type==="error"){let G=J.message,Y=G.id,H=this._requestResolvers.get(Y);if(H)if(this._requestResolvers.delete(Y),J.type==="response")H(G);else{let z=G,D=new u(z.error.code,z.error.message,z.error.data);H(D)}else{let z=J.type==="response"?"Response":"Error";this._onerror(Error(`${z} handler missing for request ${Y}`))}continue}await this._transport?.send(J.message,{relatedRequestId:$.requestId})}}let X=await this._taskStore.getTask(Q,$.sessionId);if(!X)throw new u(i.InvalidParams,`Task not found: ${Q}`);if(!q1(X.status))return await this._waitForTaskUpdate(Q,$.signal),await W();if(q1(X.status)){let J=await this._taskStore.getTaskResult(Q,$.sessionId);return this._clearTaskQueue(Q),{...J,_meta:{...J._meta,[j1]:{taskId:Q}}}}return await W()};return await W()}),this.setRequestHandler(X6,async(b,$)=>{try{let{tasks:W,nextCursor:Q}=await this._taskStore.listTasks(b.params?.cursor,$.sessionId);return{tasks:W,nextCursor:Q,_meta:{}}}catch(W){throw new u(i.InvalidParams,`Failed to list tasks: ${W instanceof Error?W.message:String(W)}`)}}),this.setRequestHandler(G6,async(b,$)=>{try{let W=await this._taskStore.getTask(b.params.taskId,$.sessionId);if(!W)throw new u(i.InvalidParams,`Task not found: ${b.params.taskId}`);if(q1(W.status))throw new u(i.InvalidParams,`Cannot cancel task in terminal status: ${W.status}`);await this._taskStore.updateTaskStatus(b.params.taskId,"cancelled","Client cancelled task execution.",$.sessionId),this._clearTaskQueue(b.params.taskId);let Q=await this._taskStore.getTask(b.params.taskId,$.sessionId);if(!Q)throw new u(i.InvalidParams,`Task not found after cancellation: ${b.params.taskId}`);return{_meta:{},...Q}}catch(W){if(W instanceof u)throw W;throw new u(i.InvalidRequest,`Failed to cancel task: ${W instanceof Error?W.message:String(W)}`)}})}async _oncancel(w){if(!w.params.requestId)return;this._requestHandlerAbortControllers.get(w.params.requestId)?.abort(w.params.reason)}_setupTimeout(w,b,$,W,Q=!1){this._timeoutInfo.set(w,{timeoutId:setTimeout(W,b),startTime:Date.now(),timeout:b,maxTotalTimeout:$,resetTimeoutOnProgress:Q,onTimeout:W})}_resetTimeout(w){let b=this._timeoutInfo.get(w);if(!b)return!1;let $=Date.now()-b.startTime;if(b.maxTotalTimeout&&$>=b.maxTotalTimeout)throw this._timeoutInfo.delete(w),u.fromError(i.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:b.maxTotalTimeout,totalElapsed:$});return clearTimeout(b.timeoutId),b.timeoutId=setTimeout(b.onTimeout,b.timeout),!0}_cleanupTimeout(w){let b=this._timeoutInfo.get(w);if(b)clearTimeout(b.timeoutId),this._timeoutInfo.delete(w)}async connect(w){this._transport=w;let b=this.transport?.onclose;this._transport.onclose=()=>{b?.(),this._onclose()};let $=this.transport?.onerror;this._transport.onerror=(Q)=>{$?.(Q),this._onerror(Q)};let W=this._transport?.onmessage;this._transport.onmessage=(Q,X)=>{if(W?.(Q,X),c0(Q)||sX(Q))this._onresponse(Q);else if(b$(Q))this._onrequest(Q,X);else if(rX(Q))this._onnotification(Q);else this._onerror(Error(`Unknown message type: ${JSON.stringify(Q)}`))},await this._transport.start()}_onclose(){let w=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();let b=u.fromError(i.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let $ of w.values())$(b)}_onerror(w){this.onerror?.(w)}_onnotification(w){let b=this._notificationHandlers.get(w.method)??this.fallbackNotificationHandler;if(b===void 0)return;Promise.resolve().then(()=>b(w)).catch(($)=>this._onerror(Error(`Uncaught error in notification handler: ${$}`)))}_onrequest(w,b){let $=this._requestHandlers.get(w.method)??this.fallbackRequestHandler,W=this._transport,Q=w.params?._meta?.[j1]?.taskId;if($===void 0){let H={jsonrpc:"2.0",id:w.id,error:{code:i.MethodNotFound,message:"Method not found"}};if(Q&&this._taskMessageQueue)this._enqueueTaskMessage(Q,{type:"error",message:H,timestamp:Date.now()},W?.sessionId).catch((z)=>this._onerror(Error(`Failed to enqueue error response: ${z}`)));else W?.send(H).catch((z)=>this._onerror(Error(`Failed to send an error response: ${z}`)));return}let X=new AbortController;this._requestHandlerAbortControllers.set(w.id,X);let J=dX(w.params)?w.params.task:void 0,G=this._taskStore?this.requestTaskStore(w,W?.sessionId):void 0,Y={signal:X.signal,sessionId:W?.sessionId,_meta:w.params?._meta,sendNotification:async(H)=>{let z={relatedRequestId:w.id};if(Q)z.relatedTask={taskId:Q};await this.notification(H,z)},sendRequest:async(H,z,D)=>{let A={...D,relatedRequestId:w.id};if(Q&&!A.relatedTask)A.relatedTask={taskId:Q};let L=A.relatedTask?.taskId??Q;if(L&&G)await G.updateTaskStatus(L,"input_required");return await this.request(H,z,A)},authInfo:b?.authInfo,requestId:w.id,requestInfo:b?.requestInfo,taskId:Q,taskStore:G,taskRequestedTtl:J?.ttl,closeSSEStream:b?.closeSSEStream,closeStandaloneSSEStream:b?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(J)this.assertTaskHandlerCapability(w.method)}).then(()=>$(w,Y)).then(async(H)=>{if(X.signal.aborted)return;let z={result:H,jsonrpc:"2.0",id:w.id};if(Q&&this._taskMessageQueue)await this._enqueueTaskMessage(Q,{type:"response",message:z,timestamp:Date.now()},W?.sessionId);else await W?.send(z)},async(H)=>{if(X.signal.aborted)return;let z={jsonrpc:"2.0",id:w.id,error:{code:Number.isSafeInteger(H.code)?H.code:i.InternalError,message:H.message??"Internal error",...H.data!==void 0&&{data:H.data}}};if(Q&&this._taskMessageQueue)await this._enqueueTaskMessage(Q,{type:"error",message:z,timestamp:Date.now()},W?.sessionId);else await W?.send(z)}).catch((H)=>this._onerror(Error(`Failed to send response: ${H}`))).finally(()=>{this._requestHandlerAbortControllers.delete(w.id)})}_onprogress(w){let{progressToken:b,...$}=w.params,W=Number(b),Q=this._progressHandlers.get(W);if(!Q){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(w)}`));return}let X=this._responseHandlers.get(W),J=this._timeoutInfo.get(W);if(J&&X&&J.resetTimeoutOnProgress)try{this._resetTimeout(W)}catch(G){this._responseHandlers.delete(W),this._progressHandlers.delete(W),this._cleanupTimeout(W),X(G);return}Q($)}_onresponse(w){let b=Number(w.id),$=this._requestResolvers.get(b);if($){if(this._requestResolvers.delete(b),c0(w))$(w);else{let X=new u(w.error.code,w.error.message,w.error.data);$(X)}return}let W=this._responseHandlers.get(b);if(W===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(w)}`));return}this._responseHandlers.delete(b),this._cleanupTimeout(b);let Q=!1;if(c0(w)&&w.result&&typeof w.result==="object"){let X=w.result;if(X.task&&typeof X.task==="object"){let J=X.task;if(typeof J.taskId==="string")Q=!0,this._taskProgressTokens.set(J.taskId,b)}}if(!Q)this._progressHandlers.delete(b);if(c0(w))W(w);else{let X=u.fromError(w.error.code,w.error.message,w.error.data);W(X)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(w,b,$){let{task:W}=$??{};if(!W){try{yield{type:"result",result:await this.request(w,b,$)}}catch(X){yield{type:"error",error:X instanceof u?X:new u(i.InternalError,String(X))}}return}let Q;try{let X=await this.request(w,w0,$);if(X.task)Q=X.task.taskId,yield{type:"taskCreated",task:X.task};else throw new u(i.InternalError,"Task creation did not return a task");while(!0){let J=await this.getTask({taskId:Q},$);if(yield{type:"taskStatus",task:J},q1(J.status)){if(J.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:Q},b,$)};else if(J.status==="failed")yield{type:"error",error:new u(i.InternalError,`Task ${Q} failed`)};else if(J.status==="cancelled")yield{type:"error",error:new u(i.InternalError,`Task ${Q} was cancelled`)};return}if(J.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:Q},b,$)};return}let G=J.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((Y)=>setTimeout(Y,G)),$?.signal?.throwIfAborted()}}catch(X){yield{type:"error",error:X instanceof u?X:new u(i.InternalError,String(X))}}}request(w,b,$){let{relatedRequestId:W,resumptionToken:Q,onresumptiontoken:X,task:J,relatedTask:G}=$??{};return new Promise((Y,H)=>{let z=(P)=>{H(P)};if(!this._transport){z(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(w.method),J)this.assertTaskCapability(w.method)}catch(P){z(P);return}$?.signal?.throwIfAborted();let D=this._requestMessageId++,A={...w,jsonrpc:"2.0",id:D};if($?.onprogress)this._progressHandlers.set(D,$.onprogress),A.params={...w.params,_meta:{...w.params?._meta||{},progressToken:D}};if(J)A.params={...A.params,task:J};if(G)A.params={...A.params,_meta:{...A.params?._meta||{},[j1]:G}};let L=(P)=>{this._responseHandlers.delete(D),this._progressHandlers.delete(D),this._cleanupTimeout(D),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:D,reason:String(P)}},{relatedRequestId:W,resumptionToken:Q,onresumptiontoken:X}).catch((S)=>this._onerror(Error(`Failed to send cancellation: ${S}`)));let k=P instanceof u?P:new u(i.RequestTimeout,String(P));H(k)};this._responseHandlers.set(D,(P)=>{if($?.signal?.aborted)return;if(P instanceof Error)return H(P);try{let k=V1(b,P.result);if(!k.success)H(k.error);else Y(k.data)}catch(k){H(k)}}),$?.signal?.addEventListener("abort",()=>{L($?.signal?.reason)});let F=$?.timeout??HA,V=()=>L(u.fromError(i.RequestTimeout,"Request timed out",{timeout:F}));this._setupTimeout(D,F,$?.maxTotalTimeout,V,$?.resetTimeoutOnProgress??!1);let q=G?.taskId;if(q){let P=(k)=>{let S=this._responseHandlers.get(D);if(S)S(k);else this._onerror(Error(`Response handler missing for side-channeled request ${D}`))};this._requestResolvers.set(D,P),this._enqueueTaskMessage(q,{type:"request",message:A,timestamp:Date.now()}).catch((k)=>{this._cleanupTimeout(D),H(k)})}else this._transport.send(A,{relatedRequestId:W,resumptionToken:Q,onresumptiontoken:X}).catch((P)=>{this._cleanupTimeout(D),H(P)})})}async getTask(w,b){return this.request({method:"tasks/get",params:w},W6,b)}async getTaskResult(w,b,$){return this.request({method:"tasks/result",params:w},b,$)}async listTasks(w,b){return this.request({method:"tasks/list",params:w},J6,b)}async cancelTask(w,b){return this.request({method:"tasks/cancel",params:w},aX,b)}async notification(w,b){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(w.method);let $=b?.relatedTask?.taskId;if($){let J={...w,jsonrpc:"2.0",params:{...w.params,_meta:{...w.params?._meta||{},[j1]:b.relatedTask}}};await this._enqueueTaskMessage($,{type:"notification",message:J,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(w.method)&&!w.params&&!b?.relatedRequestId&&!b?.relatedTask){if(this._pendingDebouncedNotifications.has(w.method))return;this._pendingDebouncedNotifications.add(w.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(w.method),!this._transport)return;let J={...w,jsonrpc:"2.0"};if(b?.relatedTask)J={...J,params:{...J.params,_meta:{...J.params?._meta||{},[j1]:b.relatedTask}}};this._transport?.send(J,b).catch((G)=>this._onerror(G))});return}let X={...w,jsonrpc:"2.0"};if(b?.relatedTask)X={...X,params:{...X.params,_meta:{...X.params?._meta||{},[j1]:b.relatedTask}}};await this._transport.send(X,b)}setRequestHandler(w,b){let $=Z$(w);this.assertRequestHandlerCapability($),this._requestHandlers.set($,(W,Q)=>{let X=M$(w,W);return Promise.resolve(b(X,Q))})}removeRequestHandler(w){this._requestHandlers.delete(w)}assertCanSetRequestHandler(w){if(this._requestHandlers.has(w))throw Error(`A request handler for ${w} already exists, which would be overridden`)}setNotificationHandler(w,b){let $=Z$(w);this._notificationHandlers.set($,(W)=>{let Q=M$(w,W);return Promise.resolve(b(Q))})}removeNotificationHandler(w){this._notificationHandlers.delete(w)}_cleanupTaskProgressHandler(w){let b=this._taskProgressTokens.get(w);if(b!==void 0)this._progressHandlers.delete(b),this._taskProgressTokens.delete(w)}async _enqueueTaskMessage(w,b,$){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(w,b,$,W)}async _clearTaskQueue(w,b){if(this._taskMessageQueue){let $=await this._taskMessageQueue.dequeueAll(w,b);for(let W of $)if(W.type==="request"&&b$(W.message)){let Q=W.message.id,X=this._requestResolvers.get(Q);if(X)X(new u(i.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(Q);else this._onerror(Error(`Resolver missing for request ${Q} during task ${w} cleanup`))}}}async _waitForTaskUpdate(w,b){let $=this._options?.defaultTaskPollInterval??1000;try{let W=await this._taskStore?.getTask(w);if(W?.pollInterval)$=W.pollInterval}catch{}return new Promise((W,Q)=>{if(b.aborted){Q(new u(i.InvalidRequest,"Request cancelled"));return}let X=setTimeout(W,$);b.addEventListener("abort",()=>{clearTimeout(X),Q(new u(i.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(w,b){let $=this._taskStore;if(!$)throw Error("No task store configured");return{createTask:async(W)=>{if(!w)throw Error("No request provided");return await $.createTask(W,w.id,{method:w.method,params:w.params},b)},getTask:async(W)=>{let Q=await $.getTask(W,b);if(!Q)throw new u(i.InvalidParams,"Failed to retrieve task: Task not found");return Q},storeTaskResult:async(W,Q,X)=>{await $.storeTaskResult(W,Q,X,b);let J=await $.getTask(W,b);if(J){let G=n0.parse({method:"notifications/tasks/status",params:J});if(await this.notification(G),q1(J.status))this._cleanupTaskProgressHandler(W)}},getTaskResult:(W)=>{return $.getTaskResult(W,b)},updateTaskStatus:async(W,Q,X)=>{let J=await $.getTask(W,b);if(!J)throw new u(i.InvalidParams,`Task "${W}" not found - it may have been cleaned up`);if(q1(J.status))throw new u(i.InvalidParams,`Cannot update task "${W}" from terminal status "${J.status}" to "${Q}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await $.updateTaskStatus(W,Q,X,b);let G=await $.getTask(W,b);if(G){let Y=n0.parse({method:"notifications/tasks/status",params:G});if(await this.notification(Y),q1(G.status))this._cleanupTaskProgressHandler(W)}},listTasks:(W)=>{return $.listTasks(W,b)}}}}function JJ(w){return w!==null&&typeof w==="object"&&!Array.isArray(w)}function GJ(w,b){let $={...w};for(let W in b){let Q=W,X=b[Q];if(X===void 0)continue;let J=$[Q];if(JJ(J)&&JJ(X))$[Q]={...J,...X};else $[Q]=X}return $}var fH=zW(U9(),1),uH=zW(yH(),1);function OV(){let w=new fH.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return uH.default(w),w}class I9{constructor(w){this._ajv=w??OV()}getValidator(w){let b="$id"in w&&typeof w.$id==="string"?this._ajv.getSchema(w.$id)??this._ajv.compile(w):this._ajv.compile(w);return($)=>{if(b($))return{valid:!0,data:$,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(b.errors)}}}}class N9{constructor(w){this._server=w}requestStream(w,b,$){return this._server.requestStream(w,b,$)}async getTask(w,b){return this._server.getTask({taskId:w},b)}async getTaskResult(w,b,$){return this._server.getTaskResult({taskId:w},b,$)}async listTasks(w,b){return this._server.listTasks(w?{cursor:w}:void 0,b)}async cancelTask(w,b){return this._server.cancelTask({taskId:w},b)}}function cH(w,b,$){if(!w)throw Error(`${$} does not support task creation (required for ${b})`);switch(b){case"tools/call":if(!w.tools?.call)throw Error(`${$} does not support task creation for tools/call (required for ${b})`);break;default:break}}function mH(w,b,$){if(!w)throw Error(`${$} does not support task creation (required for ${b})`);switch(b){case"sampling/createMessage":if(!w.sampling?.createMessage)throw Error(`${$} does not support task creation for sampling/createMessage (required for ${b})`);break;case"elicitation/create":if(!w.elicitation?.create)throw Error(`${$} does not support task creation for elicitation/create (required for ${b})`);break;default:break}}class E9 extends V${constructor(w,b){super(b);if(this._serverInfo=w,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(o0.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=b?.capabilities??{},this._instructions=b?.instructions,this._jsonSchemaValidator=b?.jsonSchemaValidator??new I9,this.setRequestHandler(Q$,($)=>this._oninitialize($)),this.setNotificationHandler(X$,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(U$,async($,W)=>{let Q=W.sessionId||W.requestInfo?.headers["mcp-session-id"]||void 0,{level:X}=$.params,J=o0.safeParse(X);if(J.success)this._loggingLevels.set(Q,J.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new N9(this)};return this._experimental}registerCapabilities(w){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=GJ(this._capabilities,w)}setRequestHandler(w,b){let W=pb(w)?.method;if(!W)throw Error("Schema is missing a method literal");let Q;if(e1(W)){let J=W;Q=J._zod?.def?.value??J.value}else{let J=W;Q=J._def?.value??J.value}if(typeof Q!=="string")throw Error("Schema method literal must be a string");if(Q==="tools/call"){let J=async(G,Y)=>{let H=V1(d0,G);if(!H.success){let L=H.error instanceof Error?H.error.message:String(H.error);throw new u(i.InvalidParams,`Invalid tools/call request: ${L}`)}let{params:z}=H.data,D=await Promise.resolve(b(G,Y));if(z.task){let L=V1(w0,D);if(!L.success){let F=L.error instanceof Error?L.error.message:String(L.error);throw new u(i.InvalidParams,`Invalid task creation result: ${F}`)}return L.data}let A=V1(Y6,D);if(!A.success){let L=A.error instanceof Error?A.error.message:String(A.error);throw new u(i.InvalidParams,`Invalid tools/call result: ${L}`)}return A.data};return super.setRequestHandler(w,J)}return super.setRequestHandler(w,b)}assertCapabilityForMethod(w){switch(w){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${w})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${w})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${w})`);break;case"ping":break}}assertNotificationCapability(w){switch(w){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${w})`);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 ${w})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${w})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${w})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${w})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(w){if(!this._capabilities)return;switch(w){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${w})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${w})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${w})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${w})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${w})`);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 ${w})`);break;case"ping":case"initialize":break}}assertTaskCapability(w){mH(this._clientCapabilities?.tasks?.requests,w,"Client")}assertTaskHandlerCapability(w){if(!this._capabilities)return;cH(this._capabilities.tasks?.requests,w,"Server")}async _oninitialize(w){let b=w.params.protocolVersion;return this._clientCapabilities=w.params.capabilities,this._clientVersion=w.params.clientInfo,{protocolVersion:iX.includes(b)?b:a4,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"},eb)}async createMessage(w,b){if(w.tools||w.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if(w.messages.length>0){let $=w.messages[w.messages.length-1],W=Array.isArray($.content)?$.content:[$.content],Q=W.some((Y)=>Y.type==="tool_result"),X=w.messages.length>1?w.messages[w.messages.length-2]:void 0,J=X?Array.isArray(X.content)?X.content:[X.content]:[],G=J.some((Y)=>Y.type==="tool_use");if(Q){if(W.some((Y)=>Y.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!G)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(G){let Y=new Set(J.filter((z)=>z.type==="tool_use").map((z)=>z.id)),H=new Set(W.filter((z)=>z.type==="tool_result").map((z)=>z.toolUseId));if(Y.size!==H.size||![...Y].every((z)=>H.has(z)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if(w.tools)return this.request({method:"sampling/createMessage",params:w},K$,b);return this.request({method:"sampling/createMessage",params:w},F$,b)}async elicitInput(w,b){switch(w.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let W=w;return this.request({method:"elicitation/create",params:W},H6,b)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let W=w.mode==="form"?w:{...w,mode:"form"},Q=await this.request({method:"elicitation/create",params:W},H6,b);if(Q.action==="accept"&&Q.content&&W.requestedSchema)try{let J=this._jsonSchemaValidator.getValidator(W.requestedSchema)(Q.content);if(!J.valid)throw new u(i.InvalidParams,`Elicitation response content does not match requested schema: ${J.errorMessage}`)}catch(X){if(X instanceof u)throw X;throw new u(i.InternalError,`Error validating elicitation response: ${X instanceof Error?X.message:String(X)}`)}return Q}}}createElicitationCompletionNotifier(w,b){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:w}},b)}async listRoots(w,b){return this.request({method:"roots/list",params:w},O$,b)}async sendLoggingMessage(w,b){if(this._capabilities.logging){if(!this.isMessageIgnored(w.level,b))return this.notification({method:"notifications/message",params:w})}}async sendResourceUpdated(w){return this.notification({method:"notifications/resources/updated",params:w})}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 lH={name:"@sequenzy/mcp",version:"0.0.142",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 T9=["product-info","domain","tracking","localization","integrations","products","events","tags","labels","goals","sync-rules","api-keys","widgets","team","danger"],gH={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 MV(w){let $=(w??process.env.SEQUENZY_APP_URL??"https://sequenzy.com").trim().replace(/\/+$/,"");return $.length>0?$:"https://sequenzy.com"}function ow(w){let b=w?.trim();return b?b:void 0}function b1(w){return encodeURIComponent(w)}function Bw(w,b){return`${w}${b}`}function Dw(w,b=""){return`/dashboard/company/${b1(w)}${b}`}function iH(w,b,$){return Bw(w,`${Dw(b,"/settings")}?tab=${encodeURIComponent($)}`)}function VV(w,b){let $=T9.map((W)=>[W,b?iH(w,b,W):""]);return Object.fromEntries($)}function D1(w={},b){let $=MV(b),W=ow(w.companyId),Q={},X=VV($,W);if(!W)return{appUrl:$,routeTemplates:gH,settingsTabValues:T9,urls:Q,settingsUrls:X};Q.dashboard=Bw($,Dw(W)),Q.campaigns=Bw($,Dw(W,"/campaign")),Q.landingPages=Bw($,Dw(W,"/landing-pages")),Q.sequences=Bw($,Dw(W,"/sequences")),Q.settings=Bw($,Dw(W,"/settings")),Q.emails=Bw($,Dw(W,"/emails")),Q.subscribers=Bw($,Dw(W,"/subscribers")),Q.sentEmails=Bw($,Dw(W,"/sent-emails")),Q.segments=Bw($,Dw(W,"/segments")),Q.metrics=Bw($,Dw(W,"/metrics")),Q.transactional=Bw($,Dw(W,"/transactional"));let J=ow(w.campaignId);if(J)Q.campaign=Bw($,Dw(W,`/campaign/${b1(J)}`)),Q.campaignPreview=`${Q.campaign}?step=review`;let G=ow(w.landingPageId);if(G)Q.landingPage=Bw($,Dw(W,`/landing-pages/${b1(G)}`));let Y=ow(w.sequenceId);if(Y)Q.sequence=Bw($,Dw(W,`/sequences/${b1(Y)}`));let H=ow(w.emailId)??ow(w.templateId);if(H)Q.email=Bw($,Dw(W,`/emails/${b1(H)}`)),Q.template=Q.email;let z=ow(w.transactionalId);if(z)Q.transactionalEmail=Bw($,Dw(W,`/transactional/${b1(z)}`));let D=ow(w.emailSendId);if(D)Q.emailSend=Bw($,Dw(W,`/sent-emails/${b1(D)}`));let A=ow(w.domainId);if(A)Q.domain=Bw($,Dw(W,`/settings/domain/${b1(A)}`)),Q.domainVerify=`${Q.domain}/verify`;let L=ow(w.status);if(L)Q.campaignList=Bw($,Dw(W,`/campaign/list/${b1(L)}`)),Q.sequenceList=Bw($,Dw(W,`/sequences/list/${b1(L)}`));let F=ow(w.settingsTab);if(F)Q.settingsTab=iH($,W,F);return{appUrl:$,routeTemplates:gH,settingsTabValues:T9,urls:Q,settingsUrls:X}}var nH=[{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 pH(w){try{let b;switch(w){case"sequenzy://dashboard":b=await B("GET","/api/v1/metrics?period=7d");break;case"sequenzy://company":{let $=await B("GET","/api/v1/account"),W=k1()??$.currentCompanyId;if(!W)throw Error("No company available. Create or select a company first.");b=await B("GET",`/api/v1/companies/${W}`);break}case"sequenzy://campaigns/recent":b=await B("GET","/api/v1/campaigns?limit=10");break;case"sequenzy://subscribers/recent":b=await B("GET","/api/v1/subscribers?sort=createdAt&limit=20");break;case"sequenzy://subscribers/engaged":b=await B("GET","/api/v1/subscribers?sort=engagement&limit=20");break;case"sequenzy://sequences":b=await B("GET","/api/v1/sequences");break;case"sequenzy://templates":b=await B("GET","/api/v1/templates");break;case"sequenzy://segments":b=await B("GET","/api/v1/segments");break;case"sequenzy://tags":b=await B("GET","/api/v1/tags");break;case"sequenzy://health":b=await B("GET","/api/v1/health/deliverability");break;case"sequenzy://app-routes":b=D1();break;default:throw Error(`Unknown resource: ${w}`)}return{contents:[{uri:w,mimeType:"application/json",text:JSON.stringify(b,null,2)}]}}catch(b){return{contents:[{uri:w,mimeType:"text/plain",text:d1(b)}]}}}function C(w){return typeof w==="object"&&w!==null&&!Array.isArray(w)}function U(w,b){let $=w[b];if(typeof $!=="string")return;let W=$.trim();return W.length>0?W:void 0}function R9(w,b,$){let W=b[$];if(W===void 0||W===null)return[];if(typeof W==="string"){let X=W.trim();return X.length>0?[X]:[]}if(!Array.isArray(W))throw Error(`\`${$}\` must be an array of strings when calling \`${w}\`.`);let Q=[];return W.forEach((X,J)=>{if(typeof X!=="string")throw Error(`\`${$}\` item ${J+1} must be a string when calling \`${w}\`.`);let G=X.trim();if(G.length>0&&!Q.includes(G))Q.push(G)}),Q}function M(w,b,$){let W=U(b,$);if(W===void 0)throw Error(`\`${$}\` is required when calling \`${w}\`.`);return W}var o6=' Minimal valid core examples: {"type":"heading","content":"Title","level":1}; {"type":"text","content":"<p>Paragraph with <strong>bold</strong></p>","variant":"paragraph"}; {"type":"button","text":"Click Me","url":"https://example.com","variant":"primary"}; {"type":"image","src":"https://...","alt":"Description","width":100,"widthType":"percent","height":240,"objectFit":"cover","href":"https://example.com","align":"center"}. Heading and text use `content`; button uses `text` but also accepts `content` as an alias and defaults `variant` to `primary`. Image `widthType` accepts `percent` or `px`.';var S9=' Any block accepts a `conditions` array so it only renders for matching recipients. To branch on a value passed in transactional `variables` or an automation `event` payload, use { "id": "c1", "field": "variable", "operator": "is", "value": "plan:pro" }; "attribute" uses the same "name:value" form, while "email"/"firstName"/"lastName" use a plain comparison value. Live subscriber fields are "status", "tag", "list", "segment", "event", "emailProvider", "phone", "smsStatus", "added", "stripeProduct", "stripeCurrentProduct", "stripeTrialProduct", "commerceProduct", "commerceCollection", "emailSent", "emailDelivered", "emailOpened", "emailClicked", "emailBounced", and "emailComplained". They use the same field-specific values and operators as segment filters, for example { "id": "c2", "field": "segment", "operator": "is", "value": "seg_123" }, { "id": "c3", "field": "tag", "operator": "contains", "value": "vip" }, or { "id": "c4", "field": "event", "operator": "at_least", "value": "purchase:3:30d" }. Supported operators across fields are is, is_not, contains, not_contains, gt, gte, lt, lte, less_than, more_than, at_least, less_than_count, is_empty, is_not_empty, is_temporary_bounce, and is_permanent_bounce; each field accepts only its segment-filter operators. Recipients without a stored subscriber match use the OTHERWISE branch or hide a conditionally displayed block. For if/else, use a { type: "conditional-group", conditions: [...], ifBranch: { children: [...] }, elseBranch: { children: [...] } } block.',v9=' 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. Set `allowMultiple: true` on a text-only options poll to let recipients pick several answers: answer links then open a hosted selection page where the recipient checks any number of options and saves them in one submit, and `attributeKey` stores the list of selected values (filter with attribute `contains`). Multi-select polls cannot use option images or configurations whose encoded signed links exceed the delivery-safe size limit. 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). `accentColor` recolors every appearance, including "brutal". `optionRadius` sets answer-button corners in px (0 is square) independently of `styles.borderRadius`, while `questionColor` recolors only the question. `fontFamily` applies to the poll; `optionFontSize`, `optionFontWeight`, `optionLetterSpacing`, and `optionTextTransform` style answers, and the matching `questionFontSize`, `questionFontWeight`, `questionLetterSpacing`, and `questionTextTransform` fields style the question. Sizes and spacing are px, weights are 100-900, and transforms are "none" or "uppercase". Optional `confirmationMessage` customizes the hosted thank-you page; set `redirectUrl` only when respondents should land on another page.',C9=' 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" }.',Hw="Raw HTML is stored as one opaque block. Sequenzy preserves that markup but does not add a company logo, branded native sections, or theme-driven block design. Use blocks for editor-native design, or a drafting prompt when you want Sequenzy to compose a new branded email.",t6=' The code is minted per subscriber at run time and reaches every later email in the same sequence as {{discount.code}}. Also available: {{discount.value}} (pre-formatted, e.g. "20% off" or "$10 off"), {{discount.percentOff}}, {{discount.amountOff}}, {{discount.currency}}, and {{date.discount.expiresAt}} (locale-formatted expiry). Present the code with a { "type": "discount-code", "code": "{{discount.code}}", "label": "Your discount code" } block, or inline {{discount.code}} in any text block. These tags resolve only in emails downstream of the discount step; render_email substitutes a clearly fake sample code so the email can be previewed before anyone is enrolled, and lists anything it could not resolve under unresolvedMergeTags.',v1='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`.',k9=" `styles` applies to the block's own container, not to an inner rendered element. On a button block, `styles.backgroundColor` colors the band behind the button and `styles.textColor` does not reach the label - set the top-level `buttonColor` and `buttonTextColor` fields instead, or leave them unset to inherit the email theme's primary color.",l1=" Unsupported fields are discarded and reported in the response `warnings` array rather than rejected.",A1=`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: [...] }.${S9}${k9}${l1}${v9}${C9}${o6}`,r6=" Replacing a step's blocks keeps that step's existing Style > Format rather than the company default: a step that already had a logo or footer gets them back even if you omit them, and every block added that way is listed in the response `warnings`. Pass `emailPreset` to change the format. A step whose stored content is a single raw HTML block has no format, so replacing it with another single raw HTML block is stored exactly as sent; replacing it with native blocks converts the step and does add a footer.",jV=` For action_email:${r6}`,L1=`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\`.${S9}${k9}${l1}${v9}${C9}${o6}`,A0=`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.${S9}${k9}${l1}${v9}${C9}${o6}`,g1="Display name recipients see, e.g. 'Brennon at TradeTally'. Selects the sender identity of that name on fromEmail, creating it when the address has no identity by that name; the mailbox's other display names, and everything pinned to them, are untouched. Requires fromEmail; omit it when using senderProfileId, which already carries its own display name.",i1="Display name for the Reply-To address. Requires replyTo; omit it when using replyProfileId, which already carries its own display name. An address carries one Reply-To name company-wide: if replyTo already has a saved profile under a different name, that saved name is kept and the response `warnings` array says so. Rename it with update_sender_profile (type 'reply') to change it everywhere.",Zb="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.",dH="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.",_9=500,x9=500,kw={type:"boolean",description:"If true, include machine-classified bot/scanner opens and clicks. Defaults to false, so metrics and activity are human-only."},Mb=["send","delivery","bounce","complaint","open","click","unsubscribe","delivery_delay","transport_failure"],Vb=Mb.join(", "),s6={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},qV={type:"object",description:"Offset relative to a wait-until date.",properties:{days:{type:"number"},hours:{type:"number"},minutes:{type:"number"}},additionalProperties:!1},L0={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:qV,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},U0={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},h9={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, emailPreset, isTransactional, attachments ([{ filename, path }] URL-backed files fetched at send time; path may use {{event.*}} from the enrollment event; [] removes them), 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.${jV}`,properties:{emailPreset:{type:"string",enum:["branded","minimal"],description:"For an action_email node with native Sequenzy blocks, set the linked email's per-email Style > Format. Native block emails may include supported custom HTML blocks. Use minimal for a direct text-forward note without the company logo and with the simple footer, or branded to restore branded chrome. This does not change the company-wide default. Not a lossless toggle: minimal deletes standalone logo blocks, so switching back to branded generates a new logo block with a new id and the company name as alt text - send the authored logo block in `blocks` alongside the branded update to keep it. A standalone raw HTML email does not support this field, and emailPreset must not be combined with html/htmlContent."}},additionalProperties:!0},e6={type:"object",properties:{nodeId:{type:"string",description:"Existing node ID from get_sequence.sequence.nodes[].id."},changes:h9,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},F0=["gray","red","orange","amber","yellow","lime","green","emerald","teal","cyan","sky","blue","indigo","violet","purple","fuchsia","pink","rose"],K0=["email.sent","email.delivered","email.delivery_delayed","email.bounced","email.failed","email.complained","email.opened","email.clicked","email.replied","email.unsubscribed","sms.sent","sms.delivered","sms.failed","sms.opted_out","subscriber.invalid","subscriber.created","subscriber.updated","subscriber.unsubscribed","subscriber.list_subscribed","subscriber.list_unsubscribed","sequence.finished","sequence.failed","poll.answered"];var PV=new Set(["get_account","get_app_urls","get_company","get_sync_rules","get_shopify_automation_settings","list_api_keys","list_websites","list_integrations","get_integration","get_integration_pixel","list_integration_capabilities","list_integration_activity","list_sender_profiles","get_notification_preferences","get_tracking_settings","get_sending_status","check_website","get_integration_guide","get_subscriber","get_subscriber_import","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_campaign_audience","render_email","list_email_sends","get_email_send","list_forms","get_form_embed","get_recipient_suppression","list_landing_pages","get_landing_page","list_sequences","get_sequence","list_sequence_enrollments","list_sequence_goals","get_sequence_inbound_webhook","list_transactional_emails","get_transactional_email","get_stats","get_transactional_stats","get_campaign_stats","get_sequence_stats","list_campaign_events","list_sequence_events","list_email_metrics","get_subscriber_activity","list_team_members","list_conversations","get_conversation","list_webhooks","list_webhook_deliveries","generate_email","generate_subject_lines","generate_sms","get_sms_settings"]),IV=new Set(["select_company","create_company","update_company","update_notification_preferences","update_sender_profile","update_tracking_settings","resume_sending","update_sync_rules","update_shopify_automation_settings","connect_integration","set_integration_sync_enabled","sync_integration","activate_integration_pixel","create_api_key","update_api_key","revoke_api_key","delete_api_key","add_sending_domain","add_website","verify_sending_domain","add_subscriber","create_subscriber_import","update_subscriber","add_subscriber_note","remove_subscriber","delete_subscriber_note","trigger_subscriber_event","trigger_subscriber_events","bulk_add_subscriber_tags","bulk_remove_subscriber_tags","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","update_ab_test","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","unschedule_campaign","cancel_campaign","pause_campaign","resume_campaign","delete_campaign","duplicate_campaign","resend_campaign_to_non_openers","create_form","update_form","create_landing_page","update_landing_page","duplicate_landing_page","delete_landing_page","publish_landing_page","unpublish_landing_page","connect_landing_page_domain","update_landing_page_domain_settings","create_sequence","generate_sequence","send_sequence_test_email","update_sequence","update_sequence_node","update_sequence_nodes","edit_sequence_graph","insert_sequence_step","enable_sequence","disable_sequence","duplicate_sequence","archive_sequence","unarchive_sequence","create_sequence_goal","update_sequence_goal","delete_sequence_goal","configure_sequence_inbound_webhook","rotate_sequence_inbound_webhook_secret","pause_sequence_enrollments","resume_sequence_enrollments","enroll_subscribers_in_sequence","cancel_sequence_enrollments","delete_sequence","create_transactional_email","update_transactional_email","delete_transactional_email","send_email","invite_team_member","cancel_team_invitation","reply_to_conversation","update_conversation_status","mark_conversation_read","create_webhook","update_webhook","delete_webhook","test_webhook","replay_webhook_delivery","submit_feedback","remove_recipient_suppression"]),NV=new Set(["send_test_email","send_test_sms","send_sequence_test_email","schedule_campaign","resume_campaign","publish_landing_page","connect_landing_page_domain","update_landing_page_domain_settings","add_sending_domain","add_website","verify_sending_domain","connect_integration","sync_integration","get_integration_pixel","activate_integration_pixel","enable_sequence","unarchive_sequence","resume_sequence_enrollments","send_email","invite_team_member","reply_to_conversation","create_webhook","update_webhook","test_webhook","replay_webhook_delivery","remove_recipient_suppression"]),EV=new Set(["revoke_api_key","delete_api_key","remove_subscriber","delete_subscriber_note","delete_product","remove_product_file","delete_tag","delete_list","remove_subscribers_from_list","bulk_remove_subscriber_tags","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","set_integration_sync_enabled","disable_sequence","archive_sequence","delete_sequence_goal","rotate_sequence_inbound_webhook_secret","edit_sequence_graph","cancel_sequence_enrollments","delete_sequence","cancel_team_invitation","delete_webhook","delete_transactional_email","remove_recipient_suppression"]);function TV(w){let b=PV.has(w),$=IV.has(w);if(b===$)throw Error(`MCP tool "${w}" must be classified as exactly one of read-only or mutating.`);return{readOnlyHint:b,destructiveHint:b?!1:EV.has(w),openWorldHint:NV.has(w)}}function oH(w){return{...w,annotations:{...w.annotations,...TV(w.name)}}}var y9={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","is","is_not"],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"],commerceCollection:["is","is_not","at_least","less_than_count"]},RV=Object.entries(y9).map(([w,b])=>`${w}: ${b.join(", ")}`).join("; "),f9={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","commerceCollection"],description:`Filter field. Use \`email\` with is/is_not for exact, case-insensitive address matching (allowlists and exclusions) and with contains/not_contains for domain or substring matching. 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. Use \`commerceCollection\` to segment on anyone who bought ANY product in a store collection - the value is the collection id or handle (e.g. \`skincare\`), optionally provider-prefixed and/or with an order-count threshold (\`shopify:skincare:2\`); collection membership is resolved from the synced catalog as it stands now, and only Shopify collections and WooCommerce categories are synced. 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. ${v1}`},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: ${RV}.`},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). ${v1}`}},required:["field","operator","value"],additionalProperties:!1},u9={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 a6(w){if(!Array.isArray(w))return w;return w.map((b)=>{if(typeof b!=="object"||b===null)return b;let $=b;if(typeof $.id==="string"&&$.id.trim()!=="")return $;return{...$,id:crypto.randomUUID()}})}function w4(w){if(typeof w!=="object"||w===null)return w;let b=w;if(b.kind==="filter"||"field"in b||"operator"in b||"value"in b){let $=a6([b]);return Array.isArray($)?$[0]:b}if(b.kind!=="group")return w;return{...b,id:typeof b.id==="string"&&b.id.trim()!==""?b.id:crypto.randomUUID(),children:Array.isArray(b.children)?b.children.map(w4):[]}}function SV(w){let b=w.indexOf(":");return b!==-1&&w.substring(0,b).trim().length>0}function vV(w){let b=w.indexOf(":");return b!==-1&&w.substring(b+1).trim().length>0}function tH(w){if(w==="all")return!0;let b=w.match(/^(\d+)d$/);if(!b?.[1])return!1;let $=Number.parseInt(b[1],10);return Number.isInteger($)&&$>0}function CV(w,b){let $=b.split(":");if(w==="at_least"||w==="less_than_count"){if($.length<3)return'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".';let X=$.slice(0,-2).join(":").trim(),J=$.at(-2),G=$.at(-1),Y=J===void 0?Number.NaN:Number.parseInt(J,10);return X&&Number.isInteger(Y)&&Y>0&&G!==void 0&&tH(G)?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&&tH(Q)?null:'Event filters must use "eventName:timeRange", like "saas.purchase:30d".'}function kV(w){let b=w.indexOf(":");if(b===-1)return{productId:w,subfilter:null,rawValue:null};let $=w.substring(0,b),W=w.substring(b+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 _V(w){return w.trim().toLowerCase().replace(/[-\s]+/g,"_")}function xV(w){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(w)}function hV(w,b){if(b==="cancels_at"||b==="cancel_at"||b==="cancellation_at")return!0;if(w==="stripeCurrentProduct")return["end_at","ends_at","period_end","period_ends_at","current_period_end"].includes(b);return["start_at","started_at","trial_start","trial_started_at","end_at","ends_at","trial_end","trial_ends_at"].includes(b)}function yV(w){return["is","is_not","gte","lte","gt","lt"].includes(w)}function fV(w,b,$){if(w==="stripeProduct"){if(b!=="at_least"&&b!=="less_than_count")return null;let G=$.indexOf(":");if(G===-1)return null;let Y=$.substring(0,G).trim(),H=Number.parseInt($.substring(G+1).trim(),10);return Y&&Number.isInteger(H)&&H>=1?null:'Stripe Product threshold filters must use "productId:count" with a count of at least 1.'}if(w!=="stripeCurrentProduct"&&w!=="stripeTrialProduct")return null;let{productId:W,subfilter:Q,rawValue:X}=kV($);if(!W.trim())return"Stripe product filters must include a product ID.";if(!Q)return b==="is"||b==="is_not"?null:'Stripe current/trial date filters must use "productId:dateField:value".';let J=_V(Q);if(xV(J))return b==="is"||b==="is_not"?null:"Stripe cancellation flag filters only support is and is_not operators.";if(!hV(w,J))return`Unsupported Stripe product subfilter "${Q}".`;if(!yV(b))return"Stripe date filters only support is, is_not, gte, lte, gt, and lt operators.";return X?.trim()?null:'Stripe date filters must include a value like "productId:end_at:2026-05-26".'}var rH=new Set(["shopify","woocommerce","api"]);function uV(w,b){let $=b.trim(),W=$.indexOf(":");if(W!==-1&&rH.has($.substring(0,W).trim()))$=$.substring(W+1).trim();if(!$)return'Purchased Product filters must include a product ID, like "shopify:42".';if(w!=="at_least"&&w!=="less_than_count")return null;let Q=$.lastIndexOf(":");if(Q===-1)return null;let X=$.substring(0,Q).trim(),J=Number.parseInt($.substring(Q+1).trim(),10);return X&&Number.isInteger(J)&&J>=1?null:'Purchased Product threshold filters must use "provider:productId:count" with a count of at least 1.'}function cV(w,b){let $=b.trim(),W=$.indexOf(":");if(W!==-1&&rH.has($.substring(0,W).trim()))$=$.substring(W+1).trim();if(!$)return'Purchased Collection filters must include a collection, like "shopify:summer-sale".';if(w!=="at_least"&&w!=="less_than_count")return null;let Q=$.lastIndexOf(":");if(Q===-1)return null;let X=$.substring(0,Q).trim(),J=Number.parseInt($.substring(Q+1).trim(),10);return X&&Number.isInteger(J)&&J>=1?null:'Purchased Collection threshold filters must use "provider:collection:count" with a count of at least 1.'}function mV(w){let b;try{b=JSON.parse(w)}catch{return`Poll response filters must use valid JSON. ${v1}`}if(!C(b)||b.v!==1||typeof b.campaignId!=="string"||!b.campaignId.trim()||typeof b.blockId!=="string"||!b.blockId.trim()||!C(b.match))return`Poll response filter context is invalid. ${v1}`;let $=b.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. ${v1}`}function b4(w){if(typeof w!=="object"||w===null)return"Segment filters must be objects.";let b=w,$=b.field,W=b.operator,Q=b.value;if(typeof $!=="string"||!($ in y9))return`Unsupported segment filter field "${String($)}".`;if(typeof W!=="string")return`Segment filter "${$}" must include an operator.`;let X=y9[$];if(!X.includes(W))return`Operator "${W}" is not supported for ${$} filters. Use one of: ${X.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(!SV(Q))return'Attribute filters must use "attributeName:value" or "attributeName:" for empty checks.';if(W!=="is_empty"&&W!=="is_not_empty"&&!vV(Q))return'Attribute filters must include a value after "attributeName:".'}if($==="event"&&typeof Q==="string"){let J=CV(W,Q);if(J)return J}if($==="pollResponse"&&typeof Q==="string"){let J=mV(Q);if(J)return J}if(($==="stripeProduct"||$==="stripeCurrentProduct"||$==="stripeTrialProduct")&&typeof Q==="string"){let J=fV($,W,Q);if(J)return J}if($==="commerceProduct"&&typeof Q==="string"){let J=uV(W,Q);if(J)return J}if($==="commerceCollection"&&typeof Q==="string"){let J=cV(W,Q);if(J)return J}if($==="tag"&&(W==="contains"||W==="not_contains")){if(!(typeof Q==="string"&&Q.split(",").map((G)=>G.trim()).some(Boolean)))return"Tag filters must include at least one tag name."}return null}function $4(w){if(typeof w!=="object"||w===null)return[];let b=w;if(b.kind==="filter"||"field"in b||"operator"in b||"value"in b){let $=b4(b);return $?[$]:[]}if(Array.isArray(b.children))return b.children.flatMap($4);return[]}function _w(w,b,$){if(b.html!==void 0&&b.blocks!==void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${w}\`, not both.`);if(b.blocks!==void 0&&!Array.isArray(b.blocks))throw Error(`\`blocks\` must be an array when calling \`${w}\`.`);if($?.requireContent&&b.html===void 0&&b.blocks===void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${w}\`.`)}function U1(w,b){if(b.labels===void 0)return;if(!Array.isArray(b.labels))throw Error(`\`labels\` must be an array when calling \`${w}\`.`);if(b.labels.some(($)=>typeof $!=="string"||$.trim().length===0))throw Error(`\`labels\` must contain only non-empty strings when calling \`${w}\`.`)}function aH(w){let b=w.filters!==void 0,$=w.root!==void 0;if(b&&$)throw Error("Provide either `filters` or `root` when calling `create_segment`, not both.");if(!b&&!$)throw Error("Provide either `filters` or `root` when calling `create_segment`.");if(b){if(!Array.isArray(w.filters))throw Error("`filters` must be an array when calling `create_segment`.");if(w.filters.length===0)throw Error("`filters` must include at least one filter when calling `create_segment`.")}if($&&(typeof w.root!=="object"||w.root===null))throw Error("`root` must be an object when calling `create_segment`.");let W=b?w.filters.flatMap((Q)=>{let X=b4(Q);return X?[X]:[]}):$4(w.root);if(W.length>0)throw Error(W[0]??"Invalid segment filter in `create_segment`.")}function w5(w){let b=w.filters!==void 0,$=w.root!==void 0;if(b&&$)throw Error("Provide either `filters` or `root` when calling `update_segment`, not both.");if(w.name===void 0&&w.filterJoinOperator===void 0&&!b&&!$)throw Error("Provide at least one of `name`, `filters`, `root`, or `filterJoinOperator` when calling `update_segment`.");if(b){if(!Array.isArray(w.filters))throw Error("`filters` must be an array when calling `update_segment`.");if(w.filters.length===0)throw Error("`filters` must include at least one filter when calling `update_segment`.")}if($&&(typeof w.root!=="object"||w.root===null))throw Error("`root` must be an object when calling `update_segment`.");let W=b?w.filters.flatMap((Q)=>{let X=b4(Q);return X?[X]:[]}):$?$4(w.root):[];if(W.length>0)throw Error(W[0]??"Invalid segment filter in `update_segment`.")}var c9=["name","description","logoUrl","founderName","primaryColor","brandColors","valueProps","testimonials","toneVoice","companyContext","emailLengthPreference","socialLinks","privacyPolicyUrl","termsUrl","address","language","pricing","fontFamily","emailTheme","emailDirection","senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName","replyTrackingEnabled","replyTrackingDomainMode","forwardReplies"];function m9(w,b,$){if(b[$]!==void 0&&!C(b[$]))throw Error(`\`${$}\` must be an object when calling \`${w}\`.`)}function sH(w,b,$){if(b[$]!==void 0&&!Array.isArray(b[$]))throw Error(`\`${$}\` must be an array when calling \`${w}\`.`)}function b5(w){let b=new Set(["companyId",...c9]),$=Object.keys(w).filter((Q)=>!b.has(Q));if($.length>0)throw Error(`\`update_company\` accepts only editable company settings. Unsupported field${$.length===1?"":"s"}: ${$.map((Q)=>`\`${Q}\``).join(", ")}.`);let W={};for(let Q of c9)if(w[Q]!==void 0)W[Q]=w[Q];if(Object.keys(W).length===0)throw Error(`Provide at least one of ${c9.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","senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName","replyTrackingDomainMode"])if(w[Q]!==void 0&&typeof w[Q]!=="string")throw Error(`\`${Q}\` must be a string when calling \`update_company\`.`);if(m9("update_company",w,"brandColors"),m9("update_company",w,"socialLinks"),m9("update_company",w,"pricing"),w.emailTheme!==void 0&&w.emailTheme!==null&&!C(w.emailTheme))throw Error("`emailTheme` must be an object or null when calling `update_company`.");sH("update_company",w,"valueProps"),sH("update_company",w,"testimonials");for(let Q of["replyTrackingEnabled","forwardReplies"])if(w[Q]!==void 0&&typeof w[Q]!=="boolean")throw Error(`\`${Q}\` must be a boolean when calling \`update_company\`.`);if(w.replyTrackingDomainMode!==void 0&&w.replyTrackingDomainMode!=="sequenzy"&&w.replyTrackingDomainMode!=="custom")throw Error("`replyTrackingDomainMode` must be `sequenzy` or `custom` when calling `update_company`.");if(typeof w.primaryColor==="string"&&!/^#[0-9a-f]{6}$/i.test(w.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 X=w[Q];if(typeof X==="string"&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(X.trim()))throw Error(`\`${Q}\` must be a valid email address when calling \`update_company\`.`)}return W}var l9=["openTrackingEnabled","clickTrackingEnabled","strictBotFilteringEnabled","unsubscribeTrackingEnabled","defaultAttributionWindowHours","doubleOptInEnabled","autoUtmEnabled","autoUtmSettings"],g9=["source","medium","campaign","content","term"];function $5(w){let b=new Set(["companyId",...l9]),$=Object.keys(w).filter((Q)=>!b.has(Q));if($.length>0)throw Error(`\`update_tracking_settings\` accepts only tracking settings. Unsupported field${$.length===1?"":"s"}: ${$.map((Q)=>`\`${Q}\``).join(", ")}. Reply tracking is set with \`update_company\`.`);let W={};for(let Q of l9)if(w[Q]!==void 0)W[Q]=w[Q];if(Object.keys(W).length===0)throw Error(`Provide at least one of ${l9.map((Q)=>`\`${Q}\``).join(", ")} when calling \`update_tracking_settings\`.`);for(let Q of["openTrackingEnabled","clickTrackingEnabled","strictBotFilteringEnabled","unsubscribeTrackingEnabled","doubleOptInEnabled","autoUtmEnabled"])if(w[Q]!==void 0&&typeof w[Q]!=="boolean")throw Error(`\`${Q}\` must be a boolean when calling \`update_tracking_settings\`.`);if(w.defaultAttributionWindowHours!==void 0&&(typeof w.defaultAttributionWindowHours!=="number"||!Number.isInteger(w.defaultAttributionWindowHours)||w.defaultAttributionWindowHours<1||w.defaultAttributionWindowHours>720))throw Error("`defaultAttributionWindowHours` must be a whole number of hours between 1 and 720 when calling `update_tracking_settings`.");if(w.autoUtmSettings!==void 0&&w.autoUtmSettings!==null&&!C(w.autoUtmSettings))throw Error("`autoUtmSettings` must be an object or null when calling `update_tracking_settings`.");if(C(w.autoUtmSettings)){let Q=w.autoUtmSettings,X=Object.keys(Q).filter((J)=>!g9.includes(J));if(X.length>0)throw Error(`\`autoUtmSettings\` accepts only ${g9.map((J)=>`\`${J}\``).join(", ")}. Unsupported: ${X.map((J)=>`\`${J}\``).join(", ")}.`);for(let J of g9){let G=Q[J];if(G!==void 0&&G!==null&&typeof G!=="string")throw Error(`\`autoUtmSettings.${J}\` must be a string or null when calling \`update_tracking_settings\`.`)}}return W}var n9={profileKey:"senderProfileId",emailKey:"fromEmail",nameKey:"fromName",addressLabel:"From"},p9={profileKey:"replyProfileId",emailKey:"replyTo",nameKey:"replyToName",addressLabel:"Reply-To"};function d9(w){let{profileKey:b,emailKey:$,nameKey:W,addressLabel:Q}=w.pair,X=w.args[b]!==void 0,J=w.args[$]!==void 0,G=w.args[W]!==void 0,Y=w.location?`for ${w.location} when calling \`${w.toolName}\``:`when calling \`${w.toolName}\``,H=`\`${b}\` already sets both the ${Q} address and the display name, so send it without \`${$}\`${w.nameIsOverride?"":` and \`${W}\``}.`;if(X&&J){let[z,D]=w.profileFirst?[b,$]:[$,b];throw Error(`Provide either \`${z}\` or \`${D}\` ${Y}, not both. ${H}`)}if(X&&G&&!w.nameIsOverride)throw Error(`\`${W}\` cannot be combined with \`${b}\` ${Y}. ${H}`);if(G&&!J&&!w.nameIsOverride)throw Error(`\`${W}\` requires \`${$}\` ${Y}. Send \`${W}\` with the \`${$}\` it names, or send \`${b}\` on its own to use an existing profile's address and name.`)}function O0(w,b,$){let W=$?.replyFirst?[p9,n9]:[n9,p9];for(let Q of W)d9({toolName:w,args:b,pair:Q})}var W5=["senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName"];function lV(w){return W5.some((b)=>w[b]!==void 0)}function gV(w){if(typeof w.nodeType==="string")return w.nodeType==="action_email";return w.type===void 0||w.type==="email"}function W4(w,b,$){for(let W of W5){let Q=$[W];if(Q!==void 0&&typeof Q!=="string")throw Error(`\`${W}\` must be a string for ${b} when calling \`${w}\`.`)}d9({toolName:w,args:$,pair:n9,location:b,profileFirst:!0,nameIsOverride:!0}),d9({toolName:w,args:$,pair:p9,location:b,profileFirst:!0})}function o9(w,b,$){if(lV($)&&!gV($))throw Error(`Sender identity fields are only supported for email steps at ${b} when calling \`${w}\`.`);W4(w,b,$)}function eH(w,b,$){if(!Array.isArray($))return;$.forEach((W,Q)=>{if(C(W))W4(w,`${b}[${Q}]`,W)})}function i9(w,b,$){if(!Array.isArray($))return;$.forEach((W,Q)=>{if(C(W))o9(w,`${b}[${Q}]`,W)})}function iV(w){if(eH("update_sequence","emails",w.emails),eH("update_sequence","steps",w.steps),C(w.insertSteps))i9("update_sequence","insertSteps.steps",w.insertSteps.steps);if(!C(w.branch))return;if(Array.isArray(w.branch.branches))w.branch.branches.forEach(($,W)=>{if(C($))i9("update_sequence",`branch.branches[${W}].steps`,$.steps)});i9("update_sequence","branch.elseSteps",w.branch.elseSteps)}function Q5(w){U1("update_sequence",w);let b=["listId","tagName","segmentId","stopOnSegmentExit","eventName","propertyFilters","integrationSlug","integrationEventKey","customIntegration","inactiveDays","inactivityBaseline","minCount","timeWindowDays"];if(w.trigger===void 0&&b.some((W)=>w[W]!==void 0))throw Error("Provide `trigger` when replacing sequence trigger configuration with `update_sequence`.");if(O0("update_sequence",w),w.clearEnrollmentFieldPath===!0&&w.enrollmentFieldPath!==void 0)throw Error("Provide either `enrollmentFieldPath` or `clearEnrollmentFieldPath` when calling `update_sequence`, not both.");if(w.clearSendingWindow===!0&&w.sendingWindow!==void 0)throw Error("Provide either `sendingWindow` or `clearSendingWindow` when calling `update_sequence`, not both.");if(w.clearBccEmails===!0&&w.bccEmails!==void 0)throw Error("Provide either `bccEmails` or `clearBccEmails` when calling `update_sequence`, not both.");if(w.branch!==void 0&&w.insertSteps!==void 0)throw Error("Provide either `branch` or `insertSteps` when calling `update_sequence`, not both.");iV(w);let $={...w};if(delete $.clearEnrollmentFieldPath,delete $.clearSendingWindow,delete $.clearBccEmails,w.clearEnrollmentFieldPath===!0)$.enrollmentFieldPath=null;if(w.clearSendingWindow===!0)$.sendingWindow=null;if(w.clearBccEmails===!0)$.bccEmails=null;return $}function nV(w,b){if((b.triggerType??"event")==="event"){if(typeof b.triggerEventName!=="string"||b.triggerEventName.trim().length===0)throw Error(`\`triggerEventName\` is required when calling \`${w}\` with an event goal (the default \`triggerType\`).`);return}if(typeof b.attributePath!=="string"||b.attributePath.trim().length===0)throw Error(`\`attributePath\` is required when calling \`${w}\` with \`triggerType: "attribute_change"\`.`);let W=b.attributeCondition??"changed",Q=typeof b.attributeValue==="string"&&b.attributeValue.trim().length>0,X=typeof b.attributePreviousValue==="string"&&b.attributePreviousValue.trim().length>0;if((W==="changed_to"||W==="changed_from_to")&&!Q)throw Error(`\`attributeValue\` is required when calling \`${w}\` with \`attributeCondition\` \`changed_to\` or \`changed_from_to\`.`);if(W==="changed_from_to"&&!X)throw Error(`\`attributePreviousValue\` is required when calling \`${w}\` with \`attributeCondition: "changed_from_to"\`.`)}function X5(w){nV("create_sequence_goal",w)}function J5(w){if(typeof w.triggerEventName==="string"&&w.triggerEventName.trim().length===0)throw Error("`triggerEventName` must be a non-empty string when provided to `update_sequence_goal`.");if(typeof w.attributePath==="string"&&w.attributePath.trim().length===0)throw Error("`attributePath` must be a non-empty string when provided to `update_sequence_goal`.")}function Y5(w,b,$){let W=M(w,b,"nodeId");if(!C(b.changes)||Object.keys(b.changes).length===0)throw Error(`\`changes\` must be a non-empty object for ${$} when calling \`${w}\`.`);let Q=M(w,b,"expectedUpdatedAt");return{nodeId:W,changes:b.changes,expectedUpdatedAt:Q}}function H5(w){let b=Y5("update_sequence_node",w,"the node update");return{...w.confirmLiveChange!==void 0&&{confirmLiveChange:w.confirmLiveChange},nodeUpdates:[b]}}function z5(w){if(!Array.isArray(w.updates)||w.updates.length===0)throw Error("`updates` must be a non-empty array when calling `update_sequence_nodes`.");let b=new Set,$=w.updates.map((W,Q)=>{if(!C(W))throw Error(`\`updates[${Q}]\` must be an object when calling \`update_sequence_nodes\`.`);let X=Y5("update_sequence_nodes",W,`updates[${Q}]`),J=String(X.nodeId);if(b.has(J))throw Error(`\`updates[${Q}]\` targets duplicate nodeId '${J}' when calling \`update_sequence_nodes\`.`);return b.add(J),X});return{...w.confirmLiveChange!==void 0&&{confirmLiveChange:w.confirmLiveChange},nodeUpdates:$}}function B5(w){let b=M("edit_sequence_graph",w,"action"),$=M("edit_sequence_graph",w,"graphRevision");if(!new Set(["move_node","delete_node","duplicate_node","replace_edges"]).has(b))throw Error("`action` must be `move_node`, `delete_node`, `duplicate_node`, or `replace_edges` when calling `edit_sequence_graph`.");let Q=U(w,"nodeId"),X=U(w,"afterNodeId"),J=U(w,"beforeNodeId"),G=w.edges;if(b!=="replace_edges"&&!Q)throw Error(`\`nodeId\` is required for ${b} when calling \`edit_sequence_graph\`.`);if(b==="replace_edges"&&Q)throw Error("`nodeId` is not used with `replace_edges` when calling `edit_sequence_graph`.");let Y=b==="move_node"||b==="duplicate_node";if(Y&&(X?1:0)+(J?1:0)!==1)throw Error(`Provide exactly one of \`afterNodeId\` or \`beforeNodeId\` for ${b} when calling \`edit_sequence_graph\`.`);if(!Y&&(X||J))throw Error(`\`afterNodeId\` and \`beforeNodeId\` are not used with ${b} when calling \`edit_sequence_graph\`.`);if((b==="replace_edges"||b==="delete_node"&&G!==void 0)&&(!Array.isArray(G)||G.length===0))throw Error(`\`edges\` must contain the complete replacement topology for ${b} when calling \`edit_sequence_graph\`.`);if((b==="move_node"||b==="duplicate_node")&&G!==void 0)throw Error(`\`edges\` is not used with ${b} when calling \`edit_sequence_graph\`.`);let H=Array.isArray(G)?G.map((z,D)=>{if(!C(z))throw Error(`\`edges\` item ${D+1} must be an object when calling \`edit_sequence_graph\`.`);let A=M("edit_sequence_graph",z,"sourceNodeId"),L=M("edit_sequence_graph",z,"targetNodeId");if(z.condition!==void 0&&z.condition!==null&&!C(z.condition))throw Error(`\`edges\` item ${D+1} \`condition\` must be an object when calling \`edit_sequence_graph\`.`);return{sourceNodeId:A,targetNodeId:L,...C(z.condition)?{condition:z.condition}:{}}}):void 0;return{...w.confirmStructuralChange!==void 0&&{confirmStructuralChange:w.confirmStructuralChange},graphEdit:{action:b,expectedRevision:$,...Q?{nodeId:Q}:{},...X?{afterNodeId:X}:{},...J?{beforeNodeId:J}:{},...H?{edges:H}:{}}}}function D5(w){let b=U(w,"type")??"email";if(!new Set(["email","sms","delay","create_discount","update_subscriber","condition","add_tag","remove_tag","add_to_list","remove_from_list","webhook","logic_wait_for_event","logic_branch"]).has(b))throw Error("`type` is not a supported dashboard sequence step when calling `insert_sequence_step`.");if(b==="logic_wait_for_event"){let J=M("insert_sequence_step",w,"eventName"),G=w.timeoutDays,Y=G===void 0?7:G;if(typeof Y!=="number"||!Number.isInteger(Y)||Y<1||Y>365)throw Error("`timeoutDays` must be a whole number from 1 to 365 when inserting `logic_wait_for_event` with `insert_sequence_step`.");let H=U(w,"timeoutAction")??"continue";if(H!=="continue"&&H!=="exit")throw Error("`timeoutAction` must be `continue` or `exit` when inserting `logic_wait_for_event` with `insert_sequence_step`.");let z={steps:[{nodeType:"logic_wait_for_event",config:{label:U(w,"label")??`Wait for ${J}`,eventName:J,timeoutDays:Y,timeoutAction:H}}]},D=U(w,"afterNodeId");if(D)z.afterNodeId=D;return{...w.confirmStructuralChange!==void 0&&{confirmStructuralChange:w.confirmStructuralChange},insertSteps:z}}if(b==="logic_branch"){let J=M("insert_sequence_step",w,"afterNodeId");if(!Array.isArray(w.branches)||w.branches.length===0)throw Error("`branches` must contain at least one typed condition when inserting `logic_branch` with `insert_sequence_step`.");let G=new Set(["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"]),Y=["id","label","conditionType","tagName","tagId","listId","segmentId","segmentName","eventName","linkUrl","activityScope","fieldName","fieldValue","targetNodeId","steps"],H=w.allowEmptyPaths===!0,z=w.branches.map((L,F)=>{if(!C(L))throw Error(`\`branches[${F}]\` must be an object when calling \`insert_sequence_step\`.`);let V=M("insert_sequence_step",L,"conditionType");if(!G.has(V))throw Error(`\`branches[${F}].conditionType\` is not supported when calling \`insert_sequence_step\`.`);let q=`branches[${F}]`;if((V==="has_tag"||V==="does_not_have_tag")&&!U(L,"tagId")&&!U(L,"tagName"))throw Error(`\`${q}\` must provide \`tagId\` or \`tagName\` for ${V} when calling \`insert_sequence_step\`.`);if(V==="in_list"&&!U(L,"listId"))throw Error(`\`${q}.listId\` is required for in_list when calling \`insert_sequence_step\`.`);if(V==="in_segment"&&!U(L,"segmentId"))throw Error(`\`${q}.segmentId\` is required for in_segment when calling \`insert_sequence_step\`.`);if(V==="event_received"&&!U(L,"eventName"))throw Error(`\`${q}.eventName\` is required for event_received when calling \`insert_sequence_step\`.`);if(V.startsWith("field_")&&(!U(L,"fieldName")||!U(L,"fieldValue")))throw Error(`\`${q}\` must provide \`fieldName\` and \`fieldValue\` for ${V} when calling \`insert_sequence_step\`.`);if(L.steps!==void 0&&!Array.isArray(L.steps))throw Error(`\`branches[${F}].steps\` must be an array when calling \`insert_sequence_step\`.`);let P=U(L,"targetNodeId"),k=Array.isArray(L.steps)&&L.steps.length>0;if(!P&&!k&&!H)throw Error(`\`branches[${F}]\` must provide \`targetNodeId\` or non-empty \`steps\` when inserting \`logic_branch\` with \`insert_sequence_step\`.`);return Object.fromEntries(Y.flatMap((S)=>L[S]===void 0?[]:[[S,L[S]]]))});if(w.elseSteps!==void 0&&!Array.isArray(w.elseSteps))throw Error("`elseSteps` must be an array when calling `insert_sequence_step`.");let D=U(w,"elseTargetNodeId"),A=Array.isArray(w.elseSteps)&&w.elseSteps.length>0;if(!D&&!A&&!H)throw Error("Provide `elseTargetNodeId` or non-empty `elseSteps` when inserting `logic_branch` with `insert_sequence_step`.");return{...w.confirmStructuralChange!==void 0&&{confirmStructuralChange:w.confirmStructuralChange},branch:{afterNodeId:J,...U(w,"label")?{label:U(w,"label")}:{},branches:z,...Array.isArray(w.elseSteps)?{elseSteps:w.elseSteps}:{},...D?{elseTargetNodeId:D}:{},...H?{allowEmptyPaths:!0}:{}}}}if(b==="delay"||b==="create_discount"||b==="update_subscriber"||b==="condition"||b==="add_tag"||b==="remove_tag"||b==="add_to_list"||b==="remove_from_list"||b==="webhook"){let J;if(b==="delay"){J={type:"delay"};for(let H of["delay","delayMs","waitUntil"])if(w[H]!==void 0)J[H]=w[H];if(J.delay===void 0&&J.delayMs===void 0&&J.waitUntil===void 0)throw Error("Provide `delay`, `delayMs`, or `waitUntil` when inserting a delay step.")}else if(b==="create_discount"){J={type:"create_discount"};for(let H of["discount","label","provider","discountType","percentOff","amountOff","currency","duration","durationInMonths","appliesToAllPlans","planIds","codePrefix","maxRedemptions","lockToSubscriber","expiresAt","expiresInHours"])if(w[H]!==void 0)J[H]=w[H]}else if(b==="update_subscriber"){if(!C(w.config))throw Error("`config` is required when inserting an update_subscriber step.");J={type:"update_subscriber",nodeType:"action_update_attributes",config:w.config}}else if(b==="webhook"){let H=U(w,"method")??"POST";if(!["POST","GET","PUT","PATCH","DELETE"].includes(H))throw Error("`method` must be one of POST, GET, PUT, PATCH, or DELETE when inserting a webhook step.");if(w.headers!==void 0&&(!C(w.headers)||Object.values(w.headers).some((L)=>typeof L!=="string")))throw Error("`headers` must be an object with string values when inserting a webhook step.");let z=U(w,"onError");if(z&&!["continue","exit","fail"].includes(z))throw Error("`onError` must be `continue`, `exit`, or `fail` when inserting a webhook step.");if(w.body!==void 0&&typeof w.body!=="string")throw Error("`body` must be a JSON string when inserting a webhook step.");if(w.resultKey!==void 0&&typeof w.resultKey!=="string")throw Error("`resultKey` must be a string when inserting a webhook step.");let D=U(w,"body"),A=U(w,"resultKey");J={type:"webhook",nodeType:"action_webhook",config:{label:U(w,"label")??"Webhook",url:M("insert_sequence_step",w,"url"),method:H,...w.headers!==void 0?{headers:w.headers}:{},...D?{body:D}:{},...A?{resultKey:A}:{},...z?{onError:z}:{}}}}else if(b==="condition"){let H=M("insert_sequence_step",w,"conditionType");if(!new Set(["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"]).has(H))throw Error("`conditionType` is not supported for condition steps.");if((H==="has_tag"||H==="does_not_have_tag")&&!U(w,"tagId")&&!U(w,"tagName"))throw Error("Provide `tagId` or `tagName` for this condition step.");if(H==="in_list"&&!U(w,"listId"))throw Error("`listId` is required for an in_list condition.");if(H==="in_segment"&&!U(w,"segmentId"))throw Error("`segmentId` is required for an in_segment condition.");if(H==="event_received"&&!U(w,"eventName"))throw Error("`eventName` is required for an event_received condition.");if(H.startsWith("field_")&&(!U(w,"fieldName")||!U(w,"fieldValue")))throw Error("`fieldName` and `fieldValue` are required for field conditions.");let D={label:U(w,"label")??"Condition",conditionType:H};for(let A of["tagId","tagName","listId","segmentId","segmentName","eventName","linkUrl","activityScope","fieldName","fieldValue"])if(w[A]!==void 0)D[A]=w[A];J={type:"condition",nodeType:"logic_condition",config:D}}else{let H=b==="add_tag"||b==="remove_tag",z=b==="add_tag"?"action_add_tag":b==="remove_tag"?"action_remove_tag":b==="add_to_list"?"action_add_to_list":"action_remove_from_list",D={label:U(w,"label")??(b==="add_tag"?"Add Tag":b==="remove_tag"?"Remove Tag":b==="add_to_list"?"Add to List":"Remove from List")};if(H){let A=U(w,"tagId"),L=U(w,"tagName");if(!A&&!L)throw Error("Provide `tagId` or `tagName` when inserting a tag action.");if(A)D.tagId=A;if(L)D.tagName=L}else{D.listId=M("insert_sequence_step",w,"listId");let A=U(w,"listName");if(A)D.listName=A}J={nodeType:z,config:D}}for(let H of["delay","delayMs","waitUntil"])if(b!=="delay"&&w[H]!==void 0)J[H]=w[H];let G={steps:[J]},Y=U(w,"afterNodeId");if(Y)G.afterNodeId=Y;return{...w.confirmStructuralChange!==void 0&&{confirmStructuralChange:w.confirmStructuralChange},insertSteps:G}}let W=b==="sms",Q;if(W){o9("insert_sequence_step","SMS step",w);let J=U(w,"text"),G=Array.isArray(w.blocks)&&w.blocks.length>0;if(J===void 0&&!G)throw Error("Provide `text` (or `blocks`) when inserting an SMS step with `insert_sequence_step`.");Q={type:"sms"};for(let Y of["text","blocks","imageUrls","label","name","ineligibleAction","delay","delayMs","waitUntil"])if(w[Y]!==void 0)Q[Y]=w[Y]}else{_w("insert_sequence_step",w,{requireContent:!0}),W4("insert_sequence_step","email step",w),Q={subject:M("insert_sequence_step",w,"subject")};for(let J of["name","previewText","html","blocks","delay","delayMs","waitUntil","senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName","isTransactional","ccEmails","bccEmails","attachments"])if(w[J]!==void 0)Q[J]=w[J]}let X={steps:[Q]};if(w.afterNodeId!==void 0)X.afterNodeId=w.afterNodeId;return{...w.confirmStructuralChange!==void 0&&{confirmStructuralChange:w.confirmStructuralChange},insertSteps:X}}function G5(w,b){let $=w[b];if($===void 0)return[];if(!Array.isArray($))throw Error(`\`${b}\` must be an array when calling \`cancel_sequence_enrollments\`.`);let W=$.map((Q)=>typeof Q==="string"?Q.trim():"").filter((Q)=>Q.length>0);if($.some((Q)=>typeof Q!=="string")||W.length===0)throw Error(`\`${b}\` must contain at least one non-empty string when calling \`cancel_sequence_enrollments\`.`);return W}function A5(w){let b=U(w,"subscriberId"),$=G5(w,"subscriberIds"),W=G5(w,"fieldValues");if(w.cancelAll!==void 0&&typeof w.cancelAll!=="boolean")throw Error("`cancelAll` must be a boolean when calling `cancel_sequence_enrollments`.");let Q=w.cancelAll===!0;if((b!==void 0?1:0)+($.length>0?1:0)+(W.length>0?1:0)+(Q?1:0)!==1)throw Error("Provide exactly one target when calling `cancel_sequence_enrollments`: `cancelAll`, `subscriberId`, `subscriberIds`, or `fieldValues`.");let J=U(w,"fieldPath"),G=U(w,"reason");return{...Q&&{cancelAll:!0},...b!==void 0&&{subscriberId:b},...$.length>0&&{subscriberIds:$},...J!==void 0&&{fieldPath:J},...W.length>0&&{fieldValues:W},...typeof w.dryRun==="boolean"&&{dryRun:w.dryRun},...G!==void 0&&{reason:G}}}function L5(w){_w("create_campaign",w),U1("create_campaign",w);let b=U(w,"prompt")!==void 0,$=w.html!==void 0,W=w.blocks!==void 0,Q=w.templateId!==void 0;if(w.prompt!==void 0&&!b)throw Error("`prompt` cannot be empty when calling `create_campaign`.");if(b&&($||W||Q))throw Error("Provide either `prompt`, `html`, `blocks`, or `templateId` when calling `create_campaign`, not multiple content sources.");if(!b&&(w.style!==void 0||w.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_campaign`.");if(!b&&U(w,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_campaign`.")}function U5(w){_w("create_template",w),U1("create_template",w);let b=U(w,"prompt")!==void 0,$=[b,w.html!==void 0,w.blocks!==void 0].filter(Boolean).length;if(w.prompt!==void 0&&!b)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(!b&&(w.style!==void 0||w.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_template`.");if(!b&&U(w,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_template`.")}function F5(w){if(U(w,"scheduledAt")===void 0)throw Error("`scheduledAt` is required when calling `schedule_campaign`.");if(w.targetLists!==void 0&&!C(w.targetLists))throw Error("`targetLists` must be an object when calling `schedule_campaign`.");if(w.sendTimeOptimization!==void 0){if(typeof w.sendTimeOptimization!=="boolean")throw Error("`sendTimeOptimization` must be a boolean when calling `schedule_campaign`.")}if(w.spreadOverHours!==void 0){if(typeof w.spreadOverHours!=="number"||!Number.isInteger(w.spreadOverHours)||w.spreadOverHours<1||w.spreadOverHours>72)throw Error("`spreadOverHours` must be an integer between 1 and 72 when calling `schedule_campaign`.")}if(w.recurringInterval!==void 0&&w.recurringInterval!=="weekly"&&w.recurringInterval!=="monthly")throw Error("`recurringInterval` must be 'weekly' or 'monthly' when calling `schedule_campaign`.")}function Q4(w,b,$){let W=new Set(["companyId","landingPageId","name","slug","content"]),Q=Object.keys(b).filter((X)=>!W.has(X));if(Q.length>0)throw Error(`\`${w}\` accepts only \`name\`, \`slug\`, and \`content\` update fields. Unsupported field${Q.length===1?"":"s"}: ${Q.map((X)=>`\`${X}\``).join(", ")}.`);if($.requireUpdate&&b.name===void 0&&b.slug===void 0&&b.content===void 0)throw Error(`Provide at least one of \`name\`, \`slug\`, or \`content\` when calling \`${w}\`.`);return{...b.name!==void 0&&{name:b.name},...b.slug!==void 0&&{slug:b.slug},...b.content!==void 0&&{content:b.content}}}function K5(w){let b=new Set(["companyId","domain","verify"]),$=Object.keys(w).filter((W)=>!b.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(w.domain===void 0&&w.verify!==!0)throw Error("Provide `domain` or `verify: true` when calling `update_landing_page_domain_settings`.");return{...w.domain!==void 0&&{domain:w.domain},...typeof w.verify==="boolean"&&{verify:w.verify}}}function O5(w){_w("create_transactional_email",w);let b=U(w,"prompt")!==void 0,$=w.html!==void 0,W=w.blocks!==void 0;if(w.prompt!==void 0&&!b)throw Error("`prompt` cannot be empty when calling `create_transactional_email`.");if(b&&($||W))throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`, not multiple content sources.");if(!b&&(w.style!==void 0||w.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_transactional_email`.");if(!b&&!$&&!W)throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`.");if(!b&&U(w,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_transactional_email`.")}var Z0={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},pV={type:"object",description:"Config for advanced nodeType steps. Required fields depend on nodeType: action_add_tag and action_remove_tag need tagId or tagName; action_add_to_list and action_remove_from_list need listId; action_update_attributes uses the Update Subscriber fields (firstName, lastName, status, customAttributeUpdates) and may use trigger-event merge tags; logic_wait_for_event needs eventName plus optional timeoutDays and timeoutAction; logic_condition needs conditionType plus that condition's resource field; action_webhook needs an HTTPS url plus optional method, headers, body, resultKey, and onError; logic_delay uses delayDays/delayHours/delayMinutes. Fields that do not apply to the node type are dropped.",properties:{...Z0.properties,tagId:{type:"string",description:"action_add_tag / action_remove_tag: tag ID. Pass a name in tagName instead, because tag actions resolve tagId by ID only. has_tag / does_not_have_tag also accept a tag name here. Missing tag definitions are created automatically."},tagName:{type:"string",description:"action_add_tag / action_remove_tag / has_tag / does_not_have_tag: tag name. Use instead of tagId when you only know the name."},listId:{type:"string",description:"action_add_to_list / action_remove_from_list / in_list: list ID. It must match an existing list in this company; listName is filled in for you."},listName:{type:"string",description:"Optional cached list display name for list actions."},eventName:{type:"string",description:"logic_wait_for_event and event_received conditions: event to wait for or check, for example email.replied."},timeoutDays:{type:"number",description:"logic_wait_for_event: maximum wait in whole days from 1 to 365. Defaults to 7."},timeoutAction:{type:"string",enum:["continue","exit"],description:"logic_wait_for_event: continue to the next node or exit the sequence when the timeout is reached. Defaults to continue."},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:"logic_condition: condition evaluated before continuing. has_phone and sms_subscribed need no resource fields."},segmentId:{type:"string",description:"logic_condition: segment ID for in_segment."},segmentName:{type:"string",description:"Optional cached segment display name."},linkUrl:{type:"string",description:"logic_condition: optional URL substring for link_clicked. Omit to match any tracked click."},activityScope:{type:"string",enum:["ever","this_sequence","previous_email"],description:"logic_condition: scope for event_received and link_clicked. Use this_sequence to restrict activity to the current enrollment."},fieldName:{type:"string",description:"logic_condition: subscriber attribute name/path for field comparisons."},fieldValue:{type:"string",description:"logic_condition: comparison value for field comparisons."},url:{type:"string",description:"action_webhook: destination HTTPS URL called when a subscriber reaches this step. Supports merge tags like {{email}} and {{event.order_id}} resolved at execution time."},method:{type:"string",enum:["POST","GET","PUT","PATCH","DELETE"],description:"action_webhook: HTTP method. Defaults to POST."},headers:{type:"object",description:"action_webhook: optional string-valued request headers. Values support merge tags. Secret values are redacted on sequence reads.",additionalProperties:{type:"string"}},body:{type:"string",description:'action_webhook: optional JSON body template for POST/PUT/PATCH. Must be valid JSON as written, with merge tags inside quoted string values ({"email": "{{email}}"}); a tag in a bare value position is rejected. Tags are resolved at execution time; when omitted, the default payload with subscriber and sequence context is sent.'},resultKey:{type:"string",description:"action_webhook: when set, the HTTP response is saved and later email steps can reference it via {{webhooks.KEY.data.field}} merge tags. Must start with a letter; letters, numbers, underscores; max 64 chars."},onError:{type:"string",enum:["continue","exit","fail"],description:"action_webhook: behavior when the request fails. continue proceeds to the next step, exit ends the sequence for the subscriber, fail marks the enrollment failed (default)."},delayDays:{type:"number",description:"logic_delay: whole days to wait."},delayHours:{type:"number",description:"logic_delay: hours to wait."},delayMinutes:{type:"number",description:"logic_delay: minutes to wait."}},additionalProperties:!0},jb={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:"Reply-To display name override for this step. Requires replyTo; omit it when using replyProfileId, which already carries its own display name."}},qb={type:"object",description:"A typed step to create inside a sequence path, including email, SMS, delay, discount, subscriber actions, conditions, waits, and webhooks.",properties:{type:{type:"string",enum:["email","sms","delay","create_discount","discount","update_subscriber","condition","webhook"],description:"Sequence path step type. Omit for email steps; use delay for fixed/date waits or update_subscriber for action_update_attributes. For an event gate, use nodeType:'logic_wait_for_event' with an explicit config object."},nodeType:{type:"string",enum:["logic_delay","action_email","action_sms","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. Tag, list, subscriber-update, wait, condition, and webhook node types carry their fields in config, for example nodeType:'action_add_tag' with config:{ tagName:'newsletter-confirmed' }. SMS steps still use the step-level text/imageUrls/ineligibleAction, discount steps the step-level discount fields, and delays the step-level delay/delayMs/waitUntil."},config:pV,subject:{type:"string",description:"Email subject. Required for email steps."},previewText:{type:"string",description:"Email preview text."},blocks:{type:"array",description:A0,items:{type:"object"}},html:{type:"string",description:"HTML content for email steps. Stored as one raw HTML block. Use this for imported provider HTML."},isTransactional:{type:"boolean",description:"Email only: omit the marketing unsubscribe footer."},ccEmails:{type:"array",items:{type:"string"},description:"Email only: addresses CC'd on this step."},bccEmails:{type:"array",items:{type:"string"},description:"Email only: addresses BCC'd on this step in addition to sequence BCC."},attachments:{type:"array",items:{type:"object",properties:{filename:{type:"string"},path:{type:"string"}},required:["filename","path"]},description:"Email only: URL-backed file attachments (max 10, 7MB total per email). path may be a public HTTPS URL or an {{event.*}} URL template resolved from the enrollment event at send time."},text:{type:"string",description:"SMS only: plain-text message body."},imageUrls:{type:"array",items:{type:"string"},description:"SMS only: up to two public MMS image URLs."},ineligibleAction:{type:"string",enum:["skip","exit"],description:"SMS only: behavior when the contact cannot receive SMS."},delay:U0,delayMs:{type:"number",description:"Delay in milliseconds. Useful for standalone type:'delay' steps."},waitUntil:L0,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:"Reply-To display name override for this email step. Requires replyTo; omit it when using replyProfileId, which already carries its own display name."},discount:{type:"object",description:`Discount configuration for create_discount steps. Same shape as create_sequence steps.${t6}`,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},t9={type:"object",properties:{id:{type:"string",description:"Optional stable path ID. Defaults to branch-0, branch-1, and so on. The value 'else' is reserved."},label:{type:"string",description:"Display label, for example 'Replied in this sequence'."},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 for this path. has_phone and sms_subscribed need no resource fields."},tagName:{type:"string",description:"Tag name for has_tag and does_not_have_tag. This can be used instead of tagId."},tagId:{type:"string",description:"Tag ID or tag name for has_tag and does_not_have_tag."},listId:{type:"string",description:"List ID for in_list."},segmentId:{type:"string",description:"Segment ID for in_segment."},segmentName:{type:"string",description:"Optional display name for in_segment."},eventName:{type:"string",description:"Event name for event_received, for example email.replied."},linkUrl:{type:"string",description:"Optional URL substring for link_clicked. Omit to match any tracked click."},activityScope:{type:"string",enum:["ever","this_sequence","previous_email"],description:"Scope for event_received and link_clicked. Use this_sequence to restrict activity to the current enrollment."},fieldName:{type:"string",description:"Subscriber attribute name/path for field conditions."},fieldValue:{type:"string",description:"Comparison value for field conditions."},targetNodeId:{type:"string",description:"Optional existing node to route this branch path to. Use a node ID from get_sequence, including the sequence completion node when this path should stop. If steps are also provided, they run before this target."},steps:{type:"array",description:"Optional new steps for this path. When targetNodeId is also set, the last new step connects to that existing node.",items:qb}},required:["conditionType"],additionalProperties:!1};function Z5(w){if(!w||typeof w!=="object")return null;let b=w;if(b.success!==!1)return null;if(typeof b.error==="string")return Error(b.error);if(b.error&&typeof b.error==="object"&&typeof b.error.message==="string")return Error(b.error.message);if(typeof b.message==="string")return Error(b.message);return Error("The tool returned an unsuccessful response.")}var M5=1000,dV=1000;function r9(w){return w.trim().toLowerCase().replace(/\s+/g,"-")}function oV(w){let b=new URLSearchParams;if(typeof w.query==="string"&&w.query.trim()!=="")b.set("query",w.query.trim());if(Array.isArray(w.tags)&&w.tags.length>0)b.set("tags",w.tags.filter(($)=>typeof $==="string"&&$.trim()!=="").join(","));if(typeof w.list==="string"&&w.list.trim()!=="")b.set("list",w.list.trim());if(typeof w.listId==="string"&&w.listId.trim()!=="")b.set("listId",w.listId.trim());if(typeof w.listName==="string"&&w.listName.trim()!=="")b.set("listName",w.listName.trim());if(typeof w.segmentId==="string"&&w.segmentId.trim()!=="")b.set("segmentId",w.segmentId);if(typeof w.status==="string"&&w.status.trim()!=="")b.set("status",w.status.trim());if(w.cursor)b.set("cursor",w.cursor);else b.set("page",String(w.page));if(b.set("limit",String(w.pageSize)),w.includeTotal===!1)b.set("includeTotal","false");return b}async function j5(w,b){let $=typeof w.limit==="number"&&Number.isFinite(w.limit)?Math.max(1,Math.trunc(w.limit)):void 0,W=Math.min(M5,Math.max(1,$??M5)),Q=[],X=1,J,G=0,Y=0,H=0;while(!0){let D=oV({query:w.query,tags:w.tags,list:w.list,listId:w.listId,listName:w.listName,segmentId:w.segmentId,status:w.status,page:X,pageSize:W,cursor:J}),A=await B("GET",`/api/v1/subscribers?${D.toString()}`,void 0,b);if(H===0)G=A.pagination?.total??A.subscribers.length,Y=A.pagination?.totalPages??1;H+=1,Q.push(...A.subscribers??[]);let L=(A.subscribers??[]).length,F=A.pagination?.nextCursor??void 0,V=$!==void 0&&Q.length>=$,q;if(F)q=!1;else if(A.pagination?.hasMore!==void 0)q=!A.pagination.hasMore;else if(A.pagination?.totalPages!==void 0&&A.pagination.totalPages!==null)q=X>=A.pagination.totalPages;else q=L<W;if(V||q||L===0||H>=dV)break;if(F)J=F;else X+=1}if(G===0&&Q.length>0)G=Q.length;let z=$!==void 0?Q.slice(0,$):Q;return{success:!0,subscribers:z,pagination:{page:1,limit:W,total:G,totalPages:Y,fetchedPages:H},returned:z.length,truncated:$!==void 0&&G>0&&z.length<G}}function s9(w){let b=typeof w.email==="string"&&w.email.trim()!==""?w.email.trim():void 0,$=typeof w.externalId==="string"&&w.externalId.trim()!==""?w.externalId.trim():void 0;return{...b?{email:b}:{},...$?{externalId:$}:{}}}function tw(w,b){let $=s9(b);if(!$.email&&!$.externalId)throw Error(`Provide either \`email\` or \`externalId\` when calling \`${w}\`.`);return $}function X4(w,b){let $=new URLSearchParams;if(b?.includeMachineEngagement)$.set("includeMachineEngagement","true");let W=$.toString(),Q=W?`?${W}`:"";if(w.email)return`/api/v1/subscribers/${encodeURIComponent(w.email)}${Q}`;return $.set("externalId",String(w.externalId)),`/api/v1/subscribers/external?${$.toString()}`}function e9(w){if(w.email)return`/api/v1/subscribers/${encodeURIComponent(w.email)}/notes`;let b=new URLSearchParams;return b.set("externalId",String(w.externalId)),`/api/v1/subscribers/external/notes?${b.toString()}`}async function Pb(w,b,$){return B("GET",X4(w,$),void 0,b)}function m(w,b,$,W){let Q=U(b,$);if(Q===void 0)return;if(!W.includes(Q))throw Error(`\`${$}\` must be one of ${W.join(", ")} when calling \`${w}\`.`);return Q}function Ib(w,b,$,W){let Q=M(w,b,$);if(!W.includes(Q))throw Error(`\`${$}\` must be one of ${W.join(", ")} when calling \`${w}\`.`);return Q}function Yw(w,b,$,W,Q){let X=b[$];if(X===void 0)return;if(typeof X!=="number"||!Number.isInteger(X)||X<W||X>Q)throw Error(`\`${$}\` must be an integer between ${W} and ${Q} when calling \`${w}\`.`);return X}function tV(w,b){let $=[],W=m(w,b,"eventType",Mb);if(W)$.push(W);if(b.eventTypes!==void 0){if(!Array.isArray(b.eventTypes))throw Error(`\`eventTypes\` must be an array when calling \`${w}\`.`);b.eventTypes.forEach((Q,X)=>{if(typeof Q!=="string")throw Error(`\`eventTypes\` item ${X+1} must be a string when calling \`${w}\`.`);let J=Q.trim();if(!Mb.includes(J))throw Error(`\`eventTypes\` item ${X+1} must be one of ${Mb.join(", ")} when calling \`${w}\`.`);$.push(J)})}return[...new Set($)]}function a9(w,b){let $=new URLSearchParams,W=tV(w,b);if(W.length>0)$.set("eventTypes",W.join(","));let Q=m(w,b,"period",["1h","24h","7d","30d","90d"]);if(Q)$.set("period",Q);let X=U(b,"start");if(X)$.set("start",X);let J=U(b,"end");if(J)$.set("end",J);let G=Yw(w,b,"page",1,1e6);if(G!==void 0)$.set("page",String(G));let Y=Yw(w,b,"limit",1,500);if(Y!==void 0)$.set("limit",String(Y));if(b.includeMachineEngagement===!0)$.set("includeMachineEngagement","true");return $}function wW(w,b){if(b.events===void 0)return;if(!Array.isArray(b.events))throw Error(`\`events\` must be an array when calling \`${w}\`.`);let $=b.events.map((W,Q)=>{if(typeof W!=="string"||!K0.includes(W))throw Error(`\`events\` item ${Q+1} must be one of ${K0.join(", ")} when calling \`${w}\`.`);return W});if($.length===0)throw Error(`\`events\` must include at least one event type when calling \`${w}\`.`);return $}function bW(w,b){if(!Array.isArray(b.emails))throw Error(`\`emails\` must be an array when calling \`${w}\`.`);let $=[];if(b.emails.forEach((W,Q)=>{if(typeof W!=="string")throw Error(`\`emails\` item ${Q+1} must be a string when calling \`${w}\`.`);let X=W.trim();if(X.length>0)$.push(X)}),$.length===0)throw Error(`\`emails\` must include at least one email address when calling \`${w}\`.`);if($.length>_9)throw Error(`\`emails\` must include no more than ${_9} email addresses when calling \`${w}\`. Split larger batches into multiple calls.`);return $}function V5(w,b,$,W){let Q=b[$];if(Q===void 0)return;if(!Array.isArray(Q))throw Error(`\`${$}\` must be an array when calling \`${w}\`.`);let X=[];if(Q.forEach((J,G)=>{if(typeof J!=="string")throw Error(`\`${$}\` item ${G+1} must be a string when calling \`${w}\`.`);let Y=J.trim();if(Y.length>0)X.push(Y)}),X.length===0)throw Error(`\`${$}\` must include at least one ${W} when calling \`${w}\`.`);return X}function q5(w){let $=V5("enroll_subscribers_in_sequence",w,"emails","email address"),W=V5("enroll_subscribers_in_sequence",w,"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>x9)throw Error(`\`emails\` and \`subscriberIds\` must include no more than ${x9} total targets when calling \`enroll_subscribers_in_sequence\`. Split larger batches into multiple calls.`);let X=U(w,"targetNodeId");return{...$!==void 0&&{emails:$},...W!==void 0&&{subscriberIds:W},...X!==void 0&&{targetNodeId:X}}}import{readFileSync as rV,statSync as sV}from"node:fs";import{basename as eV}from"node:path";var aV={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 wj(w){let b=w.split(".").pop()?.toLowerCase()??"";return aV[b]??null}var bj=104857600;async function P5(w,b){if(!Eb())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 $=wj(w);if(!$)throw Error("Unsupported file type. Use PDF, ePub, ZIP, image, audio, video, or text files.");let W=sV(w).size;if(W>bj)throw Error(`File is too large (${Math.round(W/1048576)}MB). Delivery files must be 100MB or smaller.`);let Q=rV(w),X=await B("POST","/api/v1/products/delivery/upload-url",{filename:eV(w),contentType:$,fileSizeBytes:W},b),J=await fetch(X.uploadUrl,{method:"PUT",headers:{"Content-Type":$},body:Q});if(!J.ok)throw Error(`File upload failed (${J.status})`);return{url:X.publicUrl,fileName:X.fileName,fileSizeBytes:W,mimeType:$}}async function J4(w){let b=U(w,"companyId");if(b)return b;let $=k1();if($)return $;try{return(await B("GET","/api/v1/account")).currentCompanyId??void 0}catch{return}}async function Nb(w,b){let $=await J4(b);if(!$)throw Error(`A company is required when calling \`${w}\`. Call \`get_account\`, then \`select_company\`, or pass \`companyId\` explicitly.`);return $}function V0(w,b){if(!C(w)||!b)return w;return{...w,url:b}}function I5(w,b){if(!C(w))return w;return{...w,...b.campaign!==void 0&&{url:b.campaign},...b.campaignPreview!==void 0&&{previewUrl:b.campaignPreview}}}function M0(w,b,$){if(!Array.isArray(w)||!b)return w;return w.map((W)=>{if(!C(W))return W;let Q=U(W,"id");if(!Q)return W;let X=D1({companyId:b,...$==="campaign"&&{campaignId:Q},...$==="landingPage"&&{landingPageId:Q},...$==="sequence"&&{sequenceId:Q},...$==="template"&&{emailId:Q},...$==="transactional"&&{transactionalId:Q},...$==="emailSend"&&{emailSendId:Q}});if($==="campaign")return I5(W,X.urls);let J=$==="sequence"?X.urls.sequence:$==="landingPage"?X.urls.landingPage:$==="template"?X.urls.email:$==="transactional"?X.urls.transactionalEmail:X.urls.emailSend;return V0(W,J)})}function $j(w){if(!Array.isArray(w))return w;return w.map((b)=>{if(!C(b))return b;let $=U(b,"id");if(!$)return b;let W=D1({companyId:$});return{...b,url:W.urls.dashboard,settingsUrl:W.urls.settings}})}var $W=new Set(["get_account","select_company","create_company","get_company","update_company","list_campaigns","get_campaign","get_email_send","list_email_sends","create_campaign","update_campaign","schedule_campaign","unschedule_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","duplicate_landing_page","delete_landing_page","list_sequences","get_sequence","send_sequence_test_email","create_sequence","generate_sequence","update_sequence","update_sequence_node","update_sequence_nodes","edit_sequence_graph","insert_sequence_step","enable_sequence","disable_sequence","pause_sequence_enrollments","resume_sequence_enrollments","cancel_sequence_enrollments","list_ab_tests","get_ab_test","get_ab_test_stats","update_ab_test_variant","update_ab_test","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 N5(w,b,$){if(!C($)||!$W.has(w))return $;let W=C($.company)?$.company:void 0,X=U($,"selectedCompanyId")??U($,"currentCompanyId")??U($,"companyId")??(W?U(W,"id"):void 0)??(W?U(W,"companyId"):void 0)??await J4(b);if(!X)return $;let J=C($.campaign)?$.campaign:void 0,G=C($.sequence)?$.sequence:void 0,Y=C($.landingPage)?$.landingPage:void 0,H=C($.template)?$.template:void 0,z=C($.transactional)&&!Array.isArray($.transactional)?$.transactional:void 0,D={companyId:X,campaignId:U(b,"campaignId")??U($,"campaignId")??(J?U(J,"id"):void 0),landingPageId:U(b,"landingPageId")??U($,"landingPageId")??(Y?U(Y,"id"):void 0),sequenceId:U(b,"sequenceId")??U($,"sequenceId")??(G?U(G,"id"):void 0),emailId:U($,"templateId")??(H?U(H,"id"):void 0)??(z?U(z,"emailId"):void 0)??U(b,"templateId"),transactionalId:U(b,"transactionalId")??(z?U(z,"id"):void 0)??U(b,"idOrSlug"),emailSendId:U(b,"emailSendId")??U($,"emailSendId")??(C($.emailSend)?U($.emailSend,"id"):void 0),status:U(b,"status")},A=D1(D),L=W?D1({companyId:X}):void 0;return{...$,...Array.isArray($.companies)&&{companies:$j($.companies)},...Array.isArray($.campaigns)&&{campaigns:M0($.campaigns,X,"campaign")},...Array.isArray($.landingPages)&&{landingPages:M0($.landingPages,X,"landingPage")},...Array.isArray($.sequences)&&{sequences:M0($.sequences,X,"sequence")},...Array.isArray($.templates)&&{templates:M0($.templates,X,"template")},...Array.isArray($.transactional)&&{transactional:M0($.transactional,X,"transactional")},...Array.isArray($.emailSends)&&{emailSends:M0($.emailSends,X,"emailSend")},...W&&L!==void 0&&{company:{...W,url:L.urls.dashboard,settingsUrl:L.urls.settings}},...J&&A.urls.campaign!==void 0&&{campaign:I5(J,A.urls)},...G&&A.urls.sequence!==void 0&&{sequence:V0(G,A.urls.sequence)},...Y&&A.urls.landingPage!==void 0&&{landingPage:V0(Y,A.urls.landingPage)},...H&&A.urls.email!==void 0&&{template:V0(H,A.urls.email)},...z&&A.urls.transactionalEmail!==void 0&&{transactional:V0(z,A.urls.transactionalEmail)},...C($.emailSend)&&A.urls.emailSend!==void 0&&{emailSend:V0($.emailSend,A.urls.emailSend)},appUrls:A.urls}}import{readFileSync as Wj,statSync as Qj}from"node:fs";import{basename as Xj,extname as T5}from"node:path";var QW=5242880,Jj=Math.ceil(QW/3)*4,Gj=Math.ceil(Jj*1.05)+256,R5={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"},Yj=new Set(Object.values(R5));function WW(w){return w?.split(";")[0]?.trim().toLowerCase()||void 0}function Hj(w){return R5[T5(w).toLowerCase()]}function zj(w){let b=T5(w);return(b?w.slice(0,-b.length):w).replace(/[-_]+/g," ").trim()||"Image"}function Bj(w){if(w.length>Gj)throw Error("Image assets must be 5MB or smaller.")}function Dj(w){let b=0,$=0;for(let Q=0;Q<w.length;Q+=1){let X=w.charCodeAt(Q);if(X===9||X===10||X===11||X===12||X===13||X===32)continue;b+=1,$=X===61?$+1:0}if(Math.floor(b*3/4)-Math.min($,2)>QW)throw Error("Image assets must be 5MB or smaller.")}function Aj(w){Bj(w);let b=w.trim(),$=/^data:([^;,]+);base64,([\s\S]+)$/i.exec(b),W=$?.[2]??b;Dj(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:WW($[1])}:{}}}function E5(w){if(w<=0)throw Error("The image file is empty.");if(w>QW)throw Error("Image assets must be 5MB or smaller.")}function Lj(w){let b=Hj(w.filename)??WW(w.explicitContentType)??WW(w.dataUrlContentType);if(!b||!Yj.has(b))throw Error("Unsupported image type. Use PNG, JPEG, GIF, or WebP.");return b}function Uj(w){let b,$,W;if(w.filePath!==void 0){if(!Eb())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 X=Qj(w.filePath).size;E5(X),b=Wj(w.filePath),$=w.filename??Xj(w.filePath)}else{if(!w.imageBase64)throw Error("Provide either `filePath` or `imageBase64` when uploading an image asset.");if(!w.filename)throw Error("`filename` is required with `imageBase64` when uploading an image asset.");let X=Aj(w.imageBase64);b=X.bytes,W=X.dataUrlContentType,$=w.filename,E5(b.byteLength)}let Q=Lj({filename:$,explicitContentType:w.contentType,dataUrlContentType:W});return{bytes:b,filename:$,contentType:Q,altText:w.altText??zj($)}}async function S5(w){let b=Uj(w),$=b.bytes.byteLength,W=await B("POST","/api/v1/media/upload-url",{filename:b.filename,contentType:b.contentType,fileSizeBytes:$},w.companyId);return await ZW(W.uploadUrl,b.bytes,b.contentType,w.companyId),(await B("POST","/api/v1/media/complete-upload",{key:W.key,filename:W.fileName,contentType:b.contentType,fileSizeBytes:$,...w.sourceWidth!==void 0&&{width:w.sourceWidth},...w.sourceHeight!==void 0&&{height:w.sourceHeight},altText:b.altText},w.companyId)).asset}var Fj={type:"boolean",description:"Whether the Sequenzy operation succeeded."},n1={type:"string",description:"Human-readable status, confirmation, or next-step message."},C5={type:"string",description:"Additional context about the result."};function I(w){return{type:"object",description:w,additionalProperties:!0}}function F1(w){return{type:"array",description:w,items:I("One item in the returned collection.")}}function Z(w){return{type:"string",description:w}}function j0(w){return{type:["object","null"],description:w,additionalProperties:!0}}function Lw(w){return{type:["string","null"],description:w}}function y(w){return{type:"number",description:w}}function d(w){return{type:"boolean",description:w}}function j(w){return I(`The ${w} record returned by Sequenzy.`)}function h(w){return F1(`List of ${w} records returned by Sequenzy.`)}var C1="`opened` and `clicked` are unique counts deduplicated by email send (one recipient opening five times counts once), not total open events. Every count is attributed to the sends made inside the requested window, including engagement that arrives after the window ends, so `opened <= delivered <= sent` always holds. Rates use `rateDenominator` (`delivered`, or `sent` when no delivery events were recorded, reported as `rateDenominatorBasis`); `deliveryRate` and `bounceRate` divide by `sent`.",k5="Run state: branch on effectiveStatus (draft, live, enrollment_paused, paused, or archived) rather than on status, which reads `active` even when new enrollments are paused. acceptsNewEnrollments and processesExistingEnrollments answer the two questions behind it, and effectiveStatusSummary is a plain-language sentence. The legacy triggerConfig.active flag is not read by the runtime; it is reported as a mirror of acceptsNewEnrollments.",p1=I(`The sequence record returned by Sequenzy. ${k5}`),Kj=F1(`List of sequence records returned by Sequenzy. ${k5}`),G4={effectiveStatus:{type:"string",enum:["draft","live","enrollment_paused","paused","archived"],description:"Resolved run state. The one field to branch on: `status` still reads `active` while new enrollments are paused."},acceptsNewEnrollments:d("Whether new subscribers can enter the sequence right now."),processesExistingEnrollments:d("Whether subscribers already inside the sequence keep advancing and receiving steps."),effectiveStatusSummary:Z("One plain-language sentence describing the run state, safe to show a user verbatim.")},v5={...p1,properties:{migratedRecipientCount:y("Recipients moved immediately from deleted steps to their surviving successor."),completedRecipientCount:y("Recipients completed because a deleted step had no surviving successor.")}},Oj={appUrls:I("Dashboard URLs for relevant Sequenzy resources."),url:Z("Primary dashboard URL for this result."),settingsUrl:Z("Company settings URL when available.")},Zj={success:Fj,message:n1,note:C5,warnings:{type:"array",description:"Non-fatal cautions about content, permissions, or follow-up actions.",items:Z("One warning.")},items:{type:"array",description:"Fallback array wrapper used only when a tool returns a bare array.",items:I("One returned item.")},value:I("Fallback object wrapper used only when a tool returns a non-object value.")},Mj={get_account:{account:j("account"),companies:h("company"),apiKeyPermissions:I("Current API key preset and scopes, whether common marketing work is discoverable, any missing marketing read scopes, and the API Keys management URL."),currentCompanyId:Z("Company ID selected by the authenticated API key, when available."),selectedCompanyId:Z("Company ID selected locally for subsequent MCP calls, when available.")},select_company:{companyId:Z("Selected company ID."),companyName:Z("Selected company name.")},get_app_urls:{dashboard:Z("Company dashboard URL."),settings:Z("Company settings URL."),campaign:Z("Campaign editor URL."),landingPage:Z("Landing page editor URL."),sequence:Z("Sequence editor URL."),email:Z("Email editor URL."),transactionalEmail:Z("Transactional email URL."),emailSend:Z("Sent email detail URL."),domain:Z("Sending domain settings URL."),urls:I("All generated URLs keyed by resource type.")},create_company:{company:j("company"),autoSelected:d("Whether the new company was selected for subsequent MCP calls.")},update_company:{company:j("company")},get_company:{company:j("company")},get_sync_rules:{syncRules:{type:"array",description:"Effective sync rules for the company.",items:I("One sync rule.")},isDefault:d("Whether the company uses the inherited SaaS/ecommerce platform preset.")},update_sync_rules:{syncRules:{type:"array",description:"Effective sync rules after the update.",items:I("One sync rule.")},isDefault:d("Whether the company now uses the inherited SaaS/ecommerce platform preset.")},get_shopify_automation_settings:{browseAbandonment:I("Effective browse-abandonment settings (defaults applied)."),cartAbandonment:I("Effective cart-abandonment settings (defaults applied)."),priceDrop:I("Effective price-drop settings (defaults applied)."),shopDomain:Z("Connected Shopify store domain.")},update_shopify_automation_settings:{browseAbandonment:I("Effective browse-abandonment settings after the update."),cartAbandonment:I("Effective cart-abandonment settings after the update."),priceDrop:I("Effective price-drop settings after the update."),shopDomain:Z("Connected Shopify store domain.")},create_api_key:{apiKey:I("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:Z("Newly created API key if the API response uses the short key field.")},list_api_keys:{apiKeys:h("non-secret API key metadata, including ID, name, prefix, permissions, timestamps, and active-credential status")},update_api_key:{apiKey:j("updated non-secret API key metadata, including the `scopes` now in effect (null when the key has full access)")},revoke_api_key:{apiKey:j("revoked non-secret API key metadata")},delete_api_key:{apiKey:j("deleted non-secret API key metadata")},list_websites:{websites:h("sending domain, including DNS verification and readyToSend home-transport readiness")},list_integrations:{integrations:h("connected integration, including provider, provider account ID, active and sync status, last sync time, last sync error, allowlisted non-secret details, and lastSyncSkipped (records the last sync could not import normally: suppressed profiles that cannot receive email, plus any that were not imported). Credentials are never included")},get_integration:{integration:I("The connected integration: provider, display name, category, provider account ID, active and sync status, last sync time and error, and allowlisted non-secret details. Credentials are never included."),capabilities:j0("What this provider does: category, connect method, what it syncs, every event it emits with when it fires, attributes it writes, supported actions, availability, and caveats. Null for a provider with no catalog entry."),events:F1("Each event the provider emits, every matching tag rule and its conditions, listening sequences, and account-wide observation fields. Use activity for integration-specific delivery."),unusedEvents:{type:"array",description:"Events the provider emits that no sequence triggers on. These are the concrete automation gaps for this integration.",items:Z("Event name with no listening sequence.")},accountNeverReceivedEvents:{type:"array",description:"Provider event names this account has never received from any source. This is not integration-specific delivery evidence.",items:Z("Event name never seen account-wide.")},activity:I("Webhook and sync activity over the last 24 hours: totals by status, stalled count, last activity time, and recent failures."),pixel:j0("Shopify only: live storefront pixel state (installed, endpoint, endpointCurrent, configurationCurrent, healthy, error, dependentEvents). Null for providers without a pixel. When error is null and healthy is false, every dependentEvent is confirmed dark; an error means Shopify could not confirm the state."),recommendations:F1("Prioritized problems and suggestions, each with a code, severity (error, warning, info), message, and a concrete action."),availableActions:{type:"array",description:"Action ids callable on this integration right now, given its current state.",items:Z("Available action id.")}},list_integration_capabilities:{providers:h("integration provider, including category, connect method, what it syncs, every event it emits with the moment that triggers it, the subscriber attributes it writes, supported actions, availability, and caveats")},list_integration_activity:{activity:h("integration activity row, including provider, action, status, event type, matched contact, message, and error. Payloads are sanitized, so no credentials appear"),windowHours:{type:"number",description:"Retention window in hours for integration activity."},note:C5},connect_integration:{integration:{type:"object",description:"The connected integration: id, provider, name, providerAccountId, sync state, and safe (non-credential) details."},webhookUrl:Z("URL to configure in the provider's webhook settings with the same secret. Always relay this to the user - delivery does not start until it is configured."),revenueSyncQueued:d("Payment providers only: whether the initial revenue backfill was queued."),backfillQueued:d("Affonso only: whether the affiliate backfill was queued."),history:{type:"object",description:"PostHog only: outcome of the optional history import request ({ requested, queued, error }). The webhook connection succeeds even if queueing the import failed."}},set_integration_sync_enabled:{integrationId:Z("The integration that was updated."),provider:Z("Provider of the updated integration."),syncEnabled:d("Sync state after the update."),changed:d("False when the integration was already in the requested state."),message:n1},get_integration_pixel:{integrationId:Z("The Shopify integration inspected."),provider:Z("Always `shopify`."),shopDomain:Z("Store the pixel was read from."),pixel:I("Live pixel state: installed, id, endpoint it posts to, endpointCurrent (including the supported compatibility route), configurationCurrent (endpoint plus signed connection settings), healthy, and error when Shopify could not confirm."),dependentEvents:{type:"array",description:"Event names that depend on this pixel. They are confirmed unable to arrive only when pixel.error is null and pixel.healthy is false.",items:Z("Pixel-dependent event name.")},message:n1},activate_integration_pixel:{integrationId:Z("The Shopify integration updated."),provider:Z("Always `shopify`."),shopDomain:Z("Store the pixel was installed on."),pixel:I("Pixel state after activation."),changed:d("False when the pixel was already installed and reporting to this account."),created:d("True when a new pixel was installed."),updated:d("True when an existing pixel was repointed at this account."),dependentEvents:{type:"array",description:"Event names this pixel enables.",items:Z("Pixel-dependent event name.")},message:n1},sync_integration:{integrationId:Z("The integration being synced."),provider:Z("Provider of the synced integration."),jobId:Lw("Background job id for the queued sync, when one was created."),syncStatus:Z("Sync status after queueing. Poll get_integration to watch it progress."),message:n1},list_sender_profiles:{senderProfiles:h("sender (From) profile, including the sending domain behind it, its DNS verification status, and whether DNS plus the home transport allow the address to send"),replyProfiles:h("reply-to profile"),defaultSenderProfileId:Lw("Company default sender profile ID. Null when no default is set."),defaultReplyProfileId:Lw("Company default reply-to profile ID. Null when no default is set.")},update_sender_profile:{senderProfile:j("renamed sender (From) profile, present when type was sender"),replyProfile:j("renamed reply-to profile, present when type was reply"),renamed:d("False when the profile already carried that name, so nothing changed.")},get_notification_preferences:{notificationPreferences:F1("One entry per notification event with its current mode: off, instant, or daily. Every event is always present; an event the user has never configured reports the platform default."),supportedModes:I("Modes each event accepts, keyed by event. campaign_completed does not accept daily."),defaults:I("Mode each event uses when the user has never configured it.")},update_notification_preferences:{notificationPreferences:F1("Every notification event with its mode after the update, not only the events that were changed."),supportedModes:I("Modes each event accepts, keyed by event. campaign_completed does not accept daily."),defaults:I("Mode each event uses when the user has never configured it.")},get_sending_status:{status:Z("Company-level sending state: active, paused, or suspended. Anything other than active blocks every send, including test sends."),pauseReason:Lw("Exact enforcement message, including the measured rate, the threshold it crossed, and the send volume it was measured over. Null when sending is active."),pauseReasonKind:Lw("Machine-readable pause cause: high_hard_bounce_rate, high_soft_bounce_rate, high_complaint_rate, phishing_guard, manual, or other. Only high_hard_bounce_rate can be cleared with resume_sending."),pausedAt:Lw("ISO timestamp when sending was paused. Null when sending is active."),selfResume:I("Whether the account can clear this pause itself: canSelfResume, supported, allowedByAdmin, ownerIsTrusted, the automated aiReviewStatus (not_required, pending, approved, flagged, failed) with its reason and timestamps, and unavailableReason naming the blocking gate (unsupported_reason, waiting_for_review, blocked_by_ai, review_failed, blocked_by_admin)."),senderHealth:j0("Enforcement counts and the thresholds that apply at this volume for hard bounces, soft bounces, and complaints. bounceScopedSent is the denominator for bounce rates, complaintScopedSent is the denominator for complaint rates, and scopedSent remains as a backward-compatible alias for bounceScopedSent. Also includes enforcementMode. Null when the account has no metrics record yet or sender-health analytics are temporarily unavailable; pause state and remediation remain authoritative."),metricsWindow:I("Proof that enforcement is not time-windowed: kind is always all_time_since_reset and expiresAt is always null. bounceResetAt and complaintResetAt are the watermarks the totals are counted from. Do not tell the user to wait for a window to expire - there is none."),remediation:I("Ordered steps for the current state, plus supportEmail, docsUrl, and the dashboard URL. Relay these verbatim instead of improvising recovery advice.")},resume_sending:{resumed:d("True when this call restored sending. False when sending was already active."),message:n1,status:Z("Sending state after the request. active on success."),selfResume:I("Self-resume state after the request, including the automated review status and how many gates remain."),metricsWindow:I("Enforcement watermarks after the resume. bounceResetAt moves to now, so the paused rate is recalculated from later sends."),remediation:I("Steps to keep sending healthy after the resume, plus supportEmail and docsUrl.")},get_tracking_settings:{tracking:I("Open, click, and unsubscribe tracking flags, the opt-in strictBotFilteringEnabled bot-detection flag, plus the default attribution window in hours."),consent:I("Signup consent settings: doubleOptInEnabled, and doubleOptInEmailId for the confirmation email sent to pending contacts (null when double opt-in has never been enabled)."),autoUtm:I("Automatic UTM tagging state and its configured parameters."),trackingDomain:j0("Dedicated click-tracking domain with verification and SSL status. Null when click links use the shared Sequenzy tracking domain."),replyTracking:I("Inbound reply tracking configuration.")},update_tracking_settings:{message:n1,tracking:I("Open, click, and unsubscribe tracking flags, the opt-in strictBotFilteringEnabled bot-detection flag, plus the default attribution window in hours, after the update."),consent:I("Signup consent settings after the update: doubleOptInEnabled, and doubleOptInEmailId for the confirmation email, which is provisioned automatically the first time double opt-in is enabled."),autoUtm:I("Automatic UTM tagging state and its configured parameters, after the update."),trackingDomain:j0("Dedicated click-tracking domain with verification and SSL status. Null when click links use the shared Sequenzy tracking domain."),replyTracking:I("Inbound reply tracking configuration. Unchanged by this tool; set it with update_company.")},add_website:{website:j("Sending domain with its cohort-specific DNS records. Publish every returned record, including DMARC when present.")},add_sending_domain:{website:j("Sending domain with its cohort-specific DNS records. Publish every returned record, including DMARC when present.")},check_website:{website:j("sending domain with separate DNS verification and readyToSend home-transport readiness"),ready:d("Whether the sender website is ready."),status:Z("Current processing or verification status.")},verify_sending_domain:{website:j("Sending domain with current DNS verification, readyToSend home-transport readiness, SPF, DKIM, and MAIL FROM details."),verified:d("Whether the sending domain passed the fresh DNS verification check. This does not by itself mean SES or MTA is ready."),readyToSend:d("Whether DNS and the selected home transport are both ready for sending."),message:Z("Verification result summary.")},get_integration_guide:{guide:j("integration guide"),code:Z("Generated integration code or example."),steps:{type:"array",description:"Setup steps for the requested integration.",items:I("One setup step.")}},add_subscriber:{subscriber:j("subscriber")},create_subscriber_import:{import:j("subscriber import")},get_subscriber_import:{import:j("subscriber import")},update_subscriber:{subscriber:j("subscriber")},remove_subscriber:{subscriber:j("subscriber"),hardDeleted:d("Whether the subscriber was permanently deleted.")},get_subscriber:{subscriber:j("subscriber")},list_subscriber_notes:{notes:h("subscriber note")},add_subscriber_note:{note:j("subscriber note")},delete_subscriber_note:{id:Z("Deleted subscriber note ID."),deleted:d("Whether the subscriber note was deleted.")},trigger_subscriber_event:{subscriber:j("subscriber"),event:j("recorded event with its name and whether the event definition was created"),sideEffectFailures:{type:"array",description:"Sync-rule or automation side effects that failed. The event itself is still recorded.",items:Z("One failed side effect.")}},trigger_subscriber_events:{subscriber:j("subscriber"),events:h("recorded event")},bulk_add_subscriber_tags:{tags:{type:"array",description:"Normalized tag names applied to every matched subscriber.",items:Z("One tag name.")},requested:y("Identifiers supplied in the request."),matched:y("Existing subscribers resolved."),updated:y("Subscribers whose tags actually changed."),unchanged:y("Subscribers that already carried every tag."),failed:y("Subscribers whose update failed."),notFound:I("Identifiers that did not resolve, grouped as emails, externalIds, and subscriberIds. These subscribers were NOT created."),failures:h("per-subscriber failure (up to 50)"),triggeredAutomations:d("Whether tag_added sequences were allowed to enroll these contacts.")},bulk_remove_subscriber_tags:{tags:{type:"array",description:"Normalized tag names removed from every matched subscriber.",items:Z("One tag name.")},requested:y("Identifiers supplied in the request."),matched:y("Existing subscribers resolved."),updated:y("Subscribers whose tags actually changed."),unchanged:y("Subscribers that did not carry any of the tags."),failed:y("Subscribers whose update failed."),notFound:I("Identifiers that did not resolve, grouped as emails, externalIds, and subscriberIds."),failures:h("per-subscriber failure (up to 50)")},search_subscribers:{subscribers:h("subscriber"),pagination:I("Pagination metadata."),returned:y("Number of subscribers returned."),truncated:d("Whether the result was truncated by the requested limit.")},list_products:{products:h("product"),pagination:I("Pagination metadata: limit, offset, count (this page), total (whole catalog) and hasMore. Page with offset when hasMore is true.")},upsert_products:{products:h("product"),created:y("Number of products created."),updated:y("Number of products updated.")},delete_product:{productId:Z("Deleted product ID.")},attach_product_file:{product:j("product"),delivery:j("digital delivery file")},remove_product_file:{product:j("product")},upload_image_asset:{asset:j("hosted image asset"),imageBlock:I("Ready-to-insert Sequenzy image block using the hosted asset URL.")},sync_products:{job:j("product sync job"),jobId:Z("Queued product sync job ID.")},list_tags:{tags:h("tag")},create_tag:{tag:j("tag")},update_tag:{tag:j("tag")},delete_tag:{tagId:Z("Deleted tag ID.")},list_lists:{lists:h("list")},create_list:{list:j("list")},update_list:{list:j("list")},delete_list:{listId:Z("Deleted list ID.")},add_subscribers_to_list:{list:j("list"),added:y("Number of subscribers added to the list."),skipped:y("Number of subscribers skipped.")},remove_subscribers_from_list:{list:j("list"),removed:y("Number of subscribers removed from the list."),skipped:y("Number of subscribers skipped.")},list_segments:{segments:h("segment")},create_segment:{segment:j("segment")},update_segment:{segment:j("segment")},delete_segment:{segmentId:Z("Deleted segment ID.")},get_segment_count:{count:y("Number of subscribers matching the segment."),segmentId:Z("Segment ID that was counted.")},list_audience_syncs:{audienceSyncs:h("audience sync")},list_ad_accounts:{adAccounts:h("ad account")},create_audience_sync:{audienceSync:j("audience sync")},update_audience_sync:{audienceSync:j("audience sync")},delete_audience_sync:{audienceSyncId:Z("Deleted audience sync ID.")},sync_audience_now:{audienceSync:j("audience sync"),job:j("audience sync job"),jobId:Z("Queued audience sync job ID.")},list_templates:{templates:h("email template")},get_template:{template:j("email template")},create_template:{template:j("email template")},update_template:{template:j("email template")},set_template_localization:{templateId:Z("Localized template ID."),localization:j("template localization")},sync_template_localizations:{templateId:Z("Template ID queued for localization."),queuedLocales:{type:"array",description:"Locale codes queued for AI translation.",items:Z("One queued locale code.")},queuedVariantCount:y("Number of localized variants queued for translation.")},delete_template:{templateId:Z("Deleted template ID.")},list_ab_tests:{abTests:h("A/B test")},get_ab_test:{abTest:j("A/B test")},get_ab_test_stats:{abTest:j("A/B test"),stats:j("A/B test statistics")},restart_ab_test:{abTest:j("A/B test")},update_ab_test_variant:{abTest:j("A/B test"),variant:j("A/B test variant")},update_ab_test:{abTest:j("A/B test")},create_ab_test:{abTest:j("A/B test")},add_ab_test_variant:{abTest:j("A/B test"),variant:j("A/B test variant")},delete_ab_test_variant:{abTest:j("A/B test"),variantId:Z("Deleted A/B test variant ID.")},delete_ab_test:{abTestId:Z("Deleted A/B test ID.")},list_campaigns:{campaigns:h("campaign"),pagination:I("Campaign page window: `limit`, `offset`, `count` returned in this page, `total` matching the filters, and `hasMore`. Keep calling with an advanced `offset` while `hasMore` is true to enumerate every campaign.")},get_campaign:{campaign:j("campaign")},get_campaign_audience:{campaignId:Z("Campaign the audience was resolved for."),campaignName:Z("Campaign name."),status:Z("Campaign status."),audience:I("Resolved targeting: `type`, a plain-language `summary`, `isUnset` (true when scheduling would fall back to every active subscriber), resolved `lists` and `segments` with names and a `missing` flag, `filters`, `include`/`exclude` rules, and individual subscriber adjustments."),recipientCount:y("Number of subscribers matching the effective targeting right now."),targetLists:j0("Raw stored targeting exactly as persisted on the campaign. Null when targeting has never been set.")},get_email_send:{emailSend:j("email send, including copied-recipient identity and primary email send ID when applicable"),events:h("email delivery event")},list_email_sends:{emailSends:h("email send"),pagination:j("email send pagination"),retentionDays:y("Number of days sent-email rows remain queryable in this collection.")},get_recipient_suppression:{suppression:j("recipient suppression status")},remove_recipient_suppression:{removed:d("Whether stale bounce suppression was removed."),removedLocalBounce:d("Whether the platform-local bounce block was removed."),removedSesRegions:{type:"array",description:"AWS SES regions where a bounce suppression was removed.",items:Z("One AWS SES region.")},remainingSuppression:j("recipient suppression status after cleanup")},create_campaign:{campaign:j("campaign")},update_campaign:{campaign:j("campaign")},schedule_campaign:{campaign:j("campaign"),scheduledAt:Z("Scheduled send timestamp.")},unschedule_campaign:{campaign:j("draft campaign")},send_test_email:{emailSendId:Z("Durable test email delivery ID."),recipientEmail:Z("Test email recipient.")},send_test_sms:{smsSendId:Z("Created test SMS send ID."),toPhone:Z("Normalized E.164 destination phone.")},cancel_campaign:{campaign:j("campaign")},pause_campaign:{campaign:j("campaign")},resume_campaign:{campaign:j("campaign")},delete_campaign:{campaignId:Z("Deleted campaign ID.")},duplicate_campaign:{campaign:j("duplicated campaign")},resend_campaign_to_non_openers:{campaign:j("non-opener resend draft campaign"),estimatedNonOpenerCount:y("Estimated number of subscribers who haven't opened the original campaign.")},list_forms:{forms:h("saved form")},create_form:{form:j("saved form"),embed:I("Public action URL plus JavaScript, native form, and fetch snippets.")},update_form:{form:j("saved form"),embed:I("Public action URL plus JavaScript, native form, and fetch snippets (published forms only).")},get_form_embed:{form:j("saved form"),embed:I("Public action URL plus JavaScript, native form, and fetch snippets.")},list_landing_pages:{landingPages:h("landing page")},get_landing_page:{landingPage:j("landing page")},create_landing_page:{landingPage:j("landing page")},update_landing_page:{landingPage:j("landing page")},duplicate_landing_page:{landingPage:j("landing page")},delete_landing_page:{landingPageId:Z("Deleted landing page ID.")},publish_landing_page:{landingPage:j("landing page")},unpublish_landing_page:{landingPage:j("landing page")},connect_landing_page_domain:{landingPage:j("landing page"),domain:Z("Connected landing page domain.")},update_landing_page_domain_settings:{landingPage:j("landing page"),domain:Z("Landing page domain.")},list_sequences:{sequences:Kj,pagination:I("Sequence page window: `limit` (null when limit and offset were both omitted and every sequence was returned), `offset`, `count` returned in this page, `total` matching the filters, and `hasMore`.")},get_sequence:{sequence:p1},list_sequence_enrollments:{sequenceId:Z("Sequence ID these enrollments belong to."),sequenceName:Z("Sequence name."),statuses:{type:"array",description:"Enrollment statuses included in this response. Defaults to active and waiting.",items:{type:"string",description:"Enrollment status."}},enrollments:{type:"array",description:"Contact-level enrollments matching the filters, one row per enrollment token.",items:{type:"object",description:"One subscriber's enrollment in this sequence.",properties:{enrollmentId:Z("Enrollment token ID. Stable identifier for this one run through the sequence."),sequenceId:Z("Sequence ID."),subscriberId:Z("Subscriber ID."),email:Lw("Subscriber email address. Falls back to the address captured at enrollment when the subscriber record no longer exists, and is null when neither is known."),firstName:Lw("Subscriber first name, or null when unset."),lastName:Lw("Subscriber last name, or null when unset."),subscriberStatus:Lw("Subscriber status (active, unsubscribed, bounced), or null when the subscriber record no longer exists."),status:Z("Enrollment status: active, waiting, completed, failed, or cancelled."),currentNodeId:Z("Sequence node this enrollment is currently sitting on."),currentNodeType:Z("Current sequence node type. Omitted when the node no longer exists in the graph."),currentNodeLabel:Z("Current sequence node label or email subject when available."),currentNodeMissing:d("Whether the current node no longer exists in the sequence graph."),enrollmentKey:Z("Key that distinguishes concurrent enrollments of the same subscriber in this sequence."),enrollmentStartedAt:Z("ISO 8601 timestamp when this enrollment entered the sequence."),waitUntil:Lw("ISO 8601 timestamp this enrollment is scheduled to resume, or null when nothing is scheduled."),lastUpdatedAt:Z("ISO 8601 timestamp of the last change to this enrollment. For a waiting enrollment this is when it arrived at its current node; the platform does not separately track node entry time."),failedReason:Lw("Why this enrollment stopped, for status `failed`. Null for every other status and for failures recorded before this field existed. A reason repeated across enrollments on the same currentNodeId points at that step's configuration or content rather than at the contacts.")},required:["enrollmentId","sequenceId","subscriberId","status","currentNodeId","currentNodeMissing","enrollmentStartedAt"]}},pagination:I("Pagination metadata.")},send_sequence_test_email:{sequenceId:Z("Sequence ID."),nodeId:Z("Tested sequence email-step node ID."),results:F1("Per-recipient test-send results containing recipientEmail, durable emailSendId, and legacy jobId.")},create_sequence:{sequence:p1,eventTrackingCode:Z("Ready-to-adapt code for sending a custom trigger event, including any matching-field property."),eventTracking:I("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:Z("One required event name.")}},update_sequence:{sequence:v5},update_sequence_node:{sequence:j("sequence")},update_sequence_nodes:{sequence:j("sequence")},edit_sequence_graph:{sequence:v5},insert_sequence_step:{sequence:j("sequence"),insertedNodeIds:{type:"array",description:"Node IDs created for a linear inserted step, including any delay or wait-for-event node.",items:Z("Inserted automation node ID.")},insertedEmailIds:{type:"array",description:"Email template IDs created for the inserted step.",items:Z("Inserted email template ID.")},insertedEmailCount:y("Number of email steps inserted."),addedBranchNodeId:Z("New logic_branch node ID when the inserted step is a branch."),addedBranchPathNodeIds:I("Created path node IDs keyed by branch ID, plus else. Directly wired paths have empty arrays.")},enable_sequence:{sequenceId:Z("Sequence ID."),status:Z("Stored lifecycle status after the change."),enrollmentPaused:d("Whether new sequence enrollments are paused."),...G4},disable_sequence:{sequenceId:Z("Sequence ID."),status:Z("Stored lifecycle status after the change."),enrollmentPaused:d("Whether new sequence enrollments are paused."),...G4},duplicate_sequence:{sequence:p1,nodes:h("sequence node"),edges:h("sequence edge")},archive_sequence:{sequence:p1},unarchive_sequence:{sequence:p1},list_sequence_goals:{goals:h("sequence goal")},create_sequence_goal:{goal:j("sequence goal")},update_sequence_goal:{goal:j("sequence goal")},delete_sequence_goal:{goalId:Z("Deleted sequence goal ID.")},get_sequence_inbound_webhook:{webhook:j("sequence inbound webhook")},configure_sequence_inbound_webhook:{webhook:j("sequence inbound webhook")},rotate_sequence_inbound_webhook_secret:{webhook:j("sequence inbound webhook")},pause_sequence_enrollments:{sequenceId:Z("Sequence ID."),enrollmentPaused:d("Whether new sequence enrollments are paused."),...G4},resume_sequence_enrollments:{sequenceId:Z("Sequence ID."),enrollmentPaused:d("Whether new sequence enrollments are paused."),...G4},enroll_subscribers_in_sequence:{sequence:j("sequence"),enrollments:h("sequence enrollment"),enrolled:y("Number of subscribers enrolled."),skipped:y("Number of subscribers skipped.")},cancel_sequence_enrollments:{sequenceId:Z("Sequence ID."),dryRun:d("Whether this call only reported matches instead of cancelling them."),target:I("Resolved cancellation target: mode all, subscriber, subscribers (with notFoundSubscriberIds), or field."),matchedCount:y("Active/waiting enrollments matching the target when the request started."),cancelledCount:y("Enrollments cancelled by this call."),remainingCount:y("Enrollments still matching after this call. Repeat the same request while this is above zero."),enrollments:h("sequence enrollment sample (up to 50)"),hasMore:d("Whether more enrollments matched than the returned sample.")},delete_sequence:{sequenceId:Z("Deleted sequence ID.")},list_transactional_emails:{transactional:h("transactional email with subject, all-time delivery metrics, and dashboard URL")},get_transactional_email:{transactional:j("transactional email")},create_transactional_email:{transactional:j("transactional email")},update_transactional_email:{transactional:j("transactional email")},delete_transactional_email:{deleted:I("Deleted transactional email: id, slug, name, and emailId of the email content that was kept as a reusable template.")},send_email:{emailSendId:Z("Durable email delivery ID."),emailType:{type:"string",enum:["marketing","transactional"],description:"Delivery policy accepted for the queued email."},transactional:j("transactional email")},get_stats:{stats:I(`Account-wide delivery funnel for the requested window. ${C1}`),emailType:Z("Applied structural email type filter when one was requested."),commerceForecast:j("Optional background-computed commerce AOV, 12-month customer value, and 90-day revenue forecast. Omitted when no snapshot is available; insufficient_data is returned only after eligibility was evaluated successfully.")},get_campaign_stats:{campaign:j("campaign"),stats:I(`Delivery funnel for this campaign. ${C1}`),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:I("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. Multi-select polls set allowMultiple: true, count each subscriber once per selected option (answer percentages can sum past 100), and report totalResponses as the respondent count. To list the exact historical respondents behind a count, use the summary blockId and the get_campaign_stats campaignId with create_segment. ${v1} A summary's attributeKey identifies the subscriber attribute that stores their current/latest response (a value list for multi-select polls) and may be overwritten by a later poll that reuses the key.`,items:I("One poll or NPS results summary.")},recommendations:I("Product recommendation funnel: impressions, recipients, clicks, clickers, orders, legacy revenueCents, currency-safe revenueByCurrency totals, and topProducts (per-product impressions/clicks). Orders count when a subscriber buys a recommended product within 7 days of clicking it. Present only when the campaign rendered product recommendation blocks.")},get_transactional_stats:{transactional:j("transactional email"),stats:I(`Delivery funnel for this transactional email. ${C1}`),complaints:j("complaint count and rate for the selected transactional email"),clickedLinks:h("clicked link with click count and percentage share"),bounceBreakdown:j("permanent, transient, and undetermined bounce counts plus subtype details"),engagementBreakdown:j("human and machine open and click counts")},get_sequence_stats:{sequence:p1,stats:I(`Delivery funnel across every email step in this sequence. ${C1}`),steps:{type:"array",description:`Per-step delivery funnel: one entry per email step of the sequence, in graph order, each with its own sent/delivered/opened/clicked counts. Read this to answer "how many of step N went out" - do not recount list_sequence_events. Counts come from the retained event stream, so they are not limited to the 14-day list_email_sends history. ${C1}`,items:{type:"object",description:"Metrics for one email step of the sequence.",properties:{step:y("1-based position of this email step in graph order. Step 4 is the fourth email a contact receives on the traversed path; on a branching graph, positions are assigned by traversal, so cross-check nodeId when a sequence forks."),nodeId:Z("Automation node ID of this email step. Pass it to list_sequence_events or list_email_sends as automationNodeId to reach the individual recipients behind these counts, and it is the emailId that list_email_metrics reports for sequence emails."),subject:Lw("Subject line of the step's email, falling back to the node label, or null when neither is set."),stats:I(`Delivery funnel for this step alone: sent, delivered, bounced, opened, clicked, replies, unsubscribed, and their rates. ${C1}`),failedCount:y("Contacts currently stuck on this step with a failed enrollment."),failedSubscribers:F1("Up to 20 of the failed contacts on this step, as { subscriberId, email, failedAt, failedReason }.")},required:["step","nodeId","stats"],additionalProperties:!0}},enrollmentCounts:{type:"object",description:"Live enrollment-token counts for this sequence. Includes only active and waiting enrollments and is always a current snapshot, independent of historical period/start/end filters.",properties:{active:y("Active enrollment count."),waiting:y("Waiting enrollment count."),total:y("Total active plus waiting enrollment count."),byCurrentNode:{type:"array",description:"Live active and waiting enrollment counts grouped by the token's current sequence node.",items:{type:"object",description:"Enrollment counts for one current sequence node.",properties:{currentNodeId:Z("Current sequence node ID."),currentNodeType:Z("Current sequence node type. Omitted when the node no longer exists in the graph."),currentNodeLabel:Z("Current sequence node label or email subject when available."),currentNodeMissing:d("Whether the current node no longer exists in the sequence graph."),active:y("Active enrollment count at this node."),waiting:y("Waiting enrollment count at this node."),total:y("Total active plus waiting enrollment count at this node.")},required:["currentNodeId","currentNodeMissing","active","waiting","total"],additionalProperties:!1}}},required:["active","waiting","total","byCurrentNode"],additionalProperties:!1},enrollmentSkipped:{type:"object",description:"Trigger matches where an unsubscribed or bounced contact could not be enrolled, including the total count and counts grouped by reason. Uses the requested period or start/end range; without an explicit range, this field defaults to the last 30 days.",properties:{count:y("Total skipped sequence enrollments."),byReason:{type:"object",description:"Skipped enrollment counts keyed by reason, such as unsubscribed or bounced.",additionalProperties:y("Skipped enrollment count for this reason.")}},required:["count","byReason"],additionalProperties:!1},recommendations:I("Product recommendation funnel aggregated across the sequence's email nodes: impressions, recipients, clicks, clickers, orders, legacy revenueCents, currency-safe revenueByCurrency totals, and topProducts. Present only when the sequence rendered product recommendation blocks.")},list_campaign_events:{events:h("campaign email event"),pagination:I("Pagination metadata.")},list_sequence_events:{events:h("sequence email event"),pagination:I("Pagination metadata.")},list_email_metrics:{emails:{type:"array",description:"One entry per email in scope: each campaign and each sequence email step, sorted by the requested sort/order.",items:{type:"object",description:"Metrics for one campaign or one sequence email step.",properties:{emailType:{type:"string",enum:["campaign","sequence"],description:"Whether this row is a campaign or a sequence email."},emailId:Z("Stable identifier: the campaign ID for campaigns, the automation node ID for sequence emails."),name:Z("Campaign name, or the sequence step's subject line falling back to its node label."),campaignId:Lw("Campaign ID, or null for sequence emails."),sequenceId:Lw("Sequence ID, or null for campaigns."),sequenceName:Lw("Name of the sequence this step belongs to, or null for campaigns."),automationNodeId:Lw("Automation node ID of this step, or null for campaigns. Pass it as automationNodeId to list_sequence_events or list_email_sends to reach the recipients behind these counts."),step:{type:["number","null"],description:"1-based position of this email in its sequence, counted in graph order, or null for campaigns. Matches the step number in get_sequence_stats steps[]."},stats:I(`Delivery funnel for this email alone. ${C1}`),conversions:y("Attributed conversions credited to this email."),revenueCents:y("Attributed revenue in minor currency units credited to this email.")},required:["emailType","emailId","name","stats"],additionalProperties:!0}},totals:I(`Summed funnel across every email matching the filters, not just the returned page, plus \`emails\` (the number of matching emails), \`conversions\`, and \`revenueCents\`. Read totals.sent for "how many of this step went out in total". ${C1}`),pagination:I("Pagination metadata."),sort:Z("Sort field the response was ordered by."),order:Z("Sort order the response was ordered by."),step:y("Echo of the step filter, present only when one was requested."),sequenceIds:{type:"array",description:"Echo of the sequence IDs the breakdown was scoped to, present only when scoped.",items:Z("Sequence ID.")}},get_subscriber_activity:{activity:h("subscriber activity event"),subscribers:h("subscriber"),pagination:I("Pagination metadata.")},list_team_members:{members:h("team member"),invitations:h("team invitation")},invite_team_member:{invitation:j("team invitation")},cancel_team_invitation:{invitationId:Z("Cancelled invitation ID.")},list_conversations:{conversations:h("inbox conversation"),pagination:I("Pagination metadata.")},get_conversation:{conversation:j("inbox conversation"),messages:h("conversation message")},reply_to_conversation:{conversation:j("inbox conversation"),message:j("conversation message")},update_conversation_status:{conversation:j("inbox conversation")},mark_conversation_read:{conversation:j("inbox conversation")},list_webhooks:{webhooks:h("outbound webhook")},create_webhook:{webhook:j("outbound webhook")},update_webhook:{webhook:j("outbound webhook")},delete_webhook:{webhookId:Z("Deleted outbound webhook ID.")},test_webhook:{webhook:j("outbound webhook"),delivery:j("test webhook delivery")},list_webhook_deliveries:{deliveries:h("webhook delivery")},replay_webhook_delivery:{delivery:j("webhook delivery"),job:j("webhook replay job")},generate_email:{email:j("generated email"),html:Z("Generated HTML email body."),blocks:{type:"array",description:"Generated Sequenzy email blocks, wrapped with company branding (logo + footer) unless applyBranding was false.",items:I("One generated email block.")},subject:Z("Generated subject line."),previewText:Z("Generated inbox preview text.")},generate_sequence:{sequence:j("persisted AI-generated sequence draft"),deprecated:d("Always true for this deprecated alias."),deprecationMessage:Z("Migration guidance directing callers to create_sequence.")},generate_subject_lines:{subjectLines:{type:"array",description:"Generated subject line variants.",items:Z("One generated subject line.")},variants:h("generated subject line variant")},generate_sms:{prompt:Z("The prompt the messages were generated for."),messages:{type:"array",description:"Generated SMS message variants with encoding and segment counts.",items:I("One generated SMS message.")}},get_sms_settings:{sms:I("SMS add-on status: enabled, planEligible, creditsBalance, brandPrefix, numbers, readyToSend (paid plan or credits plus an active number).")},submit_feedback:{},render_email:{html:Z("Email-safe HTML document, rendered exactly as it would be sent."),subject:Z("Subject line with merge tags resolved."),previewText:Lw("Inbox preview text with merge tags resolved, or null when unset."),locale:Z("Localization locale the render resolved to."),personalized:d("Whether a real contact was supplied. False means a sample contact was used, so contact-specific merge tags resolve to empty values."),trackingApplied:d("Whether auto-UTM link decoration was applied."),unresolvedMergeTags:F1(`Merge tags that rendered as an empty string, as [{ tag, reason }]. reason "unknown" means nothing provides that name, so it stays empty for every recipient - usually a typo or a tag copied from another platform. reason "no_value" means the name is recognized, or could not be checked, but is blank for this contact. A name is only called unknown when the render had a source to check it against. Without the contact's attributes nothing is checkable, since a bare {{plan}} reads the same attribute map as {{subscriber.plan}}, so pass a stored subscriberId or an inline subscriber carrying customAttributes. Beyond that, {{event.*}} needs sample event properties in variables, since a real send fills those from the enrolling event; {{recommendedProducts.*}} needs a stored subscriberId the catalog has something to recommend for; and {{discount.*}} is only checkable on a sequence step whose incoming paths all run the same discount step, never on a standalone template. Rendering a transactional email is checkable only when variables is passed, because its tags come from the variables of each send call and carry no prefix marking them. Otherwise those tags land in no_value rather than in unknown. An optional attribute this contact never had set is kept out of unknown by checking the names other contacts in the account carry, which needs the subscribers:read scope; a key without it may report such a name as unknown. An empty array means every tag in the email resolved.`),entity:I("Which entity was rendered: type, id, and variantId.")}};function Vj(w){let b=Mj[w];if(b===void 0)throw Error(`MCP tool "${w}" must define outputSchema properties.`);return{type:"object",description:`Structured content returned by the \`${w}\` MCP tool.`,properties:{...Zj,...b,...$W.has(w)?Oj:{}},additionalProperties:!0}}function _5(w){return{...w,outputSchema:Vj(w.name)}}function x5(w){if(C(w))return w;if(Array.isArray(w))return{items:w};return{value:w}}var h5=[{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:kw},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 an A/B test variant. Campaign variants are editable only in draft. Sequence variants can be edited after activity with confirmLiveChange, but earlier sends stay unchanged and combined results may no longer be accurate. 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. ${Hw}`},blocks:{type:"array",description:`${L1}${l1} Mutually exclusive with html.`,items:{type:"object"}},confirmLiveChange:{type:"boolean",description:"Required as true when the sequence is active, the test is no longer a draft, or it has recorded activity. The edit affects future sends and can make combined results inaccurate."}},required:["abTestId","variantId"],additionalProperties:!1}},{name:"update_ab_test",description:"Update A/B test settings. Campaign tests use testPercentage, testDurationMinutes, and winnerCriteria. Sequence tests use testType, winnerThreshold, and winnerCriteria; changing live or already-used sequence settings requires confirmLiveChange. Provide at least one setting.",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"},name:{type:"string",description:"Optional A/B test name."},testPercentage:{type:"number",description:"Campaign-only percentage of the audience used for the test phase, from 5 to 50."},testDurationMinutes:{type:"number",description:"Campaign-only test duration in minutes, from 15 to 1440."},winnerCriteria:{type:"string",enum:["open_rate","click_rate"],description:"Winner selection criteria. Applies to both campaign and sequence tests."},testType:{type:"string",enum:["subject","content"],description:"Sequence-only variant strategy. When winnerCriteria is omitted, subject defaults to open_rate and content defaults to click_rate."},winnerThreshold:{type:"number",description:"Sequence-only number of recipients before selecting a winner, from 10 to 1000."},confirmLiveChange:{type:"boolean",description:"Required as true when sequence settings affect an active test or a test with recorded activity."}},required:["abTestId"],additionalProperties:!1}},{name:"create_ab_test",description:"Create a campaign A/B test or convert a sequence email node into a typed A/B test node. Provide exactly one of campaignId or automationNodeId. Control variant A is created automatically from the current email. Campaign tests may add variants later; automationNodeId conversions require at least one variants[] entry to compete with control variant A.",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. Mutually exclusive with automationNodeId."},automationNodeId:{type:"string",description:"Sequence email-node ID to convert to action_ab_test. Mutually exclusive with campaignId."},confirmLiveChange:{type:"boolean",description:"Required as true when converting an email node in an active sequence."},name:{type:"string",description:"Optional A/B test name."},testPercentage:{type:"number",description:"Campaign-only percentage of the audience used for the test phase, from 5 to 50. Defaults to 20. Sequence tests use winnerThreshold instead."},testDurationMinutes:{type:"number",description:"Campaign-only test phase duration in minutes, from 15 to 1440. Defaults to 240. Sequence tests select after winnerThreshold recipients instead."},winnerCriteria:{type:"string",enum:["open_rate","click_rate"],description:"Winner selection criteria. Campaign tests default to open_rate. For sequence tests, an explicit value overrides the testType default."},testType:{type:"string",enum:["subject","content"],description:"Sequence A/B test variant strategy. Subject defaults to open_rate and content defaults to click_rate unless winnerCriteria is explicit. Defaults to content."},winnerThreshold:{type:"number",description:"Sequence test sample size from 10 to 1000. Defaults to 100."},variants:{type:"array",maxItems:4,description:"Extra variants to create in addition to control variant A. Optional for campaign tests; automationNodeId conversions require at least one entry.",items:{type:"object",properties:{subject:{type:"string",description:"Variant subject line."},previewText:{type:"string",description:"Variant preview text."},blocks:{type:"array",description:`${L1}${l1}`,items:{type:"object"}}},required:["subject"]}}}}},{name:"add_ab_test_variant",description:"Add a variant to a draft campaign or sequence A/B test. Sequence variants receive their own editable email template. Variants cannot be added after the test has started. Sequence tests whose parent sequence is active require confirmLiveChange.",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:`${L1}${l1}`,items:{type:"object"}},confirmLiveChange:{type:"boolean",description:"Required as true when the A/B test belongs to an active sequence, because new variants immediately enter the live rotation."}},required:["abTestId","subject"]}},{name:"delete_ab_test_variant",description:"Permanently delete a variant from a draft campaign or sequence 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. Sequence tests whose parent sequence is active require confirmLiveChange.",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."},confirmLiveChange:{type:"boolean",description:"Required as true when the A/B test belongs to an active sequence, because deletion immediately changes the live rotation."}},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 y5=[{name:"get_account",description:`Get current account information including available companies, the current API key's permission scopes, and the API Keys management URL. Call this after a missing-scope error to inspect access and find the replacement-key settings. IMPORTANT: If you have access to multiple companies, you MUST either:
28
+ `)}F.write("payload.value = newResult;"),F.write("return payload;");let v=F.compile();return(S,u)=>v(L,S,u)},X,J=y0,Y=!kb.jitless,H=Y&&q4.value,z=b.catchall,B;w._zod.parse=(L,F)=>{B??(B=Q.value);let A=L.value;if(!J(A))return L.issues.push({expected:"object",code:"invalid_type",input:A,inst:w}),L;if(Y&&H&&F?.async===!1&&F.jitless!==!0){if(!X)X=W(b.shape);if(L=X(L,F),!z)return L;return MW([],A,L,F,B,w)}return $(L,F)}});function y8(w,b,$,Q){for(let X of w)if(X.issues.length===0)return b.value=X.value,b;let W=w.filter((X)=>!P0(X));if(W.length===1)return b.value=W[0].value,W[0];return b.issues.push({code:"invalid_union",input:b.value,inst:$,errors:w.map((X)=>X.issues.map((J)=>n1(J,Q,y1())))}),b}var h4=O("$ZodUnion",(w,b)=>{w1.init(w,b),s(w._zod,"optin",()=>b.options.some((W)=>W._zod.optin==="optional")?"optional":void 0),s(w._zod,"optout",()=>b.options.some((W)=>W._zod.optout==="optional")?"optional":void 0),s(w._zod,"values",()=>{if(b.options.every((W)=>W._zod.values))return new Set(b.options.flatMap((W)=>Array.from(W._zod.values)));return}),s(w._zod,"pattern",()=>{if(b.options.every((W)=>W._zod.pattern)){let W=b.options.map((X)=>X._zod.pattern);return new RegExp(`^(${W.map((X)=>kw(X.source)).join("|")})$`)}return});let $=b.options.length===1,Q=b.options[0]._zod.run;w._zod.parse=(W,X)=>{if($)return Q(W,X);let J=!1,Y=[];for(let G of b.options){let H=G._zod.run({value:W.value,issues:[]},X);if(H instanceof Promise)Y.push(H),J=!0;else{if(H.issues.length===0)return H;Y.push(H)}}if(!J)return y8(Y,W,w,X);return Promise.all(Y).then((G)=>{return y8(G,W,w,X)})}}),PW=O("$ZodDiscriminatedUnion",(w,b)=>{h4.init(w,b);let $=w._zod.parse;s(w._zod,"propValues",()=>{let W={};for(let X of b.options){let J=X._zod.propValues;if(!J||Object.keys(J).length===0)throw Error(`Invalid discriminated union option at index "${b.options.indexOf(X)}"`);for(let[Y,G]of Object.entries(J)){if(!W[Y])W[Y]=new Set;for(let H of G)W[Y].add(H)}}return W});let Q=a0(()=>{let W=b.options,X=new Map;for(let J of W){let Y=J._zod.propValues?.[b.discriminator];if(!Y||Y.size===0)throw Error(`Invalid discriminated union option at index "${b.options.indexOf(J)}"`);for(let G of Y){if(X.has(G))throw Error(`Duplicate discriminator value "${String(G)}"`);X.set(G,J)}}return X});w._zod.parse=(W,X)=>{let J=W.value;if(!y0(J))return W.issues.push({code:"invalid_type",expected:"object",input:J,inst:w}),W;let Y=Q.value.get(J?.[b.discriminator]);if(Y)return Y._zod.run(W,X);if(b.unionFallback)return $(W,X);return W.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:b.discriminator,input:J,path:[b.discriminator],inst:w}),W}}),qW=O("$ZodIntersection",(w,b)=>{w1.init(w,b),w._zod.parse=($,Q)=>{let W=$.value,X=b.left._zod.run({value:W,issues:[]},Q),J=b.right._zod.run({value:W,issues:[]},Q);if(X instanceof Promise||J instanceof Promise)return Promise.all([X,J]).then(([G,H])=>{return f8($,G,H)});return f8($,X,J)}});function _4(w,b){if(w===b)return{valid:!0,data:w};if(w instanceof Date&&b instanceof Date&&+w===+b)return{valid:!0,data:w};if(V0(w)&&V0(b)){let $=Object.keys(b),Q=Object.keys(w).filter((X)=>$.indexOf(X)!==-1),W={...w,...b};for(let X of Q){let J=_4(w[X],b[X]);if(!J.valid)return{valid:!1,mergeErrorPath:[X,...J.mergeErrorPath]};W[X]=J.data}return{valid:!0,data:W}}if(Array.isArray(w)&&Array.isArray(b)){if(w.length!==b.length)return{valid:!1,mergeErrorPath:[]};let $=[];for(let Q=0;Q<w.length;Q++){let W=w[Q],X=b[Q],J=_4(W,X);if(!J.valid)return{valid:!1,mergeErrorPath:[Q,...J.mergeErrorPath]};$.push(J.data)}return{valid:!0,data:$}}return{valid:!1,mergeErrorPath:[]}}function f8(w,b,$){if(b.issues.length)w.issues.push(...b.issues);if($.issues.length)w.issues.push(...$.issues);if(P0(w))return w;let Q=_4(b.value,$.value);if(!Q.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(Q.mergeErrorPath)}`);return w.value=Q.data,w}var IW=O("$ZodRecord",(w,b)=>{w1.init(w,b),w._zod.parse=($,Q)=>{let W=$.value;if(!V0(W))return $.issues.push({expected:"record",code:"invalid_type",input:W,inst:w}),$;let X=[];if(b.keyType._zod.values){let J=b.keyType._zod.values;$.value={};for(let G of J)if(typeof G==="string"||typeof G==="number"||typeof G==="symbol"){let H=b.valueType._zod.run({value:W[G],issues:[]},Q);if(H instanceof Promise)X.push(H.then((z)=>{if(z.issues.length)$.issues.push(...Y0(G,z.issues));$.value[G]=z.value}));else{if(H.issues.length)$.issues.push(...Y0(G,H.issues));$.value[G]=H.value}}let Y;for(let G in W)if(!J.has(G))Y=Y??[],Y.push(G);if(Y&&Y.length>0)$.issues.push({code:"unrecognized_keys",input:W,inst:w,keys:Y})}else{$.value={};for(let J of Reflect.ownKeys(W)){if(J==="__proto__")continue;let Y=b.keyType._zod.run({value:J,issues:[]},Q);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((H)=>n1(H,Q,y1())),input:J,path:[J],inst:w}),$.value[Y.value]=Y.value;continue}let G=b.valueType._zod.run({value:W[J],issues:[]},Q);if(G instanceof Promise)X.push(G.then((H)=>{if(H.issues.length)$.issues.push(...Y0(J,H.issues));$.value[Y.value]=H.value}));else{if(G.issues.length)$.issues.push(...Y0(J,G.issues));$.value[Y.value]=G.value}}}if(X.length)return Promise.all(X).then(()=>$);return $}});var EW=O("$ZodEnum",(w,b)=>{w1.init(w,b);let $=V4(b.entries),Q=new Set($);w._zod.values=Q,w._zod.pattern=new RegExp(`^(${$.filter((W)=>I4.has(typeof W)).map((W)=>typeof W==="string"?J0(W):W.toString()).join("|")})$`),w._zod.parse=(W,X)=>{let J=W.value;if(Q.has(J))return W;return W.issues.push({code:"invalid_value",values:$,input:J,inst:w}),W}}),NW=O("$ZodLiteral",(w,b)=>{if(w1.init(w,b),b.values.length===0)throw Error("Cannot create literal schema with no valid values");w._zod.values=new Set(b.values),w._zod.pattern=new RegExp(`^(${b.values.map(($)=>typeof $==="string"?J0($):$?J0($.toString()):String($)).join("|")})$`),w._zod.parse=($,Q)=>{let W=$.value;if(w._zod.values.has(W))return $;return $.issues.push({code:"invalid_value",values:b.values,input:W,inst:w}),$}});var TW=O("$ZodTransform",(w,b)=>{w1.init(w,b),w._zod.parse=($,Q)=>{if(Q.direction==="backward")throw new Sw(w.constructor.name);let W=b.transform($.value,$);if(Q.async)return(W instanceof Promise?W:Promise.resolve(W)).then((J)=>{return $.value=J,$});if(W instanceof Promise)throw new X0;return $.value=W,$}});function u8(w,b){if(w.issues.length&&b===void 0)return{issues:[],value:void 0};return w}var RW=O("$ZodOptional",(w,b)=>{w1.init(w,b),w._zod.optin="optional",w._zod.optout="optional",s(w._zod,"values",()=>{return b.innerType._zod.values?new Set([...b.innerType._zod.values,void 0]):void 0}),s(w._zod,"pattern",()=>{let $=b.innerType._zod.pattern;return $?new RegExp(`^(${kw($.source)})?$`):void 0}),w._zod.parse=($,Q)=>{if(b.innerType._zod.optin==="optional"){let W=b.innerType._zod.run($,Q);if(W instanceof Promise)return W.then((X)=>u8(X,$.value));return u8(W,$.value)}if($.value===void 0)return $;return b.innerType._zod.run($,Q)}}),SW=O("$ZodNullable",(w,b)=>{w1.init(w,b),s(w._zod,"optin",()=>b.innerType._zod.optin),s(w._zod,"optout",()=>b.innerType._zod.optout),s(w._zod,"pattern",()=>{let $=b.innerType._zod.pattern;return $?new RegExp(`^(${kw($.source)}|null)$`):void 0}),s(w._zod,"values",()=>{return b.innerType._zod.values?new Set([...b.innerType._zod.values,null]):void 0}),w._zod.parse=($,Q)=>{if($.value===null)return $;return b.innerType._zod.run($,Q)}}),vW=O("$ZodDefault",(w,b)=>{w1.init(w,b),w._zod.optin="optional",s(w._zod,"values",()=>b.innerType._zod.values),w._zod.parse=($,Q)=>{if(Q.direction==="backward")return b.innerType._zod.run($,Q);if($.value===void 0)return $.value=b.defaultValue,$;let W=b.innerType._zod.run($,Q);if(W instanceof Promise)return W.then((X)=>c8(X,b));return c8(W,b)}});function c8(w,b){if(w.value===void 0)w.value=b.defaultValue;return w}var CW=O("$ZodPrefault",(w,b)=>{w1.init(w,b),w._zod.optin="optional",s(w._zod,"values",()=>b.innerType._zod.values),w._zod.parse=($,Q)=>{if(Q.direction==="backward")return b.innerType._zod.run($,Q);if($.value===void 0)$.value=b.defaultValue;return b.innerType._zod.run($,Q)}}),kW=O("$ZodNonOptional",(w,b)=>{w1.init(w,b),s(w._zod,"values",()=>{let $=b.innerType._zod.values;return $?new Set([...$].filter((Q)=>Q!==void 0)):void 0}),w._zod.parse=($,Q)=>{let W=b.innerType._zod.run($,Q);if(W instanceof Promise)return W.then((X)=>m8(X,w));return m8(W,w)}});function m8(w,b){if(!w.issues.length&&w.value===void 0)w.issues.push({code:"invalid_type",expected:"nonoptional",input:w.value,inst:b});return w}var _W=O("$ZodCatch",(w,b)=>{w1.init(w,b),s(w._zod,"optin",()=>b.innerType._zod.optin),s(w._zod,"optout",()=>b.innerType._zod.optout),s(w._zod,"values",()=>b.innerType._zod.values),w._zod.parse=($,Q)=>{if(Q.direction==="backward")return b.innerType._zod.run($,Q);let W=b.innerType._zod.run($,Q);if(W instanceof Promise)return W.then((X)=>{if($.value=X.value,X.issues.length)$.value=b.catchValue({...$,error:{issues:X.issues.map((J)=>n1(J,Q,y1()))},input:$.value}),$.issues=[];return $});if($.value=W.value,W.issues.length)$.value=b.catchValue({...$,error:{issues:W.issues.map((X)=>n1(X,Q,y1()))},input:$.value}),$.issues=[];return $}});var xW=O("$ZodPipe",(w,b)=>{w1.init(w,b),s(w._zod,"values",()=>b.in._zod.values),s(w._zod,"optin",()=>b.in._zod.optin),s(w._zod,"optout",()=>b.out._zod.optout),s(w._zod,"propValues",()=>b.in._zod.propValues),w._zod.parse=($,Q)=>{if(Q.direction==="backward"){let X=b.out._zod.run($,Q);if(X instanceof Promise)return X.then((J)=>gb(J,b.in,Q));return gb(X,b.in,Q)}let W=b.in._zod.run($,Q);if(W instanceof Promise)return W.then((X)=>gb(X,b.out,Q));return gb(W,b.out,Q)}});function gb(w,b,$){if(w.issues.length)return w.aborted=!0,w;return b._zod.run({value:w.value,issues:w.issues},$)}var hW=O("$ZodReadonly",(w,b)=>{w1.init(w,b),s(w._zod,"propValues",()=>b.innerType._zod.propValues),s(w._zod,"values",()=>b.innerType._zod.values),s(w._zod,"optin",()=>b.innerType._zod.optin),s(w._zod,"optout",()=>b.innerType._zod.optout),w._zod.parse=($,Q)=>{if(Q.direction==="backward")return b.innerType._zod.run($,Q);let W=b.innerType._zod.run($,Q);if(W instanceof Promise)return W.then(l8);return l8(W)}});function l8(w){return w.value=Object.freeze(w.value),w}var yW=O("$ZodCustom",(w,b)=>{U1.init(w,b),w1.init(w,b),w._zod.parse=($,Q)=>{return $},w._zod.check=($)=>{let Q=$.value,W=b.fn(Q);if(W instanceof Promise)return W.then((X)=>g8(X,$,Q,w));g8(W,$,Q,w);return}});function g8(w,b,$,Q){if(!w){let W={code:"custom",input:$,inst:Q,path:[...Q._zod.def.path??[]],continue:!Q._zod.def.abort};if(Q._zod.def.params)W.params=Q._zod.def.params;b.issues.push(ww(W))}}var hz=(w)=>{let b=typeof w;switch(b){case"number":return Number.isNaN(w)?"NaN":"number";case"object":{if(Array.isArray(w))return"array";if(w===null)return"null";if(Object.getPrototypeOf(w)!==Object.prototype&&w.constructor)return w.constructor.name}}return b},yz=()=>{let w={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 b(Q){return w[Q]??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(Q)=>{switch(Q.code){case"invalid_type":return`Invalid input: expected ${Q.expected}, received ${hz(Q.input)}`;case"invalid_value":if(Q.values.length===1)return`Invalid input: expected ${yb(Q.values[0])}`;return`Invalid option: expected one of ${_b(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",X=b(Q.origin);if(X)return`Too big: expected ${Q.origin??"value"} to have ${W}${Q.maximum.toString()} ${X.unit??"elements"}`;return`Too big: expected ${Q.origin??"value"} to be ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",X=b(Q.origin);if(X)return`Too small: expected ${Q.origin} to have ${W}${Q.minimum.toString()} ${X.unit}`;return`Too small: expected ${Q.origin} to be ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Invalid string: must start with "${W.prefix}"`;if(W.format==="ends_with")return`Invalid string: must end with "${W.suffix}"`;if(W.format==="includes")return`Invalid string: must include "${W.includes}"`;if(W.format==="regex")return`Invalid string: must match pattern ${W.pattern}`;return`Invalid ${$[W.format]??Q.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${Q.divisor}`;case"unrecognized_keys":return`Unrecognized key${Q.keys.length>1?"s":""}: ${_b(Q.keys,", ")}`;case"invalid_key":return`Invalid key in ${Q.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${Q.origin}`;default:return"Invalid input"}}};function y4(){return{localeError:yz()}}var DP=Symbol("ZodOutput"),BP=Symbol("ZodInput");class fW{constructor(){this._map=new WeakMap,this._idmap=new Map}add(w,...b){let $=b[0];if(this._map.set(w,$),$&&typeof $==="object"&&"id"in $){if(this._idmap.has($.id))throw Error(`ID ${$.id} already exists in the registry`);this._idmap.set($.id,w)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(w){let b=this._map.get(w);if(b&&typeof b==="object"&&"id"in b)this._idmap.delete(b.id);return this._map.delete(w),this}get(w){let b=w._zod.parent;if(b){let $={...this.get(b)??{}};delete $.id;let Q={...$,...this._map.get(w)};return Object.keys(Q).length?Q:void 0}return this._map.get(w)}has(w){return this._map.has(w)}}function fz(){return new fW}var uw=fz();function uW(w,b){return new w({type:"string",...C(b)})}function cW(w,b){return new w({type:"string",format:"email",check:"string_format",abort:!1,...C(b)})}function f4(w,b){return new w({type:"string",format:"guid",check:"string_format",abort:!1,...C(b)})}function mW(w,b){return new w({type:"string",format:"uuid",check:"string_format",abort:!1,...C(b)})}function lW(w,b){return new w({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...C(b)})}function gW(w,b){return new w({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...C(b)})}function iW(w,b){return new w({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...C(b)})}function nW(w,b){return new w({type:"string",format:"url",check:"string_format",abort:!1,...C(b)})}function pW(w,b){return new w({type:"string",format:"emoji",check:"string_format",abort:!1,...C(b)})}function dW(w,b){return new w({type:"string",format:"nanoid",check:"string_format",abort:!1,...C(b)})}function oW(w,b){return new w({type:"string",format:"cuid",check:"string_format",abort:!1,...C(b)})}function tW(w,b){return new w({type:"string",format:"cuid2",check:"string_format",abort:!1,...C(b)})}function rW(w,b){return new w({type:"string",format:"ulid",check:"string_format",abort:!1,...C(b)})}function sW(w,b){return new w({type:"string",format:"xid",check:"string_format",abort:!1,...C(b)})}function eW(w,b){return new w({type:"string",format:"ksuid",check:"string_format",abort:!1,...C(b)})}function aW(w,b){return new w({type:"string",format:"ipv4",check:"string_format",abort:!1,...C(b)})}function wX(w,b){return new w({type:"string",format:"ipv6",check:"string_format",abort:!1,...C(b)})}function bX(w,b){return new w({type:"string",format:"cidrv4",check:"string_format",abort:!1,...C(b)})}function $X(w,b){return new w({type:"string",format:"cidrv6",check:"string_format",abort:!1,...C(b)})}function QX(w,b){return new w({type:"string",format:"base64",check:"string_format",abort:!1,...C(b)})}function WX(w,b){return new w({type:"string",format:"base64url",check:"string_format",abort:!1,...C(b)})}function XX(w,b){return new w({type:"string",format:"e164",check:"string_format",abort:!1,...C(b)})}function JX(w,b){return new w({type:"string",format:"jwt",check:"string_format",abort:!1,...C(b)})}function YX(w,b){return new w({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...C(b)})}function GX(w,b){return new w({type:"string",format:"date",check:"string_format",...C(b)})}function HX(w,b){return new w({type:"string",format:"time",check:"string_format",precision:null,...C(b)})}function zX(w,b){return new w({type:"string",format:"duration",check:"string_format",...C(b)})}function DX(w,b){return new w({type:"number",checks:[],...C(b)})}function BX(w,b){return new w({type:"number",check:"number_format",abort:!1,format:"safeint",...C(b)})}function LX(w,b){return new w({type:"boolean",...C(b)})}function FX(w,b){return new w({type:"null",...C(b)})}function UX(w){return new w({type:"unknown"})}function AX(w,b){return new w({type:"never",...C(b)})}function pb(w,b){return new v4({check:"less_than",...C(b),value:w,inclusive:!1})}function cw(w,b){return new v4({check:"less_than",...C(b),value:w,inclusive:!0})}function db(w,b){return new C4({check:"greater_than",...C(b),value:w,inclusive:!1})}function mw(w,b){return new C4({check:"greater_than",...C(b),value:w,inclusive:!0})}function ob(w,b){return new V8({check:"multiple_of",...C(b),value:w})}function tb(w,b){return new q8({check:"max_length",...C(b),maximum:w})}function bw(w,b){return new I8({check:"min_length",...C(b),minimum:w})}function rb(w,b){return new E8({check:"length_equals",...C(b),length:w})}function u4(w,b){return new N8({check:"string_format",format:"regex",...C(b),pattern:w})}function c4(w){return new T8({check:"string_format",format:"lowercase",...C(w)})}function m4(w){return new R8({check:"string_format",format:"uppercase",...C(w)})}function l4(w,b){return new S8({check:"string_format",format:"includes",...C(b),includes:w})}function g4(w,b){return new v8({check:"string_format",format:"starts_with",...C(b),prefix:w})}function i4(w,b){return new C8({check:"string_format",format:"ends_with",...C(b),suffix:w})}function f0(w){return new k8({check:"overwrite",tx:w})}function n4(w){return f0((b)=>b.normalize(w))}function p4(){return f0((w)=>w.trim())}function d4(){return f0((w)=>w.toLowerCase())}function o4(){return f0((w)=>w.toUpperCase())}function KX(w,b,$){return new w({type:"array",element:b,...C($)})}function OX(w,b,$){let Q=C($);return Q.abort??(Q.abort=!0),new w({type:"custom",check:"custom",fn:b,...Q})}function ZX(w,b,$){return new w({type:"custom",check:"custom",fn:b,...C($)})}function jX(w){let b=uz(($)=>{return $.addIssue=(Q)=>{if(typeof Q==="string")$.issues.push(ww(Q,$.value,b._zod.def));else{let W=Q;if(W.fatal)W.continue=!1;W.code??(W.code="custom"),W.input??(W.input=$.value),W.inst??(W.inst=b),W.continue??(W.continue=!b._zod.def.abort),$.issues.push(ww(W))}},w($.value,$)});return b}function uz(w,b){let $=new U1({check:"custom",...C(b)});return $._zod.check=w,$}function $w(w){return!!w._zod}function q0(w,b){if($w(w))return hw(w,b);return w.safeParse(b)}function sb(w){if(!w)return;let b;if($w(w))b=w._zod?.def?.shape;else b=w.shape;if(!b)return;if(typeof b==="function")try{return b()}catch{return}return b}function MX(w){if($w(w)){let X=w._zod?.def;if(X){if(X.value!==void 0)return X.value;if(Array.isArray(X.values)&&X.values.length>0)return X.values[0]}}let $=w._def;if($){if($.value!==void 0)return $.value;if(Array.isArray($.values)&&$.values.length>0)return $.values[0]}let Q=w.value;if(Q!==void 0)return Q;return}var gw={};OQ(gw,{time:()=>s4,duration:()=>e4,datetime:()=>t4,date:()=>r4,ZodISOTime:()=>qX,ZodISODuration:()=>IX,ZodISODateTime:()=>VX,ZodISODate:()=>PX});var VX=O("ZodISODateTime",(w,b)=>{bW.init(w,b),W1.init(w,b)});function t4(w){return YX(VX,w)}var PX=O("ZodISODate",(w,b)=>{$W.init(w,b),W1.init(w,b)});function r4(w){return GX(PX,w)}var qX=O("ZodISOTime",(w,b)=>{QW.init(w,b),W1.init(w,b)});function s4(w){return HX(qX,w)}var IX=O("ZodISODuration",(w,b)=>{WW.init(w,b),W1.init(w,b)});function e4(w){return zX(IX,w)}var EX=(w,b)=>{fb.init(w,b),w.name="ZodError",Object.defineProperties(w,{format:{value:($)=>yQ(w,$)},flatten:{value:($)=>hQ(w,$)},addIssue:{value:($)=>{w.issues.push($),w.message=JSON.stringify(w.issues,e0,2)}},addIssues:{value:($)=>{w.issues.push(...$),w.message=JSON.stringify(w.issues,e0,2)}},isEmpty:{get(){return w.issues.length===0}}})},sP=O("ZodError",EX),k1=O("ZodError",EX,{Parent:Error});var NX=ub(k1),TX=cb(k1),RX=xw(k1),SX=yw(k1),vX=fQ(k1),CX=uQ(k1),kX=cQ(k1),_X=mQ(k1),xX=lQ(k1),hX=gQ(k1),yX=iQ(k1),fX=nQ(k1);var G1=O("ZodType",(w,b)=>{return w1.init(w,b),w.def=b,w.type=b.type,Object.defineProperty(w,"_def",{value:b}),w.check=(...$)=>{return w.clone(o.mergeDefs(b,{checks:[...b.checks??[],...$.map((Q)=>typeof Q==="function"?{_zod:{check:Q,def:{check:"custom"},onattach:[]}}:Q)]}))},w.clone=($,Q)=>i1(w,$,Q),w.brand=()=>w,w.register=($,Q)=>{return $.add(w,Q),w},w.parse=($,Q)=>NX(w,$,Q,{callee:w.parse}),w.safeParse=($,Q)=>RX(w,$,Q),w.parseAsync=async($,Q)=>TX(w,$,Q,{callee:w.parseAsync}),w.safeParseAsync=async($,Q)=>SX(w,$,Q),w.spa=w.safeParseAsync,w.encode=($,Q)=>vX(w,$,Q),w.decode=($,Q)=>CX(w,$,Q),w.encodeAsync=async($,Q)=>kX(w,$,Q),w.decodeAsync=async($,Q)=>_X(w,$,Q),w.safeEncode=($,Q)=>xX(w,$,Q),w.safeDecode=($,Q)=>hX(w,$,Q),w.safeEncodeAsync=async($,Q)=>yX(w,$,Q),w.safeDecodeAsync=async($,Q)=>fX(w,$,Q),w.refine=($,Q)=>w.check(xD($,Q)),w.superRefine=($)=>w.check(hD($)),w.overwrite=($)=>w.check(f0($)),w.optional=()=>Y1(w),w.nullable=()=>mX(w),w.nullish=()=>Y1(mX(w)),w.nonoptional=($)=>RD(w,$),w.array=()=>g(w),w.or=($)=>a([w,$]),w.and=($)=>ab(w,$),w.transform=($)=>w$(w,pX($)),w.default=($)=>ED(w,$),w.prefault=($)=>TD(w,$),w.catch=($)=>vD(w,$),w.pipe=($)=>w$(w,$),w.readonly=()=>_D(w),w.describe=($)=>{let Q=w.clone();return uw.add(Q,{description:$}),Q},Object.defineProperty(w,"description",{get(){return uw.get(w)?.description},configurable:!0}),w.meta=(...$)=>{if($.length===0)return uw.get(w);let Q=w.clone();return uw.add(Q,$[0]),Q},w.isOptional=()=>w.safeParse(void 0).success,w.isNullable=()=>w.safeParse(null).success,w}),lX=O("_ZodString",(w,b)=>{nb.init(w,b),G1.init(w,b);let $=w._zod.bag;w.format=$.format??null,w.minLength=$.minimum??null,w.maxLength=$.maximum??null,w.regex=(...Q)=>w.check(u4(...Q)),w.includes=(...Q)=>w.check(l4(...Q)),w.startsWith=(...Q)=>w.check(g4(...Q)),w.endsWith=(...Q)=>w.check(i4(...Q)),w.min=(...Q)=>w.check(bw(...Q)),w.max=(...Q)=>w.check(tb(...Q)),w.length=(...Q)=>w.check(rb(...Q)),w.nonempty=(...Q)=>w.check(bw(1,...Q)),w.lowercase=(Q)=>w.check(c4(Q)),w.uppercase=(Q)=>w.check(m4(Q)),w.trim=()=>w.check(p4()),w.normalize=(...Q)=>w.check(n4(...Q)),w.toLowerCase=()=>w.check(d4()),w.toUpperCase=()=>w.check(o4())}),oz=O("ZodString",(w,b)=>{nb.init(w,b),lX.init(w,b),w.email=($)=>w.check(cW(tz,$)),w.url=($)=>w.check(nW(rz,$)),w.jwt=($)=>w.check(JX(DD,$)),w.emoji=($)=>w.check(pW(sz,$)),w.guid=($)=>w.check(f4(uX,$)),w.uuid=($)=>w.check(mW(eb,$)),w.uuidv4=($)=>w.check(lW(eb,$)),w.uuidv6=($)=>w.check(gW(eb,$)),w.uuidv7=($)=>w.check(iW(eb,$)),w.nanoid=($)=>w.check(dW(ez,$)),w.guid=($)=>w.check(f4(uX,$)),w.cuid=($)=>w.check(oW(az,$)),w.cuid2=($)=>w.check(tW(wD,$)),w.ulid=($)=>w.check(rW(bD,$)),w.base64=($)=>w.check(QX(GD,$)),w.base64url=($)=>w.check(WX(HD,$)),w.xid=($)=>w.check(sW($D,$)),w.ksuid=($)=>w.check(eW(QD,$)),w.ipv4=($)=>w.check(aW(WD,$)),w.ipv6=($)=>w.check(wX(XD,$)),w.cidrv4=($)=>w.check(bX(JD,$)),w.cidrv6=($)=>w.check($X(YD,$)),w.e164=($)=>w.check(XX(zD,$)),w.datetime=($)=>w.check(t4($)),w.date=($)=>w.check(r4($)),w.time=($)=>w.check(s4($)),w.duration=($)=>w.check(e4($))});function K(w){return uW(oz,w)}var W1=O("ZodStringFormat",(w,b)=>{b1.init(w,b),lX.init(w,b)}),tz=O("ZodEmail",(w,b)=>{p8.init(w,b),W1.init(w,b)});var uX=O("ZodGUID",(w,b)=>{i8.init(w,b),W1.init(w,b)});var eb=O("ZodUUID",(w,b)=>{n8.init(w,b),W1.init(w,b)});var rz=O("ZodURL",(w,b)=>{d8.init(w,b),W1.init(w,b)});var sz=O("ZodEmoji",(w,b)=>{o8.init(w,b),W1.init(w,b)});var ez=O("ZodNanoID",(w,b)=>{t8.init(w,b),W1.init(w,b)});var az=O("ZodCUID",(w,b)=>{r8.init(w,b),W1.init(w,b)});var wD=O("ZodCUID2",(w,b)=>{s8.init(w,b),W1.init(w,b)});var bD=O("ZodULID",(w,b)=>{e8.init(w,b),W1.init(w,b)});var $D=O("ZodXID",(w,b)=>{a8.init(w,b),W1.init(w,b)});var QD=O("ZodKSUID",(w,b)=>{wW.init(w,b),W1.init(w,b)});var WD=O("ZodIPv4",(w,b)=>{XW.init(w,b),W1.init(w,b)});var XD=O("ZodIPv6",(w,b)=>{JW.init(w,b),W1.init(w,b)});var JD=O("ZodCIDRv4",(w,b)=>{YW.init(w,b),W1.init(w,b)});var YD=O("ZodCIDRv6",(w,b)=>{GW.init(w,b),W1.init(w,b)});var GD=O("ZodBase64",(w,b)=>{zW.init(w,b),W1.init(w,b)});var HD=O("ZodBase64URL",(w,b)=>{DW.init(w,b),W1.init(w,b)});var zD=O("ZodE164",(w,b)=>{BW.init(w,b),W1.init(w,b)});var DD=O("ZodJWT",(w,b)=>{LW.init(w,b),W1.init(w,b)});var gX=O("ZodNumber",(w,b)=>{x4.init(w,b),G1.init(w,b),w.gt=(Q,W)=>w.check(db(Q,W)),w.gte=(Q,W)=>w.check(mw(Q,W)),w.min=(Q,W)=>w.check(mw(Q,W)),w.lt=(Q,W)=>w.check(pb(Q,W)),w.lte=(Q,W)=>w.check(cw(Q,W)),w.max=(Q,W)=>w.check(cw(Q,W)),w.int=(Q)=>w.check(cX(Q)),w.safe=(Q)=>w.check(cX(Q)),w.positive=(Q)=>w.check(db(0,Q)),w.nonnegative=(Q)=>w.check(mw(0,Q)),w.negative=(Q)=>w.check(pb(0,Q)),w.nonpositive=(Q)=>w.check(cw(0,Q)),w.multipleOf=(Q,W)=>w.check(ob(Q,W)),w.step=(Q,W)=>w.check(ob(Q,W)),w.finite=()=>w;let $=w._zod.bag;w.minValue=Math.max($.minimum??Number.NEGATIVE_INFINITY,$.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,w.maxValue=Math.min($.maximum??Number.POSITIVE_INFINITY,$.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,w.isInt=($.format??"").includes("int")||Number.isSafeInteger($.multipleOf??0.5),w.isFinite=!0,w.format=$.format??null});function r(w){return DX(gX,w)}var BD=O("ZodNumberFormat",(w,b)=>{FW.init(w,b),gX.init(w,b)});function cX(w){return BX(BD,w)}var LD=O("ZodBoolean",(w,b)=>{UW.init(w,b),G1.init(w,b)});function L1(w){return LX(LD,w)}var FD=O("ZodNull",(w,b)=>{AW.init(w,b),G1.init(w,b)});function b$(w){return FX(FD,w)}var UD=O("ZodUnknown",(w,b)=>{KW.init(w,b),G1.init(w,b)});function X1(){return UX(UD)}var AD=O("ZodNever",(w,b)=>{OW.init(w,b),G1.init(w,b)});function KD(w){return AX(AD,w)}var OD=O("ZodArray",(w,b)=>{ZW.init(w,b),G1.init(w,b),w.element=b.element,w.min=($,Q)=>w.check(bw($,Q)),w.nonempty=($)=>w.check(bw(1,$)),w.max=($,Q)=>w.check(tb($,Q)),w.length=($,Q)=>w.check(rb($,Q)),w.unwrap=()=>w.element});function g(w,b){return KX(OD,w,b)}var iX=O("ZodObject",(w,b)=>{VW.init(w,b),G1.init(w,b),o.defineLazy(w,"shape",()=>{return b.shape}),w.keyof=()=>I1(Object.keys(w._zod.def.shape)),w.catchall=($)=>w.clone({...w._zod.def,catchall:$}),w.passthrough=()=>w.clone({...w._zod.def,catchall:X1()}),w.loose=()=>w.clone({...w._zod.def,catchall:X1()}),w.strict=()=>w.clone({...w._zod.def,catchall:KD()}),w.strip=()=>w.clone({...w._zod.def,catchall:void 0}),w.extend=($)=>{return o.extend(w,$)},w.safeExtend=($)=>{return o.safeExtend(w,$)},w.merge=($)=>o.merge(w,$),w.pick=($)=>o.pick(w,$),w.omit=($)=>o.omit(w,$),w.partial=(...$)=>o.partial(dX,w,$[0]),w.required=(...$)=>o.required(oX,w,$[0])});function N(w,b){let $={type:"object",shape:w??{},...o.normalizeParams(b)};return new iX($)}function V1(w,b){return new iX({type:"object",shape:w,catchall:X1(),...o.normalizeParams(b)})}var nX=O("ZodUnion",(w,b)=>{h4.init(w,b),G1.init(w,b),w.options=b.options});function a(w,b){return new nX({type:"union",options:w,...o.normalizeParams(b)})}var ZD=O("ZodDiscriminatedUnion",(w,b)=>{nX.init(w,b),PW.init(w,b)});function $$(w,b,$){return new ZD({type:"union",options:b,discriminator:w,...o.normalizeParams($)})}var jD=O("ZodIntersection",(w,b)=>{qW.init(w,b),G1.init(w,b)});function ab(w,b){return new jD({type:"intersection",left:w,right:b})}var MD=O("ZodRecord",(w,b)=>{IW.init(w,b),G1.init(w,b),w.keyType=b.keyType,w.valueType=b.valueType});function J1(w,b,$){return new MD({type:"record",keyType:w,valueType:b,...o.normalizeParams($)})}var a4=O("ZodEnum",(w,b)=>{EW.init(w,b),G1.init(w,b),w.enum=b.entries,w.options=Object.values(b.entries);let $=new Set(Object.keys(b.entries));w.extract=(Q,W)=>{let X={};for(let J of Q)if($.has(J))X[J]=b.entries[J];else throw Error(`Key ${J} not found in enum`);return new a4({...b,checks:[],...o.normalizeParams(W),entries:X})},w.exclude=(Q,W)=>{let X={...b.entries};for(let J of Q)if($.has(J))delete X[J];else throw Error(`Key ${J} not found in enum`);return new a4({...b,checks:[],...o.normalizeParams(W),entries:X})}});function I1(w,b){let $=Array.isArray(w)?Object.fromEntries(w.map((Q)=>[Q,Q])):w;return new a4({type:"enum",entries:$,...o.normalizeParams(b)})}var VD=O("ZodLiteral",(w,b)=>{NW.init(w,b),G1.init(w,b),w.values=new Set(b.values),Object.defineProperty(w,"value",{get(){if(b.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return b.values[0]}})});function T(w,b){return new VD({type:"literal",values:Array.isArray(w)?w:[w],...o.normalizeParams(b)})}var PD=O("ZodTransform",(w,b)=>{TW.init(w,b),G1.init(w,b),w._zod.parse=($,Q)=>{if(Q.direction==="backward")throw new Sw(w.constructor.name);$.addIssue=(X)=>{if(typeof X==="string")$.issues.push(o.issue(X,$.value,b));else{let J=X;if(J.fatal)J.continue=!1;J.code??(J.code="custom"),J.input??(J.input=$.value),J.inst??(J.inst=w),$.issues.push(o.issue(J))}};let W=b.transform($.value,$);if(W instanceof Promise)return W.then((X)=>{return $.value=X,$});return $.value=W,$}});function pX(w){return new PD({type:"transform",transform:w})}var dX=O("ZodOptional",(w,b)=>{RW.init(w,b),G1.init(w,b),w.unwrap=()=>w._zod.def.innerType});function Y1(w){return new dX({type:"optional",innerType:w})}var qD=O("ZodNullable",(w,b)=>{SW.init(w,b),G1.init(w,b),w.unwrap=()=>w._zod.def.innerType});function mX(w){return new qD({type:"nullable",innerType:w})}var ID=O("ZodDefault",(w,b)=>{vW.init(w,b),G1.init(w,b),w.unwrap=()=>w._zod.def.innerType,w.removeDefault=w.unwrap});function ED(w,b){return new ID({type:"default",innerType:w,get defaultValue(){return typeof b==="function"?b():o.shallowClone(b)}})}var ND=O("ZodPrefault",(w,b)=>{CW.init(w,b),G1.init(w,b),w.unwrap=()=>w._zod.def.innerType});function TD(w,b){return new ND({type:"prefault",innerType:w,get defaultValue(){return typeof b==="function"?b():o.shallowClone(b)}})}var oX=O("ZodNonOptional",(w,b)=>{kW.init(w,b),G1.init(w,b),w.unwrap=()=>w._zod.def.innerType});function RD(w,b){return new oX({type:"nonoptional",innerType:w,...o.normalizeParams(b)})}var SD=O("ZodCatch",(w,b)=>{_W.init(w,b),G1.init(w,b),w.unwrap=()=>w._zod.def.innerType,w.removeCatch=w.unwrap});function vD(w,b){return new SD({type:"catch",innerType:w,catchValue:typeof b==="function"?b:()=>b})}var CD=O("ZodPipe",(w,b)=>{xW.init(w,b),G1.init(w,b),w.in=b.in,w.out=b.out});function w$(w,b){return new CD({type:"pipe",in:w,out:b})}var kD=O("ZodReadonly",(w,b)=>{hW.init(w,b),G1.init(w,b),w.unwrap=()=>w._zod.def.innerType});function _D(w){return new kD({type:"readonly",innerType:w})}var tX=O("ZodCustom",(w,b)=>{yW.init(w,b),G1.init(w,b)});function rX(w,b){return OX(tX,w??(()=>!0),b)}function xD(w,b={}){return ZX(tX,w,b)}function hD(w){return jX(w)}function Q$(w,b){return w$(pX(w),b)}y1(y4());var W$="2025-11-25";var sX=[W$,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],I0="io.modelcontextprotocol/related-task",b6="2.0",A1=rX((w)=>w!==null&&(typeof w==="object"||typeof w==="function")),eX=a([K(),r().int()]),aX=K(),pq=V1({ttl:a([r(),b$()]).optional(),pollInterval:r().optional()}),yD=N({ttl:r().optional()}),fD=N({taskId:K()}),X$=V1({progressToken:eX.optional(),[I0]:fD.optional()}),_1=N({_meta:X$.optional()}),iw=_1.extend({task:yD.optional()}),wJ=(w)=>iw.safeParse(w).success,K1=N({method:K(),params:_1.loose().optional()}),f1=N({_meta:X$.optional()}),u1=N({method:K(),params:f1.loose().optional()}),O1=V1({_meta:X$.optional()}),$6=a([K(),r().int()]),bJ=N({jsonrpc:T(b6),id:$6,...K1.shape}).strict(),J$=(w)=>bJ.safeParse(w).success,$J=N({jsonrpc:T(b6),...u1.shape}).strict(),QJ=(w)=>$J.safeParse(w).success,Y$=N({jsonrpc:T(b6),id:$6,result:O1}).strict(),nw=(w)=>Y$.safeParse(w).success;var i;(function(w){w[w.ConnectionClosed=-32000]="ConnectionClosed",w[w.RequestTimeout=-32001]="RequestTimeout",w[w.ParseError=-32700]="ParseError",w[w.InvalidRequest=-32600]="InvalidRequest",w[w.MethodNotFound=-32601]="MethodNotFound",w[w.InvalidParams=-32602]="InvalidParams",w[w.InternalError=-32603]="InternalError",w[w.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(i||(i={}));var G$=N({jsonrpc:T(b6),id:$6.optional(),error:N({code:r().int(),message:K(),data:X1().optional()})}).strict();var WJ=(w)=>G$.safeParse(w).success;var dq=a([bJ,$J,Y$,G$]),oq=a([Y$,G$]),Q6=O1.strict(),uD=f1.extend({requestId:$6.optional(),reason:K().optional()}),W6=u1.extend({method:T("notifications/cancelled"),params:uD}),cD=N({src:K(),mimeType:K().optional(),sizes:g(K()).optional(),theme:I1(["light","dark"]).optional()}),pw=N({icons:g(cD).optional()}),Qw=N({name:K(),title:K().optional()}),XJ=Qw.extend({...Qw.shape,...pw.shape,version:K(),websiteUrl:K().optional(),description:K().optional()}),mD=ab(N({applyDefaults:L1().optional()}),J1(K(),X1())),lD=Q$((w)=>{if(w&&typeof w==="object"&&!Array.isArray(w)){if(Object.keys(w).length===0)return{form:{}}}return w},ab(N({form:mD.optional(),url:A1.optional()}),J1(K(),X1()).optional())),gD=V1({list:A1.optional(),cancel:A1.optional(),requests:V1({sampling:V1({createMessage:A1.optional()}).optional(),elicitation:V1({create:A1.optional()}).optional()}).optional()}),iD=V1({list:A1.optional(),cancel:A1.optional(),requests:V1({tools:V1({call:A1.optional()}).optional()}).optional()}),nD=N({experimental:J1(K(),A1).optional(),sampling:N({context:A1.optional(),tools:A1.optional()}).optional(),elicitation:lD.optional(),roots:N({listChanged:L1().optional()}).optional(),tasks:gD.optional()}),pD=_1.extend({protocolVersion:K(),capabilities:nD,clientInfo:XJ}),H$=K1.extend({method:T("initialize"),params:pD});var dD=N({experimental:J1(K(),A1).optional(),logging:A1.optional(),completions:A1.optional(),prompts:N({listChanged:L1().optional()}).optional(),resources:N({subscribe:L1().optional(),listChanged:L1().optional()}).optional(),tools:N({listChanged:L1().optional()}).optional(),tasks:iD.optional()}),oD=O1.extend({protocolVersion:K(),capabilities:dD,serverInfo:XJ,instructions:K().optional()}),z$=u1.extend({method:T("notifications/initialized"),params:f1.optional()});var X6=K1.extend({method:T("ping"),params:_1.optional()}),tD=N({progress:r(),total:Y1(r()),message:Y1(K())}),rD=N({...f1.shape,...tD.shape,progressToken:eX}),J6=u1.extend({method:T("notifications/progress"),params:rD}),sD=_1.extend({cursor:aX.optional()}),dw=K1.extend({params:sD.optional()}),ow=O1.extend({nextCursor:aX.optional()}),eD=I1(["working","input_required","completed","failed","cancelled"]),tw=N({taskId:K(),status:eD,ttl:a([r(),b$()]),createdAt:K(),lastUpdatedAt:K(),pollInterval:Y1(r()),statusMessage:Y1(K())}),Ww=O1.extend({task:tw}),aD=f1.merge(tw),rw=u1.extend({method:T("notifications/tasks/status"),params:aD}),Y6=K1.extend({method:T("tasks/get"),params:_1.extend({taskId:K()})}),G6=O1.merge(tw),H6=K1.extend({method:T("tasks/result"),params:_1.extend({taskId:K()})}),tq=O1.loose(),z6=dw.extend({method:T("tasks/list")}),D6=ow.extend({tasks:g(tw)}),B6=K1.extend({method:T("tasks/cancel"),params:_1.extend({taskId:K()})}),JJ=O1.merge(tw),YJ=N({uri:K(),mimeType:Y1(K()),_meta:J1(K(),X1()).optional()}),GJ=YJ.extend({text:K()}),D$=K().refine((w)=>{try{return atob(w),!0}catch{return!1}},{message:"Invalid Base64 string"}),HJ=YJ.extend({blob:D$}),sw=I1(["user","assistant"]),Xw=N({audience:g(sw).optional(),priority:r().min(0).max(1).optional(),lastModified:gw.datetime({offset:!0}).optional()}),zJ=N({...Qw.shape,...pw.shape,uri:K(),description:Y1(K()),mimeType:Y1(K()),annotations:Xw.optional(),_meta:Y1(V1({}))}),wB=N({...Qw.shape,...pw.shape,uriTemplate:K(),description:Y1(K()),mimeType:Y1(K()),annotations:Xw.optional(),_meta:Y1(V1({}))}),B$=dw.extend({method:T("resources/list")}),bB=ow.extend({resources:g(zJ)}),$B=dw.extend({method:T("resources/templates/list")}),QB=ow.extend({resourceTemplates:g(wB)}),L$=_1.extend({uri:K()}),WB=L$,F$=K1.extend({method:T("resources/read"),params:WB}),XB=O1.extend({contents:g(a([GJ,HJ]))}),JB=u1.extend({method:T("notifications/resources/list_changed"),params:f1.optional()}),YB=L$,GB=K1.extend({method:T("resources/subscribe"),params:YB}),HB=L$,zB=K1.extend({method:T("resources/unsubscribe"),params:HB}),DB=f1.extend({uri:K()}),BB=u1.extend({method:T("notifications/resources/updated"),params:DB}),LB=N({name:K(),description:Y1(K()),required:Y1(L1())}),FB=N({...Qw.shape,...pw.shape,description:Y1(K()),arguments:Y1(g(LB)),_meta:Y1(V1({}))}),UB=dw.extend({method:T("prompts/list")}),AB=ow.extend({prompts:g(FB)}),KB=_1.extend({name:K(),arguments:J1(K(),K()).optional()}),OB=K1.extend({method:T("prompts/get"),params:KB}),U$=N({type:T("text"),text:K(),annotations:Xw.optional(),_meta:J1(K(),X1()).optional()}),A$=N({type:T("image"),data:D$,mimeType:K(),annotations:Xw.optional(),_meta:J1(K(),X1()).optional()}),K$=N({type:T("audio"),data:D$,mimeType:K(),annotations:Xw.optional(),_meta:J1(K(),X1()).optional()}),ZB=N({type:T("tool_use"),name:K(),id:K(),input:J1(K(),X1()),_meta:J1(K(),X1()).optional()}),jB=N({type:T("resource"),resource:a([GJ,HJ]),annotations:Xw.optional(),_meta:J1(K(),X1()).optional()}),MB=zJ.extend({type:T("resource_link")}),O$=a([U$,A$,K$,MB,jB]),VB=N({role:sw,content:O$}),PB=O1.extend({description:K().optional(),messages:g(VB)}),qB=u1.extend({method:T("notifications/prompts/list_changed"),params:f1.optional()}),IB=N({title:K().optional(),readOnlyHint:L1().optional(),destructiveHint:L1().optional(),idempotentHint:L1().optional(),openWorldHint:L1().optional()}),EB=N({taskSupport:I1(["required","optional","forbidden"]).optional()}),DJ=N({...Qw.shape,...pw.shape,description:K().optional(),inputSchema:N({type:T("object"),properties:J1(K(),A1).optional(),required:g(K()).optional()}).catchall(X1()),outputSchema:N({type:T("object"),properties:J1(K(),A1).optional(),required:g(K()).optional()}).catchall(X1()).optional(),annotations:IB.optional(),execution:EB.optional(),_meta:J1(K(),X1()).optional()}),Z$=dw.extend({method:T("tools/list")}),NB=ow.extend({tools:g(DJ)}),L6=O1.extend({content:g(O$).default([]),structuredContent:J1(K(),X1()).optional(),isError:L1().optional()}),rq=L6.or(O1.extend({toolResult:X1()})),TB=iw.extend({name:K(),arguments:J1(K(),X1()).optional()}),ew=K1.extend({method:T("tools/call"),params:TB}),RB=u1.extend({method:T("notifications/tools/list_changed"),params:f1.optional()}),sq=N({autoRefresh:L1().default(!0),debounceMs:r().int().nonnegative().default(300)}),aw=I1(["debug","info","notice","warning","error","critical","alert","emergency"]),SB=_1.extend({level:aw}),j$=K1.extend({method:T("logging/setLevel"),params:SB}),vB=f1.extend({level:aw,logger:K().optional(),data:X1()}),CB=u1.extend({method:T("notifications/message"),params:vB}),kB=N({name:K().optional()}),_B=N({hints:g(kB).optional(),costPriority:r().min(0).max(1).optional(),speedPriority:r().min(0).max(1).optional(),intelligencePriority:r().min(0).max(1).optional()}),xB=N({mode:I1(["auto","required","none"]).optional()}),hB=N({type:T("tool_result"),toolUseId:K().describe("The unique identifier for the corresponding tool call."),content:g(O$).default([]),structuredContent:N({}).loose().optional(),isError:L1().optional(),_meta:J1(K(),X1()).optional()}),yB=$$("type",[U$,A$,K$]),w6=$$("type",[U$,A$,K$,ZB,hB]),fB=N({role:sw,content:a([w6,g(w6)]),_meta:J1(K(),X1()).optional()}),uB=iw.extend({messages:g(fB),modelPreferences:_B.optional(),systemPrompt:K().optional(),includeContext:I1(["none","thisServer","allServers"]).optional(),temperature:r().optional(),maxTokens:r().int(),stopSequences:g(K()).optional(),metadata:A1.optional(),tools:g(DJ).optional(),toolChoice:xB.optional()}),cB=K1.extend({method:T("sampling/createMessage"),params:uB}),M$=O1.extend({model:K(),stopReason:Y1(I1(["endTurn","stopSequence","maxTokens"]).or(K())),role:sw,content:yB}),V$=O1.extend({model:K(),stopReason:Y1(I1(["endTurn","stopSequence","maxTokens","toolUse"]).or(K())),role:sw,content:a([w6,g(w6)])}),mB=N({type:T("boolean"),title:K().optional(),description:K().optional(),default:L1().optional()}),lB=N({type:T("string"),title:K().optional(),description:K().optional(),minLength:r().optional(),maxLength:r().optional(),format:I1(["email","uri","date","date-time"]).optional(),default:K().optional()}),gB=N({type:I1(["number","integer"]),title:K().optional(),description:K().optional(),minimum:r().optional(),maximum:r().optional(),default:r().optional()}),iB=N({type:T("string"),title:K().optional(),description:K().optional(),enum:g(K()),default:K().optional()}),nB=N({type:T("string"),title:K().optional(),description:K().optional(),oneOf:g(N({const:K(),title:K()})),default:K().optional()}),pB=N({type:T("string"),title:K().optional(),description:K().optional(),enum:g(K()),enumNames:g(K()).optional(),default:K().optional()}),dB=a([iB,nB]),oB=N({type:T("array"),title:K().optional(),description:K().optional(),minItems:r().optional(),maxItems:r().optional(),items:N({type:T("string"),enum:g(K())}),default:g(K()).optional()}),tB=N({type:T("array"),title:K().optional(),description:K().optional(),minItems:r().optional(),maxItems:r().optional(),items:N({anyOf:g(N({const:K(),title:K()}))}),default:g(K()).optional()}),rB=a([oB,tB]),sB=a([pB,dB,rB]),eB=a([sB,mB,lB,gB]),aB=iw.extend({mode:T("form").optional(),message:K(),requestedSchema:N({type:T("object"),properties:J1(K(),eB),required:g(K()).optional()})}),wL=iw.extend({mode:T("url"),message:K(),elicitationId:K(),url:K().url()}),bL=a([aB,wL]),$L=K1.extend({method:T("elicitation/create"),params:bL}),QL=f1.extend({elicitationId:K()}),WL=u1.extend({method:T("notifications/elicitation/complete"),params:QL}),F6=O1.extend({action:I1(["accept","decline","cancel"]),content:Q$((w)=>w===null?void 0:w,J1(K(),a([K(),r(),L1(),g(K())])).optional())}),XL=N({type:T("ref/resource"),uri:K()});var JL=N({type:T("ref/prompt"),name:K()}),YL=_1.extend({ref:a([JL,XL]),argument:N({name:K(),value:K()}),context:N({arguments:J1(K(),K()).optional()}).optional()}),GL=K1.extend({method:T("completion/complete"),params:YL});var HL=O1.extend({completion:V1({values:g(K()).max(100),total:Y1(r().int()),hasMore:Y1(L1())})}),zL=N({uri:K().startsWith("file://"),name:K().optional(),_meta:J1(K(),X1()).optional()}),DL=K1.extend({method:T("roots/list"),params:_1.optional()}),P$=O1.extend({roots:g(zL)}),BL=u1.extend({method:T("notifications/roots/list_changed"),params:f1.optional()}),eq=a([X6,H$,GL,j$,OB,UB,B$,$B,F$,GB,zB,ew,Z$,Y6,H6,z6,B6]),aq=a([W6,J6,z$,BL,rw]),wI=a([Q6,M$,V$,F6,P$,G6,D6,Ww]),bI=a([X6,cB,$L,DL,Y6,H6,z6,B6]),$I=a([W6,J6,CB,BB,JB,RB,qB,rw,WL]),QI=a([Q6,oD,HL,PB,AB,bB,QB,XB,L6,NB,G6,D6,Ww]);class c extends Error{constructor(w,b,$){super(`MCP error ${w}: ${b}`);this.code=w,this.data=$,this.name="McpError"}static fromError(w,b,$){if(w===i.UrlElicitationRequired&&$){let Q=$;if(Q.elicitations)return new BJ(Q.elicitations,b)}return new c(w,b,$)}}class BJ extends c{constructor(w,b=`URL elicitation${w.length>1?"s":""} required`){super(i.UrlElicitationRequired,b,{elicitations:w})}get elicitations(){return this.data?.elicitations??[]}}function E0(w){return w==="completed"||w==="failed"||w==="cancelled"}var LL=Symbol("Let zodToJsonSchema decide on which parser to use");var hI=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function q$(w){let $=sb(w)?.method;if(!$)throw Error("Schema is missing a method literal");let Q=MX($);if(typeof Q!=="string")throw Error("Schema method literal must be a string");return Q}function I$(w,b){let $=q0(w,b);if(!$.success)throw $.error;return $.data}var ZL=60000;class E${constructor(w){if(this._options=w,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(W6,(b)=>{this._oncancel(b)}),this.setNotificationHandler(J6,(b)=>{this._onprogress(b)}),this.setRequestHandler(X6,(b)=>({})),this._taskStore=w?.taskStore,this._taskMessageQueue=w?.taskMessageQueue,this._taskStore)this.setRequestHandler(Y6,async(b,$)=>{let Q=await this._taskStore.getTask(b.params.taskId,$.sessionId);if(!Q)throw new c(i.InvalidParams,"Failed to retrieve task: Task not found");return{...Q}}),this.setRequestHandler(H6,async(b,$)=>{let Q=async()=>{let W=b.params.taskId;if(this._taskMessageQueue){let J;while(J=await this._taskMessageQueue.dequeue(W,$.sessionId)){if(J.type==="response"||J.type==="error"){let Y=J.message,G=Y.id,H=this._requestResolvers.get(G);if(H)if(this._requestResolvers.delete(G),J.type==="response")H(Y);else{let z=Y,B=new c(z.error.code,z.error.message,z.error.data);H(B)}else{let z=J.type==="response"?"Response":"Error";this._onerror(Error(`${z} handler missing for request ${G}`))}continue}await this._transport?.send(J.message,{relatedRequestId:$.requestId})}}let X=await this._taskStore.getTask(W,$.sessionId);if(!X)throw new c(i.InvalidParams,`Task not found: ${W}`);if(!E0(X.status))return await this._waitForTaskUpdate(W,$.signal),await Q();if(E0(X.status)){let J=await this._taskStore.getTaskResult(W,$.sessionId);return this._clearTaskQueue(W),{...J,_meta:{...J._meta,[I0]:{taskId:W}}}}return await Q()};return await Q()}),this.setRequestHandler(z6,async(b,$)=>{try{let{tasks:Q,nextCursor:W}=await this._taskStore.listTasks(b.params?.cursor,$.sessionId);return{tasks:Q,nextCursor:W,_meta:{}}}catch(Q){throw new c(i.InvalidParams,`Failed to list tasks: ${Q instanceof Error?Q.message:String(Q)}`)}}),this.setRequestHandler(B6,async(b,$)=>{try{let Q=await this._taskStore.getTask(b.params.taskId,$.sessionId);if(!Q)throw new c(i.InvalidParams,`Task not found: ${b.params.taskId}`);if(E0(Q.status))throw new c(i.InvalidParams,`Cannot cancel task in terminal status: ${Q.status}`);await this._taskStore.updateTaskStatus(b.params.taskId,"cancelled","Client cancelled task execution.",$.sessionId),this._clearTaskQueue(b.params.taskId);let W=await this._taskStore.getTask(b.params.taskId,$.sessionId);if(!W)throw new c(i.InvalidParams,`Task not found after cancellation: ${b.params.taskId}`);return{_meta:{},...W}}catch(Q){if(Q instanceof c)throw Q;throw new c(i.InvalidRequest,`Failed to cancel task: ${Q instanceof Error?Q.message:String(Q)}`)}})}async _oncancel(w){if(!w.params.requestId)return;this._requestHandlerAbortControllers.get(w.params.requestId)?.abort(w.params.reason)}_setupTimeout(w,b,$,Q,W=!1){this._timeoutInfo.set(w,{timeoutId:setTimeout(Q,b),startTime:Date.now(),timeout:b,maxTotalTimeout:$,resetTimeoutOnProgress:W,onTimeout:Q})}_resetTimeout(w){let b=this._timeoutInfo.get(w);if(!b)return!1;let $=Date.now()-b.startTime;if(b.maxTotalTimeout&&$>=b.maxTotalTimeout)throw this._timeoutInfo.delete(w),c.fromError(i.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:b.maxTotalTimeout,totalElapsed:$});return clearTimeout(b.timeoutId),b.timeoutId=setTimeout(b.onTimeout,b.timeout),!0}_cleanupTimeout(w){let b=this._timeoutInfo.get(w);if(b)clearTimeout(b.timeoutId),this._timeoutInfo.delete(w)}async connect(w){this._transport=w;let b=this.transport?.onclose;this._transport.onclose=()=>{b?.(),this._onclose()};let $=this.transport?.onerror;this._transport.onerror=(W)=>{$?.(W),this._onerror(W)};let Q=this._transport?.onmessage;this._transport.onmessage=(W,X)=>{if(Q?.(W,X),nw(W)||WJ(W))this._onresponse(W);else if(J$(W))this._onrequest(W,X);else if(QJ(W))this._onnotification(W);else this._onerror(Error(`Unknown message type: ${JSON.stringify(W)}`))},await this._transport.start()}_onclose(){let w=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();let b=c.fromError(i.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let $ of w.values())$(b)}_onerror(w){this.onerror?.(w)}_onnotification(w){let b=this._notificationHandlers.get(w.method)??this.fallbackNotificationHandler;if(b===void 0)return;Promise.resolve().then(()=>b(w)).catch(($)=>this._onerror(Error(`Uncaught error in notification handler: ${$}`)))}_onrequest(w,b){let $=this._requestHandlers.get(w.method)??this.fallbackRequestHandler,Q=this._transport,W=w.params?._meta?.[I0]?.taskId;if($===void 0){let H={jsonrpc:"2.0",id:w.id,error:{code:i.MethodNotFound,message:"Method not found"}};if(W&&this._taskMessageQueue)this._enqueueTaskMessage(W,{type:"error",message:H,timestamp:Date.now()},Q?.sessionId).catch((z)=>this._onerror(Error(`Failed to enqueue error response: ${z}`)));else Q?.send(H).catch((z)=>this._onerror(Error(`Failed to send an error response: ${z}`)));return}let X=new AbortController;this._requestHandlerAbortControllers.set(w.id,X);let J=wJ(w.params)?w.params.task:void 0,Y=this._taskStore?this.requestTaskStore(w,Q?.sessionId):void 0,G={signal:X.signal,sessionId:Q?.sessionId,_meta:w.params?._meta,sendNotification:async(H)=>{let z={relatedRequestId:w.id};if(W)z.relatedTask={taskId:W};await this.notification(H,z)},sendRequest:async(H,z,B)=>{let L={...B,relatedRequestId:w.id};if(W&&!L.relatedTask)L.relatedTask={taskId:W};let F=L.relatedTask?.taskId??W;if(F&&Y)await Y.updateTaskStatus(F,"input_required");return await this.request(H,z,L)},authInfo:b?.authInfo,requestId:w.id,requestInfo:b?.requestInfo,taskId:W,taskStore:Y,taskRequestedTtl:J?.ttl,closeSSEStream:b?.closeSSEStream,closeStandaloneSSEStream:b?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(J)this.assertTaskHandlerCapability(w.method)}).then(()=>$(w,G)).then(async(H)=>{if(X.signal.aborted)return;let z={result:H,jsonrpc:"2.0",id:w.id};if(W&&this._taskMessageQueue)await this._enqueueTaskMessage(W,{type:"response",message:z,timestamp:Date.now()},Q?.sessionId);else await Q?.send(z)},async(H)=>{if(X.signal.aborted)return;let z={jsonrpc:"2.0",id:w.id,error:{code:Number.isSafeInteger(H.code)?H.code:i.InternalError,message:H.message??"Internal error",...H.data!==void 0&&{data:H.data}}};if(W&&this._taskMessageQueue)await this._enqueueTaskMessage(W,{type:"error",message:z,timestamp:Date.now()},Q?.sessionId);else await Q?.send(z)}).catch((H)=>this._onerror(Error(`Failed to send response: ${H}`))).finally(()=>{this._requestHandlerAbortControllers.delete(w.id)})}_onprogress(w){let{progressToken:b,...$}=w.params,Q=Number(b),W=this._progressHandlers.get(Q);if(!W){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(w)}`));return}let X=this._responseHandlers.get(Q),J=this._timeoutInfo.get(Q);if(J&&X&&J.resetTimeoutOnProgress)try{this._resetTimeout(Q)}catch(Y){this._responseHandlers.delete(Q),this._progressHandlers.delete(Q),this._cleanupTimeout(Q),X(Y);return}W($)}_onresponse(w){let b=Number(w.id),$=this._requestResolvers.get(b);if($){if(this._requestResolvers.delete(b),nw(w))$(w);else{let X=new c(w.error.code,w.error.message,w.error.data);$(X)}return}let Q=this._responseHandlers.get(b);if(Q===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(w)}`));return}this._responseHandlers.delete(b),this._cleanupTimeout(b);let W=!1;if(nw(w)&&w.result&&typeof w.result==="object"){let X=w.result;if(X.task&&typeof X.task==="object"){let J=X.task;if(typeof J.taskId==="string")W=!0,this._taskProgressTokens.set(J.taskId,b)}}if(!W)this._progressHandlers.delete(b);if(nw(w))Q(w);else{let X=c.fromError(w.error.code,w.error.message,w.error.data);Q(X)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(w,b,$){let{task:Q}=$??{};if(!Q){try{yield{type:"result",result:await this.request(w,b,$)}}catch(X){yield{type:"error",error:X instanceof c?X:new c(i.InternalError,String(X))}}return}let W;try{let X=await this.request(w,Ww,$);if(X.task)W=X.task.taskId,yield{type:"taskCreated",task:X.task};else throw new c(i.InternalError,"Task creation did not return a task");while(!0){let J=await this.getTask({taskId:W},$);if(yield{type:"taskStatus",task:J},E0(J.status)){if(J.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:W},b,$)};else if(J.status==="failed")yield{type:"error",error:new c(i.InternalError,`Task ${W} failed`)};else if(J.status==="cancelled")yield{type:"error",error:new c(i.InternalError,`Task ${W} was cancelled`)};return}if(J.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:W},b,$)};return}let Y=J.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((G)=>setTimeout(G,Y)),$?.signal?.throwIfAborted()}}catch(X){yield{type:"error",error:X instanceof c?X:new c(i.InternalError,String(X))}}}request(w,b,$){let{relatedRequestId:Q,resumptionToken:W,onresumptiontoken:X,task:J,relatedTask:Y}=$??{};return new Promise((G,H)=>{let z=(P)=>{H(P)};if(!this._transport){z(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(w.method),J)this.assertTaskCapability(w.method)}catch(P){z(P);return}$?.signal?.throwIfAborted();let B=this._requestMessageId++,L={...w,jsonrpc:"2.0",id:B};if($?.onprogress)this._progressHandlers.set(B,$.onprogress),L.params={...w.params,_meta:{...w.params?._meta||{},progressToken:B}};if(J)L.params={...L.params,task:J};if(Y)L.params={...L.params,_meta:{...L.params?._meta||{},[I0]:Y}};let F=(P)=>{this._responseHandlers.delete(B),this._progressHandlers.delete(B),this._cleanupTimeout(B),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:B,reason:String(P)}},{relatedRequestId:Q,resumptionToken:W,onresumptiontoken:X}).catch((S)=>this._onerror(Error(`Failed to send cancellation: ${S}`)));let v=P instanceof c?P:new c(i.RequestTimeout,String(P));H(v)};this._responseHandlers.set(B,(P)=>{if($?.signal?.aborted)return;if(P instanceof Error)return H(P);try{let v=q0(b,P.result);if(!v.success)H(v.error);else G(v.data)}catch(v){H(v)}}),$?.signal?.addEventListener("abort",()=>{F($?.signal?.reason)});let A=$?.timeout??ZL,j=()=>F(c.fromError(i.RequestTimeout,"Request timed out",{timeout:A}));this._setupTimeout(B,A,$?.maxTotalTimeout,j,$?.resetTimeoutOnProgress??!1);let q=Y?.taskId;if(q){let P=(v)=>{let S=this._responseHandlers.get(B);if(S)S(v);else this._onerror(Error(`Response handler missing for side-channeled request ${B}`))};this._requestResolvers.set(B,P),this._enqueueTaskMessage(q,{type:"request",message:L,timestamp:Date.now()}).catch((v)=>{this._cleanupTimeout(B),H(v)})}else this._transport.send(L,{relatedRequestId:Q,resumptionToken:W,onresumptiontoken:X}).catch((P)=>{this._cleanupTimeout(B),H(P)})})}async getTask(w,b){return this.request({method:"tasks/get",params:w},G6,b)}async getTaskResult(w,b,$){return this.request({method:"tasks/result",params:w},b,$)}async listTasks(w,b){return this.request({method:"tasks/list",params:w},D6,b)}async cancelTask(w,b){return this.request({method:"tasks/cancel",params:w},JJ,b)}async notification(w,b){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(w.method);let $=b?.relatedTask?.taskId;if($){let J={...w,jsonrpc:"2.0",params:{...w.params,_meta:{...w.params?._meta||{},[I0]:b.relatedTask}}};await this._enqueueTaskMessage($,{type:"notification",message:J,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(w.method)&&!w.params&&!b?.relatedRequestId&&!b?.relatedTask){if(this._pendingDebouncedNotifications.has(w.method))return;this._pendingDebouncedNotifications.add(w.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(w.method),!this._transport)return;let J={...w,jsonrpc:"2.0"};if(b?.relatedTask)J={...J,params:{...J.params,_meta:{...J.params?._meta||{},[I0]:b.relatedTask}}};this._transport?.send(J,b).catch((Y)=>this._onerror(Y))});return}let X={...w,jsonrpc:"2.0"};if(b?.relatedTask)X={...X,params:{...X.params,_meta:{...X.params?._meta||{},[I0]:b.relatedTask}}};await this._transport.send(X,b)}setRequestHandler(w,b){let $=q$(w);this.assertRequestHandlerCapability($),this._requestHandlers.set($,(Q,W)=>{let X=I$(w,Q);return Promise.resolve(b(X,W))})}removeRequestHandler(w){this._requestHandlers.delete(w)}assertCanSetRequestHandler(w){if(this._requestHandlers.has(w))throw Error(`A request handler for ${w} already exists, which would be overridden`)}setNotificationHandler(w,b){let $=q$(w);this._notificationHandlers.set($,(Q)=>{let W=I$(w,Q);return Promise.resolve(b(W))})}removeNotificationHandler(w){this._notificationHandlers.delete(w)}_cleanupTaskProgressHandler(w){let b=this._taskProgressTokens.get(w);if(b!==void 0)this._progressHandlers.delete(b),this._taskProgressTokens.delete(w)}async _enqueueTaskMessage(w,b,$){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let Q=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(w,b,$,Q)}async _clearTaskQueue(w,b){if(this._taskMessageQueue){let $=await this._taskMessageQueue.dequeueAll(w,b);for(let Q of $)if(Q.type==="request"&&J$(Q.message)){let W=Q.message.id,X=this._requestResolvers.get(W);if(X)X(new c(i.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(W);else this._onerror(Error(`Resolver missing for request ${W} during task ${w} cleanup`))}}}async _waitForTaskUpdate(w,b){let $=this._options?.defaultTaskPollInterval??1000;try{let Q=await this._taskStore?.getTask(w);if(Q?.pollInterval)$=Q.pollInterval}catch{}return new Promise((Q,W)=>{if(b.aborted){W(new c(i.InvalidRequest,"Request cancelled"));return}let X=setTimeout(Q,$);b.addEventListener("abort",()=>{clearTimeout(X),W(new c(i.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(w,b){let $=this._taskStore;if(!$)throw Error("No task store configured");return{createTask:async(Q)=>{if(!w)throw Error("No request provided");return await $.createTask(Q,w.id,{method:w.method,params:w.params},b)},getTask:async(Q)=>{let W=await $.getTask(Q,b);if(!W)throw new c(i.InvalidParams,"Failed to retrieve task: Task not found");return W},storeTaskResult:async(Q,W,X)=>{await $.storeTaskResult(Q,W,X,b);let J=await $.getTask(Q,b);if(J){let Y=rw.parse({method:"notifications/tasks/status",params:J});if(await this.notification(Y),E0(J.status))this._cleanupTaskProgressHandler(Q)}},getTaskResult:(Q)=>{return $.getTaskResult(Q,b)},updateTaskStatus:async(Q,W,X)=>{let J=await $.getTask(Q,b);if(!J)throw new c(i.InvalidParams,`Task "${Q}" not found - it may have been cleaned up`);if(E0(J.status))throw new c(i.InvalidParams,`Cannot update task "${Q}" from terminal status "${J.status}" to "${W}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await $.updateTaskStatus(Q,W,X,b);let Y=await $.getTask(Q,b);if(Y){let G=rw.parse({method:"notifications/tasks/status",params:Y});if(await this.notification(G),E0(Y.status))this._cleanupTaskProgressHandler(Q)}},listTasks:(Q)=>{return $.listTasks(Q,b)}}}}function LJ(w){return w!==null&&typeof w==="object"&&!Array.isArray(w)}function FJ(w,b){let $={...w};for(let Q in b){let W=Q,X=b[W];if(X===void 0)continue;let J=$[W];if(LJ(J)&&LJ(X))$[W]={...J,...X};else $[W]=X}return $}var nH=KQ(j9(),1),pH=KQ(iH(),1);function TM(){let w=new nH.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return pH.default(w),w}class S9{constructor(w){this._ajv=w??TM()}getValidator(w){let b="$id"in w&&typeof w.$id==="string"?this._ajv.getSchema(w.$id)??this._ajv.compile(w):this._ajv.compile(w);return($)=>{if(b($))return{valid:!0,data:$,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(b.errors)}}}}class v9{constructor(w){this._server=w}requestStream(w,b,$){return this._server.requestStream(w,b,$)}async getTask(w,b){return this._server.getTask({taskId:w},b)}async getTaskResult(w,b,$){return this._server.getTaskResult({taskId:w},b,$)}async listTasks(w,b){return this._server.listTasks(w?{cursor:w}:void 0,b)}async cancelTask(w,b){return this._server.cancelTask({taskId:w},b)}}function dH(w,b,$){if(!w)throw Error(`${$} does not support task creation (required for ${b})`);switch(b){case"tools/call":if(!w.tools?.call)throw Error(`${$} does not support task creation for tools/call (required for ${b})`);break;default:break}}function oH(w,b,$){if(!w)throw Error(`${$} does not support task creation (required for ${b})`);switch(b){case"sampling/createMessage":if(!w.sampling?.createMessage)throw Error(`${$} does not support task creation for sampling/createMessage (required for ${b})`);break;case"elicitation/create":if(!w.elicitation?.create)throw Error(`${$} does not support task creation for elicitation/create (required for ${b})`);break;default:break}}class C9 extends E${constructor(w,b){super(b);if(this._serverInfo=w,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(aw.options.map(($,Q)=>[$,Q])),this.isMessageIgnored=($,Q)=>{let W=this._loggingLevels.get(Q);return W?this.LOG_LEVEL_SEVERITY.get($)<this.LOG_LEVEL_SEVERITY.get(W):!1},this._capabilities=b?.capabilities??{},this._instructions=b?.instructions,this._jsonSchemaValidator=b?.jsonSchemaValidator??new S9,this.setRequestHandler(H$,($)=>this._oninitialize($)),this.setNotificationHandler(z$,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(j$,async($,Q)=>{let W=Q.sessionId||Q.requestInfo?.headers["mcp-session-id"]||void 0,{level:X}=$.params,J=aw.safeParse(X);if(J.success)this._loggingLevels.set(W,J.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new v9(this)};return this._experimental}registerCapabilities(w){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=FJ(this._capabilities,w)}setRequestHandler(w,b){let Q=sb(w)?.method;if(!Q)throw Error("Schema is missing a method literal");let W;if($w(Q)){let J=Q;W=J._zod?.def?.value??J.value}else{let J=Q;W=J._def?.value??J.value}if(typeof W!=="string")throw Error("Schema method literal must be a string");if(W==="tools/call"){let J=async(Y,G)=>{let H=q0(ew,Y);if(!H.success){let F=H.error instanceof Error?H.error.message:String(H.error);throw new c(i.InvalidParams,`Invalid tools/call request: ${F}`)}let{params:z}=H.data,B=await Promise.resolve(b(Y,G));if(z.task){let F=q0(Ww,B);if(!F.success){let A=F.error instanceof Error?F.error.message:String(F.error);throw new c(i.InvalidParams,`Invalid task creation result: ${A}`)}return F.data}let L=q0(L6,B);if(!L.success){let F=L.error instanceof Error?L.error.message:String(L.error);throw new c(i.InvalidParams,`Invalid tools/call result: ${F}`)}return L.data};return super.setRequestHandler(w,J)}return super.setRequestHandler(w,b)}assertCapabilityForMethod(w){switch(w){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${w})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${w})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${w})`);break;case"ping":break}}assertNotificationCapability(w){switch(w){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${w})`);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 ${w})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${w})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${w})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${w})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(w){if(!this._capabilities)return;switch(w){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${w})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${w})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${w})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${w})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${w})`);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 ${w})`);break;case"ping":case"initialize":break}}assertTaskCapability(w){oH(this._clientCapabilities?.tasks?.requests,w,"Client")}assertTaskHandlerCapability(w){if(!this._capabilities)return;dH(this._capabilities.tasks?.requests,w,"Server")}async _oninitialize(w){let b=w.params.protocolVersion;return this._clientCapabilities=w.params.capabilities,this._clientVersion=w.params.clientInfo,{protocolVersion:sX.includes(b)?b:W$,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"},Q6)}async createMessage(w,b){if(w.tools||w.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if(w.messages.length>0){let $=w.messages[w.messages.length-1],Q=Array.isArray($.content)?$.content:[$.content],W=Q.some((G)=>G.type==="tool_result"),X=w.messages.length>1?w.messages[w.messages.length-2]:void 0,J=X?Array.isArray(X.content)?X.content:[X.content]:[],Y=J.some((G)=>G.type==="tool_use");if(W){if(Q.some((G)=>G.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 G=new Set(J.filter((z)=>z.type==="tool_use").map((z)=>z.id)),H=new Set(Q.filter((z)=>z.type==="tool_result").map((z)=>z.toolUseId));if(G.size!==H.size||![...G].every((z)=>H.has(z)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if(w.tools)return this.request({method:"sampling/createMessage",params:w},V$,b);return this.request({method:"sampling/createMessage",params:w},M$,b)}async elicitInput(w,b){switch(w.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let Q=w;return this.request({method:"elicitation/create",params:Q},F6,b)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let Q=w.mode==="form"?w:{...w,mode:"form"},W=await this.request({method:"elicitation/create",params:Q},F6,b);if(W.action==="accept"&&W.content&&Q.requestedSchema)try{let J=this._jsonSchemaValidator.getValidator(Q.requestedSchema)(W.content);if(!J.valid)throw new c(i.InvalidParams,`Elicitation response content does not match requested schema: ${J.errorMessage}`)}catch(X){if(X instanceof c)throw X;throw new c(i.InternalError,`Error validating elicitation response: ${X instanceof Error?X.message:String(X)}`)}return W}}}createElicitationCompletionNotifier(w,b){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:w}},b)}async listRoots(w,b){return this.request({method:"roots/list",params:w},P$,b)}async sendLoggingMessage(w,b){if(this._capabilities.logging){if(!this.isMessageIgnored(w.level,b))return this.notification({method:"notifications/message",params:w})}}async sendResourceUpdated(w){return this.notification({method:"notifications/resources/updated",params:w})}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 tH={name:"@sequenzy/mcp",version:"0.0.143",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 k9=["product-info","domain","tracking","localization","integrations","products","events","tags","labels","goals","sync-rules","api-keys","widgets","team","danger"],rH={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 SM(w){let $=(w??process.env.SEQUENZY_APP_URL??"https://sequenzy.com").trim().replace(/\/+$/,"");return $.length>0?$:"https://sequenzy.com"}function e1(w){let b=w?.trim();return b?b:void 0}function W0(w){return encodeURIComponent(w)}function D1(w,b){return`${w}${b}`}function B1(w,b=""){return`/dashboard/company/${W0(w)}${b}`}function sH(w,b,$){return D1(w,`${B1(b,"/settings")}?tab=${encodeURIComponent($)}`)}function vM(w,b){let $=k9.map((Q)=>[Q,b?sH(w,b,Q):""]);return Object.fromEntries($)}function F0(w={},b){let $=SM(b),Q=e1(w.companyId),W={},X=vM($,Q);if(!Q)return{appUrl:$,routeTemplates:rH,settingsTabValues:k9,urls:W,settingsUrls:X};W.dashboard=D1($,B1(Q)),W.campaigns=D1($,B1(Q,"/campaign")),W.landingPages=D1($,B1(Q,"/landing-pages")),W.sequences=D1($,B1(Q,"/sequences")),W.settings=D1($,B1(Q,"/settings")),W.emails=D1($,B1(Q,"/emails")),W.subscribers=D1($,B1(Q,"/subscribers")),W.sentEmails=D1($,B1(Q,"/sent-emails")),W.segments=D1($,B1(Q,"/segments")),W.metrics=D1($,B1(Q,"/metrics")),W.transactional=D1($,B1(Q,"/transactional"));let J=e1(w.campaignId);if(J)W.campaign=D1($,B1(Q,`/campaign/${W0(J)}`)),W.campaignPreview=`${W.campaign}?step=review`;let Y=e1(w.landingPageId);if(Y)W.landingPage=D1($,B1(Q,`/landing-pages/${W0(Y)}`));let G=e1(w.sequenceId);if(G)W.sequence=D1($,B1(Q,`/sequences/${W0(G)}`));let H=e1(w.emailId)??e1(w.templateId);if(H)W.email=D1($,B1(Q,`/emails/${W0(H)}`)),W.template=W.email;let z=e1(w.transactionalId);if(z)W.transactionalEmail=D1($,B1(Q,`/transactional/${W0(z)}`));let B=e1(w.emailSendId);if(B)W.emailSend=D1($,B1(Q,`/sent-emails/${W0(B)}`));let L=e1(w.domainId);if(L)W.domain=D1($,B1(Q,`/settings/domain/${W0(L)}`)),W.domainVerify=`${W.domain}/verify`;let F=e1(w.status);if(F)W.campaignList=D1($,B1(Q,`/campaign/list/${W0(F)}`)),W.sequenceList=D1($,B1(Q,`/sequences/list/${W0(F)}`));let A=e1(w.settingsTab);if(A)W.settingsTab=sH($,Q,A);return{appUrl:$,routeTemplates:rH,settingsTabValues:k9,urls:W,settingsUrls:X}}var eH=[{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 aH(w){try{let b;switch(w){case"sequenzy://dashboard":b=await D("GET","/api/v1/metrics?period=7d");break;case"sequenzy://company":{let $=await D("GET","/api/v1/account"),Q=h0()??$.currentCompanyId;if(!Q)throw Error("No company available. Create or select a company first.");b=await D("GET",`/api/v1/companies/${Q}`);break}case"sequenzy://campaigns/recent":b=await D("GET","/api/v1/campaigns?limit=10");break;case"sequenzy://subscribers/recent":b=await D("GET","/api/v1/subscribers?sort=createdAt&limit=20");break;case"sequenzy://subscribers/engaged":b=await D("GET","/api/v1/subscribers?sort=engagement&limit=20");break;case"sequenzy://sequences":b=await D("GET","/api/v1/sequences");break;case"sequenzy://templates":b=await D("GET","/api/v1/templates");break;case"sequenzy://segments":b=await D("GET","/api/v1/segments");break;case"sequenzy://tags":b=await D("GET","/api/v1/tags");break;case"sequenzy://health":b=await D("GET","/api/v1/health/deliverability");break;case"sequenzy://app-routes":b=F0();break;default:throw Error(`Unknown resource: ${w}`)}return{contents:[{uri:w,mimeType:"application/json",text:JSON.stringify(b,null,2)}]}}catch(b){return{contents:[{uri:w,mimeType:"text/plain",text:s0(b)}]}}}function k(w){return typeof w==="object"&&w!==null&&!Array.isArray(w)}function U(w,b){let $=w[b];if(typeof $!=="string")return;let Q=$.trim();return Q.length>0?Q:void 0}function _9(w,b,$){let Q=b[$];if(Q===void 0||Q===null)return[];if(typeof Q==="string"){let X=Q.trim();return X.length>0?[X]:[]}if(!Array.isArray(Q))throw Error(`\`${$}\` must be an array of strings when calling \`${w}\`.`);let W=[];return Q.forEach((X,J)=>{if(typeof X!=="string")throw Error(`\`${$}\` item ${J+1} must be a string when calling \`${w}\`.`);let Y=X.trim();if(Y.length>0&&!W.includes(Y))W.push(Y)}),W}function M(w,b,$){let Q=U(b,$);if(Q===void 0)throw Error(`\`${$}\` is required when calling \`${w}\`.`);return Q}var a6=' Minimal valid core examples: {"type":"heading","content":"Title","level":1}; {"type":"text","content":"<p>Paragraph with <strong>bold</strong></p>","variant":"paragraph"}; {"type":"button","text":"Click Me","url":"https://example.com","variant":"primary"}; {"type":"image","src":"https://...","alt":"Description","width":100,"widthType":"percent","height":240,"objectFit":"cover","href":"https://example.com","align":"center"}. Heading and text use `content`; button uses `text` but also accepts `content` as an alias and defaults `variant` to `primary`. Image `widthType` accepts `percent` or `px`.';var x9=' Any block accepts a `conditions` array so it only renders for matching recipients. To branch on a value passed in transactional `variables` or an automation `event` payload, use { "id": "c1", "field": "variable", "operator": "is", "value": "plan:pro" }; "attribute" uses the same "name:value" form, while "email"/"firstName"/"lastName" use a plain comparison value. Live subscriber fields are "status", "tag", "list", "segment", "event", "emailProvider", "phone", "smsStatus", "added", "stripeProduct", "stripeCurrentProduct", "stripeTrialProduct", "commerceProduct", "commerceCollection", "emailSent", "emailDelivered", "emailOpened", "emailClicked", "emailBounced", and "emailComplained". They use the same field-specific values and operators as segment filters, for example { "id": "c2", "field": "segment", "operator": "is", "value": "seg_123" }, { "id": "c3", "field": "tag", "operator": "contains", "value": "vip" }, or { "id": "c4", "field": "event", "operator": "at_least", "value": "purchase:3:30d" }. Supported operators across fields are is, is_not, contains, not_contains, gt, gte, lt, lte, less_than, more_than, at_least, less_than_count, is_empty, is_not_empty, is_temporary_bounce, and is_permanent_bounce; each field accepts only its segment-filter operators. Recipients without a stored subscriber match use the OTHERWISE branch or hide a conditionally displayed block. For if/else, use a { type: "conditional-group", conditions: [...], ifBranch: { children: [...] }, elseBranch: { children: [...] } } block.',h9=' 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. Set `allowMultiple: true` on a text-only options poll to let recipients pick several answers: answer links then open a hosted selection page where the recipient checks any number of options and saves them in one submit, and `attributeKey` stores the list of selected values (filter with attribute `contains`). Multi-select polls cannot use option images or configurations whose encoded signed links exceed the delivery-safe size limit. 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). `accentColor` recolors every appearance, including "brutal". `optionRadius` sets answer-button corners in px (0 is square) independently of `styles.borderRadius`, while `questionColor` recolors only the question. `fontFamily` applies to the poll; `optionFontSize`, `optionFontWeight`, `optionLetterSpacing`, and `optionTextTransform` style answers, and the matching `questionFontSize`, `questionFontWeight`, `questionLetterSpacing`, and `questionTextTransform` fields style the question. Sizes and spacing are px, weights are 100-900, and transforms are "none" or "uppercase". Optional `confirmationMessage` customizes the hosted thank-you page; set `redirectUrl` only when respondents should land on another page.',y9=' 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" }.',H1="Raw HTML is stored as one opaque block. Sequenzy preserves that markup but does not add a company logo, branded native sections, or theme-driven block design. Use blocks for editor-native design, or a drafting prompt when you want Sequenzy to compose a new branded email.",w4=' The code is minted per subscriber at run time and reaches every later email in the same sequence as {{discount.code}}. Also available: {{discount.value}} (pre-formatted, e.g. "20% off" or "$10 off"), {{discount.percentOff}}, {{discount.amountOff}}, {{discount.currency}}, and {{date.discount.expiresAt}} (locale-formatted expiry). Present the code with a { "type": "discount-code", "code": "{{discount.code}}", "label": "Your discount code" } block, or inline {{discount.code}} in any text block. These tags resolve only in emails downstream of the discount step; render_email substitutes a clearly fake sample code so the email can be previewed before anyone is enrolled, and lists anything it could not resolve under unresolvedMergeTags.',_0='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`.',f9=" `styles` applies to the block's own container, not to an inner rendered element. On a button block, `styles.backgroundColor` colors the band behind the button and `styles.textColor` does not reach the label - set the top-level `buttonColor` and `buttonTextColor` fields instead, or leave them unset to inherit the email theme's primary color.",n0=" Unsupported fields are discarded and reported in the response `warnings` array rather than rejected.",U0=`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: [...] }.${x9}${f9}${n0}${h9}${y9}${a6}`,b4=" Replacing a step's blocks keeps that step's existing Style > Format rather than the company default: a step that already had a logo or footer gets them back even if you omit them, and every block added that way is listed in the response `warnings`. Pass `emailPreset` to change the format. A step whose stored content is a single raw HTML block has no format, so replacing it with another single raw HTML block is stored exactly as sent; replacing it with native blocks converts the step and does add a footer.",CM=` For action_email:${b4}`,A0=`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\`.${x9}${f9}${n0}${h9}${y9}${a6}`,Kw=`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.${x9}${f9}${n0}${h9}${y9}${a6}`,p0="Display name recipients see, e.g. 'Brennon at TradeTally'. Selects the sender identity of that name on fromEmail, creating it when the address has no identity by that name; the mailbox's other display names, and everything pinned to them, are untouched. Requires fromEmail; omit it when using senderProfileId, which already carries its own display name.",d0="Display name for the Reply-To address. Requires replyTo; omit it when using replyProfileId, which already carries its own display name. An address carries one Reply-To name company-wide: if replyTo already has a saved profile under a different name, that saved name is kept and the response `warnings` array says so. Rename it with update_sender_profile (type 'reply') to change it everywhere.",qb="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.",w5="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.",u9=500,c9=500,$4=["is","contains","gt","gte","lt","lte","is_not_empty"],x1={type:"boolean",description:"If true, include machine-classified bot/scanner opens and clicks. Defaults to false, so metrics and activity are human-only."},Ib=["send","delivery","bounce","complaint","open","click","unsubscribe","delivery_delay","transport_failure"],Eb=Ib.join(", "),Q4={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, or 24:00 for the end-of-day boundary. 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},kM={type:"object",description:"Offset relative to a wait-until date.",properties:{days:{type:"number"},hours:{type:"number"},minutes:{type:"number"}},additionalProperties:!1},Ow={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:kM,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},Zw={type:"object",description:"Wait until the next occurrence of a weekday inside a local-time window before this step, e.g. { day: 'sunday', startTime: '09:00', endTime: '12:00', timezone: 'America/Los_Angeles' }. Continues immediately when the step is reached inside the window, so a Sunday-morning enrollment is not pushed a full week. Place it immediately before the email when the send day matters - it controls when the flow resumes, so any step between it and the email shifts the send off the window (a sequence-level sendingWindow only holds emails at send time; it does not reschedule the graph).",properties:{day:{type:"string",description:"Single weekday convenience alias for days, e.g. sunday or sun."},days:{type:"array",items:{type:"string"},description:"Weekdays the wait may release on. Full or short names such as sunday, sun. The nearest upcoming day wins."},startTime:{type:"string",description:"Window start in 24-hour HH:mm local time, e.g. 09:00. Required."},endTime:{type:"string",description:"Window end in 24-hour HH:mm local time. Defaults to the end-of-day boundary 24:00. If the wake-up is missed past endTime (rare operational failure), the wait rolls to the next configured day instead of releasing late."},timezone:{type:"string",description:"IANA timezone the window is evaluated in, e.g. America/Los_Angeles. Required."},untilStartTime:{type:"string",description:"Alias for startTime."},untilEndTime:{type:"string",description:"Alias for endTime."},untilTimezone:{type:"string",description:"Alias for timezone."}},additionalProperties:!1},jw={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. For a wait-until-weekday-window delay, either set mode:'until_weekday' plus untilDays/untilStartTime/untilTimezone here, or use waitUntilWeekday.",properties:{days:{type:"number"},hours:{type:"number"},minutes:{type:"number"},mode:{type:"string",enum:["duration","until_date","until_weekday"],description:"Use duration for a fixed wait, until_date to resolve a date from the trigger event, or until_weekday to wait for the next weekday/time window."},untilDays:{type:"array",items:{type:"string"},description:"For mode:'until_weekday', weekday names the wait may release on."},untilStartTime:{type:"string",description:"For mode:'until_weekday', window start in 24-hour HH:mm local time."},untilEndTime:{type:"string",description:"For mode:'until_weekday', window end in 24-hour HH:mm local time. Defaults to the end-of-day boundary 24:00."},untilTimezone:{type:"string",description:"For mode:'until_weekday', IANA timezone the window is evaluated in."},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},m9={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, waitUntil, or waitUntilWeekday ({ day, startTime, endTime, timezone } - hold until the next weekday window); optional label is also accepted. For action_email, use name/label, subject, previewText, html/htmlContent or blocks, emailPreset, isTransactional, attachments ([{ filename, path }] URL-backed files fetched at send time; path may use {{event.*}} from the enrollment event; [] removes them), 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.${CM}`,properties:{emailPreset:{type:"string",enum:["branded","minimal"],description:"For an action_email node with native Sequenzy blocks, set the linked email's per-email Style > Format. Native block emails may include supported custom HTML blocks. Use minimal for a direct text-forward note without the company logo and with the simple footer, or branded to restore branded chrome. This does not change the company-wide default. Not a lossless toggle: minimal deletes standalone logo blocks, so switching back to branded generates a new logo block with a new id and the company name as alt text - send the authored logo block in `blocks` alongside the branded update to keep it. A standalone raw HTML email does not support this field, and emailPreset must not be combined with html/htmlContent."}},additionalProperties:!0},W4={type:"object",properties:{nodeId:{type:"string",description:"Existing node ID from get_sequence.sequence.nodes[].id."},changes:m9,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},Mw=["gray","red","orange","amber","yellow","lime","green","emerald","teal","cyan","sky","blue","indigo","violet","purple","fuchsia","pink","rose"],Vw=["email.sent","email.delivered","email.delivery_delayed","email.bounced","email.failed","email.complained","email.opened","email.clicked","email.replied","email.unsubscribed","sms.sent","sms.delivered","sms.failed","sms.opted_out","subscriber.invalid","subscriber.created","subscriber.updated","subscriber.unsubscribed","subscriber.list_subscribed","subscriber.list_unsubscribed","sequence.finished","sequence.failed","poll.answered"];var _M=new Set(["get_account","get_app_urls","get_company","get_sync_rules","get_shopify_automation_settings","list_api_keys","list_websites","list_integrations","get_integration","get_integration_pixel","list_integration_capabilities","list_integration_activity","list_sender_profiles","get_notification_preferences","get_tracking_settings","get_sending_status","check_website","get_integration_guide","get_subscriber","get_subscriber_import","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_campaign_audience","render_email","list_email_sends","get_email_send","list_forms","get_form_embed","get_recipient_suppression","list_landing_pages","get_landing_page","list_sequences","get_sequence","list_sequence_enrollments","list_sequence_goals","get_sequence_inbound_webhook","list_transactional_emails","get_transactional_email","get_stats","get_transactional_stats","get_campaign_stats","list_poll_responses","get_sequence_stats","list_campaign_events","list_sequence_events","list_email_metrics","get_subscriber_activity","list_team_members","list_conversations","get_conversation","list_webhooks","list_webhook_deliveries","generate_email","generate_subject_lines","generate_sms","get_sms_settings"]),xM=new Set(["select_company","create_company","update_company","update_notification_preferences","update_sender_profile","update_tracking_settings","resume_sending","update_sync_rules","update_shopify_automation_settings","connect_integration","set_integration_sync_enabled","sync_integration","activate_integration_pixel","create_api_key","update_api_key","revoke_api_key","delete_api_key","add_sending_domain","add_website","verify_sending_domain","add_subscriber","create_subscriber_import","update_subscriber","add_subscriber_note","remove_subscriber","delete_subscriber_note","trigger_subscriber_event","trigger_subscriber_events","bulk_add_subscriber_tags","bulk_remove_subscriber_tags","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","update_ab_test","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","unschedule_campaign","cancel_campaign","pause_campaign","resume_campaign","delete_campaign","duplicate_campaign","resend_campaign_to_non_openers","create_form","update_form","create_landing_page","update_landing_page","duplicate_landing_page","delete_landing_page","publish_landing_page","unpublish_landing_page","connect_landing_page_domain","update_landing_page_domain_settings","create_sequence","generate_sequence","send_sequence_test_email","update_sequence","update_sequence_node","update_sequence_nodes","edit_sequence_graph","insert_sequence_step","enable_sequence","disable_sequence","duplicate_sequence","archive_sequence","unarchive_sequence","create_sequence_goal","update_sequence_goal","delete_sequence_goal","configure_sequence_inbound_webhook","rotate_sequence_inbound_webhook_secret","pause_sequence_enrollments","resume_sequence_enrollments","enroll_subscribers_in_sequence","cancel_sequence_enrollments","delete_sequence","create_transactional_email","update_transactional_email","delete_transactional_email","send_email","invite_team_member","cancel_team_invitation","reply_to_conversation","update_conversation_status","mark_conversation_read","create_webhook","update_webhook","delete_webhook","test_webhook","replay_webhook_delivery","submit_feedback","remove_recipient_suppression"]),hM=new Set(["send_test_email","send_test_sms","send_sequence_test_email","schedule_campaign","resume_campaign","publish_landing_page","connect_landing_page_domain","update_landing_page_domain_settings","add_sending_domain","add_website","verify_sending_domain","connect_integration","sync_integration","get_integration_pixel","activate_integration_pixel","enable_sequence","unarchive_sequence","resume_sequence_enrollments","send_email","invite_team_member","reply_to_conversation","create_webhook","update_webhook","test_webhook","replay_webhook_delivery","remove_recipient_suppression"]),yM=new Set(["revoke_api_key","delete_api_key","remove_subscriber","delete_subscriber_note","delete_product","remove_product_file","delete_tag","delete_list","remove_subscribers_from_list","bulk_remove_subscriber_tags","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","set_integration_sync_enabled","disable_sequence","archive_sequence","delete_sequence_goal","rotate_sequence_inbound_webhook_secret","edit_sequence_graph","cancel_sequence_enrollments","delete_sequence","cancel_team_invitation","delete_webhook","delete_transactional_email","remove_recipient_suppression"]);function fM(w){let b=_M.has(w),$=xM.has(w);if(b===$)throw Error(`MCP tool "${w}" must be classified as exactly one of read-only or mutating.`);return{readOnlyHint:b,destructiveHint:b?!1:yM.has(w),openWorldHint:hM.has(w)}}function b5(w){return{...w,annotations:{...w.annotations,...fM(w.name)}}}var l9={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","is","is_not"],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"],commerceCollection:["is","is_not","at_least","less_than_count"]},uM=Object.entries(l9).map(([w,b])=>`${w}: ${b.join(", ")}`).join("; "),g9={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","commerceCollection"],description:`Filter field. Use \`email\` with is/is_not for exact, case-insensitive address matching (allowlists and exclusions) and with contains/not_contains for domain or substring matching. 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. Use \`commerceCollection\` to segment on anyone who bought ANY product in a store collection - the value is the collection id or handle (e.g. \`skincare\`), optionally provider-prefixed and/or with an order-count threshold (\`shopify:skincare:2\`); collection membership is resolved from the synced catalog as it stands now, and only Shopify collections and WooCommerce categories are synced. 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. ${_0}`},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: ${uM}.`},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). ${_0}`}},required:["field","operator","value"],additionalProperties:!1},i9={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 X4(w){if(!Array.isArray(w))return w;return w.map((b)=>{if(typeof b!=="object"||b===null)return b;let $=b;if(typeof $.id==="string"&&$.id.trim()!=="")return $;return{...$,id:crypto.randomUUID()}})}function J4(w){if(typeof w!=="object"||w===null)return w;let b=w;if(b.kind==="filter"||"field"in b||"operator"in b||"value"in b){let $=X4([b]);return Array.isArray($)?$[0]:b}if(b.kind!=="group")return w;return{...b,id:typeof b.id==="string"&&b.id.trim()!==""?b.id:crypto.randomUUID(),children:Array.isArray(b.children)?b.children.map(J4):[]}}function cM(w){let b=w.indexOf(":");return b!==-1&&w.substring(0,b).trim().length>0}function mM(w){let b=w.indexOf(":");return b!==-1&&w.substring(b+1).trim().length>0}function $5(w){if(w==="all")return!0;let b=w.match(/^(\d+)d$/);if(!b?.[1])return!1;let $=Number.parseInt(b[1],10);return Number.isInteger($)&&$>0}function lM(w,b){let $=b.split(":");if(w==="at_least"||w==="less_than_count"){if($.length<3)return'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".';let X=$.slice(0,-2).join(":").trim(),J=$.at(-2),Y=$.at(-1),G=J===void 0?Number.NaN:Number.parseInt(J,10);return X&&Number.isInteger(G)&&G>0&&Y!==void 0&&$5(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 Q=$.slice(0,-1).join(":").trim(),W=$.at(-1);return Q&&W!==void 0&&$5(W)?null:'Event filters must use "eventName:timeRange", like "saas.purchase:30d".'}function gM(w){let b=w.indexOf(":");if(b===-1)return{productId:w,subfilter:null,rawValue:null};let $=w.substring(0,b),Q=w.substring(b+1),W=Q.indexOf(":");if(W===-1)return{productId:$,subfilter:Q,rawValue:null};return{productId:$,subfilter:Q.substring(0,W),rawValue:Q.substring(W+1)}}function iM(w){return w.trim().toLowerCase().replace(/[-\s]+/g,"_")}function nM(w){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(w)}function pM(w,b){if(b==="cancels_at"||b==="cancel_at"||b==="cancellation_at")return!0;if(w==="stripeCurrentProduct")return["end_at","ends_at","period_end","period_ends_at","current_period_end"].includes(b);return["start_at","started_at","trial_start","trial_started_at","end_at","ends_at","trial_end","trial_ends_at"].includes(b)}function dM(w){return["is","is_not","gte","lte","gt","lt"].includes(w)}function oM(w,b,$){if(w==="stripeProduct"){if(b!=="at_least"&&b!=="less_than_count")return null;let Y=$.indexOf(":");if(Y===-1)return null;let G=$.substring(0,Y).trim(),H=Number.parseInt($.substring(Y+1).trim(),10);return G&&Number.isInteger(H)&&H>=1?null:'Stripe Product threshold filters must use "productId:count" with a count of at least 1.'}if(w!=="stripeCurrentProduct"&&w!=="stripeTrialProduct")return null;let{productId:Q,subfilter:W,rawValue:X}=gM($);if(!Q.trim())return"Stripe product filters must include a product ID.";if(!W)return b==="is"||b==="is_not"?null:'Stripe current/trial date filters must use "productId:dateField:value".';let J=iM(W);if(nM(J))return b==="is"||b==="is_not"?null:"Stripe cancellation flag filters only support is and is_not operators.";if(!pM(w,J))return`Unsupported Stripe product subfilter "${W}".`;if(!dM(b))return"Stripe date filters only support is, is_not, gte, lte, gt, and lt operators.";return X?.trim()?null:'Stripe date filters must include a value like "productId:end_at:2026-05-26".'}var Q5=new Set(["shopify","woocommerce","api"]);function tM(w,b){let $=b.trim(),Q=$.indexOf(":");if(Q!==-1&&Q5.has($.substring(0,Q).trim()))$=$.substring(Q+1).trim();if(!$)return'Purchased Product filters must include a product ID, like "shopify:42".';if(w!=="at_least"&&w!=="less_than_count")return null;let W=$.lastIndexOf(":");if(W===-1)return null;let X=$.substring(0,W).trim(),J=Number.parseInt($.substring(W+1).trim(),10);return X&&Number.isInteger(J)&&J>=1?null:'Purchased Product threshold filters must use "provider:productId:count" with a count of at least 1.'}function rM(w,b){let $=b.trim(),Q=$.indexOf(":");if(Q!==-1&&Q5.has($.substring(0,Q).trim()))$=$.substring(Q+1).trim();if(!$)return'Purchased Collection filters must include a collection, like "shopify:summer-sale".';if(w!=="at_least"&&w!=="less_than_count")return null;let W=$.lastIndexOf(":");if(W===-1)return null;let X=$.substring(0,W).trim(),J=Number.parseInt($.substring(W+1).trim(),10);return X&&Number.isInteger(J)&&J>=1?null:'Purchased Collection threshold filters must use "provider:collection:count" with a count of at least 1.'}function sM(w){let b;try{b=JSON.parse(w)}catch{return`Poll response filters must use valid JSON. ${_0}`}if(!k(b)||b.v!==1||typeof b.campaignId!=="string"||!b.campaignId.trim()||typeof b.blockId!=="string"||!b.blockId.trim()||!k(b.match))return`Poll response filter context is invalid. ${_0}`;let $=b.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. ${_0}`}function Y4(w){if(typeof w!=="object"||w===null)return"Segment filters must be objects.";let b=w,$=b.field,Q=b.operator,W=b.value;if(typeof $!=="string"||!($ in l9))return`Unsupported segment filter field "${String($)}".`;if(typeof Q!=="string")return`Segment filter "${$}" must include an operator.`;let X=l9[$];if(!X.includes(Q))return`Operator "${Q}" is not supported for ${$} filters. Use one of: ${X.join(", ")}.`;if(Q!=="is_empty"&&Q!=="is_not_empty"&&(typeof W!=="string"||W.trim().length===0))return`Segment filter "${$}" must include a value.`;if($==="attribute"&&typeof W==="string"){if(!cM(W))return'Attribute filters must use "attributeName:value" or "attributeName:" for empty checks.';if(Q!=="is_empty"&&Q!=="is_not_empty"&&!mM(W))return'Attribute filters must include a value after "attributeName:".'}if($==="event"&&typeof W==="string"){let J=lM(Q,W);if(J)return J}if($==="pollResponse"&&typeof W==="string"){let J=sM(W);if(J)return J}if(($==="stripeProduct"||$==="stripeCurrentProduct"||$==="stripeTrialProduct")&&typeof W==="string"){let J=oM($,Q,W);if(J)return J}if($==="commerceProduct"&&typeof W==="string"){let J=tM(Q,W);if(J)return J}if($==="commerceCollection"&&typeof W==="string"){let J=rM(Q,W);if(J)return J}if($==="tag"&&(Q==="contains"||Q==="not_contains")){if(!(typeof W==="string"&&W.split(",").map((Y)=>Y.trim()).some(Boolean)))return"Tag filters must include at least one tag name."}return null}function G4(w){if(typeof w!=="object"||w===null)return[];let b=w;if(b.kind==="filter"||"field"in b||"operator"in b||"value"in b){let $=Y4(b);return $?[$]:[]}if(Array.isArray(b.children))return b.children.flatMap(G4);return[]}function h1(w,b,$){if(b.html!==void 0&&b.blocks!==void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${w}\`, not both.`);if(b.blocks!==void 0&&!Array.isArray(b.blocks))throw Error(`\`blocks\` must be an array when calling \`${w}\`.`);if($?.requireContent&&b.html===void 0&&b.blocks===void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${w}\`.`)}function K0(w,b){if(b.labels===void 0)return;if(!Array.isArray(b.labels))throw Error(`\`labels\` must be an array when calling \`${w}\`.`);if(b.labels.some(($)=>typeof $!=="string"||$.trim().length===0))throw Error(`\`labels\` must contain only non-empty strings when calling \`${w}\`.`)}function J5(w){let b=w.filters!==void 0,$=w.root!==void 0;if(b&&$)throw Error("Provide either `filters` or `root` when calling `create_segment`, not both.");if(!b&&!$)throw Error("Provide either `filters` or `root` when calling `create_segment`.");if(b){if(!Array.isArray(w.filters))throw Error("`filters` must be an array when calling `create_segment`.");if(w.filters.length===0)throw Error("`filters` must include at least one filter when calling `create_segment`.")}if($&&(typeof w.root!=="object"||w.root===null))throw Error("`root` must be an object when calling `create_segment`.");let Q=b?w.filters.flatMap((W)=>{let X=Y4(W);return X?[X]:[]}):G4(w.root);if(Q.length>0)throw Error(Q[0]??"Invalid segment filter in `create_segment`.")}function Y5(w){let b=w.filters!==void 0,$=w.root!==void 0;if(b&&$)throw Error("Provide either `filters` or `root` when calling `update_segment`, not both.");if(w.name===void 0&&w.filterJoinOperator===void 0&&!b&&!$)throw Error("Provide at least one of `name`, `filters`, `root`, or `filterJoinOperator` when calling `update_segment`.");if(b){if(!Array.isArray(w.filters))throw Error("`filters` must be an array when calling `update_segment`.");if(w.filters.length===0)throw Error("`filters` must include at least one filter when calling `update_segment`.")}if($&&(typeof w.root!=="object"||w.root===null))throw Error("`root` must be an object when calling `update_segment`.");let Q=b?w.filters.flatMap((W)=>{let X=Y4(W);return X?[X]:[]}):$?G4(w.root):[];if(Q.length>0)throw Error(Q[0]??"Invalid segment filter in `update_segment`.")}var n9=["name","description","logoUrl","founderName","primaryColor","brandColors","valueProps","testimonials","toneVoice","companyContext","emailLengthPreference","socialLinks","privacyPolicyUrl","termsUrl","address","language","pricing","fontFamily","emailTheme","emailDirection","senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName","replyTrackingEnabled","replyTrackingDomainMode","forwardReplies"];function p9(w,b,$){if(b[$]!==void 0&&!k(b[$]))throw Error(`\`${$}\` must be an object when calling \`${w}\`.`)}function W5(w,b,$){if(b[$]!==void 0&&!Array.isArray(b[$]))throw Error(`\`${$}\` must be an array when calling \`${w}\`.`)}function G5(w){let b=new Set(["companyId",...n9]),$=Object.keys(w).filter((W)=>!b.has(W));if($.length>0)throw Error(`\`update_company\` accepts only editable company settings. Unsupported field${$.length===1?"":"s"}: ${$.map((W)=>`\`${W}\``).join(", ")}.`);let Q={};for(let W of n9)if(w[W]!==void 0)Q[W]=w[W];if(Object.keys(Q).length===0)throw Error(`Provide at least one of ${n9.map((W)=>`\`${W}\``).join(", ")} when calling \`update_company\`.`);for(let W of["name","description","logoUrl","founderName","primaryColor","toneVoice","companyContext","emailLengthPreference","privacyPolicyUrl","termsUrl","address","language","fontFamily","emailDirection","senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName","replyTrackingDomainMode"])if(w[W]!==void 0&&typeof w[W]!=="string")throw Error(`\`${W}\` must be a string when calling \`update_company\`.`);if(p9("update_company",w,"brandColors"),p9("update_company",w,"socialLinks"),p9("update_company",w,"pricing"),w.emailTheme!==void 0&&w.emailTheme!==null&&!k(w.emailTheme))throw Error("`emailTheme` must be an object or null when calling `update_company`.");W5("update_company",w,"valueProps"),W5("update_company",w,"testimonials");for(let W of["replyTrackingEnabled","forwardReplies"])if(w[W]!==void 0&&typeof w[W]!=="boolean")throw Error(`\`${W}\` must be a boolean when calling \`update_company\`.`);if(w.replyTrackingDomainMode!==void 0&&w.replyTrackingDomainMode!=="sequenzy"&&w.replyTrackingDomainMode!=="custom")throw Error("`replyTrackingDomainMode` must be `sequenzy` or `custom` when calling `update_company`.");if(typeof w.primaryColor==="string"&&!/^#[0-9a-f]{6}$/i.test(w.primaryColor.trim()))throw Error("`primaryColor` must be a 6-digit hex color such as #f97316 when calling `update_company`.");for(let W of["fromEmail","replyTo"]){let X=w[W];if(typeof X==="string"&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(X.trim()))throw Error(`\`${W}\` must be a valid email address when calling \`update_company\`.`)}return Q}var d9=["openTrackingEnabled","clickTrackingEnabled","strictBotFilteringEnabled","unsubscribeTrackingEnabled","defaultAttributionWindowHours","doubleOptInEnabled","autoUtmEnabled","autoUtmSettings"],o9=["source","medium","campaign","content","term"];function H5(w){let b=new Set(["companyId",...d9]),$=Object.keys(w).filter((W)=>!b.has(W));if($.length>0)throw Error(`\`update_tracking_settings\` accepts only tracking settings. Unsupported field${$.length===1?"":"s"}: ${$.map((W)=>`\`${W}\``).join(", ")}. Reply tracking is set with \`update_company\`.`);let Q={};for(let W of d9)if(w[W]!==void 0)Q[W]=w[W];if(Object.keys(Q).length===0)throw Error(`Provide at least one of ${d9.map((W)=>`\`${W}\``).join(", ")} when calling \`update_tracking_settings\`.`);for(let W of["openTrackingEnabled","clickTrackingEnabled","strictBotFilteringEnabled","unsubscribeTrackingEnabled","doubleOptInEnabled","autoUtmEnabled"])if(w[W]!==void 0&&typeof w[W]!=="boolean")throw Error(`\`${W}\` must be a boolean when calling \`update_tracking_settings\`.`);if(w.defaultAttributionWindowHours!==void 0&&(typeof w.defaultAttributionWindowHours!=="number"||!Number.isInteger(w.defaultAttributionWindowHours)||w.defaultAttributionWindowHours<1||w.defaultAttributionWindowHours>720))throw Error("`defaultAttributionWindowHours` must be a whole number of hours between 1 and 720 when calling `update_tracking_settings`.");if(w.autoUtmSettings!==void 0&&w.autoUtmSettings!==null&&!k(w.autoUtmSettings))throw Error("`autoUtmSettings` must be an object or null when calling `update_tracking_settings`.");if(k(w.autoUtmSettings)){let W=w.autoUtmSettings,X=Object.keys(W).filter((J)=>!o9.includes(J));if(X.length>0)throw Error(`\`autoUtmSettings\` accepts only ${o9.map((J)=>`\`${J}\``).join(", ")}. Unsupported: ${X.map((J)=>`\`${J}\``).join(", ")}.`);for(let J of o9){let Y=W[J];if(Y!==void 0&&Y!==null&&typeof Y!=="string")throw Error(`\`autoUtmSettings.${J}\` must be a string or null when calling \`update_tracking_settings\`.`)}}return Q}var r9={profileKey:"senderProfileId",emailKey:"fromEmail",nameKey:"fromName",addressLabel:"From"},s9={profileKey:"replyProfileId",emailKey:"replyTo",nameKey:"replyToName",addressLabel:"Reply-To"};function e9(w){let{profileKey:b,emailKey:$,nameKey:Q,addressLabel:W}=w.pair,X=w.args[b]!==void 0,J=w.args[$]!==void 0,Y=w.args[Q]!==void 0,G=w.location?`for ${w.location} when calling \`${w.toolName}\``:`when calling \`${w.toolName}\``,H=`\`${b}\` already sets both the ${W} address and the display name, so send it without \`${$}\`${w.nameIsOverride?"":` and \`${Q}\``}.`;if(X&&J){let[z,B]=w.profileFirst?[b,$]:[$,b];throw Error(`Provide either \`${z}\` or \`${B}\` ${G}, not both. ${H}`)}if(X&&Y&&!w.nameIsOverride)throw Error(`\`${Q}\` cannot be combined with \`${b}\` ${G}. ${H}`);if(Y&&!J&&!w.nameIsOverride)throw Error(`\`${Q}\` requires \`${$}\` ${G}. Send \`${Q}\` with the \`${$}\` it names, or send \`${b}\` on its own to use an existing profile's address and name.`)}function Pw(w,b,$){let Q=$?.replyFirst?[s9,r9]:[r9,s9];for(let W of Q)e9({toolName:w,args:b,pair:W})}var z5=["senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName"];function eM(w){return z5.some((b)=>w[b]!==void 0)}function aM(w){if(typeof w.nodeType==="string")return w.nodeType==="action_email";return w.type===void 0||w.type==="email"}function H4(w,b,$){for(let Q of z5){let W=$[Q];if(W!==void 0&&typeof W!=="string")throw Error(`\`${Q}\` must be a string for ${b} when calling \`${w}\`.`)}e9({toolName:w,args:$,pair:r9,location:b,profileFirst:!0,nameIsOverride:!0}),e9({toolName:w,args:$,pair:s9,location:b,profileFirst:!0})}function a9(w,b,$){if(eM($)&&!aM($))throw Error(`Sender identity fields are only supported for email steps at ${b} when calling \`${w}\`.`);H4(w,b,$)}function X5(w,b,$){if(!Array.isArray($))return;$.forEach((Q,W)=>{if(k(Q))H4(w,`${b}[${W}]`,Q)})}function t9(w,b,$){if(!Array.isArray($))return;$.forEach((Q,W)=>{if(k(Q))a9(w,`${b}[${W}]`,Q)})}function wV(w){if(X5("update_sequence","emails",w.emails),X5("update_sequence","steps",w.steps),k(w.insertSteps))t9("update_sequence","insertSteps.steps",w.insertSteps.steps);if(!k(w.branch))return;if(Array.isArray(w.branch.branches))w.branch.branches.forEach(($,Q)=>{if(k($))t9("update_sequence",`branch.branches[${Q}].steps`,$.steps)});t9("update_sequence","branch.elseSteps",w.branch.elseSteps)}function D5(w){K0("update_sequence",w);let b=["listId","tagName","segmentId","stopOnSegmentExit","eventName","propertyFilters","integrationSlug","integrationEventKey","customIntegration","inactiveDays","inactivityBaseline","minCount","timeWindowDays"];if(w.trigger===void 0&&b.some((Q)=>w[Q]!==void 0))throw Error("Provide `trigger` when replacing sequence trigger configuration with `update_sequence`.");if(Pw("update_sequence",w),w.clearEnrollmentFieldPath===!0&&w.enrollmentFieldPath!==void 0)throw Error("Provide either `enrollmentFieldPath` or `clearEnrollmentFieldPath` when calling `update_sequence`, not both.");if(w.clearSendingWindow===!0&&w.sendingWindow!==void 0)throw Error("Provide either `sendingWindow` or `clearSendingWindow` when calling `update_sequence`, not both.");if(w.clearBccEmails===!0&&w.bccEmails!==void 0)throw Error("Provide either `bccEmails` or `clearBccEmails` when calling `update_sequence`, not both.");if(w.branch!==void 0&&w.insertSteps!==void 0)throw Error("Provide either `branch` or `insertSteps` when calling `update_sequence`, not both.");wV(w);let $={...w};if(delete $.clearEnrollmentFieldPath,delete $.clearSendingWindow,delete $.clearBccEmails,w.clearEnrollmentFieldPath===!0)$.enrollmentFieldPath=null;if(w.clearSendingWindow===!0)$.sendingWindow=null;if(w.clearBccEmails===!0)$.bccEmails=null;return $}function bV(w,b){if((b.triggerType??"event")==="event"){if(typeof b.triggerEventName!=="string"||b.triggerEventName.trim().length===0)throw Error(`\`triggerEventName\` is required when calling \`${w}\` with an event goal (the default \`triggerType\`).`);return}if(typeof b.attributePath!=="string"||b.attributePath.trim().length===0)throw Error(`\`attributePath\` is required when calling \`${w}\` with \`triggerType: "attribute_change"\`.`);let Q=b.attributeCondition??"changed",W=typeof b.attributeValue==="string"&&b.attributeValue.trim().length>0,X=typeof b.attributePreviousValue==="string"&&b.attributePreviousValue.trim().length>0;if((Q==="changed_to"||Q==="changed_from_to")&&!W)throw Error(`\`attributeValue\` is required when calling \`${w}\` with \`attributeCondition\` \`changed_to\` or \`changed_from_to\`.`);if(Q==="changed_from_to"&&!X)throw Error(`\`attributePreviousValue\` is required when calling \`${w}\` with \`attributeCondition: "changed_from_to"\`.`)}function B5(w){bV("create_sequence_goal",w)}function L5(w){if(typeof w.triggerEventName==="string"&&w.triggerEventName.trim().length===0)throw Error("`triggerEventName` must be a non-empty string when provided to `update_sequence_goal`.");if(typeof w.attributePath==="string"&&w.attributePath.trim().length===0)throw Error("`attributePath` must be a non-empty string when provided to `update_sequence_goal`.")}function U5(w,b,$){let Q=M(w,b,"nodeId");if(!k(b.changes)||Object.keys(b.changes).length===0)throw Error(`\`changes\` must be a non-empty object for ${$} when calling \`${w}\`.`);let W=M(w,b,"expectedUpdatedAt");return{nodeId:Q,changes:b.changes,expectedUpdatedAt:W}}function A5(w){let b=U5("update_sequence_node",w,"the node update");return{...w.confirmLiveChange!==void 0&&{confirmLiveChange:w.confirmLiveChange},nodeUpdates:[b]}}function K5(w){if(!Array.isArray(w.updates)||w.updates.length===0)throw Error("`updates` must be a non-empty array when calling `update_sequence_nodes`.");let b=new Set,$=w.updates.map((Q,W)=>{if(!k(Q))throw Error(`\`updates[${W}]\` must be an object when calling \`update_sequence_nodes\`.`);let X=U5("update_sequence_nodes",Q,`updates[${W}]`),J=String(X.nodeId);if(b.has(J))throw Error(`\`updates[${W}]\` targets duplicate nodeId '${J}' when calling \`update_sequence_nodes\`.`);return b.add(J),X});return{...w.confirmLiveChange!==void 0&&{confirmLiveChange:w.confirmLiveChange},nodeUpdates:$}}function O5(w){let b=M("edit_sequence_graph",w,"action"),$=M("edit_sequence_graph",w,"graphRevision");if(!new Set(["move_node","delete_node","duplicate_node","replace_edges"]).has(b))throw Error("`action` must be `move_node`, `delete_node`, `duplicate_node`, or `replace_edges` when calling `edit_sequence_graph`.");let W=U(w,"nodeId"),X=U(w,"afterNodeId"),J=U(w,"beforeNodeId"),Y=w.edges;if(b!=="replace_edges"&&!W)throw Error(`\`nodeId\` is required for ${b} when calling \`edit_sequence_graph\`.`);if(b==="replace_edges"&&W)throw Error("`nodeId` is not used with `replace_edges` when calling `edit_sequence_graph`.");let G=b==="move_node"||b==="duplicate_node";if(G&&(X?1:0)+(J?1:0)!==1)throw Error(`Provide exactly one of \`afterNodeId\` or \`beforeNodeId\` for ${b} when calling \`edit_sequence_graph\`.`);if(!G&&(X||J))throw Error(`\`afterNodeId\` and \`beforeNodeId\` are not used with ${b} when calling \`edit_sequence_graph\`.`);if((b==="replace_edges"||b==="delete_node"&&Y!==void 0)&&(!Array.isArray(Y)||Y.length===0))throw Error(`\`edges\` must contain the complete replacement topology for ${b} when calling \`edit_sequence_graph\`.`);if((b==="move_node"||b==="duplicate_node")&&Y!==void 0)throw Error(`\`edges\` is not used with ${b} when calling \`edit_sequence_graph\`.`);let H=Array.isArray(Y)?Y.map((z,B)=>{if(!k(z))throw Error(`\`edges\` item ${B+1} must be an object when calling \`edit_sequence_graph\`.`);let L=M("edit_sequence_graph",z,"sourceNodeId"),F=M("edit_sequence_graph",z,"targetNodeId");if(z.condition!==void 0&&z.condition!==null&&!k(z.condition))throw Error(`\`edges\` item ${B+1} \`condition\` must be an object when calling \`edit_sequence_graph\`.`);return{sourceNodeId:L,targetNodeId:F,...k(z.condition)?{condition:z.condition}:{}}}):void 0;return{...w.confirmStructuralChange!==void 0&&{confirmStructuralChange:w.confirmStructuralChange},graphEdit:{action:b,expectedRevision:$,...W?{nodeId:W}:{},...X?{afterNodeId:X}:{},...J?{beforeNodeId:J}:{},...H?{edges:H}:{}}}}function Z5(w){let b=U(w,"type")??"email";if(!new Set(["email","sms","delay","create_discount","update_subscriber","condition","add_tag","remove_tag","add_to_list","remove_from_list","webhook","logic_wait_for_event","logic_branch"]).has(b))throw Error("`type` is not a supported dashboard sequence step when calling `insert_sequence_step`.");if(b==="logic_wait_for_event"){let J=M("insert_sequence_step",w,"eventName"),Y=w.timeoutDays,G=Y===void 0?7:Y;if(typeof G!=="number"||!Number.isInteger(G)||G<1||G>365)throw Error("`timeoutDays` must be a whole number from 1 to 365 when inserting `logic_wait_for_event` with `insert_sequence_step`.");let H=U(w,"timeoutAction")??"continue";if(H!=="continue"&&H!=="exit")throw Error("`timeoutAction` must be `continue` or `exit` when inserting `logic_wait_for_event` with `insert_sequence_step`.");let z={steps:[{nodeType:"logic_wait_for_event",config:{label:U(w,"label")??`Wait for ${J}`,eventName:J,timeoutDays:G,timeoutAction:H}}]},B=U(w,"afterNodeId");if(B)z.afterNodeId=B;return{...w.confirmStructuralChange!==void 0&&{confirmStructuralChange:w.confirmStructuralChange},insertSteps:z}}if(b==="logic_branch"){let J=M("insert_sequence_step",w,"afterNodeId");if(!Array.isArray(w.branches)||w.branches.length===0)throw Error("`branches` must contain at least one typed condition when inserting `logic_branch` with `insert_sequence_step`.");let Y=new Set(["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"]),G=["id","label","conditionType","tagName","tagId","listId","segmentId","segmentName","eventName","linkUrl","activityScope","fieldName","fieldValue","targetNodeId","steps"],H=w.allowEmptyPaths===!0,z=w.branches.map((F,A)=>{if(!k(F))throw Error(`\`branches[${A}]\` must be an object when calling \`insert_sequence_step\`.`);let j=M("insert_sequence_step",F,"conditionType");if(!Y.has(j))throw Error(`\`branches[${A}].conditionType\` is not supported when calling \`insert_sequence_step\`.`);let q=`branches[${A}]`;if((j==="has_tag"||j==="does_not_have_tag")&&!U(F,"tagId")&&!U(F,"tagName"))throw Error(`\`${q}\` must provide \`tagId\` or \`tagName\` for ${j} when calling \`insert_sequence_step\`.`);if(j==="in_list"&&!U(F,"listId"))throw Error(`\`${q}.listId\` is required for in_list when calling \`insert_sequence_step\`.`);if(j==="in_segment"&&!U(F,"segmentId"))throw Error(`\`${q}.segmentId\` is required for in_segment when calling \`insert_sequence_step\`.`);if(j==="event_received"&&!U(F,"eventName"))throw Error(`\`${q}.eventName\` is required for event_received when calling \`insert_sequence_step\`.`);if(j.startsWith("field_")&&(!U(F,"fieldName")||!U(F,"fieldValue")))throw Error(`\`${q}\` must provide \`fieldName\` and \`fieldValue\` for ${j} when calling \`insert_sequence_step\`.`);if(F.steps!==void 0&&!Array.isArray(F.steps))throw Error(`\`branches[${A}].steps\` must be an array when calling \`insert_sequence_step\`.`);let P=U(F,"targetNodeId"),v=Array.isArray(F.steps)&&F.steps.length>0;if(!P&&!v&&!H)throw Error(`\`branches[${A}]\` must provide \`targetNodeId\` or non-empty \`steps\` when inserting \`logic_branch\` with \`insert_sequence_step\`.`);return Object.fromEntries(G.flatMap((S)=>F[S]===void 0?[]:[[S,F[S]]]))});if(w.elseSteps!==void 0&&!Array.isArray(w.elseSteps))throw Error("`elseSteps` must be an array when calling `insert_sequence_step`.");let B=U(w,"elseTargetNodeId"),L=Array.isArray(w.elseSteps)&&w.elseSteps.length>0;if(!B&&!L&&!H)throw Error("Provide `elseTargetNodeId` or non-empty `elseSteps` when inserting `logic_branch` with `insert_sequence_step`.");return{...w.confirmStructuralChange!==void 0&&{confirmStructuralChange:w.confirmStructuralChange},branch:{afterNodeId:J,...U(w,"label")?{label:U(w,"label")}:{},branches:z,...Array.isArray(w.elseSteps)?{elseSteps:w.elseSteps}:{},...B?{elseTargetNodeId:B}:{},...H?{allowEmptyPaths:!0}:{}}}}if(b==="delay"||b==="create_discount"||b==="update_subscriber"||b==="condition"||b==="add_tag"||b==="remove_tag"||b==="add_to_list"||b==="remove_from_list"||b==="webhook"){let J;if(b==="delay"){J={type:"delay"};for(let H of["delay","delayMs","waitUntil","waitUntilWeekday"])if(w[H]!==void 0)J[H]=w[H];if(J.delay===void 0&&J.delayMs===void 0&&J.waitUntil===void 0&&J.waitUntilWeekday===void 0)throw Error("Provide `delay`, `delayMs`, `waitUntil`, or `waitUntilWeekday` when inserting a delay step.")}else if(b==="create_discount"){J={type:"create_discount"};for(let H of["discount","label","provider","discountType","percentOff","amountOff","currency","duration","durationInMonths","appliesToAllPlans","planIds","codePrefix","maxRedemptions","lockToSubscriber","expiresAt","expiresInHours"])if(w[H]!==void 0)J[H]=w[H]}else if(b==="update_subscriber"){if(!k(w.config))throw Error("`config` is required when inserting an update_subscriber step.");J={type:"update_subscriber",nodeType:"action_update_attributes",config:w.config}}else if(b==="webhook"){let H=U(w,"method")??"POST";if(!["POST","GET","PUT","PATCH","DELETE"].includes(H))throw Error("`method` must be one of POST, GET, PUT, PATCH, or DELETE when inserting a webhook step.");if(w.headers!==void 0&&(!k(w.headers)||Object.values(w.headers).some((F)=>typeof F!=="string")))throw Error("`headers` must be an object with string values when inserting a webhook step.");let z=U(w,"onError");if(z&&!["continue","exit","fail"].includes(z))throw Error("`onError` must be `continue`, `exit`, or `fail` when inserting a webhook step.");if(w.body!==void 0&&typeof w.body!=="string")throw Error("`body` must be a JSON string when inserting a webhook step.");if(w.resultKey!==void 0&&typeof w.resultKey!=="string")throw Error("`resultKey` must be a string when inserting a webhook step.");let B=U(w,"body"),L=U(w,"resultKey");J={type:"webhook",nodeType:"action_webhook",config:{label:U(w,"label")??"Webhook",url:M("insert_sequence_step",w,"url"),method:H,...w.headers!==void 0?{headers:w.headers}:{},...B?{body:B}:{},...L?{resultKey:L}:{},...z?{onError:z}:{}}}}else if(b==="condition"){let H=M("insert_sequence_step",w,"conditionType");if(!new Set(["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"]).has(H))throw Error("`conditionType` is not supported for condition steps.");if((H==="has_tag"||H==="does_not_have_tag")&&!U(w,"tagId")&&!U(w,"tagName"))throw Error("Provide `tagId` or `tagName` for this condition step.");if(H==="in_list"&&!U(w,"listId"))throw Error("`listId` is required for an in_list condition.");if(H==="in_segment"&&!U(w,"segmentId"))throw Error("`segmentId` is required for an in_segment condition.");if(H==="event_received"&&!U(w,"eventName"))throw Error("`eventName` is required for an event_received condition.");if(H.startsWith("field_")&&(!U(w,"fieldName")||!U(w,"fieldValue")))throw Error("`fieldName` and `fieldValue` are required for field conditions.");let B={label:U(w,"label")??"Condition",conditionType:H};for(let L of["tagId","tagName","listId","segmentId","segmentName","eventName","linkUrl","activityScope","fieldName","fieldValue"])if(w[L]!==void 0)B[L]=w[L];J={type:"condition",nodeType:"logic_condition",config:B}}else{let H=b==="add_tag"||b==="remove_tag",z=b==="add_tag"?"action_add_tag":b==="remove_tag"?"action_remove_tag":b==="add_to_list"?"action_add_to_list":"action_remove_from_list",B={label:U(w,"label")??(b==="add_tag"?"Add Tag":b==="remove_tag"?"Remove Tag":b==="add_to_list"?"Add to List":"Remove from List")};if(H){let L=U(w,"tagId"),F=U(w,"tagName");if(!L&&!F)throw Error("Provide `tagId` or `tagName` when inserting a tag action.");if(L)B.tagId=L;if(F)B.tagName=F}else{B.listId=M("insert_sequence_step",w,"listId");let L=U(w,"listName");if(L)B.listName=L}J={nodeType:z,config:B}}for(let H of["delay","delayMs","waitUntil","waitUntilWeekday"])if(b!=="delay"&&w[H]!==void 0)J[H]=w[H];let Y={steps:[J]},G=U(w,"afterNodeId");if(G)Y.afterNodeId=G;return{...w.confirmStructuralChange!==void 0&&{confirmStructuralChange:w.confirmStructuralChange},insertSteps:Y}}let Q=b==="sms",W;if(Q){a9("insert_sequence_step","SMS step",w);let J=U(w,"text"),Y=Array.isArray(w.blocks)&&w.blocks.length>0;if(J===void 0&&!Y)throw Error("Provide `text` (or `blocks`) when inserting an SMS step with `insert_sequence_step`.");W={type:"sms"};for(let G of["text","blocks","imageUrls","label","name","ineligibleAction","delay","delayMs","waitUntil","waitUntilWeekday"])if(w[G]!==void 0)W[G]=w[G]}else{h1("insert_sequence_step",w,{requireContent:!0}),H4("insert_sequence_step","email step",w),W={subject:M("insert_sequence_step",w,"subject")};for(let J of["name","previewText","html","blocks","delay","delayMs","waitUntil","waitUntilWeekday","senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName","isTransactional","ccEmails","bccEmails","attachments"])if(w[J]!==void 0)W[J]=w[J]}let X={steps:[W]};if(w.afterNodeId!==void 0)X.afterNodeId=w.afterNodeId;return{...w.confirmStructuralChange!==void 0&&{confirmStructuralChange:w.confirmStructuralChange},insertSteps:X}}function F5(w,b){let $=w[b];if($===void 0)return[];if(!Array.isArray($))throw Error(`\`${b}\` must be an array when calling \`cancel_sequence_enrollments\`.`);let Q=$.map((W)=>typeof W==="string"?W.trim():"").filter((W)=>W.length>0);if($.some((W)=>typeof W!=="string")||Q.length===0)throw Error(`\`${b}\` must contain at least one non-empty string when calling \`cancel_sequence_enrollments\`.`);return Q}function j5(w){let b=U(w,"subscriberId"),$=F5(w,"subscriberIds"),Q=F5(w,"fieldValues");if(w.cancelAll!==void 0&&typeof w.cancelAll!=="boolean")throw Error("`cancelAll` must be a boolean when calling `cancel_sequence_enrollments`.");let W=w.cancelAll===!0;if((b!==void 0?1:0)+($.length>0?1:0)+(Q.length>0?1:0)+(W?1:0)!==1)throw Error("Provide exactly one target when calling `cancel_sequence_enrollments`: `cancelAll`, `subscriberId`, `subscriberIds`, or `fieldValues`.");let J=U(w,"fieldPath"),Y=U(w,"reason");return{...W&&{cancelAll:!0},...b!==void 0&&{subscriberId:b},...$.length>0&&{subscriberIds:$},...J!==void 0&&{fieldPath:J},...Q.length>0&&{fieldValues:Q},...typeof w.dryRun==="boolean"&&{dryRun:w.dryRun},...Y!==void 0&&{reason:Y}}}function M5(w){h1("create_campaign",w),K0("create_campaign",w);let b=U(w,"prompt")!==void 0,$=w.html!==void 0,Q=w.blocks!==void 0,W=w.templateId!==void 0;if(w.prompt!==void 0&&!b)throw Error("`prompt` cannot be empty when calling `create_campaign`.");if(b&&($||Q||W))throw Error("Provide either `prompt`, `html`, `blocks`, or `templateId` when calling `create_campaign`, not multiple content sources.");if(!b&&(w.style!==void 0||w.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_campaign`.");if(!b&&U(w,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_campaign`.")}function V5(w){h1("create_template",w),K0("create_template",w);let b=U(w,"prompt")!==void 0,$=[b,w.html!==void 0,w.blocks!==void 0].filter(Boolean).length;if(w.prompt!==void 0&&!b)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(!b&&(w.style!==void 0||w.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_template`.");if(!b&&U(w,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_template`.")}function P5(w){if(U(w,"scheduledAt")===void 0)throw Error("`scheduledAt` is required when calling `schedule_campaign`.");if(w.targetLists!==void 0&&!k(w.targetLists))throw Error("`targetLists` must be an object when calling `schedule_campaign`.");if(w.sendTimeOptimization!==void 0){if(typeof w.sendTimeOptimization!=="boolean")throw Error("`sendTimeOptimization` must be a boolean when calling `schedule_campaign`.")}if(w.spreadOverHours!==void 0){if(typeof w.spreadOverHours!=="number"||!Number.isInteger(w.spreadOverHours)||w.spreadOverHours<1||w.spreadOverHours>72)throw Error("`spreadOverHours` must be an integer between 1 and 72 when calling `schedule_campaign`.")}if(w.recurringInterval!==void 0&&w.recurringInterval!=="weekly"&&w.recurringInterval!=="monthly")throw Error("`recurringInterval` must be 'weekly' or 'monthly' when calling `schedule_campaign`.")}function z4(w,b,$){let Q=new Set(["companyId","landingPageId","name","slug","content"]),W=Object.keys(b).filter((X)=>!Q.has(X));if(W.length>0)throw Error(`\`${w}\` accepts only \`name\`, \`slug\`, and \`content\` update fields. Unsupported field${W.length===1?"":"s"}: ${W.map((X)=>`\`${X}\``).join(", ")}.`);if($.requireUpdate&&b.name===void 0&&b.slug===void 0&&b.content===void 0)throw Error(`Provide at least one of \`name\`, \`slug\`, or \`content\` when calling \`${w}\`.`);return{...b.name!==void 0&&{name:b.name},...b.slug!==void 0&&{slug:b.slug},...b.content!==void 0&&{content:b.content}}}function q5(w){let b=new Set(["companyId","domain","verify"]),$=Object.keys(w).filter((Q)=>!b.has(Q));if($.length>0)throw Error(`\`update_landing_page_domain_settings\` accepts only \`domain\` and \`verify\`. Unsupported field${$.length===1?"":"s"}: ${$.map((Q)=>`\`${Q}\``).join(", ")}.`);if(w.domain===void 0&&w.verify!==!0)throw Error("Provide `domain` or `verify: true` when calling `update_landing_page_domain_settings`.");return{...w.domain!==void 0&&{domain:w.domain},...typeof w.verify==="boolean"&&{verify:w.verify}}}function I5(w){h1("create_transactional_email",w);let b=U(w,"prompt")!==void 0,$=w.html!==void 0,Q=w.blocks!==void 0;if(w.prompt!==void 0&&!b)throw Error("`prompt` cannot be empty when calling `create_transactional_email`.");if(b&&($||Q))throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`, not multiple content sources.");if(!b&&(w.style!==void 0||w.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_transactional_email`.");if(!b&&!$&&!Q)throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`.");if(!b&&U(w,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_transactional_email`.")}var qw={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},$V={type:"object",description:"Config for advanced nodeType steps. Required fields depend on nodeType: action_add_tag and action_remove_tag need tagId or tagName; action_add_to_list and action_remove_from_list need listId; action_update_attributes uses the Update Subscriber fields (firstName, lastName, status, customAttributeUpdates) and may use trigger-event merge tags; logic_wait_for_event needs eventName plus optional timeoutDays and timeoutAction; logic_condition needs conditionType plus that condition's resource field; action_webhook needs an HTTPS url plus optional method, headers, body, resultKey, and onError; logic_delay uses delayDays/delayHours/delayMinutes. Fields that do not apply to the node type are dropped.",properties:{...qw.properties,tagId:{type:"string",description:"action_add_tag / action_remove_tag: tag ID. Pass a name in tagName instead, because tag actions resolve tagId by ID only. has_tag / does_not_have_tag also accept a tag name here. Missing tag definitions are created automatically."},tagName:{type:"string",description:"action_add_tag / action_remove_tag / has_tag / does_not_have_tag: tag name. Use instead of tagId when you only know the name."},listId:{type:"string",description:"action_add_to_list / action_remove_from_list / in_list: list ID. It must match an existing list in this company; listName is filled in for you."},listName:{type:"string",description:"Optional cached list display name for list actions."},eventName:{type:"string",description:"logic_wait_for_event and event_received conditions: event to wait for or check, for example email.replied."},timeoutDays:{type:"number",description:"logic_wait_for_event: maximum wait in whole days from 1 to 365. Defaults to 7."},timeoutAction:{type:"string",enum:["continue","exit"],description:"logic_wait_for_event: continue to the next node or exit the sequence when the timeout is reached. Defaults to continue."},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:"logic_condition: condition evaluated before continuing. has_phone and sms_subscribed need no resource fields."},segmentId:{type:"string",description:"logic_condition: segment ID for in_segment."},segmentName:{type:"string",description:"Optional cached segment display name."},linkUrl:{type:"string",description:"logic_condition: optional URL substring for link_clicked. Omit to match any tracked click."},activityScope:{type:"string",enum:["ever","this_sequence","previous_email"],description:"logic_condition: scope for event_received and link_clicked. Use this_sequence to restrict activity to the current enrollment."},fieldName:{type:"string",description:"logic_condition: subscriber attribute name/path for field comparisons."},fieldValue:{type:"string",description:"logic_condition: comparison value for field comparisons."},url:{type:"string",description:"action_webhook: destination HTTPS URL called when a subscriber reaches this step. Supports merge tags like {{email}} and {{event.order_id}} resolved at execution time."},method:{type:"string",enum:["POST","GET","PUT","PATCH","DELETE"],description:"action_webhook: HTTP method. Defaults to POST."},headers:{type:"object",description:"action_webhook: optional string-valued request headers. Values support merge tags. Secret values are redacted on sequence reads.",additionalProperties:{type:"string"}},body:{type:"string",description:'action_webhook: optional JSON body template for POST/PUT/PATCH. Must be valid JSON as written, with merge tags inside quoted string values ({"email": "{{email}}"}); a tag in a bare value position is rejected. Tags are resolved at execution time; when omitted, the default payload with subscriber and sequence context is sent.'},resultKey:{type:"string",description:"action_webhook: when set, the HTTP response is saved and later email steps can reference it via {{webhooks.KEY.data.field}} merge tags. Must start with a letter; letters, numbers, underscores; max 64 chars."},onError:{type:"string",enum:["continue","exit","fail"],description:"action_webhook: behavior when the request fails. continue proceeds to the next step, exit ends the sequence for the subscriber, fail marks the enrollment failed (default)."},delayDays:{type:"number",description:"logic_delay: whole days to wait."},delayHours:{type:"number",description:"logic_delay: hours to wait."},delayMinutes:{type:"number",description:"logic_delay: minutes to wait."}},additionalProperties:!0},Nb={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:"Reply-To display name override for this step. Requires replyTo; omit it when using replyProfileId, which already carries its own display name."}},Tb={type:"object",description:"A typed step to create inside a sequence path, including email, SMS, delay, discount, subscriber actions, conditions, waits, and webhooks.",properties:{type:{type:"string",enum:["email","sms","delay","create_discount","discount","update_subscriber","condition","webhook"],description:"Sequence path step type. Omit for email steps; use delay for fixed/date waits or update_subscriber for action_update_attributes. For an event gate, use nodeType:'logic_wait_for_event' with an explicit config object."},nodeType:{type:"string",enum:["logic_delay","action_email","action_sms","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. Tag, list, subscriber-update, wait, condition, and webhook node types carry their fields in config, for example nodeType:'action_add_tag' with config:{ tagName:'newsletter-confirmed' }. SMS steps still use the step-level text/imageUrls/ineligibleAction, discount steps the step-level discount fields, and delays the step-level delay/delayMs/waitUntil."},config:$V,subject:{type:"string",description:"Email subject. Required for email steps."},previewText:{type:"string",description:"Email preview text."},blocks:{type:"array",description:Kw,items:{type:"object"}},html:{type:"string",description:"HTML content for email steps. Stored as one raw HTML block. Use this for imported provider HTML."},isTransactional:{type:"boolean",description:"Email only: omit the marketing unsubscribe footer."},ccEmails:{type:"array",items:{type:"string"},description:"Email only: addresses CC'd on this step."},bccEmails:{type:"array",items:{type:"string"},description:"Email only: addresses BCC'd on this step in addition to sequence BCC."},attachments:{type:"array",items:{type:"object",properties:{filename:{type:"string"},path:{type:"string"}},required:["filename","path"]},description:"Email only: URL-backed file attachments (max 10, 7MB total per email). path may be a public HTTPS URL or an {{event.*}} URL template resolved from the enrollment event at send time."},text:{type:"string",description:"SMS only: plain-text message body."},imageUrls:{type:"array",items:{type:"string"},description:"SMS only: up to two public MMS image URLs."},ineligibleAction:{type:"string",enum:["skip","exit"],description:"SMS only: behavior when the contact cannot receive SMS."},delay:jw,delayMs:{type:"number",description:"Delay in milliseconds. Useful for standalone type:'delay' steps."},waitUntil:Ow,waitUntilWeekday:Zw,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:"Reply-To display name override for this email step. Requires replyTo; omit it when using replyProfileId, which already carries its own display name."},discount:{type:"object",description:`Discount configuration for create_discount steps. Same shape as create_sequence steps.${w4}`,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},wQ={type:"object",properties:{id:{type:"string",description:"Optional stable path ID. Defaults to branch-0, branch-1, and so on. The value 'else' is reserved."},label:{type:"string",description:"Display label, for example 'Replied in this sequence'."},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 for this path. has_phone and sms_subscribed need no resource fields."},tagName:{type:"string",description:"Tag name for has_tag and does_not_have_tag. This can be used instead of tagId."},tagId:{type:"string",description:"Tag ID or tag name for has_tag and does_not_have_tag."},listId:{type:"string",description:"List ID for in_list."},segmentId:{type:"string",description:"Segment ID for in_segment."},segmentName:{type:"string",description:"Optional display name for in_segment."},eventName:{type:"string",description:"Event name for event_received, for example email.replied."},linkUrl:{type:"string",description:"Optional URL substring for link_clicked. Omit to match any tracked click."},activityScope:{type:"string",enum:["ever","this_sequence","previous_email"],description:"Scope for event_received and link_clicked. Use this_sequence to restrict activity to the current enrollment."},fieldName:{type:"string",description:"Subscriber attribute name/path for field conditions."},fieldValue:{type:"string",description:"Comparison value for field conditions."},targetNodeId:{type:"string",description:"Optional existing node to route this branch path to. Use a node ID from get_sequence, including the sequence completion node when this path should stop. If steps are also provided, they run before this target."},steps:{type:"array",description:"Optional new steps for this path. When targetNodeId is also set, the last new step connects to that existing node.",items:Tb}},required:["conditionType"],additionalProperties:!1};function E5(w){if(!w||typeof w!=="object")return null;let b=w;if(b.success!==!1)return null;if(typeof b.error==="string")return Error(b.error);if(b.error&&typeof b.error==="object"&&typeof b.error.message==="string")return Error(b.error.message);if(typeof b.message==="string")return Error(b.message);return Error("The tool returned an unsuccessful response.")}var bQ=1000,$Q=1000,QQ=bQ*$Q-1;function WQ(w){return w.trim().toLowerCase().replace(/\s+/g,"-")}function QV(w,b){let $=U(b,"attribute"),Q=U(b,"attributeValue"),W=l(w,b,"attributeOperator",$4);if(!$){if(Q!==void 0||W!==void 0)throw Error(`\`attributeValue\` and \`attributeOperator\` require \`attribute\` when calling \`${w}\`.`);return{}}let X=W??"is",J;if(Q!==void 0)J=`${$}:${Q}`;else if($.includes(":"))J=$;else if(X==="is_not_empty")J=`${$}:`;else throw Error(`Provide \`attributeValue\` (or use \`attribute: "name:value"\`) when \`attributeOperator\` is \`${X}\` in \`${w}\`. Only \`is_not_empty\` may omit a value.`);return{attribute:J,attributeOperator:X}}function WV(w){let b=new URLSearchParams;if(typeof w.query==="string"&&w.query.trim()!=="")b.set("query",w.query.trim());if(Array.isArray(w.tags)&&w.tags.length>0)b.set("tags",w.tags.filter(($)=>typeof $==="string"&&$.trim()!=="").join(","));if(typeof w.list==="string"&&w.list.trim()!=="")b.set("list",w.list.trim());if(typeof w.listId==="string"&&w.listId.trim()!=="")b.set("listId",w.listId.trim());if(typeof w.listName==="string"&&w.listName.trim()!=="")b.set("listName",w.listName.trim());if(typeof w.segmentId==="string"&&w.segmentId.trim()!=="")b.set("segmentId",w.segmentId);if(typeof w.status==="string"&&w.status.trim()!=="")b.set("status",w.status.trim());if(w.attribute){if(b.set("attribute",w.attribute),w.attributeOperator)b.set("attributeOperator",w.attributeOperator)}if(w.cursor)b.set("cursor",w.cursor);else b.set("page",String(w.page));if(b.set("limit",String(w.pageSize)),w.includeTotal===!1)b.set("includeTotal","false");return b}async function R5(w,b){let Q=v5("search_subscribers",w,"limit"),W=U(w,"cursor"),X=W?XV("search_subscribers",w):JV("search_subscribers",w,Q),J=Q===void 0?void 0:X+Q,Y=Math.min(bQ,Math.max(1,J??bQ)),G=QV("search_subscribers",w),H=[],z=1,B=W,L,F=null,A=0,j=!1,q=!1;while(!0){let _=J===void 0?void 0:J-H.length,S1=B?Math.min(Y,Math.max(1,_??Y)):Y,l1=WV({query:w.query,tags:w.tags,list:w.list,listId:w.listId,listName:w.listName,segmentId:w.segmentId,status:w.status,attribute:G.attribute,attributeOperator:G.attributeOperator,page:z,pageSize:S1,cursor:B}),v1=await D("GET",`/api/v1/subscribers?${l1.toString()}`,void 0,b);if(A===0)F=v1.pagination?.total??null;A+=1,H.push(...v1.subscribers??[]);let r0=(v1.subscribers??[]).length,g1=v1.pagination?.nextCursor??void 0;L=g1;let Tw=J!==void 0&&H.length>=J,Z0;if(g1)Z0=!1;else if(v1.pagination?.hasMore!==void 0)Z0=!v1.pagination.hasMore;else if(v1.pagination?.totalPages!==void 0&&v1.pagination.totalPages!==null)Z0=z>=v1.pagination.totalPages;else Z0=r0<S1;if(Z0||r0===0&&!g1){j=!0;break}if(Tw)break;if(A>=$Q){q=!0;break}if(g1)B=g1;else if(B)break;else z+=1}if(q&&(H.length<X||H.length===X&&L===void 0))throw Error(`Could not reach offset ${X} within ${$Q} requests because too few matches were returned per page. Start without \`offset\` and follow \`pagination.nextCursor\` instead.`);if(F===null&&j&&!W)F=H.length;let P=H.slice(X,J),v=j?!1:F!==null?X+P.length<F:!j||H.length>X+P.length,S=L!==void 0&&H.length===X+P.length,u=X+P.length;return{success:!0,subscribers:P,pagination:{page:Q===void 0?1:Math.floor(X/Q)+1,limit:Q??Y,offset:X,total:F,totalPages:F===null?null:Math.ceil(F/(Q??Y)),fetchedPages:A,hasMore:v,nextOffset:v&&!W&&u<=QQ?u:null,nextCursor:v&&S?L??null:null},returned:P.length,truncated:v}}function XV(w,b){if(b.offset!==void 0||b.page!==void 0)throw Error(`\`cursor\` cannot be combined with \`offset\` or \`page\` when calling \`${w}\`. Keep following \`pagination.nextCursor\` instead.`);return 0}function JV(w,b,$){let Q=S5(w,b,"offset"),W=v5(w,b,"page");if(Q!==void 0&&W!==void 0)throw Error(`Provide either \`offset\` or \`page\` when calling \`${w}\`, not both.`);if(W!==void 0){if($===void 0)throw Error(`\`page\` requires \`limit\` when calling \`${w}\` so the page size is defined. Omit both to fetch every match in one call.`);return N5(w,(W-1)*$)}return N5(w,Q??0)}function N5(w,b){if(b>QQ)throw Error(`\`offset\` must be ${QQ} or less when calling \`${w}\`. Use \`cursor\` to continue beyond that point.`);return b}function S5(w,b,$){let Q=b[$];if(Q===void 0||Q===null)return;if(typeof Q!=="number"||!Number.isInteger(Q)||Q<0)throw Error(`\`${$}\` must be a non-negative integer when calling \`${w}\`.`);return Q}function v5(w,b,$){let Q=S5(w,b,$);if(Q!==void 0&&Q<1)throw Error(`\`${$}\` must be 1 or greater when calling \`${w}\`.`);return Q}function XQ(w){let b=typeof w.email==="string"&&w.email.trim()!==""?w.email.trim():void 0,$=typeof w.externalId==="string"&&w.externalId.trim()!==""?w.externalId.trim():void 0;return{...b?{email:b}:{},...$?{externalId:$}:{}}}function a1(w,b){let $=XQ(b);if(!$.email&&!$.externalId)throw Error(`Provide either \`email\` or \`externalId\` when calling \`${w}\`.`);return $}function D4(w,b){let $=new URLSearchParams;if(b?.includeMachineEngagement)$.set("includeMachineEngagement","true");let Q=$.toString(),W=Q?`?${Q}`:"";if(w.email)return`/api/v1/subscribers/${encodeURIComponent(w.email)}${W}`;return $.set("externalId",String(w.externalId)),`/api/v1/subscribers/external?${$.toString()}`}function JQ(w){if(w.email)return`/api/v1/subscribers/${encodeURIComponent(w.email)}/notes`;let b=new URLSearchParams;return b.set("externalId",String(w.externalId)),`/api/v1/subscribers/external/notes?${b.toString()}`}async function Rb(w,b,$){return D("GET",D4(w,$),void 0,b)}function l(w,b,$,Q){let W=U(b,$);if(W===void 0)return;if(!Q.includes(W))throw Error(`\`${$}\` must be one of ${Q.join(", ")} when calling \`${w}\`.`);return W}function Sb(w,b,$,Q){let W=M(w,b,$);if(!Q.includes(W))throw Error(`\`${$}\` must be one of ${Q.join(", ")} when calling \`${w}\`.`);return W}function Q1(w,b,$,Q,W){let X=b[$];if(X===void 0)return;if(typeof X!=="number"||!Number.isInteger(X)||X<Q||X>W)throw Error(`\`${$}\` must be an integer between ${Q} and ${W} when calling \`${w}\`.`);return X}function YV(w,b){let $=[],Q=l(w,b,"eventType",Ib);if(Q)$.push(Q);if(b.eventTypes!==void 0){if(!Array.isArray(b.eventTypes))throw Error(`\`eventTypes\` must be an array when calling \`${w}\`.`);b.eventTypes.forEach((W,X)=>{if(typeof W!=="string")throw Error(`\`eventTypes\` item ${X+1} must be a string when calling \`${w}\`.`);let J=W.trim();if(!Ib.includes(J))throw Error(`\`eventTypes\` item ${X+1} must be one of ${Ib.join(", ")} when calling \`${w}\`.`);$.push(J)})}return[...new Set($)]}function YQ(w,b){let $=new URLSearchParams,Q=YV(w,b);if(Q.length>0)$.set("eventTypes",Q.join(","));let W=l(w,b,"period",["1h","24h","7d","30d","90d"]);if(W)$.set("period",W);let X=U(b,"start");if(X)$.set("start",X);let J=U(b,"end");if(J)$.set("end",J);let Y=Q1(w,b,"page",1,1e6);if(Y!==void 0)$.set("page",String(Y));let G=Q1(w,b,"limit",1,500);if(G!==void 0)$.set("limit",String(G));if(b.includeMachineEngagement===!0)$.set("includeMachineEngagement","true");return $}function GQ(w,b){if(b.events===void 0)return;if(!Array.isArray(b.events))throw Error(`\`events\` must be an array when calling \`${w}\`.`);let $=b.events.map((Q,W)=>{if(typeof Q!=="string"||!Vw.includes(Q))throw Error(`\`events\` item ${W+1} must be one of ${Vw.join(", ")} when calling \`${w}\`.`);return Q});if($.length===0)throw Error(`\`events\` must include at least one event type when calling \`${w}\`.`);return $}function HQ(w,b){if(!Array.isArray(b.emails))throw Error(`\`emails\` must be an array when calling \`${w}\`.`);let $=[];if(b.emails.forEach((Q,W)=>{if(typeof Q!=="string")throw Error(`\`emails\` item ${W+1} must be a string when calling \`${w}\`.`);let X=Q.trim();if(X.length>0)$.push(X)}),$.length===0)throw Error(`\`emails\` must include at least one email address when calling \`${w}\`.`);if($.length>u9)throw Error(`\`emails\` must include no more than ${u9} email addresses when calling \`${w}\`. Split larger batches into multiple calls.`);return $}function T5(w,b,$,Q){let W=b[$];if(W===void 0)return;if(!Array.isArray(W))throw Error(`\`${$}\` must be an array when calling \`${w}\`.`);let X=[];if(W.forEach((J,Y)=>{if(typeof J!=="string")throw Error(`\`${$}\` item ${Y+1} must be a string when calling \`${w}\`.`);let G=J.trim();if(G.length>0)X.push(G)}),X.length===0)throw Error(`\`${$}\` must include at least one ${Q} when calling \`${w}\`.`);return X}function C5(w){let $=T5("enroll_subscribers_in_sequence",w,"emails","email address"),Q=T5("enroll_subscribers_in_sequence",w,"subscriberIds","subscriber ID"),W=($?.length??0)+(Q?.length??0);if(W===0)throw Error("Provide `emails` or `subscriberIds` when calling `enroll_subscribers_in_sequence`.");if(W>c9)throw Error(`\`emails\` and \`subscriberIds\` must include no more than ${c9} total targets when calling \`enroll_subscribers_in_sequence\`. Split larger batches into multiple calls.`);let X=U(w,"targetNodeId");return{...$!==void 0&&{emails:$},...Q!==void 0&&{subscriberIds:Q},...X!==void 0&&{targetNodeId:X}}}import{readFileSync as GV,statSync as HV}from"node:fs";import{basename as zV}from"node:path";var DV={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 BV(w){let b=w.split(".").pop()?.toLowerCase()??"";return DV[b]??null}var LV=104857600;async function k5(w,b){if(!Cb())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 $=BV(w);if(!$)throw Error("Unsupported file type. Use PDF, ePub, ZIP, image, audio, video, or text files.");let Q=HV(w).size;if(Q>LV)throw Error(`File is too large (${Math.round(Q/1048576)}MB). Delivery files must be 100MB or smaller.`);let W=GV(w),X=await D("POST","/api/v1/products/delivery/upload-url",{filename:zV(w),contentType:$,fileSizeBytes:Q},b),J=await fetch(X.uploadUrl,{method:"PUT",headers:{"Content-Type":$},body:W});if(!J.ok)throw Error(`File upload failed (${J.status})`);return{url:X.publicUrl,fileName:X.fileName,fileSizeBytes:Q,mimeType:$}}async function B4(w){let b=U(w,"companyId");if(b)return b;let $=h0();if($)return $;try{return(await D("GET","/api/v1/account")).currentCompanyId??void 0}catch{return}}async function vb(w,b){let $=await B4(b);if(!$)throw Error(`A company is required when calling \`${w}\`. Call \`get_account\`, then \`select_company\`, or pass \`companyId\` explicitly.`);return $}function Ew(w,b){if(!k(w)||!b)return w;return{...w,url:b}}function _5(w,b){if(!k(w))return w;return{...w,...b.campaign!==void 0&&{url:b.campaign},...b.campaignPreview!==void 0&&{previewUrl:b.campaignPreview}}}function Iw(w,b,$){if(!Array.isArray(w)||!b)return w;return w.map((Q)=>{if(!k(Q))return Q;let W=U(Q,"id");if(!W)return Q;let X=F0({companyId:b,...$==="campaign"&&{campaignId:W},...$==="landingPage"&&{landingPageId:W},...$==="sequence"&&{sequenceId:W},...$==="template"&&{emailId:W},...$==="transactional"&&{transactionalId:W},...$==="emailSend"&&{emailSendId:W}});if($==="campaign")return _5(Q,X.urls);let J=$==="sequence"?X.urls.sequence:$==="landingPage"?X.urls.landingPage:$==="template"?X.urls.email:$==="transactional"?X.urls.transactionalEmail:X.urls.emailSend;return Ew(Q,J)})}function FV(w){if(!Array.isArray(w))return w;return w.map((b)=>{if(!k(b))return b;let $=U(b,"id");if(!$)return b;let Q=F0({companyId:$});return{...b,url:Q.urls.dashboard,settingsUrl:Q.urls.settings}})}var zQ=new Set(["get_account","select_company","create_company","get_company","update_company","list_campaigns","get_campaign","get_email_send","list_email_sends","create_campaign","update_campaign","schedule_campaign","unschedule_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","duplicate_landing_page","delete_landing_page","list_sequences","get_sequence","send_sequence_test_email","create_sequence","generate_sequence","update_sequence","update_sequence_node","update_sequence_nodes","edit_sequence_graph","insert_sequence_step","enable_sequence","disable_sequence","pause_sequence_enrollments","resume_sequence_enrollments","cancel_sequence_enrollments","list_ab_tests","get_ab_test","get_ab_test_stats","update_ab_test_variant","update_ab_test","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 x5(w,b,$){if(!k($)||!zQ.has(w))return $;let Q=k($.company)?$.company:void 0,X=U($,"selectedCompanyId")??U($,"currentCompanyId")??U($,"companyId")??(Q?U(Q,"id"):void 0)??(Q?U(Q,"companyId"):void 0)??await B4(b);if(!X)return $;let J=k($.campaign)?$.campaign:void 0,Y=k($.sequence)?$.sequence:void 0,G=k($.landingPage)?$.landingPage:void 0,H=k($.template)?$.template:void 0,z=k($.transactional)&&!Array.isArray($.transactional)?$.transactional:void 0,B={companyId:X,campaignId:U(b,"campaignId")??U($,"campaignId")??(J?U(J,"id"):void 0),landingPageId:U(b,"landingPageId")??U($,"landingPageId")??(G?U(G,"id"):void 0),sequenceId:U(b,"sequenceId")??U($,"sequenceId")??(Y?U(Y,"id"):void 0),emailId:U($,"templateId")??(H?U(H,"id"):void 0)??(z?U(z,"emailId"):void 0)??U(b,"templateId"),transactionalId:U(b,"transactionalId")??(z?U(z,"id"):void 0)??U(b,"idOrSlug"),emailSendId:U(b,"emailSendId")??U($,"emailSendId")??(k($.emailSend)?U($.emailSend,"id"):void 0),status:U(b,"status")},L=F0(B),F=Q?F0({companyId:X}):void 0;return{...$,...Array.isArray($.companies)&&{companies:FV($.companies)},...Array.isArray($.campaigns)&&{campaigns:Iw($.campaigns,X,"campaign")},...Array.isArray($.landingPages)&&{landingPages:Iw($.landingPages,X,"landingPage")},...Array.isArray($.sequences)&&{sequences:Iw($.sequences,X,"sequence")},...Array.isArray($.templates)&&{templates:Iw($.templates,X,"template")},...Array.isArray($.transactional)&&{transactional:Iw($.transactional,X,"transactional")},...Array.isArray($.emailSends)&&{emailSends:Iw($.emailSends,X,"emailSend")},...Q&&F!==void 0&&{company:{...Q,url:F.urls.dashboard,settingsUrl:F.urls.settings}},...J&&L.urls.campaign!==void 0&&{campaign:_5(J,L.urls)},...Y&&L.urls.sequence!==void 0&&{sequence:Ew(Y,L.urls.sequence)},...G&&L.urls.landingPage!==void 0&&{landingPage:Ew(G,L.urls.landingPage)},...H&&L.urls.email!==void 0&&{template:Ew(H,L.urls.email)},...z&&L.urls.transactionalEmail!==void 0&&{transactional:Ew(z,L.urls.transactionalEmail)},...k($.emailSend)&&L.urls.emailSend!==void 0&&{emailSend:Ew($.emailSend,L.urls.emailSend)},appUrls:L.urls}}import{readFileSync as UV,statSync as AV}from"node:fs";import{basename as KV,extname as y5}from"node:path";var BQ=5242880,OV=Math.ceil(BQ/3)*4,ZV=Math.ceil(OV*1.05)+256,f5={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"},jV=new Set(Object.values(f5));function DQ(w){return w?.split(";")[0]?.trim().toLowerCase()||void 0}function MV(w){return f5[y5(w).toLowerCase()]}function VV(w){let b=y5(w);return(b?w.slice(0,-b.length):w).replace(/[-_]+/g," ").trim()||"Image"}function PV(w){if(w.length>ZV)throw Error("Image assets must be 5MB or smaller.")}function qV(w){let b=0,$=0;for(let W=0;W<w.length;W+=1){let X=w.charCodeAt(W);if(X===9||X===10||X===11||X===12||X===13||X===32)continue;b+=1,$=X===61?$+1:0}if(Math.floor(b*3/4)-Math.min($,2)>BQ)throw Error("Image assets must be 5MB or smaller.")}function IV(w){PV(w);let b=w.trim(),$=/^data:([^;,]+);base64,([\s\S]+)$/i.exec(b),Q=$?.[2]??b;qV(Q);let W=Q.replace(/\s+/g,"");if(W.length===0||W.length%4===1||!/^[A-Za-z0-9+/]*={0,2}$/.test(W))throw Error("`imageBase64` must contain valid base64 image bytes.");return{bytes:Buffer.from(W,"base64"),...$?.[1]?{dataUrlContentType:DQ($[1])}:{}}}function h5(w){if(w<=0)throw Error("The image file is empty.");if(w>BQ)throw Error("Image assets must be 5MB or smaller.")}function EV(w){let b=MV(w.filename)??DQ(w.explicitContentType)??DQ(w.dataUrlContentType);if(!b||!jV.has(b))throw Error("Unsupported image type. Use PNG, JPEG, GIF, or WebP.");return b}function NV(w){let b,$,Q;if(w.filePath!==void 0){if(!Cb())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 X=AV(w.filePath).size;h5(X),b=UV(w.filePath),$=w.filename??KV(w.filePath)}else{if(!w.imageBase64)throw Error("Provide either `filePath` or `imageBase64` when uploading an image asset.");if(!w.filename)throw Error("`filename` is required with `imageBase64` when uploading an image asset.");let X=IV(w.imageBase64);b=X.bytes,Q=X.dataUrlContentType,$=w.filename,h5(b.byteLength)}let W=EV({filename:$,explicitContentType:w.contentType,dataUrlContentType:Q});return{bytes:b,filename:$,contentType:W,altText:w.altText??VV($)}}async function u5(w){let b=NV(w),$=b.bytes.byteLength,Q=await D("POST","/api/v1/media/upload-url",{filename:b.filename,contentType:b.contentType,fileSizeBytes:$},w.companyId);return await EQ(Q.uploadUrl,b.bytes,b.contentType,w.companyId),(await D("POST","/api/v1/media/complete-upload",{key:Q.key,filename:Q.fileName,contentType:b.contentType,fileSizeBytes:$,...w.sourceWidth!==void 0&&{width:w.sourceWidth},...w.sourceHeight!==void 0&&{height:w.sourceHeight},altText:b.altText},w.companyId)).asset}var TV={type:"boolean",description:"Whether the Sequenzy operation succeeded."},o0={type:"string",description:"Human-readable status, confirmation, or next-step message."},m5={type:"string",description:"Additional context about the result."};function I(w){return{type:"object",description:w,additionalProperties:!0}}function O0(w){return{type:"array",description:w,items:I("One item in the returned collection.")}}function Z(w){return{type:"string",description:w}}function Nw(w){return{type:["object","null"],description:w,additionalProperties:!0}}function F1(w){return{type:["string","null"],description:w}}function y(w){return{type:"number",description:w}}function d(w){return{type:"boolean",description:w}}function V(w){return I(`The ${w} record returned by Sequenzy.`)}function h(w){return O0(`List of ${w} records returned by Sequenzy.`)}var x0="`opened` and `clicked` are unique counts deduplicated by email send (one recipient opening five times counts once), not total open events. Every count is attributed to the sends made inside the requested window, including engagement that arrives after the window ends, so `opened <= delivered <= sent` always holds. Rates use `rateDenominator` (`delivered`, or `sent` when no delivery events were recorded, reported as `rateDenominatorBasis`); `deliveryRate` and `bounceRate` divide by `sent`.",l5="Run state: branch on effectiveStatus (draft, live, enrollment_paused, paused, or archived) rather than on status, which reads `active` even when new enrollments are paused. acceptsNewEnrollments and processesExistingEnrollments answer the two questions behind it, and effectiveStatusSummary is a plain-language sentence. The legacy triggerConfig.active flag is not read by the runtime; it is reported as a mirror of acceptsNewEnrollments.",t0=I(`The sequence record returned by Sequenzy. ${l5}`),RV=O0(`List of sequence records returned by Sequenzy. ${l5}`),L4={effectiveStatus:{type:"string",enum:["draft","live","enrollment_paused","paused","archived"],description:"Resolved run state. The one field to branch on: `status` still reads `active` while new enrollments are paused."},acceptsNewEnrollments:d("Whether new subscribers can enter the sequence right now."),processesExistingEnrollments:d("Whether subscribers already inside the sequence keep advancing and receiving steps."),effectiveStatusSummary:Z("One plain-language sentence describing the run state, safe to show a user verbatim.")},c5={...t0,properties:{migratedRecipientCount:y("Recipients moved immediately from deleted steps to their surviving successor."),completedRecipientCount:y("Recipients completed because a deleted step had no surviving successor.")}},SV={appUrls:I("Dashboard URLs for relevant Sequenzy resources."),url:Z("Primary dashboard URL for this result."),settingsUrl:Z("Company settings URL when available.")},vV={success:TV,message:o0,note:m5,warnings:{type:"array",description:"Non-fatal cautions about content, permissions, or follow-up actions.",items:Z("One warning.")},items:{type:"array",description:"Fallback array wrapper used only when a tool returns a bare array.",items:I("One returned item.")},value:I("Fallback object wrapper used only when a tool returns a non-object value.")},CV={get_account:{account:V("account"),companies:h("company"),apiKeyPermissions:I("Current API key preset and scopes, whether common marketing work is discoverable, any missing marketing read scopes, and the API Keys management URL."),currentCompanyId:Z("Company ID selected by the authenticated API key, when available."),selectedCompanyId:Z("Company ID selected locally for subsequent MCP calls, when available.")},select_company:{companyId:Z("Selected company ID."),companyName:Z("Selected company name.")},get_app_urls:{dashboard:Z("Company dashboard URL."),settings:Z("Company settings URL."),campaign:Z("Campaign editor URL."),landingPage:Z("Landing page editor URL."),sequence:Z("Sequence editor URL."),email:Z("Email editor URL."),transactionalEmail:Z("Transactional email URL."),emailSend:Z("Sent email detail URL."),domain:Z("Sending domain settings URL."),urls:I("All generated URLs keyed by resource type.")},create_company:{company:V("company"),autoSelected:d("Whether the new company was selected for subsequent MCP calls.")},update_company:{company:V("company")},get_company:{company:V("company")},get_sync_rules:{syncRules:{type:"array",description:"Effective sync rules for the company.",items:I("One sync rule.")},isDefault:d("Whether the company uses the inherited SaaS/ecommerce platform preset.")},update_sync_rules:{syncRules:{type:"array",description:"Effective sync rules after the update.",items:I("One sync rule.")},isDefault:d("Whether the company now uses the inherited SaaS/ecommerce platform preset.")},get_shopify_automation_settings:{browseAbandonment:I("Effective browse-abandonment settings (defaults applied)."),cartAbandonment:I("Effective cart-abandonment settings (defaults applied)."),priceDrop:I("Effective price-drop settings (defaults applied)."),shopDomain:Z("Connected Shopify store domain.")},update_shopify_automation_settings:{browseAbandonment:I("Effective browse-abandonment settings after the update."),cartAbandonment:I("Effective cart-abandonment settings after the update."),priceDrop:I("Effective price-drop settings after the update."),shopDomain:Z("Connected Shopify store domain.")},create_api_key:{apiKey:I("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:Z("Newly created API key if the API response uses the short key field.")},list_api_keys:{apiKeys:h("non-secret API key metadata, including ID, name, prefix, permissions, timestamps, and active-credential status")},update_api_key:{apiKey:V("updated non-secret API key metadata, including the `scopes` now in effect (null when the key has full access)")},revoke_api_key:{apiKey:V("revoked non-secret API key metadata")},delete_api_key:{apiKey:V("deleted non-secret API key metadata")},list_websites:{websites:h("sending domain, including DNS verification and readyToSend home-transport readiness")},list_integrations:{integrations:h("connected integration, including provider, provider account ID, active and sync status, last sync time, last sync error, allowlisted non-secret details, and lastSyncSkipped (records the last sync could not import normally: suppressed profiles that cannot receive email, plus any that were not imported). Credentials are never included")},get_integration:{integration:I("The connected integration: provider, display name, category, provider account ID, active and sync status, last sync time and error, and allowlisted non-secret details. Credentials are never included."),capabilities:Nw("What this provider does: category, connect method, what it syncs, every event it emits with when it fires, attributes it writes, supported actions, availability, and caveats. Null for a provider with no catalog entry."),events:O0("Each event the provider emits, every matching tag rule and its conditions, listening sequences, and account-wide observation fields. Use activity for integration-specific delivery."),unusedEvents:{type:"array",description:"Events the provider emits that no sequence triggers on. These are the concrete automation gaps for this integration.",items:Z("Event name with no listening sequence.")},accountNeverReceivedEvents:{type:"array",description:"Provider event names this account has never received from any source. This is not integration-specific delivery evidence.",items:Z("Event name never seen account-wide.")},activity:I("Webhook and sync activity over the last 24 hours: totals by status, stalled count, last activity time, and recent failures."),pixel:Nw("Shopify only: live storefront pixel state (installed, endpoint, endpointCurrent, configurationCurrent, healthy, error, dependentEvents). Null for providers without a pixel. When error is null and healthy is false, every dependentEvent is confirmed dark; an error means Shopify could not confirm the state."),recommendations:O0("Prioritized problems and suggestions, each with a code, severity (error, warning, info), message, and a concrete action."),availableActions:{type:"array",description:"Action ids callable on this integration right now, given its current state.",items:Z("Available action id.")}},list_integration_capabilities:{providers:h("integration provider, including category, connect method, what it syncs, every event it emits with the moment that triggers it, the subscriber attributes it writes, supported actions, availability, and caveats")},list_integration_activity:{activity:h("integration activity row, including provider, action, status, event type, matched contact, message, and error. Payloads are sanitized, so no credentials appear"),windowHours:{type:"number",description:"Retention window in hours for integration activity."},note:m5},connect_integration:{integration:{type:"object",description:"The connected integration: id, provider, name, providerAccountId, sync state, and safe (non-credential) details."},webhookUrl:Z("URL to configure in the provider's webhook settings with the same secret. Always relay this to the user - delivery does not start until it is configured."),revenueSyncQueued:d("Payment providers only: whether the initial revenue backfill was queued."),backfillQueued:d("Affonso only: whether the affiliate backfill was queued."),history:{type:"object",description:"PostHog only: outcome of the optional history import request ({ requested, queued, error }). The webhook connection succeeds even if queueing the import failed."}},set_integration_sync_enabled:{integrationId:Z("The integration that was updated."),provider:Z("Provider of the updated integration."),syncEnabled:d("Sync state after the update."),changed:d("False when the integration was already in the requested state."),message:o0},get_integration_pixel:{integrationId:Z("The Shopify integration inspected."),provider:Z("Always `shopify`."),shopDomain:Z("Store the pixel was read from."),pixel:I("Live pixel state: installed, id, endpoint it posts to, endpointCurrent (including the supported compatibility route), configurationCurrent (endpoint plus signed connection settings), healthy, and error when Shopify could not confirm."),dependentEvents:{type:"array",description:"Event names that depend on this pixel. They are confirmed unable to arrive only when pixel.error is null and pixel.healthy is false.",items:Z("Pixel-dependent event name.")},message:o0},activate_integration_pixel:{integrationId:Z("The Shopify integration updated."),provider:Z("Always `shopify`."),shopDomain:Z("Store the pixel was installed on."),pixel:I("Pixel state after activation."),changed:d("False when the pixel was already installed and reporting to this account."),created:d("True when a new pixel was installed."),updated:d("True when an existing pixel was repointed at this account."),dependentEvents:{type:"array",description:"Event names this pixel enables.",items:Z("Pixel-dependent event name.")},message:o0},sync_integration:{integrationId:Z("The integration being synced."),provider:Z("Provider of the synced integration."),jobId:F1("Background job id for the queued sync, when one was created."),syncStatus:Z("Sync status after queueing. Poll get_integration to watch it progress."),message:o0},list_sender_profiles:{senderProfiles:h("sender (From) profile, including the sending domain behind it, its DNS verification status, and whether DNS plus the home transport allow the address to send"),replyProfiles:h("reply-to profile"),defaultSenderProfileId:F1("Company default sender profile ID. Null when no default is set."),defaultReplyProfileId:F1("Company default reply-to profile ID. Null when no default is set.")},update_sender_profile:{senderProfile:V("renamed sender (From) profile, present when type was sender"),replyProfile:V("renamed reply-to profile, present when type was reply"),renamed:d("False when the profile already carried that name, so nothing changed.")},get_notification_preferences:{notificationPreferences:O0("One entry per notification event with its current mode: off, instant, or daily. Every event is always present; an event the user has never configured reports the platform default."),supportedModes:I("Modes each event accepts, keyed by event. campaign_completed does not accept daily."),defaults:I("Mode each event uses when the user has never configured it.")},update_notification_preferences:{notificationPreferences:O0("Every notification event with its mode after the update, not only the events that were changed."),supportedModes:I("Modes each event accepts, keyed by event. campaign_completed does not accept daily."),defaults:I("Mode each event uses when the user has never configured it.")},get_sending_status:{status:Z("Company-level sending state: active, paused, or suspended. Anything other than active blocks every send, including test sends."),pauseReason:F1("Exact enforcement message, including the measured rate, the threshold it crossed, and the send volume it was measured over. Null when sending is active."),pauseReasonKind:F1("Machine-readable pause cause: high_hard_bounce_rate, high_soft_bounce_rate, high_complaint_rate, phishing_guard, manual, or other. Only high_hard_bounce_rate can be cleared with resume_sending."),pausedAt:F1("ISO timestamp when sending was paused. Null when sending is active."),selfResume:I("Whether the account can clear this pause itself: canSelfResume, supported, allowedByAdmin, ownerIsTrusted, the automated aiReviewStatus (not_required, pending, approved, flagged, failed) with its reason and timestamps, and unavailableReason naming the blocking gate (unsupported_reason, waiting_for_review, blocked_by_ai, review_failed, blocked_by_admin)."),senderHealth:Nw("Enforcement counts and the thresholds that apply at this volume for hard bounces, soft bounces, and complaints. bounceScopedSent is the denominator for bounce rates, complaintScopedSent is the denominator for complaint rates, and scopedSent remains as a backward-compatible alias for bounceScopedSent. Also includes enforcementMode. Null when the account has no metrics record yet or sender-health analytics are temporarily unavailable; pause state and remediation remain authoritative."),metricsWindow:I("Proof that enforcement is not time-windowed: kind is always all_time_since_reset and expiresAt is always null. bounceResetAt and complaintResetAt are the watermarks the totals are counted from. Do not tell the user to wait for a window to expire - there is none."),remediation:I("Ordered steps for the current state, plus supportEmail, docsUrl, and the dashboard URL. Relay these verbatim instead of improvising recovery advice.")},resume_sending:{resumed:d("True when this call restored sending. False when sending was already active."),message:o0,status:Z("Sending state after the request. active on success."),selfResume:I("Self-resume state after the request, including the automated review status and how many gates remain."),metricsWindow:I("Enforcement watermarks after the resume. bounceResetAt moves to now, so the paused rate is recalculated from later sends."),remediation:I("Steps to keep sending healthy after the resume, plus supportEmail and docsUrl.")},get_tracking_settings:{tracking:I("Open, click, and unsubscribe tracking flags, the opt-in strictBotFilteringEnabled bot-detection flag, plus the default attribution window in hours."),consent:I("Signup consent settings: doubleOptInEnabled, and doubleOptInEmailId for the confirmation email sent to pending contacts (null when double opt-in has never been enabled)."),autoUtm:I("Automatic UTM tagging state and its configured parameters."),trackingDomain:Nw("Dedicated click-tracking domain with verification and SSL status. Null when click links use the shared Sequenzy tracking domain."),replyTracking:I("Inbound reply tracking configuration.")},update_tracking_settings:{message:o0,tracking:I("Open, click, and unsubscribe tracking flags, the opt-in strictBotFilteringEnabled bot-detection flag, plus the default attribution window in hours, after the update."),consent:I("Signup consent settings after the update: doubleOptInEnabled, and doubleOptInEmailId for the confirmation email, which is provisioned automatically the first time double opt-in is enabled."),autoUtm:I("Automatic UTM tagging state and its configured parameters, after the update."),trackingDomain:Nw("Dedicated click-tracking domain with verification and SSL status. Null when click links use the shared Sequenzy tracking domain."),replyTracking:I("Inbound reply tracking configuration. Unchanged by this tool; set it with update_company.")},add_website:{website:V("Sending domain with its cohort-specific DNS records. Publish every returned record, including DMARC when present.")},add_sending_domain:{website:V("Sending domain with its cohort-specific DNS records. Publish every returned record, including DMARC when present.")},check_website:{website:V("sending domain with separate DNS verification and readyToSend home-transport readiness"),ready:d("Whether the sender website is ready."),status:Z("Current processing or verification status.")},verify_sending_domain:{website:V("Sending domain with current DNS verification, readyToSend home-transport readiness, SPF, DKIM, and MAIL FROM details."),verified:d("Whether the sending domain passed the fresh DNS verification check. This does not by itself mean SES or MTA is ready."),readyToSend:d("Whether DNS and the selected home transport are both ready for sending."),message:Z("Verification result summary.")},get_integration_guide:{guide:V("integration guide"),code:Z("Generated integration code or example."),steps:{type:"array",description:"Setup steps for the requested integration.",items:I("One setup step.")}},add_subscriber:{subscriber:V("subscriber")},create_subscriber_import:{import:V("subscriber import")},get_subscriber_import:{import:V("subscriber import")},update_subscriber:{subscriber:V("subscriber")},remove_subscriber:{subscriber:V("subscriber"),hardDeleted:d("Whether the subscriber was permanently deleted.")},get_subscriber:{subscriber:V("subscriber")},list_subscriber_notes:{notes:h("subscriber note")},add_subscriber_note:{note:V("subscriber note")},delete_subscriber_note:{id:Z("Deleted subscriber note ID."),deleted:d("Whether the subscriber note was deleted.")},trigger_subscriber_event:{subscriber:V("subscriber"),event:V("recorded event with its name and whether the event definition was created"),sideEffectFailures:{type:"array",description:"Sync-rule or automation side effects that failed. The event itself is still recorded.",items:Z("One failed side effect.")}},trigger_subscriber_events:{subscriber:V("subscriber"),events:h("recorded event")},bulk_add_subscriber_tags:{tags:{type:"array",description:"Normalized tag names applied to every matched subscriber.",items:Z("One tag name.")},requested:y("Identifiers supplied in the request."),matched:y("Existing subscribers resolved."),updated:y("Subscribers whose tags actually changed."),unchanged:y("Subscribers that already carried every tag."),failed:y("Subscribers whose update failed."),notFound:I("Identifiers that did not resolve, grouped as emails, externalIds, and subscriberIds. These subscribers were NOT created."),failures:h("per-subscriber failure (up to 50)"),triggeredAutomations:d("Whether tag_added sequences were allowed to enroll these contacts.")},bulk_remove_subscriber_tags:{tags:{type:"array",description:"Normalized tag names removed from every matched subscriber.",items:Z("One tag name.")},requested:y("Identifiers supplied in the request."),matched:y("Existing subscribers resolved."),updated:y("Subscribers whose tags actually changed."),unchanged:y("Subscribers that did not carry any of the tags."),failed:y("Subscribers whose update failed."),notFound:I("Identifiers that did not resolve, grouped as emails, externalIds, and subscriberIds."),failures:h("per-subscriber failure (up to 50)")},search_subscribers:{subscribers:h("subscriber"),pagination:I("Pagination metadata: page, limit, offset, total (null when the server skipped the count, which it does for attribute filters), totalPages, fetchedPages, hasMore, nextOffset, and nextCursor. When hasMore is true, repeat the call with cursor set to nextCursor, or with offset set to nextOffset when nextCursor is null."),returned:y("Number of subscribers returned."),truncated:d("Whether matches remain beyond the returned window. Same as pagination.hasMore.")},list_products:{products:h("product"),pagination:I("Pagination metadata: limit, offset, count (this page), total (whole catalog) and hasMore. Page with offset when hasMore is true.")},upsert_products:{products:h("product"),created:y("Number of products created."),updated:y("Number of products updated.")},delete_product:{productId:Z("Deleted product ID.")},attach_product_file:{product:V("product"),delivery:V("digital delivery file")},remove_product_file:{product:V("product")},upload_image_asset:{asset:V("hosted image asset"),imageBlock:I("Ready-to-insert Sequenzy image block using the hosted asset URL.")},sync_products:{job:V("product sync job"),jobId:Z("Queued product sync job ID.")},list_tags:{tags:h("tag")},create_tag:{tag:V("tag")},update_tag:{tag:V("tag")},delete_tag:{tagId:Z("Deleted tag ID.")},list_lists:{lists:h("list")},create_list:{list:V("list")},update_list:{list:V("list")},delete_list:{listId:Z("Deleted list ID.")},add_subscribers_to_list:{list:V("list"),added:y("Number of subscribers added to the list."),skipped:y("Number of subscribers skipped.")},remove_subscribers_from_list:{list:V("list"),removed:y("Number of subscribers removed from the list."),skipped:y("Number of subscribers skipped.")},list_segments:{segments:h("segment")},create_segment:{segment:V("segment")},update_segment:{segment:V("segment")},delete_segment:{segmentId:Z("Deleted segment ID.")},get_segment_count:{count:y("Number of subscribers matching the segment."),segmentId:Z("Segment ID that was counted.")},list_audience_syncs:{audienceSyncs:h("audience sync")},list_ad_accounts:{adAccounts:h("ad account")},create_audience_sync:{audienceSync:V("audience sync")},update_audience_sync:{audienceSync:V("audience sync")},delete_audience_sync:{audienceSyncId:Z("Deleted audience sync ID.")},sync_audience_now:{audienceSync:V("audience sync"),job:V("audience sync job"),jobId:Z("Queued audience sync job ID.")},list_templates:{templates:h("email template"),pagination:I("Pagination metadata: limit, offset, count (this page), total (every email body) and hasMore. Page with offset when hasMore is true.")},get_template:{template:V("email template")},create_template:{template:V("email template")},update_template:{template:V("email template")},set_template_localization:{templateId:Z("Localized template ID."),localization:V("template localization")},sync_template_localizations:{templateId:Z("Template ID queued for localization."),queuedLocales:{type:"array",description:"Locale codes queued for AI translation.",items:Z("One queued locale code.")},queuedVariantCount:y("Number of localized variants queued for translation.")},delete_template:{templateId:Z("Deleted template ID.")},list_ab_tests:{abTests:h("A/B test")},get_ab_test:{abTest:V("A/B test")},get_ab_test_stats:{abTest:V("A/B test"),stats:V("A/B test statistics")},restart_ab_test:{abTest:V("A/B test")},update_ab_test_variant:{abTest:V("A/B test"),variant:V("A/B test variant")},update_ab_test:{abTest:V("A/B test")},create_ab_test:{abTest:V("A/B test")},add_ab_test_variant:{abTest:V("A/B test"),variant:V("A/B test variant")},delete_ab_test_variant:{abTest:V("A/B test"),variantId:Z("Deleted A/B test variant ID.")},delete_ab_test:{abTestId:Z("Deleted A/B test ID.")},list_campaigns:{campaigns:h("campaign"),pagination:I("Campaign page window: `limit`, `offset`, `count` returned in this page, `total` matching the filters, and `hasMore`. Keep calling with an advanced `offset` while `hasMore` is true to enumerate every campaign.")},get_campaign:{campaign:V("campaign")},get_campaign_audience:{campaignId:Z("Campaign the audience was resolved for."),campaignName:Z("Campaign name."),status:Z("Campaign status."),audience:I("Resolved targeting: `type`, a plain-language `summary`, `isUnset` (true when scheduling would fall back to every active subscriber), resolved `lists` and `segments` with names and a `missing` flag, `filters`, `include`/`exclude` rules, and individual subscriber adjustments."),recipientCount:y("Number of subscribers matching the effective targeting right now."),targetLists:Nw("Raw stored targeting exactly as persisted on the campaign. Null when targeting has never been set.")},get_email_send:{emailSend:V("email send, including copied-recipient identity and primary email send ID when applicable"),events:h("email delivery event")},list_email_sends:{emailSends:h("email send"),pagination:V("email send pagination"),retentionDays:y("Number of days sent-email rows remain queryable in this collection.")},get_recipient_suppression:{suppression:V("recipient suppression status")},remove_recipient_suppression:{removed:d("Whether stale bounce suppression was removed."),removedLocalBounce:d("Whether the platform-local bounce block was removed."),removedSesRegions:{type:"array",description:"AWS SES regions where a bounce suppression was removed.",items:Z("One AWS SES region.")},remainingSuppression:V("recipient suppression status after cleanup")},create_campaign:{campaign:V("campaign")},update_campaign:{campaign:V("campaign")},schedule_campaign:{campaign:V("campaign"),scheduledAt:Z("Scheduled send timestamp.")},unschedule_campaign:{campaign:V("draft campaign")},send_test_email:{emailSendId:Z("Durable test email delivery ID."),recipientEmail:Z("Test email recipient.")},send_test_sms:{smsSendId:Z("Created test SMS send ID."),toPhone:Z("Normalized E.164 destination phone.")},cancel_campaign:{campaign:V("campaign")},pause_campaign:{campaign:V("campaign")},resume_campaign:{campaign:V("campaign")},delete_campaign:{campaignId:Z("Deleted campaign ID.")},duplicate_campaign:{campaign:V("duplicated campaign")},resend_campaign_to_non_openers:{campaign:V("non-opener resend draft campaign"),estimatedNonOpenerCount:y("Estimated number of subscribers who haven't opened the original campaign.")},list_forms:{forms:h("saved form")},create_form:{form:V("saved form"),embed:I("Public action URL plus JavaScript, native form, and fetch snippets.")},update_form:{form:V("saved form"),embed:I("Public action URL plus JavaScript, native form, and fetch snippets (published forms only).")},get_form_embed:{form:V("saved form"),embed:I("Public action URL plus JavaScript, native form, and fetch snippets.")},list_landing_pages:{landingPages:h("landing page")},get_landing_page:{landingPage:V("landing page")},create_landing_page:{landingPage:V("landing page")},update_landing_page:{landingPage:V("landing page")},duplicate_landing_page:{landingPage:V("landing page")},delete_landing_page:{landingPageId:Z("Deleted landing page ID.")},publish_landing_page:{landingPage:V("landing page")},unpublish_landing_page:{landingPage:V("landing page")},connect_landing_page_domain:{landingPage:V("landing page"),domain:Z("Connected landing page domain.")},update_landing_page_domain_settings:{landingPage:V("landing page"),domain:Z("Landing page domain.")},list_sequences:{sequences:RV,pagination:I("Sequence page window: `limit` (null when limit and offset were both omitted and every sequence was returned), `offset`, `count` returned in this page, `total` matching the filters, and `hasMore`.")},get_sequence:{sequence:t0},list_sequence_enrollments:{sequenceId:Z("Sequence ID these enrollments belong to."),sequenceName:Z("Sequence name."),statuses:{type:"array",description:"Enrollment statuses included in this response. Defaults to active and waiting.",items:{type:"string",description:"Enrollment status."}},enrollments:{type:"array",description:"Contact-level enrollments matching the filters, one row per enrollment token.",items:{type:"object",description:"One subscriber's enrollment in this sequence.",properties:{enrollmentId:Z("Enrollment token ID. Stable identifier for this one run through the sequence."),sequenceId:Z("Sequence ID."),subscriberId:Z("Subscriber ID."),email:F1("Subscriber email address. Falls back to the address captured at enrollment when the subscriber record no longer exists, and is null when neither is known."),firstName:F1("Subscriber first name, or null when unset."),lastName:F1("Subscriber last name, or null when unset."),subscriberStatus:F1("Subscriber status (active, unsubscribed, bounced), or null when the subscriber record no longer exists."),status:Z("Enrollment status: active, waiting, completed, failed, or cancelled."),currentNodeId:Z("Sequence node this enrollment is currently sitting on."),currentNodeType:Z("Current sequence node type. Omitted when the node no longer exists in the graph."),currentNodeLabel:Z("Current sequence node label or email subject when available."),currentNodeMissing:d("Whether the current node no longer exists in the sequence graph."),enrollmentKey:Z("Key that distinguishes concurrent enrollments of the same subscriber in this sequence."),enrollmentStartedAt:Z("ISO 8601 timestamp when this enrollment entered the sequence."),waitUntil:F1("ISO 8601 timestamp this enrollment is scheduled to resume, or null when nothing is scheduled."),lastUpdatedAt:Z("ISO 8601 timestamp of the last change to this enrollment. For a waiting enrollment this is when it arrived at its current node; the platform does not separately track node entry time."),failedReason:F1("Why this enrollment stopped, for status `failed`. Null for every other status and for failures recorded before this field existed. A reason repeated across enrollments on the same currentNodeId points at that step's configuration or content rather than at the contacts.")},required:["enrollmentId","sequenceId","subscriberId","status","currentNodeId","currentNodeMissing","enrollmentStartedAt"]}},pagination:I("Pagination metadata.")},send_sequence_test_email:{sequenceId:Z("Sequence ID."),nodeId:Z("Tested sequence email-step node ID."),results:O0("Per-recipient test-send results containing recipientEmail, durable emailSendId, and legacy jobId.")},create_sequence:{sequence:t0,eventTrackingCode:Z("Ready-to-adapt code for sending a custom trigger event, including any matching-field property."),eventTracking:I("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:Z("One required event name.")}},update_sequence:{sequence:c5},update_sequence_node:{sequence:V("sequence")},update_sequence_nodes:{sequence:V("sequence")},edit_sequence_graph:{sequence:c5},insert_sequence_step:{sequence:V("sequence"),insertedNodeIds:{type:"array",description:"Node IDs created for a linear inserted step, including any delay or wait-for-event node.",items:Z("Inserted automation node ID.")},insertedEmailIds:{type:"array",description:"Email template IDs created for the inserted step.",items:Z("Inserted email template ID.")},insertedEmailCount:y("Number of email steps inserted."),addedBranchNodeId:Z("New logic_branch node ID when the inserted step is a branch."),addedBranchPathNodeIds:I("Created path node IDs keyed by branch ID, plus else. Directly wired paths have empty arrays.")},enable_sequence:{sequenceId:Z("Sequence ID."),status:Z("Stored lifecycle status after the change."),enrollmentPaused:d("Whether new sequence enrollments are paused."),...L4},disable_sequence:{sequenceId:Z("Sequence ID."),status:Z("Stored lifecycle status after the change."),enrollmentPaused:d("Whether new sequence enrollments are paused."),...L4},duplicate_sequence:{sequence:t0,nodes:h("sequence node"),edges:h("sequence edge")},archive_sequence:{sequence:t0},unarchive_sequence:{sequence:t0},list_sequence_goals:{goals:h("sequence goal")},create_sequence_goal:{goal:V("sequence goal")},update_sequence_goal:{goal:V("sequence goal")},delete_sequence_goal:{goalId:Z("Deleted sequence goal ID.")},get_sequence_inbound_webhook:{webhook:V("sequence inbound webhook")},configure_sequence_inbound_webhook:{webhook:V("sequence inbound webhook")},rotate_sequence_inbound_webhook_secret:{webhook:V("sequence inbound webhook")},pause_sequence_enrollments:{sequenceId:Z("Sequence ID."),enrollmentPaused:d("Whether new sequence enrollments are paused."),...L4},resume_sequence_enrollments:{sequenceId:Z("Sequence ID."),enrollmentPaused:d("Whether new sequence enrollments are paused."),...L4},enroll_subscribers_in_sequence:{sequence:V("sequence"),enrollments:h("sequence enrollment"),enrolled:y("Number of subscribers enrolled."),skipped:y("Number of subscribers skipped.")},cancel_sequence_enrollments:{sequenceId:Z("Sequence ID."),dryRun:d("Whether this call only reported matches instead of cancelling them."),target:I("Resolved cancellation target: mode all, subscriber, subscribers (with notFoundSubscriberIds), or field."),matchedCount:y("Active/waiting enrollments matching the target when the request started."),cancelledCount:y("Enrollments cancelled by this call."),remainingCount:y("Enrollments still matching after this call. Repeat the same request while this is above zero."),enrollments:h("sequence enrollment sample (up to 50)"),hasMore:d("Whether more enrollments matched than the returned sample.")},delete_sequence:{sequenceId:Z("Deleted sequence ID.")},list_transactional_emails:{transactional:h("transactional email with subject, all-time delivery metrics, and dashboard URL")},get_transactional_email:{transactional:V("transactional email")},create_transactional_email:{transactional:V("transactional email")},update_transactional_email:{transactional:V("transactional email")},delete_transactional_email:{deleted:I("Deleted transactional email: id, slug, name, and emailId of the email content that was kept as a reusable template.")},send_email:{emailSendId:Z("Durable email delivery ID."),emailType:{type:"string",enum:["marketing","transactional"],description:"Delivery policy accepted for the queued email."},transactional:V("transactional email")},get_stats:{stats:I(`Account-wide delivery funnel for the requested window. ${x0}`),emailType:Z("Applied structural email type filter when one was requested."),commerceForecast:V("Optional background-computed commerce AOV, 12-month customer value, and 90-day revenue forecast. Omitted when no snapshot is available; insufficient_data is returned only after eligibility was evaluated successfully.")},get_campaign_stats:{campaign:V("campaign"),stats:I(`Delivery funnel for this campaign. ${x0}`),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:I("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. Multi-select polls set allowMultiple: true, count each subscriber once per selected option (answer percentages can sum past 100), and report totalResponses as the respondent count. To read the exact historical respondents with their answers and response times, call list_poll_responses with this campaignId (and the summary blockId to scope it). To build a reusable audience from one answer, use the summary blockId and this campaignId with create_segment. ${_0} A summary's attributeKey identifies the subscriber attribute that stores their current/latest response (a value list for multi-select polls) and may be overwritten by a later poll that reuses the key.`,items:I("One poll or NPS results summary.")},recommendations:I("Product recommendation funnel: impressions, recipients, clicks, clickers, orders, legacy revenueCents, currency-safe revenueByCurrency totals, and topProducts (per-product impressions/clicks). Orders count when a subscriber buys a recommended product within 7 days of clicking it. Present only when the campaign rendered product recommendation blocks.")},list_poll_responses:{campaignId:Z("Campaign the responses belong to."),blockId:Z("Poll block the results were scoped to. Present only when blockId was requested."),responses:{type:"array",description:"Individual responses, newest answer first. Each entry has subscriberId, email, externalId, firstName, lastName, blockId, variant (options or nps), question, attributeKey (the subscriber attribute the answer was stored under), allowMultiple, answers (selected option labels), values (their stored values), and respondedAt. Only each subscriber's latest answer per block appears. email is null when the subscriber has since been deleted.",items:I("One respondent's latest answer.")},pagination:I("Pagination metadata: page, limit, total (response rows across every page; one row per subscriber per poll block), and totalPages. Keep paging while page < totalPages.")},get_transactional_stats:{transactional:V("transactional email"),stats:I(`Delivery funnel for this transactional email. ${x0}`),complaints:V("complaint count and rate for the selected transactional email"),clickedLinks:h("clicked link with click count and percentage share"),bounceBreakdown:V("permanent, transient, and undetermined bounce counts plus subtype details"),engagementBreakdown:V("human and machine open and click counts")},get_sequence_stats:{sequence:t0,stats:I(`Delivery funnel across every email step in this sequence. ${x0}`),steps:{type:"array",description:`Per-step delivery funnel: one entry per email step of the sequence, in graph order, each with its own sent/delivered/opened/clicked counts. Read this to answer "how many of step N went out" - do not recount list_sequence_events. Counts come from the retained event stream, so they are not limited to the 14-day list_email_sends history. ${x0}`,items:{type:"object",description:"Metrics for one email step of the sequence.",properties:{step:y("1-based position of this email step in graph order. Step 4 is the fourth email a contact receives on the traversed path; on a branching graph, positions are assigned by traversal, so cross-check nodeId when a sequence forks."),nodeId:Z("Automation node ID of this email step. Pass it to list_sequence_events or list_email_sends as automationNodeId to reach the individual recipients behind these counts, and it is the emailId that list_email_metrics reports for sequence emails."),subject:F1("Subject line of the step's email, falling back to the node label, or null when neither is set."),stats:I(`Delivery funnel for this step alone: sent, delivered, bounced, opened, clicked, replies, unsubscribed, and their rates. ${x0}`),failedCount:y("Contacts currently stuck on this step with a failed enrollment."),failedSubscribers:O0("Up to 20 of the failed contacts on this step, as { subscriberId, email, failedAt, failedReason }.")},required:["step","nodeId","stats"],additionalProperties:!0}},enrollmentCounts:{type:"object",description:"Live enrollment-token counts for this sequence. Includes only active and waiting enrollments and is always a current snapshot, independent of historical period/start/end filters.",properties:{active:y("Active enrollment count."),waiting:y("Waiting enrollment count."),total:y("Total active plus waiting enrollment count."),byCurrentNode:{type:"array",description:"Live active and waiting enrollment counts grouped by the token's current sequence node.",items:{type:"object",description:"Enrollment counts for one current sequence node.",properties:{currentNodeId:Z("Current sequence node ID."),currentNodeType:Z("Current sequence node type. Omitted when the node no longer exists in the graph."),currentNodeLabel:Z("Current sequence node label or email subject when available."),currentNodeMissing:d("Whether the current node no longer exists in the sequence graph."),active:y("Active enrollment count at this node."),waiting:y("Waiting enrollment count at this node."),total:y("Total active plus waiting enrollment count at this node.")},required:["currentNodeId","currentNodeMissing","active","waiting","total"],additionalProperties:!1}}},required:["active","waiting","total","byCurrentNode"],additionalProperties:!1},enrollmentSkipped:{type:"object",description:"Trigger matches where an unsubscribed or bounced contact could not be enrolled, including the total count and counts grouped by reason. Uses the requested period or start/end range; without an explicit range, this field defaults to the last 30 days.",properties:{count:y("Total skipped sequence enrollments."),byReason:{type:"object",description:"Skipped enrollment counts keyed by reason, such as unsubscribed or bounced.",additionalProperties:y("Skipped enrollment count for this reason.")}},required:["count","byReason"],additionalProperties:!1},recommendations:I("Product recommendation funnel aggregated across the sequence's email nodes: impressions, recipients, clicks, clickers, orders, legacy revenueCents, currency-safe revenueByCurrency totals, and topProducts. Present only when the sequence rendered product recommendation blocks.")},list_campaign_events:{events:h("campaign email event"),pagination:I("Pagination metadata.")},list_sequence_events:{events:h("sequence email event"),pagination:I("Pagination metadata.")},list_email_metrics:{emails:{type:"array",description:"One entry per email in scope: each campaign and each sequence email step, sorted by the requested sort/order.",items:{type:"object",description:"Metrics for one campaign or one sequence email step.",properties:{emailType:{type:"string",enum:["campaign","sequence"],description:"Whether this row is a campaign or a sequence email."},emailId:Z("Stable identifier: the campaign ID for campaigns, the automation node ID for sequence emails."),name:Z("Campaign name, or the sequence step's subject line falling back to its node label."),campaignId:F1("Campaign ID, or null for sequence emails."),sequenceId:F1("Sequence ID, or null for campaigns."),sequenceName:F1("Name of the sequence this step belongs to, or null for campaigns."),automationNodeId:F1("Automation node ID of this step, or null for campaigns. Pass it as automationNodeId to list_sequence_events or list_email_sends to reach the recipients behind these counts."),step:{type:["number","null"],description:"1-based position of this email in its sequence, counted in graph order, or null for campaigns. Matches the step number in get_sequence_stats steps[]."},stats:I(`Delivery funnel for this email alone. ${x0}`),conversions:y("Attributed conversions credited to this email."),revenueCents:y("Attributed revenue in minor currency units credited to this email.")},required:["emailType","emailId","name","stats"],additionalProperties:!0}},totals:I(`Summed funnel across every email matching the filters, not just the returned page, plus \`emails\` (the number of matching emails), \`conversions\`, and \`revenueCents\`. Read totals.sent for "how many of this step went out in total". ${x0}`),pagination:I("Pagination metadata."),sort:Z("Sort field the response was ordered by."),order:Z("Sort order the response was ordered by."),step:y("Echo of the step filter, present only when one was requested."),sequenceIds:{type:"array",description:"Echo of the sequence IDs the breakdown was scoped to, present only when scoped.",items:Z("Sequence ID.")}},get_subscriber_activity:{activity:h("subscriber activity event"),subscribers:h("subscriber"),pagination:I("Pagination metadata.")},list_team_members:{members:h("team member"),invitations:h("team invitation")},invite_team_member:{invitation:V("team invitation")},cancel_team_invitation:{invitationId:Z("Cancelled invitation ID.")},list_conversations:{conversations:h("inbox conversation"),pagination:I("Pagination metadata.")},get_conversation:{conversation:V("inbox conversation"),messages:h("conversation message")},reply_to_conversation:{conversation:V("inbox conversation"),message:V("conversation message")},update_conversation_status:{conversation:V("inbox conversation")},mark_conversation_read:{conversation:V("inbox conversation")},list_webhooks:{webhooks:h("outbound webhook")},create_webhook:{webhook:V("outbound webhook")},update_webhook:{webhook:V("outbound webhook")},delete_webhook:{webhookId:Z("Deleted outbound webhook ID.")},test_webhook:{webhook:V("outbound webhook"),delivery:V("test webhook delivery")},list_webhook_deliveries:{deliveries:h("webhook delivery")},replay_webhook_delivery:{delivery:V("webhook delivery"),job:V("webhook replay job")},generate_email:{email:V("generated email"),html:Z("Generated HTML email body."),blocks:{type:"array",description:"Generated Sequenzy email blocks, wrapped with company branding (logo + footer) unless applyBranding was false.",items:I("One generated email block.")},subject:Z("Generated subject line."),previewText:Z("Generated inbox preview text.")},generate_sequence:{sequence:V("persisted AI-generated sequence draft"),deprecated:d("Always true for this deprecated alias."),deprecationMessage:Z("Migration guidance directing callers to create_sequence.")},generate_subject_lines:{subjectLines:{type:"array",description:"Generated subject line variants.",items:Z("One generated subject line.")},variants:h("generated subject line variant")},generate_sms:{prompt:Z("The prompt the messages were generated for."),messages:{type:"array",description:"Generated SMS message variants with encoding and segment counts.",items:I("One generated SMS message.")}},get_sms_settings:{sms:I("SMS add-on status: enabled, planEligible, creditsBalance, brandPrefix, numbers, readyToSend (paid plan or credits plus an active number).")},submit_feedback:{},render_email:{html:Z("Email-safe HTML document, rendered exactly as it would be sent."),subject:Z("Subject line with merge tags resolved."),previewText:F1("Inbox preview text with merge tags resolved, or null when unset."),locale:Z("Localization locale the render resolved to."),personalized:d("Whether a real contact was supplied. False means a sample contact was used, so contact-specific merge tags resolve to empty values."),trackingApplied:d("Whether auto-UTM link decoration was applied."),unresolvedMergeTags:O0(`Merge tags that rendered as an empty string, as [{ tag, reason }]. reason "unknown" means nothing provides that name, so it stays empty for every recipient - usually a typo or a tag copied from another platform. reason "no_value" means the name is recognized, or could not be checked, but is blank for this contact. A name is only called unknown when the render had a source to check it against. Without the contact's attributes nothing is checkable, since a bare {{plan}} reads the same attribute map as {{subscriber.plan}}, so pass a stored subscriberId or an inline subscriber carrying customAttributes. Beyond that, {{event.*}} needs sample event properties in variables, since a real send fills those from the enrolling event; {{recommendedProducts.*}} needs a stored subscriberId the catalog has something to recommend for; and {{discount.*}} is only checkable on a sequence step whose incoming paths all run the same discount step, never on a standalone template. Rendering a transactional email is checkable only when variables is passed, because its tags come from the variables of each send call and carry no prefix marking them. Otherwise those tags land in no_value rather than in unknown. An optional attribute this contact never had set is kept out of unknown by checking the names other contacts in the account carry, which needs the subscribers:read scope; a key without it may report such a name as unknown. An empty array means every tag in the email resolved.`),entity:I("Which entity was rendered: type, id, and variantId.")}};function kV(w){let b=CV[w];if(b===void 0)throw Error(`MCP tool "${w}" must define outputSchema properties.`);return{type:"object",description:`Structured content returned by the \`${w}\` MCP tool.`,properties:{...vV,...b,...zQ.has(w)?SV:{}},additionalProperties:!0}}function g5(w){return{...w,outputSchema:kV(w.name)}}function i5(w){if(k(w))return w;if(Array.isArray(w))return{items:w};return{value:w}}var n5=[{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:x1},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 an A/B test variant. Campaign variants are editable only in draft. Sequence variants can be edited after activity with confirmLiveChange, but earlier sends stay unchanged and combined results may no longer be accurate. 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. ${H1}`},blocks:{type:"array",description:`${A0}${n0} Mutually exclusive with html.`,items:{type:"object"}},confirmLiveChange:{type:"boolean",description:"Required as true when the sequence is active, the test is no longer a draft, or it has recorded activity. The edit affects future sends and can make combined results inaccurate."}},required:["abTestId","variantId"],additionalProperties:!1}},{name:"update_ab_test",description:"Update A/B test settings. Campaign tests use testPercentage, testDurationMinutes, and winnerCriteria. Sequence tests use testType, winnerThreshold, and winnerCriteria; changing live or already-used sequence settings requires confirmLiveChange. Provide at least one setting.",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"},name:{type:"string",description:"Optional A/B test name."},testPercentage:{type:"number",description:"Campaign-only percentage of the audience used for the test phase, from 5 to 50."},testDurationMinutes:{type:"number",description:"Campaign-only test duration in minutes, from 15 to 1440."},winnerCriteria:{type:"string",enum:["open_rate","click_rate"],description:"Winner selection criteria. Applies to both campaign and sequence tests."},testType:{type:"string",enum:["subject","content"],description:"Sequence-only variant strategy. When winnerCriteria is omitted, subject defaults to open_rate and content defaults to click_rate."},winnerThreshold:{type:"number",description:"Sequence-only number of recipients before selecting a winner, from 10 to 1000."},confirmLiveChange:{type:"boolean",description:"Required as true when sequence settings affect an active test or a test with recorded activity."}},required:["abTestId"],additionalProperties:!1}},{name:"create_ab_test",description:"Create a campaign A/B test or convert a sequence email node into a typed A/B test node. Provide exactly one of campaignId or automationNodeId. Control variant A is created automatically from the current email. Campaign tests may add variants later; automationNodeId conversions require at least one variants[] entry to compete with control variant A.",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. Mutually exclusive with automationNodeId."},automationNodeId:{type:"string",description:"Sequence email-node ID to convert to action_ab_test. Mutually exclusive with campaignId."},confirmLiveChange:{type:"boolean",description:"Required as true when converting an email node in an active sequence."},name:{type:"string",description:"Optional A/B test name."},testPercentage:{type:"number",description:"Campaign-only percentage of the audience used for the test phase, from 5 to 50. Defaults to 20. Sequence tests use winnerThreshold instead."},testDurationMinutes:{type:"number",description:"Campaign-only test phase duration in minutes, from 15 to 1440. Defaults to 240. Sequence tests select after winnerThreshold recipients instead."},winnerCriteria:{type:"string",enum:["open_rate","click_rate"],description:"Winner selection criteria. Campaign tests default to open_rate. For sequence tests, an explicit value overrides the testType default."},testType:{type:"string",enum:["subject","content"],description:"Sequence A/B test variant strategy. Subject defaults to open_rate and content defaults to click_rate unless winnerCriteria is explicit. Defaults to content."},winnerThreshold:{type:"number",description:"Sequence test sample size from 10 to 1000. Defaults to 100."},variants:{type:"array",maxItems:4,description:"Extra variants to create in addition to control variant A. Optional for campaign tests; automationNodeId conversions require at least one entry.",items:{type:"object",properties:{subject:{type:"string",description:"Variant subject line."},previewText:{type:"string",description:"Variant preview text."},blocks:{type:"array",description:`${A0}${n0}`,items:{type:"object"}}},required:["subject"]}}}}},{name:"add_ab_test_variant",description:"Add a variant to a draft campaign or sequence A/B test. Sequence variants receive their own editable email template. Variants cannot be added after the test has started. Sequence tests whose parent sequence is active require confirmLiveChange.",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:`${A0}${n0}`,items:{type:"object"}},confirmLiveChange:{type:"boolean",description:"Required as true when the A/B test belongs to an active sequence, because new variants immediately enter the live rotation."}},required:["abTestId","subject"]}},{name:"delete_ab_test_variant",description:"Permanently delete a variant from a draft campaign or sequence 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. Sequence tests whose parent sequence is active require confirmLiveChange.",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."},confirmLiveChange:{type:"boolean",description:"Required as true when the A/B test belongs to an active sequence, because deletion immediately changes the live rotation."}},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 p5=[{name:"get_account",description:`Get current account information including available companies, the current API key's permission scopes, and the API Keys management URL. Call this after a missing-scope error to inspect access and find the replacement-key settings. IMPORTANT: If you have access to multiple companies, you MUST either:
29
29
  1. Call select_company first to choose which company to work with, OR
30
30
  2. Pass companyId explicitly in each tool call
31
31
 
@@ -53,5 +53,5 @@ Use cases:
53
53
  - 'event_tracking': Tracking CUSTOM events only (not payment events - those come from the integration)
54
54
  - 'ecommerce': Connecting a custom e-commerce platform via the Commerce API (sync products, push orders/checkouts, power abandoned cart + back-in-stock automations)
55
55
 
56
- Before protected server-side API work, use create_api_key and save the key to .env as SEQUENZY_API_KEY. Static-site saved forms are the exception: use list_forms/create_form/get_form_embed and never place a secret key in browser code.`,inputSchema:{type:"object",properties:{framework:{type:"string",description:"Framework/language (nextjs, express, python, etc.)"},use_case:{type:"string",description:"Use case: 'transactional' (sending emails), 'subscribe_form' (adding subscribers), 'event_tracking' (tracking CUSTOM events only - payment events should come from Stripe/Polar/etc integration), 'ecommerce' (connecting a custom e-commerce platform via the Commerce API)"}}}}];var f5=[{name:"generate_email",description:"Generate email blocks from a prompt. Generated blocks include the company's branding chrome (logo, footer with company name/address/unsubscribe) by default, matching emails created in the dashboard.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},prompt:{type:"string",description:"Description of the email to generate"},style:{type:"string",description:"Style: minimal, branded, promotional"},tone:{type:"string",description:"Tone: professional, casual, friendly"},applyBranding:{type:"boolean",description:"Wrap the generated content with company branding (logo + footer). Defaults to true; set false to get raw content blocks only."},emailType:{type:"string",enum:["marketing","transactional"],description:"Email type. Transactional emails get a footer without the unsubscribe link. Defaults to marketing."}},required:["prompt"]}},{name:"generate_sequence",description:"[DEPRECATED compatibility alias - use create_sequence] Create and persist a disabled AI-generated email sequence draft from a goal. The saved draft appears in list_sequences. The name defaults to the goal and the trigger defaults to contact_added; optionally pass listId to scope it. Review before enabling.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},goal:{type:"string",description:"Goal of the sequence (e.g., 'onboard new SaaS trial users')"},name:{type:"string",description:"Optional sequence name. Defaults to the goal."},emailCount:{type:"number",description:"Number of emails in the sequence (default: 5, max: 10)"},durationDays:{type:"number",description:"Total duration in days (default: 14)"},listId:{type:"string",description:"Optional list ID. When provided, only contacts added to this list trigger the sequence."}},required:["goal"]}},{name:"generate_subject_lines",description:"Generate A/B test subject line variants",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},topic:{type:"string",description:"Topic or context for the subject lines"},count:{type:"number",description:"Number of variants to generate (default: 5)"}},required:["topic"]}},{name:"generate_sms",description:"Generate SMS marketing message variants from a prompt. Returns plain-text messages with per-message encoding and segment counts. Use the results as the 'text' of an SMS sequence step (insert_sequence_step with type 'sms' or a create_sequence sms step). Messages exclude opt-out footers and brand prefixes - the platform adds those automatically at send time.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},prompt:{type:"string",description:"Description of the SMS to generate (e.g., 'cart reminder with a free-shipping hook')"},count:{type:"number",description:"Number of message variants to generate (default: 3, max: 10)"}},required:["prompt"]}},{name:"get_sms_settings",description:"Get the company's SMS add-on status: whether SMS is enabled, plan eligibility, credit balance, brand prefix, phone numbers, and whether SMS steps will actually send. Check this before adding SMS steps to sequences so you can warn the user when SMS is not ready.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"send_test_sms",description:"Send a test SMS to a phone number. IMPORTANT: sends a real text message and charges SMS credits - only call when the user explicitly asks for a test send. Requires the SMS add-on with a verified number (check get_sms_settings). Limited to 5 test sends per hour; bypasses quiet hours; excluded from step stats.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},to:{type:"string",description:"Destination phone number in international E.164 format, e.g. +15550100123."},text:{type:"string",description:"Plain-text message body. Merge tags are not resolved for test sends to arbitrary numbers. Provide text or blocks."},imageUrls:{type:"array",items:{type:"string"},description:"Up to 2 publicly reachable image URLs sent as MMS media (US/CA only)."},blocks:{type:"array",items:{type:"object"},description:"SMS content blocks (text + image subset). Provide text or blocks, not both."}},required:["to"]}}];var u5=[{name:"get_stats",description:"Get overview statistics for a time period, including reply count and reply rate. Counts form a funnel over the sends made inside the period: opened and clicked are unique per email send (not total open events) and include engagement that arrives after the period ends, so they never exceed sent. Rates divide by rateDenominator (delivered, falling back to sent), reported alongside rateDenominatorBasis. Set emailType to transactional for Send API and transactional SMTP open/click rates, including both direct and saved-template sends. When no emailType filter is used and a background-computed snapshot is available, the response also includes a top-level commerceForecast with predicted AOV, 12-month customer value, 90-day revenue, confidence, and data-eligibility reasons.",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)"},emailType:{type:"string",description:"Optional structural email type filter: campaign, transactional, or sequence. Use transactional for Send API and transactional SMTP traffic."},includeMachineEngagement:kw}}},{name:"get_transactional_stats",description:"Get aggregate sends, deliveries, bounces, opens, clicks, and rates for one saved transactional email selected by ID or slug. Results are all-time by default; pass period or start/end for a window. For direct-content Send API messages, use get_stats with emailType transactional and list_email_sends/get_email_send for delivery-level detail.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},idOrSlug:{type:"string",description:"Saved transactional email ID or API slug."},period:{type:"string",description:"Optional sliding window: 1h, 24h, 7d, 30d, or 90d. Ignored when start and end are provided."},start:{type:"string",description:"Optional ISO 8601 custom range start. Must be provided with end."},end:{type:"string",description:"Optional ISO 8601 custom range end. Must be provided with start; maximum range is 90 days."},includeMachineEngagement:kw},required:["idOrSlug"]}},{name:"get_campaign_stats",description:"Get detailed statistics for a campaign, including replies and reply rate, attributed conversions, revenue (revenueCents), product recommendation funnel metrics, 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"},period:{type:"string",description:"Time period: 1h, 24h, 7d, 30d, or 90d"},start:{type:"string",description:"Custom range start as an ISO 8601 timestamp; provide end too"},end:{type:"string",description:"Custom range end as an ISO 8601 timestamp; provide start too"},includeMachineEngagement:kw},required:["campaignId"]}},{name:"get_sequence_stats",description:"Get statistics for a sequence. The steps array is the per-step breakdown: one entry per email step in graph order with its step number, automation nodeId, subject, and its own sent, delivered, bounced, opened, clicked, replies, and unsubscribed counts plus rates - so this is where you read how many of Email 4 went out, without reconstructing anything from list_sequence_events. Step counts come from the retained event stream, not the 14-day delivery history behind list_email_sends, so they stay answerable for old sends. Also returns the aggregate funnel across every step, attributed conversions and revenue (revenueCents), product recommendation funnel metrics, per-step failed subscribers and failure reasons, and enrollmentSkipped counts for trigger matches where the contact could not be enrolled (unsubscribed/bounced). Pass period or start/end to use one explicit window for every historical metric; without them, step and aggregate counts are all-time and enrollmentSkipped defaults to the last 30 days. The enrollmentCounts field is a live snapshot of active and waiting enrollments grouped by current node, so it is not limited by period or start/end. To compare the same step across many sequences in one call, use list_email_metrics instead.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"},period:{type:"string",description:"Optional sliding window: 1h, 24h, 7d, 30d, or 90d. Ignored when start and end are provided."},start:{type:"string",description:"Optional ISO 8601 custom range start. Must be provided with end."},end:{type:"string",description:"Optional ISO 8601 custom range end. Must be provided with start; maximum range is 90 days."},includeMachineEngagement:kw},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: ${Vb}. Defaults to delivery.`},eventTypes:{type:"array",description:`Optional event types to include. Supported values: ${Vb}. 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:kw},required:["campaignId"]}},{name:"list_sequence_events",description:"List paginated raw email events for every email step in a sequence, or for one step via automationNodeId. Defaults to deliveries; use eventType or eventTypes to include opens, clicks, bounces, complaints, unsubscribes, sends, or delivery delays. This is the per-recipient event stream - do not page it to count sends. Per-step and per-sequence totals already exist as get_sequence_stats steps[], and list_email_metrics gives the same per-step totals across many sequences at once.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"},automationNodeId:{type:"string",description:"Optional email step to scope the stream to, taken from get_sequence_stats steps[].nodeId or get_sequence nodes. Must be an email step of this sequence. Defaults to every email step."},eventType:{type:"string",description:`Optional single event type. Supported values: ${Vb}. Defaults to delivery.`},eventTypes:{type:"array",description:`Optional event types to include. Supported values: ${Vb}. 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:kw},required:["sequenceId"]}},{name:"list_email_metrics",description:"List per-email metrics across the account: one row per campaign and per sequence email step, each with its own delivery funnel, attributed conversions, and revenueCents. This is the tool for cross-sequence questions - 'how many Email 4s went out across these sequences' is one call with step=4 plus the returned totals, instead of one get_sequence_stats per sequence. Sequence rows carry sequenceId, sequenceName, automationNodeId, and step, so you can group or compare steps yourself. Counts come from the retained event stream (not the 14-day list_email_sends history) and match get_sequence_stats steps[] for the same step. Filter by emailType, sequenceId, campaignId, and step; sort with sort/order; page with page/limit. totals covers every matching email, not just the current page.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},emailType:{type:"string",description:"Optional email type: campaign or sequence. Defaults to both. Implied as sequence when sequenceId or step is set."},sequenceId:{type:"array",description:"Optional sequence IDs to restrict the breakdown to. Omit for every sequence in the account. Cannot be combined with campaignId.",items:{type:"string"}},campaignId:{type:"array",description:"Optional campaign IDs to restrict the breakdown to. Cannot be combined with sequenceId, step, or emailType sequence.",items:{type:"string"}},step:{type:"number",description:"Optional 1-based email step position to keep, counted in graph order per sequence. step 4 keeps only the fourth email of each sequence. Sequence emails only."},period:{type:"string",description:"Optional sliding window: 1h, 24h, 7d, 30d, or 90d. Ignored when start and end are provided. Omit for all-time counts."},start:{type:"string",description:"Optional ISO 8601 custom range start. Must be provided with end."},end:{type:"string",description:"Optional ISO 8601 custom range end. Must be provided with start; maximum range is 90 days. Omit start and end for all-time counts over the full retained window."},sort:{type:"string",description:"Sort field: sent, delivered, opened, clicked, openRate, clickRate, unsubscribed, conversions, revenue, step, or name. Defaults to sent."},order:{type:"string",description:"Sort order: asc or desc. Defaults to desc."},page:{type:"number",description:"Page number, starting at 1. Defaults to 1."},limit:{type:"number",description:"Emails per page. Defaults to 50; maximum 500."},includeMachineEngagement:kw}}},{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:kw},required:[]}}];var c5=[{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 m5=[{name:"list_campaigns",description:"List campaigns. Each item carries `emailPreset`, the linked email's Style > Format (branded or minimal; null for SMS campaigns and standalone raw HTML emails), so chrome can be compared across campaigns without one get_campaign call each. Results are paginated: the default page size is 50 and limit is capped at 100. Always read the returned `pagination` object (`limit`, `offset`, `count`, `total`, `hasMore`) and keep paging with `offset` while `hasMore` is true - a single call does not necessarily return every campaign.",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, sending, cancelled, paused, waiting_approval, or rejected). Rejected campaign results include rejectionComment feedback when provided."},label:{type:"string",description:"Optional label name filter. Only campaigns assigned this label are returned."},limit:{type:"number",description:"Page size from 1 to 100. Defaults to 50."},offset:{type:"number",description:"Zero-based result offset. Defaults to 0."}}}},{name:"get_campaign",description:"Get campaign details and stats, including rejectionComment reviewer feedback for rejected campaigns. `emailId` is the campaign's linked email body - the same record returned by the templates tools - and can be passed as templateId to create_campaign to reuse the design; it is null for SMS campaigns. `emailPreset` reports that email's Style > Format the same way get_sequence does per step (branded or minimal; null for SMS campaigns and standalone raw HTML emails), so campaign chrome can be compared against sequence steps and transactional templates without rendering them - minimal suppresses the company logo at render time. `targetLists` holds the raw audience targeting (IDs only); call get_campaign_audience for resolved list/segment names and a recipient count. Note that `computedLists` is email personalization (product lists rendered inside the email), not audience targeting.",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_campaign_audience",description:"Resolve exactly who a campaign will reach. Returns the targeting kind, resolved list and segment names (flagging references that no longer exist), filter conditions, individual include/exclude adjustments, a plain-language summary, and a live recipient count. Critically, it reports whether targeting is unset - an unset campaign falls back to every active subscriber when scheduled. Use this to verify a scheduled campaign's audience before it sends.",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:"list_email_sends",description:"List and filter the recent sent-email delivery history shown in the dashboard. Search subject/title or recipient, filter by delivery status, email type, bounce type, or source ID, then pass a returned emailSendId to get_email_send for exact open/click timestamps and the complete event timeline. Each row carries recipientEmail, subscriberId, automationNodeId, abTestVariantId, and sent/delivered/opened/clicked timestamps, so rows join into a recipient-level delivery matrix without re-reading the raw event stream. Pass automationNodeId to list only the recipients of one sequence step. Delivery rows are retained for 14 days, so this is the wrong tool for send totals: read get_sequence_stats steps[] or list_email_metrics, which cover the full retained event window.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},search:{type:"string",description:"Case-insensitive search across subject and recipient email."},subject:{type:"string",description:"Case-insensitive subject/title filter."},recipient:{type:"string",description:"Case-insensitive recipient email filter."},status:{type:"string",description:"Delivery status: pending, sent, delivered, opened, clicked, bounced, complained, failed, or suppressed. Opened includes clicked deliveries, matching the dashboard."},emailType:{type:"string",description:"Email type: campaign, transactional, or sequence."},bounceType:{type:"string",description:"Bounce type: Permanent or Transient."},campaignId:{type:"string",description:"Filter deliveries from one campaign."},transactionalEmailId:{type:"string",description:"Filter deliveries from one saved transactional email."},automationId:{type:"string",description:"Filter deliveries from one sequence/automation."},automationNodeId:{type:"string",description:"Filter deliveries from one email step of a sequence, using the nodeId from get_sequence_stats steps[] or get_sequence nodes."},days:{type:"number",description:"History window in days, from 1 to 14. Defaults to 14."},page:{type:"number",description:"Page number starting at 1. Defaults to 1."},limit:{type:"number",description:"Results per page, from 1 to 100. Defaults to 20."},sortField:{type:"string",description:"Sort field: recipientEmail, subject, status, eventAt, sentAt, or createdAt. Defaults to createdAt."},sortOrder:{type:"string",description:"Sort order: asc or desc. Defaults to desc."}}}},{name:"get_email_send",description:"Get an email delivery by emailSendId, including queued and test sends, delivery status, provider failure reason, stored HTML, effective Reply-To, copied-recipient identity and primary email send ID, and the ClickHouse event timeline. `type` is the legacy source category; use `emailType` on the send and `deliveryPolicy` on events for the actual marketing or transactional policy when known. Queue jobs are internal execution details and are not exposed.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},emailSendId:{type:"string",description:"Durable email delivery ID to inspect."}},required:["emailSendId"]}},{name:"create_campaign",description:"Create a new campaign. Omit all content fields to create an empty draft. For net-new natural-language content use `prompt`; do not author HTML or blocks. `blocks` are finished caller-supplied Sequenzy content and `html` is preserved/imported markup. Defaults to draft; status 'sent' only archives an already-sent campaign.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the campaign in. If not provided, uses the currently selected company."},name:{type:"string",description:"Campaign name"},subject:{type:"string",description:"Email subject line. Optional when `prompt` is provided because the generated subject will be used."},previewText:{type:["string","null"],description:"Email preview text. Optional when `prompt` is provided because the generated preview text will be used."},trackingCode:{type:"string",description:"Optional campaign tracking code for UTM templates. Use only when explicitly requested."},status:{type:"string",description:"Initial status: draft or sent. Defaults to draft. Use sent only for imported/already-sent campaigns; it does not send email or create delivery history."},sentAt:{type:"string",description:"ISO date-time for an imported/already-sent campaign. Only valid when status is sent; defaults to now if omitted."},html:{type:"string",description:`Email HTML content. Mutually exclusive with \`blocks\`. Use this for imported provider campaigns. ${Hw}`},blocks:{type:"array",description:A1,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:"Shorthand for targeting one saved segment. Equivalent to targetLists {type:'segment', segmentId}. Mutually exclusive with `targetLists`."},targetLists:{type:"object",description:"Campaign audience, saved on the draft. Omit to leave targeting unset and set it later with `update_campaign` or `schedule_campaign`. 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']}]}. Use this to send straight to a list without creating a segment first. Mutually exclusive with `segmentId`.",additionalProperties:!0},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:g1},senderProfileId:{type:"string",description:"Existing sender profile ID (see list_sender_profiles). It already supplies both the From address and display name, so send it on its own and omit fromEmail and fromName."},replyTo:{type:"string",description:"Reply-To address for this campaign. A reply profile is created when needed."},replyToName:{type:"string",description:i1},replyProfileId:{type:"string",description:"Existing reply profile ID (see list_sender_profiles). It already supplies both the Reply-To address and display name, so send it on its own and omit replyTo and replyToName."},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. ${Hw}`},blocks:{type:"array",description:A1,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 (see list_sender_profiles). It already supplies both the Reply-To address and display name, so send it on its own and omit replyTo and replyToName."},replyToName:{type:"string",description:i1},fromEmail:{type:"string",description:"Set this campaign's From address. Its domain must be configured and verified."},fromName:{type:"string",description:g1},senderProfileId:{type:"string",description:"Set an existing sender profile (see list_sender_profiles). It already supplies both the From address and display name, so send it on its own and omit fromEmail and fromName."},ccEmails:{type:["array","null"],description:"Addresses CC'd on every recipient's campaign email (max 10). Send an empty array or null to clear them; omit to leave unchanged.",items:{type:"string"},maxItems:10},bccEmails:{type:["array","null"],description:"Addresses BCC'd on every recipient's campaign email (max 10). Send an empty array or null to clear them; omit to leave unchanged.",items:{type:"string"},maxItems:10},campaignData:{type:"object",description:"Set campaign-scoped JSON data for repeat blocks and personalization."},computedLists:{type:"array",description:"Set computed list definitions derived from campaignData at send time.",items:{type:"object"}},targetLists:{type:["object","null"],description:"Replace the draft's saved audience, using the same shapes as `create_campaign`. Send null to clear it and choose the audience in `schedule_campaign` instead; omit to leave it unchanged. Mutually exclusive with `segmentId`.",additionalProperties:!0},segmentId:{type:"string",description:"Shorthand for retargeting the draft at one saved segment. Equivalent to targetLists {type:'segment', segmentId}. Mutually exclusive with `targetLists`."},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, as a one-off send or on a repeating weekly/monthly cadence via `recurringInterval`. Use `recurringInterval` for newsletters that go out on a fixed schedule instead of creating one campaign per issue. Returns dashboard edit and preview URLs.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"},scheduledAt:{type:"string",description:"Future ISO 8601 timestamp for the send, for example 2026-06-01T14:00:00Z."},targetLists:{type:"object",description:"Optional campaign targeting object. Omit to use saved targeting or all active subscribers. Examples: {type:'all'}, {type:'lists', listIds:['list_123']}, {type:'segment', segmentId:'seg_123'}, {type:'filtered', filters:[...], filterJoinOperator:'and'}, or {type:'rules', include:[{type:'lists', listIds:['list_123']}], exclude:[{type:'segments', segmentIds:['seg_123']}]}. Rules audiences require at least one include rule.",additionalProperties:!0},sendTimeOptimization:{type:"boolean",description:"Whether to use send-time optimization."},spreadOverHours:{type:"number",description:"Spread delivery over an integer number of hours from 1 to 72. When set, spread delivery takes precedence over send-time optimization."},recurringInterval:{type:"string",enum:["weekly","monthly"],description:"Repeat this campaign on a cadence starting at scheduledAt. The campaign becomes a recurring template: each run is duplicated and sent automatically, re-evaluating audience membership every time. Omit for a one-shot send; scheduling again without it stops the recurrence."}},required:["campaignId","scheduledAt"],additionalProperties:!1}},{name:"send_test_email",description:"Queue a campaign test email to a single address. Returns a durable emailSendId; pass it to get_email_send for delivery status and failure details.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to test"},to:{type:"string",description:"Email address to send test to"}},required:["campaignId","to"]}},{name:"unschedule_campaign",description:"Return a scheduled campaign to an editable draft. Removes its pending send and recurrence without permanently cancelling it, so it can be edited and scheduled again.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Scheduled campaign ID to return to draft."}},required:["campaignId"],additionalProperties:!1}},{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 l5=[{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 g5=[{name:"list_forms",description:"List saved signup forms for a company, including their server-managed audience settings and public action URLs.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list forms for. If not provided, uses the currently selected company."}},additionalProperties:!1}},{name:"create_form",description:"Create and publish a saved signup form whose opaque formId is a client-safe public capability. The selected lists, tags, duplicate behavior, and success action stay server-side; no API key is needed in the deployed form. This creates the email/name fields only - add typed custom fields (select, textarea, hidden, ...) afterwards with update_form's blocks argument.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the form in. If not provided, uses the currently selected company."},name:{type:"string",description:"Internal saved-form name."},listIds:{type:"array",description:"One or more list IDs that every public submission will be added to. Use list_lists to resolve IDs.",items:{type:"string"}},tagIds:{type:"array",description:"Optional existing tag IDs applied by the saved form. Use list_tags to resolve IDs.",items:{type:"string"}},duplicateStrategy:{type:"string",enum:["skip","merge","overwrite"],description:"How to handle an existing subscriber. Defaults to skip."},buttonText:{type:"string",description:"Optional submit button label."},headline:{type:"string",description:"Optional form headline."},description:{type:"string",description:"Optional supporting form copy."},successMessage:{type:"string",description:"Confirmation shown after a successful submission when redirectUrl is omitted."},redirectUrl:{type:"string",description:"Optional HTTP or HTTPS URL for successful submissions. Omit it to show the saved confirmation message."},showFirstName:{type:"boolean",description:"Whether the generated form also collects first name."},showLastName:{type:"boolean",description:"Whether the generated form also collects last name."},theme:{type:"object",description:"Optional visual theme overrides so the form matches the brand instead of the default accent. Any subset of: accentColor, backgroundColor, textColor, mutedTextColor, cardColor, borderColor (all #rrggbb), borderRadius (0-32), headingFontFamily, bodyFontFamily, density (compact | balanced | spacious).",additionalProperties:!0}},required:["name","listIds"],additionalProperties:!1}},{name:"update_form",description:"Update a saved signup form: rename it, retarget its audience, edit its copy, restyle its theme, or replace its content blocks (for example to remove unwanted blocks that render publicly). Read the current content via list_forms first when editing blocks.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},formId:{type:"string",description:"Saved form ID returned by list_forms or create_form."},name:{type:"string",description:"New internal saved-form name."},listIds:{type:"array",description:"Replacement list targeting. Every public submission will be added to these lists.",items:{type:"string"}},tagIds:{type:"array",description:"Replacement tag IDs applied by the saved form. Pass an empty array to clear tags.",items:{type:"string"}},duplicateStrategy:{type:"string",enum:["skip","merge","overwrite"],description:"How to handle an existing subscriber."},headline:{type:"string",description:"New text for the form's first heading block. Fails if the form has no heading block; edit blocks instead."},description:{type:"string",description:"New text for the form's first paragraph block. Fails if the form has no paragraph block; edit blocks instead."},buttonText:{type:"string",description:"New submit button label."},successMessage:{type:"string",description:"New confirmation message on the success screen."},redirectUrl:{type:"string",description:"HTTP or HTTPS URL for successful submissions. Pass an empty string to switch back to the confirmation message."},theme:{type:"object",description:"Visual theme overrides merged into the current theme. Any subset of: accentColor, backgroundColor, textColor, mutedTextColor, cardColor, borderColor (all #rrggbb), borderRadius (0-32), headingFontFamily, bodyFontFamily, density (compact | balanced | spacious).",additionalProperties:!0},blocks:{type:"array",description:`Full replacement for the form's content blocks. Fetch the current blocks from list_forms, modify them, and send the complete array - the form must keep exactly one required email field and one submit button. Blocks render in array order; every block needs a unique "id" and a "kind", and "sectionId" ("success" or "error") moves a content block into that screen. Input blocks are kind "form-field": { id, kind: "form-field", fieldType, name, label, placeholder, required, defaultValue, showLabel, width ("full" | "half"), mapsTo, options }. fieldType is one of text, email, phone, number, textarea, select, radio, checkbox, consent, hidden. mapsTo is one of email, firstName, lastName, phone, customAttribute and defaults to customAttribute, which stores the answer under the block's "name" as a subscriber custom attribute (name must start with a letter and may contain letters, digits, "_", ".", "-"). select, radio, and checkbox fields require options: [{ value, label, id }] - label and id default to value when omitted. A hidden field with a defaultValue always stores that server-owned value and ignores whatever the page posts; a hidden field with an empty defaultValue stores the value the page submits. Other kinds: heading, text, image, button, divider, spacer, custom-html, feature-grid, testimonial, countdown, form-step, submit-button, success-screen, error-state. Validation errors name the offending property, for example "blocks[3].options[0].value".`,items:{type:"object",additionalProperties:!0}}},required:["formId"],additionalProperties:!1}},{name:"get_form_embed",description:"Get a published saved form's action URL, one-line JavaScript embed, minimal native form action, and fetch example. Use this for Astro, Hugo, Jekyll, Cloudflare Pages, Netlify, GitHub Pages, or any browser integration.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},formId:{type:"string",description:"Saved form ID returned by list_forms or create_form."}},required:["formId"],additionalProperties:!1}}];var i5=[{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 n5=[{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 p5=[{name:"connect_integration",description:"Connect an API-key / webhook-secret integration: polar, paddle, dodo, whop, creem, chargebee, clerk, posthog, or affonso. Check list_integration_capabilities first - each connectable provider lists its exact connectFields there. Credentials are validated against the provider where possible, stored encrypted, and never returned; payment providers queue their initial revenue backfill automatically. The response includes the webhookUrl the user must configure at the provider with the same secret - always relay it. Reconnecting an already-connected provider replaces its stored credentials. OAuth and app-install providers (Stripe, Shopify, Supabase, GitHub, WooCommerce, Meta) are rejected with guidance: their flows need a human in the dashboard. SECURITY: only pass credentials the user explicitly provided for this purpose; suggest the CLI (`sequenzy integrations connect`) or dashboard when the user prefers keeping secrets out of the conversation.",inputSchema:{type:"object",properties:{provider:{type:"string",description:"Provider to connect: polar, paddle, dodo, whop, creem, chargebee, clerk, posthog, or affonso.",enum:["polar","paddle","dodo","whop","creem","chargebee","clerk","posthog","affonso"]},apiKey:{type:"string",description:"Provider API key. Required for every provider except clerk and posthog."},webhookSecret:{type:"string",description:"Signing secret of the webhook you create at the provider, pointed at the returned webhookUrl. Required for every provider. For Chargebee, pass the webhook's basic-auth credentials as username:password."},providerAccountId:{type:"string",description:"Provider account id, required for paddle (seller ID), dodo (business ID), whop (company ID, biz_...), creem (store ID), and chargebee (site name). Polar resolves it from the API key; clerk, posthog, and affonso do not use one."},settings:{type:"object",description:"PostHog only: event delivery scope. Defaults to syncing all non-internal events.",properties:{syncAllEvents:{type:"boolean",description:"Sync every event PostHog delivers."},eventAllowlist:{type:"array",items:{type:"string"},description:"Only sync these PostHog event names. Set syncAllEvents to false when using this."}}},historyImport:{type:"object",description:"PostHog only: import the project's event history after connecting. Needs a personal API key with query read access.",properties:{region:{type:"string",enum:["us","eu"],description:"PostHog Cloud region hosting the project."},projectId:{type:"string",description:"Numeric PostHog project ID."},personalApiKey:{type:"string",description:"PostHog personal API key (phx_...)."}},required:["region","projectId","personalApiKey"]},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},required:["provider","webhookSecret"]}},{name:"get_integration",description:"Inspect one connected integration in depth: what the provider syncs, every event it can emit and when, every matching tag rule, which sequences trigger on those events, recent integration-specific activity, and prioritized recommendations. `observedByAccount` and `accountLastSeenAt` are account-wide because event definitions can also be updated by another integration or the public events API; use the retained activity log for connection-specific delivery diagnosis. Read-only; credentials are never returned. Get the id from list_integrations.",inputSchema:{type:"object",properties:{integrationId:{type:"string",description:"Integration ID from list_integrations."},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},required:["integrationId"]}},{name:"list_integration_capabilities",description:"Describe what Sequenzy's integration providers do, whether or not they are connected. For each provider: category, how it connects, what it syncs, every event it emits with the real-world moment that triggers it, the subscriber attributes it writes, supported actions, availability, and caveats. Use this to answer 'what would connecting Stripe give me?', to compare providers before recommending one, or to check whether an event a sequence needs actually exists for that provider. Coverage differs sharply between providers - only Shopify has storefront browse tracking, and only Stripe and Chargebee cover the full trial lifecycle - so check here rather than assuming.",inputSchema:{type:"object",properties:{provider:{type:"string",description:"Only return this provider, for example `stripe`, `shopify`, `clerk`. Omit to list every provider."},category:{type:"string",description:"Filter by category: payments, ecommerce, auth, analytics, ads, affiliate, cms, developer."},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"list_integration_activity",description:"Read recent integration webhook and sync activity, newest first. This is the log to check when an integration reports connected but contacts or events are not appearing: each row carries the action, status, event type, matched contact, and error. Payloads are sanitized at write time, so no credentials or secrets appear here. Activity is retained for 24 hours only.",inputSchema:{type:"object",properties:{integrationId:{type:"string",description:"Only show activity for this integration."},provider:{type:"string",description:"Only show activity for this provider, for example `stripe`."},status:{type:"string",description:"Filter by status: received, queued, processed, skipped, or failed. Use `failed` to triage a broken integration.",enum:["received","queued","processed","skipped","failed"]},limit:{type:"number",description:"Rows to return, 1-100. Defaults to 25."},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"set_integration_sync_enabled",description:"Turn a supported payment integration's future bulk imports and backfills on or off. Check get_integration.availableActions first; providers without enable_sync or disable_sync are dashboard-managed. Disabling keeps the connection, credentials, and live webhook delivery active, and requires any in-flight sync to finish first. It does not disconnect the integration. Idempotent: setting the current state succeeds with `changed: false`.",inputSchema:{type:"object",properties:{integrationId:{type:"string",description:"Integration ID from list_integrations."},syncEnabled:{type:"boolean",description:"True to enable sync, false to pause it."},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},required:["integrationId","syncEnabled"]}},{name:"get_integration_pixel",description:"Check whether a Shopify store's storefront tracking pixel is installed and reporting to this account. Read live from Shopify on every call, because a merchant can remove the pixel without Sequenzy hearing about it. ALWAYS check this before promising that browse abandonment, cart recovery, product views, collection views, or storefront search will work: without a live pixel those events never arrive, the sequences built on them never fire, and nothing anywhere reports an error. Returns `pixel.healthy`, the endpoint and signed configuration state, and `dependentEvents` - the event names that rely on this pixel. When `pixel.error` is null and `pixel.healthy` is false, those events are confirmed dark; an error means Shopify could not confirm their state. Fix a confirmed unhealthy state with activate_integration_pixel. Shopify only; other providers return a clear error.",inputSchema:{type:"object",properties:{integrationId:{type:"string",description:"Shopify integration ID from list_integrations or get_integration."},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},required:["integrationId"]}},{name:"activate_integration_pixel",description:"Install the Shopify storefront tracking pixel on the connected store, or repoint an existing one at this account. This is what turns on product views, cart activity, and browse abandonment - the data every browse-abandonment and cart-recovery sequence depends on. Idempotent: an already-live pixel returns `changed: false`. Events start flowing on the next storefront visit and nothing is backfilled for the period the pixel was off, so run it before, not after, building the sequence. If the store granted an older permission set, this fails with a message naming the reconnect step rather than silently doing nothing. Shopify only.",inputSchema:{type:"object",properties:{integrationId:{type:"string",description:"Shopify integration ID from list_integrations or get_integration."},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},required:["integrationId"]}},{name:"sync_integration",description:"Queue a manual re-sync of customers and revenue for a payment provider integration (Stripe, Polar, Paddle, Dodo, Creem, Chargebee, Whop). Returns immediately - poll get_integration to watch `syncStatus` and `lastSyncAt`. Fails with a conflict if a sync is already running, and with a clear error naming the dashboard for providers whose backfill is not API-triggerable (Shopify products, Supabase users, PostHog history, Affonso affiliates). Check `availableActions` on get_integration to see whether this is supported before calling.",inputSchema:{type:"object",properties:{integrationId:{type:"string",description:"Integration ID from list_integrations."},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},required:["integrationId"]}}];var d5=[{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:dH},content:{type:"object",description:Zb,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:Zb,additionalProperties:!0}},required:["landingPageId"],additionalProperties:!1}},{name:"duplicate_landing_page",description:"Duplicate a landing page. The copy is created as a draft with its own slug and stats, so the original keeps its published URL.",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 to duplicate."},name:{type:"string",description:"Optional name for the copy. Defaults to the original name with a (copy) suffix."},slug:{type:"string",description:"Optional slug for the copy. It will be normalized and made unique within the company."}},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:Zb,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:Zb,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 o5=[{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. Returns one page: check pagination.total and pagination.hasMore, and page with offset to read the whole catalog.",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."},limit:{type:"number",description:"Maximum products to return (1-100). Defaults to 50. Compare pagination.total against the products returned to detect truncation."},offset:{type:"number",description:"Number of products to skip. Defaults to 0. Use with limit to page through catalogs larger than 100."}}}},{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."},providerCreatedAt:{type:["string","null"],description:"ISO 8601 creation time from the source catalog. Omit to preserve the stored value; pass null to clear it. Used for newest-product ranking."}},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 with bulk sync enabled. Pass integrationId when more than one Stripe account is connected; otherwise the most recently connected enabled account is used.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},integrationId:{type:"string",description:"Stripe integration ID from list_integrations. Recommended when multiple Stripe accounts are connected."}}}}];var t5=[{name:"render_email",description:"Render a campaign, sequence email step, or template to the exact email-safe HTML that would be sent, for embedding a visual preview in an external builder or dashboard, or for checking merge tags before anyone is enrolled. Pass exactly one target: campaignId, sequenceId plus nodeId, or templateId. Without a subscriber the email renders for a sample contact, so contact-specific merge tags resolve to empty values. Check unresolvedMergeTags in the response to tell an unrecognized tag apart from one that is merely blank for this contact - both render as an empty string, so the HTML alone cannot distinguish them. Only names this render could check are called unknown. Nothing is checkable without the contact's attributes, because a bare {{plan}} reads the same attribute map as {{subscriber.plan}}, so pass subscriberId (or an inline subscriber with customAttributes) to catch typos at all. On top of that, {{event.*}} needs sample event properties in variables, since a real send fills those from the enrolling event, and {{recommendedProducts.*}} is only checkable when a stored subscriberId returns recommendations. Rendering a transactional email is checkable only when variables is passed, since its tags come from the variables of each send call and nothing marks them as such. An optional attribute this contact never had set is kept out of unknown by checking the names other contacts in the account carry, which needs the subscribers:read scope. A sequence step downstream of a create_discount step renders {{discount.*}} with that step's real terms and a clearly fake sample code; when the step is reachable by paths that do not all run the same discount step, or when a template is rendered on its own, {{discount.*}} is reported as no_value rather than as a typo. Links stay clean unless tracking is true. Per-send click redirects and the open pixel are added at send time against a real email send record, so they never appear here.",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 render."},sequenceId:{type:"string",description:"Sequence ID. Requires nodeId."},nodeId:{type:"string",description:"Email step node ID from get_sequence. Requires sequenceId."},templateId:{type:"string",description:"Template ID to render."},subscriberId:{type:"string",description:"Personalize as this stored subscriber. Mutually exclusive with subscriber. The rendered HTML then carries that subscriber's details, so this needs the subscribers:read scope as well."},subscriber:{type:"object",description:"Personalize as an ad-hoc contact that need not exist in the account. Mutually exclusive with subscriberId.",properties:{email:{type:"string",description:"Contact email address."},firstName:{type:"string",description:"Contact first name."},lastName:{type:"string",description:"Contact last name."},customAttributes:{type:"object",description:"Custom attributes used by merge tags and blocks.",additionalProperties:!0}},required:["email"]},variables:{type:"object",description:"Extra merge variables layered over the contact's attributes.",additionalProperties:!0},locale:{type:"string",description:"Force a localization locale instead of deriving it from the contact."},variantId:{type:"string",description:"Render a specific A/B test variant of the campaign or sequence step."},tracking:{type:"boolean",description:"Apply the company's auto-UTM link decoration as a real send would. Defaults to false so the preview shows the author's clean URLs."}},required:[]}}];var Y4={companyId:{type:"string",description:"Company ID. If omitted, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID."}},r5={name:{type:"string",description:"Goal name."},description:{type:["string","null"],description:"Optional goal description."},triggerType:{type:"string",enum:["event","attribute_change"],description:"Conversion signal type. Defaults to event when creating."},triggerEventName:{type:["string","null"],description:"Required event name for event goals."},attributePath:{type:["string","null"],description:"Subscriber attribute path required for attribute_change goals."},attributeCondition:{type:["string","null"],enum:["changed","changed_to","changed_from_to",null],description:"How the subscriber attribute must change."},attributeValue:{type:["string","null"],description:"Target value for changed_to or changed_from_to."},attributePreviousValue:{type:["string","null"],description:"Previous value required for changed_from_to."},eventPropertyName:{type:["string","null"],description:"Optional event property whose numeric value is tracked."},eventPropertyLabel:{type:["string","null"],description:"Display label for the tracked event property."},attributionWindowHours:{type:"integer",minimum:1,maximum:720,description:"Attribution window in whole hours."},isActive:{type:"boolean",description:"Whether conversion tracking is active for this goal. Defaults to true when creating."}},s5=[{name:"list_sequence_goals",description:"List persisted conversion goals attached to one sequence in the dashboard.",inputSchema:{type:"object",properties:Y4,required:["sequenceId"],additionalProperties:!1}},{name:"create_sequence_goal",description:"Create a persisted event or subscriber-attribute conversion goal for one sequence. Event goals (the default triggerType) require triggerEventName; attribute_change goals require attributePath. This is distinct from create_sequence.goal, which is only an AI content prompt.",inputSchema:{type:"object",properties:{...Y4,...r5},required:["sequenceId","name"],additionalProperties:!1}},{name:"update_sequence_goal",description:"Update a persisted sequence conversion goal, including its signal, attribution window, or active state.",inputSchema:{type:"object",properties:{...Y4,goalId:{type:"string",description:"Sequence goal ID."},...r5},required:["sequenceId","goalId"],additionalProperties:!1}},{name:"delete_sequence_goal",description:"Delete one persisted sequence conversion goal.",inputSchema:{type:"object",properties:{...Y4,goalId:{type:"string",description:"Sequence goal ID."}},required:["sequenceId","goalId"],additionalProperties:!1}}];var XW={companyId:{type:"string",description:"Company ID. If omitted, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence with an inbound_webhook trigger."}},e5=[{name:"get_sequence_inbound_webhook",description:"Read the usable URL, mapping, sample payload, and setup status for a sequence inbound webhook.",inputSchema:{type:"object",properties:XW,required:["sequenceId"],additionalProperties:!1}},{name:"configure_sequence_inbound_webhook",description:"Create or update the secret endpoint attached to a sequence inbound_webhook trigger. On first setup, omitted mapping/sample inputs apply the selected catalog or custom integration defaults; on later calls, omitted inputs keep the saved values, so a captured sample survives mapping-only updates. Use clearFieldMapping to return to pending setup and clearSamplePayload to drop the saved sample.",inputSchema:{type:"object",properties:{...XW,fieldMapping:{type:"object",properties:{email:{type:"string"},firstName:{type:"string"},lastName:{type:"string"},properties:{type:"object",additionalProperties:{type:"string"}}},required:["email"],additionalProperties:!1},samplePayload:{type:"object",description:"Representative raw webhook payload for mapping setup.",additionalProperties:!0},clearFieldMapping:{type:"boolean",description:"Set true to clear the saved mapping and return the endpoint to pending_setup."},clearSamplePayload:{type:"boolean",description:"Set true to clear the saved sample payload."}},required:["sequenceId"],additionalProperties:!1}},{name:"rotate_sequence_inbound_webhook_secret",description:"Rotate the inbound webhook secret and return a new URL. The previous URL stops working immediately.",inputSchema:{type:"object",properties:XW,required:["sequenceId"],additionalProperties:!1}}];var a5=[{name:"list_sequences",description:"List all email sequences (automations). Read effectiveStatus (draft, live, enrollment_paused, paused, archived) to know whether a sequence is running: status alone reads `active` even when new enrollments are paused, and the legacy triggerConfig.active flag is not used by the runtime.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list sequences for. If not provided, uses the currently selected company."},status:{type:"string",enum:["draft","active","paused","archived"],description:"Optional dashboard status filter."},search:{type:"string",description:"Case-insensitive search across sequence name and description."},labels:{type:"array",items:{type:"string"},description:"Return sequences assigned any of these dashboard label names."},limit:{type:"number",description:"Page size from 1 to 100. When limit and offset are both omitted, every sequence is returned."},offset:{type:"number",description:"Zero-based result offset."}}}},{name:"get_sequence",description:"Get sequence details, editable step content, and graph topology. Read effectiveStatus (draft, live, enrollment_paused, paused, archived) to know whether a sequence is running: status alone reads `active` even when new enrollments are paused, and the legacy triggerConfig.active flag is not used by the runtime. 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, emailPreset (the per-email Style > Format for native blocks, including emails with supported custom HTML blocks; null when the entire email is standalone raw HTML), 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:"list_sequence_enrollments",description:"List the individual contacts currently enrolled in a sequence, with the node each one is sitting on. Use this when get_sequence_stats gives you enrollmentCounts and you need the actual subscribers behind a number, such as everyone waiting at one step. Filter by currentNodeId (take the ID from get_sequence_stats enrollmentCounts.byCurrentNode or get_sequence nodes), status, subscriberId, or email, and page with limit/offset to export the full list.",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 listed."},currentNodeId:{type:"array",items:{type:"string"},description:"Only return enrollments currently sitting on these sequence node IDs."},status:{type:"array",items:{type:"string",enum:["active","waiting","completed","failed","cancelled"]},description:"Enrollment statuses to include. Defaults to active and waiting, which is every contact still moving through the sequence."},subscriberId:{type:"array",items:{type:"string"},description:"Only return enrollments for these subscriber IDs. Useful for checking where specific contacts stand."},email:{type:"string",description:"Only return enrollments for this exact email address (case-insensitive)."},sort:{type:"string",enum:["enrolled_at_desc","enrolled_at_asc","wait_until_asc","wait_until_desc"],description:"Result order. Defaults to enrolled_at_desc (most recently enrolled first). Use wait_until_asc to see who resumes next."},limit:{type:"number",description:"Enrollments per page, 1-500. Defaults to 50. Use the maximum when exporting."},offset:{type:"number",description:"Number of enrollments to skip. Page until pagination.hasMore is false."}},required:["sequenceId"],additionalProperties:!1}},{name:"send_sequence_test_email",description:"Queue a real test send for one saved email step in a sequence. Call get_sequence first and pass the target email step's nodeId. Accepts 1-10 reviewer email addresses and returns one durable emailSendId per recipient for get_email_send delivery inspection. The sequence is not enabled and no subscribers are enrolled.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID containing the saved email step."},nodeId:{type:"string",description:"Email step nodeId from get_sequence. The node must belong to sequenceId."},recipients:{type:"array",minItems:1,maxItems:10,items:{type:"string",format:"email"},description:"One to ten internal reviewer email addresses. Duplicate addresses are sent only once."}},required:["sequenceId","nodeId","recipients"],additionalProperties:!1}},{name:"create_sequence",description:"Create and persist a disabled draft email sequence, follow-up series, drip campaign, nurture flow, or automation workflow. For natural-language content, provide goal and emailCount. Use explicit steps for finished caller-supplied content, exact workflows, or migrations. Configure trigger plus its relevant field, such as listId, tagName, segmentId, or eventName. Supports email and SMS steps, delays and date waits, actions that dynamically create a provider discount/code (later emails print it with {{discount.code}}), subscriber updates, event filters, enrollment rules, sending windows, and stop conditions. The saved draft appears in list_sequences. Never call enable_sequence unless the user explicitly asks to activate it.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the sequence in. If not provided, uses the currently selected company."},fromEmail:{type:"string",description:"From address for all emails in this sequence. Its domain must be configured and verified."},fromName:{type:"string",description:g1},senderProfileId:{type:"string",description:"Existing sender profile ID (see list_sender_profiles). It already supplies both the From address and display name, so send it on its own and omit fromEmail and fromName."},replyTo:{type:"string",description:"Reply-To address for all emails in this sequence. A reply profile is created when needed."},replyToName:{type:"string",description:i1},replyProfileId:{type:"string",description:"Existing reply profile ID (see list_sender_profiles). It already supplies both the Reply-To address and display name, so send it on its own and omit replyTo and replyToName."},name:{type:"string",description:"Sequence name (e.g., 'User Onboarding', 'Welcome Series')"},description:{type:"string",description:"Optional sequence description shown in the dashboard."},userCancellable:{type:"boolean",description:"Whether subscribers may cancel their own active enrollment."},bccEmails:{type:"array",items:{type:"string"},description:"Email addresses blind-copied on every email in the sequence (max 10)."},labels:{type:"array",items:{type:"string"},description:"Dashboard label names to assign. Missing labels are created."},trigger:{type:"string",enum:["contact_added","tag_added","segment_entered","event_received","inbound_webhook","inactivity","frequency"],description:"Trigger type: contact_added, tag_added, segment_entered, event_received, inbound_webhook, inactivity, or frequency. Defaults to contact_added for a blank dashboard-compatible draft."},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."},stopOnSegmentExit:{type:"boolean",description:"For segment_entered triggers, cancel active enrollments when the contact leaves the segment."},eventName:{type:"string",description:"Event name to trigger on (required for event_received, inbound_webhook, inactivity, and frequency triggers)"},integrationSlug:{type:"string",description:"Catalog integration slug for inbound_webhook, for example cal-com."},integrationEventKey:{type:"string",description:"Catalog integration event key for inbound_webhook."},customIntegration:{type:"object",description:"Custom inbound webhook integration descriptor with name, setupInstructions, samplePayload, and fieldMapping.",properties:{name:{type:"string"},setupInstructions:{type:"string"},samplePayload:{type:"object",additionalProperties:!0},fieldMapping:{type:"object",additionalProperties:!0},docsUrl:{type:"string"},suggestedProperties:{type:"array",items:{type:"object",properties:{name:{type:"string"},path:{type:"string"},description:{type:"string"}},required:["name","path","description"]}}},required:["name","setupInstructions","samplePayload","fieldMapping"]},propertyFilters:{type:"array",description:"Optional filters for event_received or inbound_webhook triggers. The sequence starts only when all filters match. Max 10.",items:{type:"object",properties:{path:{type:"string",description:"Dot-path into the event properties, e.g. 'lineItems[].providerProductId' or 'plan'."},operator:{type:"string",enum:["exists","not_exists","equals","not_equals","one_of","contains","greater_than","less_than"],description:"Comparison operator. one_of matches when the property equals any entry of the value array."},value:{type:["string","number","boolean","array"],items:{type:["string","number"]},maxItems:50,description:"Value to compare against. Required for every operator except exists/not_exists. For one_of, pass an array of strings or numbers (max 50 values); all other operators take a single value."}},required:["path","operator"]}},inactiveDays:{type:"number",description:"Number of days of inactivity (required for inactivity trigger, must be >= 1)"},inactivityBaseline:{type:"string",enum:["sequence_created_at","subscriber_created_at"],description:"When to start counting inactivity for subscribers who never had the event. Defaults to sequence_created_at."},minCount:{type:"number",description:"Minimum event count (required for frequency trigger, must be >= 1)"},timeWindowDays:{type:"number",description:"Time window in days for frequency trigger (required for frequency trigger, must be >= 1)"},emailCount:{type:"number",description:"Number of emails in the sequence (default: 5, max: 10)"},durationDays:{type:"number",description:"Total duration in days used to space AI-generated sequence emails. Only applies when using goal-based AI generation."},emailStyle:{type:"string",enum:["visual","plain"],description:"Style for AI-generated emails: 'visual' (designed, with heroes/imagery/rich sections) or 'plain' (personal, text-first notes with a single button). Only applies to goal-based AI generation. Defaults to the company's saved preference when omitted."},goal:{type:"string",description:"What this sequence should accomplish for AI generation. Be specific to the app's actual features and user journey. Avoid generic goals that don't match the app's business model."},enrollmentMode:{type:"string",enum:["unlimited","one_time","matching_field"],description:"Sequence re-entry mode. Defaults to 'unlimited', which re-enrolls a subscriber every time the trigger fires again - for a tag_added drip that means re-applying the tag sends the whole series a second time, so set 'one_time' unless repeat runs are wanted. Exception: ecommerce.back_in_stock and ecommerce.replenishment_due triggers default to 'matching_field' so each product is notified separately; leave those alone unless the user asks otherwise. Use 'matching_field' only for event_received triggers when duplicate active runs should be blocked per event field value. Changeable later with update_sequence."},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:s6,stopCondition:{type:"object",description:"Optional explicit auto-stop condition, re-evaluated before every step including the first one. Use { type: 'has_tag', value: 'customer' } to end the sequence when a subscriber gets a tag, { type: 'entered_segment', value: 'segment_123' } when they enter a segment, { type: 'added_to_list', value: 'list_123' } when they join a list, { type: 'field_changed', value: 'plan' } when a subscriber field changes, { type: 'event_received', value: 'onboarding.completed' } when an event is tracked, or { type: 'none', value: null } for no auto-stop. The negative forms are audience guards rather than lifecycle stops: { type: 'does_not_have_tag', value: 'allowlist' } and { type: 'removed_from_list', value: 'list_123' } cancel the run before any step sends unless the subscriber carries that tag or list membership. That is how you restrict a live event or segment trigger to a chosen set of contacts without editing the graph, for example for a first pass on a production trigger or a phased rollout. Guarded-out contacts still enroll and are then cancelled at the trigger node, so they appear as cancellations there rather than in the active or waiting enrollment counts. Clearing the guard does not retry them: nothing re-enrolls them, so they only receive the sequence if the trigger fires for them again, which one-shot triggers never do, and on the one_time enrollment mode a repeated trigger is ignored too because enrollment is blocked by the existence of any earlier run rather than by its outcome. Guard a duplicate sequence and leave the real one ungated, or enroll the missed contacts afterwards with enroll_subscribers_in_sequence, which skips the one_time check.",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. has_tag, added_to_list, entered_segment, field_changed, and event_received stop the run once the thing happens. does_not_have_tag and removed_from_list stop the run whenever the subscriber lacks that tag or list membership, so they act as a required-tag or required-list allowlist for everyone the trigger enrolls."},value:{type:["string","null"],description:"Tag name, list ID, segment ID, field path, or event name for the stop condition. For the does_not_have_tag and removed_from_list guards this is the tag or list a subscriber must have to keep receiving the sequence. Use null or omit for type 'none'."},matchConfig:{type:["object","null"],description:"Optional dashboard-compatible match config: event_property with rules[{entryFieldPath,eventFieldPath}] for event_received, or field_value with operator/value for field_changed.",additionalProperties:!0}},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:Z0,subject:{type:"string",description:"Email subject. Required for email steps."},previewText:{type:"string",description:"Email preview text."},blocks:{type:"array",description:A0,items:{type:"object"}},html:{type:"string",description:`HTML content for email steps. Use this for imported provider HTML. ${Hw}`},isTransactional:{type:"boolean",description:"Send this email as transactional and omit the marketing unsubscribe footer."},ccEmails:{type:"array",items:{type:"string"},description:"Addresses CC'd on this email step."},bccEmails:{type:"array",items:{type:"string"},description:"Addresses BCC'd on this email step in addition to sequence BCC."},attachments:{type:"array",items:{type:"object",properties:{filename:{type:"string",description:"Filename shown in the recipient's email client. Event merge tags are supported, for example file-{{event.order_id}}.pdf."},path:{type:"string",description:"Public HTTPS URL or event-backed URL template such as {{event.file_url}}; resolved per enrollment and fetched at send time."}},required:["filename","path"]},description:"URL-backed file attachments for this email step (max 10, 7MB total per email). Paths may use {{event.*}} values from the event that enrolled the subscriber; the resolved public URL is validated and fetched at send time."},...jb,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:U0,delayMs:{type:"number",description:"Delay before this step in milliseconds. Prefer delay for readability; use delayMs when importing provider waits."},waitUntil:L0,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.${t6}`,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"]}}];var wz=[{name:"update_sequence",description:"Update an existing sequence: both its settings and its steps. Sequence-level settings live directly on this tool - name, description, labels, trigger (with its trigger-specific field), enrollmentMode plus enrollmentFieldPath, enrollmentPaused, userCancellable, stopCondition, sendingWindow, bccEmails, and the sender/reply identity. This is the only way to change enrollmentMode after create_sequence, so use it to move a tag- or event-triggered sequence off the default 'unlimited' re-entry to 'one_time' or 'matching_field'. 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. Deleting a step immediately moves parked recipients to its unique surviving successor, or completes them when no successor remains; inspect migratedRecipientCount and completedRecipientCount in the returned sequence. 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"},description:{type:"string",description:"Sequence description shown in the dashboard."},userCancellable:{type:"boolean",description:"Whether subscribers may cancel their own active enrollment."},labels:{type:"array",items:{type:"string"},description:"Replace dashboard labels by name. Missing labels are created; [] clears labels."},trigger:{type:"string",enum:["contact_added","tag_added","segment_entered","event_received","inbound_webhook","inactivity","frequency"],description:"Atomically replace the existing dashboard trigger. Include the fields required by the new trigger type. Active sequences also require confirmLiveChange:true."},listId:{type:"string",description:"List ID for a contact_added trigger replacement."},tagName:{type:"string",description:"Tag name required for a tag_added trigger replacement."},segmentId:{type:"string",description:"Saved segment ID required for a segment_entered trigger replacement."},stopOnSegmentExit:{type:"boolean",description:"For segment_entered, stop active enrollments when the subscriber leaves the segment."},eventName:{type:"string",description:"Event name required for event_received, inbound_webhook, inactivity, and frequency trigger replacements."},propertyFilters:{type:"array",description:"Optional event-property filters for event_received or inbound_webhook.",items:{type:"object",properties:{path:{type:"string"},operator:{type:"string",enum:["exists","not_exists","equals","not_equals","one_of","contains","greater_than","less_than"]},value:{description:"Scalar comparison value, or an array for one_of."}},required:["path","operator"],additionalProperties:!1}},integrationSlug:{type:"string",description:"Catalog integration slug for inbound_webhook."},integrationEventKey:{type:"string",description:"Catalog integration event key for inbound_webhook."},customIntegration:{type:"object",description:"Typed custom inbound webhook descriptor used instead of a catalog integration.",properties:{name:{type:"string"},setupInstructions:{type:"string"},samplePayload:{type:"object",additionalProperties:!0},fieldMapping:{type:"object",properties:{email:{type:"string"},firstName:{type:"string"},lastName:{type:"string"},properties:{type:"object",additionalProperties:{type:"string"}}},required:["email"],additionalProperties:!1},docsUrl:{type:"string"},suggestedProperties:{type:"array",items:{type:"object",properties:{name:{type:"string"},path:{type:"string"},description:{type:"string"}},required:["name","path","description"],additionalProperties:!1}}},required:["name","setupInstructions","samplePayload","fieldMapping"],additionalProperties:!1},inactiveDays:{type:"number",description:"Days without event activity required for an inactivity trigger."},inactivityBaseline:{type:"string",enum:["sequence_created_at","subscriber_created_at"],description:"Baseline for subscribers who have never produced the inactivity event."},minCount:{type:"number",description:"Minimum event count for a frequency trigger."},timeWindowDays:{type:"number",description:"Frequency trigger lookback window in days."},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:g1},senderProfileId:{type:"string",description:"Set an existing sender profile (see list_sender_profiles). It already supplies both the From address and display name, so send it on its own and omit fromEmail and fromName."},replyTo:{type:"string",description:"Set the Reply-To address for all emails in this sequence."},replyToName:{type:"string",description:i1},replyProfileId:{type:"string",description:"Set an existing reply profile (see list_sender_profiles). It already supplies both the Reply-To address and display name, so send it on its own and omit replyTo and replyToName."},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."},confirmLiveChange:{type:"boolean",description:"Set true only after the user explicitly confirms replacing the trigger of an active sequence. Required with trigger when the sequence is active."},enrollmentMode:{type:"string",enum:["unlimited","one_time","matching_field"],description:"Updated sequence re-entry mode. Use this to move an existing sequence off the default 'unlimited', which re-enrolls a subscriber every time the trigger fires again. '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:s6,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, which is re-evaluated before every step including the first one. 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: 'added_to_list', value: 'list_123' } to stop when they join a list, or { type: 'none', value: null } to clear it. The negative forms are audience guards rather than lifecycle stops: { type: 'does_not_have_tag', value: 'allowlist' } and { type: 'removed_from_list', value: 'list_123' } cancel the run before any step sends unless the subscriber carries that tag or list membership. That is how you restrict a live event or segment trigger to a chosen set of contacts without editing the graph, for example for a first pass on a production trigger or a phased rollout. Guarded-out contacts still enroll and are then cancelled at the trigger node, so they appear as cancellations there rather than in the active or waiting enrollment counts. Clearing the guard does not retry them: nothing re-enrolls them, so they only receive the sequence if the trigger fires for them again, which one-shot triggers never do, and on the one_time enrollment mode a repeated trigger is ignored too because enrollment is blocked by the existence of any earlier run rather than by its outcome. Guard a duplicate sequence and leave the real one ungated, or enroll the missed contacts afterwards with enroll_subscribers_in_sequence, which skips the one_time check.",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. has_tag, added_to_list, entered_segment, field_changed, and event_received stop the run once the thing happens. does_not_have_tag and removed_from_list stop the run whenever the subscriber lacks that tag or list membership, so they act as a required-tag or required-list allowlist for everyone the trigger enrolls."},value:{type:["string","null"],description:"Tag name, list ID, segment ID, field path, or event name for the stop condition. For the does_not_have_tag and removed_from_list guards this is the tag or list a subscriber must have to keep receiving the sequence."},matchConfig:{type:["object","null"],description:"Optional event_property or field_value match config used by dashboard stop-condition matching.",additionalProperties:!0}},required:["type"]},branch:{type:"object",description:"Insert an if/else branch into an existing sequence. Use get_sequence first to choose afterNodeId and existing target nodes. Each conditional path can provide new steps, targetNodeId, or both; the else path uses elseSteps and/or elseTargetNodeId. A target may be the completion node. Empty paths require allowEmptyPaths: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. Each path can create steps, route directly to an existing targetNodeId, or do both. An else fallback is created automatically.",items:t9},elseSteps:{type:"array",description:"Optional new steps inside the else fallback path.",items:qb},elseTargetNodeId:{type:"string",description:"Optional existing node to route the else path to. Use a node ID from get_sequence, including the completion node. If elseSteps are also provided, they run before this target."},allowEmptyPaths:{type:"boolean",description:"Set true only when intentionally creating UI placeholders. A path with targetNodeId is already explicit and does not need this flag."}},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:qb}},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 for imported provider markup. ${Hw}`},htmlContent:{type:"string",description:`Alias for html for imported provider markup. ${Hw}`},emailPreset:{type:"string",enum:["branded","minimal"],description:"Per-email Style > Format for native Sequenzy blocks, including emails that contain supported custom HTML blocks. Minimal removes the company logo and uses the simple footer; branded restores the branded chrome. Does not change the company default. Not a lossless toggle: minimal deletes standalone logo blocks, so switching back to branded generates a new logo block with a new id and the company name as alt text - send the authored logo block in `blocks` alongside the branded update to keep it. Not supported when the entire email is standalone raw HTML and must not be combined with html/htmlContent."},blocks:{type:"array",description:`${L1}${r6}`,items:{type:"object"}},isTransactional:{type:"boolean"},ccEmails:{type:"array",items:{type:"string"}},bccEmails:{type:"array",items:{type:"string"}},attachments:{type:"array",items:{type:"object",properties:{filename:{type:"string"},path:{type:"string"}},required:["filename","path"]},description:"URL-backed file attachments for this email step (max 10, 7MB total per email). path may be a public HTTPS URL or an {{event.*}} URL template resolved from the enrollment event at send time. Pass [] to remove all attachments."},...jb}}},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 for imported provider markup. ${Hw}`},htmlContent:{type:"string",description:`Alias for html. ${Hw}`},emailPreset:{type:"string",enum:["branded","minimal"],description:"Per-email Style > Format for native Sequenzy blocks, including emails that contain supported custom HTML blocks. Minimal removes the company logo and uses the simple footer; branded restores the branded chrome. Does not change the company default. Not a lossless toggle: minimal deletes standalone logo blocks, so switching back to branded generates a new logo block with a new id and the company name as alt text - send the authored logo block in `blocks` alongside the branded update to keep it. Not supported when the entire email is standalone raw HTML and must not be combined with html/htmlContent."},blocks:{type:"array",description:`${L1}${r6}`,items:{type:"object"}},isTransactional:{type:"boolean"},ccEmails:{type:"array",items:{type:"string"}},bccEmails:{type:"array",items:{type:"string"}},attachments:{type:"array",items:{type:"object",properties:{filename:{type:"string"},path:{type:"string"}},required:["filename","path"]},description:"URL-backed file attachments for this email step (max 10, 7MB total per email). path may be a public HTTPS URL or an {{event.*}} URL template resolved from the enrollment event at send time. Pass [] to remove all attachments."},...jb}}},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:Z0},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 } }. For a direct text-forward email, use changes:{ emailPreset:'minimal' } on its action_email node; this changes only that linked email's Style > Format. 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:e6.properties.nodeId,changes:h9,expectedUpdatedAt:e6.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 or setting several action_email nodes to changes:{ emailPreset:'minimal' } without changing the company theme. 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:e6},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; duplicate_node creates an independent copy; delete_node safely splices a node and immediately moves parked recipients to its unique surviving successor (or completes them when none remains); replace_edges replaces the complete topology. The returned sequence reports migratedRecipientCount and completedRecipientCount. 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."},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. 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 dashboard-compatible typed step into an existing sequence: email, SMS, delay/date wait, discount (later emails print the generated code with {{discount.code}}), subscriber update, tag/list action, outbound webhook, condition gate, wait-for-event, or wired If/Else branch. Use get_sequence first and pass afterNodeId. Branch paths can target existing nodes, including completion. For active sequences, confirm the structural change 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."},type:{type:"string",enum:["email","sms","delay","create_discount","update_subscriber","add_tag","remove_tag","add_to_list","remove_from_list","webhook","condition","logic_wait_for_event","logic_branch"],description:"Dashboard step type. Defaults to email."},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:A0,items:{type:"object"}},html:{type:"string",description:`HTML content for an imported provider step. Provide either html or blocks, not both. ${Hw}`},isTransactional:{type:"boolean",description:"Email only: omit the marketing unsubscribe footer."},ccEmails:{type:"array",items:{type:"string"},description:"Email only: addresses CC'd on this step."},bccEmails:{type:"array",items:{type:"string"},description:"Email only: addresses BCC'd in addition to sequence-level BCC."},attachments:{type:"array",items:{type:"object",properties:{filename:{type:"string"},path:{type:"string"}},required:["filename","path"]},description:"Email only: URL-backed file attachments (max 10, 7MB total per email). path may be a public HTTPS URL or an {{event.*}} URL template resolved from the enrollment event at send time."},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: Reply-To display name override for the new step. Requires replyTo; omit it when using replyProfileId, which already carries its own display name."},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:"Display label for SMS, wait-for-event, or branch steps."},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."},config:{...Z0,description:"update_subscriber only: typed subscriber profile/custom-attribute changes."},tagId:{type:"string",description:"Tag ID for tag actions or tag conditions."},tagName:{type:"string",description:"Tag name for tag actions or tag conditions; missing definitions are created."},listId:{type:"string",description:"List ID for list actions or in_list conditions."},listName:{type:"string",description:"Optional cached list display name for list actions."},url:{type:"string",description:"webhook only: destination HTTPS URL called when a subscriber reaches this step. Supports merge tags like {{email}} and {{event.order_id}}."},method:{type:"string",enum:["POST","GET","PUT","PATCH","DELETE"],description:"webhook only: HTTP method. Defaults to POST."},headers:{type:"object",description:"webhook only: optional string-valued request headers. Values support merge tags. Secret values are redacted on sequence reads.",additionalProperties:{type:"string"}},body:{type:"string",description:'webhook only: optional JSON body template for POST/PUT/PATCH. Must be valid JSON as written, with merge tags inside quoted string values ({"email": "{{email}}"}); a tag in a bare value position is rejected. Tags are resolved at execution time; when omitted, the default payload with subscriber and sequence context is sent.'},resultKey:{type:"string",description:"webhook only: when set, the HTTP response is saved and later email steps can reference it via {{webhooks.KEY.data.field}} merge tags. Must start with a letter; letters, numbers, underscores; max 64 chars."},onError:{type:"string",enum:["continue","exit","fail"],description:"webhook only: behavior when the request fails. continue proceeds to the next step, exit ends the sequence for the subscriber, fail marks the enrollment failed (default)."},segmentId:{type:"string",description:"Segment ID for in_segment conditions."},segmentName:{type:"string",description:"Optional cached segment display name."},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 only: condition evaluated before continuing."},linkUrl:{type:"string"},activityScope:{type:"string",enum:["ever","this_sequence","previous_email"]},fieldName:{type:"string"},fieldValue:{type:"string"},delay:U0,delayMs:{type:"number",description:"Optional wait in milliseconds before the new step. Prefer delay for readability."},waitUntil:L0,eventName:{type:"string",description:"logic_wait_for_event only: event to wait for, for example email.replied."},timeoutDays:{type:"number",description:"logic_wait_for_event only: maximum wait in whole days from 1 to 365. Defaults to 7."},timeoutAction:{type:"string",enum:["continue","exit"],description:"logic_wait_for_event only: continue to the next node or exit the sequence when the timeout is reached. Defaults to continue."},discount:{type:"object",description:"create_discount only: provider discount configuration.",additionalProperties:!0},provider:{type:"string",enum:["stripe","shopify"]},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"},branches:{type:"array",description:"logic_branch only: ordered conditional paths. Each path may provide targetNodeId, steps, or both.",items:t9},elseSteps:{type:"array",description:"logic_branch only: optional new steps for the else path.",items:qb},elseTargetNodeId:{type:"string",description:"logic_branch only: existing node for the else path, such as the original follow-up node or completion node."},allowEmptyPaths:{type:"boolean",description:"logic_branch only: set true only to create empty dashboard placeholders. Explicit target nodes do not require it."}},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:"duplicate_sequence",description:"Create an independent draft copy of a sequence, including its graph, email templates, and sequence A/B tests. The original is not changed.",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 copy."},name:{type:"string",description:"Optional name for the copy. Defaults to the original name plus (Copy)."}},required:["sequenceId"]}},{name:"archive_sequence",description:"Archive a sequence and stop new enrollments. Archived sequences remain available in the dashboard's archive.",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 archive."}},required:["sequenceId"]}},{name:"unarchive_sequence",description:"Restore an archived sequence as a disabled draft so it can be reviewed before activation.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Archived sequence ID to restore."}},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: cancelAll to drain every active/waiting enrollment (use this to fully stop a live sequence instead of only freezing enrollment), subscriberIds for a specific batch, subscriberId for one subscriber, or fieldValues to match stored entry event properties. Every bulk target defaults to dryRun, so pass dryRun false to actually cancel. Bulk cancellation is capped per call: while the response reports remainingCount above zero, call again with the same arguments until it reaches zero.",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."},cancelAll:{type:"boolean",description:"Cancel every active/waiting enrollment in the sequence, regardless of how contacts entered it. Use this when segment-triggered enrollments expose no shared entry field value. Defaults to dryRun; pass dryRun false to apply."},subscriberId:{type:"string",description:"Subscriber ID to cancel in this sequence. Provide exactly one target."},subscriberIds:{type:"array",items:{type:"string"},description:"Up to 500 subscriber IDs to cancel in this sequence. IDs that do not resolve come back in target.notFoundSubscriberIds. Provide exactly one target."},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 exactly one target."},dryRun:{type:"boolean",description:"When true, returns matching enrollments without cancelling them. cancelAll, subscriberIds, and fieldValues default to dryRun unless explicitly false; a single subscriberId cancels immediately."},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 jj={type:"object",properties:{email:{type:"string",description:"Subscriber email address. Optional when the record has a phone - such rows import as phone-only (SMS) contacts."},externalId:{type:"string",description:"Customer-owned subscriber ID"},firstName:{type:"string"},lastName:{type:"string"},phone:{type:"string",description:"Phone number. National-format values use the batch defaultPhoneCountry."},status:{type:"string",enum:["active","unsubscribed","bounced"]},tags:{type:"array",items:{type:"string"}},customAttributes:{type:"object",description:"CRM fields and other custom attributes. Values may be strings, numbers, booleans, arrays of those scalar values, or null.",additionalProperties:!0},createdAt:{type:"string",description:"Original signup date (ISO 8601) from the source platform. Set this when migrating so date-relative segments are correct immediately rather than treating every imported contact as having joined today. An existing contact's date only ever moves earlier."}},required:[],additionalProperties:!1},bz=[{name:"add_subscriber",description:"Add one subscriber. Status is only applied when creating a new contact; use update_subscriber to change an existing contact's status. For multiple contacts or CRM records, use create_subscriber_import instead of looping this tool. For an email-only batch going into one list, add_subscribers_to_list is also available.",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. Optional when phone is provided - a contact created with only a phone becomes a phone-only (SMS) contact."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide this with email when creating, or instead of email for an existing subscriber."},phone:{type:"string",description:"Phone number in E.164 or national format, stored as a native profile field. With no email, creates or matches a phone-only (SMS) contact."},phoneCountry:{type:"string",description:"ISO 3166-1 alpha-2 country used to read a national-format phone number, such as IT or US. Defaults to US. Only send it together with phone; the stored country always comes from the parsed number."},smsConsent:{type:"boolean",description:"Set true only when express written SMS marketing consent was verified for this phone number. Never inferred from phone presence."},firstName:{type:"string",description:"Subscriber first name, stored as a native profile field."},lastName:{type:"string",description:"Subscriber last name, stored as a native profile field."},attributes:{type:"object",description:"Custom attributes (plan, company, etc.). Use firstName/lastName for names instead of attributes."},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",enum:["active","unsubscribed","bounced"],description:"Initial subscriber status: active, unsubscribed, or bounced. Defaults to active and does not change an existing contact; use update_subscriber for existing contacts."},optInMode:{type:"string",enum:["default","confirmed","double_opt_in"],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."},createdAt:{type:"string",description:"Original signup date (ISO 8601) when importing a contact from another platform. Preserves their real history so date-relative segments like 'added in the last 30 days' are correct immediately instead of treating every imported contact as brand new. An existing contact's date only ever moves earlier. Supplying this also stops welcome sequences from firing, since it describes the past rather than a signup happening now."}},required:[]}},{name:"create_subscriber_import",description:"Queue one CRM-grade subscriber import with up to 5,000 full contact records. Supports names, external IDs, phones, statuses, tags, lists, and custom attributes. Prefer this over repeated add_subscriber calls. Returns an import ID for get_subscriber_import. Use optInMode='confirmed' only when the contacts already gave verified email consent.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},subscribers:{type:"array",minItems:1,maxItems:5000,items:jj,description:"Full subscriber records to import in one batch."},duplicateStrategy:{type:"string",enum:["skip","merge","overwrite"],description:"How existing contacts are handled. Defaults to skip. Merge fills missing fields; overwrite replaces public fields without reactivating unsubscribed contacts."},fileName:{type:"string",description:"Optional source label shown in import history, such as copper-export.csv."},listIds:{type:"array",items:{type:"string"},description:"Lists to add every successfully imported active subscriber to."},enrollInSequences:{type:"boolean",description:"Whether matching sequences may enroll imported contacts. Defaults to false and requires automations:trigger."},defaultPhoneCountry:{type:"string",description:"ISO 3166-1 alpha-2 country used for national-format phone numbers, such as SG or US."},smsConsent:{type:"boolean",description:"Set true only when express written SMS marketing consent was verified for every imported phone number."},optInMode:{type:"string",enum:["default","confirmed","double_opt_in"],description:"Email consent mode. Default follows workspace double opt-in settings. Confirmed creates active contacts immediately and must only be used for verified consent. Double_opt_in may send confirmation email and requires automations:trigger."}},required:["subscribers"]}},{name:"get_subscriber_import",description:"Get progress, counts, skipped reasons, and failure summaries for a queued subscriber import.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},importId:{type:"string",description:"Import ID or batch ID returned by create_subscriber_import."}},required:["importId"]}},{name:"update_subscriber",description:"Update an existing subscriber's profile, phone, status, attributes, or tags. Names and phones are native profile fields - set them here rather than as custom attributes. Setting status to unsubscribed suppresses the contact from all marketing, deactivates list memberships, and cancels active sequence enrollments while preserving the record and suppression history.",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."},firstName:{type:"string",description:"New first name, stored as a native profile field. Pass an empty string to clear it."},lastName:{type:"string",description:"New last name, stored as a native profile field. Pass an empty string to clear it."},phone:{type:"string",description:"New phone number in E.164 or national format, stored as a native profile field. Pass an empty string to clear it, which is rejected for a phone-only (SMS) contact that has no email. Changing the number resets SMS consent unless smsConsent is sent in the same call."},phoneCountry:{type:"string",description:"ISO 3166-1 alpha-2 country used to read a national-format phone number, such as IT or US. Defaults to US. Only send it together with phone; the stored country always comes from the parsed number."},smsConsent:{type:"boolean",description:"Set true only when express written SMS marketing consent was verified for this phone number; false unsubscribes them from SMS. Omitting this leaves consent unchanged unless phone changes, which resets consent because it belonged to the old number. Consent is never inferred from phone presence."},status:{type:"string",enum:["active","unsubscribed","bounced"],description:"New global subscriber status. Use unsubscribed for compliance-grade suppression without deleting the record. Use active only when the contact has valid consent to be resubscribed."},attributes:{type:"object",description:"Custom attributes to update. Use firstName/lastName for names instead of attributes."},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 a subscriber while preserving the record and suppression history. Only permanently deletes when hardDelete is true.",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 the subscriber and suppression history. Defaults to false, which globally unsubscribes the contact, deactivates list memberships, and cancels active sequence enrollments."}},required:[]}},{name:"get_subscriber",description:"Get the full subscriber profile, including tags, notes, list memberships, sequence enrollments, email stats, and recent activity. For commerce customers, customAttributes include nightly predictive analytics: predictedLtv (next-12-month spend), churnRisk (percent), expectedNextOrderAt, avgDaysBetweenOrders, and predictionConfidence.",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:kw},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:"trigger_subscriber_event",description:"Emit a custom event for one subscriber, exactly as an integration or the public API would. This is the supported way to exercise event triggers, matching-field idempotency, branch conditions, and stop conditions end to end without waiting for real traffic. The event is recorded, sync rules apply, and matching event_received sequences enroll. Creates the subscriber if they do not exist. Use trigger_subscriber_events for several events on the same contact.",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."},event:{type:"string",description:"Event name, such as saas.purchase or invoice.paid. The event definition is created if it does not exist."},properties:{type:"object",description:"Event properties. Include the sequence's matching field (for example order.id or invoice.id) when testing idempotency or cancellation by field value.",additionalProperties:!0},firstName:{type:"string",description:"First name applied to the subscriber profile."},lastName:{type:"string",description:"Last name applied to the subscriber profile."},attributes:{type:"object",description:"Custom attributes to set on the subscriber.",additionalProperties:!0},occurredAt:{type:"string",description:"When the event actually happened (ISO 8601). Omit for live events. If this is more than an hour in the past the event is recorded as history: it is stored with its real timestamp and counts for segments and the timeline, but no sequences enroll, no sync rules apply, no waiting steps resume, and no webhooks fire. A historical event also moves the contact's signup date back to when it occurred (never later), so imported contacts do not read as added today. Use this when backfilling from another platform - never to fake a live event, since the side effects you are testing will not run."},eventId:{type:"string",description:"Your own id for this event. Makes a historical import idempotent: re-sending the same eventId writes nothing new."}},required:["event"]}},{name:"trigger_subscriber_events",description:"Emit several custom events for one subscriber in order. Events are processed independently and sequentially, so a partial failure can still leave earlier events recorded.",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."},events:{type:"array",minItems:1,maxItems:500,items:{type:"object",properties:{name:{type:"string",description:"Event name"},properties:{type:"object",description:"Event properties",additionalProperties:!0},occurredAt:{type:"string",description:"When the event actually happened (ISO 8601). When every event in the batch is more than an hour old the batch is imported as history in one idempotent write, with no sequences, sync rules, waiting steps or webhooks; the contact's signup date also moves back to the earliest event in the batch (never later)."},eventId:{type:"string",description:"Your own id for this event, making a re-run idempotent."}},required:["name"],additionalProperties:!1},description:"Events to trigger, in order, for this subscriber."},firstName:{type:"string"},lastName:{type:"string"},attributes:{type:"object",description:"Custom attributes to set on the subscriber.",additionalProperties:!0}},required:["events"]}},{name:"bulk_add_subscriber_tags",description:"Add tags to up to 500 existing subscribers in one call, identified by emails, externalIds, or subscriberIds. Built for reconciling historical or derived tags: subscribers that do not exist are reported in notFound instead of being created, and tag automations do NOT run unless triggerAutomations is true. Needs the subscribers:tag scope; a tag name that does not exist yet also needs tags:write. The agent_safe key preset includes both. Use add_subscriber or update_subscriber for single-contact changes.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},tags:{type:"array",minItems:1,items:{type:"string"},description:"Tag names to add to every matched subscriber."},emails:{type:"array",items:{type:"string"},description:"Subscriber emails to tag. Combine with externalIds/subscriberIds as needed; at least one identifier list is required."},externalIds:{type:"array",items:{type:"string"},description:"Customer-owned subscriber IDs to tag."},subscriberIds:{type:"array",items:{type:"string"},description:"Sequenzy subscriber IDs to tag."},triggerAutomations:{type:"boolean",description:"Whether tag_added sequences may enroll these contacts. Defaults to false, which is what backfills want. Requires the automations:trigger scope."}},required:["tags"]}},{name:"bulk_remove_subscriber_tags",description:"Remove tags from up to 500 existing subscribers in one call, identified by emails, externalIds, or subscriberIds. Subscribers that do not exist are reported in notFound. Needs the subscribers:tag scope; the broader subscribers:write scope also satisfies it. Use this to roll back or reconcile a derived-tag backfill.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},tags:{type:"array",minItems:1,items:{type:"string"},description:"Tag names to remove from every matched subscriber."},emails:{type:"array",items:{type:"string"},description:"Subscriber emails to untag."},externalIds:{type:"array",items:{type:"string"},description:"Customer-owned subscriber IDs to untag."},subscriberIds:{type:"array",items:{type:"string"},description:"Sequenzy subscriber IDs to untag."}},required:["tags"]}},{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 $z={companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Exact recipient email address to inspect or clean up."},region:{type:"string",description:"Optional AWS SES region such as us-east-1. Omit to check every SES region currently used by the company."}},Wz=[{name:"get_recipient_suppression",description:"Check whether one recipient is suppressed by Sequenzy's bounce/complaint safeguards or the regional Amazon SES account-level suppression list. This exact-address lookup never exposes other recipients from the shared SES account.",inputSchema:{type:"object",properties:$z,required:["email"],additionalProperties:!1}},{name:"remove_recipient_suppression",description:"Remove stale bounce suppression for an exact recipient associated with the company. Clears matching Amazon SES bounce entries and Sequenzy's local bounce block, then reactivates bounced company subscribers. Complaint and unsubscribe protections are never removed.",inputSchema:{type:"object",properties:$z,required:["email"],additionalProperties:!1}}];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:[...F0],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:[...F0],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:f9,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 commerce collection filter (anyone who bought any product in the collection; value is a collection id or handle): [{"id":"filter-1","field":"commerceCollection","operator":"is","value":"skincare"}]. 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:{...u9,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:f9,minItems:1,description:"Replacement segment filters. Same shape and validation rules as create_segment. Mutually exclusive with `root`."},root:{...u9,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 Xz=[{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 Jz=[{name:"list_templates",description:"List the company's 50 most recently created email bodies, including per-locale localization sync status and each body's `emailPreset` Style > Format (branded or minimal; null for standalone raw HTML). Results include standalone templates plus recent bodies behind campaigns and transactional emails. To retrieve a specific campaign body even when it is not among these 50 results, pass the campaign's emailId to get_template. Bodies are kept when their campaign or transactional email is deleted.",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. `emailPreset` reports the per-email Style > Format (branded or minimal; null when the whole email is standalone raw HTML) the same way get_sequence does per step.",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. ${Hw}`},blocks:{type:"array",description:A1,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`, `previewText`, `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"},previewText:{type:["string","null"],description:"Inbox preview text. Send null to clear the existing preview text."},html:{type:"string",description:`Email HTML content. Mutually exclusive with \`blocks\`. Use this for imported provider templates. ${Hw}`},blocks:{type:"array",description:A1,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\`. ${Hw}`},blocks:{type:"array",description:A1,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 Gz=[{name:"list_transactional_emails",description:"List transactional email templates with subjects, delivery metrics, API slugs, and dashboard URLs. Each item also carries `emailPreset`, the per-email Style > Format (branded or minimal, null for a standalone raw HTML email), so a chrome drift check across templates does not need one get_transactional_email call each. Search by name, slug, or email title; filter active state; and sort by sends, opens, open rate, clicks, or CTR.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},search:{type:"string",description:"Case-insensitive search across template name, API slug, and linked email subject/title."},status:{type:"string",description:"Template status: all, active, or disabled."},sort:{type:"string",description:"Sort field: date, sends, opens, open-rate, clicks, or ctr. Defaults to date."},order:{type:"string",description:"Sort order: asc or desc. Defaults to desc."},includeMachineEngagement:{type:"boolean",description:"Include bot, scanner, and privacy-proxy engagement in open and click metrics. Defaults to false."}},additionalProperties:!1}},{name:"get_transactional_email",description:"Get a transactional email by ID or slug, including subject, preview text, blocks, variables, and linked dashboard URLs. `emailPreset` reports the per-email Style > Format the same way get_sequence does per step (branded or minimal; null when the whole email is standalone raw HTML), so it can be compared against sequence steps and campaigns without rendering them - minimal suppresses the company logo at render time.",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\`. ${Hw}`},blocks:{type:"array",description:`${A1} 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\`. ${Hw}`},blocks:{type:"array",description:`${L1} Mutually exclusive with \`html\`.`,items:{type:"object"}}},required:["idOrSlug"],additionalProperties:!1}},{name:"delete_transactional_email",description:"Permanently delete a saved transactional email template by ID or slug. Use this to retire an obsolete template: the slug stops sending and becomes free to reuse. Already-sent deliveries and their stats are kept, so history and analytics survive the delete. The linked email content stays as a reusable template and comes back as `deleted.emailId`; pass that to `delete_template` to remove the content too. To stop sends without losing the template, call `update_transactional_email` with `enabled` set to false instead.",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"],additionalProperties:!1}},{name:"send_email",description:"Queue one email using either a saved transactional email API slug (`templateId`) or direct `subject` and `html` content. The default delivery policy is transactional. When the recipient matches a subscriber, saved first and last names fill omitted name variables; explicit variables take precedence. Set `emailType` to `marketing` to add subscriber suppression, a marketing footer, and RFC 8058 one-click unsubscribe. Company Reply-To defaults are inherited when no override is provided, and `{{viewInBrowserUrl}}` is replaced with a hosted copy URL. Use `trackingSettings` with `clickTracking` or `openTracking` set to `false` to disable click-link rewriting or the open-tracking pixel for this send only; these opt-out fields cannot enable tracking the account has disabled. Returns a durable emailSendId and the accepted emailType; pass the ID to get_email_send for delivery status and failure details.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},to:{type:"string",description:"Recipient email address"},subject:{type:"string",description:"Email subject line. Required with `html` when `templateId` is omitted."},html:{type:"string",description:"Direct-send HTML body. Required with `subject` when `templateId` is omitted; the MCP server maps this to the transactional API `body` field. Use `{{viewInBrowserUrl}}` for a hosted copy link generated at send time."},templateId:{type:"string",description:"Saved transactional email API slug, for example `welcome-email`. The field name is retained for MCP compatibility and is mapped to the transactional API `slug` field."},variables:{type:"object",description:"Variables for template personalization. Nested objects and arrays are supported for repeat blocks, for example { items: [...] }. When the recipient matches a subscriber, saved first and last names fill omitted name variables; explicit values, including blanks, take precedence. Variables are HTML-escaped; a template can prefix a tag with 'html.' ({{html.prerenderedHtml}}) to insert a trusted, sanitized HTML value unescaped."},subscriberExternalId:{type:"string",description:"Customer-owned subscriber ID for attaching analytics, localization, and saved-name personalization on single-recipient sends. Maximum length: 255 characters."},emailType:{type:"string",description:"Delivery policy: `transactional` (default) or `marketing`. Marketing mode supports exactly one recipient and automatically applies subscriber suppression, the standard unsubscribe footer, and RFC 8058 headers."},replyTo:{type:"string",description:"Optional Reply-To address, formatted as `email@example.com` or `Name <email@example.com>`. When omitted, the saved template or company default is used."},trackingSettings:{type:"object",description:"Per-send tracking opt-outs. Each field defaults to `true`, meaning the account tracking settings apply; set a field to `false` to disable that tracking for this send only. These fields cannot enable tracking the account has disabled.",properties:{clickTracking:{type:"boolean",description:"Set to `false` to skip click-link rewriting for this send only, which helps when tracking redirects break universal or deep links."},openTracking:{type:"boolean",description:"Set to `false` to skip the open-tracking pixel for this send only."}},additionalProperties:!1}},required:["to"],additionalProperties:!1}}];var Yz=[{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:[...K0]},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:[...K0]},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 Hz=[...y5,...p5,...bz,...Wz,...o5,...Qz,...c5,...Jz,...h5,...m5,...t5,...g5,...d5,...i5,...a5,...wz,...s5,...e5,...Gz,...u5,...Xz,...n5,...Yz,...f5,...l5];async function zz(w,b){let $;switch(w){case"get_account":{let W=await B("GET","/api/v1/account"),Q=k1();$={...W,selectedCompanyId:Q??W.currentCompanyId};break}case"select_company":{let W=b.companyId,Q=await B("GET","/api/v1/account"),X=Q.companies?.find((J)=>J.id===W);if(!X)throw Error(`Company not found. Available companies: ${Q.companies?.map((J)=>`${J.name} (${J.id})`).join(", ")??"none"}`);U4(W),$={success:!0,message:`Switched to company: ${X.name}`,companyId:X.id,companyName:X.name};break}case"get_app_urls":{let W=await J4(b);$={...D1({companyId:W,campaignId:U(b,"campaignId"),landingPageId:U(b,"landingPageId"),sequenceId:U(b,"sequenceId"),emailId:U(b,"emailId")??U(b,"templateId"),transactionalId:U(b,"transactionalId"),emailSendId:U(b,"emailSendId"),domainId:U(b,"domainId"),status:U(b,"status"),settingsTab:U(b,"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 B("POST","/api/v1/companies",{name:b.name,domain:b.domain});if(!W.success)throw Error("Failed to create company");let Q=W.company.id,X=6,J=0,G=W.company.status;while(G==="processing"&&J<X){await new Promise((z)=>setTimeout(z,20000)),J++;let H=await B("GET",`/api/v1/companies/${Q}`);if(H.success)G=H.company.status}U4(Q);let Y=await B("GET",`/api/v1/companies/${Q}`);$={success:!0,company:Y.company,message:G==="processing"?"Company created but still processing. You can continue using it while processing completes.":`Company '${Y.company.name}' created and ready to use.`,autoSelected:!0};break}case"get_company":{let W=b.companyId;$=await B("GET",`/api/v1/companies/${W}`);break}case"update_company":{let W=await Nb("update_company",b),Q=b5(b);$=await B("PATCH",`/api/v1/companies/${W}`,Q);break}case"get_sync_rules":{let W=b.companyId;$=await B("GET","/api/v1/sync-rules",void 0,W);break}case"update_sync_rules":{let W=b.companyId;if(b.syncRules!==null&&!Array.isArray(b.syncRules))throw Error("`syncRules` must be an array of rules or null when calling `update_sync_rules`.");$=await B("PUT","/api/v1/sync-rules",{syncRules:b.syncRules},W);break}case"get_shopify_automation_settings":{let W=b.companyId;$=await B("GET","/api/v1/shopify/automation-settings",void 0,W);break}case"update_shopify_automation_settings":{let W=b.companyId,Q={};if(b.browseAbandonment!==void 0)Q.browseAbandonment=b.browseAbandonment;if(b.cartAbandonment!==void 0)Q.cartAbandonment=b.cartAbandonment;if(b.priceDrop!==void 0)Q.priceDrop=b.priceDrop;if(Object.keys(Q).length===0)throw Error("Provide `browseAbandonment`, `cartAbandonment`, and/or `priceDrop` when calling `update_shopify_automation_settings`.");$=await B("PUT","/api/v1/shopify/automation-settings",Q,W);break}case"create_api_key":{let W=b.companyId,Q={};if(typeof b.name==="string")Q.name=b.name;if(typeof b.preset==="string")Q.preset=b.preset;if(Array.isArray(b.scopes))Q.scopes=b.scopes;$=await B("POST","/api/v1/api-keys",Q,W);break}case"list_api_keys":{let W=await Nb(w,b);$=await B("GET","/api/v1/api-keys",void 0,W);break}case"update_api_key":{let W=await Nb(w,b),Q={};if(typeof b.name==="string")Q.name=b.name;if(typeof b.preset==="string")Q.preset=b.preset;if(Array.isArray(b.scopes))Q.scopes=b.scopes;if(Object.keys(Q).length===0)throw Error("Provide at least one of `name`, `preset`, or `scopes` when calling `update_api_key`.");$=await B("PATCH",`/api/v1/api-keys/${encodeURIComponent(String(b.apiKeyId))}`,Q,W);break}case"revoke_api_key":case"delete_api_key":{let W=await Nb(w,b);$=await B("DELETE",`/api/v1/api-keys/${encodeURIComponent(String(b.apiKeyId))}`,void 0,W);break}case"list_websites":{let W=b.companyId;$=await B("GET","/api/v1/websites",void 0,W);break}case"add_sending_domain":case"add_website":{let W=b.companyId;$=await B("POST","/api/v1/websites",{domain:b.domain},W);break}case"check_website":{let W=b.companyId;$=await B("GET",`/api/v1/websites/${encodeURIComponent(String(b.domain))}`,void 0,W);break}case"verify_sending_domain":{let W=b.companyId;$=await B("POST",`/api/v1/websites/${encodeURIComponent(String(b.domain))}/verify`,void 0,W);break}case"list_integrations":{let W=b.companyId,Q=new URLSearchParams;if(b.includeInactive===!0)Q.set("includeInactive","true");let X=Q.toString();$=await B("GET",`/api/v1/integrations${X?`?${X}`:""}`,void 0,W);break}case"list_sender_profiles":{let W=b.companyId;$=await B("GET","/api/v1/sender-profiles",void 0,W);break}case"update_sender_profile":{let{companyId:W,profileId:Q}=b,X=b.type==="reply"?`/api/v1/reply-profiles/${encodeURIComponent(Q)}`:`/api/v1/sender-profiles/${encodeURIComponent(Q)}`;$=await B("PATCH",X,{name:b.name},W);break}case"get_sending_status":{let W=b.companyId;$=await B("GET","/api/v1/sending-status",void 0,W);break}case"resume_sending":{let W=b.companyId;$=await B("POST","/api/v1/sending-status/resume",{listSanitizationConfirmed:b.listSanitizationConfirmed===!0},W);break}case"get_tracking_settings":{let W=b.companyId;$=await B("GET","/api/v1/tracking-settings",void 0,W);break}case"update_tracking_settings":{let W=b.companyId,Q=$5(b);$=await B("PATCH","/api/v1/tracking-settings",Q,W);break}case"get_notification_preferences":{let W=b.companyId;$=await B("GET","/api/v1/notification-preferences",void 0,W);break}case"update_notification_preferences":{let W=b.companyId;$=await B("PATCH","/api/v1/notification-preferences",{notificationPreferences:b.notificationPreferences},W);break}case"get_integration_guide":$=await B("POST","/api/v1/integration-guide",b);break;default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function Bz(w,b){let $;switch(w){case"generate_email":{let W=b.companyId;$=await B("POST","/api/v1/generate/email",b,W);break}case"generate_subject_lines":{let W=b.companyId;$=await B("POST","/api/v1/generate/subjects",b,W);break}case"generate_sms":{let W=b.companyId;$=await B("POST","/api/v1/generate/sms",b,W);break}case"get_sms_settings":{let W=b.companyId;$=await B("GET","/api/v1/sms/settings",void 0,W);break}case"send_test_sms":{let W=b.companyId,Q={to:M("send_test_sms",b,"to")};for(let X of["text","imageUrls","blocks"])if(b[X]!==void 0)Q[X]=b[X];$=await B("POST","/api/v1/sms/test",Q,W);break}case"submit_feedback":{let W=b.companyId,Q={message:M("submit_feedback",b,"message"),source:"mcp"};for(let X of["category","context"])if(b[X]!==void 0)Q[X]=b[X];$=await B("POST","/api/v1/feedback",Q,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function Dz(w,b){let $;switch(w){case"list_transactional_emails":{let W=b.companyId,Q=new URLSearchParams,X=U(b,"search"),J=m("list_transactional_emails",b,"status",["all","active","disabled"]),G=m("list_transactional_emails",b,"sort",["date","sends","opens","open-rate","clicks","ctr"]),Y=m("list_transactional_emails",b,"order",["asc","desc"]);if(X)Q.set("search",X);if(J)Q.set("status",J);if(G)Q.set("sort",G);if(Y)Q.set("order",Y);if(b.includeMachineEngagement===!0)Q.set("includeMachineEngagement","true");let H=Q.toString();$=await B("GET",`/api/v1/transactional${H?`?${H}`:""}`,void 0,W);break}case"get_transactional_email":{let W=b.companyId;$=await B("GET",`/api/v1/transactional/${b.idOrSlug}`,void 0,W);break}case"create_transactional_email":{let W=b.companyId,Q=new Set(["companyId","name","slug","subject","previewText","html","blocks","prompt","style","tone","enabled"]),X=Object.keys(b).filter((G)=>!Q.has(G));if(X.length>0)throw Error(`\`create_transactional_email\` accepts only \`name\`, \`slug\`, \`subject\`, \`previewText\`, \`html\`, \`blocks\`, \`prompt\`, \`style\`, \`tone\`, and \`enabled\` fields. Unsupported field${X.length===1?"":"s"}: ${X.map((G)=>`\`${G}\``).join(", ")}.`);O5(b);let J=Object.fromEntries(Object.entries(b).filter(([G])=>G!=="companyId"));$=await B("POST","/api/v1/transactional",J,W);break}case"update_transactional_email":{let W=b.companyId,Q=new Set(["companyId","idOrSlug","name","enabled","subject","previewText","html","blocks"]),X=Object.keys(b).filter((G)=>!Q.has(G));if(X.length>0)throw Error(`\`update_transactional_email\` accepts only \`name\`, \`enabled\`, \`subject\`, \`previewText\`, \`html\`, and \`blocks\` update fields. Unsupported field${X.length===1?"":"s"}: ${X.map((G)=>`\`${G}\``).join(", ")}.`);if(_w("update_transactional_email",b),b.name===void 0&&b.enabled===void 0&&b.subject===void 0&&b.previewText===void 0&&b.html===void 0&&b.blocks===void 0)throw Error("Provide at least one of `name`, `enabled`, `subject`, `previewText`, `html`, or `blocks` when calling `update_transactional_email`.");let J=Object.fromEntries(Object.entries(b).filter(([G])=>G!=="companyId"&&G!=="idOrSlug"));$=await B("PATCH",`/api/v1/transactional/${b.idOrSlug}`,J,W);break}case"delete_transactional_email":{let W=b.companyId,Q=M("delete_transactional_email",b,"idOrSlug");$=await B("DELETE",`/api/v1/transactional/${encodeURIComponent(Q)}`,void 0,W);break}case"send_email":{let W=b.companyId,Q=M("send_email",b,"to"),X=b.templateId===void 0?void 0:M("send_email",b,"templateId"),J=b.subject===void 0?void 0:M("send_email",b,"subject"),G=b.html===void 0?void 0:M("send_email",b,"html"),Y=b.emailType===void 0?void 0:M("send_email",b,"emailType"),H=b.replyTo===void 0?void 0:M("send_email",b,"replyTo");if(Y!==void 0&&Y!=="marketing"&&Y!=="transactional")throw Error("`emailType` must be `marketing` or `transactional` when calling `send_email`.");if(X!==void 0&&(J!==void 0||G!==void 0))throw Error("`templateId` cannot be combined with `subject` or `html` when calling `send_email`.");if(X===void 0&&(J===void 0||G===void 0))throw Error("Provide either `templateId` or both `subject` and `html` when calling `send_email`.");let z;if(b.trackingSettings!==void 0){if(typeof b.trackingSettings!=="object"||b.trackingSettings===null||Array.isArray(b.trackingSettings))throw Error("`trackingSettings` must be an object with optional boolean `clickTracking` and `openTracking` fields when calling `send_email`.");let A=b.trackingSettings;z={};for(let L of["clickTracking","openTracking"]){let F=A[L];if(F===void 0)continue;if(typeof F!=="boolean")throw Error(`\`trackingSettings.${L}\` must be a boolean when calling \`send_email\`.`);z[L]=F}}let D=Object.fromEntries(Object.entries({to:Q,slug:X,subject:J,body:G,variables:b.variables,subscriberExternalId:b.subscriberExternalId,emailType:Y,replyTo:H,trackingSettings:z}).filter(([,A])=>A!==void 0));$=await B("POST","/api/v1/transactional/send",D,W);break}case"get_stats":{let W=b.companyId,Q=b.period??"7d",X=new URLSearchParams({period:String(Q)}),J=b.emailType===void 0?void 0:M("get_stats",b,"emailType");if(J!==void 0&&!["campaign","transactional","sequence"].includes(J))throw Error("`emailType` must be `campaign`, `transactional`, or `sequence` when calling `get_stats`.");if(J)X.set("emailType",J);if(b.includeMachineEngagement===!0)X.set("includeMachineEngagement","true");$=await B("GET",`/api/v1/metrics?${X.toString()}`,void 0,W);break}case"get_campaign_stats":{let W=b.companyId,Q=new URLSearchParams;if(typeof b.period==="string")Q.set("period",b.period);if(typeof b.start==="string")Q.set("start",b.start);if(typeof b.end==="string")Q.set("end",b.end);if(b.includeMachineEngagement===!0)Q.set("includeMachineEngagement","true");let X=Q.toString();$=await B("GET",`/api/v1/metrics/campaigns/${b.campaignId}${X?`?${X}`:""}`,void 0,W);break}case"get_transactional_stats":{let W=b.companyId,Q=M("get_transactional_stats",b,"idOrSlug"),X=new URLSearchParams;for(let G of["period","start","end"])if(typeof b[G]==="string"&&b[G].trim())X.set(G,b[G].trim());if(b.includeMachineEngagement===!0)X.set("includeMachineEngagement","true");let J=X.toString();$=await B("GET",`/api/v1/metrics/transactional/${encodeURIComponent(Q)}${J?`?${J}`:""}`,void 0,W);break}case"get_sequence_stats":{let W=b.companyId,Q=new URLSearchParams;for(let J of["period","start","end"])if(typeof b[J]==="string"&&b[J].trim())Q.set(J,b[J].trim());if(b.includeMachineEngagement===!0)Q.set("includeMachineEngagement","true");let X=Q.toString();$=await B("GET",`/api/v1/metrics/sequences/${b.sequenceId}${X?`?${X}`:""}`,void 0,W);break}case"list_campaign_events":{let W=b.companyId,Q=M("list_campaign_events",b,"campaignId"),J=a9("list_campaign_events",b).toString();$=await B("GET",`/api/v1/metrics/campaigns/${encodeURIComponent(Q)}/events${J?`?${J}`:""}`,void 0,W);break}case"list_sequence_events":{let W=b.companyId,Q=M("list_sequence_events",b,"sequenceId"),X=a9("list_sequence_events",b),J=U(b,"automationNodeId");if(J)X.set("automationNodeId",J);let G=X.toString();$=await B("GET",`/api/v1/metrics/sequences/${encodeURIComponent(Q)}/events${G?`?${G}`:""}`,void 0,W);break}case"list_email_metrics":{let W=b.companyId,Q=new URLSearchParams,X=m("list_email_metrics",b,"emailType",["campaign","sequence"]);if(X)Q.set("emailType",X);let J=R9("list_email_metrics",b,"sequenceId"),G=R9("list_email_metrics",b,"campaignId"),Y=Yw("list_email_metrics",b,"step",1,1000);if(G.length>0&&(J.length>0||Y))throw Error("`campaignId` cannot be combined with `sequenceId` or `step` when calling `list_email_metrics`.");if(X==="campaign"&&(J.length>0||Y!==void 0))throw Error("`emailType` campaign cannot be combined with `sequenceId` or `step` when calling `list_email_metrics`.");if(X==="sequence"&&G.length>0)throw Error("`emailType` sequence cannot be combined with `campaignId` when calling `list_email_metrics`.");if(J.length>0)Q.set("sequenceId",J.join(","));if(G.length>0)Q.set("campaignId",G.join(","));if(Y!==void 0)Q.set("step",String(Y));let H=m("list_email_metrics",b,"period",["1h","24h","7d","30d","90d"]);if(H)Q.set("period",H);for(let V of["start","end"]){let q=U(b,V);if(q)Q.set(V,q)}let z=m("list_email_metrics",b,"sort",["sent","delivered","opened","clicked","openRate","clickRate","unsubscribed","conversions","revenue","step","name"]);if(z)Q.set("sort",z);let D=m("list_email_metrics",b,"order",["asc","desc"]);if(D)Q.set("order",D);let A=Yw("list_email_metrics",b,"page",1,1e6);if(A!==void 0)Q.set("page",String(A));let L=Yw("list_email_metrics",b,"limit",1,500);if(L!==void 0)Q.set("limit",String(L));if(b.includeMachineEngagement===!0)Q.set("includeMachineEngagement","true");let F=Q.toString();$=await B("GET",`/api/v1/metrics/emails${F?`?${F}`:""}`,void 0,W);break}case"get_subscriber_activity":{let W=b.companyId,Q=tw("get_subscriber_activity",b),X=await Pb(Q,W,{includeMachineEngagement:b.includeMachineEngagement===!0});$={success:X.success,email:X.subscriber.email,emailStats:X.subscriber.emailStats??null,activity:X.subscriber.activity??[],sequenceEnrollments:X.subscriber.sequenceEnrollments??[]};break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function Az(w,b){let $;switch(w){case"list_tags":{let W=b.companyId;$=await B("GET","/api/v1/tags",void 0,W);break}case"create_tag":{let W=b.companyId,Q=M("create_tag",b,"name"),X=m("create_tag",b,"color",F0);$=await B("POST","/api/v1/tags",{name:Q,...X!==void 0&&{color:X}},W);break}case"update_tag":{let W=b.companyId,Q=M("update_tag",b,"tagId"),X=Ib("update_tag",b,"color",F0);$=await B("PATCH",`/api/v1/tags/${encodeURIComponent(Q)}`,{color:X},W);break}case"delete_tag":{let W=b.companyId,Q=M("delete_tag",b,"tagId");$=await B("DELETE",`/api/v1/tags/${encodeURIComponent(Q)}`,void 0,W);break}case"list_lists":{let W=b.companyId;$=await B("GET","/api/v1/lists",void 0,W);break}case"create_list":{let W=b.companyId;$=await B("POST","/api/v1/lists",b,W);break}case"update_list":{let W=b.companyId,Q=M("update_list",b,"listId");if(b.name===void 0&&b.description===void 0&&b.isPrivate===void 0)throw Error("Provide at least one of `name`, `description`, or `isPrivate` when calling `update_list`.");if(b.name!==void 0&&U(b,"name")===void 0)throw Error("`name` cannot be empty when calling `update_list`.");if(b.description!==void 0&&b.description!==null&&typeof b.description!=="string")throw Error("`description` must be a string or null when calling `update_list`.");if(b.isPrivate!==void 0&&typeof b.isPrivate!=="boolean")throw Error("`isPrivate` must be a boolean when calling `update_list`.");$=await B("PATCH",`/api/v1/lists/${encodeURIComponent(Q)}`,{...b.name!==void 0&&{name:U(b,"name")},...b.description!==void 0&&{description:b.description},...b.isPrivate!==void 0&&{isPrivate:b.isPrivate}},W);break}case"delete_list":{let W=b.companyId,Q=M("delete_list",b,"listId");$=await B("DELETE",`/api/v1/lists/${encodeURIComponent(Q)}`,void 0,W);break}case"add_subscribers_to_list":{let W=b.companyId,Q=M("add_subscribers_to_list",b,"listId"),X=bW("add_subscribers_to_list",b),J=m("add_subscribers_to_list",b,"duplicateStrategy",["skip","merge","overwrite"])??"skip",G=m("add_subscribers_to_list",b,"optInMode",["default","confirmed","double_opt_in"])??"default";$=await B("POST",`/api/v1/lists/${encodeURIComponent(Q)}/subscribers`,{emails:X,duplicateStrategy:J,enrollInSequences:b.enrollInSequences===!0,optInMode:G},W);break}case"remove_subscribers_from_list":{let W=b.companyId,Q=M("remove_subscribers_from_list",b,"listId"),X=bW("remove_subscribers_from_list",b);$=await B("POST",`/api/v1/lists/${encodeURIComponent(Q)}/subscribers/remove`,{emails:X},W);break}case"list_segments":{let W=b.companyId;$=await B("GET","/api/v1/segments",void 0,W);break}case"create_segment":{aH(b);let W=b.companyId;$=await B("POST","/api/v1/segments",{...b,...b.filters!==void 0?{filters:a6(b.filters)}:{},...b.root!==void 0?{root:w4(b.root)}:{}},W);break}case"update_segment":{w5(b);let W=b.companyId,Q=M("update_segment",b,"segmentId"),X=U(b,"name"),J=m("update_segment",b,"filterJoinOperator",["and","or"]);$=await B("PATCH",`/api/v1/segments/${encodeURIComponent(Q)}`,{...X!==void 0&&{name:X},...J!==void 0&&{filterJoinOperator:J},...b.filters!==void 0?{filters:a6(b.filters)}:{},...b.root!==void 0?{root:w4(b.root)}:{}},W);break}case"delete_segment":{let W=b.companyId,Q=M("delete_segment",b,"segmentId");$=await B("DELETE",`/api/v1/segments/${encodeURIComponent(Q)}`,void 0,W);break}case"get_segment_count":{let W=b.companyId;$=await B("GET",`/api/v1/segments/${b.segmentId}/count`,void 0,W);break}case"list_audience_syncs":{let W=b.companyId;$=await B("GET","/api/v1/audience-syncs",void 0,W);break}case"list_ad_accounts":{let W=b.companyId;$=await B("GET","/api/v1/ad-accounts",void 0,W);break}case"create_audience_sync":{let W=b.companyId,Q=U(b,"segmentId"),X=U(b,"predefinedSegmentId");if(Q&&X)throw Error("Provide either `segmentId` or `predefinedSegmentId` when calling `create_audience_sync`, not both.");if(!Q&&!X)throw Error("Provide either `segmentId` or `predefinedSegmentId` when calling `create_audience_sync`.");$=await B("POST","/api/v1/audience-syncs",{segmentId:Q,predefinedSegmentId:X,adAccountId:M("create_audience_sync",b,"adAccountId"),audienceName:M("create_audience_sync",b,"audienceName"),...b.frequency!==void 0?{frequency:b.frequency}:{}},W);break}case"update_audience_sync":{let W=b.companyId,Q=M("update_audience_sync",b,"syncId");$=await B("PATCH",`/api/v1/audience-syncs/${encodeURIComponent(Q)}`,{...b.frequency!==void 0?{frequency:b.frequency}:{},...b.isActive!==void 0?{isActive:b.isActive}:{}},W);break}case"delete_audience_sync":{let W=b.companyId,Q=M("delete_audience_sync",b,"syncId");$=await B("DELETE",`/api/v1/audience-syncs/${encodeURIComponent(Q)}`,void 0,W);break}case"sync_audience_now":{let W=b.companyId,Q=M("sync_audience_now",b,"syncId");$=await B("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 Lz(w,b){let $;switch(w){case"list_templates":{let W=b.companyId,Q=new URLSearchParams,X=U(b,"label");if(X)Q.set("label",X);$=await B("GET",`/api/v1/templates${Q.size>0?`?${Q}`:""}`,void 0,W);break}case"get_template":{let W=b.companyId;$=await B("GET",`/api/v1/templates/${b.templateId}`,void 0,W);break}case"create_template":{let W=b.companyId;U5(b);let Q=Object.fromEntries(Object.entries(b).filter(([X])=>X!=="companyId"));$=await B("POST","/api/v1/templates",Q,W);break}case"update_template":{let W=b.companyId,Q=new Set(["companyId","templateId","name","subject","previewText","html","blocks","labels"]),X=Object.keys(b).filter((J)=>!Q.has(J));if(X.length>0)throw Error(`\`update_template\` accepts only \`name\`, \`subject\`, \`previewText\`, \`html\`, \`blocks\`, and \`labels\` update fields. Unsupported field${X.length===1?"":"s"}: ${X.map((J)=>`\`${J}\``).join(", ")}.`);if(_w("update_template",b),U1("update_template",b),b.name===void 0&&b.subject===void 0&&b.previewText===void 0&&b.html===void 0&&b.blocks===void 0&&b.labels===void 0)throw Error("Provide at least one of `name`, `subject`, `previewText`, `html`, `blocks`, or `labels` when calling `update_template`.");$=await B("PUT",`/api/v1/templates/${b.templateId}`,b,W);break}case"set_template_localization":{let W=b.companyId,Q=M("set_template_localization",b,"templateId"),X=M("set_template_localization",b,"locale"),J=M("set_template_localization",b,"subject"),G=new Set(["companyId","templateId","locale","subject","previewText","html","blocks"]),Y=Object.keys(b).filter((z)=>!G.has(z));if(Y.length>0)throw Error(`\`set_template_localization\` received unsupported field${Y.length===1?"":"s"}: ${Y.map((z)=>`\`${z}\``).join(", ")}.`);_w("set_template_localization",b,{requireContent:!0});let H={subject:J};if(b.previewText!==void 0)H.previewText=b.previewText;if(b.html!==void 0)H.html=b.html;if(b.blocks!==void 0)H.blocks=b.blocks;$=await B("PUT",`/api/v1/templates/${encodeURIComponent(Q)}/localizations/${encodeURIComponent(X)}`,H,W);break}case"sync_template_localizations":{let W=b.companyId,Q=M("sync_template_localizations",b,"templateId"),X=new Set(["companyId","templateId","locales"]),J=Object.keys(b).filter((Y)=>!X.has(Y));if(J.length>0)throw Error(`\`sync_template_localizations\` received unsupported field${J.length===1?"":"s"}: ${J.map((Y)=>`\`${Y}\``).join(", ")}.`);let G;if(b.locales!==void 0){if(!Array.isArray(b.locales)||b.locales.length===0||b.locales.some((Y)=>typeof Y!=="string"||Y.trim().length===0))throw Error("`locales` must contain at least one non-empty locale string when calling `sync_template_localizations`.");G=b.locales.map((Y)=>Y.trim())}$=await B("POST",`/api/v1/templates/${encodeURIComponent(Q)}/localizations/sync`,G===void 0?{}:{locales:G},W);break}case"delete_template":{let W=b.companyId;$=await B("DELETE",`/api/v1/templates/${b.templateId}`,void 0,W);break}case"list_ab_tests":{let W=b.companyId,Q=new URLSearchParams,X=U(b,"sequenceId");if(X)Q.set("sequenceId",X);$=await B("GET",`/api/v1/ab-tests${Q.size>0?`?${Q}`:""}`,void 0,W);break}case"get_ab_test":{let W=b.companyId;$=await B("GET",`/api/v1/ab-tests/${b.abTestId}`,void 0,W);break}case"get_ab_test_stats":{let W=b.companyId,Q=new URLSearchParams,X=U(b,"period"),J=U(b,"start"),G=U(b,"end");if(X)Q.set("period",X);if(J)Q.set("start",J);if(G)Q.set("end",G);if(b.includeMachineEngagement===!0)Q.set("includeMachineEngagement","true");$=await B("GET",`/api/v1/ab-tests/${b.abTestId}/stats${Q.size>0?`?${Q}`:""}`,void 0,W);break}case"restart_ab_test":{let W=b.companyId,Q=new Set(["companyId","abTestId","sourceVariantId","testType","winnerThreshold","variantCount"]),X=Object.keys(b).filter((H)=>!Q.has(H));if(X.length>0)throw Error(`\`restart_ab_test\` accepts only \`sourceVariantId\`, \`testType\`, \`winnerThreshold\`, and \`variantCount\` option fields. Unsupported field${X.length===1?"":"s"}: ${X.map((H)=>`\`${H}\``).join(", ")}.`);let J=U(b,"testType");if(J!==void 0&&J!=="subject"&&J!=="content")throw Error("`restart_ab_test` testType must be `subject` or `content`.");let G=b.winnerThreshold===void 0?void 0:Number(b.winnerThreshold);if(G!==void 0&&(!Number.isInteger(G)||G<10||G>1000))throw Error("`restart_ab_test` winnerThreshold must be an integer from 10 to 1000.");let Y=b.variantCount===void 0?void 0:Number(b.variantCount);if(Y!==void 0&&(!Number.isInteger(Y)||Y<2||Y>4))throw Error("`restart_ab_test` variantCount must be an integer from 2 to 4.");$=await B("POST",`/api/v1/ab-tests/${b.abTestId}/restart`,{sourceVariantId:U(b,"sourceVariantId"),testType:J,winnerThreshold:G,variantCount:Y},W);break}case"update_ab_test_variant":{let W=b.companyId,Q=new Set(["companyId","abTestId","variantId","subject","previewText","html","blocks","confirmLiveChange"]),X=Object.keys(b).filter((J)=>!Q.has(J));if(X.length>0)throw Error(`\`update_ab_test_variant\` accepts only \`subject\`, \`previewText\`, \`html\`, \`blocks\`, and \`confirmLiveChange\` fields. Unsupported field${X.length===1?"":"s"}: ${X.map((J)=>`\`${J}\``).join(", ")}.`);if(_w("update_ab_test_variant",b),b.confirmLiveChange!==void 0&&typeof b.confirmLiveChange!=="boolean")throw Error("`confirmLiveChange` must be a boolean when calling `update_ab_test_variant`.");if(b.subject===void 0&&b.previewText===void 0&&b.html===void 0&&b.blocks===void 0)throw Error("Provide at least one of `subject`, `previewText`, `html`, or `blocks` when calling `update_ab_test_variant`.");$=await B("PATCH",`/api/v1/ab-tests/${b.abTestId}/variants/${b.variantId}`,b,W);break}case"update_ab_test":{let W=b.companyId,Q=M("update_ab_test",b,"abTestId"),X=new Set(["companyId","abTestId","name","testPercentage","testDurationMinutes","winnerCriteria","testType","winnerThreshold","confirmLiveChange"]),J=Object.keys(b).filter((L)=>!X.has(L));if(J.length>0)throw Error(`\`update_ab_test\` received unsupported field${J.length===1?"":"s"}: ${J.map((L)=>`\`${L}\``).join(", ")}.`);if(b.confirmLiveChange!==void 0&&typeof b.confirmLiveChange!=="boolean")throw Error("`confirmLiveChange` must be a boolean when calling `update_ab_test`.");let G=U(b,"name"),Y=Yw("update_ab_test",b,"testPercentage",5,50),H=Yw("update_ab_test",b,"testDurationMinutes",15,1440),z=m("update_ab_test",b,"winnerCriteria",["open_rate","click_rate"]),D=m("update_ab_test",b,"testType",["subject","content"]),A=Yw("update_ab_test",b,"winnerThreshold",10,1000);if(G===void 0&&Y===void 0&&H===void 0&&z===void 0&&D===void 0&&A===void 0)throw Error("Provide at least one of `name`, `testPercentage`, `testDurationMinutes`, `winnerCriteria`, `testType`, or `winnerThreshold` when calling `update_ab_test`.");$=await B("PATCH",`/api/v1/ab-tests/${encodeURIComponent(Q)}`,{...G!==void 0&&{name:G},...Y!==void 0&&{testPercentage:Y},...H!==void 0&&{testDurationMinutes:H},...z!==void 0&&{winnerCriteria:z},...D!==void 0&&{testType:D},...A!==void 0&&{winnerThreshold:A},...b.confirmLiveChange===!0&&{confirmLiveChange:!0}},W);break}case"create_ab_test":{let W=b.companyId,Q=U(b,"campaignId"),X=U(b,"automationNodeId");if(b.confirmLiveChange!==void 0&&typeof b.confirmLiveChange!=="boolean")throw Error("`confirmLiveChange` must be a boolean when calling `create_ab_test`.");if(Boolean(Q)===Boolean(X))throw Error("Provide exactly one of `campaignId` or `automationNodeId` when calling `create_ab_test`.");let J=U(b,"name"),G=Yw("create_ab_test",b,"testPercentage",5,50),Y=Yw("create_ab_test",b,"testDurationMinutes",15,1440),H=m("create_ab_test",b,"winnerCriteria",["open_rate","click_rate"]),z=m("create_ab_test",b,"testType",["subject","content"]),D=Yw("create_ab_test",b,"winnerThreshold",10,1000);if(b.variants!==void 0){if(!Array.isArray(b.variants))throw Error("`variants` must be an array when calling `create_ab_test`.");b.variants.forEach((L,F)=>{if(!C(L)||typeof L.subject!=="string"||L.subject.trim()==="")throw Error(`\`variants\` item ${F+1} must include a non-empty \`subject\` when calling \`create_ab_test\`.`);if(L.blocks!==void 0&&!Array.isArray(L.blocks))throw Error(`\`variants\` item ${F+1} \`blocks\` must be an array when calling \`create_ab_test\`.`)})}let A=Array.isArray(b.variants)?b.variants:void 0;if(X!==void 0&&(!A||A.length<1))throw Error("`variants` must include at least one competing variant when calling `create_ab_test` with `automationNodeId`.");if(A&&A.length>4)throw Error("`variants` supports at most four extra variants when calling `create_ab_test`.");$=await B("POST","/api/v1/ab-tests",{...Q!==void 0&&{campaignId:Q},...X!==void 0&&{automationNodeId:X},...b.confirmLiveChange===!0&&{confirmLiveChange:!0},...J!==void 0&&{name:J},...G!==void 0&&{testPercentage:G},...Y!==void 0&&{testDurationMinutes:Y},...H!==void 0&&{winnerCriteria:H},...z!==void 0&&{testType:z},...D!==void 0&&{winnerThreshold:D},...b.variants!==void 0&&{variants:b.variants}},W);break}case"add_ab_test_variant":{let W=b.companyId,Q=M("add_ab_test_variant",b,"abTestId"),X=M("add_ab_test_variant",b,"subject"),J=U(b,"previewText");if(b.blocks!==void 0&&!Array.isArray(b.blocks))throw Error("`blocks` must be an array when calling `add_ab_test_variant`.");if(b.confirmLiveChange!==void 0&&typeof b.confirmLiveChange!=="boolean")throw Error("`confirmLiveChange` must be a boolean when calling `add_ab_test_variant`.");$=await B("POST",`/api/v1/ab-tests/${encodeURIComponent(Q)}/variants`,{subject:X,...J!==void 0&&{previewText:J},...b.blocks!==void 0&&{blocks:b.blocks},...b.confirmLiveChange===!0&&{confirmLiveChange:!0}},W);break}case"delete_ab_test_variant":{let W=b.companyId,Q=M("delete_ab_test_variant",b,"abTestId"),X=M("delete_ab_test_variant",b,"variantId");if(b.confirmLiveChange!==void 0&&typeof b.confirmLiveChange!=="boolean")throw Error("`confirmLiveChange` must be a boolean when calling `delete_ab_test_variant`.");$=await B("DELETE",`/api/v1/ab-tests/${encodeURIComponent(Q)}/variants/${encodeURIComponent(X)}${b.confirmLiveChange===!0?"?confirmLiveChange=true":""}`,void 0,W);break}case"delete_ab_test":{let W=b.companyId,Q=M("delete_ab_test",b,"abTestId");$=await B("DELETE",`/api/v1/ab-tests/${encodeURIComponent(Q)}`,void 0,W);break}case"list_campaigns":{let W=b.companyId,Q=new URLSearchParams;if(b.status)Q.set("status",String(b.status));let X=U(b,"label");if(X)Q.set("label",X);for(let J of["limit","offset"])if(b[J]!==void 0)Q.set(J,String(b[J]));$=await B("GET",`/api/v1/campaigns?${Q}`,void 0,W);break}case"get_campaign":{let W=b.companyId;$=await B("GET",`/api/v1/campaigns/${b.campaignId}`,void 0,W);break}case"get_campaign_audience":{let W=b.companyId;$=await B("GET",`/api/v1/campaigns/${encodeURIComponent(String(b.campaignId))}/audience`,void 0,W);break}case"get_email_send":{let W=b.companyId;$=await B("GET",`/api/v1/email-sends/${encodeURIComponent(String(b.emailSendId))}`,void 0,W);break}case"list_email_sends":{let W=b.companyId,Q=new URLSearchParams,X=["search","subject","recipient","campaignId","transactionalEmailId","automationId","automationNodeId"];for(let q of X){let P=U(b,q);if(P)Q.set(q,P)}let J=m("list_email_sends",b,"status",["pending","sent","delivered","opened","clicked","bounced","complained","failed","suppressed"]),G=m("list_email_sends",b,"emailType",["campaign","transactional","sequence"]),Y=m("list_email_sends",b,"bounceType",["Permanent","Transient"]),H=m("list_email_sends",b,"sortField",["recipientEmail","subject","status","eventAt","sentAt","createdAt"]),z=m("list_email_sends",b,"sortOrder",["asc","desc"]),D=Yw("list_email_sends",b,"days",1,14),A=Yw("list_email_sends",b,"page",1,Number.MAX_SAFE_INTEGER),L=Yw("list_email_sends",b,"limit",1,100),F=[["status",J],["emailType",G],["bounceType",Y],["sortField",H],["sortOrder",z],["days",D],["page",A],["limit",L]];for(let[q,P]of F)if(P!==void 0)Q.set(q,String(P));let V=Q.toString();$=await B("GET",`/api/v1/email-sends${V?`?${V}`:""}`,void 0,W);break}case"create_campaign":{let W=b.companyId;L5(b),O0("create_campaign",b);let Q=Object.fromEntries(Object.entries(b).filter(([X])=>X!=="companyId"));$=await B("POST","/api/v1/campaigns",Q,W);break}case"update_campaign":{let W=b.companyId,Q=new Set(["companyId","campaignId","name","subject","trackingCode","html","blocks","fromEmail","fromName","senderProfileId","replyTo","replyToName","replyProfileId","ccEmails","bccEmails","campaignData","computedLists","targetLists","segmentId","labels"]),X=Object.keys(b).filter((J)=>!Q.has(J));if(X.length>0)throw Error(`\`update_campaign\` accepts only content, sending identity, campaign data, computed list, audience, and label update fields. Unsupported field${X.length===1?"":"s"}: ${X.map((J)=>`\`${J}\``).join(", ")}.`);if(_w("update_campaign",b),U1("update_campaign",b),O0("update_campaign",b,{replyFirst:!0}),b.segmentId!==void 0&&b.targetLists!==void 0)throw Error("Provide either `segmentId` or `targetLists` when calling `update_campaign`, not both.");if(b.name===void 0&&b.subject===void 0&&b.trackingCode===void 0&&b.html===void 0&&b.blocks===void 0&&b.fromEmail===void 0&&b.senderProfileId===void 0&&b.replyTo===void 0&&b.replyProfileId===void 0&&b.ccEmails===void 0&&b.bccEmails===void 0&&b.campaignData===void 0&&b.computedLists===void 0&&b.targetLists===void 0&&b.segmentId===void 0&&b.labels===void 0)throw Error("Provide at least one campaign content, sending identity, campaign data, computed list, audience, or label field when calling `update_campaign`.");$=await B("PUT",`/api/v1/campaigns/${b.campaignId}`,b,W);break}case"schedule_campaign":{let W=b.companyId,Q=new Set(["companyId","campaignId","scheduledAt","targetLists","sendTimeOptimization","spreadOverHours","recurringInterval"]),X=Object.keys(b).filter((J)=>!Q.has(J));if(X.length>0)throw Error(`\`schedule_campaign\` accepts only \`campaignId\`, \`scheduledAt\`, \`targetLists\`, \`sendTimeOptimization\`, \`spreadOverHours\`, and \`recurringInterval\`. Unsupported field${X.length===1?"":"s"}: ${X.map((J)=>`\`${J}\``).join(", ")}.`);F5(b),$=await B("POST",`/api/v1/campaigns/${b.campaignId}/schedule`,{scheduledAt:b.scheduledAt,...b.targetLists!==void 0&&{targetLists:b.targetLists},...b.sendTimeOptimization!==void 0&&{sendTimeOptimization:b.sendTimeOptimization},...b.spreadOverHours!==void 0&&{spreadOverHours:b.spreadOverHours},...b.recurringInterval!==void 0&&{recurringInterval:b.recurringInterval}},W);break}case"send_test_email":{let W=b.companyId;$=await B("POST",`/api/v1/campaigns/${b.campaignId}/test`,{to:b.to},W);break}case"cancel_campaign":{let W=b.companyId,Q=M("cancel_campaign",b,"campaignId");$=await B("POST",`/api/v1/campaigns/${encodeURIComponent(Q)}/cancel`,void 0,W);break}case"unschedule_campaign":{let W=b.companyId,Q=M("unschedule_campaign",b,"campaignId");$=await B("POST",`/api/v1/campaigns/${encodeURIComponent(Q)}/unschedule`,void 0,W);break}case"pause_campaign":{let W=b.companyId,Q=M("pause_campaign",b,"campaignId");$=await B("POST",`/api/v1/campaigns/${encodeURIComponent(Q)}/pause`,void 0,W);break}case"resume_campaign":{let W=b.companyId,Q=M("resume_campaign",b,"campaignId"),X=Yw("resume_campaign",b,"spreadOverHours",1,72);$=await B("POST",`/api/v1/campaigns/${encodeURIComponent(Q)}/resume`,{...X!==void 0&&{spreadOverHours:X}},W);break}case"delete_campaign":{let W=b.companyId,Q=M("delete_campaign",b,"campaignId");$=await B("DELETE",`/api/v1/campaigns/${encodeURIComponent(Q)}`,void 0,W);break}case"duplicate_campaign":{let W=b.companyId,Q=M("duplicate_campaign",b,"campaignId"),X=m("duplicate_campaign",b,"mode",["campaign","ab_test","variant"]),J=U(b,"variantId");if(X==="variant"&&J===void 0)throw Error("`variantId` is required when calling `duplicate_campaign` with mode `variant`.");$=await B("POST",`/api/v1/campaigns/${encodeURIComponent(Q)}/duplicate`,{...X!==void 0&&{mode:X},...J!==void 0&&{variantId:J}},W);break}case"resend_campaign_to_non_openers":{let W=b.companyId,Q=M("resend_campaign_to_non_openers",b,"campaignId");$=await B("POST",`/api/v1/campaigns/${encodeURIComponent(Q)}/resend-to-non-openers`,void 0,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function Uz(w,b){let $;switch(w){case"list_forms":{let W=b.companyId;$=await B("GET","/api/v1/forms",void 0,W);break}case"create_form":{let W=b.companyId,Q=M("create_form",b,"name"),X=Array.isArray(b.listIds)?b.listIds.filter((Y)=>typeof Y==="string").map((Y)=>Y.trim()).filter(Boolean):[];if(X.length===0)throw Error("`listIds` must contain at least one list ID when calling `create_form`.");let J=m("create_form",b,"duplicateStrategy",["skip","merge","overwrite"]),G={name:Q,listIds:X};for(let Y of["tagIds","buttonText","headline","description","successMessage","redirectUrl","showFirstName","showLastName","theme"])if(b[Y]!==void 0)G[Y]=b[Y];if(J!==void 0)G.duplicateStrategy=J;$=await B("POST","/api/v1/forms",G,W);break}case"update_form":{let W=b.companyId,Q=M("update_form",b,"formId"),X=m("update_form",b,"duplicateStrategy",["skip","merge","overwrite"]),J={};for(let G of["name","listIds","tagIds","buttonText","headline","description","successMessage","redirectUrl","theme","blocks"])if(b[G]!==void 0)J[G]=b[G];if(X!==void 0)J.duplicateStrategy=X;if(Object.keys(J).length===0)throw Error("Provide at least one field to change when calling `update_form`.");$=await B("PATCH",`/api/v1/forms/${encodeURIComponent(Q)}`,J,W);break}case"get_form_embed":{let W=b.companyId,Q=M("get_form_embed",b,"formId");$=await B("GET",`/api/v1/forms/embed/${encodeURIComponent(Q)}`,void 0,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}function H4(w,b,$,W,Q){let X=w[b];if(X===void 0)return;if(typeof X!=="number"||!Number.isFinite(X)||X<$||X>W||Q&&!Number.isInteger(X))throw Error(`\`${b}\` must be a ${Q?"integer":"number"} between ${$} and ${W} when calling \`upload_image_asset\`.`);return X}async function Fz(w,b){if(w!=="upload_image_asset")return{handled:!1,result:void 0};let $=U(b,"filePath"),W=U(b,"imageBase64");if($===void 0===(W===void 0))throw Error("Provide either `filePath` or `imageBase64` (not both) when calling `upload_image_asset`.");let Q=U(b,"filename");if(W!==void 0&&Q===void 0)throw Error("`filename` is required with `imageBase64` when calling `upload_image_asset`.");let X=H4(b,"sourceWidth",1,20000,!0),J=H4(b,"sourceHeight",1,20000,!0);if(X===void 0!==(J===void 0))throw Error("Provide both `sourceWidth` and `sourceHeight` when calling `upload_image_asset`.");let G=H4(b,"displayWidthPercent",1,100,!1)??100,Y=H4(b,"cropHeight",1,2000,!0),H=U(b,"objectFit");if(H!==void 0&&H!=="cover"&&H!=="contain")throw Error("`objectFit` must be 'cover' or 'contain' when calling `upload_image_asset`.");if(H!==void 0&&Y===void 0)throw Error("`objectFit` can only be used with `cropHeight` when calling `upload_image_asset`.");let z=U(b,"align");if(z!==void 0&&!["left","center","right"].includes(z))throw Error("`align` must be 'left', 'center', or 'right' when calling `upload_image_asset`.");let D=typeof b.altText==="string"?b.altText.trim():void 0;if(D!==void 0&&D.length>500)throw Error("`altText` must be 500 characters or fewer when calling `upload_image_asset`.");let A=await S5({companyId:U(b,"companyId"),filePath:$,imageBase64:W,filename:Q,contentType:U(b,"contentType"),altText:D,sourceWidth:X,sourceHeight:J}),L={type:"image",src:A.url,alt:A.altText??"",width:G,widthType:"percent",...Y!==void 0&&{height:Y,objectFit:H??"cover"},...z!==void 0&&{align:z}};return{handled:!0,result:{success:!0,asset:A,imageBlock:L,message:"Insert imageBlock into the target email's blocks array with its create or update tool."}}}async function Kz(w,b){let $=b.companyId,W;switch(w){case"connect_integration":{let Q=M("connect_integration",b,"provider"),X=M("connect_integration",b,"webhookSecret");W=await B("POST","/api/v1/integrations/connect",{provider:Q,webhookSecret:X,...typeof b.apiKey==="string"&&b.apiKey?{apiKey:b.apiKey}:{},...typeof b.providerAccountId==="string"&&b.providerAccountId?{providerAccountId:b.providerAccountId}:{},...b.settings!==void 0?{settings:b.settings}:{},...b.historyImport!==void 0?{historyImport:b.historyImport}:{}},$);break}case"get_integration":{let Q=M("get_integration",b,"integrationId");W=await B("GET",`/api/v1/integrations/${encodeURIComponent(Q)}`,void 0,$);break}case"list_integration_capabilities":{let Q=new URLSearchParams;if(typeof b.provider==="string"&&b.provider)Q.set("provider",b.provider);if(typeof b.category==="string"&&b.category)Q.set("category",b.category);let X=Q.toString();W=await B("GET",`/api/v1/integrations/catalog${X?`?${X}`:""}`,void 0,$);break}case"list_integration_activity":{let Q=new URLSearchParams;if(typeof b.integrationId==="string"&&b.integrationId)Q.set("integrationId",b.integrationId);if(typeof b.provider==="string"&&b.provider)Q.set("provider",b.provider);if(typeof b.status==="string"&&b.status)Q.set("status",b.status);if(typeof b.limit==="number")Q.set("limit",String(b.limit));let X=Q.toString();W=await B("GET",`/api/v1/integrations/activity${X?`?${X}`:""}`,void 0,$);break}case"set_integration_sync_enabled":{let Q=M("set_integration_sync_enabled",b,"integrationId");if(typeof b.syncEnabled!=="boolean")throw Error("`syncEnabled` must be a boolean when calling `set_integration_sync_enabled`.");W=await B("PATCH",`/api/v1/integrations/${encodeURIComponent(Q)}`,{syncEnabled:b.syncEnabled},$);break}case"get_integration_pixel":{let Q=M("get_integration_pixel",b,"integrationId");W=await B("GET",`/api/v1/integrations/${encodeURIComponent(Q)}/pixel`,void 0,$);break}case"activate_integration_pixel":{let Q=M("activate_integration_pixel",b,"integrationId");W=await B("POST",`/api/v1/integrations/${encodeURIComponent(Q)}/pixel`,void 0,$);break}case"sync_integration":{let Q=M("sync_integration",b,"integrationId");W=await B("POST",`/api/v1/integrations/${encodeURIComponent(Q)}/sync`,void 0,$);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:W}}async function Oz(w,b){let $;switch(w){case"list_landing_pages":{let W=b.companyId;$=await B("GET","/api/v1/landing-pages",void 0,W);break}case"get_landing_page":{let W=b.companyId;$=await B("GET",`/api/v1/landing-pages/${b.landingPageId}`,void 0,W);break}case"create_landing_page":{let W=b.companyId,Q=new Set(["companyId","name","slug","template","content"]),X=Object.keys(b).filter((J)=>!Q.has(J));if(X.length>0)throw Error(`\`create_landing_page\` accepts only \`name\`, \`slug\`, \`template\`, and \`content\` fields. Unsupported field${X.length===1?"":"s"}: ${X.map((J)=>`\`${J}\``).join(", ")}.`);$=await B("POST","/api/v1/landing-pages",{...b.name!==void 0&&{name:b.name},...b.slug!==void 0&&{slug:b.slug},...b.template!==void 0&&{template:b.template},...b.content!==void 0&&{content:b.content}},W);break}case"update_landing_page":{let W=b.companyId,Q=Q4("update_landing_page",b,{requireUpdate:!0});$=await B("PUT",`/api/v1/landing-pages/${b.landingPageId}`,Q,W);break}case"publish_landing_page":{let W=b.companyId,Q=Q4("publish_landing_page",b,{requireUpdate:!1});$=await B("POST",`/api/v1/landing-pages/${b.landingPageId}/publish`,Q,W);break}case"unpublish_landing_page":{let W=b.companyId,Q=Q4("unpublish_landing_page",b,{requireUpdate:!1});$=await B("POST",`/api/v1/landing-pages/${b.landingPageId}/unpublish`,Q,W);break}case"duplicate_landing_page":{let W=b.companyId;$=await B("POST",`/api/v1/landing-pages/${b.landingPageId}/duplicate`,{...b.name!==void 0&&{name:b.name},...b.slug!==void 0&&{slug:b.slug}},W);break}case"delete_landing_page":{let W=b.companyId;$=await B("DELETE",`/api/v1/landing-pages/${b.landingPageId}`,void 0,W);break}case"connect_landing_page_domain":{let W=b.companyId;$=await B("POST","/api/v1/landing-pages/domain",{domain:b.domain},W);break}case"update_landing_page_domain_settings":{let W=b.companyId,Q=K5(b);$=await B("PUT","/api/v1/landing-pages/domain",Q,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function Zz(w,b){let $;switch(w){case"list_products":{let W=b.companyId,Q=new URLSearchParams;if(typeof b.provider==="string"&&b.provider.trim())Q.set("provider",b.provider.trim());if(typeof b.search==="string"&&b.search.trim())Q.set("search",b.search.trim());let X=Yw("list_products",b,"limit",1,100);if(X!==void 0)Q.set("limit",String(X));let J=Yw("list_products",b,"offset",0,Number.MAX_SAFE_INTEGER);if(J!==void 0)Q.set("offset",String(J));let G=Q.size>0?`?${Q.toString()}`:"";$=await B("GET",`/api/v1/products${G}`,void 0,W);break}case"upsert_products":{let W=b.companyId;if(!Array.isArray(b.products)||b.products.length===0)throw Error("`products` must be a non-empty array when calling `upsert_products`.");$=await B("POST","/api/v1/products",{products:b.products},W);break}case"delete_product":{let W=b.companyId,Q=M("delete_product",b,"productId");$=await B("DELETE",`/api/v1/products/${encodeURIComponent(Q)}`,void 0,W);break}case"attach_product_file":{let W=b.companyId,Q=M("attach_product_file",b,"productId"),X=U(b,"url"),J=U(b,"filePath");if(X===void 0===(J===void 0))throw Error("Provide either `url` or `filePath` (not both) when calling `attach_product_file`.");let G;if(J!==void 0){let Y=await P5(J,W);G={url:Y.url,source:"upload",fileName:U(b,"fileName")??Y.fileName,fileSizeBytes:Y.fileSizeBytes,mimeType:Y.mimeType}}else{G={url:X};let Y=U(b,"fileName");if(Y)G.fileName=Y}$=await B("PUT",`/api/v1/products/${encodeURIComponent(Q)}/delivery`,G,W);break}case"remove_product_file":{let W=b.companyId,Q=M("remove_product_file",b,"productId");$=await B("DELETE",`/api/v1/products/${encodeURIComponent(Q)}/delivery`,void 0,W);break}case"sync_products":{let W=b.companyId,Q=new URLSearchParams;if(typeof b.integrationId==="string"&&b.integrationId)Q.set("integrationId",b.integrationId);let X=Q.toString();$=await B("POST",`/api/v1/products/sync${X?`?${X}`:""}`,void 0,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}function qj(w){let b=U(w,"campaignId"),$=U(w,"sequenceId"),W=U(w,"templateId"),Q=[b,$,W].filter((X)=>X!==void 0);if(Q.length===0)throw Error("render_email requires one of campaignId, sequenceId plus nodeId, or templateId.");if(Q.length>1)throw Error("render_email accepts exactly one of campaignId, sequenceId, or templateId.");if(b!==void 0)return`/api/v1/campaigns/${encodeURIComponent(b)}/render`;if($!==void 0){let X=M("render_email",w,"nodeId");return`/api/v1/sequences/${encodeURIComponent($)}/nodes/${encodeURIComponent(X)}/render`}return`/api/v1/templates/${encodeURIComponent(W)}/render`}var Pj=["subscriberId","subscriber","variables","locale","variantId","tracking"];async function Mz(w,b){if(w!=="render_email")return{handled:!1,result:void 0};let $=qj(b),W={};for(let X of Pj)if(b[X]!==void 0)W[X]=b[X];return{handled:!0,result:await B("POST",$,W,U(b,"companyId"))}}var Vz=80,jz=10;function Ij(w){if(!Array.isArray(w.recipients))throw Error("`recipients` must be an array when calling `send_sequence_test_email`.");if(w.recipients.length>jz)throw Error(`\`recipients\` must include no more than ${jz} email addresses when calling \`send_sequence_test_email\`.`);if(w.recipients.find((Q)=>typeof Q!=="string"||Q.trim().length===0)!==void 0)throw Error("Every `recipients` item must be a non-empty email address when calling `send_sequence_test_email`.");let $=Array.from(new Set(w.recipients.map((Q)=>typeof Q==="string"?Q.trim().toLowerCase():""))).filter(Boolean);if($.length===0)throw Error("`recipients` must include at least one email address when calling `send_sequence_test_email`.");let W=$.find((Q)=>!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(Q));if(W)throw Error(`Invalid test recipient email address: \`${W}\`.`);return $}function Nj(w){let b=w.trim().replace(/\s+/g," ");if(b.length<=Vz)return b;return`${b.slice(0,Vz-3).trimEnd()}...`}async function JW(w,b){let $;switch(w){case"generate_sequence":{let W=M("generate_sequence",b,"goal"),Q=typeof b.name==="string"&&b.name.trim().length>0?b.name.trim():void 0,J=(await JW("create_sequence",{...b,goal:W,name:Q??Nj(W),trigger:"contact_added",durationDays:b.durationDays??14})).result;return{handled:!0,result:typeof J==="object"&&J!==null?{...J,deprecated:!0,deprecationMessage:"generate_sequence is deprecated. Use create_sequence for new integrations."}:J}}case"list_sequences":{let W=b.companyId,Q=new URLSearchParams;for(let J of["status","search","limit","offset"])if(b[J]!==void 0)Q.set(J,String(b[J]));if(Array.isArray(b.labels)&&b.labels.length>0)Q.set("labels",b.labels.join(","));let X=Q.size>0?`?${Q.toString()}`:"";$=await B("GET",`/api/v1/sequences${X}`,void 0,W);break}case"get_sequence":{let W=b.companyId;$=await B("GET",`/api/v1/sequences/${b.sequenceId}`,void 0,W);break}case"list_sequence_enrollments":{let W=b.companyId,Q=M(w,b,"sequenceId"),X=new URLSearchParams;for(let G of["currentNodeId","status","subscriberId"]){let Y=b[G];if(Array.isArray(Y)){if(Y.length>0)X.set(G,Y.join(","))}else if(Y!==void 0)X.set(G,String(Y))}for(let G of["email","sort","limit","offset"])if(b[G]!==void 0)X.set(G,String(b[G]));let J=X.size>0?`?${X.toString()}`:"";$=await B("GET",`/api/v1/sequences/${encodeURIComponent(Q)}/enrollments${J}`,void 0,W);break}case"send_sequence_test_email":{let W=b.companyId,Q=M(w,b,"sequenceId"),X=M(w,b,"nodeId"),J=Ij(b);$=await B("POST",`/api/v1/sequences/${encodeURIComponent(Q)}/nodes/${encodeURIComponent(X)}/test`,{recipients:J},W);break}case"create_sequence":{let W=b.companyId;U1("create_sequence",b),O0("create_sequence",b);let Q=Array.isArray(b.steps),X=b.goal===void 0&&b.steps===void 0,J=await B("POST","/api/v1/sequences",b,W);if(!J.success){$=J;break}let G=J.sequence.id;if(Q||X){let A=await B("GET",`/api/v1/sequences/${G}`,void 0,W);if(A.success)$={...J,success:!0,sequence:A.sequence,message:`Sequence "${A.sequence.name}" created ${X?"as a blank draft":"with explicit steps"}. Review it before enabling.${J.eventTrackingCode?" Add the custom event feed using eventTrackingCode and eventTracking before enabling.":""}`};else $=A;break}let Y=7,H=0,z="pending";while(z!=="complete"&&H<Y){let A=await B("GET",`/api/v1/sequences/${G}`,void 0,W);if(A.success)z=A.sequence.enrichmentStatus;if(H++,z!=="complete"&&H<Y)await new Promise((L)=>setTimeout(L,20000))}let D=await B("GET",`/api/v1/sequences/${G}`,void 0,W);if(D.success)$={...J,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.${J.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.${J.eventTrackingCode?" Add the custom event feed using eventTrackingCode and eventTracking before enabling.":""}`};else $=D;break}case"update_sequence":{let W=b.companyId,Q=Q5(b);$=await B("PUT",`/api/v1/sequences/${b.sequenceId}`,Q,W);break}case"update_sequence_node":{let W=b.companyId,Q=M("update_sequence_node",b,"sequenceId"),X=H5(b);$=await B("PUT",`/api/v1/sequences/${Q}`,X,W);break}case"update_sequence_nodes":{let W=b.companyId,Q=M("update_sequence_nodes",b,"sequenceId"),X=z5(b);$=await B("PUT",`/api/v1/sequences/${Q}`,X,W);break}case"edit_sequence_graph":{let W=b.companyId,Q=B5(b);$=await B("PUT",`/api/v1/sequences/${b.sequenceId}`,Q,W);break}case"insert_sequence_step":{let W=b.companyId,Q=D5(b),X=await B("PUT",`/api/v1/sequences/${b.sequenceId}`,Q,W);if(typeof X==="object"&&X!==null){let J=X,G=J.sequence;if(typeof G==="object"&&G!==null){let Y=G;$={...J,...Y.insertedNodeIds!==void 0?{insertedNodeIds:Y.insertedNodeIds}:{},...Y.insertedEmailIds!==void 0?{insertedEmailIds:Y.insertedEmailIds}:{},...Y.insertedEmailCount!==void 0?{insertedEmailCount:Y.insertedEmailCount}:{},...Y.addedBranchNodeId!==void 0?{addedBranchNodeId:Y.addedBranchNodeId}:{},...Y.addedBranchPathNodeIds!==void 0?{addedBranchPathNodeIds:Y.addedBranchPathNodeIds}:{}};break}}$=X;break}case"enable_sequence":{let W=b.companyId;$=await B("POST",`/api/v1/sequences/${b.sequenceId}/enable`,void 0,W);break}case"disable_sequence":{let W=b.companyId;$=await B("POST",`/api/v1/sequences/${b.sequenceId}/disable`,void 0,W);break}case"duplicate_sequence":{let W=b.companyId,Q=M("duplicate_sequence",b,"sequenceId"),X=U(b,"name");$=await B("POST",`/api/v1/sequences/${encodeURIComponent(Q)}/duplicate`,X===void 0?void 0:{name:X},W);break}case"archive_sequence":case"unarchive_sequence":{let W=b.companyId,Q=M(w,b,"sequenceId"),X=w==="archive_sequence"?"archive":"unarchive";$=await B("POST",`/api/v1/sequences/${encodeURIComponent(Q)}/${X}`,void 0,W);break}case"list_sequence_goals":{let W=b.companyId,Q=M(w,b,"sequenceId");$=await B("GET",`/api/v1/sequences/${encodeURIComponent(Q)}/goals`,void 0,W);break}case"create_sequence_goal":case"update_sequence_goal":{let W=b.companyId,Q=M(w,b,"sequenceId");if(w==="create_sequence_goal")M(w,b,"name"),X5(b);else J5(b);let X=w==="update_sequence_goal"?M(w,b,"goalId"):void 0,J={...b};delete J.companyId,delete J.sequenceId,delete J.goalId,$=await B(w==="create_sequence_goal"?"POST":"PATCH",`/api/v1/sequences/${encodeURIComponent(Q)}/goals${X?`/${encodeURIComponent(X)}`:""}`,J,W);break}case"delete_sequence_goal":{let W=b.companyId,Q=M(w,b,"sequenceId"),X=M(w,b,"goalId");$=await B("DELETE",`/api/v1/sequences/${encodeURIComponent(Q)}/goals/${encodeURIComponent(X)}`,void 0,W);break}case"get_sequence_inbound_webhook":case"configure_sequence_inbound_webhook":case"rotate_sequence_inbound_webhook_secret":{let W=b.companyId,Q=M(w,b,"sequenceId");if(b.clearFieldMapping===!0&&b.fieldMapping!==void 0)throw Error("Provide either `fieldMapping` or `clearFieldMapping`, not both.");if(b.clearSamplePayload===!0&&b.samplePayload!==void 0)throw Error("Provide either `samplePayload` or `clearSamplePayload`, not both.");let X=w==="configure_sequence_inbound_webhook",J=w==="rotate_sequence_inbound_webhook_secret",G=X?{...b.clearFieldMapping===!0?{fieldMapping:null}:b.fieldMapping!==void 0?{fieldMapping:b.fieldMapping}:{},...b.clearSamplePayload===!0?{samplePayload:null}:b.samplePayload!==void 0?{samplePayload:b.samplePayload}:{}}:void 0;$=await B(J?"POST":X?"PUT":"GET",`/api/v1/sequences/${encodeURIComponent(Q)}/inbound-webhook${J?"/rotate-secret":""}`,G,W);break}case"pause_sequence_enrollments":{let W=b.companyId;$=await B("POST",`/api/v1/sequences/${b.sequenceId}/pause-enrollments`,void 0,W);break}case"resume_sequence_enrollments":{let W=b.companyId;$=await B("POST",`/api/v1/sequences/${b.sequenceId}/resume-enrollments`,void 0,W);break}case"enroll_subscribers_in_sequence":{let W=b.companyId,Q=M("enroll_subscribers_in_sequence",b,"sequenceId"),X=q5(b);$=await B("POST",`/api/v1/sequences/${encodeURIComponent(Q)}/enroll`,X,W);break}case"cancel_sequence_enrollments":{let W=b.companyId,Q=A5(b);$=await B("POST",`/api/v1/sequences/${b.sequenceId}/enrollments/cancel`,Q,W);break}case"delete_sequence":{let W=b.companyId;$=await B("DELETE",`/api/v1/sequences/${b.sequenceId}`,void 0,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}function z4(w,b,$){let W=b[$];if(W===void 0)return;if(!Array.isArray(W))throw Error(`\`${$}\` must be an array of strings when calling \`${w}\`.`);let Q=W.filter((X)=>typeof X==="string").map((X)=>X.trim()).filter((X)=>X.length>0);if(Q.length!==W.length)throw Error(`\`${$}\` must contain only non-empty strings when calling \`${w}\`.`);return Q}function Ej(w,b){let $=z4(w,b,"tags");if($===void 0||$.length===0)throw Error(`\`tags\` must contain at least one tag when calling \`${w}\`.`);let W=z4(w,b,"emails"),Q=z4(w,b,"externalIds"),X=z4(w,b,"subscriberIds");if((W?.length??0)+(Q?.length??0)+(X?.length??0)===0)throw Error(`Provide \`emails\`, \`externalIds\`, or \`subscriberIds\` when calling \`${w}\`.`);return{tags:$,...W?.length?{emails:W}:{},...Q?.length?{externalIds:Q}:{},...X?.length?{subscriberIds:X}:{},...w==="bulk_add_subscriber_tags"&&typeof b.triggerAutomations==="boolean"?{triggerAutomations:b.triggerAutomations}:{}}}async function qz(w,b){let $;switch(w){case"add_subscriber":{let W=b.companyId,Q=typeof b.phone==="string"&&b.phone.trim()!==""?b.phone.trim():void 0,X=Q?s9(b):tw("add_subscriber",b),J=m("add_subscriber",b,"status",["active","unsubscribed","bounced"]),G=m("add_subscriber",b,"optInMode",["default","confirmed","double_opt_in"]);if($=await B("POST","/api/v1/subscribers",{...X,...Q!==void 0&&{phone:Q},...typeof b.phoneCountry==="string"&&b.phoneCountry.trim()!==""&&{phoneCountry:b.phoneCountry.trim()},...typeof b.smsConsent==="boolean"&&{smsConsent:b.smsConsent},...b.firstName!==void 0&&{firstName:b.firstName},...b.lastName!==void 0&&{lastName:b.lastName},customAttributes:b.attributes,tags:b.tags,lists:b.listIds,...J!==void 0&&{status:J},...G!==void 0&&{optInMode:G},...b.createdAt!==void 0&&{createdAt:b.createdAt}},W),J!==void 0&&C($)&&C($.subscriber)&&$.subscriber.skipped===!0&&$.subscriber.status!==J)throw Error(`Existing subscriber was not changed to status '${J}'. Use update_subscriber to change an existing contact's status.`);break}case"create_subscriber_import":{let W=b.companyId;if(!Array.isArray(b.subscribers)||b.subscribers.length===0)throw Error("`subscribers` must be a non-empty array when calling `create_subscriber_import`.");if(b.subscribers.length>5000)throw Error("`create_subscriber_import` accepts at most 5000 subscriber records per call.");for(let J=0;J<b.subscribers.length;J+=1){let G=b.subscribers[J],Y=C(G)&&typeof G.email==="string"&&G.email.trim()!=="",H=C(G)&&typeof G.phone==="string"&&G.phone.trim()!=="";if(!Y&&!H)throw Error(`Subscriber record ${J} must include an email or a phone number.`)}let Q=m("create_subscriber_import",b,"duplicateStrategy",["skip","merge","overwrite"]),X=m("create_subscriber_import",b,"optInMode",["default","confirmed","double_opt_in"]);$=await B("POST","/api/v1/subscribers/imports",{subscribers:b.subscribers,...Q!==void 0&&{duplicateStrategy:Q},...b.fileName!==void 0&&{fileName:b.fileName},...b.listIds!==void 0&&{listIds:b.listIds},...b.enrollInSequences!==void 0&&{enrollInSequences:b.enrollInSequences},...b.defaultPhoneCountry!==void 0&&{defaultPhoneCountry:b.defaultPhoneCountry},...b.smsConsent!==void 0&&{smsConsent:b.smsConsent},...X!==void 0&&{optInMode:X}},W);break}case"get_subscriber_import":{let W=b.companyId,Q=M("get_subscriber_import",b,"importId");$=await B("GET",`/api/v1/subscribers/imports/${encodeURIComponent(Q)}`,void 0,W);break}case"update_subscriber":{let W=b.companyId,Q=tw("update_subscriber",b),X=m("update_subscriber",b,"status",["active","unsubscribed","bounced"]),G=C(b.attributes)||b.addTags!==void 0||b.removeTags!==void 0?await Pb(Q,W):null,Y=Array.isArray(G?.subscriber.tags)?G.subscriber.tags.filter((L)=>typeof L==="string"):[],H=Array.isArray(b.addTags)?b.addTags.filter((L)=>typeof L==="string"&&L.trim()!=="").map(r9):[],z=new Set(Array.isArray(b.removeTags)?b.removeTags.filter((L)=>typeof L==="string"&&L.trim()!=="").map(r9):[]),D=Y.filter((L)=>!z.has(L));for(let L of H)if(!D.includes(L))D.push(L);let A={};if(Q.email&&Q.externalId)A.externalId=Q.externalId;if(b.firstName!==void 0)A.firstName=b.firstName;if(b.lastName!==void 0)A.lastName=b.lastName;if(typeof b.phone==="string"||b.phone===null)A.phone=b.phone;if(typeof b.phoneCountry==="string")A.phoneCountry=b.phoneCountry;if(typeof b.smsConsent==="boolean")A.smsConsent=b.smsConsent;if(X!==void 0)A.status=X;if(C(b.attributes))A.customAttributes={...C(G?.subscriber.customAttributes)?G.subscriber.customAttributes:{},...b.attributes};if(b.addTags||b.removeTags)A.tags=D;$=await B("PATCH",X4(Q),A,W);break}case"remove_subscriber":{let W=b.companyId,Q=tw("remove_subscriber",b),X=X4(Q);if(b.hardDelete===!0)$=await B("DELETE",X,void 0,W);else $=await B("PATCH",X,{status:"unsubscribed"},W);break}case"get_subscriber":{let W=b.companyId,Q=tw("get_subscriber",b);$=await Pb(Q,W,{includeMachineEngagement:b.includeMachineEngagement===!0});break}case"list_subscriber_notes":{let W=b.companyId,Q=tw("list_subscriber_notes",b);$=await B("GET",e9(Q),void 0,W);break}case"add_subscriber_note":{let W=b.companyId,Q=tw("add_subscriber_note",b),X=typeof b.body==="string"?b.body.trim():void 0;if(!X)throw Error("`body` is required when calling `add_subscriber_note`.");if(X.length>5000)throw Error("`body` must be 5000 characters or fewer when calling `add_subscriber_note`.");$=await B("POST",e9(Q),{body:X},W);break}case"delete_subscriber_note":{let W=b.companyId,Q=typeof b.noteId==="string"?b.noteId.trim():"";if(!Q)throw Error("`noteId` is required when calling `delete_subscriber_note`.");$=await B("DELETE",`/api/v1/subscribers/notes/${encodeURIComponent(Q)}`,void 0,W);break}case"trigger_subscriber_event":{let W=b.companyId,Q=tw("trigger_subscriber_event",b),X=M("trigger_subscriber_event",b,"event");if(b.properties!==void 0&&!C(b.properties))throw Error("`properties` must be an object when calling `trigger_subscriber_event`.");$=await B("POST","/api/v1/subscribers/events",{...Q,event:X,...b.properties!==void 0&&{properties:b.properties},...b.firstName!==void 0&&{firstName:b.firstName},...b.lastName!==void 0&&{lastName:b.lastName},...b.attributes!==void 0&&{customAttributes:b.attributes},...b.occurredAt!==void 0&&{occurredAt:b.occurredAt},...b.eventId!==void 0&&{eventId:b.eventId}},W);break}case"trigger_subscriber_events":{let W=b.companyId,Q=tw("trigger_subscriber_events",b);if(!Array.isArray(b.events)||b.events.length===0)throw Error("`events` must be a non-empty array when calling `trigger_subscriber_events`.");if(b.events.length>500)throw Error("`trigger_subscriber_events` accepts at most 500 events per call. Split a larger history import into several calls.");for(let X=0;X<b.events.length;X+=1){let J=b.events[X];if(!C(J)||typeof J.name!=="string"||J.name.trim()==="")throw Error(`Event ${X} must include a non-empty \`name\` string.`)}$=await B("POST","/api/v1/subscribers/events/bulk",{...Q,events:b.events,...b.firstName!==void 0&&{firstName:b.firstName},...b.lastName!==void 0&&{lastName:b.lastName},...b.attributes!==void 0&&{customAttributes:b.attributes}},W);break}case"bulk_add_subscriber_tags":case"bulk_remove_subscriber_tags":{let W=b.companyId,Q=Ej(w,b);$=await B("POST",`/api/v1/subscribers/bulk/tags/${w==="bulk_add_subscriber_tags"?"add":"remove"}`,Q,W);break}case"search_subscribers":{let W=b.companyId;$=await j5(b,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function Pz(w,b){if(w!=="get_recipient_suppression"&&w!=="remove_recipient_suppression")return{handled:!1,result:void 0};let $=U(b,"companyId"),W=M(w,b,"email"),Q=U(b,"region"),X=new URLSearchParams;if(Q)X.set("region",Q);let J=`/api/v1/suppressions/${encodeURIComponent(W)}${X.size>0?`?${X}`:""}`;return{handled:!0,result:await B(w==="get_recipient_suppression"?"GET":"DELETE",J,void 0,$)}}async function Iz(w,b){let $;switch(w){case"list_team_members":{let W=b.companyId;$=await B("GET","/api/v1/team",void 0,W);break}case"invite_team_member":{let W=b.companyId,Q=M("invite_team_member",b,"email"),X=Ib("invite_team_member",b,"role",["admin","viewer","restricted"]);if(b.canManageBilling!==void 0&&typeof b.canManageBilling!=="boolean")throw Error("`canManageBilling` must be a boolean when calling `invite_team_member`.");$=await B("POST","/api/v1/team/invitations",{email:Q,role:X,...b.canManageBilling!==void 0&&{canManageBilling:b.canManageBilling}},W);break}case"cancel_team_invitation":{let W=b.companyId,Q=M("cancel_team_invitation",b,"invitationId");$=await B("DELETE",`/api/v1/team/invitations/${encodeURIComponent(Q)}`,void 0,W);break}case"list_conversations":{let W=b.companyId,Q=new URLSearchParams,X=m("list_conversations",b,"status",["open","closed","all"]);if(X)Q.set("status",X);let J=U(b,"search");if(J)Q.set("search",J);if(b.unread!==void 0){if(typeof b.unread!=="boolean")throw Error("`unread` must be a boolean when calling `list_conversations`.");if(b.unread)Q.set("unread","true")}if(b.page!==void 0){if(typeof b.page!=="number"||!Number.isInteger(b.page)||b.page<1)throw Error("`page` must be a positive integer when calling `list_conversations`.");Q.set("page",String(b.page))}let G=Yw("list_conversations",b,"limit",1,100);if(G!==void 0)Q.set("limit",String(G));$=await B("GET",`/api/v1/conversations${Q.size>0?`?${Q}`:""}`,void 0,W);break}case"get_conversation":{let W=b.companyId,Q=M("get_conversation",b,"conversationId");$=await B("GET",`/api/v1/conversations/${encodeURIComponent(Q)}`,void 0,W);break}case"reply_to_conversation":{let W=b.companyId,Q=M("reply_to_conversation",b,"conversationId"),X=m("reply_to_conversation",b,"type",["outbound","note"])??"outbound",J=U(b,"subject"),G=U(b,"bodyText"),Y=U(b,"bodyHtml");if(X==="outbound"&&G===void 0&&Y===void 0)throw Error("Provide `bodyText` or `bodyHtml` when calling `reply_to_conversation` with an outbound message.");$=await B("POST",`/api/v1/conversations/${encodeURIComponent(Q)}/messages`,{type:X,...J!==void 0&&{subject:J},...G!==void 0&&{bodyText:G},...Y!==void 0&&{bodyHtml:Y}},W);break}case"update_conversation_status":{let W=b.companyId,Q=M("update_conversation_status",b,"conversationId"),X=Ib("update_conversation_status",b,"status",["open","closed"]);$=await B("POST",`/api/v1/conversations/${encodeURIComponent(Q)}/status`,{status:X},W);break}case"mark_conversation_read":{let W=b.companyId,Q=M("mark_conversation_read",b,"conversationId");$=await B("POST",`/api/v1/conversations/${encodeURIComponent(Q)}/read`,void 0,W);break}case"list_webhooks":{let W=b.companyId;$=await B("GET","/api/v1/webhooks",void 0,W);break}case"create_webhook":{let W=b.companyId,Q=M("create_webhook",b,"name"),X=M("create_webhook",b,"url"),J=wW("create_webhook",b);$=await B("POST","/api/v1/webhooks",{name:Q,url:X,...J!==void 0&&{events:J}},W);break}case"update_webhook":{let W=b.companyId,Q=M("update_webhook",b,"webhookId"),X=U(b,"name"),J=U(b,"url"),G=wW("update_webhook",b),Y=m("update_webhook",b,"status",["enabled","disabled"]);if(X===void 0&&J===void 0&&G===void 0&&Y===void 0)throw Error("Provide at least one of `name`, `url`, `events`, or `status` when calling `update_webhook`.");$=await B("PATCH",`/api/v1/webhooks/${encodeURIComponent(Q)}`,{...X!==void 0&&{name:X},...J!==void 0&&{url:J},...G!==void 0&&{events:G},...Y!==void 0&&{status:Y}},W);break}case"delete_webhook":{let W=b.companyId,Q=M("delete_webhook",b,"webhookId");$=await B("DELETE",`/api/v1/webhooks/${encodeURIComponent(Q)}`,void 0,W);break}case"test_webhook":{let W=b.companyId,Q=M("test_webhook",b,"webhookId");$=await B("POST",`/api/v1/webhooks/${encodeURIComponent(Q)}/test`,void 0,W);break}case"list_webhook_deliveries":{let W=b.companyId,Q=M("list_webhook_deliveries",b,"webhookId"),X=Yw("list_webhook_deliveries",b,"limit",1,100),J=new URLSearchParams;if(X!==void 0)J.set("limit",String(X));$=await B("GET",`/api/v1/webhooks/${encodeURIComponent(Q)}/deliveries${J.size>0?`?${J}`:""}`,void 0,W);break}case"replay_webhook_delivery":{let W=b.companyId,Q=M("replay_webhook_delivery",b,"webhookId"),X=M("replay_webhook_delivery",b,"deliveryId");$=await B("POST",`/api/v1/webhooks/${encodeURIComponent(Q)}/deliveries/${encodeURIComponent(X)}/replay`,void 0,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}var Nz=[zz,Kz,qz,Pz,Zz,Az,Lz,Mz,Uz,Oz,Fz,JW,Dz,Iz,Bz];var Tj=new Set(["create_campaign","update_campaign","create_template","update_template","set_template_localization","create_transactional_email","update_transactional_email","create_sequence","update_sequence","update_sequence_node","update_sequence_nodes","insert_sequence_step","update_ab_test_variant","create_ab_test"]);function Ez(w){return typeof w==="object"&&w!==null&&!Array.isArray(w)}function GW(w){if(Array.isArray(w))return w.some(GW);if(!Ez(w))return!1;for(let[b,$]of Object.entries(w)){if((b==="html"||b==="htmlContent")&&typeof $==="string"&&$.trim().length>0)return!0;if(GW($))return!0}return!1}function Tz(w,b,$){if(!Tj.has(w)||!GW(b)||!Ez($))return $;let W=Array.isArray($.warnings)?$.warnings.filter((Q)=>typeof Q==="string"):[];return{...$,warnings:[...new Set([...W,Hw])]}}var Rz=Hz.map(_5).map(oH);async function Sz(w,b){try{let $,W=!1;for(let X of Nz){let J=await X(w,b);if(J.handled){$=J.result,W=!0;break}}if(!W)throw Error(`Unknown tool: ${w}`);let Q=Z5($);if(Q)throw Q;return $=Tz(w,b,$),$=await N5(w,b,$),{structuredContent:x5($),content:[{type:"text",text:JSON.stringify($,null,2)}]}}catch($){return{isError:!0,content:[{type:"text",text:d1($)}]}}}async function vz(w,b,$){let W=b.getRequestContext?.(w)??{};try{return await LW(W,$)}finally{await b.onRequestContextUpdated?.(W,w)}}function ok(w={}){let b=new E9({name:"sequenzy",version:lH.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(`
57
- `)});return b.setRequestHandler(L$,async()=>{return{tools:Rz}}),b.setRequestHandler(d0,async($,W)=>{let{name:Q,arguments:X}=$.params;return vz(W,w,()=>Sz(Q,X??{}))}),b.setRequestHandler(G$,async()=>{return{resources:nH}}),b.setRequestHandler(H$,async($,W)=>{let{uri:Q}=$.params;return vz(W,w,()=>pH(Q))}),b}export{ok as createSequenzyMcpServer};
56
+ Before protected server-side API work, use create_api_key and save the key to .env as SEQUENZY_API_KEY. Static-site saved forms are the exception: use list_forms/create_form/get_form_embed and never place a secret key in browser code.`,inputSchema:{type:"object",properties:{framework:{type:"string",description:"Framework/language (nextjs, express, python, etc.)"},use_case:{type:"string",description:"Use case: 'transactional' (sending emails), 'subscribe_form' (adding subscribers), 'event_tracking' (tracking CUSTOM events only - payment events should come from Stripe/Polar/etc integration), 'ecommerce' (connecting a custom e-commerce platform via the Commerce API)"}}}}];var d5=[{name:"generate_email",description:"Generate email blocks from a prompt. Generated blocks include the company's branding chrome (logo, footer with company name/address/unsubscribe) by default, matching emails created in the dashboard.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},prompt:{type:"string",description:"Description of the email to generate"},style:{type:"string",description:"Style: minimal, branded, promotional"},tone:{type:"string",description:"Tone: professional, casual, friendly"},applyBranding:{type:"boolean",description:"Wrap the generated content with company branding (logo + footer). Defaults to true; set false to get raw content blocks only."},emailType:{type:"string",enum:["marketing","transactional"],description:"Email type. Transactional emails get a footer without the unsubscribe link. Defaults to marketing."}},required:["prompt"]}},{name:"generate_sequence",description:"[DEPRECATED compatibility alias - use create_sequence] Create and persist a disabled AI-generated email sequence draft from a goal. The saved draft appears in list_sequences. The name defaults to the goal and the trigger defaults to contact_added; optionally pass listId to scope it. Review before enabling.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},goal:{type:"string",description:"Goal of the sequence (e.g., 'onboard new SaaS trial users')"},name:{type:"string",description:"Optional sequence name. Defaults to the goal."},emailCount:{type:"number",description:"Number of emails in the sequence (default: 5, max: 10)"},durationDays:{type:"number",description:"Total duration in days (default: 14)"},listId:{type:"string",description:"Optional list ID. When provided, only contacts added to this list trigger the sequence."}},required:["goal"]}},{name:"generate_subject_lines",description:"Generate A/B test subject line variants",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},topic:{type:"string",description:"Topic or context for the subject lines"},count:{type:"number",description:"Number of variants to generate (default: 5)"}},required:["topic"]}},{name:"generate_sms",description:"Generate SMS marketing message variants from a prompt. Returns plain-text messages with per-message encoding and segment counts. Use the results as the 'text' of an SMS sequence step (insert_sequence_step with type 'sms' or a create_sequence sms step). Messages exclude opt-out footers and brand prefixes - the platform adds those automatically at send time.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},prompt:{type:"string",description:"Description of the SMS to generate (e.g., 'cart reminder with a free-shipping hook')"},count:{type:"number",description:"Number of message variants to generate (default: 3, max: 10)"}},required:["prompt"]}},{name:"get_sms_settings",description:"Get the company's SMS add-on status: whether SMS is enabled, plan eligibility, credit balance, brand prefix, phone numbers, and whether SMS steps will actually send. Check this before adding SMS steps to sequences so you can warn the user when SMS is not ready.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"send_test_sms",description:"Send a test SMS to a phone number. IMPORTANT: sends a real text message and charges SMS credits - only call when the user explicitly asks for a test send. Requires the SMS add-on with a verified number (check get_sms_settings). Limited to 5 test sends per hour; bypasses quiet hours; excluded from step stats.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},to:{type:"string",description:"Destination phone number in international E.164 format, e.g. +15550100123."},text:{type:"string",description:"Plain-text message body. Merge tags are not resolved for test sends to arbitrary numbers. Provide text or blocks."},imageUrls:{type:"array",items:{type:"string"},description:"Up to 2 publicly reachable image URLs sent as MMS media (US/CA only)."},blocks:{type:"array",items:{type:"object"},description:"SMS content blocks (text + image subset). Provide text or blocks, not both."}},required:["to"]}}];var o5=[{name:"get_stats",description:"Get overview statistics for a time period, including reply count and reply rate. Counts form a funnel over the sends made inside the period: opened and clicked are unique per email send (not total open events) and include engagement that arrives after the period ends, so they never exceed sent. Rates divide by rateDenominator (delivered, falling back to sent), reported alongside rateDenominatorBasis. Set emailType to transactional for Send API and transactional SMTP open/click rates, including both direct and saved-template sends. When no emailType filter is used and a background-computed snapshot is available, the response also includes a top-level commerceForecast with predicted AOV, 12-month customer value, 90-day revenue, confidence, and data-eligibility reasons.",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)"},emailType:{type:"string",description:"Optional structural email type filter: campaign, transactional, or sequence. Use transactional for Send API and transactional SMTP traffic."},includeMachineEngagement:x1}}},{name:"get_transactional_stats",description:"Get aggregate sends, deliveries, bounces, opens, clicks, and rates for one saved transactional email selected by ID or slug. Results are all-time by default; pass period or start/end for a window. For direct-content Send API messages, use get_stats with emailType transactional and list_email_sends/get_email_send for delivery-level detail.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},idOrSlug:{type:"string",description:"Saved transactional email ID or API slug."},period:{type:"string",description:"Optional sliding window: 1h, 24h, 7d, 30d, or 90d. Ignored when start and end are provided."},start:{type:"string",description:"Optional ISO 8601 custom range start. Must be provided with end."},end:{type:"string",description:"Optional ISO 8601 custom range end. Must be provided with start; maximum range is 90 days."},includeMachineEngagement:x1},required:["idOrSlug"]}},{name:"get_campaign_stats",description:"Get detailed statistics for a campaign, including replies and reply rate, attributed conversions, revenue (revenueCents), product recommendation funnel metrics, 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"},period:{type:"string",description:"Time period: 1h, 24h, 7d, 30d, or 90d"},start:{type:"string",description:"Custom range start as an ISO 8601 timestamp; provide end too"},end:{type:"string",description:"Custom range end as an ISO 8601 timestamp; provide start too"},includeMachineEngagement:x1},required:["campaignId"]}},{name:"list_poll_responses",description:"List individual Poll and NPS responses for a campaign, newest answer first, with each respondent's email, their answer and stored value, the subscriber attribute the answer was saved to, and the response time. get_campaign_stats reports the totals; this reports who answered what and when. Only each subscriber's latest answer per poll block is returned, so the counts match the campaign stats summary. Do not reconstruct respondents by scanning subscribers for the poll attribute - the attribute carries no response time and reflects the latest answer to any email. Multi-select answers list every selected option in answers/values. Results are paginated: read the returned pagination object and keep paging with page while page < totalPages.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID. For a sequence email step, pass the step's automation node ID."},blockId:{type:"string",description:"Restrict to one poll block. Block IDs come from the polls array of get_campaign_stats. Omit to return every poll block in the email."},page:{type:"number",description:"1-based page number. Defaults to 1."},limit:{type:"number",description:"Page size. Defaults to 100 and is capped at 500 by the server."}},required:["campaignId"]}},{name:"get_sequence_stats",description:"Get statistics for a sequence. The steps array is the per-step breakdown: one entry per email step in graph order with its step number, automation nodeId, subject, and its own sent, delivered, bounced, opened, clicked, replies, and unsubscribed counts plus rates - so this is where you read how many of Email 4 went out, without reconstructing anything from list_sequence_events. Step counts come from the retained event stream, not the 14-day delivery history behind list_email_sends, so they stay answerable for old sends. Also returns the aggregate funnel across every step, attributed conversions and revenue (revenueCents), product recommendation funnel metrics, per-step failed subscribers and failure reasons, and enrollmentSkipped counts for trigger matches where the contact could not be enrolled (unsubscribed/bounced). Pass period or start/end to use one explicit window for every historical metric; without them, step and aggregate counts are all-time and enrollmentSkipped defaults to the last 30 days. The enrollmentCounts field is a live snapshot of active and waiting enrollments grouped by current node, so it is not limited by period or start/end. To compare the same step across many sequences in one call, use list_email_metrics instead.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"},period:{type:"string",description:"Optional sliding window: 1h, 24h, 7d, 30d, or 90d. Ignored when start and end are provided."},start:{type:"string",description:"Optional ISO 8601 custom range start. Must be provided with end."},end:{type:"string",description:"Optional ISO 8601 custom range end. Must be provided with start; maximum range is 90 days."},includeMachineEngagement:x1},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: ${Eb}. Defaults to delivery.`},eventTypes:{type:"array",description:`Optional event types to include. Supported values: ${Eb}. 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:x1},required:["campaignId"]}},{name:"list_sequence_events",description:"List paginated raw email events for every email step in a sequence, or for one step via automationNodeId. Defaults to deliveries; use eventType or eventTypes to include opens, clicks, bounces, complaints, unsubscribes, sends, or delivery delays. This is the per-recipient event stream - do not page it to count sends. Per-step and per-sequence totals already exist as get_sequence_stats steps[], and list_email_metrics gives the same per-step totals across many sequences at once.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"},automationNodeId:{type:"string",description:"Optional email step to scope the stream to, taken from get_sequence_stats steps[].nodeId or get_sequence nodes. Must be an email step of this sequence. Defaults to every email step."},eventType:{type:"string",description:`Optional single event type. Supported values: ${Eb}. Defaults to delivery.`},eventTypes:{type:"array",description:`Optional event types to include. Supported values: ${Eb}. 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:x1},required:["sequenceId"]}},{name:"list_email_metrics",description:"List per-email metrics across the account: one row per campaign and per sequence email step, each with its own delivery funnel, attributed conversions, and revenueCents. This is the tool for cross-sequence questions - 'how many Email 4s went out across these sequences' is one call with step=4 plus the returned totals, instead of one get_sequence_stats per sequence. Sequence rows carry sequenceId, sequenceName, automationNodeId, and step, so you can group or compare steps yourself. Counts come from the retained event stream (not the 14-day list_email_sends history) and match get_sequence_stats steps[] for the same step. Filter by emailType, sequenceId, campaignId, and step; sort with sort/order; page with page/limit. totals covers every matching email, not just the current page.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},emailType:{type:"string",description:"Optional email type: campaign or sequence. Defaults to both. Implied as sequence when sequenceId or step is set."},sequenceId:{type:"array",description:"Optional sequence IDs to restrict the breakdown to. Omit for every sequence in the account. Cannot be combined with campaignId.",items:{type:"string"}},campaignId:{type:"array",description:"Optional campaign IDs to restrict the breakdown to. Cannot be combined with sequenceId, step, or emailType sequence.",items:{type:"string"}},step:{type:"number",description:"Optional 1-based email step position to keep, counted in graph order per sequence. step 4 keeps only the fourth email of each sequence. Sequence emails only."},period:{type:"string",description:"Optional sliding window: 1h, 24h, 7d, 30d, or 90d. Ignored when start and end are provided. Omit for all-time counts."},start:{type:"string",description:"Optional ISO 8601 custom range start. Must be provided with end."},end:{type:"string",description:"Optional ISO 8601 custom range end. Must be provided with start; maximum range is 90 days. Omit start and end for all-time counts over the full retained window."},sort:{type:"string",description:"Sort field: sent, delivered, opened, clicked, openRate, clickRate, unsubscribed, conversions, revenue, step, or name. Defaults to sent."},order:{type:"string",description:"Sort order: asc or desc. Defaults to desc."},page:{type:"number",description:"Page number, starting at 1. Defaults to 1."},limit:{type:"number",description:"Emails per page. Defaults to 50; maximum 500."},includeMachineEngagement:x1}}},{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:x1},required:[]}}];var t5=[{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 r5=[{name:"list_campaigns",description:"List campaigns. Each item carries `emailPreset`, the linked email's Style > Format (branded or minimal; null for SMS campaigns and standalone raw HTML emails), so chrome can be compared across campaigns without one get_campaign call each. Results are paginated: the default page size is 50 and limit is capped at 100. Always read the returned `pagination` object (`limit`, `offset`, `count`, `total`, `hasMore`) and keep paging with `offset` while `hasMore` is true - a single call does not necessarily return every campaign.",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, sending, cancelled, paused, waiting_approval, or rejected). Rejected campaign results include rejectionComment feedback when provided."},label:{type:"string",description:"Optional label name filter. Only campaigns assigned this label are returned."},limit:{type:"number",description:"Page size from 1 to 100. Defaults to 50."},offset:{type:"number",description:"Zero-based result offset. Defaults to 0."}}}},{name:"get_campaign",description:"Get campaign details and stats, including rejectionComment reviewer feedback for rejected campaigns. `emailId` is the campaign's linked email body - the same record returned by the templates tools - and can be passed as templateId to create_campaign to reuse the design; it is null for SMS campaigns. `emailPreset` reports that email's Style > Format the same way get_sequence does per step (branded or minimal; null for SMS campaigns and standalone raw HTML emails), so campaign chrome can be compared against sequence steps and transactional templates without rendering them - minimal suppresses the company logo at render time. `targetLists` holds the raw audience targeting (IDs only); call get_campaign_audience for resolved list/segment names and a recipient count. Note that `computedLists` is email personalization (product lists rendered inside the email), not audience targeting.",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_campaign_audience",description:"Resolve exactly who a campaign will reach. Returns the targeting kind, resolved list and segment names (flagging references that no longer exist), filter conditions, individual include/exclude adjustments, a plain-language summary, and a live recipient count. Critically, it reports whether targeting is unset - an unset campaign falls back to every active subscriber when scheduled. Use this to verify a scheduled campaign's audience before it sends.",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:"list_email_sends",description:"List and filter the recent sent-email delivery history shown in the dashboard. Search subject/title or recipient, filter by delivery status, email type, bounce type, or source ID, then pass a returned emailSendId to get_email_send for exact open/click timestamps and the complete event timeline. Each row carries recipientEmail, subscriberId, automationNodeId, abTestVariantId, and sent/delivered/opened/clicked timestamps, so rows join into a recipient-level delivery matrix without re-reading the raw event stream. Pass automationNodeId to list only the recipients of one sequence step. Delivery rows are retained for 14 days, so this is the wrong tool for send totals: read get_sequence_stats steps[] or list_email_metrics, which cover the full retained event window.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},search:{type:"string",description:"Case-insensitive search across subject and recipient email."},subject:{type:"string",description:"Case-insensitive subject/title filter."},recipient:{type:"string",description:"Case-insensitive recipient email filter."},status:{type:"string",description:"Delivery status: pending, sent, delivered, opened, clicked, bounced, complained, failed, or suppressed. Opened includes clicked deliveries, matching the dashboard."},emailType:{type:"string",description:"Email type: campaign, transactional, or sequence."},bounceType:{type:"string",description:"Bounce type: Permanent or Transient."},campaignId:{type:"string",description:"Filter deliveries from one campaign."},transactionalEmailId:{type:"string",description:"Filter deliveries from one saved transactional email."},automationId:{type:"string",description:"Filter deliveries from one sequence/automation."},automationNodeId:{type:"string",description:"Filter deliveries from one email step of a sequence, using the nodeId from get_sequence_stats steps[] or get_sequence nodes."},days:{type:"number",description:"History window in days, from 1 to 14. Defaults to 14."},page:{type:"number",description:"Page number starting at 1. Defaults to 1."},limit:{type:"number",description:"Results per page, from 1 to 100. Defaults to 20."},sortField:{type:"string",description:"Sort field: recipientEmail, subject, status, eventAt, sentAt, or createdAt. Defaults to createdAt."},sortOrder:{type:"string",description:"Sort order: asc or desc. Defaults to desc."}}}},{name:"get_email_send",description:"Get an email delivery by emailSendId, including queued and test sends, delivery status, provider failure reason, stored HTML, effective Reply-To, copied-recipient identity and primary email send ID, and the ClickHouse event timeline. `type` is the legacy source category; use `emailType` on the send and `deliveryPolicy` on events for the actual marketing or transactional policy when known. Queue jobs are internal execution details and are not exposed.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},emailSendId:{type:"string",description:"Durable email delivery ID to inspect."}},required:["emailSendId"]}},{name:"create_campaign",description:"Create a new campaign. Omit all content fields to create an empty draft. For net-new natural-language content use `prompt`; do not author HTML or blocks. `blocks` are finished caller-supplied Sequenzy content and `html` is preserved/imported markup. Defaults to draft; status 'sent' only archives an already-sent campaign.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the campaign in. If not provided, uses the currently selected company."},name:{type:"string",description:"Campaign name"},subject:{type:"string",description:"Email subject line. Optional when `prompt` is provided because the generated subject will be used."},previewText:{type:["string","null"],description:"Email preview text. Optional when `prompt` is provided because the generated preview text will be used."},trackingCode:{type:"string",description:"Optional campaign tracking code for UTM templates. Use only when explicitly requested."},status:{type:"string",description:"Initial status: draft or sent. Defaults to draft. Use sent only for imported/already-sent campaigns; it does not send email or create delivery history."},sentAt:{type:"string",description:"ISO date-time for an imported/already-sent campaign. Only valid when status is sent; defaults to now if omitted."},html:{type:"string",description:`Email HTML content. Mutually exclusive with \`blocks\`. Use this for imported provider campaigns. ${H1}`},blocks:{type:"array",description:U0,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:"Shorthand for targeting one saved segment. Equivalent to targetLists {type:'segment', segmentId}. Mutually exclusive with `targetLists`."},targetLists:{type:"object",description:"Campaign audience, saved on the draft. Omit to leave targeting unset and set it later with `update_campaign` or `schedule_campaign`. 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']}]}. Use this to send straight to a list without creating a segment first. Mutually exclusive with `segmentId`.",additionalProperties:!0},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:p0},senderProfileId:{type:"string",description:"Existing sender profile ID (see list_sender_profiles). It already supplies both the From address and display name, so send it on its own and omit fromEmail and fromName."},replyTo:{type:"string",description:"Reply-To address for this campaign. A reply profile is created when needed."},replyToName:{type:"string",description:d0},replyProfileId:{type:"string",description:"Existing reply profile ID (see list_sender_profiles). It already supplies both the Reply-To address and display name, so send it on its own and omit replyTo and replyToName."},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. ${H1}`},blocks:{type:"array",description:U0,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 (see list_sender_profiles). It already supplies both the Reply-To address and display name, so send it on its own and omit replyTo and replyToName."},replyToName:{type:"string",description:d0},fromEmail:{type:"string",description:"Set this campaign's From address. Its domain must be configured and verified."},fromName:{type:"string",description:p0},senderProfileId:{type:"string",description:"Set an existing sender profile (see list_sender_profiles). It already supplies both the From address and display name, so send it on its own and omit fromEmail and fromName."},ccEmails:{type:["array","null"],description:"Addresses CC'd on every recipient's campaign email (max 10). Send an empty array or null to clear them; omit to leave unchanged.",items:{type:"string"},maxItems:10},bccEmails:{type:["array","null"],description:"Addresses BCC'd on every recipient's campaign email (max 10). Send an empty array or null to clear them; omit to leave unchanged.",items:{type:"string"},maxItems:10},campaignData:{type:"object",description:"Set campaign-scoped JSON data for repeat blocks and personalization."},computedLists:{type:"array",description:"Set computed list definitions derived from campaignData at send time.",items:{type:"object"}},targetLists:{type:["object","null"],description:"Replace the draft's saved audience, using the same shapes as `create_campaign`. Send null to clear it and choose the audience in `schedule_campaign` instead; omit to leave it unchanged. Mutually exclusive with `segmentId`.",additionalProperties:!0},segmentId:{type:"string",description:"Shorthand for retargeting the draft at one saved segment. Equivalent to targetLists {type:'segment', segmentId}. Mutually exclusive with `targetLists`."},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, as a one-off send or on a repeating weekly/monthly cadence via `recurringInterval`. Use `recurringInterval` for newsletters that go out on a fixed schedule instead of creating one campaign per issue. Returns dashboard edit and preview URLs.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"},scheduledAt:{type:"string",description:"Future ISO 8601 timestamp for the send, for example 2026-06-01T14:00:00Z."},targetLists:{type:"object",description:"Optional campaign targeting object. Omit to use saved targeting or all active subscribers. Examples: {type:'all'}, {type:'lists', listIds:['list_123']}, {type:'segment', segmentId:'seg_123'}, {type:'filtered', filters:[...], filterJoinOperator:'and'}, or {type:'rules', include:[{type:'lists', listIds:['list_123']}], exclude:[{type:'segments', segmentIds:['seg_123']}]}. Rules audiences require at least one include rule.",additionalProperties:!0},sendTimeOptimization:{type:"boolean",description:"Whether to use send-time optimization."},spreadOverHours:{type:"number",description:"Spread delivery over an integer number of hours from 1 to 72. When set, spread delivery takes precedence over send-time optimization."},recurringInterval:{type:"string",enum:["weekly","monthly"],description:"Repeat this campaign on a cadence starting at scheduledAt. The campaign becomes a recurring template: each run is duplicated and sent automatically, re-evaluating audience membership every time. Omit for a one-shot send; scheduling again without it stops the recurrence."}},required:["campaignId","scheduledAt"],additionalProperties:!1}},{name:"send_test_email",description:"Queue a campaign test email to a single address. Returns a durable emailSendId; pass it to get_email_send for delivery status and failure details.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to test"},to:{type:"string",description:"Email address to send test to"}},required:["campaignId","to"]}},{name:"unschedule_campaign",description:"Return a scheduled campaign to an editable draft. Removes its pending send and recurrence without permanently cancelling it, so it can be edited and scheduled again.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Scheduled campaign ID to return to draft."}},required:["campaignId"],additionalProperties:!1}},{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 s5=[{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 e5=[{name:"list_forms",description:"List saved signup forms for a company, including their server-managed audience settings and public action URLs.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list forms for. If not provided, uses the currently selected company."}},additionalProperties:!1}},{name:"create_form",description:"Create and publish a saved signup form whose opaque formId is a client-safe public capability. The selected lists, tags, duplicate behavior, and success action stay server-side; no API key is needed in the deployed form. This creates the email/name fields only - add typed custom fields (select, textarea, hidden, ...) afterwards with update_form's blocks argument.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the form in. If not provided, uses the currently selected company."},name:{type:"string",description:"Internal saved-form name."},listIds:{type:"array",description:"One or more list IDs that every public submission will be added to. Use list_lists to resolve IDs.",items:{type:"string"}},tagIds:{type:"array",description:"Optional existing tag IDs applied by the saved form. Use list_tags to resolve IDs.",items:{type:"string"}},duplicateStrategy:{type:"string",enum:["skip","merge","overwrite"],description:"How to handle an existing subscriber. Defaults to skip."},buttonText:{type:"string",description:"Optional submit button label."},headline:{type:"string",description:"Optional form headline."},description:{type:"string",description:"Optional supporting form copy."},successMessage:{type:"string",description:"Confirmation shown after a successful submission when redirectUrl is omitted."},redirectUrl:{type:"string",description:"Optional HTTP or HTTPS URL for successful submissions. Omit it to show the saved confirmation message."},showFirstName:{type:"boolean",description:"Whether the generated form also collects first name."},showLastName:{type:"boolean",description:"Whether the generated form also collects last name."},theme:{type:"object",description:"Optional visual theme overrides so the form matches the brand instead of the default accent. Any subset of: accentColor, backgroundColor, textColor, mutedTextColor, cardColor, borderColor (all #rrggbb), borderRadius (0-32), headingFontFamily, bodyFontFamily, density (compact | balanced | spacious).",additionalProperties:!0}},required:["name","listIds"],additionalProperties:!1}},{name:"update_form",description:"Update a saved signup form: rename it, retarget its audience, edit its copy, restyle its theme, or replace its content blocks (for example to remove unwanted blocks that render publicly). Read the current content via list_forms first when editing blocks.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},formId:{type:"string",description:"Saved form ID returned by list_forms or create_form."},name:{type:"string",description:"New internal saved-form name."},listIds:{type:"array",description:"Replacement list targeting. Every public submission will be added to these lists.",items:{type:"string"}},tagIds:{type:"array",description:"Replacement tag IDs applied by the saved form. Pass an empty array to clear tags.",items:{type:"string"}},duplicateStrategy:{type:"string",enum:["skip","merge","overwrite"],description:"How to handle an existing subscriber."},headline:{type:"string",description:"New text for the form's first heading block. Fails if the form has no heading block; edit blocks instead."},description:{type:"string",description:"New text for the form's first paragraph block. Fails if the form has no paragraph block; edit blocks instead."},buttonText:{type:"string",description:"New submit button label."},successMessage:{type:"string",description:"New confirmation message on the success screen."},redirectUrl:{type:"string",description:"HTTP or HTTPS URL for successful submissions. Pass an empty string to switch back to the confirmation message."},theme:{type:"object",description:"Visual theme overrides merged into the current theme. Any subset of: accentColor, backgroundColor, textColor, mutedTextColor, cardColor, borderColor (all #rrggbb), borderRadius (0-32), headingFontFamily, bodyFontFamily, density (compact | balanced | spacious).",additionalProperties:!0},blocks:{type:"array",description:`Full replacement for the form's content blocks. Fetch the current blocks from list_forms, modify them, and send the complete array - the form must keep exactly one required email field and one submit button. Blocks render in array order; every block needs a unique "id" and a "kind", and "sectionId" ("success" or "error") moves a content block into that screen. Input blocks are kind "form-field": { id, kind: "form-field", fieldType, name, label, placeholder, required, defaultValue, showLabel, width ("full" | "half"), mapsTo, options }. fieldType is one of text, email, phone, number, textarea, select, radio, checkbox, consent, hidden. mapsTo is one of email, firstName, lastName, phone, customAttribute and defaults to customAttribute, which stores the answer under the block's "name" as a subscriber custom attribute (name must start with a letter and may contain letters, digits, "_", ".", "-"). select, radio, and checkbox fields require options: [{ value, label, id }] - label and id default to value when omitted. A hidden field with a defaultValue always stores that server-owned value and ignores whatever the page posts; a hidden field with an empty defaultValue stores the value the page submits. Other kinds: heading, text, image, button, divider, spacer, custom-html, feature-grid, testimonial, countdown, form-step, submit-button, success-screen, error-state. Validation errors name the offending property, for example "blocks[3].options[0].value".`,items:{type:"object",additionalProperties:!0}}},required:["formId"],additionalProperties:!1}},{name:"get_form_embed",description:"Get a published saved form's action URL, one-line JavaScript embed, minimal native form action, and fetch example. Use this for Astro, Hugo, Jekyll, Cloudflare Pages, Netlify, GitHub Pages, or any browser integration.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},formId:{type:"string",description:"Saved form ID returned by list_forms or create_form."}},required:["formId"],additionalProperties:!1}}];var a5=[{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 w3=[{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 b3=[{name:"connect_integration",description:"Connect an API-key / webhook-secret integration: polar, paddle, dodo, whop, creem, chargebee, clerk, posthog, or affonso. Check list_integration_capabilities first - each connectable provider lists its exact connectFields there. Credentials are validated against the provider where possible, stored encrypted, and never returned; payment providers queue their initial revenue backfill automatically. The response includes the webhookUrl the user must configure at the provider with the same secret - always relay it. Reconnecting an already-connected provider replaces its stored credentials. OAuth and app-install providers (Stripe, Shopify, Supabase, GitHub, WooCommerce, Meta) are rejected with guidance: their flows need a human in the dashboard. SECURITY: only pass credentials the user explicitly provided for this purpose; suggest the CLI (`sequenzy integrations connect`) or dashboard when the user prefers keeping secrets out of the conversation.",inputSchema:{type:"object",properties:{provider:{type:"string",description:"Provider to connect: polar, paddle, dodo, whop, creem, chargebee, clerk, posthog, or affonso.",enum:["polar","paddle","dodo","whop","creem","chargebee","clerk","posthog","affonso"]},apiKey:{type:"string",description:"Provider API key. Required for every provider except clerk and posthog."},webhookSecret:{type:"string",description:"Signing secret of the webhook you create at the provider, pointed at the returned webhookUrl. Required for every provider. For Chargebee, pass the webhook's basic-auth credentials as username:password."},providerAccountId:{type:"string",description:"Provider account id, required for paddle (seller ID), dodo (business ID), whop (company ID, biz_...), creem (store ID), and chargebee (site name). Polar resolves it from the API key; clerk, posthog, and affonso do not use one."},settings:{type:"object",description:"PostHog only: event delivery scope. Defaults to syncing all non-internal events.",properties:{syncAllEvents:{type:"boolean",description:"Sync every event PostHog delivers."},eventAllowlist:{type:"array",items:{type:"string"},description:"Only sync these PostHog event names. Set syncAllEvents to false when using this."}}},historyImport:{type:"object",description:"PostHog only: import the project's event history after connecting. Needs a personal API key with query read access.",properties:{region:{type:"string",enum:["us","eu"],description:"PostHog Cloud region hosting the project."},projectId:{type:"string",description:"Numeric PostHog project ID."},personalApiKey:{type:"string",description:"PostHog personal API key (phx_...)."}},required:["region","projectId","personalApiKey"]},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},required:["provider","webhookSecret"]}},{name:"get_integration",description:"Inspect one connected integration in depth: what the provider syncs, every event it can emit and when, every matching tag rule, which sequences trigger on those events, recent integration-specific activity, and prioritized recommendations. `observedByAccount` and `accountLastSeenAt` are account-wide because event definitions can also be updated by another integration or the public events API; use the retained activity log for connection-specific delivery diagnosis. Read-only; credentials are never returned. Get the id from list_integrations.",inputSchema:{type:"object",properties:{integrationId:{type:"string",description:"Integration ID from list_integrations."},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},required:["integrationId"]}},{name:"list_integration_capabilities",description:"Describe what Sequenzy's integration providers do, whether or not they are connected. For each provider: category, how it connects, what it syncs, every event it emits with the real-world moment that triggers it, the subscriber attributes it writes, supported actions, availability, and caveats. Use this to answer 'what would connecting Stripe give me?', to compare providers before recommending one, or to check whether an event a sequence needs actually exists for that provider. Coverage differs sharply between providers - only Shopify has storefront browse tracking, and only Stripe and Chargebee cover the full trial lifecycle - so check here rather than assuming.",inputSchema:{type:"object",properties:{provider:{type:"string",description:"Only return this provider, for example `stripe`, `shopify`, `clerk`. Omit to list every provider."},category:{type:"string",description:"Filter by category: payments, ecommerce, auth, analytics, ads, affiliate, cms, developer."},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"list_integration_activity",description:"Read recent integration webhook and sync activity, newest first. This is the log to check when an integration reports connected but contacts or events are not appearing: each row carries the action, status, event type, matched contact, and error. Payloads are sanitized at write time, so no credentials or secrets appear here. Activity is retained for 24 hours only.",inputSchema:{type:"object",properties:{integrationId:{type:"string",description:"Only show activity for this integration."},provider:{type:"string",description:"Only show activity for this provider, for example `stripe`."},status:{type:"string",description:"Filter by status: received, queued, processed, skipped, or failed. Use `failed` to triage a broken integration.",enum:["received","queued","processed","skipped","failed"]},limit:{type:"number",description:"Rows to return, 1-100. Defaults to 25."},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"set_integration_sync_enabled",description:"Turn a supported payment integration's future bulk imports and backfills on or off. Check get_integration.availableActions first; providers without enable_sync or disable_sync are dashboard-managed. Disabling keeps the connection, credentials, and live webhook delivery active, and requires any in-flight sync to finish first. It does not disconnect the integration. Idempotent: setting the current state succeeds with `changed: false`.",inputSchema:{type:"object",properties:{integrationId:{type:"string",description:"Integration ID from list_integrations."},syncEnabled:{type:"boolean",description:"True to enable sync, false to pause it."},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},required:["integrationId","syncEnabled"]}},{name:"get_integration_pixel",description:"Check whether a Shopify store's storefront tracking pixel is installed and reporting to this account. Read live from Shopify on every call, because a merchant can remove the pixel without Sequenzy hearing about it. ALWAYS check this before promising that browse abandonment, cart recovery, product views, collection views, or storefront search will work: without a live pixel those events never arrive, the sequences built on them never fire, and nothing anywhere reports an error. Returns `pixel.healthy`, the endpoint and signed configuration state, and `dependentEvents` - the event names that rely on this pixel. When `pixel.error` is null and `pixel.healthy` is false, those events are confirmed dark; an error means Shopify could not confirm their state. Fix a confirmed unhealthy state with activate_integration_pixel. Shopify only; other providers return a clear error.",inputSchema:{type:"object",properties:{integrationId:{type:"string",description:"Shopify integration ID from list_integrations or get_integration."},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},required:["integrationId"]}},{name:"activate_integration_pixel",description:"Install the Shopify storefront tracking pixel on the connected store, or repoint an existing one at this account. This is what turns on product views, cart activity, and browse abandonment - the data every browse-abandonment and cart-recovery sequence depends on. Idempotent: an already-live pixel returns `changed: false`. Events start flowing on the next storefront visit and nothing is backfilled for the period the pixel was off, so run it before, not after, building the sequence. If the store granted an older permission set, this fails with a message naming the reconnect step rather than silently doing nothing. Shopify only.",inputSchema:{type:"object",properties:{integrationId:{type:"string",description:"Shopify integration ID from list_integrations or get_integration."},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},required:["integrationId"]}},{name:"sync_integration",description:"Queue a manual re-sync of customers and revenue for a payment provider integration (Stripe, Polar, Paddle, Dodo, Creem, Chargebee, Whop). Returns immediately - poll get_integration to watch `syncStatus` and `lastSyncAt`. Fails with a conflict if a sync is already running, and with a clear error naming the dashboard for providers whose backfill is not API-triggerable (Shopify products, Supabase users, PostHog history, Affonso affiliates). Check `availableActions` on get_integration to see whether this is supported before calling.",inputSchema:{type:"object",properties:{integrationId:{type:"string",description:"Integration ID from list_integrations."},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},required:["integrationId"]}}];var $3=[{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:w5},content:{type:"object",description:qb,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:qb,additionalProperties:!0}},required:["landingPageId"],additionalProperties:!1}},{name:"duplicate_landing_page",description:"Duplicate a landing page. The copy is created as a draft with its own slug and stats, so the original keeps its published URL.",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 to duplicate."},name:{type:"string",description:"Optional name for the copy. Defaults to the original name with a (copy) suffix."},slug:{type:"string",description:"Optional slug for the copy. It will be normalized and made unique within the company."}},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:qb,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:qb,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 Q3=[{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. Returns one page: check pagination.total and pagination.hasMore, and page with offset to read the whole catalog.",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."},limit:{type:"number",description:"Maximum products to return (1-100). Defaults to 50. Compare pagination.total against the products returned to detect truncation."},offset:{type:"number",description:"Number of products to skip. Defaults to 0. Use with limit to page through catalogs larger than 100."}}}},{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."},providerCreatedAt:{type:["string","null"],description:"ISO 8601 creation time from the source catalog. Omit to preserve the stored value; pass null to clear it. Used for newest-product ranking."}},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 with bulk sync enabled. Pass integrationId when more than one Stripe account is connected; otherwise the most recently connected enabled account is used.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},integrationId:{type:"string",description:"Stripe integration ID from list_integrations. Recommended when multiple Stripe accounts are connected."}}}}];var W3=[{name:"render_email",description:"Render a campaign, sequence email step, or template to the exact email-safe HTML that would be sent, for embedding a visual preview in an external builder or dashboard, or for checking merge tags before anyone is enrolled. Pass exactly one target: campaignId, sequenceId plus nodeId, or templateId. Without a subscriber the email renders for a sample contact, so contact-specific merge tags resolve to empty values. Check unresolvedMergeTags in the response to tell an unrecognized tag apart from one that is merely blank for this contact - both render as an empty string, so the HTML alone cannot distinguish them. Only names this render could check are called unknown. Nothing is checkable without the contact's attributes, because a bare {{plan}} reads the same attribute map as {{subscriber.plan}}, so pass subscriberId (or an inline subscriber with customAttributes) to catch typos at all. On top of that, {{event.*}} needs sample event properties in variables, since a real send fills those from the enrolling event, and {{recommendedProducts.*}} is only checkable when a stored subscriberId returns recommendations. Rendering a transactional email is checkable only when variables is passed, since its tags come from the variables of each send call and nothing marks them as such. An optional attribute this contact never had set is kept out of unknown by checking the names other contacts in the account carry, which needs the subscribers:read scope. A sequence step downstream of a create_discount step renders {{discount.*}} with that step's real terms and a clearly fake sample code; when the step is reachable by paths that do not all run the same discount step, or when a template is rendered on its own, {{discount.*}} is reported as no_value rather than as a typo. Links stay clean unless tracking is true. Per-send click redirects and the open pixel are added at send time against a real email send record, so they never appear here.",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 render."},sequenceId:{type:"string",description:"Sequence ID. Requires nodeId."},nodeId:{type:"string",description:"Email step node ID from get_sequence. Requires sequenceId."},templateId:{type:"string",description:"Template ID to render."},subscriberId:{type:"string",description:"Personalize as this stored subscriber. Mutually exclusive with subscriber. The rendered HTML then carries that subscriber's details, so this needs the subscribers:read scope as well."},subscriber:{type:"object",description:"Personalize as an ad-hoc contact that need not exist in the account. Mutually exclusive with subscriberId.",properties:{email:{type:"string",description:"Contact email address."},firstName:{type:"string",description:"Contact first name."},lastName:{type:"string",description:"Contact last name."},customAttributes:{type:"object",description:"Custom attributes used by merge tags and blocks.",additionalProperties:!0}},required:["email"]},variables:{type:"object",description:"Extra merge variables layered over the contact's attributes.",additionalProperties:!0},locale:{type:"string",description:"Force a localization locale instead of deriving it from the contact."},variantId:{type:"string",description:"Render a specific A/B test variant of the campaign or sequence step."},tracking:{type:"boolean",description:"Apply the company's auto-UTM link decoration as a real send would. Defaults to false so the preview shows the author's clean URLs."}},required:[]}}];var F4={companyId:{type:"string",description:"Company ID. If omitted, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID."}},X3={name:{type:"string",description:"Goal name."},description:{type:["string","null"],description:"Optional goal description."},triggerType:{type:"string",enum:["event","attribute_change"],description:"Conversion signal type. Defaults to event when creating."},triggerEventName:{type:["string","null"],description:"Required event name for event goals."},attributePath:{type:["string","null"],description:"Subscriber attribute path required for attribute_change goals."},attributeCondition:{type:["string","null"],enum:["changed","changed_to","changed_from_to",null],description:"How the subscriber attribute must change."},attributeValue:{type:["string","null"],description:"Target value for changed_to or changed_from_to."},attributePreviousValue:{type:["string","null"],description:"Previous value required for changed_from_to."},eventPropertyName:{type:["string","null"],description:"Optional event property whose numeric value is tracked."},eventPropertyLabel:{type:["string","null"],description:"Display label for the tracked event property."},attributionWindowHours:{type:"integer",minimum:1,maximum:720,description:"Attribution window in whole hours."},isActive:{type:"boolean",description:"Whether conversion tracking is active for this goal. Defaults to true when creating."}},J3=[{name:"list_sequence_goals",description:"List persisted conversion goals attached to one sequence in the dashboard.",inputSchema:{type:"object",properties:F4,required:["sequenceId"],additionalProperties:!1}},{name:"create_sequence_goal",description:"Create a persisted event or subscriber-attribute conversion goal for one sequence. Event goals (the default triggerType) require triggerEventName; attribute_change goals require attributePath. This is distinct from create_sequence.goal, which is only an AI content prompt.",inputSchema:{type:"object",properties:{...F4,...X3},required:["sequenceId","name"],additionalProperties:!1}},{name:"update_sequence_goal",description:"Update a persisted sequence conversion goal, including its signal, attribution window, or active state.",inputSchema:{type:"object",properties:{...F4,goalId:{type:"string",description:"Sequence goal ID."},...X3},required:["sequenceId","goalId"],additionalProperties:!1}},{name:"delete_sequence_goal",description:"Delete one persisted sequence conversion goal.",inputSchema:{type:"object",properties:{...F4,goalId:{type:"string",description:"Sequence goal ID."}},required:["sequenceId","goalId"],additionalProperties:!1}}];var LQ={companyId:{type:"string",description:"Company ID. If omitted, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence with an inbound_webhook trigger."}},Y3=[{name:"get_sequence_inbound_webhook",description:"Read the usable URL, mapping, sample payload, and setup status for a sequence inbound webhook.",inputSchema:{type:"object",properties:LQ,required:["sequenceId"],additionalProperties:!1}},{name:"configure_sequence_inbound_webhook",description:"Create or update the secret endpoint attached to a sequence inbound_webhook trigger. On first setup, omitted mapping/sample inputs apply the selected catalog or custom integration defaults; on later calls, omitted inputs keep the saved values, so a captured sample survives mapping-only updates. Use clearFieldMapping to return to pending setup and clearSamplePayload to drop the saved sample.",inputSchema:{type:"object",properties:{...LQ,fieldMapping:{type:"object",properties:{email:{type:"string"},firstName:{type:"string"},lastName:{type:"string"},properties:{type:"object",additionalProperties:{type:"string"}}},required:["email"],additionalProperties:!1},samplePayload:{type:"object",description:"Representative raw webhook payload for mapping setup.",additionalProperties:!0},clearFieldMapping:{type:"boolean",description:"Set true to clear the saved mapping and return the endpoint to pending_setup."},clearSamplePayload:{type:"boolean",description:"Set true to clear the saved sample payload."}},required:["sequenceId"],additionalProperties:!1}},{name:"rotate_sequence_inbound_webhook_secret",description:"Rotate the inbound webhook secret and return a new URL. The previous URL stops working immediately.",inputSchema:{type:"object",properties:LQ,required:["sequenceId"],additionalProperties:!1}}];var G3=[{name:"list_sequences",description:"List all email sequences (automations). Read effectiveStatus (draft, live, enrollment_paused, paused, archived) to know whether a sequence is running: status alone reads `active` even when new enrollments are paused, and the legacy triggerConfig.active flag is not used by the runtime.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list sequences for. If not provided, uses the currently selected company."},status:{type:"string",enum:["draft","active","paused","archived"],description:"Optional dashboard status filter."},search:{type:"string",description:"Case-insensitive search across sequence name and description."},labels:{type:"array",items:{type:"string"},description:"Return sequences assigned any of these dashboard label names."},limit:{type:"number",description:"Page size from 1 to 100. When limit and offset are both omitted, every sequence is returned."},offset:{type:"number",description:"Zero-based result offset."}}}},{name:"get_sequence",description:"Get sequence details, editable step content, and graph topology. Read effectiveStatus (draft, live, enrollment_paused, paused, archived) to know whether a sequence is running: status alone reads `active` even when new enrollments are paused, and the legacy triggerConfig.active flag is not used by the runtime. 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, emailPreset (the per-email Style > Format for native blocks, including emails with supported custom HTML blocks; null when the entire email is standalone raw HTML), 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:"list_sequence_enrollments",description:"List the individual contacts currently enrolled in a sequence, with the node each one is sitting on. Use this when get_sequence_stats gives you enrollmentCounts and you need the actual subscribers behind a number, such as everyone waiting at one step. Filter by currentNodeId (take the ID from get_sequence_stats enrollmentCounts.byCurrentNode or get_sequence nodes), status, subscriberId, or email, and page with limit/offset to export the full list.",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 listed."},currentNodeId:{type:"array",items:{type:"string"},description:"Only return enrollments currently sitting on these sequence node IDs."},status:{type:"array",items:{type:"string",enum:["active","waiting","completed","failed","cancelled"]},description:"Enrollment statuses to include. Defaults to active and waiting, which is every contact still moving through the sequence."},subscriberId:{type:"array",items:{type:"string"},description:"Only return enrollments for these subscriber IDs. Useful for checking where specific contacts stand."},email:{type:"string",description:"Only return enrollments for this exact email address (case-insensitive)."},sort:{type:"string",enum:["enrolled_at_desc","enrolled_at_asc","wait_until_asc","wait_until_desc"],description:"Result order. Defaults to enrolled_at_desc (most recently enrolled first). Use wait_until_asc to see who resumes next."},limit:{type:"number",description:"Enrollments per page, 1-500. Defaults to 50. Use the maximum when exporting."},offset:{type:"number",description:"Number of enrollments to skip. Page until pagination.hasMore is false."}},required:["sequenceId"],additionalProperties:!1}},{name:"send_sequence_test_email",description:"Queue a real test send for one saved email step in a sequence. Call get_sequence first and pass the target email step's nodeId. Accepts 1-10 reviewer email addresses and returns one durable emailSendId per recipient for get_email_send delivery inspection. The sequence is not enabled and no subscribers are enrolled.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID containing the saved email step."},nodeId:{type:"string",description:"Email step nodeId from get_sequence. The node must belong to sequenceId."},recipients:{type:"array",minItems:1,maxItems:10,items:{type:"string",format:"email"},description:"One to ten internal reviewer email addresses. Duplicate addresses are sent only once."}},required:["sequenceId","nodeId","recipients"],additionalProperties:!1}},{name:"create_sequence",description:"Create and persist a disabled draft email sequence, follow-up series, drip campaign, nurture flow, or automation workflow. For natural-language content, provide goal and emailCount. Use explicit steps for finished caller-supplied content, exact workflows, or migrations. Configure trigger plus its relevant field, such as listId, tagName, segmentId, or eventName. Supports email and SMS steps, delays and date waits, actions that dynamically create a provider discount/code (later emails print it with {{discount.code}}), subscriber updates, event filters, enrollment rules, sending windows, and stop conditions. The saved draft appears in list_sequences. Never call enable_sequence unless the user explicitly asks to activate it.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the sequence in. If not provided, uses the currently selected company."},fromEmail:{type:"string",description:"From address for all emails in this sequence. Its domain must be configured and verified."},fromName:{type:"string",description:p0},senderProfileId:{type:"string",description:"Existing sender profile ID (see list_sender_profiles). It already supplies both the From address and display name, so send it on its own and omit fromEmail and fromName."},replyTo:{type:"string",description:"Reply-To address for all emails in this sequence. A reply profile is created when needed."},replyToName:{type:"string",description:d0},replyProfileId:{type:"string",description:"Existing reply profile ID (see list_sender_profiles). It already supplies both the Reply-To address and display name, so send it on its own and omit replyTo and replyToName."},name:{type:"string",description:"Sequence name (e.g., 'User Onboarding', 'Welcome Series')"},description:{type:"string",description:"Optional sequence description shown in the dashboard."},userCancellable:{type:"boolean",description:"Whether subscribers may cancel their own active enrollment."},bccEmails:{type:"array",items:{type:"string"},description:"Email addresses blind-copied on every email in the sequence (max 10)."},labels:{type:"array",items:{type:"string"},description:"Dashboard label names to assign. Missing labels are created."},trigger:{type:"string",enum:["contact_added","tag_added","segment_entered","event_received","inbound_webhook","inactivity","frequency"],description:"Trigger type: contact_added, tag_added, segment_entered, event_received, inbound_webhook, inactivity, or frequency. Defaults to contact_added for a blank dashboard-compatible draft."},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."},stopOnSegmentExit:{type:"boolean",description:"For segment_entered triggers, cancel active enrollments when the contact leaves the segment."},eventName:{type:"string",description:"Event name to trigger on (required for event_received, inbound_webhook, inactivity, and frequency triggers)"},integrationSlug:{type:"string",description:"Catalog integration slug for inbound_webhook, for example cal-com."},integrationEventKey:{type:"string",description:"Catalog integration event key for inbound_webhook."},customIntegration:{type:"object",description:"Custom inbound webhook integration descriptor with name, setupInstructions, samplePayload, and fieldMapping.",properties:{name:{type:"string"},setupInstructions:{type:"string"},samplePayload:{type:"object",additionalProperties:!0},fieldMapping:{type:"object",additionalProperties:!0},docsUrl:{type:"string"},suggestedProperties:{type:"array",items:{type:"object",properties:{name:{type:"string"},path:{type:"string"},description:{type:"string"}},required:["name","path","description"]}}},required:["name","setupInstructions","samplePayload","fieldMapping"]},propertyFilters:{type:"array",description:"Optional filters for event_received or inbound_webhook triggers. The sequence starts only when all filters match. Max 10.",items:{type:"object",properties:{path:{type:"string",description:"Dot-path into the event properties, e.g. 'lineItems[].providerProductId' or 'plan'."},operator:{type:"string",enum:["exists","not_exists","equals","not_equals","one_of","contains","greater_than","less_than"],description:"Comparison operator. one_of matches when the property equals any entry of the value array."},value:{type:["string","number","boolean","array"],items:{type:["string","number"]},maxItems:50,description:"Value to compare against. Required for every operator except exists/not_exists. For one_of, pass an array of strings or numbers (max 50 values); all other operators take a single value."}},required:["path","operator"]}},inactiveDays:{type:"number",description:"Number of days of inactivity (required for inactivity trigger, must be >= 1)"},inactivityBaseline:{type:"string",enum:["sequence_created_at","subscriber_created_at"],description:"When to start counting inactivity for subscribers who never had the event. Defaults to sequence_created_at."},minCount:{type:"number",description:"Minimum event count (required for frequency trigger, must be >= 1)"},timeWindowDays:{type:"number",description:"Time window in days for frequency trigger (required for frequency trigger, must be >= 1)"},emailCount:{type:"number",description:"Number of emails in the sequence (default: 5, max: 10)"},durationDays:{type:"number",description:"Total duration in days used to space AI-generated sequence emails. Only applies when using goal-based AI generation."},emailStyle:{type:"string",enum:["visual","plain"],description:"Style for AI-generated emails: 'visual' (designed, with heroes/imagery/rich sections) or 'plain' (personal, text-first notes with a single button). Only applies to goal-based AI generation. Defaults to the company's saved preference when omitted."},goal:{type:"string",description:"What this sequence should accomplish for AI generation. Be specific to the app's actual features and user journey. Avoid generic goals that don't match the app's business model."},enrollmentMode:{type:"string",enum:["unlimited","one_time","matching_field"],description:"Sequence re-entry mode. Defaults to 'unlimited', which re-enrolls a subscriber every time the trigger fires again - for a tag_added drip that means re-applying the tag sends the whole series a second time, so set 'one_time' unless repeat runs are wanted. Exception: ecommerce.back_in_stock and ecommerce.replenishment_due triggers default to 'matching_field' so each product is notified separately; leave those alone unless the user asks otherwise. Use 'matching_field' only for event_received triggers when duplicate active runs should be blocked per event field value. Changeable later with update_sequence."},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:Q4,stopCondition:{type:"object",description:"Optional explicit auto-stop condition, re-evaluated before every step including the first one. Use { type: 'has_tag', value: 'customer' } to end the sequence when a subscriber gets a tag, { type: 'entered_segment', value: 'segment_123' } when they enter a segment, { type: 'added_to_list', value: 'list_123' } when they join a list, { type: 'field_changed', value: 'plan' } when a subscriber field changes, { type: 'event_received', value: 'onboarding.completed' } when an event is tracked, or { type: 'none', value: null } for no auto-stop. The negative forms are audience guards rather than lifecycle stops: { type: 'does_not_have_tag', value: 'allowlist' } and { type: 'removed_from_list', value: 'list_123' } cancel the run before any step sends unless the subscriber carries that tag or list membership. That is how you restrict a live event or segment trigger to a chosen set of contacts without editing the graph, for example for a first pass on a production trigger or a phased rollout. Guarded-out contacts still enroll and are then cancelled at the trigger node, so they appear as cancellations there rather than in the active or waiting enrollment counts. Clearing the guard does not retry them: nothing re-enrolls them, so they only receive the sequence if the trigger fires for them again, which one-shot triggers never do, and on the one_time enrollment mode a repeated trigger is ignored too because enrollment is blocked by the existence of any earlier run rather than by its outcome. Guard a duplicate sequence and leave the real one ungated, or enroll the missed contacts afterwards with enroll_subscribers_in_sequence, which skips the one_time check.",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. has_tag, added_to_list, entered_segment, field_changed, and event_received stop the run once the thing happens. does_not_have_tag and removed_from_list stop the run whenever the subscriber lacks that tag or list membership, so they act as a required-tag or required-list allowlist for everyone the trigger enrolls."},value:{type:["string","null"],description:"Tag name, list ID, segment ID, field path, or event name for the stop condition. For the does_not_have_tag and removed_from_list guards this is the tag or list a subscriber must have to keep receiving the sequence. Use null or omit for type 'none'."},matchConfig:{type:["object","null"],description:"Optional dashboard-compatible match config: event_property with rules[{entryFieldPath,eventFieldPath}] for event_received, or field_value with operator/value for field_changed.",additionalProperties:!0}},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:qw,subject:{type:"string",description:"Email subject. Required for email steps."},previewText:{type:"string",description:"Email preview text."},blocks:{type:"array",description:Kw,items:{type:"object"}},html:{type:"string",description:`HTML content for email steps. Use this for imported provider HTML. ${H1}`},isTransactional:{type:"boolean",description:"Send this email as transactional and omit the marketing unsubscribe footer."},ccEmails:{type:"array",items:{type:"string"},description:"Addresses CC'd on this email step."},bccEmails:{type:"array",items:{type:"string"},description:"Addresses BCC'd on this email step in addition to sequence BCC."},attachments:{type:"array",items:{type:"object",properties:{filename:{type:"string",description:"Filename shown in the recipient's email client. Event merge tags are supported, for example file-{{event.order_id}}.pdf."},path:{type:"string",description:"Public HTTPS URL or event-backed URL template such as {{event.file_url}}; resolved per enrollment and fetched at send time."}},required:["filename","path"]},description:"URL-backed file attachments for this email step (max 10, 7MB total per email). Paths may use {{event.*}} values from the event that enrolled the subscriber; the resolved public URL is validated and fetched at send time."},...Nb,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:jw,delayMs:{type:"number",description:"Delay before this step in milliseconds. Prefer delay for readability; use delayMs when importing provider waits."},waitUntil:Ow,waitUntilWeekday:Zw,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.${w4}`,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"]}}];var H3=[{name:"update_sequence",description:"Update an existing sequence: both its settings and its steps. Sequence-level settings live directly on this tool - name, description, labels, trigger (with its trigger-specific field), enrollmentMode plus enrollmentFieldPath, enrollmentPaused, userCancellable, stopCondition, sendingWindow, bccEmails, and the sender/reply identity. This is the only way to change enrollmentMode after create_sequence, so use it to move a tag- or event-triggered sequence off the default 'unlimited' re-entry to 'one_time' or 'matching_field'. 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. Deleting a step immediately moves parked recipients to its unique surviving successor, or completes them when no successor remains; inspect migratedRecipientCount and completedRecipientCount in the returned sequence. 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"},description:{type:"string",description:"Sequence description shown in the dashboard."},userCancellable:{type:"boolean",description:"Whether subscribers may cancel their own active enrollment."},labels:{type:"array",items:{type:"string"},description:"Replace dashboard labels by name. Missing labels are created; [] clears labels."},trigger:{type:"string",enum:["contact_added","tag_added","segment_entered","event_received","inbound_webhook","inactivity","frequency"],description:"Atomically replace the existing dashboard trigger. Include the fields required by the new trigger type. Active sequences also require confirmLiveChange:true."},listId:{type:"string",description:"List ID for a contact_added trigger replacement."},tagName:{type:"string",description:"Tag name required for a tag_added trigger replacement."},segmentId:{type:"string",description:"Saved segment ID required for a segment_entered trigger replacement."},stopOnSegmentExit:{type:"boolean",description:"For segment_entered, stop active enrollments when the subscriber leaves the segment."},eventName:{type:"string",description:"Event name required for event_received, inbound_webhook, inactivity, and frequency trigger replacements."},propertyFilters:{type:"array",description:"Optional event-property filters for event_received or inbound_webhook.",items:{type:"object",properties:{path:{type:"string"},operator:{type:"string",enum:["exists","not_exists","equals","not_equals","one_of","contains","greater_than","less_than"]},value:{description:"Scalar comparison value, or an array for one_of."}},required:["path","operator"],additionalProperties:!1}},integrationSlug:{type:"string",description:"Catalog integration slug for inbound_webhook."},integrationEventKey:{type:"string",description:"Catalog integration event key for inbound_webhook."},customIntegration:{type:"object",description:"Typed custom inbound webhook descriptor used instead of a catalog integration.",properties:{name:{type:"string"},setupInstructions:{type:"string"},samplePayload:{type:"object",additionalProperties:!0},fieldMapping:{type:"object",properties:{email:{type:"string"},firstName:{type:"string"},lastName:{type:"string"},properties:{type:"object",additionalProperties:{type:"string"}}},required:["email"],additionalProperties:!1},docsUrl:{type:"string"},suggestedProperties:{type:"array",items:{type:"object",properties:{name:{type:"string"},path:{type:"string"},description:{type:"string"}},required:["name","path","description"],additionalProperties:!1}}},required:["name","setupInstructions","samplePayload","fieldMapping"],additionalProperties:!1},inactiveDays:{type:"number",description:"Days without event activity required for an inactivity trigger."},inactivityBaseline:{type:"string",enum:["sequence_created_at","subscriber_created_at"],description:"Baseline for subscribers who have never produced the inactivity event."},minCount:{type:"number",description:"Minimum event count for a frequency trigger."},timeWindowDays:{type:"number",description:"Frequency trigger lookback window in days."},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:p0},senderProfileId:{type:"string",description:"Set an existing sender profile (see list_sender_profiles). It already supplies both the From address and display name, so send it on its own and omit fromEmail and fromName."},replyTo:{type:"string",description:"Set the Reply-To address for all emails in this sequence."},replyToName:{type:"string",description:d0},replyProfileId:{type:"string",description:"Set an existing reply profile (see list_sender_profiles). It already supplies both the Reply-To address and display name, so send it on its own and omit replyTo and replyToName."},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."},confirmLiveChange:{type:"boolean",description:"Set true only after the user explicitly confirms replacing the trigger of an active sequence. Required with trigger when the sequence is active."},enrollmentMode:{type:"string",enum:["unlimited","one_time","matching_field"],description:"Updated sequence re-entry mode. Use this to move an existing sequence off the default 'unlimited', which re-enrolls a subscriber every time the trigger fires again. '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:Q4,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, which is re-evaluated before every step including the first one. 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: 'added_to_list', value: 'list_123' } to stop when they join a list, or { type: 'none', value: null } to clear it. The negative forms are audience guards rather than lifecycle stops: { type: 'does_not_have_tag', value: 'allowlist' } and { type: 'removed_from_list', value: 'list_123' } cancel the run before any step sends unless the subscriber carries that tag or list membership. That is how you restrict a live event or segment trigger to a chosen set of contacts without editing the graph, for example for a first pass on a production trigger or a phased rollout. Guarded-out contacts still enroll and are then cancelled at the trigger node, so they appear as cancellations there rather than in the active or waiting enrollment counts. Clearing the guard does not retry them: nothing re-enrolls them, so they only receive the sequence if the trigger fires for them again, which one-shot triggers never do, and on the one_time enrollment mode a repeated trigger is ignored too because enrollment is blocked by the existence of any earlier run rather than by its outcome. Guard a duplicate sequence and leave the real one ungated, or enroll the missed contacts afterwards with enroll_subscribers_in_sequence, which skips the one_time check.",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. has_tag, added_to_list, entered_segment, field_changed, and event_received stop the run once the thing happens. does_not_have_tag and removed_from_list stop the run whenever the subscriber lacks that tag or list membership, so they act as a required-tag or required-list allowlist for everyone the trigger enrolls."},value:{type:["string","null"],description:"Tag name, list ID, segment ID, field path, or event name for the stop condition. For the does_not_have_tag and removed_from_list guards this is the tag or list a subscriber must have to keep receiving the sequence."},matchConfig:{type:["object","null"],description:"Optional event_property or field_value match config used by dashboard stop-condition matching.",additionalProperties:!0}},required:["type"]},branch:{type:"object",description:"Insert an if/else branch into an existing sequence. Use get_sequence first to choose afterNodeId and existing target nodes. Each conditional path can provide new steps, targetNodeId, or both; the else path uses elseSteps and/or elseTargetNodeId. A target may be the completion node. Empty paths require allowEmptyPaths: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. Each path can create steps, route directly to an existing targetNodeId, or do both. An else fallback is created automatically.",items:wQ},elseSteps:{type:"array",description:"Optional new steps inside the else fallback path.",items:Tb},elseTargetNodeId:{type:"string",description:"Optional existing node to route the else path to. Use a node ID from get_sequence, including the completion node. If elseSteps are also provided, they run before this target."},allowEmptyPaths:{type:"boolean",description:"Set true only when intentionally creating UI placeholders. A path with targetNodeId is already explicit and does not need this flag."}},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:Tb}},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 for imported provider markup. ${H1}`},htmlContent:{type:"string",description:`Alias for html for imported provider markup. ${H1}`},emailPreset:{type:"string",enum:["branded","minimal"],description:"Per-email Style > Format for native Sequenzy blocks, including emails that contain supported custom HTML blocks. Minimal removes the company logo and uses the simple footer; branded restores the branded chrome. Does not change the company default. Not a lossless toggle: minimal deletes standalone logo blocks, so switching back to branded generates a new logo block with a new id and the company name as alt text - send the authored logo block in `blocks` alongside the branded update to keep it. Not supported when the entire email is standalone raw HTML and must not be combined with html/htmlContent."},blocks:{type:"array",description:`${A0}${b4}`,items:{type:"object"}},isTransactional:{type:"boolean"},ccEmails:{type:"array",items:{type:"string"}},bccEmails:{type:"array",items:{type:"string"}},attachments:{type:"array",items:{type:"object",properties:{filename:{type:"string"},path:{type:"string"}},required:["filename","path"]},description:"URL-backed file attachments for this email step (max 10, 7MB total per email). path may be a public HTTPS URL or an {{event.*}} URL template resolved from the enrollment event at send time. Pass [] to remove all attachments."},...Nb}}},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 for imported provider markup. ${H1}`},htmlContent:{type:"string",description:`Alias for html. ${H1}`},emailPreset:{type:"string",enum:["branded","minimal"],description:"Per-email Style > Format for native Sequenzy blocks, including emails that contain supported custom HTML blocks. Minimal removes the company logo and uses the simple footer; branded restores the branded chrome. Does not change the company default. Not a lossless toggle: minimal deletes standalone logo blocks, so switching back to branded generates a new logo block with a new id and the company name as alt text - send the authored logo block in `blocks` alongside the branded update to keep it. Not supported when the entire email is standalone raw HTML and must not be combined with html/htmlContent."},blocks:{type:"array",description:`${A0}${b4}`,items:{type:"object"}},isTransactional:{type:"boolean"},ccEmails:{type:"array",items:{type:"string"}},bccEmails:{type:"array",items:{type:"string"}},attachments:{type:"array",items:{type:"object",properties:{filename:{type:"string"},path:{type:"string"}},required:["filename","path"]},description:"URL-backed file attachments for this email step (max 10, 7MB total per email). path may be a public HTTPS URL or an {{event.*}} URL template resolved from the enrollment event at send time. Pass [] to remove all attachments."},...Nb}}},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:qw},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 } }. For a direct text-forward email, use changes:{ emailPreset:'minimal' } on its action_email node; this changes only that linked email's Style > Format. 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:W4.properties.nodeId,changes:m9,expectedUpdatedAt:W4.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 or setting several action_email nodes to changes:{ emailPreset:'minimal' } without changing the company theme. 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:W4},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; duplicate_node creates an independent copy; delete_node safely splices a node and immediately moves parked recipients to its unique surviving successor (or completes them when none remains); replace_edges replaces the complete topology. The returned sequence reports migratedRecipientCount and completedRecipientCount. 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."},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. 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 dashboard-compatible typed step into an existing sequence: email, SMS, delay/date wait, discount (later emails print the generated code with {{discount.code}}), subscriber update, tag/list action, outbound webhook, condition gate, wait-for-event, or wired If/Else branch. Use get_sequence first and pass afterNodeId. Branch paths can target existing nodes, including completion. For active sequences, confirm the structural change 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."},type:{type:"string",enum:["email","sms","delay","create_discount","update_subscriber","add_tag","remove_tag","add_to_list","remove_from_list","webhook","condition","logic_wait_for_event","logic_branch"],description:"Dashboard step type. Defaults to email."},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:Kw,items:{type:"object"}},html:{type:"string",description:`HTML content for an imported provider step. Provide either html or blocks, not both. ${H1}`},isTransactional:{type:"boolean",description:"Email only: omit the marketing unsubscribe footer."},ccEmails:{type:"array",items:{type:"string"},description:"Email only: addresses CC'd on this step."},bccEmails:{type:"array",items:{type:"string"},description:"Email only: addresses BCC'd in addition to sequence-level BCC."},attachments:{type:"array",items:{type:"object",properties:{filename:{type:"string"},path:{type:"string"}},required:["filename","path"]},description:"Email only: URL-backed file attachments (max 10, 7MB total per email). path may be a public HTTPS URL or an {{event.*}} URL template resolved from the enrollment event at send time."},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: Reply-To display name override for the new step. Requires replyTo; omit it when using replyProfileId, which already carries its own display name."},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:"Display label for SMS, wait-for-event, or branch steps."},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."},config:{...qw,description:"update_subscriber only: typed subscriber profile/custom-attribute changes."},tagId:{type:"string",description:"Tag ID for tag actions or tag conditions."},tagName:{type:"string",description:"Tag name for tag actions or tag conditions; missing definitions are created."},listId:{type:"string",description:"List ID for list actions or in_list conditions."},listName:{type:"string",description:"Optional cached list display name for list actions."},url:{type:"string",description:"webhook only: destination HTTPS URL called when a subscriber reaches this step. Supports merge tags like {{email}} and {{event.order_id}}."},method:{type:"string",enum:["POST","GET","PUT","PATCH","DELETE"],description:"webhook only: HTTP method. Defaults to POST."},headers:{type:"object",description:"webhook only: optional string-valued request headers. Values support merge tags. Secret values are redacted on sequence reads.",additionalProperties:{type:"string"}},body:{type:"string",description:'webhook only: optional JSON body template for POST/PUT/PATCH. Must be valid JSON as written, with merge tags inside quoted string values ({"email": "{{email}}"}); a tag in a bare value position is rejected. Tags are resolved at execution time; when omitted, the default payload with subscriber and sequence context is sent.'},resultKey:{type:"string",description:"webhook only: when set, the HTTP response is saved and later email steps can reference it via {{webhooks.KEY.data.field}} merge tags. Must start with a letter; letters, numbers, underscores; max 64 chars."},onError:{type:"string",enum:["continue","exit","fail"],description:"webhook only: behavior when the request fails. continue proceeds to the next step, exit ends the sequence for the subscriber, fail marks the enrollment failed (default)."},segmentId:{type:"string",description:"Segment ID for in_segment conditions."},segmentName:{type:"string",description:"Optional cached segment display name."},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 only: condition evaluated before continuing."},linkUrl:{type:"string"},activityScope:{type:"string",enum:["ever","this_sequence","previous_email"]},fieldName:{type:"string"},fieldValue:{type:"string"},delay:jw,delayMs:{type:"number",description:"Optional wait in milliseconds before the new step. Prefer delay for readability."},waitUntil:Ow,waitUntilWeekday:Zw,eventName:{type:"string",description:"logic_wait_for_event only: event to wait for, for example email.replied."},timeoutDays:{type:"number",description:"logic_wait_for_event only: maximum wait in whole days from 1 to 365. Defaults to 7."},timeoutAction:{type:"string",enum:["continue","exit"],description:"logic_wait_for_event only: continue to the next node or exit the sequence when the timeout is reached. Defaults to continue."},discount:{type:"object",description:"create_discount only: provider discount configuration.",additionalProperties:!0},provider:{type:"string",enum:["stripe","shopify"]},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"},branches:{type:"array",description:"logic_branch only: ordered conditional paths. Each path may provide targetNodeId, steps, or both.",items:wQ},elseSteps:{type:"array",description:"logic_branch only: optional new steps for the else path.",items:Tb},elseTargetNodeId:{type:"string",description:"logic_branch only: existing node for the else path, such as the original follow-up node or completion node."},allowEmptyPaths:{type:"boolean",description:"logic_branch only: set true only to create empty dashboard placeholders. Explicit target nodes do not require it."}},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:"duplicate_sequence",description:"Create an independent draft copy of a sequence, including its graph, email templates, and sequence A/B tests. The original is not changed.",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 copy."},name:{type:"string",description:"Optional name for the copy. Defaults to the original name plus (Copy)."}},required:["sequenceId"]}},{name:"archive_sequence",description:"Archive a sequence and stop new enrollments. Archived sequences remain available in the dashboard's archive.",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 archive."}},required:["sequenceId"]}},{name:"unarchive_sequence",description:"Restore an archived sequence as a disabled draft so it can be reviewed before activation.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Archived sequence ID to restore."}},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: cancelAll to drain every active/waiting enrollment (use this to fully stop a live sequence instead of only freezing enrollment), subscriberIds for a specific batch, subscriberId for one subscriber, or fieldValues to match stored entry event properties. Every bulk target defaults to dryRun, so pass dryRun false to actually cancel. Bulk cancellation is capped per call: while the response reports remainingCount above zero, call again with the same arguments until it reaches zero.",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."},cancelAll:{type:"boolean",description:"Cancel every active/waiting enrollment in the sequence, regardless of how contacts entered it. Use this when segment-triggered enrollments expose no shared entry field value. Defaults to dryRun; pass dryRun false to apply."},subscriberId:{type:"string",description:"Subscriber ID to cancel in this sequence. Provide exactly one target."},subscriberIds:{type:"array",items:{type:"string"},description:"Up to 500 subscriber IDs to cancel in this sequence. IDs that do not resolve come back in target.notFoundSubscriberIds. Provide exactly one target."},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 exactly one target."},dryRun:{type:"boolean",description:"When true, returns matching enrollments without cancelling them. cancelAll, subscriberIds, and fieldValues default to dryRun unless explicitly false; a single subscriberId cancels immediately."},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 _V={type:"object",properties:{email:{type:"string",description:"Subscriber email address. Optional when the record has a phone - such rows import as phone-only (SMS) contacts."},externalId:{type:"string",description:"Customer-owned subscriber ID"},firstName:{type:"string"},lastName:{type:"string"},phone:{type:"string",description:"Phone number. National-format values use the batch defaultPhoneCountry."},status:{type:"string",enum:["active","unsubscribed","bounced"]},tags:{type:"array",items:{type:"string"}},customAttributes:{type:"object",description:"CRM fields and other custom attributes. Values may be strings, numbers, booleans, arrays of those scalar values, or null.",additionalProperties:!0},createdAt:{type:"string",description:"Original signup date (ISO 8601) from the source platform. Set this when migrating so date-relative segments are correct immediately rather than treating every imported contact as having joined today. An existing contact's date only ever moves earlier."}},required:[],additionalProperties:!1},z3=[{name:"add_subscriber",description:"Add one subscriber. Status is only applied when creating a new contact; use update_subscriber to change an existing contact's status. For multiple contacts or CRM records, use create_subscriber_import instead of looping this tool. For an email-only batch going into one list, add_subscribers_to_list is also available.",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. Optional when phone is provided - a contact created with only a phone becomes a phone-only (SMS) contact."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide this with email when creating, or instead of email for an existing subscriber."},phone:{type:"string",description:"Phone number in E.164 or national format, stored as a native profile field. With no email, creates or matches a phone-only (SMS) contact."},phoneCountry:{type:"string",description:"ISO 3166-1 alpha-2 country used to read a national-format phone number, such as IT or US. Defaults to US. Only send it together with phone; the stored country always comes from the parsed number."},smsConsent:{type:"boolean",description:"Set true only when express written SMS marketing consent was verified for this phone number. Never inferred from phone presence."},firstName:{type:"string",description:"Subscriber first name, stored as a native profile field."},lastName:{type:"string",description:"Subscriber last name, stored as a native profile field."},attributes:{type:"object",description:"Custom attributes (plan, company, etc.). Use firstName/lastName for names instead of attributes."},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",enum:["active","unsubscribed","bounced"],description:"Initial subscriber status: active, unsubscribed, or bounced. Defaults to active and does not change an existing contact; use update_subscriber for existing contacts."},optInMode:{type:"string",enum:["default","confirmed","double_opt_in"],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."},createdAt:{type:"string",description:"Original signup date (ISO 8601) when importing a contact from another platform. Preserves their real history so date-relative segments like 'added in the last 30 days' are correct immediately instead of treating every imported contact as brand new. An existing contact's date only ever moves earlier. Supplying this also stops welcome sequences from firing, since it describes the past rather than a signup happening now."}},required:[]}},{name:"create_subscriber_import",description:"Queue one CRM-grade subscriber import with up to 5,000 full contact records. Supports names, external IDs, phones, statuses, tags, lists, and custom attributes. Prefer this over repeated add_subscriber calls. Returns an import ID for get_subscriber_import. Use optInMode='confirmed' only when the contacts already gave verified email consent.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},subscribers:{type:"array",minItems:1,maxItems:5000,items:_V,description:"Full subscriber records to import in one batch."},duplicateStrategy:{type:"string",enum:["skip","merge","overwrite"],description:"How existing contacts are handled. Defaults to skip. Merge fills missing fields; overwrite replaces public fields without reactivating unsubscribed contacts."},fileName:{type:"string",description:"Optional source label shown in import history, such as copper-export.csv."},listIds:{type:"array",items:{type:"string"},description:"Lists to add every successfully imported active subscriber to."},enrollInSequences:{type:"boolean",description:"Whether matching sequences may enroll imported contacts. Defaults to false and requires automations:trigger."},defaultPhoneCountry:{type:"string",description:"ISO 3166-1 alpha-2 country used for national-format phone numbers, such as SG or US."},smsConsent:{type:"boolean",description:"Set true only when express written SMS marketing consent was verified for every imported phone number."},optInMode:{type:"string",enum:["default","confirmed","double_opt_in"],description:"Email consent mode. Default follows workspace double opt-in settings. Confirmed creates active contacts immediately and must only be used for verified consent. Double_opt_in may send confirmation email and requires automations:trigger."}},required:["subscribers"]}},{name:"get_subscriber_import",description:"Get progress, counts, skipped reasons, and failure summaries for a queued subscriber import.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},importId:{type:"string",description:"Import ID or batch ID returned by create_subscriber_import."}},required:["importId"]}},{name:"update_subscriber",description:"Update an existing subscriber's profile, phone, status, attributes, or tags. Names and phones are native profile fields - set them here rather than as custom attributes. Setting status to unsubscribed suppresses the contact from all marketing, deactivates list memberships, and cancels active sequence enrollments while preserving the record and suppression history.",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."},firstName:{type:"string",description:"New first name, stored as a native profile field. Pass an empty string to clear it."},lastName:{type:"string",description:"New last name, stored as a native profile field. Pass an empty string to clear it."},phone:{type:"string",description:"New phone number in E.164 or national format, stored as a native profile field. Pass an empty string to clear it, which is rejected for a phone-only (SMS) contact that has no email. Changing the number resets SMS consent unless smsConsent is sent in the same call."},phoneCountry:{type:"string",description:"ISO 3166-1 alpha-2 country used to read a national-format phone number, such as IT or US. Defaults to US. Only send it together with phone; the stored country always comes from the parsed number."},smsConsent:{type:"boolean",description:"Set true only when express written SMS marketing consent was verified for this phone number; false unsubscribes them from SMS. Omitting this leaves consent unchanged unless phone changes, which resets consent because it belonged to the old number. Consent is never inferred from phone presence."},status:{type:"string",enum:["active","unsubscribed","bounced"],description:"New global subscriber status. Use unsubscribed for compliance-grade suppression without deleting the record. Use active only when the contact has valid consent to be resubscribed."},attributes:{type:"object",description:"Custom attributes to update. Use firstName/lastName for names instead of attributes."},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 a subscriber while preserving the record and suppression history. Only permanently deletes when hardDelete is true.",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 the subscriber and suppression history. Defaults to false, which globally unsubscribes the contact, deactivates list memberships, and cancels active sequence enrollments."}},required:[]}},{name:"get_subscriber",description:"Get the full subscriber profile, including tags, notes, list memberships, sequence enrollments, email stats, and recent activity. For commerce customers, customAttributes include nightly predictive analytics: predictedLtv (next-12-month spend), churnRisk (percent), expectedNextOrderAt, avgDaysBetweenOrders, and predictionConfidence.",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:x1},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:"trigger_subscriber_event",description:"Emit a custom event for one subscriber, exactly as an integration or the public API would. This is the supported way to exercise event triggers, matching-field idempotency, branch conditions, and stop conditions end to end without waiting for real traffic. The event is recorded, sync rules apply, and matching event_received sequences enroll. Creates the subscriber if they do not exist. Use trigger_subscriber_events for several events on the same contact.",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."},event:{type:"string",description:"Event name, such as saas.purchase or invoice.paid. The event definition is created if it does not exist."},properties:{type:"object",description:"Event properties. Include the sequence's matching field (for example order.id or invoice.id) when testing idempotency or cancellation by field value.",additionalProperties:!0},firstName:{type:"string",description:"First name applied to the subscriber profile."},lastName:{type:"string",description:"Last name applied to the subscriber profile."},attributes:{type:"object",description:"Custom attributes to set on the subscriber.",additionalProperties:!0},occurredAt:{type:"string",description:"When the event actually happened (ISO 8601). Omit for live events. If this is more than an hour in the past the event is recorded as history: it is stored with its real timestamp and counts for segments and the timeline, but no sequences enroll, no sync rules apply, no waiting steps resume, and no webhooks fire. A historical event also moves the contact's signup date back to when it occurred (never later), so imported contacts do not read as added today. Use this when backfilling from another platform - never to fake a live event, since the side effects you are testing will not run."},eventId:{type:"string",description:"Your own id for this event. Makes a historical import idempotent: re-sending the same eventId writes nothing new."}},required:["event"]}},{name:"trigger_subscriber_events",description:"Emit several custom events for one subscriber in order. Events are processed independently and sequentially, so a partial failure can still leave earlier events recorded.",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."},events:{type:"array",minItems:1,maxItems:500,items:{type:"object",properties:{name:{type:"string",description:"Event name"},properties:{type:"object",description:"Event properties",additionalProperties:!0},occurredAt:{type:"string",description:"When the event actually happened (ISO 8601). When every event in the batch is more than an hour old the batch is imported as history in one idempotent write, with no sequences, sync rules, waiting steps or webhooks; the contact's signup date also moves back to the earliest event in the batch (never later)."},eventId:{type:"string",description:"Your own id for this event, making a re-run idempotent."}},required:["name"],additionalProperties:!1},description:"Events to trigger, in order, for this subscriber."},firstName:{type:"string"},lastName:{type:"string"},attributes:{type:"object",description:"Custom attributes to set on the subscriber.",additionalProperties:!0}},required:["events"]}},{name:"bulk_add_subscriber_tags",description:"Add tags to up to 500 existing subscribers in one call, identified by emails, externalIds, or subscriberIds. Built for reconciling historical or derived tags: subscribers that do not exist are reported in notFound instead of being created, and tag automations do NOT run unless triggerAutomations is true. Needs the subscribers:tag scope; a tag name that does not exist yet also needs tags:write. The agent_safe key preset includes both. Use add_subscriber or update_subscriber for single-contact changes.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},tags:{type:"array",minItems:1,items:{type:"string"},description:"Tag names to add to every matched subscriber."},emails:{type:"array",items:{type:"string"},description:"Subscriber emails to tag. Combine with externalIds/subscriberIds as needed; at least one identifier list is required."},externalIds:{type:"array",items:{type:"string"},description:"Customer-owned subscriber IDs to tag."},subscriberIds:{type:"array",items:{type:"string"},description:"Sequenzy subscriber IDs to tag."},triggerAutomations:{type:"boolean",description:"Whether tag_added sequences may enroll these contacts. Defaults to false, which is what backfills want. Requires the automations:trigger scope."}},required:["tags"]}},{name:"bulk_remove_subscriber_tags",description:"Remove tags from up to 500 existing subscribers in one call, identified by emails, externalIds, or subscriberIds. Subscribers that do not exist are reported in notFound. Needs the subscribers:tag scope; the broader subscribers:write scope also satisfies it. Use this to roll back or reconcile a derived-tag backfill.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},tags:{type:"array",minItems:1,items:{type:"string"},description:"Tag names to remove from every matched subscriber."},emails:{type:"array",items:{type:"string"},description:"Subscriber emails to untag."},externalIds:{type:"array",items:{type:"string"},description:"Customer-owned subscriber IDs to untag."},subscriberIds:{type:"array",items:{type:"string"},description:"Sequenzy subscriber IDs to untag."}},required:["tags"]}},{name:"search_subscribers",description:"Search subscribers by free-text query, tags, list, segment, or custom attribute. If you omit limit, the tool fetches all pages and returns every match in one call - that is the fastest way to enumerate an audience. To walk a large audience in chunks instead, pass limit and then follow pagination.nextCursor (or pagination.nextOffset) until pagination.hasMore is false. Default searches are newest first; searches with attribute use stable subscriber-ID ascending order.",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."},attribute:{type:"string",description:'Filter by custom attribute name, e.g. "plan". Pair with attributeValue and attributeOperator. The wire form "name:value" is also accepted. Cannot be combined with segmentId - use a saved segment for compound attribute filters.'},attributeValue:{type:"string",description:"Value the custom attribute is compared against. Omit only when attributeOperator is is_not_empty."},attributeOperator:{type:"string",enum:[...$4],description:"How to compare the custom attribute. Defaults to is. Use is_not_empty to match every subscriber that has the attribute set to any value. For is_not, not_contains, or is_empty, create a segment and pass segmentId instead."},limit:{type:"number",minimum:1,description:"Maximum results to return. If omitted, the tool returns all matches across pages."},offset:{type:"number",minimum:0,maximum:999999,description:"Number of matches to skip before returning results, up to 999999. Use with limit to page through a large audience; follow pagination.nextOffset from the previous response, then switch to nextCursor for deeper pagination."},page:{type:"number",description:"1-based page number, an alternative to offset. Requires limit, which defines the page size. Cannot be combined with offset."},cursor:{type:"string",description:"pagination.nextCursor from the previous response. The cheapest way to walk a large audience in chunks, because the server does not re-scan the rows already returned. Cannot be combined with offset or page."}}}}];var D3={companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Exact recipient email address to inspect or clean up."},region:{type:"string",description:"Optional AWS SES region such as us-east-1. Omit to check every SES region currently used by the company."}},B3=[{name:"get_recipient_suppression",description:"Check whether one recipient is suppressed by Sequenzy's bounce/complaint safeguards or the regional Amazon SES account-level suppression list. This exact-address lookup never exposes other recipients from the shared SES account.",inputSchema:{type:"object",properties:D3,required:["email"],additionalProperties:!1}},{name:"remove_recipient_suppression",description:"Remove stale bounce suppression for an exact recipient associated with the company. Clears matching Amazon SES bounce entries and Sequenzy's local bounce block, then reactivates bounced company subscribers. Complaint and unsubscribe protections are never removed.",inputSchema:{type:"object",properties:D3,required:["email"],additionalProperties:!1}}];var L3=[{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:[...Mw],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:[...Mw],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:g9,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 commerce collection filter (anyone who bought any product in the collection; value is a collection id or handle): [{"id":"filter-1","field":"commerceCollection","operator":"is","value":"skincare"}]. 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:{...i9,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:g9,minItems:1,description:"Replacement segment filters. Same shape and validation rules as create_segment. Mutually exclusive with `root`."},root:{...i9,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 F3=[{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 U3=[{name:"list_templates",description:"List the company's email bodies newest first, including per-locale localization sync status and each body's `emailPreset` Style > Format (branded or minimal; null for standalone raw HTML). Results include standalone templates plus the bodies behind campaigns and transactional emails. Returns 50 per call by default (100 max); page with offset while pagination.hasMore is true, and read pagination.total for the full count. You can also pass a campaign's emailId to get_template to fetch one body directly. Bodies are kept when their campaign or transactional email is deleted.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},label:{type:"string",description:"Optional label name filter. Only templates assigned this label are returned."},limit:{type:"number",description:"Templates per page, 1-100. Defaults to 50."},offset:{type:"number",description:"Templates to skip before returning results. Add pagination.count to the current offset to fetch the next page while pagination.hasMore is true."}}}},{name:"get_template",description:"Get a template's details, content, and all localized variants with sync status. `emailPreset` reports the per-email Style > Format (branded or minimal; null when the whole email is standalone raw HTML) the same way get_sequence does per step.",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. ${H1}`},blocks:{type:"array",description:U0,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`, `previewText`, `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"},previewText:{type:["string","null"],description:"Inbox preview text. Send null to clear the existing preview text."},html:{type:"string",description:`Email HTML content. Mutually exclusive with \`blocks\`. Use this for imported provider templates. ${H1}`},blocks:{type:"array",description:U0,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\`. ${H1}`},blocks:{type:"array",description:U0,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 A3=[{name:"list_transactional_emails",description:"List transactional email templates with subjects, delivery metrics, API slugs, and dashboard URLs. Each item also carries `emailPreset`, the per-email Style > Format (branded or minimal, null for a standalone raw HTML email), so a chrome drift check across templates does not need one get_transactional_email call each. Search by name, slug, or email title; filter active state; and sort by sends, opens, open rate, clicks, or CTR.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},search:{type:"string",description:"Case-insensitive search across template name, API slug, and linked email subject/title."},status:{type:"string",description:"Template status: all, active, or disabled."},sort:{type:"string",description:"Sort field: date, sends, opens, open-rate, clicks, or ctr. Defaults to date."},order:{type:"string",description:"Sort order: asc or desc. Defaults to desc."},includeMachineEngagement:{type:"boolean",description:"Include bot, scanner, and privacy-proxy engagement in open and click metrics. Defaults to false."}},additionalProperties:!1}},{name:"get_transactional_email",description:"Get a transactional email by ID or slug, including subject, preview text, blocks, variables, and linked dashboard URLs. `emailPreset` reports the per-email Style > Format the same way get_sequence does per step (branded or minimal; null when the whole email is standalone raw HTML), so it can be compared against sequence steps and campaigns without rendering them - minimal suppresses the company logo at render time.",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\`. ${H1}`},blocks:{type:"array",description:`${U0} 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\`. ${H1}`},blocks:{type:"array",description:`${A0} Mutually exclusive with \`html\`.`,items:{type:"object"}}},required:["idOrSlug"],additionalProperties:!1}},{name:"delete_transactional_email",description:"Permanently delete a saved transactional email template by ID or slug. Use this to retire an obsolete template: the slug stops sending and becomes free to reuse. Already-sent deliveries and their stats are kept, so history and analytics survive the delete. The linked email content stays as a reusable template and comes back as `deleted.emailId`; pass that to `delete_template` to remove the content too. To stop sends without losing the template, call `update_transactional_email` with `enabled` set to false instead.",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"],additionalProperties:!1}},{name:"send_email",description:"Queue one email using either a saved transactional email API slug (`templateId`) or direct `subject` and `html` content. The default delivery policy is transactional. When the recipient matches a subscriber, saved first and last names fill omitted name variables; explicit variables take precedence. Set `emailType` to `marketing` to add subscriber suppression, a marketing footer, and RFC 8058 one-click unsubscribe. Company Reply-To defaults are inherited when no override is provided, and `{{viewInBrowserUrl}}` is replaced with a hosted copy URL. Use `trackingSettings` with `clickTracking` or `openTracking` set to `false` to disable click-link rewriting or the open-tracking pixel for this send only; these opt-out fields cannot enable tracking the account has disabled. Returns a durable emailSendId and the accepted emailType; pass the ID to get_email_send for delivery status and failure details.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},to:{type:"string",description:"Recipient email address"},subject:{type:"string",description:"Email subject line. Required with `html` when `templateId` is omitted."},html:{type:"string",description:"Direct-send HTML body. Required with `subject` when `templateId` is omitted; the MCP server maps this to the transactional API `body` field. Use `{{viewInBrowserUrl}}` for a hosted copy link generated at send time."},templateId:{type:"string",description:"Saved transactional email API slug, for example `welcome-email`. The field name is retained for MCP compatibility and is mapped to the transactional API `slug` field."},variables:{type:"object",description:"Variables for template personalization. Nested objects and arrays are supported for repeat blocks, for example { items: [...] }. When the recipient matches a subscriber, saved first and last names fill omitted name variables; explicit values, including blanks, take precedence. Variables are HTML-escaped; a template can prefix a tag with 'html.' ({{html.prerenderedHtml}}) to insert a trusted, sanitized HTML value unescaped."},subscriberExternalId:{type:"string",description:"Customer-owned subscriber ID for attaching analytics, localization, and saved-name personalization on single-recipient sends. Maximum length: 255 characters."},emailType:{type:"string",description:"Delivery policy: `transactional` (default) or `marketing`. Marketing mode supports exactly one recipient and automatically applies subscriber suppression, the standard unsubscribe footer, and RFC 8058 headers."},replyTo:{type:"string",description:"Optional Reply-To address, formatted as `email@example.com` or `Name <email@example.com>`. When omitted, the saved template or company default is used."},trackingSettings:{type:"object",description:"Per-send tracking opt-outs. Each field defaults to `true`, meaning the account tracking settings apply; set a field to `false` to disable that tracking for this send only. These fields cannot enable tracking the account has disabled.",properties:{clickTracking:{type:"boolean",description:"Set to `false` to skip click-link rewriting for this send only, which helps when tracking redirects break universal or deep links."},openTracking:{type:"boolean",description:"Set to `false` to skip the open-tracking pixel for this send only."}},additionalProperties:!1}},required:["to"],additionalProperties:!1}}];var K3=[{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:[...Vw]},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:[...Vw]},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 U4=[...p5,...b3,...z3,...B3,...Q3,...L3,...t5,...U3,...n5,...r5,...W3,...e5,...$3,...a5,...G3,...H3,...J3,...Y3,...A3,...o5,...F3,...w3,...K3,...d5,...s5];async function O3(w,b){let $;switch(w){case"get_account":{let Q=await D("GET","/api/v1/account"),W=h0();$={...Q,selectedCompanyId:W??Q.currentCompanyId};break}case"select_company":{let Q=b.companyId,W=await D("GET","/api/v1/account"),X=W.companies?.find((J)=>J.id===Q);if(!X)throw Error(`Company not found. Available companies: ${W.companies?.map((J)=>`${J.name} (${J.id})`).join(", ")??"none"}`);j4(Q),$={success:!0,message:`Switched to company: ${X.name}`,companyId:X.id,companyName:X.name};break}case"get_app_urls":{let Q=await B4(b);$={...F0({companyId:Q,campaignId:U(b,"campaignId"),landingPageId:U(b,"landingPageId"),sequenceId:U(b,"sequenceId"),emailId:U(b,"emailId")??U(b,"templateId"),transactionalId:U(b,"transactionalId"),emailSendId:U(b,"emailSendId"),domainId:U(b,"domainId"),status:U(b,"status"),settingsTab:U(b,"settingsTab")}),...Q===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 Q=await D("POST","/api/v1/companies",{name:b.name,domain:b.domain});if(!Q.success)throw Error("Failed to create company");let W=Q.company.id,X=6,J=0,Y=Q.company.status;while(Y==="processing"&&J<X){await new Promise((z)=>setTimeout(z,20000)),J++;let H=await D("GET",`/api/v1/companies/${W}`);if(H.success)Y=H.company.status}j4(W);let G=await D("GET",`/api/v1/companies/${W}`);$={success:!0,company:G.company,message:Y==="processing"?"Company created but still processing. You can continue using it while processing completes.":`Company '${G.company.name}' created and ready to use.`,autoSelected:!0};break}case"get_company":{let Q=b.companyId;$=await D("GET",`/api/v1/companies/${Q}`);break}case"update_company":{let Q=await vb("update_company",b),W=G5(b);$=await D("PATCH",`/api/v1/companies/${Q}`,W);break}case"get_sync_rules":{let Q=b.companyId;$=await D("GET","/api/v1/sync-rules",void 0,Q);break}case"update_sync_rules":{let Q=b.companyId;if(b.syncRules!==null&&!Array.isArray(b.syncRules))throw Error("`syncRules` must be an array of rules or null when calling `update_sync_rules`.");$=await D("PUT","/api/v1/sync-rules",{syncRules:b.syncRules},Q);break}case"get_shopify_automation_settings":{let Q=b.companyId;$=await D("GET","/api/v1/shopify/automation-settings",void 0,Q);break}case"update_shopify_automation_settings":{let Q=b.companyId,W={};if(b.browseAbandonment!==void 0)W.browseAbandonment=b.browseAbandonment;if(b.cartAbandonment!==void 0)W.cartAbandonment=b.cartAbandonment;if(b.priceDrop!==void 0)W.priceDrop=b.priceDrop;if(Object.keys(W).length===0)throw Error("Provide `browseAbandonment`, `cartAbandonment`, and/or `priceDrop` when calling `update_shopify_automation_settings`.");$=await D("PUT","/api/v1/shopify/automation-settings",W,Q);break}case"create_api_key":{let Q=b.companyId,W={};if(typeof b.name==="string")W.name=b.name;if(typeof b.preset==="string")W.preset=b.preset;if(Array.isArray(b.scopes))W.scopes=b.scopes;$=await D("POST","/api/v1/api-keys",W,Q);break}case"list_api_keys":{let Q=await vb(w,b);$=await D("GET","/api/v1/api-keys",void 0,Q);break}case"update_api_key":{let Q=await vb(w,b),W={};if(typeof b.name==="string")W.name=b.name;if(typeof b.preset==="string")W.preset=b.preset;if(Array.isArray(b.scopes))W.scopes=b.scopes;if(Object.keys(W).length===0)throw Error("Provide at least one of `name`, `preset`, or `scopes` when calling `update_api_key`.");$=await D("PATCH",`/api/v1/api-keys/${encodeURIComponent(String(b.apiKeyId))}`,W,Q);break}case"revoke_api_key":case"delete_api_key":{let Q=await vb(w,b);$=await D("DELETE",`/api/v1/api-keys/${encodeURIComponent(String(b.apiKeyId))}`,void 0,Q);break}case"list_websites":{let Q=b.companyId;$=await D("GET","/api/v1/websites",void 0,Q);break}case"add_sending_domain":case"add_website":{let Q=b.companyId;$=await D("POST","/api/v1/websites",{domain:b.domain},Q);break}case"check_website":{let Q=b.companyId;$=await D("GET",`/api/v1/websites/${encodeURIComponent(String(b.domain))}`,void 0,Q);break}case"verify_sending_domain":{let Q=b.companyId;$=await D("POST",`/api/v1/websites/${encodeURIComponent(String(b.domain))}/verify`,void 0,Q);break}case"list_integrations":{let Q=b.companyId,W=new URLSearchParams;if(b.includeInactive===!0)W.set("includeInactive","true");let X=W.toString();$=await D("GET",`/api/v1/integrations${X?`?${X}`:""}`,void 0,Q);break}case"list_sender_profiles":{let Q=b.companyId;$=await D("GET","/api/v1/sender-profiles",void 0,Q);break}case"update_sender_profile":{let{companyId:Q,profileId:W}=b,X=b.type==="reply"?`/api/v1/reply-profiles/${encodeURIComponent(W)}`:`/api/v1/sender-profiles/${encodeURIComponent(W)}`;$=await D("PATCH",X,{name:b.name},Q);break}case"get_sending_status":{let Q=b.companyId;$=await D("GET","/api/v1/sending-status",void 0,Q);break}case"resume_sending":{let Q=b.companyId;$=await D("POST","/api/v1/sending-status/resume",{listSanitizationConfirmed:b.listSanitizationConfirmed===!0},Q);break}case"get_tracking_settings":{let Q=b.companyId;$=await D("GET","/api/v1/tracking-settings",void 0,Q);break}case"update_tracking_settings":{let Q=b.companyId,W=H5(b);$=await D("PATCH","/api/v1/tracking-settings",W,Q);break}case"get_notification_preferences":{let Q=b.companyId;$=await D("GET","/api/v1/notification-preferences",void 0,Q);break}case"update_notification_preferences":{let Q=b.companyId;$=await D("PATCH","/api/v1/notification-preferences",{notificationPreferences:b.notificationPreferences},Q);break}case"get_integration_guide":$=await D("POST","/api/v1/integration-guide",b);break;default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function Z3(w,b){let $;switch(w){case"generate_email":{let Q=b.companyId;$=await D("POST","/api/v1/generate/email",b,Q);break}case"generate_subject_lines":{let Q=b.companyId;$=await D("POST","/api/v1/generate/subjects",b,Q);break}case"generate_sms":{let Q=b.companyId;$=await D("POST","/api/v1/generate/sms",b,Q);break}case"get_sms_settings":{let Q=b.companyId;$=await D("GET","/api/v1/sms/settings",void 0,Q);break}case"send_test_sms":{let Q=b.companyId,W={to:M("send_test_sms",b,"to")};for(let X of["text","imageUrls","blocks"])if(b[X]!==void 0)W[X]=b[X];$=await D("POST","/api/v1/sms/test",W,Q);break}case"submit_feedback":{let Q=b.companyId,W={message:M("submit_feedback",b,"message"),source:"mcp"};for(let X of["category","context"])if(b[X]!==void 0)W[X]=b[X];$=await D("POST","/api/v1/feedback",W,Q);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function j3(w,b){let $;switch(w){case"list_transactional_emails":{let Q=b.companyId,W=new URLSearchParams,X=U(b,"search"),J=l("list_transactional_emails",b,"status",["all","active","disabled"]),Y=l("list_transactional_emails",b,"sort",["date","sends","opens","open-rate","clicks","ctr"]),G=l("list_transactional_emails",b,"order",["asc","desc"]);if(X)W.set("search",X);if(J)W.set("status",J);if(Y)W.set("sort",Y);if(G)W.set("order",G);if(b.includeMachineEngagement===!0)W.set("includeMachineEngagement","true");let H=W.toString();$=await D("GET",`/api/v1/transactional${H?`?${H}`:""}`,void 0,Q);break}case"get_transactional_email":{let Q=b.companyId;$=await D("GET",`/api/v1/transactional/${b.idOrSlug}`,void 0,Q);break}case"create_transactional_email":{let Q=b.companyId,W=new Set(["companyId","name","slug","subject","previewText","html","blocks","prompt","style","tone","enabled"]),X=Object.keys(b).filter((Y)=>!W.has(Y));if(X.length>0)throw Error(`\`create_transactional_email\` accepts only \`name\`, \`slug\`, \`subject\`, \`previewText\`, \`html\`, \`blocks\`, \`prompt\`, \`style\`, \`tone\`, and \`enabled\` fields. Unsupported field${X.length===1?"":"s"}: ${X.map((Y)=>`\`${Y}\``).join(", ")}.`);I5(b);let J=Object.fromEntries(Object.entries(b).filter(([Y])=>Y!=="companyId"));$=await D("POST","/api/v1/transactional",J,Q);break}case"update_transactional_email":{let Q=b.companyId,W=new Set(["companyId","idOrSlug","name","enabled","subject","previewText","html","blocks"]),X=Object.keys(b).filter((Y)=>!W.has(Y));if(X.length>0)throw Error(`\`update_transactional_email\` accepts only \`name\`, \`enabled\`, \`subject\`, \`previewText\`, \`html\`, and \`blocks\` update fields. Unsupported field${X.length===1?"":"s"}: ${X.map((Y)=>`\`${Y}\``).join(", ")}.`);if(h1("update_transactional_email",b),b.name===void 0&&b.enabled===void 0&&b.subject===void 0&&b.previewText===void 0&&b.html===void 0&&b.blocks===void 0)throw Error("Provide at least one of `name`, `enabled`, `subject`, `previewText`, `html`, or `blocks` when calling `update_transactional_email`.");let J=Object.fromEntries(Object.entries(b).filter(([Y])=>Y!=="companyId"&&Y!=="idOrSlug"));$=await D("PATCH",`/api/v1/transactional/${b.idOrSlug}`,J,Q);break}case"delete_transactional_email":{let Q=b.companyId,W=M("delete_transactional_email",b,"idOrSlug");$=await D("DELETE",`/api/v1/transactional/${encodeURIComponent(W)}`,void 0,Q);break}case"send_email":{let Q=b.companyId,W=M("send_email",b,"to"),X=b.templateId===void 0?void 0:M("send_email",b,"templateId"),J=b.subject===void 0?void 0:M("send_email",b,"subject"),Y=b.html===void 0?void 0:M("send_email",b,"html"),G=b.emailType===void 0?void 0:M("send_email",b,"emailType"),H=b.replyTo===void 0?void 0:M("send_email",b,"replyTo");if(G!==void 0&&G!=="marketing"&&G!=="transactional")throw Error("`emailType` must be `marketing` or `transactional` when calling `send_email`.");if(X!==void 0&&(J!==void 0||Y!==void 0))throw Error("`templateId` cannot be combined with `subject` or `html` when calling `send_email`.");if(X===void 0&&(J===void 0||Y===void 0))throw Error("Provide either `templateId` or both `subject` and `html` when calling `send_email`.");let z;if(b.trackingSettings!==void 0){if(typeof b.trackingSettings!=="object"||b.trackingSettings===null||Array.isArray(b.trackingSettings))throw Error("`trackingSettings` must be an object with optional boolean `clickTracking` and `openTracking` fields when calling `send_email`.");let L=b.trackingSettings;z={};for(let F of["clickTracking","openTracking"]){let A=L[F];if(A===void 0)continue;if(typeof A!=="boolean")throw Error(`\`trackingSettings.${F}\` must be a boolean when calling \`send_email\`.`);z[F]=A}}let B=Object.fromEntries(Object.entries({to:W,slug:X,subject:J,body:Y,variables:b.variables,subscriberExternalId:b.subscriberExternalId,emailType:G,replyTo:H,trackingSettings:z}).filter(([,L])=>L!==void 0));$=await D("POST","/api/v1/transactional/send",B,Q);break}case"get_stats":{let Q=b.companyId,W=b.period??"7d",X=new URLSearchParams({period:String(W)}),J=b.emailType===void 0?void 0:M("get_stats",b,"emailType");if(J!==void 0&&!["campaign","transactional","sequence"].includes(J))throw Error("`emailType` must be `campaign`, `transactional`, or `sequence` when calling `get_stats`.");if(J)X.set("emailType",J);if(b.includeMachineEngagement===!0)X.set("includeMachineEngagement","true");$=await D("GET",`/api/v1/metrics?${X.toString()}`,void 0,Q);break}case"get_campaign_stats":{let Q=b.companyId,W=new URLSearchParams;if(typeof b.period==="string")W.set("period",b.period);if(typeof b.start==="string")W.set("start",b.start);if(typeof b.end==="string")W.set("end",b.end);if(b.includeMachineEngagement===!0)W.set("includeMachineEngagement","true");let X=W.toString();$=await D("GET",`/api/v1/metrics/campaigns/${b.campaignId}${X?`?${X}`:""}`,void 0,Q);break}case"list_poll_responses":{let Q=b.companyId,W=M("list_poll_responses",b,"campaignId"),X=new URLSearchParams,J=U(b,"blockId");if(J)X.set("blockId",J);for(let G of["page","limit"])if(b[G]!==void 0)X.set(G,String(b[G]));let Y=X.toString();$=await D("GET",`/api/v1/metrics/campaigns/${encodeURIComponent(W)}/poll-responses${Y?`?${Y}`:""}`,void 0,Q);break}case"get_transactional_stats":{let Q=b.companyId,W=M("get_transactional_stats",b,"idOrSlug"),X=new URLSearchParams;for(let Y of["period","start","end"])if(typeof b[Y]==="string"&&b[Y].trim())X.set(Y,b[Y].trim());if(b.includeMachineEngagement===!0)X.set("includeMachineEngagement","true");let J=X.toString();$=await D("GET",`/api/v1/metrics/transactional/${encodeURIComponent(W)}${J?`?${J}`:""}`,void 0,Q);break}case"get_sequence_stats":{let Q=b.companyId,W=new URLSearchParams;for(let J of["period","start","end"])if(typeof b[J]==="string"&&b[J].trim())W.set(J,b[J].trim());if(b.includeMachineEngagement===!0)W.set("includeMachineEngagement","true");let X=W.toString();$=await D("GET",`/api/v1/metrics/sequences/${b.sequenceId}${X?`?${X}`:""}`,void 0,Q);break}case"list_campaign_events":{let Q=b.companyId,W=M("list_campaign_events",b,"campaignId"),J=YQ("list_campaign_events",b).toString();$=await D("GET",`/api/v1/metrics/campaigns/${encodeURIComponent(W)}/events${J?`?${J}`:""}`,void 0,Q);break}case"list_sequence_events":{let Q=b.companyId,W=M("list_sequence_events",b,"sequenceId"),X=YQ("list_sequence_events",b),J=U(b,"automationNodeId");if(J)X.set("automationNodeId",J);let Y=X.toString();$=await D("GET",`/api/v1/metrics/sequences/${encodeURIComponent(W)}/events${Y?`?${Y}`:""}`,void 0,Q);break}case"list_email_metrics":{let Q=b.companyId,W=new URLSearchParams,X=l("list_email_metrics",b,"emailType",["campaign","sequence"]);if(X)W.set("emailType",X);let J=_9("list_email_metrics",b,"sequenceId"),Y=_9("list_email_metrics",b,"campaignId"),G=Q1("list_email_metrics",b,"step",1,1000);if(Y.length>0&&(J.length>0||G))throw Error("`campaignId` cannot be combined with `sequenceId` or `step` when calling `list_email_metrics`.");if(X==="campaign"&&(J.length>0||G!==void 0))throw Error("`emailType` campaign cannot be combined with `sequenceId` or `step` when calling `list_email_metrics`.");if(X==="sequence"&&Y.length>0)throw Error("`emailType` sequence cannot be combined with `campaignId` when calling `list_email_metrics`.");if(J.length>0)W.set("sequenceId",J.join(","));if(Y.length>0)W.set("campaignId",Y.join(","));if(G!==void 0)W.set("step",String(G));let H=l("list_email_metrics",b,"period",["1h","24h","7d","30d","90d"]);if(H)W.set("period",H);for(let j of["start","end"]){let q=U(b,j);if(q)W.set(j,q)}let z=l("list_email_metrics",b,"sort",["sent","delivered","opened","clicked","openRate","clickRate","unsubscribed","conversions","revenue","step","name"]);if(z)W.set("sort",z);let B=l("list_email_metrics",b,"order",["asc","desc"]);if(B)W.set("order",B);let L=Q1("list_email_metrics",b,"page",1,1e6);if(L!==void 0)W.set("page",String(L));let F=Q1("list_email_metrics",b,"limit",1,500);if(F!==void 0)W.set("limit",String(F));if(b.includeMachineEngagement===!0)W.set("includeMachineEngagement","true");let A=W.toString();$=await D("GET",`/api/v1/metrics/emails${A?`?${A}`:""}`,void 0,Q);break}case"get_subscriber_activity":{let Q=b.companyId,W=a1("get_subscriber_activity",b),X=await Rb(W,Q,{includeMachineEngagement:b.includeMachineEngagement===!0});$={success:X.success,email:X.subscriber.email,emailStats:X.subscriber.emailStats??null,activity:X.subscriber.activity??[],sequenceEnrollments:X.subscriber.sequenceEnrollments??[]};break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function M3(w,b){let $;switch(w){case"list_tags":{let Q=b.companyId;$=await D("GET","/api/v1/tags",void 0,Q);break}case"create_tag":{let Q=b.companyId,W=M("create_tag",b,"name"),X=l("create_tag",b,"color",Mw);$=await D("POST","/api/v1/tags",{name:W,...X!==void 0&&{color:X}},Q);break}case"update_tag":{let Q=b.companyId,W=M("update_tag",b,"tagId"),X=Sb("update_tag",b,"color",Mw);$=await D("PATCH",`/api/v1/tags/${encodeURIComponent(W)}`,{color:X},Q);break}case"delete_tag":{let Q=b.companyId,W=M("delete_tag",b,"tagId");$=await D("DELETE",`/api/v1/tags/${encodeURIComponent(W)}`,void 0,Q);break}case"list_lists":{let Q=b.companyId;$=await D("GET","/api/v1/lists",void 0,Q);break}case"create_list":{let Q=b.companyId;$=await D("POST","/api/v1/lists",b,Q);break}case"update_list":{let Q=b.companyId,W=M("update_list",b,"listId");if(b.name===void 0&&b.description===void 0&&b.isPrivate===void 0)throw Error("Provide at least one of `name`, `description`, or `isPrivate` when calling `update_list`.");if(b.name!==void 0&&U(b,"name")===void 0)throw Error("`name` cannot be empty when calling `update_list`.");if(b.description!==void 0&&b.description!==null&&typeof b.description!=="string")throw Error("`description` must be a string or null when calling `update_list`.");if(b.isPrivate!==void 0&&typeof b.isPrivate!=="boolean")throw Error("`isPrivate` must be a boolean when calling `update_list`.");$=await D("PATCH",`/api/v1/lists/${encodeURIComponent(W)}`,{...b.name!==void 0&&{name:U(b,"name")},...b.description!==void 0&&{description:b.description},...b.isPrivate!==void 0&&{isPrivate:b.isPrivate}},Q);break}case"delete_list":{let Q=b.companyId,W=M("delete_list",b,"listId");$=await D("DELETE",`/api/v1/lists/${encodeURIComponent(W)}`,void 0,Q);break}case"add_subscribers_to_list":{let Q=b.companyId,W=M("add_subscribers_to_list",b,"listId"),X=HQ("add_subscribers_to_list",b),J=l("add_subscribers_to_list",b,"duplicateStrategy",["skip","merge","overwrite"])??"skip",Y=l("add_subscribers_to_list",b,"optInMode",["default","confirmed","double_opt_in"])??"default";$=await D("POST",`/api/v1/lists/${encodeURIComponent(W)}/subscribers`,{emails:X,duplicateStrategy:J,enrollInSequences:b.enrollInSequences===!0,optInMode:Y},Q);break}case"remove_subscribers_from_list":{let Q=b.companyId,W=M("remove_subscribers_from_list",b,"listId"),X=HQ("remove_subscribers_from_list",b);$=await D("POST",`/api/v1/lists/${encodeURIComponent(W)}/subscribers/remove`,{emails:X},Q);break}case"list_segments":{let Q=b.companyId;$=await D("GET","/api/v1/segments",void 0,Q);break}case"create_segment":{J5(b);let Q=b.companyId;$=await D("POST","/api/v1/segments",{...b,...b.filters!==void 0?{filters:X4(b.filters)}:{},...b.root!==void 0?{root:J4(b.root)}:{}},Q);break}case"update_segment":{Y5(b);let Q=b.companyId,W=M("update_segment",b,"segmentId"),X=U(b,"name"),J=l("update_segment",b,"filterJoinOperator",["and","or"]);$=await D("PATCH",`/api/v1/segments/${encodeURIComponent(W)}`,{...X!==void 0&&{name:X},...J!==void 0&&{filterJoinOperator:J},...b.filters!==void 0?{filters:X4(b.filters)}:{},...b.root!==void 0?{root:J4(b.root)}:{}},Q);break}case"delete_segment":{let Q=b.companyId,W=M("delete_segment",b,"segmentId");$=await D("DELETE",`/api/v1/segments/${encodeURIComponent(W)}`,void 0,Q);break}case"get_segment_count":{let Q=b.companyId;$=await D("GET",`/api/v1/segments/${b.segmentId}/count`,void 0,Q);break}case"list_audience_syncs":{let Q=b.companyId;$=await D("GET","/api/v1/audience-syncs",void 0,Q);break}case"list_ad_accounts":{let Q=b.companyId;$=await D("GET","/api/v1/ad-accounts",void 0,Q);break}case"create_audience_sync":{let Q=b.companyId,W=U(b,"segmentId"),X=U(b,"predefinedSegmentId");if(W&&X)throw Error("Provide either `segmentId` or `predefinedSegmentId` when calling `create_audience_sync`, not both.");if(!W&&!X)throw Error("Provide either `segmentId` or `predefinedSegmentId` when calling `create_audience_sync`.");$=await D("POST","/api/v1/audience-syncs",{segmentId:W,predefinedSegmentId:X,adAccountId:M("create_audience_sync",b,"adAccountId"),audienceName:M("create_audience_sync",b,"audienceName"),...b.frequency!==void 0?{frequency:b.frequency}:{}},Q);break}case"update_audience_sync":{let Q=b.companyId,W=M("update_audience_sync",b,"syncId");$=await D("PATCH",`/api/v1/audience-syncs/${encodeURIComponent(W)}`,{...b.frequency!==void 0?{frequency:b.frequency}:{},...b.isActive!==void 0?{isActive:b.isActive}:{}},Q);break}case"delete_audience_sync":{let Q=b.companyId,W=M("delete_audience_sync",b,"syncId");$=await D("DELETE",`/api/v1/audience-syncs/${encodeURIComponent(W)}`,void 0,Q);break}case"sync_audience_now":{let Q=b.companyId,W=M("sync_audience_now",b,"syncId");$=await D("POST",`/api/v1/audience-syncs/${encodeURIComponent(W)}/sync`,void 0,Q);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function V3(w,b){let $;switch(w){case"list_templates":{let Q=b.companyId,W=new URLSearchParams,X=U(b,"label");if(X)W.set("label",X);let J=Q1("list_templates",b,"limit",1,100);if(J!==void 0)W.set("limit",String(J));let Y=Q1("list_templates",b,"offset",0,1e6);if(Y!==void 0)W.set("offset",String(Y));$=await D("GET",`/api/v1/templates${W.size>0?`?${W}`:""}`,void 0,Q);break}case"get_template":{let Q=b.companyId;$=await D("GET",`/api/v1/templates/${b.templateId}`,void 0,Q);break}case"create_template":{let Q=b.companyId;V5(b);let W=Object.fromEntries(Object.entries(b).filter(([X])=>X!=="companyId"));$=await D("POST","/api/v1/templates",W,Q);break}case"update_template":{let Q=b.companyId,W=new Set(["companyId","templateId","name","subject","previewText","html","blocks","labels"]),X=Object.keys(b).filter((J)=>!W.has(J));if(X.length>0)throw Error(`\`update_template\` accepts only \`name\`, \`subject\`, \`previewText\`, \`html\`, \`blocks\`, and \`labels\` update fields. Unsupported field${X.length===1?"":"s"}: ${X.map((J)=>`\`${J}\``).join(", ")}.`);if(h1("update_template",b),K0("update_template",b),b.name===void 0&&b.subject===void 0&&b.previewText===void 0&&b.html===void 0&&b.blocks===void 0&&b.labels===void 0)throw Error("Provide at least one of `name`, `subject`, `previewText`, `html`, `blocks`, or `labels` when calling `update_template`.");$=await D("PUT",`/api/v1/templates/${b.templateId}`,b,Q);break}case"set_template_localization":{let Q=b.companyId,W=M("set_template_localization",b,"templateId"),X=M("set_template_localization",b,"locale"),J=M("set_template_localization",b,"subject"),Y=new Set(["companyId","templateId","locale","subject","previewText","html","blocks"]),G=Object.keys(b).filter((z)=>!Y.has(z));if(G.length>0)throw Error(`\`set_template_localization\` received unsupported field${G.length===1?"":"s"}: ${G.map((z)=>`\`${z}\``).join(", ")}.`);h1("set_template_localization",b,{requireContent:!0});let H={subject:J};if(b.previewText!==void 0)H.previewText=b.previewText;if(b.html!==void 0)H.html=b.html;if(b.blocks!==void 0)H.blocks=b.blocks;$=await D("PUT",`/api/v1/templates/${encodeURIComponent(W)}/localizations/${encodeURIComponent(X)}`,H,Q);break}case"sync_template_localizations":{let Q=b.companyId,W=M("sync_template_localizations",b,"templateId"),X=new Set(["companyId","templateId","locales"]),J=Object.keys(b).filter((G)=>!X.has(G));if(J.length>0)throw Error(`\`sync_template_localizations\` received unsupported field${J.length===1?"":"s"}: ${J.map((G)=>`\`${G}\``).join(", ")}.`);let Y;if(b.locales!==void 0){if(!Array.isArray(b.locales)||b.locales.length===0||b.locales.some((G)=>typeof G!=="string"||G.trim().length===0))throw Error("`locales` must contain at least one non-empty locale string when calling `sync_template_localizations`.");Y=b.locales.map((G)=>G.trim())}$=await D("POST",`/api/v1/templates/${encodeURIComponent(W)}/localizations/sync`,Y===void 0?{}:{locales:Y},Q);break}case"delete_template":{let Q=b.companyId;$=await D("DELETE",`/api/v1/templates/${b.templateId}`,void 0,Q);break}case"list_ab_tests":{let Q=b.companyId,W=new URLSearchParams,X=U(b,"sequenceId");if(X)W.set("sequenceId",X);$=await D("GET",`/api/v1/ab-tests${W.size>0?`?${W}`:""}`,void 0,Q);break}case"get_ab_test":{let Q=b.companyId;$=await D("GET",`/api/v1/ab-tests/${b.abTestId}`,void 0,Q);break}case"get_ab_test_stats":{let Q=b.companyId,W=new URLSearchParams,X=U(b,"period"),J=U(b,"start"),Y=U(b,"end");if(X)W.set("period",X);if(J)W.set("start",J);if(Y)W.set("end",Y);if(b.includeMachineEngagement===!0)W.set("includeMachineEngagement","true");$=await D("GET",`/api/v1/ab-tests/${b.abTestId}/stats${W.size>0?`?${W}`:""}`,void 0,Q);break}case"restart_ab_test":{let Q=b.companyId,W=new Set(["companyId","abTestId","sourceVariantId","testType","winnerThreshold","variantCount"]),X=Object.keys(b).filter((H)=>!W.has(H));if(X.length>0)throw Error(`\`restart_ab_test\` accepts only \`sourceVariantId\`, \`testType\`, \`winnerThreshold\`, and \`variantCount\` option fields. Unsupported field${X.length===1?"":"s"}: ${X.map((H)=>`\`${H}\``).join(", ")}.`);let J=U(b,"testType");if(J!==void 0&&J!=="subject"&&J!=="content")throw Error("`restart_ab_test` testType must be `subject` or `content`.");let Y=b.winnerThreshold===void 0?void 0:Number(b.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 G=b.variantCount===void 0?void 0:Number(b.variantCount);if(G!==void 0&&(!Number.isInteger(G)||G<2||G>4))throw Error("`restart_ab_test` variantCount must be an integer from 2 to 4.");$=await D("POST",`/api/v1/ab-tests/${b.abTestId}/restart`,{sourceVariantId:U(b,"sourceVariantId"),testType:J,winnerThreshold:Y,variantCount:G},Q);break}case"update_ab_test_variant":{let Q=b.companyId,W=new Set(["companyId","abTestId","variantId","subject","previewText","html","blocks","confirmLiveChange"]),X=Object.keys(b).filter((J)=>!W.has(J));if(X.length>0)throw Error(`\`update_ab_test_variant\` accepts only \`subject\`, \`previewText\`, \`html\`, \`blocks\`, and \`confirmLiveChange\` fields. Unsupported field${X.length===1?"":"s"}: ${X.map((J)=>`\`${J}\``).join(", ")}.`);if(h1("update_ab_test_variant",b),b.confirmLiveChange!==void 0&&typeof b.confirmLiveChange!=="boolean")throw Error("`confirmLiveChange` must be a boolean when calling `update_ab_test_variant`.");if(b.subject===void 0&&b.previewText===void 0&&b.html===void 0&&b.blocks===void 0)throw Error("Provide at least one of `subject`, `previewText`, `html`, or `blocks` when calling `update_ab_test_variant`.");$=await D("PATCH",`/api/v1/ab-tests/${b.abTestId}/variants/${b.variantId}`,b,Q);break}case"update_ab_test":{let Q=b.companyId,W=M("update_ab_test",b,"abTestId"),X=new Set(["companyId","abTestId","name","testPercentage","testDurationMinutes","winnerCriteria","testType","winnerThreshold","confirmLiveChange"]),J=Object.keys(b).filter((F)=>!X.has(F));if(J.length>0)throw Error(`\`update_ab_test\` received unsupported field${J.length===1?"":"s"}: ${J.map((F)=>`\`${F}\``).join(", ")}.`);if(b.confirmLiveChange!==void 0&&typeof b.confirmLiveChange!=="boolean")throw Error("`confirmLiveChange` must be a boolean when calling `update_ab_test`.");let Y=U(b,"name"),G=Q1("update_ab_test",b,"testPercentage",5,50),H=Q1("update_ab_test",b,"testDurationMinutes",15,1440),z=l("update_ab_test",b,"winnerCriteria",["open_rate","click_rate"]),B=l("update_ab_test",b,"testType",["subject","content"]),L=Q1("update_ab_test",b,"winnerThreshold",10,1000);if(Y===void 0&&G===void 0&&H===void 0&&z===void 0&&B===void 0&&L===void 0)throw Error("Provide at least one of `name`, `testPercentage`, `testDurationMinutes`, `winnerCriteria`, `testType`, or `winnerThreshold` when calling `update_ab_test`.");$=await D("PATCH",`/api/v1/ab-tests/${encodeURIComponent(W)}`,{...Y!==void 0&&{name:Y},...G!==void 0&&{testPercentage:G},...H!==void 0&&{testDurationMinutes:H},...z!==void 0&&{winnerCriteria:z},...B!==void 0&&{testType:B},...L!==void 0&&{winnerThreshold:L},...b.confirmLiveChange===!0&&{confirmLiveChange:!0}},Q);break}case"create_ab_test":{let Q=b.companyId,W=U(b,"campaignId"),X=U(b,"automationNodeId");if(b.confirmLiveChange!==void 0&&typeof b.confirmLiveChange!=="boolean")throw Error("`confirmLiveChange` must be a boolean when calling `create_ab_test`.");if(Boolean(W)===Boolean(X))throw Error("Provide exactly one of `campaignId` or `automationNodeId` when calling `create_ab_test`.");let J=U(b,"name"),Y=Q1("create_ab_test",b,"testPercentage",5,50),G=Q1("create_ab_test",b,"testDurationMinutes",15,1440),H=l("create_ab_test",b,"winnerCriteria",["open_rate","click_rate"]),z=l("create_ab_test",b,"testType",["subject","content"]),B=Q1("create_ab_test",b,"winnerThreshold",10,1000);if(b.variants!==void 0){if(!Array.isArray(b.variants))throw Error("`variants` must be an array when calling `create_ab_test`.");b.variants.forEach((F,A)=>{if(!k(F)||typeof F.subject!=="string"||F.subject.trim()==="")throw Error(`\`variants\` item ${A+1} must include a non-empty \`subject\` when calling \`create_ab_test\`.`);if(F.blocks!==void 0&&!Array.isArray(F.blocks))throw Error(`\`variants\` item ${A+1} \`blocks\` must be an array when calling \`create_ab_test\`.`)})}let L=Array.isArray(b.variants)?b.variants:void 0;if(X!==void 0&&(!L||L.length<1))throw Error("`variants` must include at least one competing variant when calling `create_ab_test` with `automationNodeId`.");if(L&&L.length>4)throw Error("`variants` supports at most four extra variants when calling `create_ab_test`.");$=await D("POST","/api/v1/ab-tests",{...W!==void 0&&{campaignId:W},...X!==void 0&&{automationNodeId:X},...b.confirmLiveChange===!0&&{confirmLiveChange:!0},...J!==void 0&&{name:J},...Y!==void 0&&{testPercentage:Y},...G!==void 0&&{testDurationMinutes:G},...H!==void 0&&{winnerCriteria:H},...z!==void 0&&{testType:z},...B!==void 0&&{winnerThreshold:B},...b.variants!==void 0&&{variants:b.variants}},Q);break}case"add_ab_test_variant":{let Q=b.companyId,W=M("add_ab_test_variant",b,"abTestId"),X=M("add_ab_test_variant",b,"subject"),J=U(b,"previewText");if(b.blocks!==void 0&&!Array.isArray(b.blocks))throw Error("`blocks` must be an array when calling `add_ab_test_variant`.");if(b.confirmLiveChange!==void 0&&typeof b.confirmLiveChange!=="boolean")throw Error("`confirmLiveChange` must be a boolean when calling `add_ab_test_variant`.");$=await D("POST",`/api/v1/ab-tests/${encodeURIComponent(W)}/variants`,{subject:X,...J!==void 0&&{previewText:J},...b.blocks!==void 0&&{blocks:b.blocks},...b.confirmLiveChange===!0&&{confirmLiveChange:!0}},Q);break}case"delete_ab_test_variant":{let Q=b.companyId,W=M("delete_ab_test_variant",b,"abTestId"),X=M("delete_ab_test_variant",b,"variantId");if(b.confirmLiveChange!==void 0&&typeof b.confirmLiveChange!=="boolean")throw Error("`confirmLiveChange` must be a boolean when calling `delete_ab_test_variant`.");$=await D("DELETE",`/api/v1/ab-tests/${encodeURIComponent(W)}/variants/${encodeURIComponent(X)}${b.confirmLiveChange===!0?"?confirmLiveChange=true":""}`,void 0,Q);break}case"delete_ab_test":{let Q=b.companyId,W=M("delete_ab_test",b,"abTestId");$=await D("DELETE",`/api/v1/ab-tests/${encodeURIComponent(W)}`,void 0,Q);break}case"list_campaigns":{let Q=b.companyId,W=new URLSearchParams;if(b.status)W.set("status",String(b.status));let X=U(b,"label");if(X)W.set("label",X);for(let J of["limit","offset"])if(b[J]!==void 0)W.set(J,String(b[J]));$=await D("GET",`/api/v1/campaigns?${W}`,void 0,Q);break}case"get_campaign":{let Q=b.companyId;$=await D("GET",`/api/v1/campaigns/${b.campaignId}`,void 0,Q);break}case"get_campaign_audience":{let Q=b.companyId;$=await D("GET",`/api/v1/campaigns/${encodeURIComponent(String(b.campaignId))}/audience`,void 0,Q);break}case"get_email_send":{let Q=b.companyId;$=await D("GET",`/api/v1/email-sends/${encodeURIComponent(String(b.emailSendId))}`,void 0,Q);break}case"list_email_sends":{let Q=b.companyId,W=new URLSearchParams,X=["search","subject","recipient","campaignId","transactionalEmailId","automationId","automationNodeId"];for(let q of X){let P=U(b,q);if(P)W.set(q,P)}let J=l("list_email_sends",b,"status",["pending","sent","delivered","opened","clicked","bounced","complained","failed","suppressed"]),Y=l("list_email_sends",b,"emailType",["campaign","transactional","sequence"]),G=l("list_email_sends",b,"bounceType",["Permanent","Transient"]),H=l("list_email_sends",b,"sortField",["recipientEmail","subject","status","eventAt","sentAt","createdAt"]),z=l("list_email_sends",b,"sortOrder",["asc","desc"]),B=Q1("list_email_sends",b,"days",1,14),L=Q1("list_email_sends",b,"page",1,Number.MAX_SAFE_INTEGER),F=Q1("list_email_sends",b,"limit",1,100),A=[["status",J],["emailType",Y],["bounceType",G],["sortField",H],["sortOrder",z],["days",B],["page",L],["limit",F]];for(let[q,P]of A)if(P!==void 0)W.set(q,String(P));let j=W.toString();$=await D("GET",`/api/v1/email-sends${j?`?${j}`:""}`,void 0,Q);break}case"create_campaign":{let Q=b.companyId;M5(b),Pw("create_campaign",b);let W=Object.fromEntries(Object.entries(b).filter(([X])=>X!=="companyId"));$=await D("POST","/api/v1/campaigns",W,Q);break}case"update_campaign":{let Q=b.companyId,W=new Set(["companyId","campaignId","name","subject","trackingCode","html","blocks","fromEmail","fromName","senderProfileId","replyTo","replyToName","replyProfileId","ccEmails","bccEmails","campaignData","computedLists","targetLists","segmentId","labels"]),X=Object.keys(b).filter((J)=>!W.has(J));if(X.length>0)throw Error(`\`update_campaign\` accepts only content, sending identity, campaign data, computed list, audience, and label update fields. Unsupported field${X.length===1?"":"s"}: ${X.map((J)=>`\`${J}\``).join(", ")}.`);if(h1("update_campaign",b),K0("update_campaign",b),Pw("update_campaign",b,{replyFirst:!0}),b.segmentId!==void 0&&b.targetLists!==void 0)throw Error("Provide either `segmentId` or `targetLists` when calling `update_campaign`, not both.");if(b.name===void 0&&b.subject===void 0&&b.trackingCode===void 0&&b.html===void 0&&b.blocks===void 0&&b.fromEmail===void 0&&b.senderProfileId===void 0&&b.replyTo===void 0&&b.replyProfileId===void 0&&b.ccEmails===void 0&&b.bccEmails===void 0&&b.campaignData===void 0&&b.computedLists===void 0&&b.targetLists===void 0&&b.segmentId===void 0&&b.labels===void 0)throw Error("Provide at least one campaign content, sending identity, campaign data, computed list, audience, or label field when calling `update_campaign`.");$=await D("PUT",`/api/v1/campaigns/${b.campaignId}`,b,Q);break}case"schedule_campaign":{let Q=b.companyId,W=new Set(["companyId","campaignId","scheduledAt","targetLists","sendTimeOptimization","spreadOverHours","recurringInterval"]),X=Object.keys(b).filter((J)=>!W.has(J));if(X.length>0)throw Error(`\`schedule_campaign\` accepts only \`campaignId\`, \`scheduledAt\`, \`targetLists\`, \`sendTimeOptimization\`, \`spreadOverHours\`, and \`recurringInterval\`. Unsupported field${X.length===1?"":"s"}: ${X.map((J)=>`\`${J}\``).join(", ")}.`);P5(b),$=await D("POST",`/api/v1/campaigns/${b.campaignId}/schedule`,{scheduledAt:b.scheduledAt,...b.targetLists!==void 0&&{targetLists:b.targetLists},...b.sendTimeOptimization!==void 0&&{sendTimeOptimization:b.sendTimeOptimization},...b.spreadOverHours!==void 0&&{spreadOverHours:b.spreadOverHours},...b.recurringInterval!==void 0&&{recurringInterval:b.recurringInterval}},Q);break}case"send_test_email":{let Q=b.companyId;$=await D("POST",`/api/v1/campaigns/${b.campaignId}/test`,{to:b.to},Q);break}case"cancel_campaign":{let Q=b.companyId,W=M("cancel_campaign",b,"campaignId");$=await D("POST",`/api/v1/campaigns/${encodeURIComponent(W)}/cancel`,void 0,Q);break}case"unschedule_campaign":{let Q=b.companyId,W=M("unschedule_campaign",b,"campaignId");$=await D("POST",`/api/v1/campaigns/${encodeURIComponent(W)}/unschedule`,void 0,Q);break}case"pause_campaign":{let Q=b.companyId,W=M("pause_campaign",b,"campaignId");$=await D("POST",`/api/v1/campaigns/${encodeURIComponent(W)}/pause`,void 0,Q);break}case"resume_campaign":{let Q=b.companyId,W=M("resume_campaign",b,"campaignId"),X=Q1("resume_campaign",b,"spreadOverHours",1,72);$=await D("POST",`/api/v1/campaigns/${encodeURIComponent(W)}/resume`,{...X!==void 0&&{spreadOverHours:X}},Q);break}case"delete_campaign":{let Q=b.companyId,W=M("delete_campaign",b,"campaignId");$=await D("DELETE",`/api/v1/campaigns/${encodeURIComponent(W)}`,void 0,Q);break}case"duplicate_campaign":{let Q=b.companyId,W=M("duplicate_campaign",b,"campaignId"),X=l("duplicate_campaign",b,"mode",["campaign","ab_test","variant"]),J=U(b,"variantId");if(X==="variant"&&J===void 0)throw Error("`variantId` is required when calling `duplicate_campaign` with mode `variant`.");$=await D("POST",`/api/v1/campaigns/${encodeURIComponent(W)}/duplicate`,{...X!==void 0&&{mode:X},...J!==void 0&&{variantId:J}},Q);break}case"resend_campaign_to_non_openers":{let Q=b.companyId,W=M("resend_campaign_to_non_openers",b,"campaignId");$=await D("POST",`/api/v1/campaigns/${encodeURIComponent(W)}/resend-to-non-openers`,void 0,Q);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function P3(w,b){let $;switch(w){case"list_forms":{let Q=b.companyId;$=await D("GET","/api/v1/forms",void 0,Q);break}case"create_form":{let Q=b.companyId,W=M("create_form",b,"name"),X=Array.isArray(b.listIds)?b.listIds.filter((G)=>typeof G==="string").map((G)=>G.trim()).filter(Boolean):[];if(X.length===0)throw Error("`listIds` must contain at least one list ID when calling `create_form`.");let J=l("create_form",b,"duplicateStrategy",["skip","merge","overwrite"]),Y={name:W,listIds:X};for(let G of["tagIds","buttonText","headline","description","successMessage","redirectUrl","showFirstName","showLastName","theme"])if(b[G]!==void 0)Y[G]=b[G];if(J!==void 0)Y.duplicateStrategy=J;$=await D("POST","/api/v1/forms",Y,Q);break}case"update_form":{let Q=b.companyId,W=M("update_form",b,"formId"),X=l("update_form",b,"duplicateStrategy",["skip","merge","overwrite"]),J={};for(let Y of["name","listIds","tagIds","buttonText","headline","description","successMessage","redirectUrl","theme","blocks"])if(b[Y]!==void 0)J[Y]=b[Y];if(X!==void 0)J.duplicateStrategy=X;if(Object.keys(J).length===0)throw Error("Provide at least one field to change when calling `update_form`.");$=await D("PATCH",`/api/v1/forms/${encodeURIComponent(W)}`,J,Q);break}case"get_form_embed":{let Q=b.companyId,W=M("get_form_embed",b,"formId");$=await D("GET",`/api/v1/forms/embed/${encodeURIComponent(W)}`,void 0,Q);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}function A4(w,b,$,Q,W){let X=w[b];if(X===void 0)return;if(typeof X!=="number"||!Number.isFinite(X)||X<$||X>Q||W&&!Number.isInteger(X))throw Error(`\`${b}\` must be a ${W?"integer":"number"} between ${$} and ${Q} when calling \`upload_image_asset\`.`);return X}async function q3(w,b){if(w!=="upload_image_asset")return{handled:!1,result:void 0};let $=U(b,"filePath"),Q=U(b,"imageBase64");if($===void 0===(Q===void 0))throw Error("Provide either `filePath` or `imageBase64` (not both) when calling `upload_image_asset`.");let W=U(b,"filename");if(Q!==void 0&&W===void 0)throw Error("`filename` is required with `imageBase64` when calling `upload_image_asset`.");let X=A4(b,"sourceWidth",1,20000,!0),J=A4(b,"sourceHeight",1,20000,!0);if(X===void 0!==(J===void 0))throw Error("Provide both `sourceWidth` and `sourceHeight` when calling `upload_image_asset`.");let Y=A4(b,"displayWidthPercent",1,100,!1)??100,G=A4(b,"cropHeight",1,2000,!0),H=U(b,"objectFit");if(H!==void 0&&H!=="cover"&&H!=="contain")throw Error("`objectFit` must be 'cover' or 'contain' when calling `upload_image_asset`.");if(H!==void 0&&G===void 0)throw Error("`objectFit` can only be used with `cropHeight` when calling `upload_image_asset`.");let z=U(b,"align");if(z!==void 0&&!["left","center","right"].includes(z))throw Error("`align` must be 'left', 'center', or 'right' when calling `upload_image_asset`.");let B=typeof b.altText==="string"?b.altText.trim():void 0;if(B!==void 0&&B.length>500)throw Error("`altText` must be 500 characters or fewer when calling `upload_image_asset`.");let L=await u5({companyId:U(b,"companyId"),filePath:$,imageBase64:Q,filename:W,contentType:U(b,"contentType"),altText:B,sourceWidth:X,sourceHeight:J}),F={type:"image",src:L.url,alt:L.altText??"",width:Y,widthType:"percent",...G!==void 0&&{height:G,objectFit:H??"cover"},...z!==void 0&&{align:z}};return{handled:!0,result:{success:!0,asset:L,imageBlock:F,message:"Insert imageBlock into the target email's blocks array with its create or update tool."}}}async function I3(w,b){let $=b.companyId,Q;switch(w){case"connect_integration":{let W=M("connect_integration",b,"provider"),X=M("connect_integration",b,"webhookSecret");Q=await D("POST","/api/v1/integrations/connect",{provider:W,webhookSecret:X,...typeof b.apiKey==="string"&&b.apiKey?{apiKey:b.apiKey}:{},...typeof b.providerAccountId==="string"&&b.providerAccountId?{providerAccountId:b.providerAccountId}:{},...b.settings!==void 0?{settings:b.settings}:{},...b.historyImport!==void 0?{historyImport:b.historyImport}:{}},$);break}case"get_integration":{let W=M("get_integration",b,"integrationId");Q=await D("GET",`/api/v1/integrations/${encodeURIComponent(W)}`,void 0,$);break}case"list_integration_capabilities":{let W=new URLSearchParams;if(typeof b.provider==="string"&&b.provider)W.set("provider",b.provider);if(typeof b.category==="string"&&b.category)W.set("category",b.category);let X=W.toString();Q=await D("GET",`/api/v1/integrations/catalog${X?`?${X}`:""}`,void 0,$);break}case"list_integration_activity":{let W=new URLSearchParams;if(typeof b.integrationId==="string"&&b.integrationId)W.set("integrationId",b.integrationId);if(typeof b.provider==="string"&&b.provider)W.set("provider",b.provider);if(typeof b.status==="string"&&b.status)W.set("status",b.status);if(typeof b.limit==="number")W.set("limit",String(b.limit));let X=W.toString();Q=await D("GET",`/api/v1/integrations/activity${X?`?${X}`:""}`,void 0,$);break}case"set_integration_sync_enabled":{let W=M("set_integration_sync_enabled",b,"integrationId");if(typeof b.syncEnabled!=="boolean")throw Error("`syncEnabled` must be a boolean when calling `set_integration_sync_enabled`.");Q=await D("PATCH",`/api/v1/integrations/${encodeURIComponent(W)}`,{syncEnabled:b.syncEnabled},$);break}case"get_integration_pixel":{let W=M("get_integration_pixel",b,"integrationId");Q=await D("GET",`/api/v1/integrations/${encodeURIComponent(W)}/pixel`,void 0,$);break}case"activate_integration_pixel":{let W=M("activate_integration_pixel",b,"integrationId");Q=await D("POST",`/api/v1/integrations/${encodeURIComponent(W)}/pixel`,void 0,$);break}case"sync_integration":{let W=M("sync_integration",b,"integrationId");Q=await D("POST",`/api/v1/integrations/${encodeURIComponent(W)}/sync`,void 0,$);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:Q}}async function E3(w,b){let $;switch(w){case"list_landing_pages":{let Q=b.companyId;$=await D("GET","/api/v1/landing-pages",void 0,Q);break}case"get_landing_page":{let Q=b.companyId;$=await D("GET",`/api/v1/landing-pages/${b.landingPageId}`,void 0,Q);break}case"create_landing_page":{let Q=b.companyId,W=new Set(["companyId","name","slug","template","content"]),X=Object.keys(b).filter((J)=>!W.has(J));if(X.length>0)throw Error(`\`create_landing_page\` accepts only \`name\`, \`slug\`, \`template\`, and \`content\` fields. Unsupported field${X.length===1?"":"s"}: ${X.map((J)=>`\`${J}\``).join(", ")}.`);$=await D("POST","/api/v1/landing-pages",{...b.name!==void 0&&{name:b.name},...b.slug!==void 0&&{slug:b.slug},...b.template!==void 0&&{template:b.template},...b.content!==void 0&&{content:b.content}},Q);break}case"update_landing_page":{let Q=b.companyId,W=z4("update_landing_page",b,{requireUpdate:!0});$=await D("PUT",`/api/v1/landing-pages/${b.landingPageId}`,W,Q);break}case"publish_landing_page":{let Q=b.companyId,W=z4("publish_landing_page",b,{requireUpdate:!1});$=await D("POST",`/api/v1/landing-pages/${b.landingPageId}/publish`,W,Q);break}case"unpublish_landing_page":{let Q=b.companyId,W=z4("unpublish_landing_page",b,{requireUpdate:!1});$=await D("POST",`/api/v1/landing-pages/${b.landingPageId}/unpublish`,W,Q);break}case"duplicate_landing_page":{let Q=b.companyId;$=await D("POST",`/api/v1/landing-pages/${b.landingPageId}/duplicate`,{...b.name!==void 0&&{name:b.name},...b.slug!==void 0&&{slug:b.slug}},Q);break}case"delete_landing_page":{let Q=b.companyId;$=await D("DELETE",`/api/v1/landing-pages/${b.landingPageId}`,void 0,Q);break}case"connect_landing_page_domain":{let Q=b.companyId;$=await D("POST","/api/v1/landing-pages/domain",{domain:b.domain},Q);break}case"update_landing_page_domain_settings":{let Q=b.companyId,W=q5(b);$=await D("PUT","/api/v1/landing-pages/domain",W,Q);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function N3(w,b){let $;switch(w){case"list_products":{let Q=b.companyId,W=new URLSearchParams;if(typeof b.provider==="string"&&b.provider.trim())W.set("provider",b.provider.trim());if(typeof b.search==="string"&&b.search.trim())W.set("search",b.search.trim());let X=Q1("list_products",b,"limit",1,100);if(X!==void 0)W.set("limit",String(X));let J=Q1("list_products",b,"offset",0,Number.MAX_SAFE_INTEGER);if(J!==void 0)W.set("offset",String(J));let Y=W.size>0?`?${W.toString()}`:"";$=await D("GET",`/api/v1/products${Y}`,void 0,Q);break}case"upsert_products":{let Q=b.companyId;if(!Array.isArray(b.products)||b.products.length===0)throw Error("`products` must be a non-empty array when calling `upsert_products`.");$=await D("POST","/api/v1/products",{products:b.products},Q);break}case"delete_product":{let Q=b.companyId,W=M("delete_product",b,"productId");$=await D("DELETE",`/api/v1/products/${encodeURIComponent(W)}`,void 0,Q);break}case"attach_product_file":{let Q=b.companyId,W=M("attach_product_file",b,"productId"),X=U(b,"url"),J=U(b,"filePath");if(X===void 0===(J===void 0))throw Error("Provide either `url` or `filePath` (not both) when calling `attach_product_file`.");let Y;if(J!==void 0){let G=await k5(J,Q);Y={url:G.url,source:"upload",fileName:U(b,"fileName")??G.fileName,fileSizeBytes:G.fileSizeBytes,mimeType:G.mimeType}}else{Y={url:X};let G=U(b,"fileName");if(G)Y.fileName=G}$=await D("PUT",`/api/v1/products/${encodeURIComponent(W)}/delivery`,Y,Q);break}case"remove_product_file":{let Q=b.companyId,W=M("remove_product_file",b,"productId");$=await D("DELETE",`/api/v1/products/${encodeURIComponent(W)}/delivery`,void 0,Q);break}case"sync_products":{let Q=b.companyId,W=new URLSearchParams;if(typeof b.integrationId==="string"&&b.integrationId)W.set("integrationId",b.integrationId);let X=W.toString();$=await D("POST",`/api/v1/products/sync${X?`?${X}`:""}`,void 0,Q);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}function xV(w){let b=U(w,"campaignId"),$=U(w,"sequenceId"),Q=U(w,"templateId"),W=[b,$,Q].filter((X)=>X!==void 0);if(W.length===0)throw Error("render_email requires one of campaignId, sequenceId plus nodeId, or templateId.");if(W.length>1)throw Error("render_email accepts exactly one of campaignId, sequenceId, or templateId.");if(b!==void 0)return`/api/v1/campaigns/${encodeURIComponent(b)}/render`;if($!==void 0){let X=M("render_email",w,"nodeId");return`/api/v1/sequences/${encodeURIComponent($)}/nodes/${encodeURIComponent(X)}/render`}return`/api/v1/templates/${encodeURIComponent(Q)}/render`}var hV=["subscriberId","subscriber","variables","locale","variantId","tracking"];async function T3(w,b){if(w!=="render_email")return{handled:!1,result:void 0};let $=xV(b),Q={};for(let X of hV)if(b[X]!==void 0)Q[X]=b[X];return{handled:!0,result:await D("POST",$,Q,U(b,"companyId"))}}var R3=80,S3=10;function yV(w){if(!Array.isArray(w.recipients))throw Error("`recipients` must be an array when calling `send_sequence_test_email`.");if(w.recipients.length>S3)throw Error(`\`recipients\` must include no more than ${S3} email addresses when calling \`send_sequence_test_email\`.`);if(w.recipients.find((W)=>typeof W!=="string"||W.trim().length===0)!==void 0)throw Error("Every `recipients` item must be a non-empty email address when calling `send_sequence_test_email`.");let $=Array.from(new Set(w.recipients.map((W)=>typeof W==="string"?W.trim().toLowerCase():""))).filter(Boolean);if($.length===0)throw Error("`recipients` must include at least one email address when calling `send_sequence_test_email`.");let Q=$.find((W)=>!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(W));if(Q)throw Error(`Invalid test recipient email address: \`${Q}\`.`);return $}function fV(w){let b=w.trim().replace(/\s+/g," ");if(b.length<=R3)return b;return`${b.slice(0,R3-3).trimEnd()}...`}async function FQ(w,b){let $;switch(w){case"generate_sequence":{let Q=M("generate_sequence",b,"goal"),W=typeof b.name==="string"&&b.name.trim().length>0?b.name.trim():void 0,J=(await FQ("create_sequence",{...b,goal:Q,name:W??fV(Q),trigger:"contact_added",durationDays:b.durationDays??14})).result;return{handled:!0,result:typeof J==="object"&&J!==null?{...J,deprecated:!0,deprecationMessage:"generate_sequence is deprecated. Use create_sequence for new integrations."}:J}}case"list_sequences":{let Q=b.companyId,W=new URLSearchParams;for(let J of["status","search","limit","offset"])if(b[J]!==void 0)W.set(J,String(b[J]));if(Array.isArray(b.labels)&&b.labels.length>0)W.set("labels",b.labels.join(","));let X=W.size>0?`?${W.toString()}`:"";$=await D("GET",`/api/v1/sequences${X}`,void 0,Q);break}case"get_sequence":{let Q=b.companyId;$=await D("GET",`/api/v1/sequences/${b.sequenceId}`,void 0,Q);break}case"list_sequence_enrollments":{let Q=b.companyId,W=M(w,b,"sequenceId"),X=new URLSearchParams;for(let Y of["currentNodeId","status","subscriberId"]){let G=b[Y];if(Array.isArray(G)){if(G.length>0)X.set(Y,G.join(","))}else if(G!==void 0)X.set(Y,String(G))}for(let Y of["email","sort","limit","offset"])if(b[Y]!==void 0)X.set(Y,String(b[Y]));let J=X.size>0?`?${X.toString()}`:"";$=await D("GET",`/api/v1/sequences/${encodeURIComponent(W)}/enrollments${J}`,void 0,Q);break}case"send_sequence_test_email":{let Q=b.companyId,W=M(w,b,"sequenceId"),X=M(w,b,"nodeId"),J=yV(b);$=await D("POST",`/api/v1/sequences/${encodeURIComponent(W)}/nodes/${encodeURIComponent(X)}/test`,{recipients:J},Q);break}case"create_sequence":{let Q=b.companyId;K0("create_sequence",b),Pw("create_sequence",b);let W=Array.isArray(b.steps),X=b.goal===void 0&&b.steps===void 0,J=await D("POST","/api/v1/sequences",b,Q);if(!J.success){$=J;break}let Y=J.sequence.id;if(W||X){let L=await D("GET",`/api/v1/sequences/${Y}`,void 0,Q);if(L.success)$={...J,success:!0,sequence:L.sequence,message:`Sequence "${L.sequence.name}" created ${X?"as a blank draft":"with explicit steps"}. Review it before enabling.${J.eventTrackingCode?" Add the custom event feed using eventTrackingCode and eventTracking before enabling.":""}`};else $=L;break}let G=7,H=0,z="pending";while(z!=="complete"&&H<G){let L=await D("GET",`/api/v1/sequences/${Y}`,void 0,Q);if(L.success)z=L.sequence.enrichmentStatus;if(H++,z!=="complete"&&H<G)await new Promise((F)=>setTimeout(F,20000))}let B=await D("GET",`/api/v1/sequences/${Y}`,void 0,Q);if(B.success)$={...J,success:!0,sequence:B.sequence,message:B.sequence.enrichmentStatus==="complete"?`Sequence "${B.sequence.name}" created with ${B.sequence.emailCount} AI-generated emails. The sequence is ready to review and enable.${J.eventTrackingCode?" Add the custom event feed using eventTrackingCode and eventTracking before enabling.":""}`:`Sequence "${B.sequence.name}" created. Email enrichment is still in progress (${B.sequence.enrichedCount}/${B.sequence.emailCount} emails generated). You can check status with get_sequence.${J.eventTrackingCode?" Add the custom event feed using eventTrackingCode and eventTracking before enabling.":""}`};else $=B;break}case"update_sequence":{let Q=b.companyId,W=D5(b);$=await D("PUT",`/api/v1/sequences/${b.sequenceId}`,W,Q);break}case"update_sequence_node":{let Q=b.companyId,W=M("update_sequence_node",b,"sequenceId"),X=A5(b);$=await D("PUT",`/api/v1/sequences/${W}`,X,Q);break}case"update_sequence_nodes":{let Q=b.companyId,W=M("update_sequence_nodes",b,"sequenceId"),X=K5(b);$=await D("PUT",`/api/v1/sequences/${W}`,X,Q);break}case"edit_sequence_graph":{let Q=b.companyId,W=O5(b);$=await D("PUT",`/api/v1/sequences/${b.sequenceId}`,W,Q);break}case"insert_sequence_step":{let Q=b.companyId,W=Z5(b),X=await D("PUT",`/api/v1/sequences/${b.sequenceId}`,W,Q);if(typeof X==="object"&&X!==null){let J=X,Y=J.sequence;if(typeof Y==="object"&&Y!==null){let G=Y;$={...J,...G.insertedNodeIds!==void 0?{insertedNodeIds:G.insertedNodeIds}:{},...G.insertedEmailIds!==void 0?{insertedEmailIds:G.insertedEmailIds}:{},...G.insertedEmailCount!==void 0?{insertedEmailCount:G.insertedEmailCount}:{},...G.addedBranchNodeId!==void 0?{addedBranchNodeId:G.addedBranchNodeId}:{},...G.addedBranchPathNodeIds!==void 0?{addedBranchPathNodeIds:G.addedBranchPathNodeIds}:{}};break}}$=X;break}case"enable_sequence":{let Q=b.companyId;$=await D("POST",`/api/v1/sequences/${b.sequenceId}/enable`,void 0,Q);break}case"disable_sequence":{let Q=b.companyId;$=await D("POST",`/api/v1/sequences/${b.sequenceId}/disable`,void 0,Q);break}case"duplicate_sequence":{let Q=b.companyId,W=M("duplicate_sequence",b,"sequenceId"),X=U(b,"name");$=await D("POST",`/api/v1/sequences/${encodeURIComponent(W)}/duplicate`,X===void 0?void 0:{name:X},Q);break}case"archive_sequence":case"unarchive_sequence":{let Q=b.companyId,W=M(w,b,"sequenceId"),X=w==="archive_sequence"?"archive":"unarchive";$=await D("POST",`/api/v1/sequences/${encodeURIComponent(W)}/${X}`,void 0,Q);break}case"list_sequence_goals":{let Q=b.companyId,W=M(w,b,"sequenceId");$=await D("GET",`/api/v1/sequences/${encodeURIComponent(W)}/goals`,void 0,Q);break}case"create_sequence_goal":case"update_sequence_goal":{let Q=b.companyId,W=M(w,b,"sequenceId");if(w==="create_sequence_goal")M(w,b,"name"),B5(b);else L5(b);let X=w==="update_sequence_goal"?M(w,b,"goalId"):void 0,J={...b};delete J.companyId,delete J.sequenceId,delete J.goalId,$=await D(w==="create_sequence_goal"?"POST":"PATCH",`/api/v1/sequences/${encodeURIComponent(W)}/goals${X?`/${encodeURIComponent(X)}`:""}`,J,Q);break}case"delete_sequence_goal":{let Q=b.companyId,W=M(w,b,"sequenceId"),X=M(w,b,"goalId");$=await D("DELETE",`/api/v1/sequences/${encodeURIComponent(W)}/goals/${encodeURIComponent(X)}`,void 0,Q);break}case"get_sequence_inbound_webhook":case"configure_sequence_inbound_webhook":case"rotate_sequence_inbound_webhook_secret":{let Q=b.companyId,W=M(w,b,"sequenceId");if(b.clearFieldMapping===!0&&b.fieldMapping!==void 0)throw Error("Provide either `fieldMapping` or `clearFieldMapping`, not both.");if(b.clearSamplePayload===!0&&b.samplePayload!==void 0)throw Error("Provide either `samplePayload` or `clearSamplePayload`, not both.");let X=w==="configure_sequence_inbound_webhook",J=w==="rotate_sequence_inbound_webhook_secret",Y=X?{...b.clearFieldMapping===!0?{fieldMapping:null}:b.fieldMapping!==void 0?{fieldMapping:b.fieldMapping}:{},...b.clearSamplePayload===!0?{samplePayload:null}:b.samplePayload!==void 0?{samplePayload:b.samplePayload}:{}}:void 0;$=await D(J?"POST":X?"PUT":"GET",`/api/v1/sequences/${encodeURIComponent(W)}/inbound-webhook${J?"/rotate-secret":""}`,Y,Q);break}case"pause_sequence_enrollments":{let Q=b.companyId;$=await D("POST",`/api/v1/sequences/${b.sequenceId}/pause-enrollments`,void 0,Q);break}case"resume_sequence_enrollments":{let Q=b.companyId;$=await D("POST",`/api/v1/sequences/${b.sequenceId}/resume-enrollments`,void 0,Q);break}case"enroll_subscribers_in_sequence":{let Q=b.companyId,W=M("enroll_subscribers_in_sequence",b,"sequenceId"),X=C5(b);$=await D("POST",`/api/v1/sequences/${encodeURIComponent(W)}/enroll`,X,Q);break}case"cancel_sequence_enrollments":{let Q=b.companyId,W=j5(b);$=await D("POST",`/api/v1/sequences/${b.sequenceId}/enrollments/cancel`,W,Q);break}case"delete_sequence":{let Q=b.companyId;$=await D("DELETE",`/api/v1/sequences/${b.sequenceId}`,void 0,Q);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}function K4(w,b,$){let Q=b[$];if(Q===void 0)return;if(!Array.isArray(Q))throw Error(`\`${$}\` must be an array of strings when calling \`${w}\`.`);let W=Q.filter((X)=>typeof X==="string").map((X)=>X.trim()).filter((X)=>X.length>0);if(W.length!==Q.length)throw Error(`\`${$}\` must contain only non-empty strings when calling \`${w}\`.`);return W}function uV(w,b){let $=K4(w,b,"tags");if($===void 0||$.length===0)throw Error(`\`tags\` must contain at least one tag when calling \`${w}\`.`);let Q=K4(w,b,"emails"),W=K4(w,b,"externalIds"),X=K4(w,b,"subscriberIds");if((Q?.length??0)+(W?.length??0)+(X?.length??0)===0)throw Error(`Provide \`emails\`, \`externalIds\`, or \`subscriberIds\` when calling \`${w}\`.`);return{tags:$,...Q?.length?{emails:Q}:{},...W?.length?{externalIds:W}:{},...X?.length?{subscriberIds:X}:{},...w==="bulk_add_subscriber_tags"&&typeof b.triggerAutomations==="boolean"?{triggerAutomations:b.triggerAutomations}:{}}}async function v3(w,b){let $;switch(w){case"add_subscriber":{let Q=b.companyId,W=typeof b.phone==="string"&&b.phone.trim()!==""?b.phone.trim():void 0,X=W?XQ(b):a1("add_subscriber",b),J=l("add_subscriber",b,"status",["active","unsubscribed","bounced"]),Y=l("add_subscriber",b,"optInMode",["default","confirmed","double_opt_in"]);if($=await D("POST","/api/v1/subscribers",{...X,...W!==void 0&&{phone:W},...typeof b.phoneCountry==="string"&&b.phoneCountry.trim()!==""&&{phoneCountry:b.phoneCountry.trim()},...typeof b.smsConsent==="boolean"&&{smsConsent:b.smsConsent},...b.firstName!==void 0&&{firstName:b.firstName},...b.lastName!==void 0&&{lastName:b.lastName},customAttributes:b.attributes,tags:b.tags,lists:b.listIds,...J!==void 0&&{status:J},...Y!==void 0&&{optInMode:Y},...b.createdAt!==void 0&&{createdAt:b.createdAt}},Q),J!==void 0&&k($)&&k($.subscriber)&&$.subscriber.skipped===!0&&$.subscriber.status!==J)throw Error(`Existing subscriber was not changed to status '${J}'. Use update_subscriber to change an existing contact's status.`);break}case"create_subscriber_import":{let Q=b.companyId;if(!Array.isArray(b.subscribers)||b.subscribers.length===0)throw Error("`subscribers` must be a non-empty array when calling `create_subscriber_import`.");if(b.subscribers.length>5000)throw Error("`create_subscriber_import` accepts at most 5000 subscriber records per call.");for(let J=0;J<b.subscribers.length;J+=1){let Y=b.subscribers[J],G=k(Y)&&typeof Y.email==="string"&&Y.email.trim()!=="",H=k(Y)&&typeof Y.phone==="string"&&Y.phone.trim()!=="";if(!G&&!H)throw Error(`Subscriber record ${J} must include an email or a phone number.`)}let W=l("create_subscriber_import",b,"duplicateStrategy",["skip","merge","overwrite"]),X=l("create_subscriber_import",b,"optInMode",["default","confirmed","double_opt_in"]);$=await D("POST","/api/v1/subscribers/imports",{subscribers:b.subscribers,...W!==void 0&&{duplicateStrategy:W},...b.fileName!==void 0&&{fileName:b.fileName},...b.listIds!==void 0&&{listIds:b.listIds},...b.enrollInSequences!==void 0&&{enrollInSequences:b.enrollInSequences},...b.defaultPhoneCountry!==void 0&&{defaultPhoneCountry:b.defaultPhoneCountry},...b.smsConsent!==void 0&&{smsConsent:b.smsConsent},...X!==void 0&&{optInMode:X}},Q);break}case"get_subscriber_import":{let Q=b.companyId,W=M("get_subscriber_import",b,"importId");$=await D("GET",`/api/v1/subscribers/imports/${encodeURIComponent(W)}`,void 0,Q);break}case"update_subscriber":{let Q=b.companyId,W=a1("update_subscriber",b),X=l("update_subscriber",b,"status",["active","unsubscribed","bounced"]),Y=k(b.attributes)||b.addTags!==void 0||b.removeTags!==void 0?await Rb(W,Q):null,G=Array.isArray(Y?.subscriber.tags)?Y.subscriber.tags.filter((F)=>typeof F==="string"):[],H=Array.isArray(b.addTags)?b.addTags.filter((F)=>typeof F==="string"&&F.trim()!=="").map(WQ):[],z=new Set(Array.isArray(b.removeTags)?b.removeTags.filter((F)=>typeof F==="string"&&F.trim()!=="").map(WQ):[]),B=G.filter((F)=>!z.has(F));for(let F of H)if(!B.includes(F))B.push(F);let L={};if(W.email&&W.externalId)L.externalId=W.externalId;if(b.firstName!==void 0)L.firstName=b.firstName;if(b.lastName!==void 0)L.lastName=b.lastName;if(typeof b.phone==="string"||b.phone===null)L.phone=b.phone;if(typeof b.phoneCountry==="string")L.phoneCountry=b.phoneCountry;if(typeof b.smsConsent==="boolean")L.smsConsent=b.smsConsent;if(X!==void 0)L.status=X;if(k(b.attributes))L.customAttributes={...k(Y?.subscriber.customAttributes)?Y.subscriber.customAttributes:{},...b.attributes};if(b.addTags||b.removeTags)L.tags=B;$=await D("PATCH",D4(W),L,Q);break}case"remove_subscriber":{let Q=b.companyId,W=a1("remove_subscriber",b),X=D4(W);if(b.hardDelete===!0)$=await D("DELETE",X,void 0,Q);else $=await D("PATCH",X,{status:"unsubscribed"},Q);break}case"get_subscriber":{let Q=b.companyId,W=a1("get_subscriber",b);$=await Rb(W,Q,{includeMachineEngagement:b.includeMachineEngagement===!0});break}case"list_subscriber_notes":{let Q=b.companyId,W=a1("list_subscriber_notes",b);$=await D("GET",JQ(W),void 0,Q);break}case"add_subscriber_note":{let Q=b.companyId,W=a1("add_subscriber_note",b),X=typeof b.body==="string"?b.body.trim():void 0;if(!X)throw Error("`body` is required when calling `add_subscriber_note`.");if(X.length>5000)throw Error("`body` must be 5000 characters or fewer when calling `add_subscriber_note`.");$=await D("POST",JQ(W),{body:X},Q);break}case"delete_subscriber_note":{let Q=b.companyId,W=typeof b.noteId==="string"?b.noteId.trim():"";if(!W)throw Error("`noteId` is required when calling `delete_subscriber_note`.");$=await D("DELETE",`/api/v1/subscribers/notes/${encodeURIComponent(W)}`,void 0,Q);break}case"trigger_subscriber_event":{let Q=b.companyId,W=a1("trigger_subscriber_event",b),X=M("trigger_subscriber_event",b,"event");if(b.properties!==void 0&&!k(b.properties))throw Error("`properties` must be an object when calling `trigger_subscriber_event`.");$=await D("POST","/api/v1/subscribers/events",{...W,event:X,...b.properties!==void 0&&{properties:b.properties},...b.firstName!==void 0&&{firstName:b.firstName},...b.lastName!==void 0&&{lastName:b.lastName},...b.attributes!==void 0&&{customAttributes:b.attributes},...b.occurredAt!==void 0&&{occurredAt:b.occurredAt},...b.eventId!==void 0&&{eventId:b.eventId}},Q);break}case"trigger_subscriber_events":{let Q=b.companyId,W=a1("trigger_subscriber_events",b);if(!Array.isArray(b.events)||b.events.length===0)throw Error("`events` must be a non-empty array when calling `trigger_subscriber_events`.");if(b.events.length>500)throw Error("`trigger_subscriber_events` accepts at most 500 events per call. Split a larger history import into several calls.");for(let X=0;X<b.events.length;X+=1){let J=b.events[X];if(!k(J)||typeof J.name!=="string"||J.name.trim()==="")throw Error(`Event ${X} must include a non-empty \`name\` string.`)}$=await D("POST","/api/v1/subscribers/events/bulk",{...W,events:b.events,...b.firstName!==void 0&&{firstName:b.firstName},...b.lastName!==void 0&&{lastName:b.lastName},...b.attributes!==void 0&&{customAttributes:b.attributes}},Q);break}case"bulk_add_subscriber_tags":case"bulk_remove_subscriber_tags":{let Q=b.companyId,W=uV(w,b);$=await D("POST",`/api/v1/subscribers/bulk/tags/${w==="bulk_add_subscriber_tags"?"add":"remove"}`,W,Q);break}case"search_subscribers":{let Q=b.companyId;$=await R5(b,Q);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function C3(w,b){if(w!=="get_recipient_suppression"&&w!=="remove_recipient_suppression")return{handled:!1,result:void 0};let $=U(b,"companyId"),Q=M(w,b,"email"),W=U(b,"region"),X=new URLSearchParams;if(W)X.set("region",W);let J=`/api/v1/suppressions/${encodeURIComponent(Q)}${X.size>0?`?${X}`:""}`;return{handled:!0,result:await D(w==="get_recipient_suppression"?"GET":"DELETE",J,void 0,$)}}async function k3(w,b){let $;switch(w){case"list_team_members":{let Q=b.companyId;$=await D("GET","/api/v1/team",void 0,Q);break}case"invite_team_member":{let Q=b.companyId,W=M("invite_team_member",b,"email"),X=Sb("invite_team_member",b,"role",["admin","viewer","restricted"]);if(b.canManageBilling!==void 0&&typeof b.canManageBilling!=="boolean")throw Error("`canManageBilling` must be a boolean when calling `invite_team_member`.");$=await D("POST","/api/v1/team/invitations",{email:W,role:X,...b.canManageBilling!==void 0&&{canManageBilling:b.canManageBilling}},Q);break}case"cancel_team_invitation":{let Q=b.companyId,W=M("cancel_team_invitation",b,"invitationId");$=await D("DELETE",`/api/v1/team/invitations/${encodeURIComponent(W)}`,void 0,Q);break}case"list_conversations":{let Q=b.companyId,W=new URLSearchParams,X=l("list_conversations",b,"status",["open","closed","all"]);if(X)W.set("status",X);let J=U(b,"search");if(J)W.set("search",J);if(b.unread!==void 0){if(typeof b.unread!=="boolean")throw Error("`unread` must be a boolean when calling `list_conversations`.");if(b.unread)W.set("unread","true")}if(b.page!==void 0){if(typeof b.page!=="number"||!Number.isInteger(b.page)||b.page<1)throw Error("`page` must be a positive integer when calling `list_conversations`.");W.set("page",String(b.page))}let Y=Q1("list_conversations",b,"limit",1,100);if(Y!==void 0)W.set("limit",String(Y));$=await D("GET",`/api/v1/conversations${W.size>0?`?${W}`:""}`,void 0,Q);break}case"get_conversation":{let Q=b.companyId,W=M("get_conversation",b,"conversationId");$=await D("GET",`/api/v1/conversations/${encodeURIComponent(W)}`,void 0,Q);break}case"reply_to_conversation":{let Q=b.companyId,W=M("reply_to_conversation",b,"conversationId"),X=l("reply_to_conversation",b,"type",["outbound","note"])??"outbound",J=U(b,"subject"),Y=U(b,"bodyText"),G=U(b,"bodyHtml");if(X==="outbound"&&Y===void 0&&G===void 0)throw Error("Provide `bodyText` or `bodyHtml` when calling `reply_to_conversation` with an outbound message.");$=await D("POST",`/api/v1/conversations/${encodeURIComponent(W)}/messages`,{type:X,...J!==void 0&&{subject:J},...Y!==void 0&&{bodyText:Y},...G!==void 0&&{bodyHtml:G}},Q);break}case"update_conversation_status":{let Q=b.companyId,W=M("update_conversation_status",b,"conversationId"),X=Sb("update_conversation_status",b,"status",["open","closed"]);$=await D("POST",`/api/v1/conversations/${encodeURIComponent(W)}/status`,{status:X},Q);break}case"mark_conversation_read":{let Q=b.companyId,W=M("mark_conversation_read",b,"conversationId");$=await D("POST",`/api/v1/conversations/${encodeURIComponent(W)}/read`,void 0,Q);break}case"list_webhooks":{let Q=b.companyId;$=await D("GET","/api/v1/webhooks",void 0,Q);break}case"create_webhook":{let Q=b.companyId,W=M("create_webhook",b,"name"),X=M("create_webhook",b,"url"),J=GQ("create_webhook",b);$=await D("POST","/api/v1/webhooks",{name:W,url:X,...J!==void 0&&{events:J}},Q);break}case"update_webhook":{let Q=b.companyId,W=M("update_webhook",b,"webhookId"),X=U(b,"name"),J=U(b,"url"),Y=GQ("update_webhook",b),G=l("update_webhook",b,"status",["enabled","disabled"]);if(X===void 0&&J===void 0&&Y===void 0&&G===void 0)throw Error("Provide at least one of `name`, `url`, `events`, or `status` when calling `update_webhook`.");$=await D("PATCH",`/api/v1/webhooks/${encodeURIComponent(W)}`,{...X!==void 0&&{name:X},...J!==void 0&&{url:J},...Y!==void 0&&{events:Y},...G!==void 0&&{status:G}},Q);break}case"delete_webhook":{let Q=b.companyId,W=M("delete_webhook",b,"webhookId");$=await D("DELETE",`/api/v1/webhooks/${encodeURIComponent(W)}`,void 0,Q);break}case"test_webhook":{let Q=b.companyId,W=M("test_webhook",b,"webhookId");$=await D("POST",`/api/v1/webhooks/${encodeURIComponent(W)}/test`,void 0,Q);break}case"list_webhook_deliveries":{let Q=b.companyId,W=M("list_webhook_deliveries",b,"webhookId"),X=Q1("list_webhook_deliveries",b,"limit",1,100),J=new URLSearchParams;if(X!==void 0)J.set("limit",String(X));$=await D("GET",`/api/v1/webhooks/${encodeURIComponent(W)}/deliveries${J.size>0?`?${J}`:""}`,void 0,Q);break}case"replay_webhook_delivery":{let Q=b.companyId,W=M("replay_webhook_delivery",b,"webhookId"),X=M("replay_webhook_delivery",b,"deliveryId");$=await D("POST",`/api/v1/webhooks/${encodeURIComponent(W)}/deliveries/${encodeURIComponent(X)}/replay`,void 0,Q);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}var _3=[O3,I3,v3,C3,N3,M3,V3,T3,P3,E3,q3,FQ,j3,k3,Z3];var cV=new Set(["create_campaign","update_campaign","create_template","update_template","set_template_localization","create_transactional_email","update_transactional_email","create_sequence","update_sequence","update_sequence_node","update_sequence_nodes","insert_sequence_step","update_ab_test_variant","create_ab_test"]);function x3(w){return typeof w==="object"&&w!==null&&!Array.isArray(w)}function UQ(w){if(Array.isArray(w))return w.some(UQ);if(!x3(w))return!1;for(let[b,$]of Object.entries(w)){if((b==="html"||b==="htmlContent")&&typeof $==="string"&&$.trim().length>0)return!0;if(UQ($))return!0}return!1}function h3(w,b,$){if(!cV.has(w)||!UQ(b)||!x3($))return $;let Q=Array.isArray($.warnings)?$.warnings.filter((W)=>typeof W==="string"):[];return{...$,warnings:[...new Set([...Q,H1])]}}var O4="Ordinary searches are ordered newest-created first; attribute-filtered searches are ordered by subscriber ID ascending. Sort the returned array yourself if you need another order.",mV={search_subscribers:{filters:"Use the tags, list/listId/listName, status, and attribute arguments for single conditions, or create_segment plus segmentId for compound, OR, engagement, or event conditions.",filterJoinOperator:"The supported arguments always combine with AND. Use create_segment plus segmentId for OR logic.",sortBy:O4,sortOrder:O4,sort:O4,order:O4,attributes:'Filter on one attribute at a time with attribute: "attributeName:value".',customAttributes:'Filter on one attribute at a time with attribute: "attributeName:value".',page:"Omit limit to fetch every page automatically, or set limit to cap the result size.",offset:"Omit limit to fetch every page automatically, or set limit to cap the result size.",cursor:"Omit limit to fetch every page automatically, or set limit to cap the result size."}},y3=null;function lV(w){return y3??=new Map(U4.map((b)=>{let $=b.inputSchema.properties;return[b.name,new Set($&&typeof $==="object"?Object.keys($):[])]})),y3.get(w)??null}function f3(w,b){let $=lV(w);if(!$)return;let Q=Object.keys(b??{}).filter((Y)=>!$.has(Y));if(Q.length===0)return;let W=mV[w]??{},X=[...new Set(Q.flatMap((Y)=>W[Y]?[W[Y]]:[]))],J=$.size>0?`Supported arguments: ${[...$].map((Y)=>`\`${Y}\``).join(", ")}.`:`\`${w}\` takes no arguments.`;throw Error([`Unsupported field${Q.length===1?"":"s"}: ${Q.map((Y)=>`\`${Y}\``).join(", ")}.`,`\`${w}\` rejects arguments it does not support rather than ignoring them, because ignoring them would return a result that silently does not match the request.`,J,...X].join(" "))}var u3=U4.map(g5).map(b5);async function c3(w,b){try{f3(w,b);let $,Q=!1;for(let X of _3){let J=await X(w,b);if(J.handled){$=J.result,Q=!0;break}}if(!Q)throw Error(`Unknown tool: ${w}`);let W=E5($);if(W)throw W;return $=h3(w,b,$),$=await x5(w,b,$),{structuredContent:i5($),content:[{type:"text",text:JSON.stringify($,null,2)}]}}catch($){return{isError:!0,content:[{type:"text",text:s0($)}]}}}async function m3(w,b,$){let Q=b.getRequestContext?.(w)??{};try{return await MQ(Q,$)}finally{await b.onRequestContextUpdated?.(Q,w)}}function B_(w={}){let b=new C9({name:"sequenzy",version:tH.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(`
57
+ `)});return b.setRequestHandler(Z$,async()=>{return{tools:u3}}),b.setRequestHandler(ew,async($,Q)=>{let{name:W,arguments:X}=$.params;return m3(Q,w,()=>c3(W,X??{}))}),b.setRequestHandler(B$,async()=>{return{resources:eH}}),b.setRequestHandler(F$,async($,Q)=>{let{uri:W}=$.params;return m3(Q,w,()=>aH(W))}),b}export{B_ as createSequenzyMcpServer};