@sequenzy/mcp 0.0.119 → 0.0.121
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +14 -14
- package/dist/runtime.js +2 -2
- package/dist/server.js +12 -12
- package/package.json +1 -1
- package/server.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var qz=Object.create;var{getPrototypeOf:Xz,defineProperty:b4,getOwnPropertyNames:Yz}=Object;var Jz=Object.prototype.hasOwnProperty;function Dz(b){return this[b]}var Hz,zz,gW=(b,w,$)=>{var W=b!=null&&typeof b==="object";if(W){var Q=w?Hz??=new WeakMap:zz??=new WeakMap,G=Q.get(b);if(G)return G}$=b!=null?qz(Xz(b)):{};let q=w||!b||!b.__esModule?b4($,"default",{value:b,enumerable:!0}):$;for(let X of Yz(b))if(!Jz.call(q,X))b4(q,X,{get:Dz.bind(b,X),enumerable:!0});if(W)Q.set(b,q);return q};var Z=(b,w)=>()=>(w||b((w={exports:{}}).exports,w),w.exports);var Oz=(b)=>b;function Az(b,w){this[b]=Oz.bind(null,w)}var pW=(b,w)=>{for(var $ in w)b4(b,$,{get:w[$],enumerable:!0,configurable:!0,set:Az.bind(w,$)})};var f1=Z((o8)=>{Object.defineProperty(o8,"__esModule",{value:!0});o8.regexpCode=o8.getEsmExportName=o8.getProperty=o8.safeStringify=o8.stringify=o8.strConcat=o8.addCodeArg=o8.str=o8._=o8.nil=o8._Code=o8.Name=o8.IDENTIFIER=o8._CodeOrName=void 0;class s0{}o8._CodeOrName=s0;o8.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class dw extends s0{constructor(b){super();if(!o8.IDENTIFIER.test(b))throw Error("CodeGen: name must be a valid identifier");this.str=b}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}o8.Name=dw;class cb extends s0{constructor(b){super();this._items=typeof b==="string"?[b]:b}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let b=this._items[0];return b===""||b==='""'}get str(){var b;return(b=this._str)!==null&&b!==void 0?b:this._str=this._items.reduce((w,$)=>`${w}${$}`,"")}get names(){var b;return(b=this._names)!==null&&b!==void 0?b:this._names=this._items.reduce((w,$)=>{if($ instanceof dw)w[$.str]=(w[$.str]||0)+1;return w},{})}}o8._Code=cb;o8.nil=new cb("");function g8(b,...w){let $=[b[0]],W=0;while(W<w.length)J6($,w[W]),$.push(b[++W]);return new cb($)}o8._=g8;var Y6=new cb("+");function p8(b,...w){let $=[c1(b[0])],W=0;while(W<w.length)$.push(Y6),J6($,w[W]),$.push(Y6,c1(b[++W]));return x7($),new cb($)}o8.str=p8;function J6(b,w){if(w instanceof cb)b.push(...w._items);else if(w instanceof dw)b.push(w);else b.push(c7(w))}o8.addCodeArg=J6;function x7(b){let w=1;while(w<b.length-1){if(b[w]===Y6){let $=y7(b[w-1],b[w+1]);if($!==void 0){b.splice(w-1,3,$);continue}b[w++]="+"}w++}}function y7(b,w){if(w==='""')return b;if(b==='""')return w;if(typeof b=="string"){if(w instanceof dw||b[b.length-1]!=='"')return;if(typeof w!="string")return`${b.slice(0,-1)}${w}"`;if(w[0]==='"')return b.slice(0,-1)+w.slice(1);return}if(typeof w=="string"&&w[0]==='"'&&!(b instanceof dw))return`"${b}${w.slice(1)}`;return}function h7(b,w){return w.emptyStr()?b:b.emptyStr()?w:p8`${b}${w}`}o8.strConcat=h7;function c7(b){return typeof b=="number"||typeof b=="boolean"||b===null?b:c1(Array.isArray(b)?b.join(","):b)}function f7(b){return new cb(c1(b))}o8.stringify=f7;function c1(b){return JSON.stringify(b).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}o8.safeStringify=c1;function n7(b){return typeof b=="string"&&o8.IDENTIFIER.test(b)?new cb(`.${b}`):g8`[${b}]`}o8.getProperty=n7;function i7(b){if(typeof b=="string"&&o8.IDENTIFIER.test(b))return new cb(`${b}`);throw Error(`CodeGen: invalid export name: ${b}, use explicit $id name mapping`)}o8.getEsmExportName=i7;function m7(b){return new cb(b.toString())}o8.regexpCode=m7});var O6=Z((e8)=>{Object.defineProperty(e8,"__esModule",{value:!0});e8.ValueScope=e8.ValueScopeName=e8.Scope=e8.varKinds=e8.UsedValueState=void 0;var _b=f1();class t8 extends Error{constructor(b){super(`CodeGen: "code" for ${b} not defined`);this.value=b.value}}var b$;(function(b){b[b.Started=0]="Started",b[b.Completed=1]="Completed"})(b$||(e8.UsedValueState=b$={}));e8.varKinds={const:new _b.Name("const"),let:new _b.Name("let"),var:new _b.Name("var")};class H6{constructor({prefixes:b,parent:w}={}){this._names={},this._prefixes=b,this._parent=w}toName(b){return b instanceof _b.Name?b:this.name(b)}name(b){return new _b.Name(this._newName(b))}_newName(b){let w=this._names[b]||this._nameGroup(b);return`${b}${w.index++}`}_nameGroup(b){var w,$;if((($=(w=this._parent)===null||w===void 0?void 0:w._prefixes)===null||$===void 0?void 0:$.has(b))||this._prefixes&&!this._prefixes.has(b))throw Error(`CodeGen: prefix "${b}" is not allowed in this scope`);return this._names[b]={prefix:b,index:0}}}e8.Scope=H6;class z6 extends _b.Name{constructor(b,w){super(w);this.prefix=b}setValue(b,{property:w,itemIndex:$}){this.value=b,this.scopePath=_b._`.${new _b.Name(w)}[${$}]`}}e8.ValueScopeName=z6;var $5=_b._`\n`;class r8 extends H6{constructor(b){super(b);this._values={},this._scope=b.scope,this.opts={...b,_n:b.lines?$5:_b.nil}}get(){return this._scope}name(b){return new z6(b,this._newName(b))}value(b,w){var $;if(w.ref===void 0)throw Error("CodeGen: ref must be passed in value");let W=this.toName(b),{prefix:Q}=W,G=($=w.key)!==null&&$!==void 0?$:w.ref,q=this._values[Q];if(q){let J=q.get(G);if(J)return J}else q=this._values[Q]=new Map;q.set(G,W);let X=this._scope[Q]||(this._scope[Q]=[]),Y=X.length;return X[Y]=w.ref,W.setValue(w,{property:Q,itemIndex:Y}),W}getValue(b,w){let $=this._values[b];if(!$)return;return $.get(w)}scopeRefs(b,w=this._values){return this._reduceValues(w,($)=>{if($.scopePath===void 0)throw Error(`CodeGen: name "${$}" has no value`);return _b._`${b}${$.scopePath}`})}scopeCode(b=this._values,w,$){return this._reduceValues(b,(W)=>{if(W.value===void 0)throw Error(`CodeGen: name "${W}" has no value`);return W.value.code},w,$)}_reduceValues(b,w,$={},W){let Q=_b.nil;for(let G in b){let q=b[G];if(!q)continue;let X=$[G]=$[G]||new Map;q.forEach((Y)=>{if(X.has(Y))return;X.set(Y,b$.Started);let J=w(Y);if(J){let D=this.opts.es5?e8.varKinds.var:e8.varKinds.const;Q=_b._`${Q}${D} ${Y} = ${J};${this.opts._n}`}else if(J=W===null||W===void 0?void 0:W(Y))Q=_b._`${Q}${J}${this.opts._n}`;else throw new t8(Y);X.set(Y,b$.Completed)})}return Q}}e8.ValueScope=r8});var y=Z((Zb)=>{Object.defineProperty(Zb,"__esModule",{value:!0});Zb.or=Zb.and=Zb.not=Zb.CodeGen=Zb.operators=Zb.varKinds=Zb.ValueScopeName=Zb.ValueScope=Zb.Scope=Zb.Name=Zb.regexpCode=Zb.stringify=Zb.getProperty=Zb.nil=Zb.strConcat=Zb.str=Zb._=void 0;var n=f1(),fb=O6(),Zw=f1();Object.defineProperty(Zb,"_",{enumerable:!0,get:function(){return Zw._}});Object.defineProperty(Zb,"str",{enumerable:!0,get:function(){return Zw.str}});Object.defineProperty(Zb,"strConcat",{enumerable:!0,get:function(){return Zw.strConcat}});Object.defineProperty(Zb,"nil",{enumerable:!0,get:function(){return Zw.nil}});Object.defineProperty(Zb,"getProperty",{enumerable:!0,get:function(){return Zw.getProperty}});Object.defineProperty(Zb,"stringify",{enumerable:!0,get:function(){return Zw.stringify}});Object.defineProperty(Zb,"regexpCode",{enumerable:!0,get:function(){return Zw.regexpCode}});Object.defineProperty(Zb,"Name",{enumerable:!0,get:function(){return Zw.Name}});var q$=O6();Object.defineProperty(Zb,"Scope",{enumerable:!0,get:function(){return q$.Scope}});Object.defineProperty(Zb,"ValueScope",{enumerable:!0,get:function(){return q$.ValueScope}});Object.defineProperty(Zb,"ValueScopeName",{enumerable:!0,get:function(){return q$.ValueScopeName}});Object.defineProperty(Zb,"varKinds",{enumerable:!0,get:function(){return q$.varKinds}});Zb.operators={GT:new n._Code(">"),GTE:new n._Code(">="),LT:new n._Code("<"),LTE:new n._Code("<="),EQ:new n._Code("==="),NEQ:new n._Code("!=="),NOT:new n._Code("!"),OR:new n._Code("||"),AND:new n._Code("&&"),ADD:new n._Code("+")};class jw{optimizeNodes(){return this}optimizeNames(b,w){return this}}class a8 extends jw{constructor(b,w,$){super();this.varKind=b,this.name=w,this.rhs=$}render({es5:b,_n:w}){let $=b?fb.varKinds.var:this.varKind,W=this.rhs===void 0?"":` = ${this.rhs}`;return`${$} ${this.name}${W};`+w}optimizeNames(b,w){if(!b[this.name.str])return;if(this.rhs)this.rhs=rw(this.rhs,b,w);return this}get names(){return this.rhs instanceof n._CodeOrName?this.rhs.names:{}}}class L6 extends jw{constructor(b,w,$){super();this.lhs=b,this.rhs=w,this.sideEffects=$}render({_n:b}){return`${this.lhs} = ${this.rhs};`+b}optimizeNames(b,w){if(this.lhs instanceof n.Name&&!b[this.lhs.str]&&!this.sideEffects)return;return this.rhs=rw(this.rhs,b,w),this}get names(){let b=this.lhs instanceof n.Name?{}:{...this.lhs.names};return G$(b,this.rhs)}}class bq extends L6{constructor(b,w,$,W){super(b,$,W);this.op=w}render({_n:b}){return`${this.lhs} ${this.op}= ${this.rhs};`+b}}class wq extends jw{constructor(b){super();this.label=b,this.names={}}render({_n:b}){return`${this.label}:`+b}}class $q extends jw{constructor(b){super();this.label=b,this.names={}}render({_n:b}){return`break${this.label?` ${this.label}`:""};`+b}}class Wq extends jw{constructor(b){super();this.error=b}render({_n:b}){return`throw ${this.error};`+b}get names(){return this.error.names}}class Qq extends jw{constructor(b){super();this.code=b}render({_n:b}){return`${this.code};`+b}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(b,w){return this.code=rw(this.code,b,w),this}get names(){return this.code instanceof n._CodeOrName?this.code.names:{}}}class X$ extends jw{constructor(b=[]){super();this.nodes=b}render(b){return this.nodes.reduce((w,$)=>w+$.render(b),"")}optimizeNodes(){let{nodes:b}=this,w=b.length;while(w--){let $=b[w].optimizeNodes();if(Array.isArray($))b.splice(w,1,...$);else if($)b[w]=$;else b.splice(w,1)}return b.length>0?this:void 0}optimizeNames(b,w){let{nodes:$}=this,W=$.length;while(W--){let Q=$[W];if(Q.optimizeNames(b,w))continue;q5(b,Q.names),$.splice(W,1)}return $.length>0?this:void 0}get names(){return this.nodes.reduce((b,w)=>Cw(b,w.names),{})}}class Vw extends X${render(b){return"{"+b._n+super.render(b)+"}"+b._n}}class Gq extends X${}class n1 extends Vw{}n1.kind="else";class Gw extends Vw{constructor(b,w){super(w);this.condition=b}render(b){let w=`if(${this.condition})`+super.render(b);if(this.else)w+="else "+this.else.render(b);return w}optimizeNodes(){super.optimizeNodes();let b=this.condition;if(b===!0)return this.nodes;let w=this.else;if(w){let $=w.optimizeNodes();w=this.else=Array.isArray($)?new n1($):$}if(w){if(b===!1)return w instanceof Gw?w:w.nodes;if(this.nodes.length)return this;return new Gw(Dq(b),w instanceof Gw?[w]:w.nodes)}if(b===!1||!this.nodes.length)return;return this}optimizeNames(b,w){var $;if(this.else=($=this.else)===null||$===void 0?void 0:$.optimizeNames(b,w),!(super.optimizeNames(b,w)||this.else))return;return this.condition=rw(this.condition,b,w),this}get names(){let b=super.names;if(G$(b,this.condition),this.else)Cw(b,this.else.names);return b}}Gw.kind="if";class tw extends Vw{}tw.kind="for";class qq extends tw{constructor(b){super();this.iteration=b}render(b){return`for(${this.iteration})`+super.render(b)}optimizeNames(b,w){if(!super.optimizeNames(b,w))return;return this.iteration=rw(this.iteration,b,w),this}get names(){return Cw(super.names,this.iteration.names)}}class Xq extends tw{constructor(b,w,$,W){super();this.varKind=b,this.name=w,this.from=$,this.to=W}render(b){let w=b.es5?fb.varKinds.var:this.varKind,{name:$,from:W,to:Q}=this;return`for(${w} ${$}=${W}; ${$}<${Q}; ${$}++)`+super.render(b)}get names(){let b=G$(super.names,this.from);return G$(b,this.to)}}class A6 extends tw{constructor(b,w,$,W){super();this.loop=b,this.varKind=w,this.name=$,this.iterable=W}render(b){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(b)}optimizeNames(b,w){if(!super.optimizeNames(b,w))return;return this.iterable=rw(this.iterable,b,w),this}get names(){return Cw(super.names,this.iterable.names)}}class w$ extends Vw{constructor(b,w,$){super();this.name=b,this.args=w,this.async=$}render(b){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(b)}}w$.kind="func";class $$ extends X${render(b){return"return "+super.render(b)}}$$.kind="return";class Yq extends Vw{render(b){let w="try"+super.render(b);if(this.catch)w+=this.catch.render(b);if(this.finally)w+=this.finally.render(b);return w}optimizeNodes(){var b,w;return super.optimizeNodes(),(b=this.catch)===null||b===void 0||b.optimizeNodes(),(w=this.finally)===null||w===void 0||w.optimizeNodes(),this}optimizeNames(b,w){var $,W;return super.optimizeNames(b,w),($=this.catch)===null||$===void 0||$.optimizeNames(b,w),(W=this.finally)===null||W===void 0||W.optimizeNames(b,w),this}get names(){let b=super.names;if(this.catch)Cw(b,this.catch.names);if(this.finally)Cw(b,this.finally.names);return b}}class W$ extends Vw{constructor(b){super();this.error=b}render(b){return`catch(${this.error})`+super.render(b)}}W$.kind="catch";class Q$ extends Vw{render(b){return"finally"+super.render(b)}}Q$.kind="finally";class Jq{constructor(b,w={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...w,_n:w.lines?`
|
|
3
|
-
`:""},this._extScope=b,this._scope=new fb.Scope({parent:b}),this._nodes=[new Gq]}toString(){return this._root.render(this.opts)}name(b){return this._scope.name(b)}scopeName(b){return this._extScope.name(b)}scopeValue(b,w){let $=this._extScope.value(b,w);return(this._values[$.prefix]||(this._values[$.prefix]=new Set)).add($),$}getScopeValue(b,w){return this._extScope.getValue(b,w)}scopeRefs(b){return this._extScope.scopeRefs(b,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(b,w,$,W){let Q=this._scope.toName(w);if($!==void 0&&W)this._constants[Q.str]=$;return this._leafNode(new a8(b,Q,$)),Q}const(b,w,$){return this._def(fb.varKinds.const,b,w,$)}let(b,w,$){return this._def(fb.varKinds.let,b,w,$)}var(b,w,$){return this._def(fb.varKinds.var,b,w,$)}assign(b,w,$){return this._leafNode(new L6(b,w,$))}add(b,w){return this._leafNode(new bq(b,Zb.operators.ADD,w))}code(b){if(typeof b=="function")b();else if(b!==n.nil)this._leafNode(new Qq(b));return this}object(...b){let w=["{"];for(let[$,W]of b){if(w.length>1)w.push(",");if(w.push($),$!==W||this.opts.es5)w.push(":"),(0,n.addCodeArg)(w,W)}return w.push("}"),new n._Code(w)}if(b,w,$){if(this._blockNode(new Gw(b)),w&&$)this.code(w).else().code($).endIf();else if(w)this.code(w).endIf();else if($)throw Error('CodeGen: "else" body without "then" body');return this}elseIf(b){return this._elseNode(new Gw(b))}else(){return this._elseNode(new n1)}endIf(){return this._endBlockNode(Gw,n1)}_for(b,w){if(this._blockNode(b),w)this.code(w).endFor();return this}for(b,w){return this._for(new qq(b),w)}forRange(b,w,$,W,Q=this.opts.es5?fb.varKinds.var:fb.varKinds.let){let G=this._scope.toName(b);return this._for(new Xq(Q,G,w,$),()=>W(G))}forOf(b,w,$,W=fb.varKinds.const){let Q=this._scope.toName(b);if(this.opts.es5){let G=w instanceof n.Name?w:this.var("_arr",w);return this.forRange("_i",0,n._`${G}.length`,(q)=>{this.var(Q,n._`${G}[${q}]`),$(Q)})}return this._for(new A6("of",W,Q,w),()=>$(Q))}forIn(b,w,$,W=this.opts.es5?fb.varKinds.var:fb.varKinds.const){if(this.opts.ownProperties)return this.forOf(b,n._`Object.keys(${w})`,$);let Q=this._scope.toName(b);return this._for(new A6("in",W,Q,w),()=>$(Q))}endFor(){return this._endBlockNode(tw)}label(b){return this._leafNode(new wq(b))}break(b){return this._leafNode(new $q(b))}return(b){let w=new $$;if(this._blockNode(w),this.code(b),w.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode($$)}try(b,w,$){if(!w&&!$)throw Error('CodeGen: "try" without "catch" and "finally"');let W=new Yq;if(this._blockNode(W),this.code(b),w){let Q=this.name("e");this._currNode=W.catch=new W$(Q),w(Q)}if($)this._currNode=W.finally=new Q$,this.code($);return this._endBlockNode(W$,Q$)}throw(b){return this._leafNode(new Wq(b))}block(b,w){if(this._blockStarts.push(this._nodes.length),b)this.code(b).endBlock(w);return this}endBlock(b){let w=this._blockStarts.pop();if(w===void 0)throw Error("CodeGen: not in self-balancing block");let $=this._nodes.length-w;if($<0||b!==void 0&&$!==b)throw Error(`CodeGen: wrong number of nodes: ${$} vs ${b} expected`);return this._nodes.length=w,this}func(b,w=n.nil,$,W){if(this._blockNode(new w$(b,w,$)),W)this.code(W).endFunc();return this}endFunc(){return this._endBlockNode(w$)}optimize(b=1){while(b-- >0)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(b){return this._currNode.nodes.push(b),this}_blockNode(b){this._currNode.nodes.push(b),this._nodes.push(b)}_endBlockNode(b,w){let $=this._currNode;if($ instanceof b||w&&$ instanceof w)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${w?`${b.kind}/${w.kind}`:b.kind}"`)}_elseNode(b){let w=this._currNode;if(!(w instanceof Gw))throw Error('CodeGen: "else" without "if"');return this._currNode=w.else=b,this}get _root(){return this._nodes[0]}get _currNode(){let b=this._nodes;return b[b.length-1]}set _currNode(b){let w=this._nodes;w[w.length-1]=b}}Zb.CodeGen=Jq;function Cw(b,w){for(let $ in w)b[$]=(b[$]||0)+(w[$]||0);return b}function G$(b,w){return w instanceof n._CodeOrName?Cw(b,w.names):b}function rw(b,w,$){if(b instanceof n.Name)return W(b);if(!Q(b))return b;return new n._Code(b._items.reduce((G,q)=>{if(q instanceof n.Name)q=W(q);if(q instanceof n._Code)G.push(...q._items);else G.push(q);return G},[]));function W(G){let q=$[G.str];if(q===void 0||w[G.str]!==1)return G;return delete w[G.str],q}function Q(G){return G instanceof n._Code&&G._items.some((q)=>q instanceof n.Name&&w[q.str]===1&&$[q.str]!==void 0)}}function q5(b,w){for(let $ in w)b[$]=(b[$]||0)-(w[$]||0)}function Dq(b){return typeof b=="boolean"||typeof b=="number"||b===null?!b:n._`!${U6(b)}`}Zb.not=Dq;var X5=Hq(Zb.operators.AND);function Y5(...b){return b.reduce(X5)}Zb.and=Y5;var J5=Hq(Zb.operators.OR);function D5(...b){return b.reduce(J5)}Zb.or=D5;function Hq(b){return(w,$)=>w===n.nil?$:$===n.nil?w:n._`${U6(w)} ${b} ${U6($)}`}function U6(b){return b instanceof n.Name?b:n._`(${b})`}});var g=Z((Kq)=>{Object.defineProperty(Kq,"__esModule",{value:!0});Kq.checkStrictMode=Kq.getErrorPath=Kq.Type=Kq.useFunc=Kq.setEvaluated=Kq.evaluatedPropsToName=Kq.mergeEvaluated=Kq.eachItem=Kq.unescapeJsonPointer=Kq.escapeJsonPointer=Kq.escapeFragment=Kq.unescapeFragment=Kq.schemaRefOrVal=Kq.schemaHasRulesButRef=Kq.schemaHasRules=Kq.checkUnknownRules=Kq.alwaysValidSchema=Kq.toHash=void 0;var t=y(),A5=f1();function U5(b){let w={};for(let $ of b)w[$]=!0;return w}Kq.toHash=U5;function L5(b,w){if(typeof w=="boolean")return w;if(Object.keys(w).length===0)return!0;return Uq(b,w),!Lq(w,b.self.RULES.all)}Kq.alwaysValidSchema=L5;function Uq(b,w=b.schema){let{opts:$,self:W}=b;if(!$.strictSchema)return;if(typeof w==="boolean")return;let Q=W.RULES.keywords;for(let G in w)if(!Q[G])Fq(b,`unknown keyword: "${G}"`)}Kq.checkUnknownRules=Uq;function Lq(b,w){if(typeof b=="boolean")return!b;for(let $ in b)if(w[$])return!0;return!1}Kq.schemaHasRules=Lq;function P5(b,w){if(typeof b=="boolean")return!b;for(let $ in b)if($!=="$ref"&&w.all[$])return!0;return!1}Kq.schemaHasRulesButRef=P5;function B5({topSchemaRef:b,schemaPath:w},$,W,Q){if(!Q){if(typeof $=="number"||typeof $=="boolean")return $;if(typeof $=="string")return t._`${$}`}return t._`${b}${w}${(0,t.getProperty)(W)}`}Kq.schemaRefOrVal=B5;function F5(b){return Pq(decodeURIComponent(b))}Kq.unescapeFragment=F5;function K5(b){return encodeURIComponent(B6(b))}Kq.escapeFragment=K5;function B6(b){if(typeof b=="number")return`${b}`;return b.replace(/~/g,"~0").replace(/\//g,"~1")}Kq.escapeJsonPointer=B6;function Pq(b){return b.replace(/~1/g,"/").replace(/~0/g,"~")}Kq.unescapeJsonPointer=Pq;function M5(b,w){if(Array.isArray(b))for(let $ of b)w($);else w(b)}Kq.eachItem=M5;function Oq({mergeNames:b,mergeToName:w,mergeValues:$,resultToName:W}){return(Q,G,q,X)=>{let Y=q===void 0?G:q instanceof t.Name?(G instanceof t.Name?b(Q,G,q):w(Q,G,q),q):G instanceof t.Name?(w(Q,q,G),G):$(G,q);return X===t.Name&&!(Y instanceof t.Name)?W(Q,Y):Y}}Kq.mergeEvaluated={props:Oq({mergeNames:(b,w,$)=>b.if(t._`${$} !== true && ${w} !== undefined`,()=>{b.if(t._`${w} === true`,()=>b.assign($,!0),()=>b.assign($,t._`${$} || {}`).code(t._`Object.assign(${$}, ${w})`))}),mergeToName:(b,w,$)=>b.if(t._`${$} !== true`,()=>{if(w===!0)b.assign($,!0);else b.assign($,t._`${$} || {}`),F6(b,$,w)}),mergeValues:(b,w)=>b===!0?!0:{...b,...w},resultToName:Bq}),items:Oq({mergeNames:(b,w,$)=>b.if(t._`${$} !== true && ${w} !== undefined`,()=>b.assign($,t._`${w} === true ? true : ${$} > ${w} ? ${$} : ${w}`)),mergeToName:(b,w,$)=>b.if(t._`${$} !== true`,()=>b.assign($,w===!0?!0:t._`${$} > ${w} ? ${$} : ${w}`)),mergeValues:(b,w)=>b===!0?!0:Math.max(b,w),resultToName:(b,w)=>b.var("items",w)})};function Bq(b,w){if(w===!0)return b.var("props",!0);let $=b.var("props",t._`{}`);if(w!==void 0)F6(b,$,w);return $}Kq.evaluatedPropsToName=Bq;function F6(b,w,$){Object.keys($).forEach((W)=>b.assign(t._`${w}${(0,t.getProperty)(W)}`,!0))}Kq.setEvaluated=F6;var Aq={};function I5(b,w){return b.scopeValue("func",{ref:w,code:Aq[w.code]||(Aq[w.code]=new A5._Code(w.code))})}Kq.useFunc=I5;var P6;(function(b){b[b.Num=0]="Num",b[b.Str=1]="Str"})(P6||(Kq.Type=P6={}));function _5(b,w,$){if(b instanceof t.Name){let W=w===P6.Num;return $?W?t._`"[" + ${b} + "]"`:t._`"['" + ${b} + "']"`:W?t._`"/" + ${b}`:t._`"/" + ${b}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return $?(0,t.getProperty)(b).toString():"/"+B6(b)}Kq.getErrorPath=_5;function Fq(b,w,$=b.opts.strictSchema){if(!$)return;if(w=`strict mode: ${w}`,$===!0)throw Error(w);b.self.logger.warn(w)}Kq.checkStrictMode=Fq});var qw=Z((Iq)=>{Object.defineProperty(Iq,"__esModule",{value:!0});var Pb=y(),n5={data:new Pb.Name("data"),valCxt:new Pb.Name("valCxt"),instancePath:new Pb.Name("instancePath"),parentData:new Pb.Name("parentData"),parentDataProperty:new Pb.Name("parentDataProperty"),rootData:new Pb.Name("rootData"),dynamicAnchors:new Pb.Name("dynamicAnchors"),vErrors:new Pb.Name("vErrors"),errors:new Pb.Name("errors"),this:new Pb.Name("this"),self:new Pb.Name("self"),scope:new Pb.Name("scope"),json:new Pb.Name("json"),jsonPos:new Pb.Name("jsonPos"),jsonLen:new Pb.Name("jsonLen"),jsonPart:new Pb.Name("jsonPart")};Iq.default=n5});var i1=Z((Vq)=>{Object.defineProperty(Vq,"__esModule",{value:!0});Vq.extendErrors=Vq.resetErrorsCount=Vq.reportExtraError=Vq.reportError=Vq.keyword$DataError=Vq.keywordError=void 0;var m=y(),J$=g(),Fb=qw();Vq.keywordError={message:({keyword:b})=>m.str`must pass "${b}" keyword validation`};Vq.keyword$DataError={message:({keyword:b,schemaType:w})=>w?m.str`"${b}" keyword must be ${w} ($data)`:m.str`"${b}" keyword is invalid ($data)`};function m5(b,w=Vq.keywordError,$,W){let{it:Q}=b,{gen:G,compositeRule:q,allErrors:X}=Q,Y=jq(b,w,$);if(W!==null&&W!==void 0?W:q||X)_q(G,Y);else Zq(Q,m._`[${Y}]`)}Vq.reportError=m5;function l5(b,w=Vq.keywordError,$){let{it:W}=b,{gen:Q,compositeRule:G,allErrors:q}=W,X=jq(b,w,$);if(_q(Q,X),!(G||q))Zq(W,Fb.default.vErrors)}Vq.reportExtraError=l5;function g5(b,w){b.assign(Fb.default.errors,w),b.if(m._`${Fb.default.vErrors} !== null`,()=>b.if(w,()=>b.assign(m._`${Fb.default.vErrors}.length`,w),()=>b.assign(Fb.default.vErrors,null)))}Vq.resetErrorsCount=g5;function p5({gen:b,keyword:w,schemaValue:$,data:W,errsCount:Q,it:G}){if(Q===void 0)throw Error("ajv implementation error");let q=b.name("err");b.forRange("i",Q,Fb.default.errors,(X)=>{if(b.const(q,m._`${Fb.default.vErrors}[${X}]`),b.if(m._`${q}.instancePath === undefined`,()=>b.assign(m._`${q}.instancePath`,(0,m.strConcat)(Fb.default.instancePath,G.errorPath))),b.assign(m._`${q}.schemaPath`,m.str`${G.errSchemaPath}/${w}`),G.opts.verbose)b.assign(m._`${q}.schema`,$),b.assign(m._`${q}.data`,W)})}Vq.extendErrors=p5;function _q(b,w){let $=b.const("err",w);b.if(m._`${Fb.default.vErrors} === null`,()=>b.assign(Fb.default.vErrors,m._`[${$}]`),m._`${Fb.default.vErrors}.push(${$})`),b.code(m._`${Fb.default.errors}++`)}function Zq(b,w){let{gen:$,validateName:W,schemaEnv:Q}=b;if(Q.$async)$.throw(m._`new ${b.ValidationError}(${w})`);else $.assign(m._`${W}.errors`,w),$.return(!1)}var uw={keyword:new m.Name("keyword"),schemaPath:new m.Name("schemaPath"),params:new m.Name("params"),propertyName:new m.Name("propertyName"),message:new m.Name("message"),schema:new m.Name("schema"),parentSchema:new m.Name("parentSchema")};function jq(b,w,$){let{createErrors:W}=b.it;if(W===!1)return m._`{}`;return o5(b,w,$)}function o5(b,w,$={}){let{gen:W,it:Q}=b,G=[d5(Q,$),t5(b,$)];return r5(b,w,G),W.object(...G)}function d5({errorPath:b},{instancePath:w}){let $=w?m.str`${b}${(0,J$.getErrorPath)(w,J$.Type.Str)}`:b;return[Fb.default.instancePath,(0,m.strConcat)(Fb.default.instancePath,$)]}function t5({keyword:b,it:{errSchemaPath:w}},{schemaPath:$,parentSchema:W}){let Q=W?w:m.str`${w}/${b}`;if($)Q=m.str`${Q}${(0,J$.getErrorPath)($,J$.Type.Str)}`;return[uw.schemaPath,Q]}function r5(b,{params:w,message:$},W){let{keyword:Q,data:G,schemaValue:q,it:X}=b,{opts:Y,propertyName:J,topSchemaRef:D,schemaPath:H}=X;if(W.push([uw.keyword,Q],[uw.params,typeof w=="function"?w(b):w||m._`{}`]),Y.messages)W.push([uw.message,typeof $=="function"?$(b):$]);if(Y.verbose)W.push([uw.schema,q],[uw.parentSchema,m._`${D}${H}`],[Fb.default.data,G]);if(J)W.push([uw.propertyName,J])}});var Rq=Z((Tq)=>{Object.defineProperty(Tq,"__esModule",{value:!0});Tq.boolOrEmptySchema=Tq.topBoolOrEmptySchema=void 0;var wU=i1(),$U=y(),WU=qw(),QU={message:"boolean schema is false"};function GU(b){let{gen:w,schema:$,validateName:W}=b;if($===!1)Eq(b,!1);else if(typeof $=="object"&&$.$async===!0)w.return(WU.default.data);else w.assign($U._`${W}.errors`,null),w.return(!0)}Tq.topBoolOrEmptySchema=GU;function qU(b,w){let{gen:$,schema:W}=b;if(W===!1)$.var(w,!1),Eq(b);else $.var(w,!0)}Tq.boolOrEmptySchema=qU;function Eq(b,w){let{gen:$,data:W}=b,Q={gen:$,keyword:"false schema",data:W,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:b};(0,wU.reportError)(Q,QU,void 0,w)}});var M6=Z((vq)=>{Object.defineProperty(vq,"__esModule",{value:!0});vq.getRules=vq.isJSONType=void 0;var YU=["string","number","integer","boolean","null","object","array"],JU=new Set(YU);function DU(b){return typeof b=="string"&&JU.has(b)}vq.isJSONType=DU;function HU(){let b={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...b,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},b.number,b.string,b.array,b.object],post:{rules:[]},all:{},keywords:{}}}vq.getRules=HU});var I6=Z((xq)=>{Object.defineProperty(xq,"__esModule",{value:!0});xq.shouldUseRule=xq.shouldUseGroup=xq.schemaHasRulesForType=void 0;function OU({schema:b,self:w},$){let W=w.RULES.types[$];return W&&W!==!0&&Cq(b,W)}xq.schemaHasRulesForType=OU;function Cq(b,w){return w.rules.some(($)=>uq(b,$))}xq.shouldUseGroup=Cq;function uq(b,w){var $;return b[w.keyword]!==void 0||(($=w.definition.implements)===null||$===void 0?void 0:$.some((W)=>b[W]!==void 0))}xq.shouldUseRule=uq});var m1=Z((nq)=>{Object.defineProperty(nq,"__esModule",{value:!0});nq.reportTypeError=nq.checkDataTypes=nq.checkDataType=nq.coerceAndCheckDataType=nq.getJSONTypes=nq.getSchemaTypes=nq.DataType=void 0;var LU=M6(),PU=I6(),BU=i1(),u=y(),hq=g(),ew;(function(b){b[b.Correct=0]="Correct",b[b.Wrong=1]="Wrong"})(ew||(nq.DataType=ew={}));function FU(b){let w=cq(b.type);if(w.includes("null")){if(b.nullable===!1)throw Error("type: null contradicts nullable: false")}else{if(!w.length&&b.nullable!==void 0)throw Error('"nullable" cannot be used without "type"');if(b.nullable===!0)w.push("null")}return w}nq.getSchemaTypes=FU;function cq(b){let w=Array.isArray(b)?b:b?[b]:[];if(w.every(LU.isJSONType))return w;throw Error("type must be JSONType or JSONType[]: "+w.join(","))}nq.getJSONTypes=cq;function KU(b,w){let{gen:$,data:W,opts:Q}=b,G=MU(w,Q.coerceTypes),q=w.length>0&&!(G.length===0&&w.length===1&&(0,PU.schemaHasRulesForType)(b,w[0]));if(q){let X=Z6(w,W,Q.strictNumbers,ew.Wrong);$.if(X,()=>{if(G.length)IU(b,w,G);else j6(b)})}return q}nq.coerceAndCheckDataType=KU;var fq=new Set(["string","number","integer","boolean","null"]);function MU(b,w){return w?b.filter(($)=>fq.has($)||w==="array"&&$==="array"):[]}function IU(b,w,$){let{gen:W,data:Q,opts:G}=b,q=W.let("dataType",u._`typeof ${Q}`),X=W.let("coerced",u._`undefined`);if(G.coerceTypes==="array")W.if(u._`${q} == 'object' && Array.isArray(${Q}) && ${Q}.length == 1`,()=>W.assign(Q,u._`${Q}[0]`).assign(q,u._`typeof ${Q}`).if(Z6(w,Q,G.strictNumbers),()=>W.assign(X,Q)));W.if(u._`${X} !== undefined`);for(let J of $)if(fq.has(J)||J==="array"&&G.coerceTypes==="array")Y(J);W.else(),j6(b),W.endIf(),W.if(u._`${X} !== undefined`,()=>{W.assign(Q,X),_U(b,X)});function Y(J){switch(J){case"string":W.elseIf(u._`${q} == "number" || ${q} == "boolean"`).assign(X,u._`"" + ${Q}`).elseIf(u._`${Q} === null`).assign(X,u._`""`);return;case"number":W.elseIf(u._`${q} == "boolean" || ${Q} === null
|
|
4
|
-
|| (${
|
|
5
|
-
|| (${
|
|
6
|
-
|| ${q} === "boolean" || ${Q} === null`).assign(X,u._`[${Q}]`)}}}function _U({gen:b,parentData:w,parentDataProperty:$},W){b.if(u._`${w} !== undefined`,()=>b.assign(u._`${w}[${$}]`,W))}function _6(b,w,$,W=ew.Correct){let Q=W===ew.Correct?u.operators.EQ:u.operators.NEQ,G;switch(b){case"null":return u._`${w} ${Q} null`;case"array":G=u._`Array.isArray(${w})`;break;case"object":G=u._`${w} && typeof ${w} == "object" && !Array.isArray(${w})`;break;case"integer":G=q(u._`!(${w} % 1) && !isNaN(${w})`);break;case"number":G=q();break;default:return u._`typeof ${w} ${Q} ${b}`}return W===ew.Correct?G:(0,u.not)(G);function q(X=u.nil){return(0,u.and)(u._`typeof ${w} == "number"`,X,$?u._`isFinite(${w})`:u.nil)}}nq.checkDataType=_6;function Z6(b,w,$,W){if(b.length===1)return _6(b[0],w,$,W);let Q,G=(0,hq.toHash)(b);if(G.array&&G.object){let q=u._`typeof ${w} != "object"`;Q=G.null?q:u._`!${w} || ${q}`,delete G.null,delete G.array,delete G.object}else Q=u.nil;if(G.number)delete G.integer;for(let q in G)Q=(0,u.and)(Q,_6(q,w,$,W));return Q}nq.checkDataTypes=Z6;var ZU={message:({schema:b})=>`must be ${b}`,params:({schema:b,schemaValue:w})=>typeof b=="string"?u._`{type: ${b}}`:u._`{type: ${w}}`};function j6(b){let w=jU(b);(0,BU.reportError)(w,ZU)}nq.reportTypeError=j6;function jU(b){let{gen:w,data:$,schema:W}=b,Q=(0,hq.schemaRefOrVal)(b,W,"type");return{gen:w,keyword:"type",data:$,schema:W.type,schemaCode:Q,schemaValue:Q,parentSchema:W,params:{},it:b}}});var pq=Z((lq)=>{Object.defineProperty(lq,"__esModule",{value:!0});lq.assignDefaults=void 0;var sw=y(),vU=g();function kU(b,w){let{properties:$,items:W}=b.schema;if(w==="object"&&$)for(let Q in $)mq(b,Q,$[Q].default);else if(w==="array"&&Array.isArray(W))W.forEach((Q,G)=>mq(b,G,Q.default))}lq.assignDefaults=kU;function mq(b,w,$){let{gen:W,compositeRule:Q,data:G,opts:q}=b;if($===void 0)return;let X=sw._`${G}${(0,sw.getProperty)(w)}`;if(Q){(0,vU.checkStrictMode)(b,`default is ignored for: ${X}`);return}let Y=sw._`${X} === undefined`;if(q.useDefaults==="empty")Y=sw._`${Y} || ${X} === null || ${X} === ""`;W.if(Y,sw._`${X} = ${(0,sw.stringify)($)}`)}});var ub=Z((tq)=>{Object.defineProperty(tq,"__esModule",{value:!0});tq.validateUnion=tq.validateArray=tq.usePattern=tq.callValidateCode=tq.schemaProperties=tq.allSchemaProperties=tq.noPropertyInData=tq.propertyInData=tq.isOwnProperty=tq.hasPropFunc=tq.reportMissingProp=tq.checkMissingProp=tq.checkReportMissingProp=void 0;var a=y(),V6=g(),Nw=qw(),CU=g();function uU(b,w){let{gen:$,data:W,it:Q}=b;$.if(E6($,W,w,Q.opts.ownProperties),()=>{b.setParams({missingProperty:a._`${w}`},!0),b.error()})}tq.checkReportMissingProp=uU;function xU({gen:b,data:w,it:{opts:$}},W,Q){return(0,a.or)(...W.map((G)=>(0,a.and)(E6(b,w,G,$.ownProperties),a._`${Q} = ${G}`)))}tq.checkMissingProp=xU;function yU(b,w){b.setParams({missingProperty:w},!0),b.error()}tq.reportMissingProp=yU;function oq(b){return b.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:a._`Object.prototype.hasOwnProperty`})}tq.hasPropFunc=oq;function N6(b,w,$){return a._`${oq(b)}.call(${w}, ${$})`}tq.isOwnProperty=N6;function hU(b,w,$,W){let Q=a._`${w}${(0,a.getProperty)($)} !== undefined`;return W?a._`${Q} && ${N6(b,w,$)}`:Q}tq.propertyInData=hU;function E6(b,w,$,W){let Q=a._`${w}${(0,a.getProperty)($)} === undefined`;return W?(0,a.or)(Q,(0,a.not)(N6(b,w,$))):Q}tq.noPropertyInData=E6;function dq(b){return b?Object.keys(b).filter((w)=>w!=="__proto__"):[]}tq.allSchemaProperties=dq;function cU(b,w){return dq(w).filter(($)=>!(0,V6.alwaysValidSchema)(b,w[$]))}tq.schemaProperties=cU;function fU({schemaCode:b,data:w,it:{gen:$,topSchemaRef:W,schemaPath:Q,errorPath:G},it:q},X,Y,J){let D=J?a._`${b}, ${w}, ${W}${Q}`:w,H=[[Nw.default.instancePath,(0,a.strConcat)(Nw.default.instancePath,G)],[Nw.default.parentData,q.parentData],[Nw.default.parentDataProperty,q.parentDataProperty],[Nw.default.rootData,Nw.default.rootData]];if(q.opts.dynamicRef)H.push([Nw.default.dynamicAnchors,Nw.default.dynamicAnchors]);let O=a._`${D}, ${$.object(...H)}`;return Y!==a.nil?a._`${X}.call(${Y}, ${O})`:a._`${X}(${O})`}tq.callValidateCode=fU;var nU=a._`new RegExp`;function iU({gen:b,it:{opts:w}},$){let W=w.unicodeRegExp?"u":"",{regExp:Q}=w.code,G=Q($,W);return b.scopeValue("pattern",{key:G.toString(),ref:G,code:a._`${Q.code==="new RegExp"?nU:(0,CU.useFunc)(b,Q)}(${$}, ${W})`})}tq.usePattern=iU;function mU(b){let{gen:w,data:$,keyword:W,it:Q}=b,G=w.name("valid");if(Q.allErrors){let X=w.let("valid",!0);return q(()=>w.assign(X,!1)),X}return w.var(G,!0),q(()=>w.break()),G;function q(X){let Y=w.const("len",a._`${$}.length`);w.forRange("i",0,Y,(J)=>{b.subschema({keyword:W,dataProp:J,dataPropType:V6.Type.Num},G),w.if((0,a.not)(G),X)})}}tq.validateArray=mU;function lU(b){let{gen:w,schema:$,keyword:W,it:Q}=b;if(!Array.isArray($))throw Error("ajv implementation error");if($.some((Y)=>(0,V6.alwaysValidSchema)(Q,Y))&&!Q.opts.unevaluated)return;let q=w.let("valid",!1),X=w.name("_valid");w.block(()=>$.forEach((Y,J)=>{let D=b.subschema({keyword:W,schemaProp:J,compositeRule:!0},X);if(w.assign(q,a._`${q} || ${X}`),!b.mergeValidEvaluated(D,X))w.if((0,a.not)(q))})),b.result(q,()=>b.reset(),()=>b.error(!0))}tq.validateUnion=lU});var wX=Z((aq)=>{Object.defineProperty(aq,"__esModule",{value:!0});aq.validateKeywordUsage=aq.validSchemaType=aq.funcKeywordCode=aq.macroKeywordCode=void 0;var Kb=y(),xw=qw(),WL=ub(),QL=i1();function GL(b,w){let{gen:$,keyword:W,schema:Q,parentSchema:G,it:q}=b,X=w.macro.call(q.self,Q,G,q),Y=sq($,W,X);if(q.opts.validateSchema!==!1)q.self.validateSchema(X,!0);let J=$.name("valid");b.subschema({schema:X,schemaPath:Kb.nil,errSchemaPath:`${q.errSchemaPath}/${W}`,topSchemaRef:Y,compositeRule:!0},J),b.pass(J,()=>b.error(!0))}aq.macroKeywordCode=GL;function qL(b,w){var $;let{gen:W,keyword:Q,schema:G,parentSchema:q,$data:X,it:Y}=b;YL(Y,w);let J=!X&&w.compile?w.compile.call(Y.self,G,q,Y):w.validate,D=sq(W,Q,J),H=W.let("valid");b.block$data(H,O),b.ok(($=w.valid)!==null&&$!==void 0?$:H);function O(){if(w.errors===!1){if(K(),w.modifying)eq(b);_(()=>b.error())}else{let I=w.async?A():B();if(w.modifying)eq(b);_(()=>XL(b,I))}}function A(){let I=W.let("ruleErrs",null);return W.try(()=>K(Kb._`await `),(R)=>W.assign(H,!1).if(Kb._`${R} instanceof ${Y.ValidationError}`,()=>W.assign(I,Kb._`${R}.errors`),()=>W.throw(R))),I}function B(){let I=Kb._`${D}.errors`;return W.assign(I,null),K(Kb.nil),I}function K(I=w.async?Kb._`await `:Kb.nil){let R=Y.opts.passContext?xw.default.this:xw.default.self,T=!(("compile"in w)&&!X||w.schema===!1);W.assign(H,Kb._`${I}${(0,WL.callValidateCode)(b,D,R,T)}`,w.modifying)}function _(I){var R;W.if((0,Kb.not)((R=w.valid)!==null&&R!==void 0?R:H),I)}}aq.funcKeywordCode=qL;function eq(b){let{gen:w,data:$,it:W}=b;w.if(W.parentData,()=>w.assign($,Kb._`${W.parentData}[${W.parentDataProperty}]`))}function XL(b,w){let{gen:$}=b;$.if(Kb._`Array.isArray(${w})`,()=>{$.assign(xw.default.vErrors,Kb._`${xw.default.vErrors} === null ? ${w} : ${xw.default.vErrors}.concat(${w})`).assign(xw.default.errors,Kb._`${xw.default.vErrors}.length`),(0,QL.extendErrors)(b)},()=>b.error())}function YL({schemaEnv:b},w){if(w.async&&!b.$async)throw Error("async keyword in sync schema")}function sq(b,w,$){if($===void 0)throw Error(`keyword "${w}" failed to compile`);return b.scopeValue("keyword",typeof $=="function"?{ref:$}:{ref:$,code:(0,Kb.stringify)($)})}function JL(b,w,$=!1){return!w.length||w.some((W)=>W==="array"?Array.isArray(b):W==="object"?b&&typeof b=="object"&&!Array.isArray(b):typeof b==W||$&&typeof b>"u")}aq.validSchemaType=JL;function DL({schema:b,opts:w,self:$,errSchemaPath:W},Q,G){if(Array.isArray(Q.keyword)?!Q.keyword.includes(G):Q.keyword!==G)throw Error("ajv implementation error");let q=Q.dependencies;if(q===null||q===void 0?void 0:q.some((X)=>!Object.prototype.hasOwnProperty.call(b,X)))throw Error(`parent schema must have dependencies of ${G}: ${q.join(",")}`);if(Q.validateSchema){if(!Q.validateSchema(b[G])){let Y=`keyword "${G}" value is invalid at path "${W}": `+$.errorsText(Q.validateSchema.errors);if(w.validateSchema==="log")$.logger.error(Y);else throw Error(Y)}}}aq.validateKeywordUsage=DL});var GX=Z((WX)=>{Object.defineProperty(WX,"__esModule",{value:!0});WX.extendSubschemaMode=WX.extendSubschemaData=WX.getSubschema=void 0;var tb=y(),$X=g();function AL(b,{keyword:w,schemaProp:$,schema:W,schemaPath:Q,errSchemaPath:G,topSchemaRef:q}){if(w!==void 0&&W!==void 0)throw Error('both "keyword" and "schema" passed, only one allowed');if(w!==void 0){let X=b.schema[w];return $===void 0?{schema:X,schemaPath:tb._`${b.schemaPath}${(0,tb.getProperty)(w)}`,errSchemaPath:`${b.errSchemaPath}/${w}`}:{schema:X[$],schemaPath:tb._`${b.schemaPath}${(0,tb.getProperty)(w)}${(0,tb.getProperty)($)}`,errSchemaPath:`${b.errSchemaPath}/${w}/${(0,$X.escapeFragment)($)}`}}if(W!==void 0){if(Q===void 0||G===void 0||q===void 0)throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:W,schemaPath:Q,topSchemaRef:q,errSchemaPath:G}}throw Error('either "keyword" or "schema" must be passed')}WX.getSubschema=AL;function UL(b,w,{dataProp:$,dataPropType:W,data:Q,dataTypes:G,propertyName:q}){if(Q!==void 0&&$!==void 0)throw Error('both "data" and "dataProp" passed, only one allowed');let{gen:X}=w;if($!==void 0){let{errorPath:J,dataPathArr:D,opts:H}=w,O=X.let("data",tb._`${w.data}${(0,tb.getProperty)($)}`,!0);Y(O),b.errorPath=tb.str`${J}${(0,$X.getErrorPath)($,W,H.jsPropertySyntax)}`,b.parentDataProperty=tb._`${$}`,b.dataPathArr=[...D,b.parentDataProperty]}if(Q!==void 0){let J=Q instanceof tb.Name?Q:X.let("data",Q,!0);if(Y(J),q!==void 0)b.propertyName=q}if(G)b.dataTypes=G;function Y(J){b.data=J,b.dataLevel=w.dataLevel+1,b.dataTypes=[],w.definedProperties=new Set,b.parentData=w.data,b.dataNames=[...w.dataNames,J]}}WX.extendSubschemaData=UL;function LL(b,{jtdDiscriminator:w,jtdMetadata:$,compositeRule:W,createErrors:Q,allErrors:G}){if(W!==void 0)b.compositeRule=W;if(Q!==void 0)b.createErrors=Q;if(G!==void 0)b.allErrors=G;b.jtdDiscriminator=w,b.jtdMetadata=$}WX.extendSubschemaMode=LL});var T6=Z((OE,qX)=>{qX.exports=function b(w,$){if(w===$)return!0;if(w&&$&&typeof w=="object"&&typeof $=="object"){if(w.constructor!==$.constructor)return!1;var W,Q,G;if(Array.isArray(w)){if(W=w.length,W!=$.length)return!1;for(Q=W;Q--!==0;)if(!b(w[Q],$[Q]))return!1;return!0}if(w.constructor===RegExp)return w.source===$.source&&w.flags===$.flags;if(w.valueOf!==Object.prototype.valueOf)return w.valueOf()===$.valueOf();if(w.toString!==Object.prototype.toString)return w.toString()===$.toString();if(G=Object.keys(w),W=G.length,W!==Object.keys($).length)return!1;for(Q=W;Q--!==0;)if(!Object.prototype.hasOwnProperty.call($,G[Q]))return!1;for(Q=W;Q--!==0;){var q=G[Q];if(!b(w[q],$[q]))return!1}return!0}return w!==w&&$!==$}});var YX=Z((AE,XX)=>{var Ew=XX.exports=function(b,w,$){if(typeof w=="function")$=w,w={};$=w.cb||$;var W=typeof $=="function"?$:$.pre||function(){},Q=$.post||function(){};D$(w,W,Q,b,"",b)};Ew.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Ew.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Ew.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Ew.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function D$(b,w,$,W,Q,G,q,X,Y,J){if(W&&typeof W=="object"&&!Array.isArray(W)){w(W,Q,G,q,X,Y,J);for(var D in W){var H=W[D];if(Array.isArray(H)){if(D in Ew.arrayKeywords)for(var O=0;O<H.length;O++)D$(b,w,$,H[O],Q+"/"+D+"/"+O,G,Q,D,W,O)}else if(D in Ew.propsKeywords){if(H&&typeof H=="object")for(var A in H)D$(b,w,$,H[A],Q+"/"+D+"/"+FL(A),G,Q,D,W,A)}else if(D in Ew.keywords||b.allKeys&&!(D in Ew.skipKeywords))D$(b,w,$,H,Q+"/"+D,G,Q,D,W)}$(W,Q,G,q,X,Y,J)}}function FL(b){return b.replace(/~/g,"~0").replace(/\//g,"~1")}});var l1=Z((zX)=>{Object.defineProperty(zX,"__esModule",{value:!0});zX.getSchemaRefs=zX.resolveUrl=zX.normalizeId=zX._getFullPath=zX.getFullPath=zX.inlineRef=void 0;var KL=g(),ML=T6(),IL=YX(),_L=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function ZL(b,w=!0){if(typeof b=="boolean")return!0;if(w===!0)return!S6(b);if(!w)return!1;return JX(b)<=w}zX.inlineRef=ZL;var jL=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function S6(b){for(let w in b){if(jL.has(w))return!0;let $=b[w];if(Array.isArray($)&&$.some(S6))return!0;if(typeof $=="object"&&S6($))return!0}return!1}function JX(b){let w=0;for(let $ in b){if($==="$ref")return 1/0;if(w++,_L.has($))continue;if(typeof b[$]=="object")(0,KL.eachItem)(b[$],(W)=>w+=JX(W));if(w===1/0)return 1/0}return w}function DX(b,w="",$){if($!==!1)w=aw(w);let W=b.parse(w);return HX(b,W)}zX.getFullPath=DX;function HX(b,w){return b.serialize(w).split("#")[0]+"#"}zX._getFullPath=HX;var VL=/#\/?$/;function aw(b){return b?b.replace(VL,""):""}zX.normalizeId=aw;function NL(b,w,$){return $=aw($),b.resolve(w,$)}zX.resolveUrl=NL;var EL=/^[a-z_][-a-z0-9._]*$/i;function TL(b,w){if(typeof b=="boolean")return{};let{schemaId:$,uriResolver:W}=this.opts,Q=aw(b[$]||w),G={"":Q},q=DX(W,Q,!1),X={},Y=new Set;return IL(b,{allKeys:!0},(H,O,A,B)=>{if(B===void 0)return;let K=q+O,_=G[B];if(typeof H[$]=="string")_=I.call(this,H[$]);R.call(this,H.$anchor),R.call(this,H.$dynamicAnchor),G[O]=_;function I(T){let h=this.opts.uriResolver.resolve;if(T=aw(_?h(_,T):T),Y.has(T))throw D(T);Y.add(T);let v=this.refs[T];if(typeof v=="string")v=this.refs[v];if(typeof v=="object")J(H,v.schema,T);else if(T!==aw(K))if(T[0]==="#")J(H,X[T],T),X[T]=H;else this.refs[T]=K;return T}function R(T){if(typeof T=="string"){if(!EL.test(T))throw Error(`invalid anchor "${T}"`);I.call(this,`#${T}`)}}}),X;function J(H,O,A){if(O!==void 0&&!ML(H,O))throw D(A)}function D(H){return Error(`reference "${H}" resolves to more than one schema`)}}zX.getSchemaRefs=TL});var o1=Z((EX)=>{Object.defineProperty(EX,"__esModule",{value:!0});EX.getData=EX.KeywordCxt=EX.validateFunctionCode=void 0;var BX=Rq(),AX=m1(),v6=I6(),H$=m1(),uL=pq(),p1=wX(),R6=GX(),E=y(),C=qw(),xL=l1(),Xw=g(),g1=i1();function yL(b){if(MX(b)){if(IX(b),KX(b)){fL(b);return}}FX(b,()=>(0,BX.topBoolOrEmptySchema)(b))}EX.validateFunctionCode=yL;function FX({gen:b,validateName:w,schema:$,schemaEnv:W,opts:Q},G){if(Q.code.es5)b.func(w,E._`${C.default.data}, ${C.default.valCxt}`,W.$async,()=>{b.code(E._`"use strict"; ${UX($,Q)}`),cL(b,Q),b.code(G)});else b.func(w,E._`${C.default.data}, ${hL(Q)}`,W.$async,()=>b.code(UX($,Q)).code(G))}function hL(b){return E._`{${C.default.instancePath}="", ${C.default.parentData}, ${C.default.parentDataProperty}, ${C.default.rootData}=${C.default.data}${b.dynamicRef?E._`, ${C.default.dynamicAnchors}={}`:E.nil}}={}`}function cL(b,w){b.if(C.default.valCxt,()=>{if(b.var(C.default.instancePath,E._`${C.default.valCxt}.${C.default.instancePath}`),b.var(C.default.parentData,E._`${C.default.valCxt}.${C.default.parentData}`),b.var(C.default.parentDataProperty,E._`${C.default.valCxt}.${C.default.parentDataProperty}`),b.var(C.default.rootData,E._`${C.default.valCxt}.${C.default.rootData}`),w.dynamicRef)b.var(C.default.dynamicAnchors,E._`${C.default.valCxt}.${C.default.dynamicAnchors}`)},()=>{if(b.var(C.default.instancePath,E._`""`),b.var(C.default.parentData,E._`undefined`),b.var(C.default.parentDataProperty,E._`undefined`),b.var(C.default.rootData,C.default.data),w.dynamicRef)b.var(C.default.dynamicAnchors,E._`{}`)})}function fL(b){let{schema:w,opts:$,gen:W}=b;FX(b,()=>{if($.$comment&&w.$comment)ZX(b);if(gL(b),W.let(C.default.vErrors,null),W.let(C.default.errors,0),$.unevaluated)nL(b);_X(b),dL(b)});return}function nL(b){let{gen:w,validateName:$}=b;b.evaluated=w.const("evaluated",E._`${$}.evaluated`),w.if(E._`${b.evaluated}.dynamicProps`,()=>w.assign(E._`${b.evaluated}.props`,E._`undefined`)),w.if(E._`${b.evaluated}.dynamicItems`,()=>w.assign(E._`${b.evaluated}.items`,E._`undefined`))}function UX(b,w){let $=typeof b=="object"&&b[w.schemaId];return $&&(w.code.source||w.code.process)?E._`/*# sourceURL=${$} */`:E.nil}function iL(b,w){if(MX(b)){if(IX(b),KX(b)){mL(b,w);return}}(0,BX.boolOrEmptySchema)(b,w)}function KX({schema:b,self:w}){if(typeof b=="boolean")return!b;for(let $ in b)if(w.RULES.all[$])return!0;return!1}function MX(b){return typeof b.schema!="boolean"}function mL(b,w){let{schema:$,gen:W,opts:Q}=b;if(Q.$comment&&$.$comment)ZX(b);pL(b),oL(b);let G=W.const("_errs",C.default.errors);_X(b,G),W.var(w,E._`${G} === ${C.default.errors}`)}function IX(b){(0,Xw.checkUnknownRules)(b),lL(b)}function _X(b,w){if(b.opts.jtd)return LX(b,[],!1,w);let $=(0,AX.getSchemaTypes)(b.schema),W=(0,AX.coerceAndCheckDataType)(b,$);LX(b,$,!W,w)}function lL(b){let{schema:w,errSchemaPath:$,opts:W,self:Q}=b;if(w.$ref&&W.ignoreKeywordsWithRef&&(0,Xw.schemaHasRulesButRef)(w,Q.RULES))Q.logger.warn(`$ref: keywords ignored in schema at path "${$}"`)}function gL(b){let{schema:w,opts:$}=b;if(w.default!==void 0&&$.useDefaults&&$.strictSchema)(0,Xw.checkStrictMode)(b,"default is ignored in the schema root")}function pL(b){let w=b.schema[b.opts.schemaId];if(w)b.baseId=(0,xL.resolveUrl)(b.opts.uriResolver,b.baseId,w)}function oL(b){if(b.schema.$async&&!b.schemaEnv.$async)throw Error("async schema in sync schema")}function ZX({gen:b,schemaEnv:w,schema:$,errSchemaPath:W,opts:Q}){let G=$.$comment;if(Q.$comment===!0)b.code(E._`${C.default.self}.logger.log(${G})`);else if(typeof Q.$comment=="function"){let q=E.str`${W}/$comment`,X=b.scopeValue("root",{ref:w.root});b.code(E._`${C.default.self}.opts.$comment(${G}, ${q}, ${X}.schema)`)}}function dL(b){let{gen:w,schemaEnv:$,validateName:W,ValidationError:Q,opts:G}=b;if($.$async)w.if(E._`${C.default.errors} === 0`,()=>w.return(C.default.data),()=>w.throw(E._`new ${Q}(${C.default.vErrors})`));else{if(w.assign(E._`${W}.errors`,C.default.vErrors),G.unevaluated)tL(b);w.return(E._`${C.default.errors} === 0`)}}function tL({gen:b,evaluated:w,props:$,items:W}){if($ instanceof E.Name)b.assign(E._`${w}.props`,$);if(W instanceof E.Name)b.assign(E._`${w}.items`,W)}function LX(b,w,$,W){let{gen:Q,schema:G,data:q,allErrors:X,opts:Y,self:J}=b,{RULES:D}=J;if(G.$ref&&(Y.ignoreKeywordsWithRef||!(0,Xw.schemaHasRulesButRef)(G,D))){Q.block(()=>VX(b,"$ref",D.all.$ref.definition));return}if(!Y.jtd)rL(b,w);Q.block(()=>{for(let O of D.rules)H(O);H(D.post)});function H(O){if(!(0,v6.shouldUseGroup)(G,O))return;if(O.type){if(Q.if((0,H$.checkDataType)(O.type,q,Y.strictNumbers)),PX(b,O),w.length===1&&w[0]===O.type&&$)Q.else(),(0,H$.reportTypeError)(b);Q.endIf()}else PX(b,O);if(!X)Q.if(E._`${C.default.errors} === ${W||0}`)}}function PX(b,w){let{gen:$,schema:W,opts:{useDefaults:Q}}=b;if(Q)(0,uL.assignDefaults)(b,w.type);$.block(()=>{for(let G of w.rules)if((0,v6.shouldUseRule)(W,G))VX(b,G.keyword,G.definition,w.type)})}function rL(b,w){if(b.schemaEnv.meta||!b.opts.strictTypes)return;if(eL(b,w),!b.opts.allowUnionTypes)sL(b,w);aL(b,b.dataTypes)}function eL(b,w){if(!w.length)return;if(!b.dataTypes.length){b.dataTypes=w;return}w.forEach(($)=>{if(!jX(b.dataTypes,$))k6(b,`type "${$}" not allowed by context "${b.dataTypes.join(",")}"`)}),wP(b,w)}function sL(b,w){if(w.length>1&&!(w.length===2&&w.includes("null")))k6(b,"use allowUnionTypes to allow union type keyword")}function aL(b,w){let $=b.self.RULES.all;for(let W in $){let Q=$[W];if(typeof Q=="object"&&(0,v6.shouldUseRule)(b.schema,Q)){let{type:G}=Q.definition;if(G.length&&!G.some((q)=>bP(w,q)))k6(b,`missing type "${G.join(",")}" for keyword "${W}"`)}}}function bP(b,w){return b.includes(w)||w==="number"&&b.includes("integer")}function jX(b,w){return b.includes(w)||w==="integer"&&b.includes("number")}function wP(b,w){let $=[];for(let W of b.dataTypes)if(jX(w,W))$.push(W);else if(w.includes("integer")&&W==="number")$.push("integer");b.dataTypes=$}function k6(b,w){let $=b.schemaEnv.baseId+b.errSchemaPath;w+=` at "${$}" (strictTypes)`,(0,Xw.checkStrictMode)(b,w,b.opts.strictTypes)}class C6{constructor(b,w,$){if((0,p1.validateKeywordUsage)(b,w,$),this.gen=b.gen,this.allErrors=b.allErrors,this.keyword=$,this.data=b.data,this.schema=b.schema[$],this.$data=w.$data&&b.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Xw.schemaRefOrVal)(b,this.schema,$,this.$data),this.schemaType=w.schemaType,this.parentSchema=b.schema,this.params={},this.it=b,this.def=w,this.$data)this.schemaCode=b.gen.const("vSchema",NX(this.$data,b));else if(this.schemaCode=this.schemaValue,!(0,p1.validSchemaType)(this.schema,w.schemaType,w.allowUndefined))throw Error(`${$} value must be ${JSON.stringify(w.schemaType)}`);if("code"in w?w.trackErrors:w.errors!==!1)this.errsCount=b.gen.const("_errs",C.default.errors)}result(b,w,$){this.failResult((0,E.not)(b),w,$)}failResult(b,w,$){if(this.gen.if(b),$)$();else this.error();if(w){if(this.gen.else(),w(),this.allErrors)this.gen.endIf()}else if(this.allErrors)this.gen.endIf();else this.gen.else()}pass(b,w){this.failResult((0,E.not)(b),void 0,w)}fail(b){if(b===void 0){if(this.error(),!this.allErrors)this.gen.if(!1);return}if(this.gen.if(b),this.error(),this.allErrors)this.gen.endIf();else this.gen.else()}fail$data(b){if(!this.$data)return this.fail(b);let{schemaCode:w}=this;this.fail(E._`${w} !== undefined && (${(0,E.or)(this.invalid$data(),b)})`)}error(b,w,$){if(w){this.setParams(w),this._error(b,$),this.setParams({});return}this._error(b,$)}_error(b,w){(b?g1.reportExtraError:g1.reportError)(this,this.def.error,w)}$dataError(){(0,g1.reportError)(this,this.def.$dataError||g1.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error('add "trackErrors" to keyword definition');(0,g1.resetErrorsCount)(this.gen,this.errsCount)}ok(b){if(!this.allErrors)this.gen.if(b)}setParams(b,w){if(w)Object.assign(this.params,b);else this.params=b}block$data(b,w,$=E.nil){this.gen.block(()=>{this.check$data(b,$),w()})}check$data(b=E.nil,w=E.nil){if(!this.$data)return;let{gen:$,schemaCode:W,schemaType:Q,def:G}=this;if($.if((0,E.or)(E._`${W} === undefined`,w)),b!==E.nil)$.assign(b,!0);if(Q.length||G.validateSchema){if($.elseIf(this.invalid$data()),this.$dataError(),b!==E.nil)$.assign(b,!1)}$.else()}invalid$data(){let{gen:b,schemaCode:w,schemaType:$,def:W,it:Q}=this;return(0,E.or)(G(),q());function G(){if($.length){if(!(w instanceof E.Name))throw Error("ajv implementation error");let X=Array.isArray($)?$:[$];return E._`${(0,H$.checkDataTypes)(X,w,Q.opts.strictNumbers,H$.DataType.Wrong)}`}return E.nil}function q(){if(W.validateSchema){let X=b.scopeValue("validate$data",{ref:W.validateSchema});return E._`!${X}(${w})`}return E.nil}}subschema(b,w){let $=(0,R6.getSubschema)(this.it,b);(0,R6.extendSubschemaData)($,this.it,b),(0,R6.extendSubschemaMode)($,b);let W={...this.it,...$,items:void 0,props:void 0};return iL(W,w),W}mergeEvaluated(b,w){let{it:$,gen:W}=this;if(!$.opts.unevaluated)return;if($.props!==!0&&b.props!==void 0)$.props=Xw.mergeEvaluated.props(W,b.props,$.props,w);if($.items!==!0&&b.items!==void 0)$.items=Xw.mergeEvaluated.items(W,b.items,$.items,w)}mergeValidEvaluated(b,w){let{it:$,gen:W}=this;if($.opts.unevaluated&&($.props!==!0||$.items!==!0))return W.if(w,()=>this.mergeEvaluated(b,E.Name)),!0}}EX.KeywordCxt=C6;function VX(b,w,$,W){let Q=new C6(b,$,w);if("code"in $)$.code(Q,W);else if(Q.$data&&$.validate)(0,p1.funcKeywordCode)(Q,$);else if("macro"in $)(0,p1.macroKeywordCode)(Q,$);else if($.compile||$.validate)(0,p1.funcKeywordCode)(Q,$)}var $P=/^\/(?:[^~]|~0|~1)*$/,WP=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function NX(b,{dataLevel:w,dataNames:$,dataPathArr:W}){let Q,G;if(b==="")return C.default.rootData;if(b[0]==="/"){if(!$P.test(b))throw Error(`Invalid JSON-pointer: ${b}`);Q=b,G=C.default.rootData}else{let J=WP.exec(b);if(!J)throw Error(`Invalid JSON-pointer: ${b}`);let D=+J[1];if(Q=J[2],Q==="#"){if(D>=w)throw Error(Y("property/index",D));return W[w-D]}if(D>w)throw Error(Y("data",D));if(G=$[w-D],!Q)return G}let q=G,X=Q.split("/");for(let J of X)if(J)G=E._`${G}${(0,E.getProperty)((0,Xw.unescapeJsonPointer)(J))}`,q=E._`${q} && ${G}`;return q;function Y(J,D){return`Cannot access ${J} ${D} levels up, current level is ${w}`}}EX.getData=NX});var z$=Z((RX)=>{Object.defineProperty(RX,"__esModule",{value:!0});class SX extends Error{constructor(b){super("validation failed");this.errors=b,this.ajv=this.validation=!0}}RX.default=SX});var d1=Z((kX)=>{Object.defineProperty(kX,"__esModule",{value:!0});var u6=l1();class vX extends Error{constructor(b,w,$,W){super(W||`can't resolve reference ${$} from id ${w}`);this.missingRef=(0,u6.resolveUrl)(b,w,$),this.missingSchema=(0,u6.normalizeId)((0,u6.getFullPath)(b,this.missingRef))}}kX.default=vX});var A$=Z((xX)=>{Object.defineProperty(xX,"__esModule",{value:!0});xX.resolveSchema=xX.getCompilingSchema=xX.resolveRef=xX.compileSchema=xX.SchemaEnv=void 0;var nb=y(),YP=z$(),yw=qw(),ib=l1(),CX=g(),JP=o1();class t1{constructor(b){var w;this.refs={},this.dynamicAnchors={};let $;if(typeof b.schema=="object")$=b.schema;this.schema=b.schema,this.schemaId=b.schemaId,this.root=b.root||this,this.baseId=(w=b.baseId)!==null&&w!==void 0?w:(0,ib.normalizeId)($===null||$===void 0?void 0:$[b.schemaId||"$id"]),this.schemaPath=b.schemaPath,this.localRefs=b.localRefs,this.meta=b.meta,this.$async=$===null||$===void 0?void 0:$.$async,this.refs={}}}xX.SchemaEnv=t1;function y6(b){let w=uX.call(this,b);if(w)return w;let $=(0,ib.getFullPath)(this.opts.uriResolver,b.root.baseId),{es5:W,lines:Q}=this.opts.code,{ownProperties:G}=this.opts,q=new nb.CodeGen(this.scope,{es5:W,lines:Q,ownProperties:G}),X;if(b.$async)X=q.scopeValue("Error",{ref:YP.default,code:nb._`require("ajv/dist/runtime/validation_error").default`});let Y=q.scopeName("validate");b.validateName=Y;let J={gen:q,allErrors:this.opts.allErrors,data:yw.default.data,parentData:yw.default.parentData,parentDataProperty:yw.default.parentDataProperty,dataNames:[yw.default.data],dataPathArr:[nb.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:q.scopeValue("schema",this.opts.code.source===!0?{ref:b.schema,code:(0,nb.stringify)(b.schema)}:{ref:b.schema}),validateName:Y,ValidationError:X,schema:b.schema,schemaEnv:b,rootId:$,baseId:b.baseId||$,schemaPath:nb.nil,errSchemaPath:b.schemaPath||(this.opts.jtd?"":"#"),errorPath:nb._`""`,opts:this.opts,self:this},D;try{this._compilations.add(b),(0,JP.validateFunctionCode)(J),q.optimize(this.opts.code.optimize);let H=q.toString();if(D=`${q.scopeRefs(yw.default.scope)}return ${H}`,this.opts.code.process)D=this.opts.code.process(D,b);let A=Function(`${yw.default.self}`,`${yw.default.scope}`,D)(this,this.scope.get());if(this.scope.value(Y,{ref:A}),A.errors=null,A.schema=b.schema,A.schemaEnv=b,b.$async)A.$async=!0;if(this.opts.code.source===!0)A.source={validateName:Y,validateCode:H,scopeValues:q._values};if(this.opts.unevaluated){let{props:B,items:K}=J;if(A.evaluated={props:B instanceof nb.Name?void 0:B,items:K instanceof nb.Name?void 0:K,dynamicProps:B instanceof nb.Name,dynamicItems:K instanceof nb.Name},A.source)A.source.evaluated=(0,nb.stringify)(A.evaluated)}return b.validate=A,b}catch(H){if(delete b.validate,delete b.validateName,D)this.logger.error("Error compiling schema, function code:",D);throw H}finally{this._compilations.delete(b)}}xX.compileSchema=y6;function DP(b,w,$){var W;$=(0,ib.resolveUrl)(this.opts.uriResolver,w,$);let Q=b.refs[$];if(Q)return Q;let G=OP.call(this,b,$);if(G===void 0){let q=(W=b.localRefs)===null||W===void 0?void 0:W[$],{schemaId:X}=this.opts;if(q)G=new t1({schema:q,schemaId:X,root:b,baseId:w})}if(G===void 0)return;return b.refs[$]=HP.call(this,G)}xX.resolveRef=DP;function HP(b){if((0,ib.inlineRef)(b.schema,this.opts.inlineRefs))return b.schema;return b.validate?b:y6.call(this,b)}function uX(b){for(let w of this._compilations)if(zP(w,b))return w}xX.getCompilingSchema=uX;function zP(b,w){return b.schema===w.schema&&b.root===w.root&&b.baseId===w.baseId}function OP(b,w){let $;while(typeof($=this.refs[w])=="string")w=$;return $||this.schemas[w]||O$.call(this,b,w)}function O$(b,w){let $=this.opts.uriResolver.parse(w),W=(0,ib._getFullPath)(this.opts.uriResolver,$),Q=(0,ib.getFullPath)(this.opts.uriResolver,b.baseId,void 0);if(Object.keys(b.schema).length>0&&W===Q)return x6.call(this,$,b);let G=(0,ib.normalizeId)(W),q=this.refs[G]||this.schemas[G];if(typeof q=="string"){let X=O$.call(this,b,q);if(typeof(X===null||X===void 0?void 0:X.schema)!=="object")return;return x6.call(this,$,X)}if(typeof(q===null||q===void 0?void 0:q.schema)!=="object")return;if(!q.validate)y6.call(this,q);if(G===(0,ib.normalizeId)(w)){let{schema:X}=q,{schemaId:Y}=this.opts,J=X[Y];if(J)Q=(0,ib.resolveUrl)(this.opts.uriResolver,Q,J);return new t1({schema:X,schemaId:Y,root:b,baseId:Q})}return x6.call(this,$,q)}xX.resolveSchema=O$;var AP=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function x6(b,{baseId:w,schema:$,root:W}){var Q;if(((Q=b.fragment)===null||Q===void 0?void 0:Q[0])!=="/")return;for(let X of b.fragment.slice(1).split("/")){if(typeof $==="boolean")return;let Y=$[(0,CX.unescapeFragment)(X)];if(Y===void 0)return;$=Y;let J=typeof $==="object"&&$[this.opts.schemaId];if(!AP.has(X)&&J)w=(0,ib.resolveUrl)(this.opts.uriResolver,w,J)}let G;if(typeof $!="boolean"&&$.$ref&&!(0,CX.schemaHasRulesButRef)($,this.RULES)){let X=(0,ib.resolveUrl)(this.opts.uriResolver,w,$.$ref);G=O$.call(this,W,X)}let{schemaId:q}=this.opts;if(G=G||new t1({schema:$,schemaId:q,root:W,baseId:w}),G.schema!==G.root.schema)return G;return}});var hX=Z((KE,FP)=>{FP.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var c6=Z((ME,iX)=>{var KP=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),fX=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 h6(b){let w="",$=0,W=0;for(W=0;W<b.length;W++){if($=b[W].charCodeAt(0),$===48)continue;if(!($>=48&&$<=57||$>=65&&$<=70||$>=97&&$<=102))return"";w+=b[W];break}for(W+=1;W<b.length;W++){if($=b[W].charCodeAt(0),!($>=48&&$<=57||$>=65&&$<=70||$>=97&&$<=102))return"";w+=b[W]}return w}var MP=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function cX(b){return b.length=0,!0}function IP(b,w,$){if(b.length){let W=h6(b);if(W!=="")w.push(W);else return $.error=!0,!1;b.length=0}return!0}function _P(b){let w=0,$={error:!1,address:"",zone:""},W=[],Q=[],G=!1,q=!1,X=IP;for(let Y=0;Y<b.length;Y++){let J=b[Y];if(J==="["||J==="]")continue;if(J===":"){if(G===!0)q=!0;if(!X(Q,W,$))break;if(++w>7){$.error=!0;break}if(Y>0&&b[Y-1]===":")G=!0;W.push(":");continue}else if(J==="%"){if(!X(Q,W,$))break;X=cX}else{Q.push(J);continue}}if(Q.length)if(X===cX)$.zone=Q.join("");else if(q)W.push(Q.join(""));else W.push(h6(Q));return $.address=W.join(""),$}function nX(b){if(ZP(b,":")<2)return{host:b,isIPV6:!1};let w=_P(b);if(!w.error){let{address:$,address:W}=w;if(w.zone)$+="%"+w.zone,W+="%25"+w.zone;return{host:$,isIPV6:!0,escapedHost:W}}else return{host:b,isIPV6:!1}}function ZP(b,w){let $=0;for(let W=0;W<b.length;W++)if(b[W]===w)$++;return $}function jP(b){let w=b,$=[],W=-1,Q=0;while(Q=w.length){if(Q===1)if(w===".")break;else if(w==="/"){$.push("/");break}else{$.push(w);break}else if(Q===2){if(w[0]==="."){if(w[1]===".")break;else if(w[1]==="/"){w=w.slice(2);continue}}else if(w[0]==="/"){if(w[1]==="."||w[1]==="/"){$.push("/");break}}}else if(Q===3){if(w==="/.."){if($.length!==0)$.pop();$.push("/");break}}if(w[0]==="."){if(w[1]==="."){if(w[2]==="/"){w=w.slice(3);continue}}else if(w[1]==="/"){w=w.slice(2);continue}}else if(w[0]==="/"){if(w[1]==="."){if(w[2]==="/"){w=w.slice(2);continue}else if(w[2]==="."){if(w[3]==="/"){if(w=w.slice(3),$.length!==0)$.pop();continue}}}}if((W=w.indexOf("/",1))===-1){$.push(w);break}else $.push(w.slice(0,W)),w=w.slice(W)}return $.join("")}function VP(b,w){let $=w!==!0?escape:unescape;if(b.scheme!==void 0)b.scheme=$(b.scheme);if(b.userinfo!==void 0)b.userinfo=$(b.userinfo);if(b.host!==void 0)b.host=$(b.host);if(b.path!==void 0)b.path=$(b.path);if(b.query!==void 0)b.query=$(b.query);if(b.fragment!==void 0)b.fragment=$(b.fragment);return b}function NP(b){let w=[];if(b.userinfo!==void 0)w.push(b.userinfo),w.push("@");if(b.host!==void 0){let $=unescape(b.host);if(!fX($)){let W=nX($);if(W.isIPV6===!0)$=`[${W.escapedHost}]`;else $=b.host}w.push($)}if(typeof b.port==="number"||typeof b.port==="string")w.push(":"),w.push(String(b.port));return w.length?w.join(""):void 0}iX.exports={nonSimpleDomain:MP,recomposeAuthority:NP,normalizeComponentEncoding:VP,removeDotSegments:jP,isIPv4:fX,isUUID:KP,normalizeIPv6:nX,stringArrayToHexStripped:h6}});var oX=Z((IE,pX)=>{var{isUUID:EP}=c6(),TP=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,SP=["http","https","ws","wss","urn","urn:uuid"];function RP(b){return SP.indexOf(b)!==-1}function f6(b){if(b.secure===!0)return!0;else if(b.secure===!1)return!1;else if(b.scheme)return b.scheme.length===3&&(b.scheme[0]==="w"||b.scheme[0]==="W")&&(b.scheme[1]==="s"||b.scheme[1]==="S")&&(b.scheme[2]==="s"||b.scheme[2]==="S");else return!1}function mX(b){if(!b.host)b.error=b.error||"HTTP URIs must have a host.";return b}function lX(b){let w=String(b.scheme).toLowerCase()==="https";if(b.port===(w?443:80)||b.port==="")b.port=void 0;if(!b.path)b.path="/";return b}function vP(b){return b.secure=f6(b),b.resourceName=(b.path||"/")+(b.query?"?"+b.query:""),b.path=void 0,b.query=void 0,b}function kP(b){if(b.port===(f6(b)?443:80)||b.port==="")b.port=void 0;if(typeof b.secure==="boolean")b.scheme=b.secure?"wss":"ws",b.secure=void 0;if(b.resourceName){let[w,$]=b.resourceName.split("?");b.path=w&&w!=="/"?w:void 0,b.query=$,b.resourceName=void 0}return b.fragment=void 0,b}function CP(b,w){if(!b.path)return b.error="URN can not be parsed",b;let $=b.path.match(TP);if($){let W=w.scheme||b.scheme||"urn";b.nid=$[1].toLowerCase(),b.nss=$[2];let Q=`${W}:${w.nid||b.nid}`,G=n6(Q);if(b.path=void 0,G)b=G.parse(b,w)}else b.error=b.error||"URN can not be parsed.";return b}function uP(b,w){if(b.nid===void 0)throw Error("URN without nid cannot be serialized");let $=w.scheme||b.scheme||"urn",W=b.nid.toLowerCase(),Q=`${$}:${w.nid||W}`,G=n6(Q);if(G)b=G.serialize(b,w);let q=b,X=b.nss;return q.path=`${W||w.nid}:${X}`,w.skipEscape=!0,q}function xP(b,w){let $=b;if($.uuid=$.nss,$.nss=void 0,!w.tolerant&&(!$.uuid||!EP($.uuid)))$.error=$.error||"UUID is not valid.";return $}function yP(b){let w=b;return w.nss=(b.uuid||"").toLowerCase(),w}var gX={scheme:"http",domainHost:!0,parse:mX,serialize:lX},hP={scheme:"https",domainHost:gX.domainHost,parse:mX,serialize:lX},U$={scheme:"ws",domainHost:!0,parse:vP,serialize:kP},cP={scheme:"wss",domainHost:U$.domainHost,parse:U$.parse,serialize:U$.serialize},fP={scheme:"urn",parse:CP,serialize:uP,skipNormalize:!0},nP={scheme:"urn:uuid",parse:xP,serialize:yP,skipNormalize:!0},L$={http:gX,https:hP,ws:U$,wss:cP,urn:fP,"urn:uuid":nP};Object.setPrototypeOf(L$,null);function n6(b){return b&&(L$[b]||L$[b.toLowerCase()])||void 0}pX.exports={wsIsSecure:f6,SCHEMES:L$,isValidSchemeName:RP,getSchemeHandler:n6}});var rX=Z((_E,B$)=>{var{normalizeIPv6:iP,removeDotSegments:r1,recomposeAuthority:mP,normalizeComponentEncoding:P$,isIPv4:lP,nonSimpleDomain:gP}=c6(),{SCHEMES:pP,getSchemeHandler:dX}=oX();function oP(b,w){if(typeof b==="string")b=rb(Yw(b,w),w);else if(typeof b==="object")b=Yw(rb(b,w),w);return b}function dP(b,w,$){let W=$?Object.assign({scheme:"null"},$):{scheme:"null"},Q=tX(Yw(b,W),Yw(w,W),W,!0);return W.skipEscape=!0,rb(Q,W)}function tX(b,w,$,W){let Q={};if(!W)b=Yw(rb(b,$),$),w=Yw(rb(w,$),$);if($=$||{},!$.tolerant&&w.scheme)Q.scheme=w.scheme,Q.userinfo=w.userinfo,Q.host=w.host,Q.port=w.port,Q.path=r1(w.path||""),Q.query=w.query;else{if(w.userinfo!==void 0||w.host!==void 0||w.port!==void 0)Q.userinfo=w.userinfo,Q.host=w.host,Q.port=w.port,Q.path=r1(w.path||""),Q.query=w.query;else{if(!w.path)if(Q.path=b.path,w.query!==void 0)Q.query=w.query;else Q.query=b.query;else{if(w.path[0]==="/")Q.path=r1(w.path);else{if((b.userinfo!==void 0||b.host!==void 0||b.port!==void 0)&&!b.path)Q.path="/"+w.path;else if(!b.path)Q.path=w.path;else Q.path=b.path.slice(0,b.path.lastIndexOf("/")+1)+w.path;Q.path=r1(Q.path)}Q.query=w.query}Q.userinfo=b.userinfo,Q.host=b.host,Q.port=b.port}Q.scheme=b.scheme}return Q.fragment=w.fragment,Q}function tP(b,w,$){if(typeof b==="string")b=unescape(b),b=rb(P$(Yw(b,$),!0),{...$,skipEscape:!0});else if(typeof b==="object")b=rb(P$(b,!0),{...$,skipEscape:!0});if(typeof w==="string")w=unescape(w),w=rb(P$(Yw(w,$),!0),{...$,skipEscape:!0});else if(typeof w==="object")w=rb(P$(w,!0),{...$,skipEscape:!0});return b.toLowerCase()===w.toLowerCase()}function rb(b,w){let $={host:b.host,scheme:b.scheme,userinfo:b.userinfo,port:b.port,path:b.path,query:b.query,nid:b.nid,nss:b.nss,uuid:b.uuid,fragment:b.fragment,reference:b.reference,resourceName:b.resourceName,secure:b.secure,error:""},W=Object.assign({},w),Q=[],G=dX(W.scheme||$.scheme);if(G&&G.serialize)G.serialize($,W);if($.path!==void 0)if(!W.skipEscape){if($.path=escape($.path),$.scheme!==void 0)$.path=$.path.split("%3A").join(":")}else $.path=unescape($.path);if(W.reference!=="suffix"&&$.scheme)Q.push($.scheme,":");let q=mP($);if(q!==void 0){if(W.reference!=="suffix")Q.push("//");if(Q.push(q),$.path&&$.path[0]!=="/")Q.push("/")}if($.path!==void 0){let X=$.path;if(!W.absolutePath&&(!G||!G.absolutePath))X=r1(X);if(q===void 0&&X[0]==="/"&&X[1]==="/")X="/%2F"+X.slice(2);Q.push(X)}if($.query!==void 0)Q.push("?",$.query);if($.fragment!==void 0)Q.push("#",$.fragment);return Q.join("")}var rP=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function Yw(b,w){let $=Object.assign({},w),W={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},Q=!1;if($.reference==="suffix")if($.scheme)b=$.scheme+":"+b;else b="//"+b;let G=b.match(rP);if(G){if(W.scheme=G[1],W.userinfo=G[3],W.host=G[4],W.port=parseInt(G[5],10),W.path=G[6]||"",W.query=G[7],W.fragment=G[8],isNaN(W.port))W.port=G[5];if(W.host)if(lP(W.host)===!1){let Y=iP(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 q=dX($.scheme||W.scheme);if(!$.unicodeSupport&&(!q||!q.unicodeSupport)){if(W.host&&($.domainHost||q&&q.domainHost)&&Q===!1&&gP(W.host))try{W.host=URL.domainToASCII(W.host.toLowerCase())}catch(X){W.error=W.error||"Host's domain name can not be converted to ASCII: "+X}}if(!q||q&&!q.skipNormalize){if(b.indexOf("%")!==-1){if(W.scheme!==void 0)W.scheme=unescape(W.scheme);if(W.host!==void 0)W.host=unescape(W.host)}if(W.path)W.path=escape(unescape(W.path));if(W.fragment)W.fragment=encodeURI(decodeURIComponent(W.fragment))}if(q&&q.parse)q.parse(W,$)}else W.error=W.error||"URI can not be parsed.";return W}var i6={SCHEMES:pP,normalize:oP,resolve:dP,resolveComponent:tX,equal:tP,serialize:rb,parse:Yw};B$.exports=i6;B$.exports.default=i6;B$.exports.fastUri=i6});var aX=Z((sX)=>{Object.defineProperty(sX,"__esModule",{value:!0});var eX=rX();eX.code='require("ajv/dist/runtime/uri").default';sX.default=eX});var XY=Z((Jw)=>{Object.defineProperty(Jw,"__esModule",{value:!0});Jw.CodeGen=Jw.Name=Jw.nil=Jw.stringify=Jw.str=Jw._=Jw.KeywordCxt=void 0;var sP=o1();Object.defineProperty(Jw,"KeywordCxt",{enumerable:!0,get:function(){return sP.KeywordCxt}});var b1=y();Object.defineProperty(Jw,"_",{enumerable:!0,get:function(){return b1._}});Object.defineProperty(Jw,"str",{enumerable:!0,get:function(){return b1.str}});Object.defineProperty(Jw,"stringify",{enumerable:!0,get:function(){return b1.stringify}});Object.defineProperty(Jw,"nil",{enumerable:!0,get:function(){return b1.nil}});Object.defineProperty(Jw,"Name",{enumerable:!0,get:function(){return b1.Name}});Object.defineProperty(Jw,"CodeGen",{enumerable:!0,get:function(){return b1.CodeGen}});var aP=z$(),QY=d1(),b3=M6(),e1=A$(),w3=y(),s1=l1(),F$=m1(),l6=g(),bY=hX(),$3=aX(),GY=(b,w)=>new RegExp(b,w);GY.code="new RegExp";var W3=["removeAdditional","useDefaults","coerceTypes"],Q3=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),G3={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."},q3={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},wY=200;function X3(b){var w,$,W,Q,G,q,X,Y,J,D,H,O,A,B,K,_,I,R,T,h,v,ob,bw,e$,s$;let z1=b.strict,a$=(w=b.code)===null||w===void 0?void 0:w.optimize,mW=a$===!0||a$===void 0?1:a$||0,lW=(W=($=b.code)===null||$===void 0?void 0:$.regExp)!==null&&W!==void 0?W:GY,Gz=(Q=b.uriResolver)!==null&&Q!==void 0?Q:$3.default;return{strictSchema:(q=(G=b.strictSchema)!==null&&G!==void 0?G:z1)!==null&&q!==void 0?q:!0,strictNumbers:(Y=(X=b.strictNumbers)!==null&&X!==void 0?X:z1)!==null&&Y!==void 0?Y:!0,strictTypes:(D=(J=b.strictTypes)!==null&&J!==void 0?J:z1)!==null&&D!==void 0?D:"log",strictTuples:(O=(H=b.strictTuples)!==null&&H!==void 0?H:z1)!==null&&O!==void 0?O:"log",strictRequired:(B=(A=b.strictRequired)!==null&&A!==void 0?A:z1)!==null&&B!==void 0?B:!1,code:b.code?{...b.code,optimize:mW,regExp:lW}:{optimize:mW,regExp:lW},loopRequired:(K=b.loopRequired)!==null&&K!==void 0?K:wY,loopEnum:(_=b.loopEnum)!==null&&_!==void 0?_:wY,meta:(I=b.meta)!==null&&I!==void 0?I:!0,messages:(R=b.messages)!==null&&R!==void 0?R:!0,inlineRefs:(T=b.inlineRefs)!==null&&T!==void 0?T:!0,schemaId:(h=b.schemaId)!==null&&h!==void 0?h:"$id",addUsedSchema:(v=b.addUsedSchema)!==null&&v!==void 0?v:!0,validateSchema:(ob=b.validateSchema)!==null&&ob!==void 0?ob:!0,validateFormats:(bw=b.validateFormats)!==null&&bw!==void 0?bw:!0,unicodeRegExp:(e$=b.unicodeRegExp)!==null&&e$!==void 0?e$:!0,int32range:(s$=b.int32range)!==null&&s$!==void 0?s$:!0,uriResolver:Gz}}class K${constructor(b={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,b=this.opts={...b,...X3(b)};let{es5:w,lines:$}=this.opts.code;this.scope=new w3.ValueScope({scope:{},prefixes:Q3,es5:w,lines:$}),this.logger=O3(b.logger);let W=b.validateFormats;if(b.validateFormats=!1,this.RULES=(0,b3.getRules)(),$Y.call(this,G3,b,"NOT SUPPORTED"),$Y.call(this,q3,b,"DEPRECATED","warn"),this._metaOpts=H3.call(this),b.formats)J3.call(this);if(this._addVocabularies(),this._addDefaultMetaSchema(),b.keywords)D3.call(this,b.keywords);if(typeof b.meta=="object")this.addMetaSchema(b.meta);Y3.call(this),b.validateFormats=W}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:b,meta:w,schemaId:$}=this.opts,W=bY;if($==="id")W={...bY},W.id=W.$id,delete W.$id;if(w&&b)this.addMetaSchema(W,W[$],!1)}defaultMeta(){let{meta:b,schemaId:w}=this.opts;return this.opts.defaultMeta=typeof b=="object"?b[w]||b:void 0}validate(b,w){let $;if(typeof b=="string"){if($=this.getSchema(b),!$)throw Error(`no schema with key or ref "${b}"`)}else $=this.compile(b);let W=$(w);if(!("$async"in $))this.errors=$.errors;return W}compile(b,w){let $=this._addSchema(b,w);return $.validate||this._compileSchemaEnv($)}compileAsync(b,w){if(typeof this.opts.loadSchema!="function")throw Error("options.loadSchema should be a function");let{loadSchema:$}=this.opts;return W.call(this,b,w);async function W(J,D){await Q.call(this,J.$schema);let H=this._addSchema(J,D);return H.validate||G.call(this,H)}async function Q(J){if(J&&!this.getSchema(J))await W.call(this,{$ref:J},!0)}async function G(J){try{return this._compileSchemaEnv(J)}catch(D){if(!(D instanceof QY.default))throw D;return q.call(this,D),await X.call(this,D.missingSchema),G.call(this,J)}}function q({missingSchema:J,missingRef:D}){if(this.refs[J])throw Error(`AnySchema ${J} is loaded but ${D} cannot be resolved`)}async function X(J){let D=await Y.call(this,J);if(!this.refs[J])await Q.call(this,D.$schema);if(!this.refs[J])this.addSchema(D,J,w)}async function Y(J){let D=this._loading[J];if(D)return D;try{return await(this._loading[J]=$(J))}finally{delete this._loading[J]}}}addSchema(b,w,$,W=this.opts.validateSchema){if(Array.isArray(b)){for(let G of b)this.addSchema(G,void 0,$,W);return this}let Q;if(typeof b==="object"){let{schemaId:G}=this.opts;if(Q=b[G],Q!==void 0&&typeof Q!="string")throw Error(`schema ${G} must be string`)}return w=(0,s1.normalizeId)(w||Q),this._checkUnique(w),this.schemas[w]=this._addSchema(b,$,w,W,!0),this}addMetaSchema(b,w,$=this.opts.validateSchema){return this.addSchema(b,w,!0,$),this}validateSchema(b,w){if(typeof b=="boolean")return!0;let $;if($=b.$schema,$!==void 0&&typeof $!="string")throw Error("$schema must be a string");if($=$||this.opts.defaultMeta||this.defaultMeta(),!$)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let W=this.validate($,b);if(!W&&w){let Q="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(Q);else throw Error(Q)}return W}getSchema(b){let w;while(typeof(w=WY.call(this,b))=="string")b=w;if(w===void 0){let{schemaId:$}=this.opts,W=new e1.SchemaEnv({schema:{},schemaId:$});if(w=e1.resolveSchema.call(this,W,b),!w)return;this.refs[b]=w}return w.validate||this._compileSchemaEnv(w)}removeSchema(b){if(b instanceof RegExp)return this._removeAllSchemas(this.schemas,b),this._removeAllSchemas(this.refs,b),this;switch(typeof b){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let w=WY.call(this,b);if(typeof w=="object")this._cache.delete(w.schema);return delete this.schemas[b],delete this.refs[b],this}case"object":{let w=b;this._cache.delete(w);let $=b[this.opts.schemaId];if($)$=(0,s1.normalizeId)($),delete this.schemas[$],delete this.refs[$];return this}default:throw Error("ajv.removeSchema: invalid parameter")}}addVocabulary(b){for(let w of b)this.addKeyword(w);return this}addKeyword(b,w){let $;if(typeof b=="string"){if($=b,typeof w=="object")this.logger.warn("these parameters are deprecated, see docs for addKeyword"),w.keyword=$}else if(typeof b=="object"&&w===void 0){if(w=b,$=w.keyword,Array.isArray($)&&!$.length)throw Error("addKeywords: keyword must be string or non-empty array")}else throw Error("invalid addKeywords parameters");if(U3.call(this,$,w),!w)return(0,l6.eachItem)($,(Q)=>m6.call(this,Q)),this;P3.call(this,w);let W={...w,type:(0,F$.getJSONTypes)(w.type),schemaType:(0,F$.getJSONTypes)(w.schemaType)};return(0,l6.eachItem)($,W.type.length===0?(Q)=>m6.call(this,Q,W):(Q)=>W.type.forEach((G)=>m6.call(this,Q,W,G))),this}getKeyword(b){let w=this.RULES.all[b];return typeof w=="object"?w.definition:!!w}removeKeyword(b){let{RULES:w}=this;delete w.keywords[b],delete w.all[b];for(let $ of w.rules){let W=$.rules.findIndex((Q)=>Q.keyword===b);if(W>=0)$.rules.splice(W,1)}return this}addFormat(b,w){if(typeof w=="string")w=new RegExp(w);return this.formats[b]=w,this}errorsText(b=this.errors,{separator:w=", ",dataVar:$="data"}={}){if(!b||b.length===0)return"No errors";return b.map((W)=>`${$}${W.instancePath} ${W.message}`).reduce((W,Q)=>W+w+Q)}$dataMetaSchema(b,w){let $=this.RULES.all;b=JSON.parse(JSON.stringify(b));for(let W of w){let Q=W.split("/").slice(1),G=b;for(let q of Q)G=G[q];for(let q in $){let X=$[q];if(typeof X!="object")continue;let{$data:Y}=X.definition,J=G[q];if(Y&&J)G[q]=qY(J)}}return b}_removeAllSchemas(b,w){for(let $ in b){let W=b[$];if(!w||w.test($)){if(typeof W=="string")delete b[$];else if(W&&!W.meta)this._cache.delete(W.schema),delete b[$]}}}_addSchema(b,w,$,W=this.opts.validateSchema,Q=this.opts.addUsedSchema){let G,{schemaId:q}=this.opts;if(typeof b=="object")G=b[q];else if(this.opts.jtd)throw Error("schema must be object");else if(typeof b!="boolean")throw Error("schema must be object or boolean");let X=this._cache.get(b);if(X!==void 0)return X;$=(0,s1.normalizeId)(G||$);let Y=s1.getSchemaRefs.call(this,b,$);if(X=new e1.SchemaEnv({schema:b,schemaId:q,meta:w,baseId:$,localRefs:Y}),this._cache.set(X.schema,X),Q&&!$.startsWith("#")){if($)this._checkUnique($);this.refs[$]=X}if(W)this.validateSchema(b,!0);return X}_checkUnique(b){if(this.schemas[b]||this.refs[b])throw Error(`schema with key or id "${b}" already exists`)}_compileSchemaEnv(b){if(b.meta)this._compileMetaSchema(b);else e1.compileSchema.call(this,b);if(!b.validate)throw Error("ajv implementation error");return b.validate}_compileMetaSchema(b){let w=this.opts;this.opts=this._metaOpts;try{e1.compileSchema.call(this,b)}finally{this.opts=w}}}K$.ValidationError=aP.default;K$.MissingRefError=QY.default;Jw.default=K$;function $Y(b,w,$,W="error"){for(let Q in b){let G=Q;if(G in w)this.logger[W](`${$}: option ${Q}. ${b[G]}`)}}function WY(b){return b=(0,s1.normalizeId)(b),this.schemas[b]||this.refs[b]}function Y3(){let b=this.opts.schemas;if(!b)return;if(Array.isArray(b))this.addSchema(b);else for(let w in b)this.addSchema(b[w],w)}function J3(){for(let b in this.opts.formats){let w=this.opts.formats[b];if(w)this.addFormat(b,w)}}function D3(b){if(Array.isArray(b)){this.addVocabulary(b);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let w in b){let $=b[w];if(!$.keyword)$.keyword=w;this.addKeyword($)}}function H3(){let b={...this.opts};for(let w of W3)delete b[w];return b}var z3={log(){},warn(){},error(){}};function O3(b){if(b===!1)return z3;if(b===void 0)return console;if(b.log&&b.warn&&b.error)return b;throw Error("logger must implement log, warn and error methods")}var A3=/^[a-z_$][a-z0-9_$:-]*$/i;function U3(b,w){let{RULES:$}=this;if((0,l6.eachItem)(b,(W)=>{if($.keywords[W])throw Error(`Keyword ${W} is already defined`);if(!A3.test(W))throw Error(`Keyword ${W} has invalid name`)}),!w)return;if(w.$data&&!(("code"in w)||("validate"in w)))throw Error('$data keyword must have "code" or "validate" function')}function m6(b,w,$){var W;let Q=w===null||w===void 0?void 0:w.post;if($&&Q)throw Error('keyword with "post" flag cannot have "type"');let{RULES:G}=this,q=Q?G.post:G.rules.find(({type:Y})=>Y===$);if(!q)q={type:$,rules:[]},G.rules.push(q);if(G.keywords[b]=!0,!w)return;let X={keyword:b,definition:{...w,type:(0,F$.getJSONTypes)(w.type),schemaType:(0,F$.getJSONTypes)(w.schemaType)}};if(w.before)L3.call(this,q,X,w.before);else q.rules.push(X);G.all[b]=X,(W=w.implements)===null||W===void 0||W.forEach((Y)=>this.addKeyword(Y))}function L3(b,w,$){let W=b.rules.findIndex((Q)=>Q.keyword===$);if(W>=0)b.rules.splice(W,0,w);else b.rules.push(w),this.logger.warn(`rule ${$} is not defined`)}function P3(b){let{metaSchema:w}=b;if(w===void 0)return;if(b.$data&&this.opts.$data)w=qY(w);b.validateSchema=this.compile(w,!0)}var B3={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function qY(b){return{anyOf:[b,B3]}}});var JY=Z((YY)=>{Object.defineProperty(YY,"__esModule",{value:!0});var M3={keyword:"id",code(){throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};YY.default=M3});var UY=Z((OY)=>{Object.defineProperty(OY,"__esModule",{value:!0});OY.callRef=OY.getValidate=void 0;var _3=d1(),DY=ub(),jb=y(),w1=qw(),HY=A$(),M$=g(),Z3={keyword:"$ref",schemaType:"string",code(b){let{gen:w,schema:$,it:W}=b,{baseId:Q,schemaEnv:G,validateName:q,opts:X,self:Y}=W,{root:J}=G;if(($==="#"||$==="#/")&&Q===J.baseId)return H();let D=HY.resolveRef.call(Y,J,Q,$);if(D===void 0)throw new _3.default(W.opts.uriResolver,Q,$);if(D instanceof HY.SchemaEnv)return O(D);return A(D);function H(){if(G===J)return I$(b,q,G,G.$async);let B=w.scopeValue("root",{ref:J});return I$(b,jb._`${B}.validate`,J,J.$async)}function O(B){let K=zY(b,B);I$(b,K,B,B.$async)}function A(B){let K=w.scopeValue("schema",X.code.source===!0?{ref:B,code:(0,jb.stringify)(B)}:{ref:B}),_=w.name("valid"),I=b.subschema({schema:B,dataTypes:[],schemaPath:jb.nil,topSchemaRef:K,errSchemaPath:$},_);b.mergeEvaluated(I),b.ok(_)}}};function zY(b,w){let{gen:$}=b;return w.validate?$.scopeValue("validate",{ref:w.validate}):jb._`${$.scopeValue("wrapper",{ref:w})}.validate`}OY.getValidate=zY;function I$(b,w,$,W){let{gen:Q,it:G}=b,{allErrors:q,schemaEnv:X,opts:Y}=G,J=Y.passContext?w1.default.this:jb.nil;if(W)D();else H();function D(){if(!X.$async)throw Error("async schema referenced by sync schema");let B=Q.let("valid");Q.try(()=>{if(Q.code(jb._`await ${(0,DY.callValidateCode)(b,w,J)}`),A(w),!q)Q.assign(B,!0)},(K)=>{if(Q.if(jb._`!(${K} instanceof ${G.ValidationError})`,()=>Q.throw(K)),O(K),!q)Q.assign(B,!1)}),b.ok(B)}function H(){b.result((0,DY.callValidateCode)(b,w,J),()=>A(w),()=>O(w))}function O(B){let K=jb._`${B}.errors`;Q.assign(w1.default.vErrors,jb._`${w1.default.vErrors} === null ? ${K} : ${w1.default.vErrors}.concat(${K})`),Q.assign(w1.default.errors,jb._`${w1.default.vErrors}.length`)}function A(B){var K;if(!G.opts.unevaluated)return;let _=(K=$===null||$===void 0?void 0:$.validate)===null||K===void 0?void 0:K.evaluated;if(G.props!==!0)if(_&&!_.dynamicProps){if(_.props!==void 0)G.props=M$.mergeEvaluated.props(Q,_.props,G.props)}else{let I=Q.var("props",jb._`${B}.evaluated.props`);G.props=M$.mergeEvaluated.props(Q,I,G.props,jb.Name)}if(G.items!==!0)if(_&&!_.dynamicItems){if(_.items!==void 0)G.items=M$.mergeEvaluated.items(Q,_.items,G.items)}else{let I=Q.var("items",jb._`${B}.evaluated.items`);G.items=M$.mergeEvaluated.items(Q,I,G.items,jb.Name)}}}OY.callRef=I$;OY.default=Z3});var PY=Z((LY)=>{Object.defineProperty(LY,"__esModule",{value:!0});var N3=JY(),E3=UY(),T3=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",N3.default,E3.default];LY.default=T3});var FY=Z((BY)=>{Object.defineProperty(BY,"__esModule",{value:!0});var _$=y(),Tw=_$.operators,Z$={maximum:{okStr:"<=",ok:Tw.LTE,fail:Tw.GT},minimum:{okStr:">=",ok:Tw.GTE,fail:Tw.LT},exclusiveMaximum:{okStr:"<",ok:Tw.LT,fail:Tw.GTE},exclusiveMinimum:{okStr:">",ok:Tw.GT,fail:Tw.LTE}},R3={message:({keyword:b,schemaCode:w})=>_$.str`must be ${Z$[b].okStr} ${w}`,params:({keyword:b,schemaCode:w})=>_$._`{comparison: ${Z$[b].okStr}, limit: ${w}}`},v3={keyword:Object.keys(Z$),type:"number",schemaType:"number",$data:!0,error:R3,code(b){let{keyword:w,data:$,schemaCode:W}=b;b.fail$data(_$._`${$} ${Z$[w].fail} ${W} || isNaN(${$})`)}};BY.default=v3});var MY=Z((KY)=>{Object.defineProperty(KY,"__esModule",{value:!0});var a1=y(),C3={message:({schemaCode:b})=>a1.str`must be multiple of ${b}`,params:({schemaCode:b})=>a1._`{multipleOf: ${b}}`},u3={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:C3,code(b){let{gen:w,data:$,schemaCode:W,it:Q}=b,G=Q.opts.multipleOfPrecision,q=w.let("res"),X=G?a1._`Math.abs(Math.round(${q}) - ${q}) > 1e-${G}`:a1._`${q} !== parseInt(${q})`;b.fail$data(a1._`(${W} === 0 || (${q} = ${$}/${W}, ${X}))`)}};KY.default=u3});var ZY=Z((_Y)=>{Object.defineProperty(_Y,"__esModule",{value:!0});function IY(b){let w=b.length,$=0,W=0,Q;while(W<w)if($++,Q=b.charCodeAt(W++),Q>=55296&&Q<=56319&&W<w){if(Q=b.charCodeAt(W),(Q&64512)===56320)W++}return $}_Y.default=IY;IY.code='require("ajv/dist/runtime/ucs2length").default'});var VY=Z((jY)=>{Object.defineProperty(jY,"__esModule",{value:!0});var hw=y(),h3=g(),c3=ZY(),f3={message({keyword:b,schemaCode:w}){let $=b==="maxLength"?"more":"fewer";return hw.str`must NOT have ${$} than ${w} characters`},params:({schemaCode:b})=>hw._`{limit: ${b}}`},n3={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:f3,code(b){let{keyword:w,data:$,schemaCode:W,it:Q}=b,G=w==="maxLength"?hw.operators.GT:hw.operators.LT,q=Q.opts.unicode===!1?hw._`${$}.length`:hw._`${(0,h3.useFunc)(b.gen,c3.default)}(${$})`;b.fail$data(hw._`${q} ${G} ${W}`)}};jY.default=n3});var EY=Z((NY)=>{Object.defineProperty(NY,"__esModule",{value:!0});var m3=ub(),j$=y(),l3={message:({schemaCode:b})=>j$.str`must match pattern "${b}"`,params:({schemaCode:b})=>j$._`{pattern: ${b}}`},g3={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:l3,code(b){let{data:w,$data:$,schema:W,schemaCode:Q,it:G}=b,q=G.opts.unicodeRegExp?"u":"",X=$?j$._`(new RegExp(${Q}, ${q}))`:(0,m3.usePattern)(b,W);b.fail$data(j$._`!${X}.test(${w})`)}};NY.default=g3});var SY=Z((TY)=>{Object.defineProperty(TY,"__esModule",{value:!0});var b0=y(),o3={message({keyword:b,schemaCode:w}){let $=b==="maxProperties"?"more":"fewer";return b0.str`must NOT have ${$} than ${w} properties`},params:({schemaCode:b})=>b0._`{limit: ${b}}`},d3={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:o3,code(b){let{keyword:w,data:$,schemaCode:W}=b,Q=w==="maxProperties"?b0.operators.GT:b0.operators.LT;b.fail$data(b0._`Object.keys(${$}).length ${Q} ${W}`)}};TY.default=d3});var vY=Z((RY)=>{Object.defineProperty(RY,"__esModule",{value:!0});var w0=ub(),$0=y(),r3=g(),e3={message:({params:{missingProperty:b}})=>$0.str`must have required property '${b}'`,params:({params:{missingProperty:b}})=>$0._`{missingProperty: ${b}}`},s3={keyword:"required",type:"object",schemaType:"array",$data:!0,error:e3,code(b){let{gen:w,schema:$,schemaCode:W,data:Q,$data:G,it:q}=b,{opts:X}=q;if(!G&&$.length===0)return;let Y=$.length>=X.loopRequired;if(q.allErrors)J();else D();if(X.strictRequired){let A=b.parentSchema.properties,{definedProperties:B}=b.it;for(let K of $)if((A===null||A===void 0?void 0:A[K])===void 0&&!B.has(K)){let _=q.schemaEnv.baseId+q.errSchemaPath,I=`required property "${K}" is not defined at "${_}" (strictRequired)`;(0,r3.checkStrictMode)(q,I,q.opts.strictRequired)}}function J(){if(Y||G)b.block$data($0.nil,H);else for(let A of $)(0,w0.checkReportMissingProp)(b,A)}function D(){let A=w.let("missing");if(Y||G){let B=w.let("valid",!0);b.block$data(B,()=>O(A,B)),b.ok(B)}else w.if((0,w0.checkMissingProp)(b,$,A)),(0,w0.reportMissingProp)(b,A),w.else()}function H(){w.forOf("prop",W,(A)=>{b.setParams({missingProperty:A}),w.if((0,w0.noPropertyInData)(w,Q,A,X.ownProperties),()=>b.error())})}function O(A,B){b.setParams({missingProperty:A}),w.forOf(A,W,()=>{w.assign(B,(0,w0.propertyInData)(w,Q,A,X.ownProperties)),w.if((0,$0.not)(B),()=>{b.error(),w.break()})},$0.nil)}}};RY.default=s3});var CY=Z((kY)=>{Object.defineProperty(kY,"__esModule",{value:!0});var W0=y(),bB={message({keyword:b,schemaCode:w}){let $=b==="maxItems"?"more":"fewer";return W0.str`must NOT have ${$} than ${w} items`},params:({schemaCode:b})=>W0._`{limit: ${b}}`},wB={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:bB,code(b){let{keyword:w,data:$,schemaCode:W}=b,Q=w==="maxItems"?W0.operators.GT:W0.operators.LT;b.fail$data(W0._`${$}.length ${Q} ${W}`)}};kY.default=wB});var V$=Z((xY)=>{Object.defineProperty(xY,"__esModule",{value:!0});var uY=T6();uY.code='require("ajv/dist/runtime/equal").default';xY.default=uY});var hY=Z((yY)=>{Object.defineProperty(yY,"__esModule",{value:!0});var g6=m1(),Lb=y(),QB=g(),GB=V$(),qB={message:({params:{i:b,j:w}})=>Lb.str`must NOT have duplicate items (items ## ${w} and ${b} are identical)`,params:({params:{i:b,j:w}})=>Lb._`{i: ${b}, j: ${w}}`},XB={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:qB,code(b){let{gen:w,data:$,$data:W,schema:Q,parentSchema:G,schemaCode:q,it:X}=b;if(!W&&!Q)return;let Y=w.let("valid"),J=G.items?(0,g6.getSchemaTypes)(G.items):[];b.block$data(Y,D,Lb._`${q} === false`),b.ok(Y);function D(){let B=w.let("i",Lb._`${$}.length`),K=w.let("j");b.setParams({i:B,j:K}),w.assign(Y,!0),w.if(Lb._`${B} > 1`,()=>(H()?O:A)(B,K))}function H(){return J.length>0&&!J.some((B)=>B==="object"||B==="array")}function O(B,K){let _=w.name("item"),I=(0,g6.checkDataTypes)(J,_,X.opts.strictNumbers,g6.DataType.Wrong),R=w.const("indices",Lb._`{}`);w.for(Lb._`;${B}--;`,()=>{if(w.let(_,Lb._`${$}[${B}]`),w.if(I,Lb._`continue`),J.length>1)w.if(Lb._`typeof ${_} == "string"`,Lb._`${_} += "_"`);w.if(Lb._`typeof ${R}[${_}] == "number"`,()=>{w.assign(K,Lb._`${R}[${_}]`),b.error(),w.assign(Y,!1).break()}).code(Lb._`${R}[${_}] = ${B}`)})}function A(B,K){let _=(0,QB.useFunc)(w,GB.default),I=w.name("outer");w.label(I).for(Lb._`;${B}--;`,()=>w.for(Lb._`${K} = ${B}; ${K}--;`,()=>w.if(Lb._`${_}(${$}[${B}], ${$}[${K}])`,()=>{b.error(),w.assign(Y,!1).break(I)})))}}};yY.default=XB});var fY=Z((cY)=>{Object.defineProperty(cY,"__esModule",{value:!0});var p6=y(),JB=g(),DB=V$(),HB={message:"must be equal to constant",params:({schemaCode:b})=>p6._`{allowedValue: ${b}}`},zB={keyword:"const",$data:!0,error:HB,code(b){let{gen:w,data:$,$data:W,schemaCode:Q,schema:G}=b;if(W||G&&typeof G=="object")b.fail$data(p6._`!${(0,JB.useFunc)(w,DB.default)}(${$}, ${Q})`);else b.fail(p6._`${G} !== ${$}`)}};cY.default=zB});var iY=Z((nY)=>{Object.defineProperty(nY,"__esModule",{value:!0});var Q0=y(),AB=g(),UB=V$(),LB={message:"must be equal to one of the allowed values",params:({schemaCode:b})=>Q0._`{allowedValues: ${b}}`},PB={keyword:"enum",schemaType:"array",$data:!0,error:LB,code(b){let{gen:w,data:$,$data:W,schema:Q,schemaCode:G,it:q}=b;if(!W&&Q.length===0)throw Error("enum must have non-empty array");let X=Q.length>=q.opts.loopEnum,Y,J=()=>Y!==null&&Y!==void 0?Y:Y=(0,AB.useFunc)(w,UB.default),D;if(X||W)D=w.let("valid"),b.block$data(D,H);else{if(!Array.isArray(Q))throw Error("ajv implementation error");let A=w.const("vSchema",G);D=(0,Q0.or)(...Q.map((B,K)=>O(A,K)))}b.pass(D);function H(){w.assign(D,!1),w.forOf("v",G,(A)=>w.if(Q0._`${J()}(${$}, ${A})`,()=>w.assign(D,!0).break()))}function O(A,B){let K=Q[B];return typeof K==="object"&&K!==null?Q0._`${J()}(${$}, ${A}[${B}])`:Q0._`${$} === ${K}`}}};nY.default=PB});var lY=Z((mY)=>{Object.defineProperty(mY,"__esModule",{value:!0});var FB=FY(),KB=MY(),MB=VY(),IB=EY(),_B=SY(),ZB=vY(),jB=CY(),VB=hY(),NB=fY(),EB=iY(),TB=[FB.default,KB.default,MB.default,IB.default,_B.default,ZB.default,jB.default,VB.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},NB.default,EB.default];mY.default=TB});var d6=Z((pY)=>{Object.defineProperty(pY,"__esModule",{value:!0});pY.validateAdditionalItems=void 0;var cw=y(),o6=g(),RB={message:({params:{len:b}})=>cw.str`must NOT have more than ${b} items`,params:({params:{len:b}})=>cw._`{limit: ${b}}`},vB={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:RB,code(b){let{parentSchema:w,it:$}=b,{items:W}=w;if(!Array.isArray(W)){(0,o6.checkStrictMode)($,'"additionalItems" is ignored when "items" is not an array of schemas');return}gY(b,W)}};function gY(b,w){let{gen:$,schema:W,data:Q,keyword:G,it:q}=b;q.items=!0;let X=$.const("len",cw._`${Q}.length`);if(W===!1)b.setParams({len:w.length}),b.pass(cw._`${X} <= ${w.length}`);else if(typeof W=="object"&&!(0,o6.alwaysValidSchema)(q,W)){let J=$.var("valid",cw._`${X} <= ${w.length}`);$.if((0,cw.not)(J),()=>Y(J)),b.ok(J)}function Y(J){$.forRange("i",w.length,X,(D)=>{if(b.subschema({keyword:G,dataProp:D,dataPropType:o6.Type.Num},J),!q.allErrors)$.if((0,cw.not)(J),()=>$.break())})}}pY.validateAdditionalItems=gY;pY.default=vB});var t6=Z((rY)=>{Object.defineProperty(rY,"__esModule",{value:!0});rY.validateTuple=void 0;var dY=y(),N$=g(),CB=ub(),uB={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(b){let{schema:w,it:$}=b;if(Array.isArray(w))return tY(b,"additionalItems",w);if($.items=!0,(0,N$.alwaysValidSchema)($,w))return;b.ok((0,CB.validateArray)(b))}};function tY(b,w,$=b.schema){let{gen:W,parentSchema:Q,data:G,keyword:q,it:X}=b;if(D(Q),X.opts.unevaluated&&$.length&&X.items!==!0)X.items=N$.mergeEvaluated.items(W,$.length,X.items);let Y=W.name("valid"),J=W.const("len",dY._`${G}.length`);$.forEach((H,O)=>{if((0,N$.alwaysValidSchema)(X,H))return;W.if(dY._`${J} > ${O}`,()=>b.subschema({keyword:q,schemaProp:O,dataProp:O},Y)),b.ok(Y)});function D(H){let{opts:O,errSchemaPath:A}=X,B=$.length,K=B===H.minItems&&(B===H.maxItems||H[w]===!1);if(O.strictTuples&&!K){let _=`"${q}" is ${B}-tuple, but minItems or maxItems/${w} are not specified or different at path "${A}"`;(0,N$.checkStrictMode)(X,_,O.strictTuples)}}}rY.validateTuple=tY;rY.default=uB});var aY=Z((sY)=>{Object.defineProperty(sY,"__esModule",{value:!0});var yB=t6(),hB={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:(b)=>(0,yB.validateTuple)(b,"items")};sY.default=hB});var $J=Z((wJ)=>{Object.defineProperty(wJ,"__esModule",{value:!0});var bJ=y(),fB=g(),nB=ub(),iB=d6(),mB={message:({params:{len:b}})=>bJ.str`must NOT have more than ${b} items`,params:({params:{len:b}})=>bJ._`{limit: ${b}}`},lB={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:mB,code(b){let{schema:w,parentSchema:$,it:W}=b,{prefixItems:Q}=$;if(W.items=!0,(0,fB.alwaysValidSchema)(W,w))return;if(Q)(0,iB.validateAdditionalItems)(b,Q);else b.ok((0,nB.validateArray)(b))}};wJ.default=lB});var QJ=Z((WJ)=>{Object.defineProperty(WJ,"__esModule",{value:!0});var xb=y(),E$=g(),pB={message:({params:{min:b,max:w}})=>w===void 0?xb.str`must contain at least ${b} valid item(s)`:xb.str`must contain at least ${b} and no more than ${w} valid item(s)`,params:({params:{min:b,max:w}})=>w===void 0?xb._`{minContains: ${b}}`:xb._`{minContains: ${b}, maxContains: ${w}}`},oB={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:pB,code(b){let{gen:w,schema:$,parentSchema:W,data:Q,it:G}=b,q,X,{minContains:Y,maxContains:J}=W;if(G.opts.next)q=Y===void 0?1:Y,X=J;else q=1;let D=w.const("len",xb._`${Q}.length`);if(b.setParams({min:q,max:X}),X===void 0&&q===0){(0,E$.checkStrictMode)(G,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(X!==void 0&&q>X){(0,E$.checkStrictMode)(G,'"minContains" > "maxContains" is always invalid'),b.fail();return}if((0,E$.alwaysValidSchema)(G,$)){let K=xb._`${D} >= ${q}`;if(X!==void 0)K=xb._`${K} && ${D} <= ${X}`;b.pass(K);return}G.items=!0;let H=w.name("valid");if(X===void 0&&q===1)A(H,()=>w.if(H,()=>w.break()));else if(q===0){if(w.let(H,!0),X!==void 0)w.if(xb._`${Q}.length > 0`,O)}else w.let(H,!1),O();b.result(H,()=>b.reset());function O(){let K=w.name("_valid"),_=w.let("count",0);A(K,()=>w.if(K,()=>B(_)))}function A(K,_){w.forRange("i",0,D,(I)=>{b.subschema({keyword:"contains",dataProp:I,dataPropType:E$.Type.Num,compositeRule:!0},K),_()})}function B(K){if(w.code(xb._`${K}++`),X===void 0)w.if(xb._`${K} >= ${q}`,()=>w.assign(H,!0).break());else if(w.if(xb._`${K} > ${X}`,()=>w.assign(H,!1).break()),q===1)w.assign(H,!0);else w.if(xb._`${K} >= ${q}`,()=>w.assign(H,!0))}}};WJ.default=oB});var DJ=Z((XJ)=>{Object.defineProperty(XJ,"__esModule",{value:!0});XJ.validateSchemaDeps=XJ.validatePropertyDeps=XJ.error=void 0;var r6=y(),tB=g(),G0=ub();XJ.error={message:({params:{property:b,depsCount:w,deps:$}})=>{let W=w===1?"property":"properties";return r6.str`must have ${W} ${$} when property ${b} is present`},params:({params:{property:b,depsCount:w,deps:$,missingProperty:W}})=>r6._`{property: ${b},
|
|
2
|
+
var Gz=Object.create;var{getPrototypeOf:Xz,defineProperty:b4,getOwnPropertyNames:Yz}=Object;var Jz=Object.prototype.hasOwnProperty;function Dz(b){return this[b]}var Hz,zz,gW=(b,w,$)=>{var W=b!=null&&typeof b==="object";if(W){var Q=w?Hz??=new WeakMap:zz??=new WeakMap,q=Q.get(b);if(q)return q}$=b!=null?Gz(Xz(b)):{};let G=w||!b||!b.__esModule?b4($,"default",{value:b,enumerable:!0}):$;for(let X of Yz(b))if(!Jz.call(G,X))b4(G,X,{get:Dz.bind(b,X),enumerable:!0});if(W)Q.set(b,G);return G};var j=(b,w)=>()=>(w||b((w={exports:{}}).exports,w),w.exports);var Oz=(b)=>b;function Az(b,w){this[b]=Oz.bind(null,w)}var pW=(b,w)=>{for(var $ in w)b4(b,$,{get:w[$],enumerable:!0,configurable:!0,set:Az.bind(w,$)})};var f1=j((oq)=>{Object.defineProperty(oq,"__esModule",{value:!0});oq.regexpCode=oq.getEsmExportName=oq.getProperty=oq.safeStringify=oq.stringify=oq.strConcat=oq.addCodeArg=oq.str=oq._=oq.nil=oq._Code=oq.Name=oq.IDENTIFIER=oq._CodeOrName=void 0;class s0{}oq._CodeOrName=s0;oq.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class dw extends s0{constructor(b){super();if(!oq.IDENTIFIER.test(b))throw Error("CodeGen: name must be a valid identifier");this.str=b}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}oq.Name=dw;class cb extends s0{constructor(b){super();this._items=typeof b==="string"?[b]:b}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let b=this._items[0];return b===""||b==='""'}get str(){var b;return(b=this._str)!==null&&b!==void 0?b:this._str=this._items.reduce((w,$)=>`${w}${$}`,"")}get names(){var b;return(b=this._names)!==null&&b!==void 0?b:this._names=this._items.reduce((w,$)=>{if($ instanceof dw)w[$.str]=(w[$.str]||0)+1;return w},{})}}oq._Code=cb;oq.nil=new cb("");function gq(b,...w){let $=[b[0]],W=0;while(W<w.length)J6($,w[W]),$.push(b[++W]);return new cb($)}oq._=gq;var Y6=new cb("+");function pq(b,...w){let $=[c1(b[0])],W=0;while(W<w.length)$.push(Y6),J6($,w[W]),$.push(Y6,c1(b[++W]));return yA($),new cb($)}oq.str=pq;function J6(b,w){if(w instanceof cb)b.push(...w._items);else if(w instanceof dw)b.push(w);else b.push(fA(w))}oq.addCodeArg=J6;function yA(b){let w=1;while(w<b.length-1){if(b[w]===Y6){let $=hA(b[w-1],b[w+1]);if($!==void 0){b.splice(w-1,3,$);continue}b[w++]="+"}w++}}function hA(b,w){if(w==='""')return b;if(b==='""')return w;if(typeof b=="string"){if(w instanceof dw||b[b.length-1]!=='"')return;if(typeof w!="string")return`${b.slice(0,-1)}${w}"`;if(w[0]==='"')return b.slice(0,-1)+w.slice(1);return}if(typeof w=="string"&&w[0]==='"'&&!(b instanceof dw))return`"${b}${w.slice(1)}`;return}function cA(b,w){return w.emptyStr()?b:b.emptyStr()?w:pq`${b}${w}`}oq.strConcat=cA;function fA(b){return typeof b=="number"||typeof b=="boolean"||b===null?b:c1(Array.isArray(b)?b.join(","):b)}function nA(b){return new cb(c1(b))}oq.stringify=nA;function c1(b){return JSON.stringify(b).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}oq.safeStringify=c1;function iA(b){return typeof b=="string"&&oq.IDENTIFIER.test(b)?new cb(`.${b}`):gq`[${b}]`}oq.getProperty=iA;function mA(b){if(typeof b=="string"&&oq.IDENTIFIER.test(b))return new cb(`${b}`);throw Error(`CodeGen: invalid export name: ${b}, use explicit $id name mapping`)}oq.getEsmExportName=mA;function lA(b){return new cb(b.toString())}oq.regexpCode=lA});var O6=j((eq)=>{Object.defineProperty(eq,"__esModule",{value:!0});eq.ValueScope=eq.ValueScopeName=eq.Scope=eq.varKinds=eq.UsedValueState=void 0;var _b=f1();class tq extends Error{constructor(b){super(`CodeGen: "code" for ${b} not defined`);this.value=b.value}}var b$;(function(b){b[b.Started=0]="Started",b[b.Completed=1]="Completed"})(b$||(eq.UsedValueState=b$={}));eq.varKinds={const:new _b.Name("const"),let:new _b.Name("let"),var:new _b.Name("var")};class H6{constructor({prefixes:b,parent:w}={}){this._names={},this._prefixes=b,this._parent=w}toName(b){return b instanceof _b.Name?b:this.name(b)}name(b){return new _b.Name(this._newName(b))}_newName(b){let w=this._names[b]||this._nameGroup(b);return`${b}${w.index++}`}_nameGroup(b){var w,$;if((($=(w=this._parent)===null||w===void 0?void 0:w._prefixes)===null||$===void 0?void 0:$.has(b))||this._prefixes&&!this._prefixes.has(b))throw Error(`CodeGen: prefix "${b}" is not allowed in this scope`);return this._names[b]={prefix:b,index:0}}}eq.Scope=H6;class z6 extends _b.Name{constructor(b,w){super(w);this.prefix=b}setValue(b,{property:w,itemIndex:$}){this.value=b,this.scopePath=_b._`.${new _b.Name(w)}[${$}]`}}eq.ValueScopeName=z6;var W5=_b._`\n`;class rq extends H6{constructor(b){super(b);this._values={},this._scope=b.scope,this.opts={...b,_n:b.lines?W5:_b.nil}}get(){return this._scope}name(b){return new z6(b,this._newName(b))}value(b,w){var $;if(w.ref===void 0)throw Error("CodeGen: ref must be passed in value");let W=this.toName(b),{prefix:Q}=W,q=($=w.key)!==null&&$!==void 0?$:w.ref,G=this._values[Q];if(G){let J=G.get(q);if(J)return J}else G=this._values[Q]=new Map;G.set(q,W);let X=this._scope[Q]||(this._scope[Q]=[]),Y=X.length;return X[Y]=w.ref,W.setValue(w,{property:Q,itemIndex:Y}),W}getValue(b,w){let $=this._values[b];if(!$)return;return $.get(w)}scopeRefs(b,w=this._values){return this._reduceValues(w,($)=>{if($.scopePath===void 0)throw Error(`CodeGen: name "${$}" has no value`);return _b._`${b}${$.scopePath}`})}scopeCode(b=this._values,w,$){return this._reduceValues(b,(W)=>{if(W.value===void 0)throw Error(`CodeGen: name "${W}" has no value`);return W.value.code},w,$)}_reduceValues(b,w,$={},W){let Q=_b.nil;for(let q in b){let G=b[q];if(!G)continue;let X=$[q]=$[q]||new Map;G.forEach((Y)=>{if(X.has(Y))return;X.set(Y,b$.Started);let J=w(Y);if(J){let D=this.opts.es5?eq.varKinds.var:eq.varKinds.const;Q=_b._`${Q}${D} ${Y} = ${J};${this.opts._n}`}else if(J=W===null||W===void 0?void 0:W(Y))Q=_b._`${Q}${J}${this.opts._n}`;else throw new tq(Y);X.set(Y,b$.Completed)})}return Q}}eq.ValueScope=rq});var y=j((jb)=>{Object.defineProperty(jb,"__esModule",{value:!0});jb.or=jb.and=jb.not=jb.CodeGen=jb.operators=jb.varKinds=jb.ValueScopeName=jb.ValueScope=jb.Scope=jb.Name=jb.regexpCode=jb.stringify=jb.getProperty=jb.nil=jb.strConcat=jb.str=jb._=void 0;var n=f1(),fb=O6(),jw=f1();Object.defineProperty(jb,"_",{enumerable:!0,get:function(){return jw._}});Object.defineProperty(jb,"str",{enumerable:!0,get:function(){return jw.str}});Object.defineProperty(jb,"strConcat",{enumerable:!0,get:function(){return jw.strConcat}});Object.defineProperty(jb,"nil",{enumerable:!0,get:function(){return jw.nil}});Object.defineProperty(jb,"getProperty",{enumerable:!0,get:function(){return jw.getProperty}});Object.defineProperty(jb,"stringify",{enumerable:!0,get:function(){return jw.stringify}});Object.defineProperty(jb,"regexpCode",{enumerable:!0,get:function(){return jw.regexpCode}});Object.defineProperty(jb,"Name",{enumerable:!0,get:function(){return jw.Name}});var G$=O6();Object.defineProperty(jb,"Scope",{enumerable:!0,get:function(){return G$.Scope}});Object.defineProperty(jb,"ValueScope",{enumerable:!0,get:function(){return G$.ValueScope}});Object.defineProperty(jb,"ValueScopeName",{enumerable:!0,get:function(){return G$.ValueScopeName}});Object.defineProperty(jb,"varKinds",{enumerable:!0,get:function(){return G$.varKinds}});jb.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 Zw{optimizeNodes(){return this}optimizeNames(b,w){return this}}class aq extends Zw{constructor(b,w,$){super();this.varKind=b,this.name=w,this.rhs=$}render({es5:b,_n:w}){let $=b?fb.varKinds.var:this.varKind,W=this.rhs===void 0?"":` = ${this.rhs}`;return`${$} ${this.name}${W};`+w}optimizeNames(b,w){if(!b[this.name.str])return;if(this.rhs)this.rhs=rw(this.rhs,b,w);return this}get names(){return this.rhs instanceof n._CodeOrName?this.rhs.names:{}}}class U6 extends Zw{constructor(b,w,$){super();this.lhs=b,this.rhs=w,this.sideEffects=$}render({_n:b}){return`${this.lhs} = ${this.rhs};`+b}optimizeNames(b,w){if(this.lhs instanceof n.Name&&!b[this.lhs.str]&&!this.sideEffects)return;return this.rhs=rw(this.rhs,b,w),this}get names(){let b=this.lhs instanceof n.Name?{}:{...this.lhs.names};return q$(b,this.rhs)}}class bG extends U6{constructor(b,w,$,W){super(b,$,W);this.op=w}render({_n:b}){return`${this.lhs} ${this.op}= ${this.rhs};`+b}}class wG extends Zw{constructor(b){super();this.label=b,this.names={}}render({_n:b}){return`${this.label}:`+b}}class $G extends Zw{constructor(b){super();this.label=b,this.names={}}render({_n:b}){return`break${this.label?` ${this.label}`:""};`+b}}class WG extends Zw{constructor(b){super();this.error=b}render({_n:b}){return`throw ${this.error};`+b}get names(){return this.error.names}}class QG extends Zw{constructor(b){super();this.code=b}render({_n:b}){return`${this.code};`+b}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(b,w){return this.code=rw(this.code,b,w),this}get names(){return this.code instanceof n._CodeOrName?this.code.names:{}}}class X$ extends Zw{constructor(b=[]){super();this.nodes=b}render(b){return this.nodes.reduce((w,$)=>w+$.render(b),"")}optimizeNodes(){let{nodes:b}=this,w=b.length;while(w--){let $=b[w].optimizeNodes();if(Array.isArray($))b.splice(w,1,...$);else if($)b[w]=$;else b.splice(w,1)}return b.length>0?this:void 0}optimizeNames(b,w){let{nodes:$}=this,W=$.length;while(W--){let Q=$[W];if(Q.optimizeNames(b,w))continue;X5(b,Q.names),$.splice(W,1)}return $.length>0?this:void 0}get names(){return this.nodes.reduce((b,w)=>Cw(b,w.names),{})}}class Vw extends X${render(b){return"{"+b._n+super.render(b)+"}"+b._n}}class qG extends X${}class n1 extends Vw{}n1.kind="else";class qw extends Vw{constructor(b,w){super(w);this.condition=b}render(b){let w=`if(${this.condition})`+super.render(b);if(this.else)w+="else "+this.else.render(b);return w}optimizeNodes(){super.optimizeNodes();let b=this.condition;if(b===!0)return this.nodes;let w=this.else;if(w){let $=w.optimizeNodes();w=this.else=Array.isArray($)?new n1($):$}if(w){if(b===!1)return w instanceof qw?w:w.nodes;if(this.nodes.length)return this;return new qw(DG(b),w instanceof qw?[w]:w.nodes)}if(b===!1||!this.nodes.length)return;return this}optimizeNames(b,w){var $;if(this.else=($=this.else)===null||$===void 0?void 0:$.optimizeNames(b,w),!(super.optimizeNames(b,w)||this.else))return;return this.condition=rw(this.condition,b,w),this}get names(){let b=super.names;if(q$(b,this.condition),this.else)Cw(b,this.else.names);return b}}qw.kind="if";class tw extends Vw{}tw.kind="for";class GG extends tw{constructor(b){super();this.iteration=b}render(b){return`for(${this.iteration})`+super.render(b)}optimizeNames(b,w){if(!super.optimizeNames(b,w))return;return this.iteration=rw(this.iteration,b,w),this}get names(){return Cw(super.names,this.iteration.names)}}class XG extends tw{constructor(b,w,$,W){super();this.varKind=b,this.name=w,this.from=$,this.to=W}render(b){let w=b.es5?fb.varKinds.var:this.varKind,{name:$,from:W,to:Q}=this;return`for(${w} ${$}=${W}; ${$}<${Q}; ${$}++)`+super.render(b)}get names(){let b=q$(super.names,this.from);return q$(b,this.to)}}class A6 extends tw{constructor(b,w,$,W){super();this.loop=b,this.varKind=w,this.name=$,this.iterable=W}render(b){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(b)}optimizeNames(b,w){if(!super.optimizeNames(b,w))return;return this.iterable=rw(this.iterable,b,w),this}get names(){return Cw(super.names,this.iterable.names)}}class w$ extends Vw{constructor(b,w,$){super();this.name=b,this.args=w,this.async=$}render(b){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(b)}}w$.kind="func";class $$ extends X${render(b){return"return "+super.render(b)}}$$.kind="return";class YG extends Vw{render(b){let w="try"+super.render(b);if(this.catch)w+=this.catch.render(b);if(this.finally)w+=this.finally.render(b);return w}optimizeNodes(){var b,w;return super.optimizeNodes(),(b=this.catch)===null||b===void 0||b.optimizeNodes(),(w=this.finally)===null||w===void 0||w.optimizeNodes(),this}optimizeNames(b,w){var $,W;return super.optimizeNames(b,w),($=this.catch)===null||$===void 0||$.optimizeNames(b,w),(W=this.finally)===null||W===void 0||W.optimizeNames(b,w),this}get names(){let b=super.names;if(this.catch)Cw(b,this.catch.names);if(this.finally)Cw(b,this.finally.names);return b}}class W$ extends Vw{constructor(b){super();this.error=b}render(b){return`catch(${this.error})`+super.render(b)}}W$.kind="catch";class Q$ extends Vw{render(b){return"finally"+super.render(b)}}Q$.kind="finally";class JG{constructor(b,w={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...w,_n:w.lines?`
|
|
3
|
+
`:""},this._extScope=b,this._scope=new fb.Scope({parent:b}),this._nodes=[new qG]}toString(){return this._root.render(this.opts)}name(b){return this._scope.name(b)}scopeName(b){return this._extScope.name(b)}scopeValue(b,w){let $=this._extScope.value(b,w);return(this._values[$.prefix]||(this._values[$.prefix]=new Set)).add($),$}getScopeValue(b,w){return this._extScope.getValue(b,w)}scopeRefs(b){return this._extScope.scopeRefs(b,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(b,w,$,W){let Q=this._scope.toName(w);if($!==void 0&&W)this._constants[Q.str]=$;return this._leafNode(new aq(b,Q,$)),Q}const(b,w,$){return this._def(fb.varKinds.const,b,w,$)}let(b,w,$){return this._def(fb.varKinds.let,b,w,$)}var(b,w,$){return this._def(fb.varKinds.var,b,w,$)}assign(b,w,$){return this._leafNode(new U6(b,w,$))}add(b,w){return this._leafNode(new bG(b,jb.operators.ADD,w))}code(b){if(typeof b=="function")b();else if(b!==n.nil)this._leafNode(new QG(b));return this}object(...b){let w=["{"];for(let[$,W]of b){if(w.length>1)w.push(",");if(w.push($),$!==W||this.opts.es5)w.push(":"),(0,n.addCodeArg)(w,W)}return w.push("}"),new n._Code(w)}if(b,w,$){if(this._blockNode(new qw(b)),w&&$)this.code(w).else().code($).endIf();else if(w)this.code(w).endIf();else if($)throw Error('CodeGen: "else" body without "then" body');return this}elseIf(b){return this._elseNode(new qw(b))}else(){return this._elseNode(new n1)}endIf(){return this._endBlockNode(qw,n1)}_for(b,w){if(this._blockNode(b),w)this.code(w).endFor();return this}for(b,w){return this._for(new GG(b),w)}forRange(b,w,$,W,Q=this.opts.es5?fb.varKinds.var:fb.varKinds.let){let q=this._scope.toName(b);return this._for(new XG(Q,q,w,$),()=>W(q))}forOf(b,w,$,W=fb.varKinds.const){let Q=this._scope.toName(b);if(this.opts.es5){let q=w instanceof n.Name?w:this.var("_arr",w);return this.forRange("_i",0,n._`${q}.length`,(G)=>{this.var(Q,n._`${q}[${G}]`),$(Q)})}return this._for(new A6("of",W,Q,w),()=>$(Q))}forIn(b,w,$,W=this.opts.es5?fb.varKinds.var:fb.varKinds.const){if(this.opts.ownProperties)return this.forOf(b,n._`Object.keys(${w})`,$);let Q=this._scope.toName(b);return this._for(new A6("in",W,Q,w),()=>$(Q))}endFor(){return this._endBlockNode(tw)}label(b){return this._leafNode(new wG(b))}break(b){return this._leafNode(new $G(b))}return(b){let w=new $$;if(this._blockNode(w),this.code(b),w.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode($$)}try(b,w,$){if(!w&&!$)throw Error('CodeGen: "try" without "catch" and "finally"');let W=new YG;if(this._blockNode(W),this.code(b),w){let Q=this.name("e");this._currNode=W.catch=new W$(Q),w(Q)}if($)this._currNode=W.finally=new Q$,this.code($);return this._endBlockNode(W$,Q$)}throw(b){return this._leafNode(new WG(b))}block(b,w){if(this._blockStarts.push(this._nodes.length),b)this.code(b).endBlock(w);return this}endBlock(b){let w=this._blockStarts.pop();if(w===void 0)throw Error("CodeGen: not in self-balancing block");let $=this._nodes.length-w;if($<0||b!==void 0&&$!==b)throw Error(`CodeGen: wrong number of nodes: ${$} vs ${b} expected`);return this._nodes.length=w,this}func(b,w=n.nil,$,W){if(this._blockNode(new w$(b,w,$)),W)this.code(W).endFunc();return this}endFunc(){return this._endBlockNode(w$)}optimize(b=1){while(b-- >0)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(b){return this._currNode.nodes.push(b),this}_blockNode(b){this._currNode.nodes.push(b),this._nodes.push(b)}_endBlockNode(b,w){let $=this._currNode;if($ instanceof b||w&&$ instanceof w)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${w?`${b.kind}/${w.kind}`:b.kind}"`)}_elseNode(b){let w=this._currNode;if(!(w instanceof qw))throw Error('CodeGen: "else" without "if"');return this._currNode=w.else=b,this}get _root(){return this._nodes[0]}get _currNode(){let b=this._nodes;return b[b.length-1]}set _currNode(b){let w=this._nodes;w[w.length-1]=b}}jb.CodeGen=JG;function Cw(b,w){for(let $ in w)b[$]=(b[$]||0)+(w[$]||0);return b}function q$(b,w){return w instanceof n._CodeOrName?Cw(b,w.names):b}function rw(b,w,$){if(b instanceof n.Name)return W(b);if(!Q(b))return b;return new n._Code(b._items.reduce((q,G)=>{if(G instanceof n.Name)G=W(G);if(G instanceof n._Code)q.push(...G._items);else q.push(G);return q},[]));function W(q){let G=$[q.str];if(G===void 0||w[q.str]!==1)return q;return delete w[q.str],G}function Q(q){return q instanceof n._Code&&q._items.some((G)=>G instanceof n.Name&&w[G.str]===1&&$[G.str]!==void 0)}}function X5(b,w){for(let $ in w)b[$]=(b[$]||0)-(w[$]||0)}function DG(b){return typeof b=="boolean"||typeof b=="number"||b===null?!b:n._`!${L6(b)}`}jb.not=DG;var Y5=HG(jb.operators.AND);function J5(...b){return b.reduce(Y5)}jb.and=J5;var D5=HG(jb.operators.OR);function H5(...b){return b.reduce(D5)}jb.or=H5;function HG(b){return(w,$)=>w===n.nil?$:$===n.nil?w:n._`${L6(w)} ${b} ${L6($)}`}function L6(b){return b instanceof n.Name?b:n._`(${b})`}});var g=j((KG)=>{Object.defineProperty(KG,"__esModule",{value:!0});KG.checkStrictMode=KG.getErrorPath=KG.Type=KG.useFunc=KG.setEvaluated=KG.evaluatedPropsToName=KG.mergeEvaluated=KG.eachItem=KG.unescapeJsonPointer=KG.escapeJsonPointer=KG.escapeFragment=KG.unescapeFragment=KG.schemaRefOrVal=KG.schemaHasRulesButRef=KG.schemaHasRules=KG.checkUnknownRules=KG.alwaysValidSchema=KG.toHash=void 0;var t=y(),L5=f1();function U5(b){let w={};for(let $ of b)w[$]=!0;return w}KG.toHash=U5;function P5(b,w){if(typeof w=="boolean")return w;if(Object.keys(w).length===0)return!0;return LG(b,w),!UG(w,b.self.RULES.all)}KG.alwaysValidSchema=P5;function LG(b,w=b.schema){let{opts:$,self:W}=b;if(!$.strictSchema)return;if(typeof w==="boolean")return;let Q=W.RULES.keywords;for(let q in w)if(!Q[q])FG(b,`unknown keyword: "${q}"`)}KG.checkUnknownRules=LG;function UG(b,w){if(typeof b=="boolean")return!b;for(let $ in b)if(w[$])return!0;return!1}KG.schemaHasRules=UG;function B5(b,w){if(typeof b=="boolean")return!b;for(let $ in b)if($!=="$ref"&&w.all[$])return!0;return!1}KG.schemaHasRulesButRef=B5;function F5({topSchemaRef:b,schemaPath:w},$,W,Q){if(!Q){if(typeof $=="number"||typeof $=="boolean")return $;if(typeof $=="string")return t._`${$}`}return t._`${b}${w}${(0,t.getProperty)(W)}`}KG.schemaRefOrVal=F5;function K5(b){return PG(decodeURIComponent(b))}KG.unescapeFragment=K5;function M5(b){return encodeURIComponent(B6(b))}KG.escapeFragment=M5;function B6(b){if(typeof b=="number")return`${b}`;return b.replace(/~/g,"~0").replace(/\//g,"~1")}KG.escapeJsonPointer=B6;function PG(b){return b.replace(/~1/g,"/").replace(/~0/g,"~")}KG.unescapeJsonPointer=PG;function I5(b,w){if(Array.isArray(b))for(let $ of b)w($);else w(b)}KG.eachItem=I5;function OG({mergeNames:b,mergeToName:w,mergeValues:$,resultToName:W}){return(Q,q,G,X)=>{let Y=G===void 0?q:G instanceof t.Name?(q instanceof t.Name?b(Q,q,G):w(Q,q,G),G):q instanceof t.Name?(w(Q,G,q),q):$(q,G);return X===t.Name&&!(Y instanceof t.Name)?W(Q,Y):Y}}KG.mergeEvaluated={props:OG({mergeNames:(b,w,$)=>b.if(t._`${$} !== true && ${w} !== undefined`,()=>{b.if(t._`${w} === true`,()=>b.assign($,!0),()=>b.assign($,t._`${$} || {}`).code(t._`Object.assign(${$}, ${w})`))}),mergeToName:(b,w,$)=>b.if(t._`${$} !== true`,()=>{if(w===!0)b.assign($,!0);else b.assign($,t._`${$} || {}`),F6(b,$,w)}),mergeValues:(b,w)=>b===!0?!0:{...b,...w},resultToName:BG}),items:OG({mergeNames:(b,w,$)=>b.if(t._`${$} !== true && ${w} !== undefined`,()=>b.assign($,t._`${w} === true ? true : ${$} > ${w} ? ${$} : ${w}`)),mergeToName:(b,w,$)=>b.if(t._`${$} !== true`,()=>b.assign($,w===!0?!0:t._`${$} > ${w} ? ${$} : ${w}`)),mergeValues:(b,w)=>b===!0?!0:Math.max(b,w),resultToName:(b,w)=>b.var("items",w)})};function BG(b,w){if(w===!0)return b.var("props",!0);let $=b.var("props",t._`{}`);if(w!==void 0)F6(b,$,w);return $}KG.evaluatedPropsToName=BG;function F6(b,w,$){Object.keys($).forEach((W)=>b.assign(t._`${w}${(0,t.getProperty)(W)}`,!0))}KG.setEvaluated=F6;var AG={};function _5(b,w){return b.scopeValue("func",{ref:w,code:AG[w.code]||(AG[w.code]=new L5._Code(w.code))})}KG.useFunc=_5;var P6;(function(b){b[b.Num=0]="Num",b[b.Str=1]="Str"})(P6||(KG.Type=P6={}));function j5(b,w,$){if(b instanceof t.Name){let W=w===P6.Num;return $?W?t._`"[" + ${b} + "]"`:t._`"['" + ${b} + "']"`:W?t._`"/" + ${b}`:t._`"/" + ${b}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return $?(0,t.getProperty)(b).toString():"/"+B6(b)}KG.getErrorPath=j5;function FG(b,w,$=b.opts.strictSchema){if(!$)return;if(w=`strict mode: ${w}`,$===!0)throw Error(w);b.self.logger.warn(w)}KG.checkStrictMode=FG});var Gw=j((IG)=>{Object.defineProperty(IG,"__esModule",{value:!0});var Pb=y(),i5={data:new Pb.Name("data"),valCxt:new Pb.Name("valCxt"),instancePath:new Pb.Name("instancePath"),parentData:new Pb.Name("parentData"),parentDataProperty:new Pb.Name("parentDataProperty"),rootData:new Pb.Name("rootData"),dynamicAnchors:new Pb.Name("dynamicAnchors"),vErrors:new Pb.Name("vErrors"),errors:new Pb.Name("errors"),this:new Pb.Name("this"),self:new Pb.Name("self"),scope:new Pb.Name("scope"),json:new Pb.Name("json"),jsonPos:new Pb.Name("jsonPos"),jsonLen:new Pb.Name("jsonLen"),jsonPart:new Pb.Name("jsonPart")};IG.default=i5});var i1=j((VG)=>{Object.defineProperty(VG,"__esModule",{value:!0});VG.extendErrors=VG.resetErrorsCount=VG.reportExtraError=VG.reportError=VG.keyword$DataError=VG.keywordError=void 0;var m=y(),J$=g(),Fb=Gw();VG.keywordError={message:({keyword:b})=>m.str`must pass "${b}" keyword validation`};VG.keyword$DataError={message:({keyword:b,schemaType:w})=>w?m.str`"${b}" keyword must be ${w} ($data)`:m.str`"${b}" keyword is invalid ($data)`};function l5(b,w=VG.keywordError,$,W){let{it:Q}=b,{gen:q,compositeRule:G,allErrors:X}=Q,Y=ZG(b,w,$);if(W!==null&&W!==void 0?W:G||X)_G(q,Y);else jG(Q,m._`[${Y}]`)}VG.reportError=l5;function g5(b,w=VG.keywordError,$){let{it:W}=b,{gen:Q,compositeRule:q,allErrors:G}=W,X=ZG(b,w,$);if(_G(Q,X),!(q||G))jG(W,Fb.default.vErrors)}VG.reportExtraError=g5;function p5(b,w){b.assign(Fb.default.errors,w),b.if(m._`${Fb.default.vErrors} !== null`,()=>b.if(w,()=>b.assign(m._`${Fb.default.vErrors}.length`,w),()=>b.assign(Fb.default.vErrors,null)))}VG.resetErrorsCount=p5;function o5({gen:b,keyword:w,schemaValue:$,data:W,errsCount:Q,it:q}){if(Q===void 0)throw Error("ajv implementation error");let G=b.name("err");b.forRange("i",Q,Fb.default.errors,(X)=>{if(b.const(G,m._`${Fb.default.vErrors}[${X}]`),b.if(m._`${G}.instancePath === undefined`,()=>b.assign(m._`${G}.instancePath`,(0,m.strConcat)(Fb.default.instancePath,q.errorPath))),b.assign(m._`${G}.schemaPath`,m.str`${q.errSchemaPath}/${w}`),q.opts.verbose)b.assign(m._`${G}.schema`,$),b.assign(m._`${G}.data`,W)})}VG.extendErrors=o5;function _G(b,w){let $=b.const("err",w);b.if(m._`${Fb.default.vErrors} === null`,()=>b.assign(Fb.default.vErrors,m._`[${$}]`),m._`${Fb.default.vErrors}.push(${$})`),b.code(m._`${Fb.default.errors}++`)}function jG(b,w){let{gen:$,validateName:W,schemaEnv:Q}=b;if(Q.$async)$.throw(m._`new ${b.ValidationError}(${w})`);else $.assign(m._`${W}.errors`,w),$.return(!1)}var uw={keyword:new m.Name("keyword"),schemaPath:new m.Name("schemaPath"),params:new m.Name("params"),propertyName:new m.Name("propertyName"),message:new m.Name("message"),schema:new m.Name("schema"),parentSchema:new m.Name("parentSchema")};function ZG(b,w,$){let{createErrors:W}=b.it;if(W===!1)return m._`{}`;return d5(b,w,$)}function d5(b,w,$={}){let{gen:W,it:Q}=b,q=[t5(Q,$),r5(b,$)];return e5(b,w,q),W.object(...q)}function t5({errorPath:b},{instancePath:w}){let $=w?m.str`${b}${(0,J$.getErrorPath)(w,J$.Type.Str)}`:b;return[Fb.default.instancePath,(0,m.strConcat)(Fb.default.instancePath,$)]}function r5({keyword:b,it:{errSchemaPath:w}},{schemaPath:$,parentSchema:W}){let Q=W?w:m.str`${w}/${b}`;if($)Q=m.str`${Q}${(0,J$.getErrorPath)($,J$.Type.Str)}`;return[uw.schemaPath,Q]}function e5(b,{params:w,message:$},W){let{keyword:Q,data:q,schemaValue:G,it:X}=b,{opts:Y,propertyName:J,topSchemaRef:D,schemaPath:H}=X;if(W.push([uw.keyword,Q],[uw.params,typeof w=="function"?w(b):w||m._`{}`]),Y.messages)W.push([uw.message,typeof $=="function"?$(b):$]);if(Y.verbose)W.push([uw.schema,G],[uw.parentSchema,m._`${D}${H}`],[Fb.default.data,q]);if(J)W.push([uw.propertyName,J])}});var RG=j((TG)=>{Object.defineProperty(TG,"__esModule",{value:!0});TG.boolOrEmptySchema=TG.topBoolOrEmptySchema=void 0;var $L=i1(),WL=y(),QL=Gw(),qL={message:"boolean schema is false"};function GL(b){let{gen:w,schema:$,validateName:W}=b;if($===!1)EG(b,!1);else if(typeof $=="object"&&$.$async===!0)w.return(QL.default.data);else w.assign(WL._`${W}.errors`,null),w.return(!0)}TG.topBoolOrEmptySchema=GL;function XL(b,w){let{gen:$,schema:W}=b;if(W===!1)$.var(w,!1),EG(b);else $.var(w,!0)}TG.boolOrEmptySchema=XL;function EG(b,w){let{gen:$,data:W}=b,Q={gen:$,keyword:"false schema",data:W,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:b};(0,$L.reportError)(Q,qL,void 0,w)}});var M6=j((vG)=>{Object.defineProperty(vG,"__esModule",{value:!0});vG.getRules=vG.isJSONType=void 0;var JL=["string","number","integer","boolean","null","object","array"],DL=new Set(JL);function HL(b){return typeof b=="string"&&DL.has(b)}vG.isJSONType=HL;function zL(){let b={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...b,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},b.number,b.string,b.array,b.object],post:{rules:[]},all:{},keywords:{}}}vG.getRules=zL});var I6=j((xG)=>{Object.defineProperty(xG,"__esModule",{value:!0});xG.shouldUseRule=xG.shouldUseGroup=xG.schemaHasRulesForType=void 0;function AL({schema:b,self:w},$){let W=w.RULES.types[$];return W&&W!==!0&&CG(b,W)}xG.schemaHasRulesForType=AL;function CG(b,w){return w.rules.some(($)=>uG(b,$))}xG.shouldUseGroup=CG;function uG(b,w){var $;return b[w.keyword]!==void 0||(($=w.definition.implements)===null||$===void 0?void 0:$.some((W)=>b[W]!==void 0))}xG.shouldUseRule=uG});var m1=j((nG)=>{Object.defineProperty(nG,"__esModule",{value:!0});nG.reportTypeError=nG.checkDataTypes=nG.checkDataType=nG.coerceAndCheckDataType=nG.getJSONTypes=nG.getSchemaTypes=nG.DataType=void 0;var PL=M6(),BL=I6(),FL=i1(),u=y(),hG=g(),ew;(function(b){b[b.Correct=0]="Correct",b[b.Wrong=1]="Wrong"})(ew||(nG.DataType=ew={}));function KL(b){let w=cG(b.type);if(w.includes("null")){if(b.nullable===!1)throw Error("type: null contradicts nullable: false")}else{if(!w.length&&b.nullable!==void 0)throw Error('"nullable" cannot be used without "type"');if(b.nullable===!0)w.push("null")}return w}nG.getSchemaTypes=KL;function cG(b){let w=Array.isArray(b)?b:b?[b]:[];if(w.every(PL.isJSONType))return w;throw Error("type must be JSONType or JSONType[]: "+w.join(","))}nG.getJSONTypes=cG;function ML(b,w){let{gen:$,data:W,opts:Q}=b,q=IL(w,Q.coerceTypes),G=w.length>0&&!(q.length===0&&w.length===1&&(0,BL.schemaHasRulesForType)(b,w[0]));if(G){let X=j6(w,W,Q.strictNumbers,ew.Wrong);$.if(X,()=>{if(q.length)_L(b,w,q);else Z6(b)})}return G}nG.coerceAndCheckDataType=ML;var fG=new Set(["string","number","integer","boolean","null"]);function IL(b,w){return w?b.filter(($)=>fG.has($)||w==="array"&&$==="array"):[]}function _L(b,w,$){let{gen:W,data:Q,opts:q}=b,G=W.let("dataType",u._`typeof ${Q}`),X=W.let("coerced",u._`undefined`);if(q.coerceTypes==="array")W.if(u._`${G} == 'object' && Array.isArray(${Q}) && ${Q}.length == 1`,()=>W.assign(Q,u._`${Q}[0]`).assign(G,u._`typeof ${Q}`).if(j6(w,Q,q.strictNumbers),()=>W.assign(X,Q)));W.if(u._`${X} !== undefined`);for(let J of $)if(fG.has(J)||J==="array"&&q.coerceTypes==="array")Y(J);W.else(),Z6(b),W.endIf(),W.if(u._`${X} !== undefined`,()=>{W.assign(Q,X),jL(b,X)});function Y(J){switch(J){case"string":W.elseIf(u._`${G} == "number" || ${G} == "boolean"`).assign(X,u._`"" + ${Q}`).elseIf(u._`${Q} === null`).assign(X,u._`""`);return;case"number":W.elseIf(u._`${G} == "boolean" || ${Q} === null
|
|
4
|
+
|| (${G} == "string" && ${Q} && ${Q} == +${Q})`).assign(X,u._`+${Q}`);return;case"integer":W.elseIf(u._`${G} === "boolean" || ${Q} === null
|
|
5
|
+
|| (${G} === "string" && ${Q} && ${Q} == +${Q} && !(${Q} % 1))`).assign(X,u._`+${Q}`);return;case"boolean":W.elseIf(u._`${Q} === "false" || ${Q} === 0 || ${Q} === null`).assign(X,!1).elseIf(u._`${Q} === "true" || ${Q} === 1`).assign(X,!0);return;case"null":W.elseIf(u._`${Q} === "" || ${Q} === 0 || ${Q} === false`),W.assign(X,null);return;case"array":W.elseIf(u._`${G} === "string" || ${G} === "number"
|
|
6
|
+
|| ${G} === "boolean" || ${Q} === null`).assign(X,u._`[${Q}]`)}}}function jL({gen:b,parentData:w,parentDataProperty:$},W){b.if(u._`${w} !== undefined`,()=>b.assign(u._`${w}[${$}]`,W))}function _6(b,w,$,W=ew.Correct){let Q=W===ew.Correct?u.operators.EQ:u.operators.NEQ,q;switch(b){case"null":return u._`${w} ${Q} null`;case"array":q=u._`Array.isArray(${w})`;break;case"object":q=u._`${w} && typeof ${w} == "object" && !Array.isArray(${w})`;break;case"integer":q=G(u._`!(${w} % 1) && !isNaN(${w})`);break;case"number":q=G();break;default:return u._`typeof ${w} ${Q} ${b}`}return W===ew.Correct?q:(0,u.not)(q);function G(X=u.nil){return(0,u.and)(u._`typeof ${w} == "number"`,X,$?u._`isFinite(${w})`:u.nil)}}nG.checkDataType=_6;function j6(b,w,$,W){if(b.length===1)return _6(b[0],w,$,W);let Q,q=(0,hG.toHash)(b);if(q.array&&q.object){let G=u._`typeof ${w} != "object"`;Q=q.null?G:u._`!${w} || ${G}`,delete q.null,delete q.array,delete q.object}else Q=u.nil;if(q.number)delete q.integer;for(let G in q)Q=(0,u.and)(Q,_6(G,w,$,W));return Q}nG.checkDataTypes=j6;var ZL={message:({schema:b})=>`must be ${b}`,params:({schema:b,schemaValue:w})=>typeof b=="string"?u._`{type: ${b}}`:u._`{type: ${w}}`};function Z6(b){let w=VL(b);(0,FL.reportError)(w,ZL)}nG.reportTypeError=Z6;function VL(b){let{gen:w,data:$,schema:W}=b,Q=(0,hG.schemaRefOrVal)(b,W,"type");return{gen:w,keyword:"type",data:$,schema:W.type,schemaCode:Q,schemaValue:Q,parentSchema:W,params:{},it:b}}});var pG=j((lG)=>{Object.defineProperty(lG,"__esModule",{value:!0});lG.assignDefaults=void 0;var sw=y(),kL=g();function CL(b,w){let{properties:$,items:W}=b.schema;if(w==="object"&&$)for(let Q in $)mG(b,Q,$[Q].default);else if(w==="array"&&Array.isArray(W))W.forEach((Q,q)=>mG(b,q,Q.default))}lG.assignDefaults=CL;function mG(b,w,$){let{gen:W,compositeRule:Q,data:q,opts:G}=b;if($===void 0)return;let X=sw._`${q}${(0,sw.getProperty)(w)}`;if(Q){(0,kL.checkStrictMode)(b,`default is ignored for: ${X}`);return}let Y=sw._`${X} === undefined`;if(G.useDefaults==="empty")Y=sw._`${Y} || ${X} === null || ${X} === ""`;W.if(Y,sw._`${X} = ${(0,sw.stringify)($)}`)}});var ub=j((tG)=>{Object.defineProperty(tG,"__esModule",{value:!0});tG.validateUnion=tG.validateArray=tG.usePattern=tG.callValidateCode=tG.schemaProperties=tG.allSchemaProperties=tG.noPropertyInData=tG.propertyInData=tG.isOwnProperty=tG.hasPropFunc=tG.reportMissingProp=tG.checkMissingProp=tG.checkReportMissingProp=void 0;var a=y(),V6=g(),Nw=Gw(),uL=g();function xL(b,w){let{gen:$,data:W,it:Q}=b;$.if(E6($,W,w,Q.opts.ownProperties),()=>{b.setParams({missingProperty:a._`${w}`},!0),b.error()})}tG.checkReportMissingProp=xL;function yL({gen:b,data:w,it:{opts:$}},W,Q){return(0,a.or)(...W.map((q)=>(0,a.and)(E6(b,w,q,$.ownProperties),a._`${Q} = ${q}`)))}tG.checkMissingProp=yL;function hL(b,w){b.setParams({missingProperty:w},!0),b.error()}tG.reportMissingProp=hL;function oG(b){return b.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:a._`Object.prototype.hasOwnProperty`})}tG.hasPropFunc=oG;function N6(b,w,$){return a._`${oG(b)}.call(${w}, ${$})`}tG.isOwnProperty=N6;function cL(b,w,$,W){let Q=a._`${w}${(0,a.getProperty)($)} !== undefined`;return W?a._`${Q} && ${N6(b,w,$)}`:Q}tG.propertyInData=cL;function E6(b,w,$,W){let Q=a._`${w}${(0,a.getProperty)($)} === undefined`;return W?(0,a.or)(Q,(0,a.not)(N6(b,w,$))):Q}tG.noPropertyInData=E6;function dG(b){return b?Object.keys(b).filter((w)=>w!=="__proto__"):[]}tG.allSchemaProperties=dG;function fL(b,w){return dG(w).filter(($)=>!(0,V6.alwaysValidSchema)(b,w[$]))}tG.schemaProperties=fL;function nL({schemaCode:b,data:w,it:{gen:$,topSchemaRef:W,schemaPath:Q,errorPath:q},it:G},X,Y,J){let D=J?a._`${b}, ${w}, ${W}${Q}`:w,H=[[Nw.default.instancePath,(0,a.strConcat)(Nw.default.instancePath,q)],[Nw.default.parentData,G.parentData],[Nw.default.parentDataProperty,G.parentDataProperty],[Nw.default.rootData,Nw.default.rootData]];if(G.opts.dynamicRef)H.push([Nw.default.dynamicAnchors,Nw.default.dynamicAnchors]);let O=a._`${D}, ${$.object(...H)}`;return Y!==a.nil?a._`${X}.call(${Y}, ${O})`:a._`${X}(${O})`}tG.callValidateCode=nL;var iL=a._`new RegExp`;function mL({gen:b,it:{opts:w}},$){let W=w.unicodeRegExp?"u":"",{regExp:Q}=w.code,q=Q($,W);return b.scopeValue("pattern",{key:q.toString(),ref:q,code:a._`${Q.code==="new RegExp"?iL:(0,uL.useFunc)(b,Q)}(${$}, ${W})`})}tG.usePattern=mL;function lL(b){let{gen:w,data:$,keyword:W,it:Q}=b,q=w.name("valid");if(Q.allErrors){let X=w.let("valid",!0);return G(()=>w.assign(X,!1)),X}return w.var(q,!0),G(()=>w.break()),q;function G(X){let Y=w.const("len",a._`${$}.length`);w.forRange("i",0,Y,(J)=>{b.subschema({keyword:W,dataProp:J,dataPropType:V6.Type.Num},q),w.if((0,a.not)(q),X)})}}tG.validateArray=lL;function gL(b){let{gen:w,schema:$,keyword:W,it:Q}=b;if(!Array.isArray($))throw Error("ajv implementation error");if($.some((Y)=>(0,V6.alwaysValidSchema)(Q,Y))&&!Q.opts.unevaluated)return;let G=w.let("valid",!1),X=w.name("_valid");w.block(()=>$.forEach((Y,J)=>{let D=b.subschema({keyword:W,schemaProp:J,compositeRule:!0},X);if(w.assign(G,a._`${G} || ${X}`),!b.mergeValidEvaluated(D,X))w.if((0,a.not)(G))})),b.result(G,()=>b.reset(),()=>b.error(!0))}tG.validateUnion=gL});var wX=j((aG)=>{Object.defineProperty(aG,"__esModule",{value:!0});aG.validateKeywordUsage=aG.validSchemaType=aG.funcKeywordCode=aG.macroKeywordCode=void 0;var Kb=y(),xw=Gw(),QU=ub(),qU=i1();function GU(b,w){let{gen:$,keyword:W,schema:Q,parentSchema:q,it:G}=b,X=w.macro.call(G.self,Q,q,G),Y=sG($,W,X);if(G.opts.validateSchema!==!1)G.self.validateSchema(X,!0);let J=$.name("valid");b.subschema({schema:X,schemaPath:Kb.nil,errSchemaPath:`${G.errSchemaPath}/${W}`,topSchemaRef:Y,compositeRule:!0},J),b.pass(J,()=>b.error(!0))}aG.macroKeywordCode=GU;function XU(b,w){var $;let{gen:W,keyword:Q,schema:q,parentSchema:G,$data:X,it:Y}=b;JU(Y,w);let J=!X&&w.compile?w.compile.call(Y.self,q,G,Y):w.validate,D=sG(W,Q,J),H=W.let("valid");b.block$data(H,O),b.ok(($=w.valid)!==null&&$!==void 0?$:H);function O(){if(w.errors===!1){if(K(),w.modifying)eG(b);_(()=>b.error())}else{let I=w.async?A():B();if(w.modifying)eG(b);_(()=>YU(b,I))}}function A(){let I=W.let("ruleErrs",null);return W.try(()=>K(Kb._`await `),(R)=>W.assign(H,!1).if(Kb._`${R} instanceof ${Y.ValidationError}`,()=>W.assign(I,Kb._`${R}.errors`),()=>W.throw(R))),I}function B(){let I=Kb._`${D}.errors`;return W.assign(I,null),K(Kb.nil),I}function K(I=w.async?Kb._`await `:Kb.nil){let R=Y.opts.passContext?xw.default.this:xw.default.self,T=!(("compile"in w)&&!X||w.schema===!1);W.assign(H,Kb._`${I}${(0,QU.callValidateCode)(b,D,R,T)}`,w.modifying)}function _(I){var R;W.if((0,Kb.not)((R=w.valid)!==null&&R!==void 0?R:H),I)}}aG.funcKeywordCode=XU;function eG(b){let{gen:w,data:$,it:W}=b;w.if(W.parentData,()=>w.assign($,Kb._`${W.parentData}[${W.parentDataProperty}]`))}function YU(b,w){let{gen:$}=b;$.if(Kb._`Array.isArray(${w})`,()=>{$.assign(xw.default.vErrors,Kb._`${xw.default.vErrors} === null ? ${w} : ${xw.default.vErrors}.concat(${w})`).assign(xw.default.errors,Kb._`${xw.default.vErrors}.length`),(0,qU.extendErrors)(b)},()=>b.error())}function JU({schemaEnv:b},w){if(w.async&&!b.$async)throw Error("async keyword in sync schema")}function sG(b,w,$){if($===void 0)throw Error(`keyword "${w}" failed to compile`);return b.scopeValue("keyword",typeof $=="function"?{ref:$}:{ref:$,code:(0,Kb.stringify)($)})}function DU(b,w,$=!1){return!w.length||w.some((W)=>W==="array"?Array.isArray(b):W==="object"?b&&typeof b=="object"&&!Array.isArray(b):typeof b==W||$&&typeof b>"u")}aG.validSchemaType=DU;function HU({schema:b,opts:w,self:$,errSchemaPath:W},Q,q){if(Array.isArray(Q.keyword)?!Q.keyword.includes(q):Q.keyword!==q)throw Error("ajv implementation error");let G=Q.dependencies;if(G===null||G===void 0?void 0:G.some((X)=>!Object.prototype.hasOwnProperty.call(b,X)))throw Error(`parent schema must have dependencies of ${q}: ${G.join(",")}`);if(Q.validateSchema){if(!Q.validateSchema(b[q])){let Y=`keyword "${q}" value is invalid at path "${W}": `+$.errorsText(Q.validateSchema.errors);if(w.validateSchema==="log")$.logger.error(Y);else throw Error(Y)}}}aG.validateKeywordUsage=HU});var qX=j((WX)=>{Object.defineProperty(WX,"__esModule",{value:!0});WX.extendSubschemaMode=WX.extendSubschemaData=WX.getSubschema=void 0;var tb=y(),$X=g();function LU(b,{keyword:w,schemaProp:$,schema:W,schemaPath:Q,errSchemaPath:q,topSchemaRef:G}){if(w!==void 0&&W!==void 0)throw Error('both "keyword" and "schema" passed, only one allowed');if(w!==void 0){let X=b.schema[w];return $===void 0?{schema:X,schemaPath:tb._`${b.schemaPath}${(0,tb.getProperty)(w)}`,errSchemaPath:`${b.errSchemaPath}/${w}`}:{schema:X[$],schemaPath:tb._`${b.schemaPath}${(0,tb.getProperty)(w)}${(0,tb.getProperty)($)}`,errSchemaPath:`${b.errSchemaPath}/${w}/${(0,$X.escapeFragment)($)}`}}if(W!==void 0){if(Q===void 0||q===void 0||G===void 0)throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:W,schemaPath:Q,topSchemaRef:G,errSchemaPath:q}}throw Error('either "keyword" or "schema" must be passed')}WX.getSubschema=LU;function UU(b,w,{dataProp:$,dataPropType:W,data:Q,dataTypes:q,propertyName:G}){if(Q!==void 0&&$!==void 0)throw Error('both "data" and "dataProp" passed, only one allowed');let{gen:X}=w;if($!==void 0){let{errorPath:J,dataPathArr:D,opts:H}=w,O=X.let("data",tb._`${w.data}${(0,tb.getProperty)($)}`,!0);Y(O),b.errorPath=tb.str`${J}${(0,$X.getErrorPath)($,W,H.jsPropertySyntax)}`,b.parentDataProperty=tb._`${$}`,b.dataPathArr=[...D,b.parentDataProperty]}if(Q!==void 0){let J=Q instanceof tb.Name?Q:X.let("data",Q,!0);if(Y(J),G!==void 0)b.propertyName=G}if(q)b.dataTypes=q;function Y(J){b.data=J,b.dataLevel=w.dataLevel+1,b.dataTypes=[],w.definedProperties=new Set,b.parentData=w.data,b.dataNames=[...w.dataNames,J]}}WX.extendSubschemaData=UU;function PU(b,{jtdDiscriminator:w,jtdMetadata:$,compositeRule:W,createErrors:Q,allErrors:q}){if(W!==void 0)b.compositeRule=W;if(Q!==void 0)b.createErrors=Q;if(q!==void 0)b.allErrors=q;b.jtdDiscriminator=w,b.jtdMetadata=$}WX.extendSubschemaMode=PU});var T6=j((AE,GX)=>{GX.exports=function b(w,$){if(w===$)return!0;if(w&&$&&typeof w=="object"&&typeof $=="object"){if(w.constructor!==$.constructor)return!1;var W,Q,q;if(Array.isArray(w)){if(W=w.length,W!=$.length)return!1;for(Q=W;Q--!==0;)if(!b(w[Q],$[Q]))return!1;return!0}if(w.constructor===RegExp)return w.source===$.source&&w.flags===$.flags;if(w.valueOf!==Object.prototype.valueOf)return w.valueOf()===$.valueOf();if(w.toString!==Object.prototype.toString)return w.toString()===$.toString();if(q=Object.keys(w),W=q.length,W!==Object.keys($).length)return!1;for(Q=W;Q--!==0;)if(!Object.prototype.hasOwnProperty.call($,q[Q]))return!1;for(Q=W;Q--!==0;){var G=q[Q];if(!b(w[G],$[G]))return!1}return!0}return w!==w&&$!==$}});var YX=j((LE,XX)=>{var Ew=XX.exports=function(b,w,$){if(typeof w=="function")$=w,w={};$=w.cb||$;var W=typeof $=="function"?$:$.pre||function(){},Q=$.post||function(){};D$(w,W,Q,b,"",b)};Ew.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Ew.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Ew.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Ew.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function D$(b,w,$,W,Q,q,G,X,Y,J){if(W&&typeof W=="object"&&!Array.isArray(W)){w(W,Q,q,G,X,Y,J);for(var D in W){var H=W[D];if(Array.isArray(H)){if(D in Ew.arrayKeywords)for(var O=0;O<H.length;O++)D$(b,w,$,H[O],Q+"/"+D+"/"+O,q,Q,D,W,O)}else if(D in Ew.propsKeywords){if(H&&typeof H=="object")for(var A in H)D$(b,w,$,H[A],Q+"/"+D+"/"+KU(A),q,Q,D,W,A)}else if(D in Ew.keywords||b.allKeys&&!(D in Ew.skipKeywords))D$(b,w,$,H,Q+"/"+D,q,Q,D,W)}$(W,Q,q,G,X,Y,J)}}function KU(b){return b.replace(/~/g,"~0").replace(/\//g,"~1")}});var l1=j((zX)=>{Object.defineProperty(zX,"__esModule",{value:!0});zX.getSchemaRefs=zX.resolveUrl=zX.normalizeId=zX._getFullPath=zX.getFullPath=zX.inlineRef=void 0;var MU=g(),IU=T6(),_U=YX(),jU=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function ZU(b,w=!0){if(typeof b=="boolean")return!0;if(w===!0)return!S6(b);if(!w)return!1;return JX(b)<=w}zX.inlineRef=ZU;var VU=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function S6(b){for(let w in b){if(VU.has(w))return!0;let $=b[w];if(Array.isArray($)&&$.some(S6))return!0;if(typeof $=="object"&&S6($))return!0}return!1}function JX(b){let w=0;for(let $ in b){if($==="$ref")return 1/0;if(w++,jU.has($))continue;if(typeof b[$]=="object")(0,MU.eachItem)(b[$],(W)=>w+=JX(W));if(w===1/0)return 1/0}return w}function DX(b,w="",$){if($!==!1)w=aw(w);let W=b.parse(w);return HX(b,W)}zX.getFullPath=DX;function HX(b,w){return b.serialize(w).split("#")[0]+"#"}zX._getFullPath=HX;var NU=/#\/?$/;function aw(b){return b?b.replace(NU,""):""}zX.normalizeId=aw;function EU(b,w,$){return $=aw($),b.resolve(w,$)}zX.resolveUrl=EU;var TU=/^[a-z_][-a-z0-9._]*$/i;function SU(b,w){if(typeof b=="boolean")return{};let{schemaId:$,uriResolver:W}=this.opts,Q=aw(b[$]||w),q={"":Q},G=DX(W,Q,!1),X={},Y=new Set;return _U(b,{allKeys:!0},(H,O,A,B)=>{if(B===void 0)return;let K=G+O,_=q[B];if(typeof H[$]=="string")_=I.call(this,H[$]);R.call(this,H.$anchor),R.call(this,H.$dynamicAnchor),q[O]=_;function I(T){let h=this.opts.uriResolver.resolve;if(T=aw(_?h(_,T):T),Y.has(T))throw D(T);Y.add(T);let v=this.refs[T];if(typeof v=="string")v=this.refs[v];if(typeof v=="object")J(H,v.schema,T);else if(T!==aw(K))if(T[0]==="#")J(H,X[T],T),X[T]=H;else this.refs[T]=K;return T}function R(T){if(typeof T=="string"){if(!TU.test(T))throw Error(`invalid anchor "${T}"`);I.call(this,`#${T}`)}}}),X;function J(H,O,A){if(O!==void 0&&!IU(H,O))throw D(A)}function D(H){return Error(`reference "${H}" resolves to more than one schema`)}}zX.getSchemaRefs=SU});var o1=j((EX)=>{Object.defineProperty(EX,"__esModule",{value:!0});EX.getData=EX.KeywordCxt=EX.validateFunctionCode=void 0;var BX=RG(),AX=m1(),v6=I6(),H$=m1(),xU=pG(),p1=wX(),R6=qX(),E=y(),C=Gw(),yU=l1(),Xw=g(),g1=i1();function hU(b){if(MX(b)){if(IX(b),KX(b)){nU(b);return}}FX(b,()=>(0,BX.topBoolOrEmptySchema)(b))}EX.validateFunctionCode=hU;function FX({gen:b,validateName:w,schema:$,schemaEnv:W,opts:Q},q){if(Q.code.es5)b.func(w,E._`${C.default.data}, ${C.default.valCxt}`,W.$async,()=>{b.code(E._`"use strict"; ${LX($,Q)}`),fU(b,Q),b.code(q)});else b.func(w,E._`${C.default.data}, ${cU(Q)}`,W.$async,()=>b.code(LX($,Q)).code(q))}function cU(b){return E._`{${C.default.instancePath}="", ${C.default.parentData}, ${C.default.parentDataProperty}, ${C.default.rootData}=${C.default.data}${b.dynamicRef?E._`, ${C.default.dynamicAnchors}={}`:E.nil}}={}`}function fU(b,w){b.if(C.default.valCxt,()=>{if(b.var(C.default.instancePath,E._`${C.default.valCxt}.${C.default.instancePath}`),b.var(C.default.parentData,E._`${C.default.valCxt}.${C.default.parentData}`),b.var(C.default.parentDataProperty,E._`${C.default.valCxt}.${C.default.parentDataProperty}`),b.var(C.default.rootData,E._`${C.default.valCxt}.${C.default.rootData}`),w.dynamicRef)b.var(C.default.dynamicAnchors,E._`${C.default.valCxt}.${C.default.dynamicAnchors}`)},()=>{if(b.var(C.default.instancePath,E._`""`),b.var(C.default.parentData,E._`undefined`),b.var(C.default.parentDataProperty,E._`undefined`),b.var(C.default.rootData,C.default.data),w.dynamicRef)b.var(C.default.dynamicAnchors,E._`{}`)})}function nU(b){let{schema:w,opts:$,gen:W}=b;FX(b,()=>{if($.$comment&&w.$comment)jX(b);if(pU(b),W.let(C.default.vErrors,null),W.let(C.default.errors,0),$.unevaluated)iU(b);_X(b),tU(b)});return}function iU(b){let{gen:w,validateName:$}=b;b.evaluated=w.const("evaluated",E._`${$}.evaluated`),w.if(E._`${b.evaluated}.dynamicProps`,()=>w.assign(E._`${b.evaluated}.props`,E._`undefined`)),w.if(E._`${b.evaluated}.dynamicItems`,()=>w.assign(E._`${b.evaluated}.items`,E._`undefined`))}function LX(b,w){let $=typeof b=="object"&&b[w.schemaId];return $&&(w.code.source||w.code.process)?E._`/*# sourceURL=${$} */`:E.nil}function mU(b,w){if(MX(b)){if(IX(b),KX(b)){lU(b,w);return}}(0,BX.boolOrEmptySchema)(b,w)}function KX({schema:b,self:w}){if(typeof b=="boolean")return!b;for(let $ in b)if(w.RULES.all[$])return!0;return!1}function MX(b){return typeof b.schema!="boolean"}function lU(b,w){let{schema:$,gen:W,opts:Q}=b;if(Q.$comment&&$.$comment)jX(b);oU(b),dU(b);let q=W.const("_errs",C.default.errors);_X(b,q),W.var(w,E._`${q} === ${C.default.errors}`)}function IX(b){(0,Xw.checkUnknownRules)(b),gU(b)}function _X(b,w){if(b.opts.jtd)return UX(b,[],!1,w);let $=(0,AX.getSchemaTypes)(b.schema),W=(0,AX.coerceAndCheckDataType)(b,$);UX(b,$,!W,w)}function gU(b){let{schema:w,errSchemaPath:$,opts:W,self:Q}=b;if(w.$ref&&W.ignoreKeywordsWithRef&&(0,Xw.schemaHasRulesButRef)(w,Q.RULES))Q.logger.warn(`$ref: keywords ignored in schema at path "${$}"`)}function pU(b){let{schema:w,opts:$}=b;if(w.default!==void 0&&$.useDefaults&&$.strictSchema)(0,Xw.checkStrictMode)(b,"default is ignored in the schema root")}function oU(b){let w=b.schema[b.opts.schemaId];if(w)b.baseId=(0,yU.resolveUrl)(b.opts.uriResolver,b.baseId,w)}function dU(b){if(b.schema.$async&&!b.schemaEnv.$async)throw Error("async schema in sync schema")}function jX({gen:b,schemaEnv:w,schema:$,errSchemaPath:W,opts:Q}){let q=$.$comment;if(Q.$comment===!0)b.code(E._`${C.default.self}.logger.log(${q})`);else if(typeof Q.$comment=="function"){let G=E.str`${W}/$comment`,X=b.scopeValue("root",{ref:w.root});b.code(E._`${C.default.self}.opts.$comment(${q}, ${G}, ${X}.schema)`)}}function tU(b){let{gen:w,schemaEnv:$,validateName:W,ValidationError:Q,opts:q}=b;if($.$async)w.if(E._`${C.default.errors} === 0`,()=>w.return(C.default.data),()=>w.throw(E._`new ${Q}(${C.default.vErrors})`));else{if(w.assign(E._`${W}.errors`,C.default.vErrors),q.unevaluated)rU(b);w.return(E._`${C.default.errors} === 0`)}}function rU({gen:b,evaluated:w,props:$,items:W}){if($ instanceof E.Name)b.assign(E._`${w}.props`,$);if(W instanceof E.Name)b.assign(E._`${w}.items`,W)}function UX(b,w,$,W){let{gen:Q,schema:q,data:G,allErrors:X,opts:Y,self:J}=b,{RULES:D}=J;if(q.$ref&&(Y.ignoreKeywordsWithRef||!(0,Xw.schemaHasRulesButRef)(q,D))){Q.block(()=>VX(b,"$ref",D.all.$ref.definition));return}if(!Y.jtd)eU(b,w);Q.block(()=>{for(let O of D.rules)H(O);H(D.post)});function H(O){if(!(0,v6.shouldUseGroup)(q,O))return;if(O.type){if(Q.if((0,H$.checkDataType)(O.type,G,Y.strictNumbers)),PX(b,O),w.length===1&&w[0]===O.type&&$)Q.else(),(0,H$.reportTypeError)(b);Q.endIf()}else PX(b,O);if(!X)Q.if(E._`${C.default.errors} === ${W||0}`)}}function PX(b,w){let{gen:$,schema:W,opts:{useDefaults:Q}}=b;if(Q)(0,xU.assignDefaults)(b,w.type);$.block(()=>{for(let q of w.rules)if((0,v6.shouldUseRule)(W,q))VX(b,q.keyword,q.definition,w.type)})}function eU(b,w){if(b.schemaEnv.meta||!b.opts.strictTypes)return;if(sU(b,w),!b.opts.allowUnionTypes)aU(b,w);bP(b,b.dataTypes)}function sU(b,w){if(!w.length)return;if(!b.dataTypes.length){b.dataTypes=w;return}w.forEach(($)=>{if(!ZX(b.dataTypes,$))k6(b,`type "${$}" not allowed by context "${b.dataTypes.join(",")}"`)}),$P(b,w)}function aU(b,w){if(w.length>1&&!(w.length===2&&w.includes("null")))k6(b,"use allowUnionTypes to allow union type keyword")}function bP(b,w){let $=b.self.RULES.all;for(let W in $){let Q=$[W];if(typeof Q=="object"&&(0,v6.shouldUseRule)(b.schema,Q)){let{type:q}=Q.definition;if(q.length&&!q.some((G)=>wP(w,G)))k6(b,`missing type "${q.join(",")}" for keyword "${W}"`)}}}function wP(b,w){return b.includes(w)||w==="number"&&b.includes("integer")}function ZX(b,w){return b.includes(w)||w==="integer"&&b.includes("number")}function $P(b,w){let $=[];for(let W of b.dataTypes)if(ZX(w,W))$.push(W);else if(w.includes("integer")&&W==="number")$.push("integer");b.dataTypes=$}function k6(b,w){let $=b.schemaEnv.baseId+b.errSchemaPath;w+=` at "${$}" (strictTypes)`,(0,Xw.checkStrictMode)(b,w,b.opts.strictTypes)}class C6{constructor(b,w,$){if((0,p1.validateKeywordUsage)(b,w,$),this.gen=b.gen,this.allErrors=b.allErrors,this.keyword=$,this.data=b.data,this.schema=b.schema[$],this.$data=w.$data&&b.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Xw.schemaRefOrVal)(b,this.schema,$,this.$data),this.schemaType=w.schemaType,this.parentSchema=b.schema,this.params={},this.it=b,this.def=w,this.$data)this.schemaCode=b.gen.const("vSchema",NX(this.$data,b));else if(this.schemaCode=this.schemaValue,!(0,p1.validSchemaType)(this.schema,w.schemaType,w.allowUndefined))throw Error(`${$} value must be ${JSON.stringify(w.schemaType)}`);if("code"in w?w.trackErrors:w.errors!==!1)this.errsCount=b.gen.const("_errs",C.default.errors)}result(b,w,$){this.failResult((0,E.not)(b),w,$)}failResult(b,w,$){if(this.gen.if(b),$)$();else this.error();if(w){if(this.gen.else(),w(),this.allErrors)this.gen.endIf()}else if(this.allErrors)this.gen.endIf();else this.gen.else()}pass(b,w){this.failResult((0,E.not)(b),void 0,w)}fail(b){if(b===void 0){if(this.error(),!this.allErrors)this.gen.if(!1);return}if(this.gen.if(b),this.error(),this.allErrors)this.gen.endIf();else this.gen.else()}fail$data(b){if(!this.$data)return this.fail(b);let{schemaCode:w}=this;this.fail(E._`${w} !== undefined && (${(0,E.or)(this.invalid$data(),b)})`)}error(b,w,$){if(w){this.setParams(w),this._error(b,$),this.setParams({});return}this._error(b,$)}_error(b,w){(b?g1.reportExtraError:g1.reportError)(this,this.def.error,w)}$dataError(){(0,g1.reportError)(this,this.def.$dataError||g1.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error('add "trackErrors" to keyword definition');(0,g1.resetErrorsCount)(this.gen,this.errsCount)}ok(b){if(!this.allErrors)this.gen.if(b)}setParams(b,w){if(w)Object.assign(this.params,b);else this.params=b}block$data(b,w,$=E.nil){this.gen.block(()=>{this.check$data(b,$),w()})}check$data(b=E.nil,w=E.nil){if(!this.$data)return;let{gen:$,schemaCode:W,schemaType:Q,def:q}=this;if($.if((0,E.or)(E._`${W} === undefined`,w)),b!==E.nil)$.assign(b,!0);if(Q.length||q.validateSchema){if($.elseIf(this.invalid$data()),this.$dataError(),b!==E.nil)$.assign(b,!1)}$.else()}invalid$data(){let{gen:b,schemaCode:w,schemaType:$,def:W,it:Q}=this;return(0,E.or)(q(),G());function q(){if($.length){if(!(w instanceof E.Name))throw Error("ajv implementation error");let X=Array.isArray($)?$:[$];return E._`${(0,H$.checkDataTypes)(X,w,Q.opts.strictNumbers,H$.DataType.Wrong)}`}return E.nil}function G(){if(W.validateSchema){let X=b.scopeValue("validate$data",{ref:W.validateSchema});return E._`!${X}(${w})`}return E.nil}}subschema(b,w){let $=(0,R6.getSubschema)(this.it,b);(0,R6.extendSubschemaData)($,this.it,b),(0,R6.extendSubschemaMode)($,b);let W={...this.it,...$,items:void 0,props:void 0};return mU(W,w),W}mergeEvaluated(b,w){let{it:$,gen:W}=this;if(!$.opts.unevaluated)return;if($.props!==!0&&b.props!==void 0)$.props=Xw.mergeEvaluated.props(W,b.props,$.props,w);if($.items!==!0&&b.items!==void 0)$.items=Xw.mergeEvaluated.items(W,b.items,$.items,w)}mergeValidEvaluated(b,w){let{it:$,gen:W}=this;if($.opts.unevaluated&&($.props!==!0||$.items!==!0))return W.if(w,()=>this.mergeEvaluated(b,E.Name)),!0}}EX.KeywordCxt=C6;function VX(b,w,$,W){let Q=new C6(b,$,w);if("code"in $)$.code(Q,W);else if(Q.$data&&$.validate)(0,p1.funcKeywordCode)(Q,$);else if("macro"in $)(0,p1.macroKeywordCode)(Q,$);else if($.compile||$.validate)(0,p1.funcKeywordCode)(Q,$)}var WP=/^\/(?:[^~]|~0|~1)*$/,QP=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function NX(b,{dataLevel:w,dataNames:$,dataPathArr:W}){let Q,q;if(b==="")return C.default.rootData;if(b[0]==="/"){if(!WP.test(b))throw Error(`Invalid JSON-pointer: ${b}`);Q=b,q=C.default.rootData}else{let J=QP.exec(b);if(!J)throw Error(`Invalid JSON-pointer: ${b}`);let D=+J[1];if(Q=J[2],Q==="#"){if(D>=w)throw Error(Y("property/index",D));return W[w-D]}if(D>w)throw Error(Y("data",D));if(q=$[w-D],!Q)return q}let G=q,X=Q.split("/");for(let J of X)if(J)q=E._`${q}${(0,E.getProperty)((0,Xw.unescapeJsonPointer)(J))}`,G=E._`${G} && ${q}`;return G;function Y(J,D){return`Cannot access ${J} ${D} levels up, current level is ${w}`}}EX.getData=NX});var z$=j((RX)=>{Object.defineProperty(RX,"__esModule",{value:!0});class SX extends Error{constructor(b){super("validation failed");this.errors=b,this.ajv=this.validation=!0}}RX.default=SX});var d1=j((kX)=>{Object.defineProperty(kX,"__esModule",{value:!0});var u6=l1();class vX extends Error{constructor(b,w,$,W){super(W||`can't resolve reference ${$} from id ${w}`);this.missingRef=(0,u6.resolveUrl)(b,w,$),this.missingSchema=(0,u6.normalizeId)((0,u6.getFullPath)(b,this.missingRef))}}kX.default=vX});var A$=j((xX)=>{Object.defineProperty(xX,"__esModule",{value:!0});xX.resolveSchema=xX.getCompilingSchema=xX.resolveRef=xX.compileSchema=xX.SchemaEnv=void 0;var nb=y(),JP=z$(),yw=Gw(),ib=l1(),CX=g(),DP=o1();class t1{constructor(b){var w;this.refs={},this.dynamicAnchors={};let $;if(typeof b.schema=="object")$=b.schema;this.schema=b.schema,this.schemaId=b.schemaId,this.root=b.root||this,this.baseId=(w=b.baseId)!==null&&w!==void 0?w:(0,ib.normalizeId)($===null||$===void 0?void 0:$[b.schemaId||"$id"]),this.schemaPath=b.schemaPath,this.localRefs=b.localRefs,this.meta=b.meta,this.$async=$===null||$===void 0?void 0:$.$async,this.refs={}}}xX.SchemaEnv=t1;function y6(b){let w=uX.call(this,b);if(w)return w;let $=(0,ib.getFullPath)(this.opts.uriResolver,b.root.baseId),{es5:W,lines:Q}=this.opts.code,{ownProperties:q}=this.opts,G=new nb.CodeGen(this.scope,{es5:W,lines:Q,ownProperties:q}),X;if(b.$async)X=G.scopeValue("Error",{ref:JP.default,code:nb._`require("ajv/dist/runtime/validation_error").default`});let Y=G.scopeName("validate");b.validateName=Y;let J={gen:G,allErrors:this.opts.allErrors,data:yw.default.data,parentData:yw.default.parentData,parentDataProperty:yw.default.parentDataProperty,dataNames:[yw.default.data],dataPathArr:[nb.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:G.scopeValue("schema",this.opts.code.source===!0?{ref:b.schema,code:(0,nb.stringify)(b.schema)}:{ref:b.schema}),validateName:Y,ValidationError:X,schema:b.schema,schemaEnv:b,rootId:$,baseId:b.baseId||$,schemaPath:nb.nil,errSchemaPath:b.schemaPath||(this.opts.jtd?"":"#"),errorPath:nb._`""`,opts:this.opts,self:this},D;try{this._compilations.add(b),(0,DP.validateFunctionCode)(J),G.optimize(this.opts.code.optimize);let H=G.toString();if(D=`${G.scopeRefs(yw.default.scope)}return ${H}`,this.opts.code.process)D=this.opts.code.process(D,b);let A=Function(`${yw.default.self}`,`${yw.default.scope}`,D)(this,this.scope.get());if(this.scope.value(Y,{ref:A}),A.errors=null,A.schema=b.schema,A.schemaEnv=b,b.$async)A.$async=!0;if(this.opts.code.source===!0)A.source={validateName:Y,validateCode:H,scopeValues:G._values};if(this.opts.unevaluated){let{props:B,items:K}=J;if(A.evaluated={props:B instanceof nb.Name?void 0:B,items:K instanceof nb.Name?void 0:K,dynamicProps:B instanceof nb.Name,dynamicItems:K instanceof nb.Name},A.source)A.source.evaluated=(0,nb.stringify)(A.evaluated)}return b.validate=A,b}catch(H){if(delete b.validate,delete b.validateName,D)this.logger.error("Error compiling schema, function code:",D);throw H}finally{this._compilations.delete(b)}}xX.compileSchema=y6;function HP(b,w,$){var W;$=(0,ib.resolveUrl)(this.opts.uriResolver,w,$);let Q=b.refs[$];if(Q)return Q;let q=AP.call(this,b,$);if(q===void 0){let G=(W=b.localRefs)===null||W===void 0?void 0:W[$],{schemaId:X}=this.opts;if(G)q=new t1({schema:G,schemaId:X,root:b,baseId:w})}if(q===void 0)return;return b.refs[$]=zP.call(this,q)}xX.resolveRef=HP;function zP(b){if((0,ib.inlineRef)(b.schema,this.opts.inlineRefs))return b.schema;return b.validate?b:y6.call(this,b)}function uX(b){for(let w of this._compilations)if(OP(w,b))return w}xX.getCompilingSchema=uX;function OP(b,w){return b.schema===w.schema&&b.root===w.root&&b.baseId===w.baseId}function AP(b,w){let $;while(typeof($=this.refs[w])=="string")w=$;return $||this.schemas[w]||O$.call(this,b,w)}function O$(b,w){let $=this.opts.uriResolver.parse(w),W=(0,ib._getFullPath)(this.opts.uriResolver,$),Q=(0,ib.getFullPath)(this.opts.uriResolver,b.baseId,void 0);if(Object.keys(b.schema).length>0&&W===Q)return x6.call(this,$,b);let q=(0,ib.normalizeId)(W),G=this.refs[q]||this.schemas[q];if(typeof G=="string"){let X=O$.call(this,b,G);if(typeof(X===null||X===void 0?void 0:X.schema)!=="object")return;return x6.call(this,$,X)}if(typeof(G===null||G===void 0?void 0:G.schema)!=="object")return;if(!G.validate)y6.call(this,G);if(q===(0,ib.normalizeId)(w)){let{schema:X}=G,{schemaId:Y}=this.opts,J=X[Y];if(J)Q=(0,ib.resolveUrl)(this.opts.uriResolver,Q,J);return new t1({schema:X,schemaId:Y,root:b,baseId:Q})}return x6.call(this,$,G)}xX.resolveSchema=O$;var LP=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function x6(b,{baseId:w,schema:$,root:W}){var Q;if(((Q=b.fragment)===null||Q===void 0?void 0:Q[0])!=="/")return;for(let X of b.fragment.slice(1).split("/")){if(typeof $==="boolean")return;let Y=$[(0,CX.unescapeFragment)(X)];if(Y===void 0)return;$=Y;let J=typeof $==="object"&&$[this.opts.schemaId];if(!LP.has(X)&&J)w=(0,ib.resolveUrl)(this.opts.uriResolver,w,J)}let q;if(typeof $!="boolean"&&$.$ref&&!(0,CX.schemaHasRulesButRef)($,this.RULES)){let X=(0,ib.resolveUrl)(this.opts.uriResolver,w,$.$ref);q=O$.call(this,W,X)}let{schemaId:G}=this.opts;if(q=q||new t1({schema:$,schemaId:G,root:W,baseId:w}),q.schema!==q.root.schema)return q;return}});var hX=j((ME,KP)=>{KP.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var c6=j((IE,iX)=>{var MP=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),fX=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 h6(b){let w="",$=0,W=0;for(W=0;W<b.length;W++){if($=b[W].charCodeAt(0),$===48)continue;if(!($>=48&&$<=57||$>=65&&$<=70||$>=97&&$<=102))return"";w+=b[W];break}for(W+=1;W<b.length;W++){if($=b[W].charCodeAt(0),!($>=48&&$<=57||$>=65&&$<=70||$>=97&&$<=102))return"";w+=b[W]}return w}var IP=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function cX(b){return b.length=0,!0}function _P(b,w,$){if(b.length){let W=h6(b);if(W!=="")w.push(W);else return $.error=!0,!1;b.length=0}return!0}function jP(b){let w=0,$={error:!1,address:"",zone:""},W=[],Q=[],q=!1,G=!1,X=_P;for(let Y=0;Y<b.length;Y++){let J=b[Y];if(J==="["||J==="]")continue;if(J===":"){if(q===!0)G=!0;if(!X(Q,W,$))break;if(++w>7){$.error=!0;break}if(Y>0&&b[Y-1]===":")q=!0;W.push(":");continue}else if(J==="%"){if(!X(Q,W,$))break;X=cX}else{Q.push(J);continue}}if(Q.length)if(X===cX)$.zone=Q.join("");else if(G)W.push(Q.join(""));else W.push(h6(Q));return $.address=W.join(""),$}function nX(b){if(ZP(b,":")<2)return{host:b,isIPV6:!1};let w=jP(b);if(!w.error){let{address:$,address:W}=w;if(w.zone)$+="%"+w.zone,W+="%25"+w.zone;return{host:$,isIPV6:!0,escapedHost:W}}else return{host:b,isIPV6:!1}}function ZP(b,w){let $=0;for(let W=0;W<b.length;W++)if(b[W]===w)$++;return $}function VP(b){let w=b,$=[],W=-1,Q=0;while(Q=w.length){if(Q===1)if(w===".")break;else if(w==="/"){$.push("/");break}else{$.push(w);break}else if(Q===2){if(w[0]==="."){if(w[1]===".")break;else if(w[1]==="/"){w=w.slice(2);continue}}else if(w[0]==="/"){if(w[1]==="."||w[1]==="/"){$.push("/");break}}}else if(Q===3){if(w==="/.."){if($.length!==0)$.pop();$.push("/");break}}if(w[0]==="."){if(w[1]==="."){if(w[2]==="/"){w=w.slice(3);continue}}else if(w[1]==="/"){w=w.slice(2);continue}}else if(w[0]==="/"){if(w[1]==="."){if(w[2]==="/"){w=w.slice(2);continue}else if(w[2]==="."){if(w[3]==="/"){if(w=w.slice(3),$.length!==0)$.pop();continue}}}}if((W=w.indexOf("/",1))===-1){$.push(w);break}else $.push(w.slice(0,W)),w=w.slice(W)}return $.join("")}function NP(b,w){let $=w!==!0?escape:unescape;if(b.scheme!==void 0)b.scheme=$(b.scheme);if(b.userinfo!==void 0)b.userinfo=$(b.userinfo);if(b.host!==void 0)b.host=$(b.host);if(b.path!==void 0)b.path=$(b.path);if(b.query!==void 0)b.query=$(b.query);if(b.fragment!==void 0)b.fragment=$(b.fragment);return b}function EP(b){let w=[];if(b.userinfo!==void 0)w.push(b.userinfo),w.push("@");if(b.host!==void 0){let $=unescape(b.host);if(!fX($)){let W=nX($);if(W.isIPV6===!0)$=`[${W.escapedHost}]`;else $=b.host}w.push($)}if(typeof b.port==="number"||typeof b.port==="string")w.push(":"),w.push(String(b.port));return w.length?w.join(""):void 0}iX.exports={nonSimpleDomain:IP,recomposeAuthority:EP,normalizeComponentEncoding:NP,removeDotSegments:VP,isIPv4:fX,isUUID:MP,normalizeIPv6:nX,stringArrayToHexStripped:h6}});var oX=j((_E,pX)=>{var{isUUID:TP}=c6(),SP=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,RP=["http","https","ws","wss","urn","urn:uuid"];function vP(b){return RP.indexOf(b)!==-1}function f6(b){if(b.secure===!0)return!0;else if(b.secure===!1)return!1;else if(b.scheme)return b.scheme.length===3&&(b.scheme[0]==="w"||b.scheme[0]==="W")&&(b.scheme[1]==="s"||b.scheme[1]==="S")&&(b.scheme[2]==="s"||b.scheme[2]==="S");else return!1}function mX(b){if(!b.host)b.error=b.error||"HTTP URIs must have a host.";return b}function lX(b){let w=String(b.scheme).toLowerCase()==="https";if(b.port===(w?443:80)||b.port==="")b.port=void 0;if(!b.path)b.path="/";return b}function kP(b){return b.secure=f6(b),b.resourceName=(b.path||"/")+(b.query?"?"+b.query:""),b.path=void 0,b.query=void 0,b}function CP(b){if(b.port===(f6(b)?443:80)||b.port==="")b.port=void 0;if(typeof b.secure==="boolean")b.scheme=b.secure?"wss":"ws",b.secure=void 0;if(b.resourceName){let[w,$]=b.resourceName.split("?");b.path=w&&w!=="/"?w:void 0,b.query=$,b.resourceName=void 0}return b.fragment=void 0,b}function uP(b,w){if(!b.path)return b.error="URN can not be parsed",b;let $=b.path.match(SP);if($){let W=w.scheme||b.scheme||"urn";b.nid=$[1].toLowerCase(),b.nss=$[2];let Q=`${W}:${w.nid||b.nid}`,q=n6(Q);if(b.path=void 0,q)b=q.parse(b,w)}else b.error=b.error||"URN can not be parsed.";return b}function xP(b,w){if(b.nid===void 0)throw Error("URN without nid cannot be serialized");let $=w.scheme||b.scheme||"urn",W=b.nid.toLowerCase(),Q=`${$}:${w.nid||W}`,q=n6(Q);if(q)b=q.serialize(b,w);let G=b,X=b.nss;return G.path=`${W||w.nid}:${X}`,w.skipEscape=!0,G}function yP(b,w){let $=b;if($.uuid=$.nss,$.nss=void 0,!w.tolerant&&(!$.uuid||!TP($.uuid)))$.error=$.error||"UUID is not valid.";return $}function hP(b){let w=b;return w.nss=(b.uuid||"").toLowerCase(),w}var gX={scheme:"http",domainHost:!0,parse:mX,serialize:lX},cP={scheme:"https",domainHost:gX.domainHost,parse:mX,serialize:lX},L$={scheme:"ws",domainHost:!0,parse:kP,serialize:CP},fP={scheme:"wss",domainHost:L$.domainHost,parse:L$.parse,serialize:L$.serialize},nP={scheme:"urn",parse:uP,serialize:xP,skipNormalize:!0},iP={scheme:"urn:uuid",parse:yP,serialize:hP,skipNormalize:!0},U$={http:gX,https:cP,ws:L$,wss:fP,urn:nP,"urn:uuid":iP};Object.setPrototypeOf(U$,null);function n6(b){return b&&(U$[b]||U$[b.toLowerCase()])||void 0}pX.exports={wsIsSecure:f6,SCHEMES:U$,isValidSchemeName:vP,getSchemeHandler:n6}});var rX=j((jE,B$)=>{var{normalizeIPv6:mP,removeDotSegments:r1,recomposeAuthority:lP,normalizeComponentEncoding:P$,isIPv4:gP,nonSimpleDomain:pP}=c6(),{SCHEMES:oP,getSchemeHandler:dX}=oX();function dP(b,w){if(typeof b==="string")b=rb(Yw(b,w),w);else if(typeof b==="object")b=Yw(rb(b,w),w);return b}function tP(b,w,$){let W=$?Object.assign({scheme:"null"},$):{scheme:"null"},Q=tX(Yw(b,W),Yw(w,W),W,!0);return W.skipEscape=!0,rb(Q,W)}function tX(b,w,$,W){let Q={};if(!W)b=Yw(rb(b,$),$),w=Yw(rb(w,$),$);if($=$||{},!$.tolerant&&w.scheme)Q.scheme=w.scheme,Q.userinfo=w.userinfo,Q.host=w.host,Q.port=w.port,Q.path=r1(w.path||""),Q.query=w.query;else{if(w.userinfo!==void 0||w.host!==void 0||w.port!==void 0)Q.userinfo=w.userinfo,Q.host=w.host,Q.port=w.port,Q.path=r1(w.path||""),Q.query=w.query;else{if(!w.path)if(Q.path=b.path,w.query!==void 0)Q.query=w.query;else Q.query=b.query;else{if(w.path[0]==="/")Q.path=r1(w.path);else{if((b.userinfo!==void 0||b.host!==void 0||b.port!==void 0)&&!b.path)Q.path="/"+w.path;else if(!b.path)Q.path=w.path;else Q.path=b.path.slice(0,b.path.lastIndexOf("/")+1)+w.path;Q.path=r1(Q.path)}Q.query=w.query}Q.userinfo=b.userinfo,Q.host=b.host,Q.port=b.port}Q.scheme=b.scheme}return Q.fragment=w.fragment,Q}function rP(b,w,$){if(typeof b==="string")b=unescape(b),b=rb(P$(Yw(b,$),!0),{...$,skipEscape:!0});else if(typeof b==="object")b=rb(P$(b,!0),{...$,skipEscape:!0});if(typeof w==="string")w=unescape(w),w=rb(P$(Yw(w,$),!0),{...$,skipEscape:!0});else if(typeof w==="object")w=rb(P$(w,!0),{...$,skipEscape:!0});return b.toLowerCase()===w.toLowerCase()}function rb(b,w){let $={host:b.host,scheme:b.scheme,userinfo:b.userinfo,port:b.port,path:b.path,query:b.query,nid:b.nid,nss:b.nss,uuid:b.uuid,fragment:b.fragment,reference:b.reference,resourceName:b.resourceName,secure:b.secure,error:""},W=Object.assign({},w),Q=[],q=dX(W.scheme||$.scheme);if(q&&q.serialize)q.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 G=lP($);if(G!==void 0){if(W.reference!=="suffix")Q.push("//");if(Q.push(G),$.path&&$.path[0]!=="/")Q.push("/")}if($.path!==void 0){let X=$.path;if(!W.absolutePath&&(!q||!q.absolutePath))X=r1(X);if(G===void 0&&X[0]==="/"&&X[1]==="/")X="/%2F"+X.slice(2);Q.push(X)}if($.query!==void 0)Q.push("?",$.query);if($.fragment!==void 0)Q.push("#",$.fragment);return Q.join("")}var eP=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function Yw(b,w){let $=Object.assign({},w),W={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},Q=!1;if($.reference==="suffix")if($.scheme)b=$.scheme+":"+b;else b="//"+b;let q=b.match(eP);if(q){if(W.scheme=q[1],W.userinfo=q[3],W.host=q[4],W.port=parseInt(q[5],10),W.path=q[6]||"",W.query=q[7],W.fragment=q[8],isNaN(W.port))W.port=q[5];if(W.host)if(gP(W.host)===!1){let Y=mP(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 G=dX($.scheme||W.scheme);if(!$.unicodeSupport&&(!G||!G.unicodeSupport)){if(W.host&&($.domainHost||G&&G.domainHost)&&Q===!1&&pP(W.host))try{W.host=URL.domainToASCII(W.host.toLowerCase())}catch(X){W.error=W.error||"Host's domain name can not be converted to ASCII: "+X}}if(!G||G&&!G.skipNormalize){if(b.indexOf("%")!==-1){if(W.scheme!==void 0)W.scheme=unescape(W.scheme);if(W.host!==void 0)W.host=unescape(W.host)}if(W.path)W.path=escape(unescape(W.path));if(W.fragment)W.fragment=encodeURI(decodeURIComponent(W.fragment))}if(G&&G.parse)G.parse(W,$)}else W.error=W.error||"URI can not be parsed.";return W}var i6={SCHEMES:oP,normalize:dP,resolve:tP,resolveComponent:tX,equal:rP,serialize:rb,parse:Yw};B$.exports=i6;B$.exports.default=i6;B$.exports.fastUri=i6});var aX=j((sX)=>{Object.defineProperty(sX,"__esModule",{value:!0});var eX=rX();eX.code='require("ajv/dist/runtime/uri").default';sX.default=eX});var XY=j((Jw)=>{Object.defineProperty(Jw,"__esModule",{value:!0});Jw.CodeGen=Jw.Name=Jw.nil=Jw.stringify=Jw.str=Jw._=Jw.KeywordCxt=void 0;var aP=o1();Object.defineProperty(Jw,"KeywordCxt",{enumerable:!0,get:function(){return aP.KeywordCxt}});var b1=y();Object.defineProperty(Jw,"_",{enumerable:!0,get:function(){return b1._}});Object.defineProperty(Jw,"str",{enumerable:!0,get:function(){return b1.str}});Object.defineProperty(Jw,"stringify",{enumerable:!0,get:function(){return b1.stringify}});Object.defineProperty(Jw,"nil",{enumerable:!0,get:function(){return b1.nil}});Object.defineProperty(Jw,"Name",{enumerable:!0,get:function(){return b1.Name}});Object.defineProperty(Jw,"CodeGen",{enumerable:!0,get:function(){return b1.CodeGen}});var b3=z$(),QY=d1(),w3=M6(),e1=A$(),$3=y(),s1=l1(),F$=m1(),l6=g(),bY=hX(),W3=aX(),qY=(b,w)=>new RegExp(b,w);qY.code="new RegExp";var Q3=["removeAdditional","useDefaults","coerceTypes"],q3=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),G3={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},X3={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},wY=200;function Y3(b){var w,$,W,Q,q,G,X,Y,J,D,H,O,A,B,K,_,I,R,T,h,v,ob,bw,e$,s$;let z1=b.strict,a$=(w=b.code)===null||w===void 0?void 0:w.optimize,mW=a$===!0||a$===void 0?1:a$||0,lW=(W=($=b.code)===null||$===void 0?void 0:$.regExp)!==null&&W!==void 0?W:qY,qz=(Q=b.uriResolver)!==null&&Q!==void 0?Q:W3.default;return{strictSchema:(G=(q=b.strictSchema)!==null&&q!==void 0?q:z1)!==null&&G!==void 0?G:!0,strictNumbers:(Y=(X=b.strictNumbers)!==null&&X!==void 0?X:z1)!==null&&Y!==void 0?Y:!0,strictTypes:(D=(J=b.strictTypes)!==null&&J!==void 0?J:z1)!==null&&D!==void 0?D:"log",strictTuples:(O=(H=b.strictTuples)!==null&&H!==void 0?H:z1)!==null&&O!==void 0?O:"log",strictRequired:(B=(A=b.strictRequired)!==null&&A!==void 0?A:z1)!==null&&B!==void 0?B:!1,code:b.code?{...b.code,optimize:mW,regExp:lW}:{optimize:mW,regExp:lW},loopRequired:(K=b.loopRequired)!==null&&K!==void 0?K:wY,loopEnum:(_=b.loopEnum)!==null&&_!==void 0?_:wY,meta:(I=b.meta)!==null&&I!==void 0?I:!0,messages:(R=b.messages)!==null&&R!==void 0?R:!0,inlineRefs:(T=b.inlineRefs)!==null&&T!==void 0?T:!0,schemaId:(h=b.schemaId)!==null&&h!==void 0?h:"$id",addUsedSchema:(v=b.addUsedSchema)!==null&&v!==void 0?v:!0,validateSchema:(ob=b.validateSchema)!==null&&ob!==void 0?ob:!0,validateFormats:(bw=b.validateFormats)!==null&&bw!==void 0?bw:!0,unicodeRegExp:(e$=b.unicodeRegExp)!==null&&e$!==void 0?e$:!0,int32range:(s$=b.int32range)!==null&&s$!==void 0?s$:!0,uriResolver:qz}}class K${constructor(b={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,b=this.opts={...b,...Y3(b)};let{es5:w,lines:$}=this.opts.code;this.scope=new $3.ValueScope({scope:{},prefixes:q3,es5:w,lines:$}),this.logger=A3(b.logger);let W=b.validateFormats;if(b.validateFormats=!1,this.RULES=(0,w3.getRules)(),$Y.call(this,G3,b,"NOT SUPPORTED"),$Y.call(this,X3,b,"DEPRECATED","warn"),this._metaOpts=z3.call(this),b.formats)D3.call(this);if(this._addVocabularies(),this._addDefaultMetaSchema(),b.keywords)H3.call(this,b.keywords);if(typeof b.meta=="object")this.addMetaSchema(b.meta);J3.call(this),b.validateFormats=W}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:b,meta:w,schemaId:$}=this.opts,W=bY;if($==="id")W={...bY},W.id=W.$id,delete W.$id;if(w&&b)this.addMetaSchema(W,W[$],!1)}defaultMeta(){let{meta:b,schemaId:w}=this.opts;return this.opts.defaultMeta=typeof b=="object"?b[w]||b:void 0}validate(b,w){let $;if(typeof b=="string"){if($=this.getSchema(b),!$)throw Error(`no schema with key or ref "${b}"`)}else $=this.compile(b);let W=$(w);if(!("$async"in $))this.errors=$.errors;return W}compile(b,w){let $=this._addSchema(b,w);return $.validate||this._compileSchemaEnv($)}compileAsync(b,w){if(typeof this.opts.loadSchema!="function")throw Error("options.loadSchema should be a function");let{loadSchema:$}=this.opts;return W.call(this,b,w);async function W(J,D){await Q.call(this,J.$schema);let H=this._addSchema(J,D);return H.validate||q.call(this,H)}async function Q(J){if(J&&!this.getSchema(J))await W.call(this,{$ref:J},!0)}async function q(J){try{return this._compileSchemaEnv(J)}catch(D){if(!(D instanceof QY.default))throw D;return G.call(this,D),await X.call(this,D.missingSchema),q.call(this,J)}}function G({missingSchema:J,missingRef:D}){if(this.refs[J])throw Error(`AnySchema ${J} is loaded but ${D} cannot be resolved`)}async function X(J){let D=await Y.call(this,J);if(!this.refs[J])await Q.call(this,D.$schema);if(!this.refs[J])this.addSchema(D,J,w)}async function Y(J){let D=this._loading[J];if(D)return D;try{return await(this._loading[J]=$(J))}finally{delete this._loading[J]}}}addSchema(b,w,$,W=this.opts.validateSchema){if(Array.isArray(b)){for(let q of b)this.addSchema(q,void 0,$,W);return this}let Q;if(typeof b==="object"){let{schemaId:q}=this.opts;if(Q=b[q],Q!==void 0&&typeof Q!="string")throw Error(`schema ${q} must be string`)}return w=(0,s1.normalizeId)(w||Q),this._checkUnique(w),this.schemas[w]=this._addSchema(b,$,w,W,!0),this}addMetaSchema(b,w,$=this.opts.validateSchema){return this.addSchema(b,w,!0,$),this}validateSchema(b,w){if(typeof b=="boolean")return!0;let $;if($=b.$schema,$!==void 0&&typeof $!="string")throw Error("$schema must be a string");if($=$||this.opts.defaultMeta||this.defaultMeta(),!$)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let W=this.validate($,b);if(!W&&w){let Q="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(Q);else throw Error(Q)}return W}getSchema(b){let w;while(typeof(w=WY.call(this,b))=="string")b=w;if(w===void 0){let{schemaId:$}=this.opts,W=new e1.SchemaEnv({schema:{},schemaId:$});if(w=e1.resolveSchema.call(this,W,b),!w)return;this.refs[b]=w}return w.validate||this._compileSchemaEnv(w)}removeSchema(b){if(b instanceof RegExp)return this._removeAllSchemas(this.schemas,b),this._removeAllSchemas(this.refs,b),this;switch(typeof b){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let w=WY.call(this,b);if(typeof w=="object")this._cache.delete(w.schema);return delete this.schemas[b],delete this.refs[b],this}case"object":{let w=b;this._cache.delete(w);let $=b[this.opts.schemaId];if($)$=(0,s1.normalizeId)($),delete this.schemas[$],delete this.refs[$];return this}default:throw Error("ajv.removeSchema: invalid parameter")}}addVocabulary(b){for(let w of b)this.addKeyword(w);return this}addKeyword(b,w){let $;if(typeof b=="string"){if($=b,typeof w=="object")this.logger.warn("these parameters are deprecated, see docs for addKeyword"),w.keyword=$}else if(typeof b=="object"&&w===void 0){if(w=b,$=w.keyword,Array.isArray($)&&!$.length)throw Error("addKeywords: keyword must be string or non-empty array")}else throw Error("invalid addKeywords parameters");if(U3.call(this,$,w),!w)return(0,l6.eachItem)($,(Q)=>m6.call(this,Q)),this;B3.call(this,w);let W={...w,type:(0,F$.getJSONTypes)(w.type),schemaType:(0,F$.getJSONTypes)(w.schemaType)};return(0,l6.eachItem)($,W.type.length===0?(Q)=>m6.call(this,Q,W):(Q)=>W.type.forEach((q)=>m6.call(this,Q,W,q))),this}getKeyword(b){let w=this.RULES.all[b];return typeof w=="object"?w.definition:!!w}removeKeyword(b){let{RULES:w}=this;delete w.keywords[b],delete w.all[b];for(let $ of w.rules){let W=$.rules.findIndex((Q)=>Q.keyword===b);if(W>=0)$.rules.splice(W,1)}return this}addFormat(b,w){if(typeof w=="string")w=new RegExp(w);return this.formats[b]=w,this}errorsText(b=this.errors,{separator:w=", ",dataVar:$="data"}={}){if(!b||b.length===0)return"No errors";return b.map((W)=>`${$}${W.instancePath} ${W.message}`).reduce((W,Q)=>W+w+Q)}$dataMetaSchema(b,w){let $=this.RULES.all;b=JSON.parse(JSON.stringify(b));for(let W of w){let Q=W.split("/").slice(1),q=b;for(let G of Q)q=q[G];for(let G in $){let X=$[G];if(typeof X!="object")continue;let{$data:Y}=X.definition,J=q[G];if(Y&&J)q[G]=GY(J)}}return b}_removeAllSchemas(b,w){for(let $ in b){let W=b[$];if(!w||w.test($)){if(typeof W=="string")delete b[$];else if(W&&!W.meta)this._cache.delete(W.schema),delete b[$]}}}_addSchema(b,w,$,W=this.opts.validateSchema,Q=this.opts.addUsedSchema){let q,{schemaId:G}=this.opts;if(typeof b=="object")q=b[G];else if(this.opts.jtd)throw Error("schema must be object");else if(typeof b!="boolean")throw Error("schema must be object or boolean");let X=this._cache.get(b);if(X!==void 0)return X;$=(0,s1.normalizeId)(q||$);let Y=s1.getSchemaRefs.call(this,b,$);if(X=new e1.SchemaEnv({schema:b,schemaId:G,meta:w,baseId:$,localRefs:Y}),this._cache.set(X.schema,X),Q&&!$.startsWith("#")){if($)this._checkUnique($);this.refs[$]=X}if(W)this.validateSchema(b,!0);return X}_checkUnique(b){if(this.schemas[b]||this.refs[b])throw Error(`schema with key or id "${b}" already exists`)}_compileSchemaEnv(b){if(b.meta)this._compileMetaSchema(b);else e1.compileSchema.call(this,b);if(!b.validate)throw Error("ajv implementation error");return b.validate}_compileMetaSchema(b){let w=this.opts;this.opts=this._metaOpts;try{e1.compileSchema.call(this,b)}finally{this.opts=w}}}K$.ValidationError=b3.default;K$.MissingRefError=QY.default;Jw.default=K$;function $Y(b,w,$,W="error"){for(let Q in b){let q=Q;if(q in w)this.logger[W](`${$}: option ${Q}. ${b[q]}`)}}function WY(b){return b=(0,s1.normalizeId)(b),this.schemas[b]||this.refs[b]}function J3(){let b=this.opts.schemas;if(!b)return;if(Array.isArray(b))this.addSchema(b);else for(let w in b)this.addSchema(b[w],w)}function D3(){for(let b in this.opts.formats){let w=this.opts.formats[b];if(w)this.addFormat(b,w)}}function H3(b){if(Array.isArray(b)){this.addVocabulary(b);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let w in b){let $=b[w];if(!$.keyword)$.keyword=w;this.addKeyword($)}}function z3(){let b={...this.opts};for(let w of Q3)delete b[w];return b}var O3={log(){},warn(){},error(){}};function A3(b){if(b===!1)return O3;if(b===void 0)return console;if(b.log&&b.warn&&b.error)return b;throw Error("logger must implement log, warn and error methods")}var L3=/^[a-z_$][a-z0-9_$:-]*$/i;function U3(b,w){let{RULES:$}=this;if((0,l6.eachItem)(b,(W)=>{if($.keywords[W])throw Error(`Keyword ${W} is already defined`);if(!L3.test(W))throw Error(`Keyword ${W} has invalid name`)}),!w)return;if(w.$data&&!(("code"in w)||("validate"in w)))throw Error('$data keyword must have "code" or "validate" function')}function m6(b,w,$){var W;let Q=w===null||w===void 0?void 0:w.post;if($&&Q)throw Error('keyword with "post" flag cannot have "type"');let{RULES:q}=this,G=Q?q.post:q.rules.find(({type:Y})=>Y===$);if(!G)G={type:$,rules:[]},q.rules.push(G);if(q.keywords[b]=!0,!w)return;let X={keyword:b,definition:{...w,type:(0,F$.getJSONTypes)(w.type),schemaType:(0,F$.getJSONTypes)(w.schemaType)}};if(w.before)P3.call(this,G,X,w.before);else G.rules.push(X);q.all[b]=X,(W=w.implements)===null||W===void 0||W.forEach((Y)=>this.addKeyword(Y))}function P3(b,w,$){let W=b.rules.findIndex((Q)=>Q.keyword===$);if(W>=0)b.rules.splice(W,0,w);else b.rules.push(w),this.logger.warn(`rule ${$} is not defined`)}function B3(b){let{metaSchema:w}=b;if(w===void 0)return;if(b.$data&&this.opts.$data)w=GY(w);b.validateSchema=this.compile(w,!0)}var F3={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function GY(b){return{anyOf:[b,F3]}}});var JY=j((YY)=>{Object.defineProperty(YY,"__esModule",{value:!0});var I3={keyword:"id",code(){throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};YY.default=I3});var LY=j((OY)=>{Object.defineProperty(OY,"__esModule",{value:!0});OY.callRef=OY.getValidate=void 0;var j3=d1(),DY=ub(),Zb=y(),w1=Gw(),HY=A$(),M$=g(),Z3={keyword:"$ref",schemaType:"string",code(b){let{gen:w,schema:$,it:W}=b,{baseId:Q,schemaEnv:q,validateName:G,opts:X,self:Y}=W,{root:J}=q;if(($==="#"||$==="#/")&&Q===J.baseId)return H();let D=HY.resolveRef.call(Y,J,Q,$);if(D===void 0)throw new j3.default(W.opts.uriResolver,Q,$);if(D instanceof HY.SchemaEnv)return O(D);return A(D);function H(){if(q===J)return I$(b,G,q,q.$async);let B=w.scopeValue("root",{ref:J});return I$(b,Zb._`${B}.validate`,J,J.$async)}function O(B){let K=zY(b,B);I$(b,K,B,B.$async)}function A(B){let K=w.scopeValue("schema",X.code.source===!0?{ref:B,code:(0,Zb.stringify)(B)}:{ref:B}),_=w.name("valid"),I=b.subschema({schema:B,dataTypes:[],schemaPath:Zb.nil,topSchemaRef:K,errSchemaPath:$},_);b.mergeEvaluated(I),b.ok(_)}}};function zY(b,w){let{gen:$}=b;return w.validate?$.scopeValue("validate",{ref:w.validate}):Zb._`${$.scopeValue("wrapper",{ref:w})}.validate`}OY.getValidate=zY;function I$(b,w,$,W){let{gen:Q,it:q}=b,{allErrors:G,schemaEnv:X,opts:Y}=q,J=Y.passContext?w1.default.this:Zb.nil;if(W)D();else H();function D(){if(!X.$async)throw Error("async schema referenced by sync schema");let B=Q.let("valid");Q.try(()=>{if(Q.code(Zb._`await ${(0,DY.callValidateCode)(b,w,J)}`),A(w),!G)Q.assign(B,!0)},(K)=>{if(Q.if(Zb._`!(${K} instanceof ${q.ValidationError})`,()=>Q.throw(K)),O(K),!G)Q.assign(B,!1)}),b.ok(B)}function H(){b.result((0,DY.callValidateCode)(b,w,J),()=>A(w),()=>O(w))}function O(B){let K=Zb._`${B}.errors`;Q.assign(w1.default.vErrors,Zb._`${w1.default.vErrors} === null ? ${K} : ${w1.default.vErrors}.concat(${K})`),Q.assign(w1.default.errors,Zb._`${w1.default.vErrors}.length`)}function A(B){var K;if(!q.opts.unevaluated)return;let _=(K=$===null||$===void 0?void 0:$.validate)===null||K===void 0?void 0:K.evaluated;if(q.props!==!0)if(_&&!_.dynamicProps){if(_.props!==void 0)q.props=M$.mergeEvaluated.props(Q,_.props,q.props)}else{let I=Q.var("props",Zb._`${B}.evaluated.props`);q.props=M$.mergeEvaluated.props(Q,I,q.props,Zb.Name)}if(q.items!==!0)if(_&&!_.dynamicItems){if(_.items!==void 0)q.items=M$.mergeEvaluated.items(Q,_.items,q.items)}else{let I=Q.var("items",Zb._`${B}.evaluated.items`);q.items=M$.mergeEvaluated.items(Q,I,q.items,Zb.Name)}}}OY.callRef=I$;OY.default=Z3});var PY=j((UY)=>{Object.defineProperty(UY,"__esModule",{value:!0});var E3=JY(),T3=LY(),S3=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",E3.default,T3.default];UY.default=S3});var FY=j((BY)=>{Object.defineProperty(BY,"__esModule",{value:!0});var _$=y(),Tw=_$.operators,j$={maximum:{okStr:"<=",ok:Tw.LTE,fail:Tw.GT},minimum:{okStr:">=",ok:Tw.GTE,fail:Tw.LT},exclusiveMaximum:{okStr:"<",ok:Tw.LT,fail:Tw.GTE},exclusiveMinimum:{okStr:">",ok:Tw.GT,fail:Tw.LTE}},v3={message:({keyword:b,schemaCode:w})=>_$.str`must be ${j$[b].okStr} ${w}`,params:({keyword:b,schemaCode:w})=>_$._`{comparison: ${j$[b].okStr}, limit: ${w}}`},k3={keyword:Object.keys(j$),type:"number",schemaType:"number",$data:!0,error:v3,code(b){let{keyword:w,data:$,schemaCode:W}=b;b.fail$data(_$._`${$} ${j$[w].fail} ${W} || isNaN(${$})`)}};BY.default=k3});var MY=j((KY)=>{Object.defineProperty(KY,"__esModule",{value:!0});var a1=y(),u3={message:({schemaCode:b})=>a1.str`must be multiple of ${b}`,params:({schemaCode:b})=>a1._`{multipleOf: ${b}}`},x3={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:u3,code(b){let{gen:w,data:$,schemaCode:W,it:Q}=b,q=Q.opts.multipleOfPrecision,G=w.let("res"),X=q?a1._`Math.abs(Math.round(${G}) - ${G}) > 1e-${q}`:a1._`${G} !== parseInt(${G})`;b.fail$data(a1._`(${W} === 0 || (${G} = ${$}/${W}, ${X}))`)}};KY.default=x3});var jY=j((_Y)=>{Object.defineProperty(_Y,"__esModule",{value:!0});function IY(b){let w=b.length,$=0,W=0,Q;while(W<w)if($++,Q=b.charCodeAt(W++),Q>=55296&&Q<=56319&&W<w){if(Q=b.charCodeAt(W),(Q&64512)===56320)W++}return $}_Y.default=IY;IY.code='require("ajv/dist/runtime/ucs2length").default'});var VY=j((ZY)=>{Object.defineProperty(ZY,"__esModule",{value:!0});var hw=y(),c3=g(),f3=jY(),n3={message({keyword:b,schemaCode:w}){let $=b==="maxLength"?"more":"fewer";return hw.str`must NOT have ${$} than ${w} characters`},params:({schemaCode:b})=>hw._`{limit: ${b}}`},i3={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:n3,code(b){let{keyword:w,data:$,schemaCode:W,it:Q}=b,q=w==="maxLength"?hw.operators.GT:hw.operators.LT,G=Q.opts.unicode===!1?hw._`${$}.length`:hw._`${(0,c3.useFunc)(b.gen,f3.default)}(${$})`;b.fail$data(hw._`${G} ${q} ${W}`)}};ZY.default=i3});var EY=j((NY)=>{Object.defineProperty(NY,"__esModule",{value:!0});var l3=ub(),Z$=y(),g3={message:({schemaCode:b})=>Z$.str`must match pattern "${b}"`,params:({schemaCode:b})=>Z$._`{pattern: ${b}}`},p3={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:g3,code(b){let{data:w,$data:$,schema:W,schemaCode:Q,it:q}=b,G=q.opts.unicodeRegExp?"u":"",X=$?Z$._`(new RegExp(${Q}, ${G}))`:(0,l3.usePattern)(b,W);b.fail$data(Z$._`!${X}.test(${w})`)}};NY.default=p3});var SY=j((TY)=>{Object.defineProperty(TY,"__esModule",{value:!0});var b0=y(),d3={message({keyword:b,schemaCode:w}){let $=b==="maxProperties"?"more":"fewer";return b0.str`must NOT have ${$} than ${w} properties`},params:({schemaCode:b})=>b0._`{limit: ${b}}`},t3={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:d3,code(b){let{keyword:w,data:$,schemaCode:W}=b,Q=w==="maxProperties"?b0.operators.GT:b0.operators.LT;b.fail$data(b0._`Object.keys(${$}).length ${Q} ${W}`)}};TY.default=t3});var vY=j((RY)=>{Object.defineProperty(RY,"__esModule",{value:!0});var w0=ub(),$0=y(),e3=g(),s3={message:({params:{missingProperty:b}})=>$0.str`must have required property '${b}'`,params:({params:{missingProperty:b}})=>$0._`{missingProperty: ${b}}`},a3={keyword:"required",type:"object",schemaType:"array",$data:!0,error:s3,code(b){let{gen:w,schema:$,schemaCode:W,data:Q,$data:q,it:G}=b,{opts:X}=G;if(!q&&$.length===0)return;let Y=$.length>=X.loopRequired;if(G.allErrors)J();else D();if(X.strictRequired){let A=b.parentSchema.properties,{definedProperties:B}=b.it;for(let K of $)if((A===null||A===void 0?void 0:A[K])===void 0&&!B.has(K)){let _=G.schemaEnv.baseId+G.errSchemaPath,I=`required property "${K}" is not defined at "${_}" (strictRequired)`;(0,e3.checkStrictMode)(G,I,G.opts.strictRequired)}}function J(){if(Y||q)b.block$data($0.nil,H);else for(let A of $)(0,w0.checkReportMissingProp)(b,A)}function D(){let A=w.let("missing");if(Y||q){let B=w.let("valid",!0);b.block$data(B,()=>O(A,B)),b.ok(B)}else w.if((0,w0.checkMissingProp)(b,$,A)),(0,w0.reportMissingProp)(b,A),w.else()}function H(){w.forOf("prop",W,(A)=>{b.setParams({missingProperty:A}),w.if((0,w0.noPropertyInData)(w,Q,A,X.ownProperties),()=>b.error())})}function O(A,B){b.setParams({missingProperty:A}),w.forOf(A,W,()=>{w.assign(B,(0,w0.propertyInData)(w,Q,A,X.ownProperties)),w.if((0,$0.not)(B),()=>{b.error(),w.break()})},$0.nil)}}};RY.default=a3});var CY=j((kY)=>{Object.defineProperty(kY,"__esModule",{value:!0});var W0=y(),wB={message({keyword:b,schemaCode:w}){let $=b==="maxItems"?"more":"fewer";return W0.str`must NOT have ${$} than ${w} items`},params:({schemaCode:b})=>W0._`{limit: ${b}}`},$B={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:wB,code(b){let{keyword:w,data:$,schemaCode:W}=b,Q=w==="maxItems"?W0.operators.GT:W0.operators.LT;b.fail$data(W0._`${$}.length ${Q} ${W}`)}};kY.default=$B});var V$=j((xY)=>{Object.defineProperty(xY,"__esModule",{value:!0});var uY=T6();uY.code='require("ajv/dist/runtime/equal").default';xY.default=uY});var hY=j((yY)=>{Object.defineProperty(yY,"__esModule",{value:!0});var g6=m1(),Ub=y(),qB=g(),GB=V$(),XB={message:({params:{i:b,j:w}})=>Ub.str`must NOT have duplicate items (items ## ${w} and ${b} are identical)`,params:({params:{i:b,j:w}})=>Ub._`{i: ${b}, j: ${w}}`},YB={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:XB,code(b){let{gen:w,data:$,$data:W,schema:Q,parentSchema:q,schemaCode:G,it:X}=b;if(!W&&!Q)return;let Y=w.let("valid"),J=q.items?(0,g6.getSchemaTypes)(q.items):[];b.block$data(Y,D,Ub._`${G} === false`),b.ok(Y);function D(){let B=w.let("i",Ub._`${$}.length`),K=w.let("j");b.setParams({i:B,j:K}),w.assign(Y,!0),w.if(Ub._`${B} > 1`,()=>(H()?O:A)(B,K))}function H(){return J.length>0&&!J.some((B)=>B==="object"||B==="array")}function O(B,K){let _=w.name("item"),I=(0,g6.checkDataTypes)(J,_,X.opts.strictNumbers,g6.DataType.Wrong),R=w.const("indices",Ub._`{}`);w.for(Ub._`;${B}--;`,()=>{if(w.let(_,Ub._`${$}[${B}]`),w.if(I,Ub._`continue`),J.length>1)w.if(Ub._`typeof ${_} == "string"`,Ub._`${_} += "_"`);w.if(Ub._`typeof ${R}[${_}] == "number"`,()=>{w.assign(K,Ub._`${R}[${_}]`),b.error(),w.assign(Y,!1).break()}).code(Ub._`${R}[${_}] = ${B}`)})}function A(B,K){let _=(0,qB.useFunc)(w,GB.default),I=w.name("outer");w.label(I).for(Ub._`;${B}--;`,()=>w.for(Ub._`${K} = ${B}; ${K}--;`,()=>w.if(Ub._`${_}(${$}[${B}], ${$}[${K}])`,()=>{b.error(),w.assign(Y,!1).break(I)})))}}};yY.default=YB});var fY=j((cY)=>{Object.defineProperty(cY,"__esModule",{value:!0});var p6=y(),DB=g(),HB=V$(),zB={message:"must be equal to constant",params:({schemaCode:b})=>p6._`{allowedValue: ${b}}`},OB={keyword:"const",$data:!0,error:zB,code(b){let{gen:w,data:$,$data:W,schemaCode:Q,schema:q}=b;if(W||q&&typeof q=="object")b.fail$data(p6._`!${(0,DB.useFunc)(w,HB.default)}(${$}, ${Q})`);else b.fail(p6._`${q} !== ${$}`)}};cY.default=OB});var iY=j((nY)=>{Object.defineProperty(nY,"__esModule",{value:!0});var Q0=y(),LB=g(),UB=V$(),PB={message:"must be equal to one of the allowed values",params:({schemaCode:b})=>Q0._`{allowedValues: ${b}}`},BB={keyword:"enum",schemaType:"array",$data:!0,error:PB,code(b){let{gen:w,data:$,$data:W,schema:Q,schemaCode:q,it:G}=b;if(!W&&Q.length===0)throw Error("enum must have non-empty array");let X=Q.length>=G.opts.loopEnum,Y,J=()=>Y!==null&&Y!==void 0?Y:Y=(0,LB.useFunc)(w,UB.default),D;if(X||W)D=w.let("valid"),b.block$data(D,H);else{if(!Array.isArray(Q))throw Error("ajv implementation error");let A=w.const("vSchema",q);D=(0,Q0.or)(...Q.map((B,K)=>O(A,K)))}b.pass(D);function H(){w.assign(D,!1),w.forOf("v",q,(A)=>w.if(Q0._`${J()}(${$}, ${A})`,()=>w.assign(D,!0).break()))}function O(A,B){let K=Q[B];return typeof K==="object"&&K!==null?Q0._`${J()}(${$}, ${A}[${B}])`:Q0._`${$} === ${K}`}}};nY.default=BB});var lY=j((mY)=>{Object.defineProperty(mY,"__esModule",{value:!0});var KB=FY(),MB=MY(),IB=VY(),_B=EY(),jB=SY(),ZB=vY(),VB=CY(),NB=hY(),EB=fY(),TB=iY(),SB=[KB.default,MB.default,IB.default,_B.default,jB.default,ZB.default,VB.default,NB.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},EB.default,TB.default];mY.default=SB});var d6=j((pY)=>{Object.defineProperty(pY,"__esModule",{value:!0});pY.validateAdditionalItems=void 0;var cw=y(),o6=g(),vB={message:({params:{len:b}})=>cw.str`must NOT have more than ${b} items`,params:({params:{len:b}})=>cw._`{limit: ${b}}`},kB={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:vB,code(b){let{parentSchema:w,it:$}=b,{items:W}=w;if(!Array.isArray(W)){(0,o6.checkStrictMode)($,'"additionalItems" is ignored when "items" is not an array of schemas');return}gY(b,W)}};function gY(b,w){let{gen:$,schema:W,data:Q,keyword:q,it:G}=b;G.items=!0;let X=$.const("len",cw._`${Q}.length`);if(W===!1)b.setParams({len:w.length}),b.pass(cw._`${X} <= ${w.length}`);else if(typeof W=="object"&&!(0,o6.alwaysValidSchema)(G,W)){let J=$.var("valid",cw._`${X} <= ${w.length}`);$.if((0,cw.not)(J),()=>Y(J)),b.ok(J)}function Y(J){$.forRange("i",w.length,X,(D)=>{if(b.subschema({keyword:q,dataProp:D,dataPropType:o6.Type.Num},J),!G.allErrors)$.if((0,cw.not)(J),()=>$.break())})}}pY.validateAdditionalItems=gY;pY.default=kB});var t6=j((rY)=>{Object.defineProperty(rY,"__esModule",{value:!0});rY.validateTuple=void 0;var dY=y(),N$=g(),uB=ub(),xB={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(b){let{schema:w,it:$}=b;if(Array.isArray(w))return tY(b,"additionalItems",w);if($.items=!0,(0,N$.alwaysValidSchema)($,w))return;b.ok((0,uB.validateArray)(b))}};function tY(b,w,$=b.schema){let{gen:W,parentSchema:Q,data:q,keyword:G,it:X}=b;if(D(Q),X.opts.unevaluated&&$.length&&X.items!==!0)X.items=N$.mergeEvaluated.items(W,$.length,X.items);let Y=W.name("valid"),J=W.const("len",dY._`${q}.length`);$.forEach((H,O)=>{if((0,N$.alwaysValidSchema)(X,H))return;W.if(dY._`${J} > ${O}`,()=>b.subschema({keyword:G,schemaProp:O,dataProp:O},Y)),b.ok(Y)});function D(H){let{opts:O,errSchemaPath:A}=X,B=$.length,K=B===H.minItems&&(B===H.maxItems||H[w]===!1);if(O.strictTuples&&!K){let _=`"${G}" is ${B}-tuple, but minItems or maxItems/${w} are not specified or different at path "${A}"`;(0,N$.checkStrictMode)(X,_,O.strictTuples)}}}rY.validateTuple=tY;rY.default=xB});var aY=j((sY)=>{Object.defineProperty(sY,"__esModule",{value:!0});var hB=t6(),cB={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:(b)=>(0,hB.validateTuple)(b,"items")};sY.default=cB});var $J=j((wJ)=>{Object.defineProperty(wJ,"__esModule",{value:!0});var bJ=y(),nB=g(),iB=ub(),mB=d6(),lB={message:({params:{len:b}})=>bJ.str`must NOT have more than ${b} items`,params:({params:{len:b}})=>bJ._`{limit: ${b}}`},gB={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:lB,code(b){let{schema:w,parentSchema:$,it:W}=b,{prefixItems:Q}=$;if(W.items=!0,(0,nB.alwaysValidSchema)(W,w))return;if(Q)(0,mB.validateAdditionalItems)(b,Q);else b.ok((0,iB.validateArray)(b))}};wJ.default=gB});var QJ=j((WJ)=>{Object.defineProperty(WJ,"__esModule",{value:!0});var xb=y(),E$=g(),oB={message:({params:{min:b,max:w}})=>w===void 0?xb.str`must contain at least ${b} valid item(s)`:xb.str`must contain at least ${b} and no more than ${w} valid item(s)`,params:({params:{min:b,max:w}})=>w===void 0?xb._`{minContains: ${b}}`:xb._`{minContains: ${b}, maxContains: ${w}}`},dB={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:oB,code(b){let{gen:w,schema:$,parentSchema:W,data:Q,it:q}=b,G,X,{minContains:Y,maxContains:J}=W;if(q.opts.next)G=Y===void 0?1:Y,X=J;else G=1;let D=w.const("len",xb._`${Q}.length`);if(b.setParams({min:G,max:X}),X===void 0&&G===0){(0,E$.checkStrictMode)(q,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(X!==void 0&&G>X){(0,E$.checkStrictMode)(q,'"minContains" > "maxContains" is always invalid'),b.fail();return}if((0,E$.alwaysValidSchema)(q,$)){let K=xb._`${D} >= ${G}`;if(X!==void 0)K=xb._`${K} && ${D} <= ${X}`;b.pass(K);return}q.items=!0;let H=w.name("valid");if(X===void 0&&G===1)A(H,()=>w.if(H,()=>w.break()));else if(G===0){if(w.let(H,!0),X!==void 0)w.if(xb._`${Q}.length > 0`,O)}else w.let(H,!1),O();b.result(H,()=>b.reset());function O(){let K=w.name("_valid"),_=w.let("count",0);A(K,()=>w.if(K,()=>B(_)))}function A(K,_){w.forRange("i",0,D,(I)=>{b.subschema({keyword:"contains",dataProp:I,dataPropType:E$.Type.Num,compositeRule:!0},K),_()})}function B(K){if(w.code(xb._`${K}++`),X===void 0)w.if(xb._`${K} >= ${G}`,()=>w.assign(H,!0).break());else if(w.if(xb._`${K} > ${X}`,()=>w.assign(H,!1).break()),G===1)w.assign(H,!0);else w.if(xb._`${K} >= ${G}`,()=>w.assign(H,!0))}}};WJ.default=dB});var DJ=j((XJ)=>{Object.defineProperty(XJ,"__esModule",{value:!0});XJ.validateSchemaDeps=XJ.validatePropertyDeps=XJ.error=void 0;var r6=y(),rB=g(),q0=ub();XJ.error={message:({params:{property:b,depsCount:w,deps:$}})=>{let W=w===1?"property":"properties";return r6.str`must have ${W} ${$} when property ${b} is present`},params:({params:{property:b,depsCount:w,deps:$,missingProperty:W}})=>r6._`{property: ${b},
|
|
7
7
|
missingProperty: ${W},
|
|
8
8
|
depsCount: ${w},
|
|
9
|
-
deps: ${$}}`};var rB={keyword:"dependencies",type:"object",schemaType:"object",error:XJ.error,code(b){let[w,$]=eB(b);GJ(b,w),qJ(b,$)}};function eB({schema:b}){let w={},$={};for(let W in b){if(W==="__proto__")continue;let Q=Array.isArray(b[W])?w:$;Q[W]=b[W]}return[w,$]}function GJ(b,w=b.schema){let{gen:$,data:W,it:Q}=b;if(Object.keys(w).length===0)return;let G=$.let("missing");for(let q in w){let X=w[q];if(X.length===0)continue;let Y=(0,G0.propertyInData)($,W,q,Q.opts.ownProperties);if(b.setParams({property:q,depsCount:X.length,deps:X.join(", ")}),Q.allErrors)$.if(Y,()=>{for(let J of X)(0,G0.checkReportMissingProp)(b,J)});else $.if(r6._`${Y} && (${(0,G0.checkMissingProp)(b,X,G)})`),(0,G0.reportMissingProp)(b,G),$.else()}}XJ.validatePropertyDeps=GJ;function qJ(b,w=b.schema){let{gen:$,data:W,keyword:Q,it:G}=b,q=$.name("valid");for(let X in w){if((0,tB.alwaysValidSchema)(G,w[X]))continue;$.if((0,G0.propertyInData)($,W,X,G.opts.ownProperties),()=>{let Y=b.subschema({keyword:Q,schemaProp:X},q);b.mergeValidEvaluated(Y,q)},()=>$.var(q,!0)),b.ok(q)}}XJ.validateSchemaDeps=qJ;XJ.default=rB});var OJ=Z((zJ)=>{Object.defineProperty(zJ,"__esModule",{value:!0});var HJ=y(),bF=g(),wF={message:"property name must be valid",params:({params:b})=>HJ._`{propertyName: ${b.propertyName}}`},$F={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:wF,code(b){let{gen:w,schema:$,data:W,it:Q}=b;if((0,bF.alwaysValidSchema)(Q,$))return;let G=w.name("valid");w.forIn("key",W,(q)=>{b.setParams({propertyName:q}),b.subschema({keyword:"propertyNames",data:q,dataTypes:["string"],propertyName:q,compositeRule:!0},G),w.if((0,HJ.not)(G),()=>{if(b.error(!0),!Q.allErrors)w.break()})}),b.ok(G)}};zJ.default=$F});var e6=Z((AJ)=>{Object.defineProperty(AJ,"__esModule",{value:!0});var T$=ub(),mb=y(),QF=qw(),S$=g(),GF={message:"must NOT have additional properties",params:({params:b})=>mb._`{additionalProperty: ${b.additionalProperty}}`},qF={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:GF,code(b){let{gen:w,schema:$,parentSchema:W,data:Q,errsCount:G,it:q}=b;if(!G)throw Error("ajv implementation error");let{allErrors:X,opts:Y}=q;if(q.props=!0,Y.removeAdditional!=="all"&&(0,S$.alwaysValidSchema)(q,$))return;let J=(0,T$.allSchemaProperties)(W.properties),D=(0,T$.allSchemaProperties)(W.patternProperties);H(),b.ok(mb._`${G} === ${QF.default.errors}`);function H(){w.forIn("key",Q,(_)=>{if(!J.length&&!D.length)B(_);else w.if(O(_),()=>B(_))})}function O(_){let I;if(J.length>8){let R=(0,S$.schemaRefOrVal)(q,W.properties,"properties");I=(0,T$.isOwnProperty)(w,R,_)}else if(J.length)I=(0,mb.or)(...J.map((R)=>mb._`${_} === ${R}`));else I=mb.nil;if(D.length)I=(0,mb.or)(I,...D.map((R)=>mb._`${(0,T$.usePattern)(b,R)}.test(${_})`));return(0,mb.not)(I)}function A(_){w.code(mb._`delete ${Q}[${_}]`)}function B(_){if(Y.removeAdditional==="all"||Y.removeAdditional&&$===!1){A(_);return}if($===!1){if(b.setParams({additionalProperty:_}),b.error(),!X)w.break();return}if(typeof $=="object"&&!(0,S$.alwaysValidSchema)(q,$)){let I=w.name("valid");if(Y.removeAdditional==="failing")K(_,I,!1),w.if((0,mb.not)(I),()=>{b.reset(),A(_)});else if(K(_,I),!X)w.if((0,mb.not)(I),()=>w.break())}}function K(_,I,R){let T={keyword:"additionalProperties",dataProp:_,dataPropType:S$.Type.Str};if(R===!1)Object.assign(T,{compositeRule:!0,createErrors:!1,allErrors:!1});b.subschema(T,I)}}};AJ.default=qF});var BJ=Z((PJ)=>{Object.defineProperty(PJ,"__esModule",{value:!0});var YF=o1(),UJ=ub(),s6=g(),LJ=e6(),JF={keyword:"properties",type:"object",schemaType:"object",code(b){let{gen:w,schema:$,parentSchema:W,data:Q,it:G}=b;if(G.opts.removeAdditional==="all"&&W.additionalProperties===void 0)LJ.default.code(new YF.KeywordCxt(G,LJ.default,"additionalProperties"));let q=(0,UJ.allSchemaProperties)($);for(let H of q)G.definedProperties.add(H);if(G.opts.unevaluated&&q.length&&G.props!==!0)G.props=s6.mergeEvaluated.props(w,(0,s6.toHash)(q),G.props);let X=q.filter((H)=>!(0,s6.alwaysValidSchema)(G,$[H]));if(X.length===0)return;let Y=w.name("valid");for(let H of X){if(J(H))D(H);else{if(w.if((0,UJ.propertyInData)(w,Q,H,G.opts.ownProperties)),D(H),!G.allErrors)w.else().var(Y,!0);w.endIf()}b.it.definedProperties.add(H),b.ok(Y)}function J(H){return G.opts.useDefaults&&!G.compositeRule&&$[H].default!==void 0}function D(H){b.subschema({keyword:"properties",schemaProp:H,dataProp:H},Y)}}};PJ.default=JF});var _J=Z((IJ)=>{Object.defineProperty(IJ,"__esModule",{value:!0});var FJ=ub(),R$=y(),KJ=g(),MJ=g(),HF={keyword:"patternProperties",type:"object",schemaType:"object",code(b){let{gen:w,schema:$,data:W,parentSchema:Q,it:G}=b,{opts:q}=G,X=(0,FJ.allSchemaProperties)($),Y=X.filter((K)=>(0,KJ.alwaysValidSchema)(G,$[K]));if(X.length===0||Y.length===X.length&&(!G.opts.unevaluated||G.props===!0))return;let J=q.strictSchema&&!q.allowMatchingProperties&&Q.properties,D=w.name("valid");if(G.props!==!0&&!(G.props instanceof R$.Name))G.props=(0,MJ.evaluatedPropsToName)(w,G.props);let{props:H}=G;O();function O(){for(let K of X){if(J)A(K);if(G.allErrors)B(K);else w.var(D,!0),B(K),w.if(D)}}function A(K){for(let _ in J)if(new RegExp(K).test(_))(0,KJ.checkStrictMode)(G,`property ${_} matches pattern ${K} (use allowMatchingProperties)`)}function B(K){w.forIn("key",W,(_)=>{w.if(R$._`${(0,FJ.usePattern)(b,K)}.test(${_})`,()=>{let I=Y.includes(K);if(!I)b.subschema({keyword:"patternProperties",schemaProp:K,dataProp:_,dataPropType:MJ.Type.Str},D);if(G.opts.unevaluated&&H!==!0)w.assign(R$._`${H}[${_}]`,!0);else if(!I&&!G.allErrors)w.if((0,R$.not)(D),()=>w.break())})})}}};IJ.default=HF});var jJ=Z((ZJ)=>{Object.defineProperty(ZJ,"__esModule",{value:!0});var OF=g(),AF={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(b){let{gen:w,schema:$,it:W}=b;if((0,OF.alwaysValidSchema)(W,$)){b.fail();return}let Q=w.name("valid");b.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},Q),b.failResult(Q,()=>b.reset(),()=>b.error())},error:{message:"must NOT be valid"}};ZJ.default=AF});var NJ=Z((VJ)=>{Object.defineProperty(VJ,"__esModule",{value:!0});var LF=ub(),PF={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:LF.validateUnion,error:{message:"must match a schema in anyOf"}};VJ.default=PF});var TJ=Z((EJ)=>{Object.defineProperty(EJ,"__esModule",{value:!0});var v$=y(),FF=g(),KF={message:"must match exactly one schema in oneOf",params:({params:b})=>v$._`{passingSchemas: ${b.passing}}`},MF={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:KF,code(b){let{gen:w,schema:$,parentSchema:W,it:Q}=b;if(!Array.isArray($))throw Error("ajv implementation error");if(Q.opts.discriminator&&W.discriminator)return;let G=$,q=w.let("valid",!1),X=w.let("passing",null),Y=w.name("_valid");b.setParams({passing:X}),w.block(J),b.result(q,()=>b.reset(),()=>b.error(!0));function J(){G.forEach((D,H)=>{let O;if((0,FF.alwaysValidSchema)(Q,D))w.var(Y,!0);else O=b.subschema({keyword:"oneOf",schemaProp:H,compositeRule:!0},Y);if(H>0)w.if(v$._`${Y} && ${q}`).assign(q,!1).assign(X,v$._`[${X}, ${H}]`).else();w.if(Y,()=>{if(w.assign(q,!0),w.assign(X,H),O)b.mergeEvaluated(O,v$.Name)})})}}};EJ.default=MF});var RJ=Z((SJ)=>{Object.defineProperty(SJ,"__esModule",{value:!0});var _F=g(),ZF={keyword:"allOf",schemaType:"array",code(b){let{gen:w,schema:$,it:W}=b;if(!Array.isArray($))throw Error("ajv implementation error");let Q=w.name("valid");$.forEach((G,q)=>{if((0,_F.alwaysValidSchema)(W,G))return;let X=b.subschema({keyword:"allOf",schemaProp:q},Q);b.ok(Q),b.mergeEvaluated(X)})}};SJ.default=ZF});var uJ=Z((CJ)=>{Object.defineProperty(CJ,"__esModule",{value:!0});var k$=y(),kJ=g(),VF={message:({params:b})=>k$.str`must match "${b.ifClause}" schema`,params:({params:b})=>k$._`{failingKeyword: ${b.ifClause}}`},NF={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:VF,code(b){let{gen:w,parentSchema:$,it:W}=b;if($.then===void 0&&$.else===void 0)(0,kJ.checkStrictMode)(W,'"if" without "then" and "else" is ignored');let Q=vJ(W,"then"),G=vJ(W,"else");if(!Q&&!G)return;let q=w.let("valid",!0),X=w.name("_valid");if(Y(),b.reset(),Q&&G){let D=w.let("ifClause");b.setParams({ifClause:D}),w.if(X,J("then",D),J("else",D))}else if(Q)w.if(X,J("then"));else w.if((0,k$.not)(X),J("else"));b.pass(q,()=>b.error(!0));function Y(){let D=b.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},X);b.mergeEvaluated(D)}function J(D,H){return()=>{let O=b.subschema({keyword:D},X);if(w.assign(q,X),b.mergeValidEvaluated(O,q),H)w.assign(H,k$._`${D}`);else b.setParams({ifClause:D})}}}};function vJ(b,w){let $=b.schema[w];return $!==void 0&&!(0,kJ.alwaysValidSchema)(b,$)}CJ.default=NF});var yJ=Z((xJ)=>{Object.defineProperty(xJ,"__esModule",{value:!0});var TF=g(),SF={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:b,parentSchema:w,it:$}){if(w.if===void 0)(0,TF.checkStrictMode)($,`"${b}" without "if" is ignored`)}};xJ.default=SF});var cJ=Z((hJ)=>{Object.defineProperty(hJ,"__esModule",{value:!0});var vF=d6(),kF=aY(),CF=t6(),uF=$J(),xF=QJ(),yF=DJ(),hF=OJ(),cF=e6(),fF=BJ(),nF=_J(),iF=jJ(),mF=NJ(),lF=TJ(),gF=RJ(),pF=uJ(),oF=yJ();function dF(b=!1){let w=[iF.default,mF.default,lF.default,gF.default,pF.default,oF.default,hF.default,cF.default,yF.default,fF.default,nF.default];if(b)w.push(kF.default,uF.default);else w.push(vF.default,CF.default);return w.push(xF.default),w}hJ.default=dF});var nJ=Z((fJ)=>{Object.defineProperty(fJ,"__esModule",{value:!0});var Xb=y(),rF={message:({schemaCode:b})=>Xb.str`must match format "${b}"`,params:({schemaCode:b})=>Xb._`{format: ${b}}`},eF={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:rF,code(b,w){let{gen:$,data:W,$data:Q,schema:G,schemaCode:q,it:X}=b,{opts:Y,errSchemaPath:J,schemaEnv:D,self:H}=X;if(!Y.validateFormats)return;if(Q)O();else A();function O(){let B=$.scopeValue("formats",{ref:H.formats,code:Y.code.formats}),K=$.const("fDef",Xb._`${B}[${q}]`),_=$.let("fType"),I=$.let("format");$.if(Xb._`typeof ${K} == "object" && !(${K} instanceof RegExp)`,()=>$.assign(_,Xb._`${K}.type || "string"`).assign(I,Xb._`${K}.validate`),()=>$.assign(_,Xb._`"string"`).assign(I,K)),b.fail$data((0,Xb.or)(R(),T()));function R(){if(Y.strictSchema===!1)return Xb.nil;return Xb._`${q} && !${I}`}function T(){let h=D.$async?Xb._`(${K}.async ? await ${I}(${W}) : ${I}(${W}))`:Xb._`${I}(${W})`,v=Xb._`(typeof ${I} == "function" ? ${h} : ${I}.test(${W}))`;return Xb._`${I} && ${I} !== true && ${_} === ${w} && !${v}`}}function A(){let B=H.formats[G];if(!B){R();return}if(B===!0)return;let[K,_,I]=T(B);if(K===w)b.pass(h());function R(){if(Y.strictSchema===!1){H.logger.warn(v());return}throw Error(v());function v(){return`unknown format "${G}" ignored in schema at path "${J}"`}}function T(v){let ob=v instanceof RegExp?(0,Xb.regexpCode)(v):Y.code.formats?Xb._`${Y.code.formats}${(0,Xb.getProperty)(G)}`:void 0,bw=$.scopeValue("formats",{key:G,ref:v,code:ob});if(typeof v=="object"&&!(v instanceof RegExp))return[v.type||"string",v.validate,Xb._`${bw}.validate`];return["string",v,bw]}function h(){if(typeof B=="object"&&!(B instanceof RegExp)&&B.async){if(!D.$async)throw Error("async format in sync schema");return Xb._`await ${I}(${W})`}return typeof _=="function"?Xb._`${I}(${W})`:Xb._`${I}.test(${W})`}}}};fJ.default=eF});var mJ=Z((iJ)=>{Object.defineProperty(iJ,"__esModule",{value:!0});var aF=nJ(),bK=[aF.default];iJ.default=bK});var pJ=Z((lJ)=>{Object.defineProperty(lJ,"__esModule",{value:!0});lJ.contentVocabulary=lJ.metadataVocabulary=void 0;lJ.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];lJ.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var tJ=Z((dJ)=>{Object.defineProperty(dJ,"__esModule",{value:!0});var WK=PY(),QK=lY(),GK=cJ(),qK=mJ(),oJ=pJ(),XK=[WK.default,QK.default,(0,GK.default)(),qK.default,oJ.metadataVocabulary,oJ.contentVocabulary];dJ.default=XK});var aJ=Z((eJ)=>{Object.defineProperty(eJ,"__esModule",{value:!0});eJ.DiscrError=void 0;var rJ;(function(b){b.Tag="tag",b.Mapping="mapping"})(rJ||(eJ.DiscrError=rJ={}))});var $D=Z((wD)=>{Object.defineProperty(wD,"__esModule",{value:!0});var $1=y(),a6=aJ(),bD=A$(),JK=d1(),DK=g(),HK={message:({params:{discrError:b,tagName:w}})=>b===a6.DiscrError.Tag?`tag "${w}" must be string`:`value of tag "${w}" must be in oneOf`,params:({params:{discrError:b,tag:w,tagName:$}})=>$1._`{error: ${b}, tag: ${$}, tagValue: ${w}}`},zK={keyword:"discriminator",type:"object",schemaType:"object",error:HK,code(b){let{gen:w,data:$,schema:W,parentSchema:Q,it:G}=b,{oneOf:q}=Q;if(!G.opts.discriminator)throw Error("discriminator: requires discriminator option");let X=W.propertyName;if(typeof X!="string")throw Error("discriminator: requires propertyName");if(W.mapping)throw Error("discriminator: mapping is not supported");if(!q)throw Error("discriminator: requires oneOf keyword");let Y=w.let("valid",!1),J=w.const("tag",$1._`${$}${(0,$1.getProperty)(X)}`);w.if($1._`typeof ${J} == "string"`,()=>D(),()=>b.error(!1,{discrError:a6.DiscrError.Tag,tag:J,tagName:X})),b.ok(Y);function D(){let A=O();w.if(!1);for(let B in A)w.elseIf($1._`${J} === ${B}`),w.assign(Y,H(A[B]));w.else(),b.error(!1,{discrError:a6.DiscrError.Mapping,tag:J,tagName:X}),w.endIf()}function H(A){let B=w.name("valid"),K=b.subschema({keyword:"oneOf",schemaProp:A},B);return b.mergeEvaluated(K,$1.Name),B}function O(){var A;let B={},K=I(Q),_=!0;for(let h=0;h<q.length;h++){let v=q[h];if((v===null||v===void 0?void 0:v.$ref)&&!(0,DK.schemaHasRulesButRef)(v,G.self.RULES)){let bw=v.$ref;if(v=bD.resolveRef.call(G.self,G.schemaEnv.root,G.baseId,bw),v instanceof bD.SchemaEnv)v=v.schema;if(v===void 0)throw new JK.default(G.opts.uriResolver,G.baseId,bw)}let ob=(A=v===null||v===void 0?void 0:v.properties)===null||A===void 0?void 0:A[X];if(typeof ob!="object")throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${X}"`);_=_&&(K||I(v)),R(ob,h)}if(!_)throw Error(`discriminator: "${X}" must be required`);return B;function I({required:h}){return Array.isArray(h)&&h.includes(X)}function R(h,v){if(h.const)T(h.const,v);else if(h.enum)for(let ob of h.enum)T(ob,v);else throw Error(`discriminator: "properties/${X}" must have "const" or "enum"`)}function T(h,v){if(typeof h!="string"||h in B)throw Error(`discriminator: "${X}" values must be unique strings`);B[h]=v}}}};wD.default=zK});var WD=Z((PT,AK)=>{AK.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 wW=Z((Vb,bW)=>{Object.defineProperty(Vb,"__esModule",{value:!0});Vb.MissingRefError=Vb.ValidationError=Vb.CodeGen=Vb.Name=Vb.nil=Vb.stringify=Vb.str=Vb._=Vb.KeywordCxt=Vb.Ajv=void 0;var UK=XY(),LK=tJ(),PK=$D(),QD=WD(),BK=["/properties"],C$="http://json-schema.org/draft-07/schema";class q0 extends UK.default{_addVocabularies(){if(super._addVocabularies(),LK.default.forEach((b)=>this.addVocabulary(b)),this.opts.discriminator)this.addKeyword(PK.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let b=this.opts.$data?this.$dataMetaSchema(QD,BK):QD;this.addMetaSchema(b,C$,!1),this.refs["http://json-schema.org/schema"]=C$}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(C$)?C$:void 0)}}Vb.Ajv=q0;bW.exports=Vb=q0;bW.exports.Ajv=q0;Object.defineProperty(Vb,"__esModule",{value:!0});Vb.default=q0;var FK=o1();Object.defineProperty(Vb,"KeywordCxt",{enumerable:!0,get:function(){return FK.KeywordCxt}});var W1=y();Object.defineProperty(Vb,"_",{enumerable:!0,get:function(){return W1._}});Object.defineProperty(Vb,"str",{enumerable:!0,get:function(){return W1.str}});Object.defineProperty(Vb,"stringify",{enumerable:!0,get:function(){return W1.stringify}});Object.defineProperty(Vb,"nil",{enumerable:!0,get:function(){return W1.nil}});Object.defineProperty(Vb,"Name",{enumerable:!0,get:function(){return W1.Name}});Object.defineProperty(Vb,"CodeGen",{enumerable:!0,get:function(){return W1.CodeGen}});var KK=z$();Object.defineProperty(Vb,"ValidationError",{enumerable:!0,get:function(){return KK.default}});var MK=d1();Object.defineProperty(Vb,"MissingRefError",{enumerable:!0,get:function(){return MK.default}})});var AD=Z((zD)=>{Object.defineProperty(zD,"__esModule",{value:!0});zD.formatNames=zD.fastFormats=zD.fullFormats=void 0;function eb(b,w){return{validate:b,compare:w}}zD.fullFormats={date:eb(YD,GW),time:eb(WW(!0),qW),"date-time":eb(GD(!0),DD),"iso-time":eb(WW(),JD),"iso-date-time":eb(GD(),HD),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:TK,"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:xK,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:SK,int32:{type:"number",validate:kK},int64:{type:"number",validate:CK},float:{type:"number",validate:XD},double:{type:"number",validate:XD},password:!0,binary:!0};zD.fastFormats={...zD.fullFormats,date:eb(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,GW),time:eb(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,qW),"date-time":eb(/^\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,DD),"iso-time":eb(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,JD),"iso-date-time":eb(/^\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,HD),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};zD.formatNames=Object.keys(zD.fullFormats);function ZK(b){return b%4===0&&(b%100!==0||b%400===0)}var jK=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,VK=[0,31,28,31,30,31,30,31,31,30,31,30,31];function YD(b){let w=jK.exec(b);if(!w)return!1;let $=+w[1],W=+w[2],Q=+w[3];return W>=1&&W<=12&&Q>=1&&Q<=(W===2&&ZK($)?29:VK[W])}function GW(b,w){if(!(b&&w))return;if(b>w)return 1;if(b<w)return-1;return 0}var $W=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function WW(b){return function($){let W=$W.exec($);if(!W)return!1;let Q=+W[1],G=+W[2],q=+W[3],X=W[4],Y=W[5]==="-"?-1:1,J=+(W[6]||0),D=+(W[7]||0);if(J>23||D>59||b&&!X)return!1;if(Q<=23&&G<=59&&q<60)return!0;let H=G-D*Y,O=Q-J*Y-(H<0?1:0);return(O===23||O===-1)&&(H===59||H===-1)&&q<61}}function qW(b,w){if(!(b&&w))return;let $=new Date("2020-01-01T"+b).valueOf(),W=new Date("2020-01-01T"+w).valueOf();if(!($&&W))return;return $-W}function JD(b,w){if(!(b&&w))return;let $=$W.exec(b),W=$W.exec(w);if(!($&&W))return;if(b=$[1]+$[2]+$[3],w=W[1]+W[2]+W[3],b>w)return 1;if(b<w)return-1;return 0}var QW=/t|\s/i;function GD(b){let w=WW(b);return function(W){let Q=W.split(QW);return Q.length===2&&YD(Q[0])&&w(Q[1])}}function DD(b,w){if(!(b&&w))return;let $=new Date(b).valueOf(),W=new Date(w).valueOf();if(!($&&W))return;return $-W}function HD(b,w){if(!(b&&w))return;let[$,W]=b.split(QW),[Q,G]=w.split(QW),q=GW($,Q);if(q===void 0)return;return q||qW(W,G)}var NK=/\/|:/,EK=/^(?:[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 TK(b){return NK.test(b)&&EK.test(b)}var qD=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function SK(b){return qD.lastIndex=0,qD.test(b)}var RK=-2147483648,vK=2147483647;function kK(b){return Number.isInteger(b)&&b<=vK&&b>=RK}function CK(b){return Number.isInteger(b)}function XD(){return!0}var uK=/[^\\]\\Z/;function xK(b){if(uK.test(b))return!1;try{return new RegExp(b),!0}catch(w){return!1}}});var LD=Z((UD)=>{Object.defineProperty(UD,"__esModule",{value:!0});UD.formatLimitDefinition=void 0;var hK=wW(),lb=y(),Sw=lb.operators,u$={formatMaximum:{okStr:"<=",ok:Sw.LTE,fail:Sw.GT},formatMinimum:{okStr:">=",ok:Sw.GTE,fail:Sw.LT},formatExclusiveMaximum:{okStr:"<",ok:Sw.LT,fail:Sw.GTE},formatExclusiveMinimum:{okStr:">",ok:Sw.GT,fail:Sw.LTE}},cK={message:({keyword:b,schemaCode:w})=>lb.str`should be ${u$[b].okStr} ${w}`,params:({keyword:b,schemaCode:w})=>lb._`{comparison: ${u$[b].okStr}, limit: ${w}}`};UD.formatLimitDefinition={keyword:Object.keys(u$),type:"string",schemaType:"string",$data:!0,error:cK,code(b){let{gen:w,data:$,schemaCode:W,keyword:Q,it:G}=b,{opts:q,self:X}=G;if(!q.validateFormats)return;let Y=new hK.KeywordCxt(G,X.RULES.all.format.definition,"format");if(Y.$data)J();else D();function J(){let O=w.scopeValue("formats",{ref:X.formats,code:q.code.formats}),A=w.const("fmt",lb._`${O}[${Y.schemaCode}]`);b.fail$data((0,lb.or)(lb._`typeof ${A} != "object"`,lb._`${A} instanceof RegExp`,lb._`typeof ${A}.compare != "function"`,H(A)))}function D(){let O=Y.schema,A=X.formats[O];if(!A||A===!0)return;if(typeof A!="object"||A instanceof RegExp||typeof A.compare!="function")throw Error(`"${Q}": format "${O}" does not define "compare" function`);let B=w.scopeValue("formats",{key:O,ref:A,code:q.code.formats?lb._`${q.code.formats}${(0,lb.getProperty)(O)}`:void 0});b.fail$data(H(B))}function H(O){return lb._`${O}.compare(${$}, ${W}) ${u$[Q].fail} 0`}},dependencies:["format"]};var fK=(b)=>{return b.addKeyword(UD.formatLimitDefinition),b};UD.default=fK});var KD=Z((X0,FD)=>{Object.defineProperty(X0,"__esModule",{value:!0});var Q1=AD(),iK=LD(),JW=y(),PD=new JW.Name("fullFormats"),mK=new JW.Name("fastFormats"),DW=(b,w={keywords:!0})=>{if(Array.isArray(w))return BD(b,w,Q1.fullFormats,PD),b;let[$,W]=w.mode==="fast"?[Q1.fastFormats,mK]:[Q1.fullFormats,PD],Q=w.formats||Q1.formatNames;if(BD(b,Q,$,W),w.keywords)(0,iK.default)(b);return b};DW.get=(b,w="full")=>{let W=(w==="fast"?Q1.fastFormats:Q1.fullFormats)[b];if(!W)throw Error(`Unknown format "${b}"`);return W};function BD(b,w,$,W){var Q,G;(Q=(G=b.opts.code).formats)!==null&&Q!==void 0||(G.formats=JW._`require("ajv-formats/dist/formats").${W}`);for(let q of w)b.addFormat(q,$[q])}FD.exports=X0=DW;Object.defineProperty(X0,"__esModule",{value:!0});X0.default=DW});import{AsyncLocalStorage as Bz}from"node:async_hooks";class db extends Error{statusCode;rawDetails;code;context;constructor(b,w,$,W,Q){super(b);this.statusCode=w;this.rawDetails=$;this.code=W;this.context=Q;this.name="McpApiError"}}function Uz(b){if(b instanceof db)return{message:b.message,statusCode:b.statusCode,code:b.code,rawDetails:b.rawDetails,context:b.context};if(b instanceof Error)return{message:b.message};return{message:String(b)}}function Lz(b){let w=b.match(/api key is missing required scopes?:\s*(.+)$/i);if(!w?.[1])return[];return w[1].match(/[a-z_]+:[a-z_]+/gi)??[]}function Pz(b){let w=Uz(b),$=w.message.trim()||"Unknown error",W=$.toLowerCase(),Q=w.rawDetails?.trim()||$;if(w.context?.title||w.context?.description||w.context?.howToFix||w.context?.docsUrl)return{title:w.context.title??(w.statusCode===409?"Request conflict":"API request failed"),description:w.context.description??$,howToFix:w.context.howToFix??"Review the details below, adjust the tool input, and retry.",docsUrl:w.context.docsUrl??"https://docs.sequenzy.com/concepts/mcp",details:Q};if(w.code==="MCP_AUTH_REQUIRED"||W.includes("sequenzy_api_key environment variable is required"))return{title:"Missing MCP API key",description:"The MCP server started without a Sequenzy API key, so it cannot authenticate any tool or resource request.",howToFix:"Add `SEQUENZY_API_KEY` to the MCP server environment, or run `npx @sequenzy/setup` to configure the integration automatically.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(w.statusCode===401||w.code==="UNAUTHORIZED")return{title:"Authentication failed",description:"The MCP server reached Sequenzy, but the current API key was rejected.",howToFix:"Replace `SEQUENZY_API_KEY` with a valid personal API key, then restart the MCP client so it reconnects with fresh credentials.",docsUrl:"https://docs.sequenzy.com/authentication",details:Q};let G=Lz($);if(G.length>0){let q=G.map((Y)=>`\`${Y}\``).join(", "),X=G.every((Y)=>Y.endsWith(":read"))?"the Read-only or Safer agent access preset":"Safer agent access when it covers the task, or Custom permissions";return{title:"API key permission required",description:`The current API key is valid, but this operation requires the missing ${G.length===1?"scope":"scopes"}: ${q}.`,howToFix:`For a local API-key connection, call \`get_account\` to inspect \`apiKeyPermissions\` and open \`apiKeyPermissions.manageUrl\` (or \`companies[].settingsUrl\` → API Keys). If \`get_account\` also requires \`account:read\`, open ${"https://sequenzy.com/dashboard"} directly and use the MCP setup or Settings → API Keys. Create a replacement key with ${X} including ${q}, replace \`SEQUENZY_API_KEY\`, and restart the client. For hosted OAuth MCP, disconnect and reauthorize the Sequenzy connection with a preset or Custom permissions including ${q}. Existing key permissions cannot be edited in place.`,docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q}}if(w.statusCode===403||W.includes("access denied"))return{title:"Access denied",description:"The current API key is valid, but it does not have permission to access the requested company or action.",howToFix:"Use an API key that belongs to the right account, or select a company the key can access before retrying the tool call.",docsUrl:"https://docs.sequenzy.com/authentication",details:Q};if(W.includes("no company available")||W.includes("company not found"))return{title:"Company selection required",description:"The MCP server could not resolve a company for this request.",howToFix:"Call `get_account` to inspect available companies, then call `select_company`, or pass `companyId` explicitly in the next tool call.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(w.statusCode===404||W.includes("not found"))return{title:"Requested resource not found",description:"Sequenzy could not find the requested campaign, template, sequence, company, or subscriber.",howToFix:"List or fetch the resource collection first, then retry the tool with a confirmed ID or email value.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(w.statusCode===409||W.includes("already exists"))return{title:"Resource already exists",description:"Sequenzy rejected this MCP request because it would create a duplicate resource.",howToFix:"List the existing resources first, reuse the matching resource when appropriate, or retry with a unique name or domain.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(w.statusCode===429||W.includes("rate limit"))return{title:"Rate limited",description:"Sequenzy temporarily slowed this MCP request because too many requests were sent too quickly.",howToFix:"Wait briefly before retrying. If the client is looping, reduce retries or add backoff before the next tool call.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(w.code==="NETWORK_ERROR"||W.includes("fetch failed"))return{title:"Network or configuration error",description:"The MCP server could not reach the Sequenzy API from this environment.",howToFix:"Check connectivity and verify `SEQUENZY_API_URL` if you override it in the MCP environment.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(W.includes("unknown tool")||W.includes("unknown resource"))return{title:"Unsupported MCP request",description:"The client asked for a tool or resource name that this Sequenzy MCP server does not expose.",howToFix:"Refresh the client's tool list and call only the names returned by `list_tools` or `list_resources`.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(W.includes("is required")||W.includes("invalid"))return{title:"Invalid MCP input",description:"The tool call was missing a required field or included an invalid value.",howToFix:"Review the tool schema, supply the missing argument, and retry the request with corrected input.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(w.statusCode&&w.statusCode>=500)return{title:"Sequenzy server error",description:"The request reached Sequenzy, but the server could not complete it successfully.",howToFix:"Retry once. If it still fails, keep the details below and consult the docs before escalating.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};return{title:"Tool execution failed",description:"The MCP server could not complete the requested operation.",howToFix:"Review the details below, adjust the tool input or credentials, and retry.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q}}function Uw(b){let w=Pz(b);return[`Sequenzy MCP error: ${w.title}`,`Description: ${w.description}`,`How to fix: ${w.howToFix}`,`Docs: ${w.docsUrl}`,`Details: ${w.details}`].join(`
|
|
10
|
-
`)}var Fz="https://api.sequenzy.com",O1=new Bz,oW=!1;function dW(){oW=!0}function A0(){return oW}var tW=null;function Lw(){let b=O1.getStore();if(b)return b.selectedCompanyId??null;return tW}function U0(b){let w=O1.getStore();if(w){w.selectedCompanyId=b;return}tW=b}function w4(b,w){return O1.run(b,w)}function rW(){return O1.getStore()?.apiUrl??process.env.SEQUENZY_API_URL??Fz}function eW(){return O1.getStore()?.apiKey??process.env.SEQUENZY_API_KEY}function sW(b,w){let $=eW();if(!$)throw new db("SEQUENZY_API_KEY environment variable is required",401,void 0,"MCP_AUTH_REQUIRED");let W={"Content-Type":b,Authorization:`Bearer ${$}`},Q=w??Lw();if(Q)W["x-company-id"]=Q;return W}function aW(){if(eW())return;console.error(Uw(new db("SEQUENZY_API_KEY environment variable is required",401,void 0,"MCP_AUTH_REQUIRED"))),process.exit(1)}function Nb(b,w){let $=b[w];return typeof $==="string"&&$.trim()!==""?$.trim():void 0}function Kz(b){if(b===void 0)return;if(typeof b==="string")return b.trim()||void 0;return JSON.stringify(b)}function b9(b){if(!b.trim())return{message:"Request failed"};try{let w=JSON.parse(b);if(typeof w==="string")return{message:w};let $=typeof w.error==="object"&&w.error!==null?w.error:void 0,W=Nb(w,"code")??($?Nb($,"code"):void 0),Q=(typeof w.error==="string"?w.error:void 0)??($?Nb($,"message"):void 0)??Nb(w,"message")??Nb(w,"error")??b,G=Nb(w,"howToFix")??Nb(w,"resolution"),q={...Nb(w,"title")?{title:Nb(w,"title")}:{},...Nb(w,"description")?{description:Nb(w,"description")}:{},...G?{howToFix:G}:{},...Nb(w,"docsUrl")?{docsUrl:Nb(w,"docsUrl")}:{}},X=Kz(w.details);if(Object.keys(q).length>0||X)return{message:Q,...W?{code:W}:{},...X?{details:X}:{},...Object.keys(q).length>0?{context:q}:{}};if(typeof w.error==="string")return{message:w.error,...W?{code:W}:{}};if($)return{message:Q,...W?{code:W}:{}};return{message:Q,...W?{code:W}:{}}}catch{return{message:b}}}async function z(b,w,$,W){let Q=sW("application/json",W),G;try{G=await fetch(`${rW()}${w}`,{method:b,headers:Q,body:$?JSON.stringify($):void 0})}catch(q){throw new db(q instanceof Error?q.message:"Failed to reach Sequenzy API",0,void 0,"NETWORK_ERROR")}if(!G.ok){let q=await G.text(),X=b9(q);throw new db(X.message,G.status,X.details??q,X.code,X.context)}return G.json()}async function w9(b,w,$,W){let Q=new URL(rW()).origin,G=new URL(b,`${Q}/`);if(G.origin!==Q)throw new db("The image upload URL did not point to the configured Sequenzy API.",500,void 0,"INVALID_UPLOAD_URL");let q;try{q=await fetch(G,{method:"PUT",headers:sW($,W),body:w})}catch(X){throw new db(X instanceof Error?X.message:"Failed to upload image bytes",0,void 0,"NETWORK_ERROR")}if(!q.ok){let X=await q.text(),Y=b9(X);throw new db(Y.message,q.status,Y.details??X,Y.code,Y.context)}}var QI=Object.freeze({status:"aborted"});function P(b,w,$){function W(X,Y){var J;Object.defineProperty(X,"_zod",{value:X._zod??{},enumerable:!1}),(J=X._zod).traits??(J.traits=new Set),X._zod.traits.add(b),w(X,Y);for(let D in q.prototype)if(!(D in X))Object.defineProperty(X,D,{value:q.prototype[D].bind(X)});X._zod.constr=q,X._zod.def=Y}let Q=$?.Parent??Object;class G extends Q{}Object.defineProperty(G,"name",{value:b});function q(X){var Y;let J=$?.Parent?new G:this;W(J,X),(Y=J._zod).deferred??(Y.deferred=[]);for(let D of J._zod.deferred)D();return J}return Object.defineProperty(q,"init",{value:W}),Object.defineProperty(q,Symbol.hasInstance,{value:(X)=>{if($?.Parent&&X instanceof $.Parent)return!0;return X?._zod?.traits?.has(b)}}),Object.defineProperty(q,"name",{value:b}),q}var GI=Symbol("zod_brand");class ww extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class A1 extends Error{constructor(b){super(`Encountered unidirectional transform during encode: ${b}`);this.name="ZodEncodeError"}}var L0={};function vb(b){if(b)Object.assign(L0,b);return L0}var l={};pW(l,{unwrapMessage:()=>U1,uint8ArrayToHex:()=>gz,uint8ArrayToBase64url:()=>mz,uint8ArrayToBase64:()=>Y9,stringifyPrimitive:()=>K0,shallowClone:()=>W9,safeExtend:()=>yz,required:()=>fz,randomString:()=>Sz,propertyKeyTypes:()=>q4,promiseAllObject:()=>Tz,primitiveTypes:()=>Q9,prefixIssues:()=>Ww,pick:()=>Cz,partial:()=>cz,optionalKeys:()=>X4,omit:()=>uz,objectClone:()=>Vz,numKeys:()=>Rz,nullish:()=>L1,normalizeParams:()=>S,mergeDefs:()=>Bw,merge:()=>hz,jsonStringifyReplacer:()=>fw,joinValues:()=>P0,issue:()=>iw,isPlainObject:()=>Fw,isObject:()=>vw,hexToUint8Array:()=>lz,getSizableOrigin:()=>q9,getParsedType:()=>vz,getLengthableOrigin:()=>B1,getEnumValues:()=>W4,getElementAtPath:()=>Ez,floatSafeRemainder:()=>Q4,finalizeIssue:()=>hb,extend:()=>xz,escapeRegex:()=>$w,esc:()=>B0,defineLazy:()=>d,createTransparentProxy:()=>kz,cloneDef:()=>Nz,clone:()=>yb,cleanRegex:()=>P1,cleanEnum:()=>nz,captureStackTrace:()=>F0,cached:()=>nw,base64urlToUint8Array:()=>iz,base64ToUint8Array:()=>X9,assignProp:()=>Pw,assertNotEqual:()=>Iz,assertNever:()=>Zz,assertIs:()=>_z,assertEqual:()=>Mz,assert:()=>jz,allowsEval:()=>G4,aborted:()=>Kw,NUMBER_FORMAT_RANGES:()=>Y4,Class:()=>J9,BIGINT_FORMAT_RANGES:()=>G9});function Mz(b){return b}function Iz(b){return b}function _z(b){}function Zz(b){throw Error()}function jz(b){}function W4(b){let w=Object.values(b).filter((W)=>typeof W==="number");return Object.entries(b).filter(([W,Q])=>w.indexOf(+W)===-1).map(([W,Q])=>Q)}function P0(b,w="|"){return b.map(($)=>K0($)).join(w)}function fw(b,w){if(typeof w==="bigint")return w.toString();return w}function nw(b){return{get value(){{let $=b();return Object.defineProperty(this,"value",{value:$}),$}throw Error("cached value already set")}}}function L1(b){return b===null||b===void 0}function P1(b){let w=b.startsWith("^")?1:0,$=b.endsWith("$")?b.length-1:b.length;return b.slice(w,$)}function Q4(b,w){let $=(b.toString().split(".")[1]||"").length,W=w.toString(),Q=(W.split(".")[1]||"").length;if(Q===0&&/\d?e-\d?/.test(W)){let Y=W.match(/\d?e-(\d?)/);if(Y?.[1])Q=Number.parseInt(Y[1])}let G=$>Q?$:Q,q=Number.parseInt(b.toFixed(G).replace(".","")),X=Number.parseInt(w.toFixed(G).replace(".",""));return q%X/10**G}var $9=Symbol("evaluating");function d(b,w,$){let W=void 0;Object.defineProperty(b,w,{get(){if(W===$9)return;if(W===void 0)W=$9,W=$();return W},set(Q){Object.defineProperty(b,w,{value:Q})},configurable:!0})}function Vz(b){return Object.create(Object.getPrototypeOf(b),Object.getOwnPropertyDescriptors(b))}function Pw(b,w,$){Object.defineProperty(b,w,{value:$,writable:!0,enumerable:!0,configurable:!0})}function Bw(...b){let w={};for(let $ of b){let W=Object.getOwnPropertyDescriptors($);Object.assign(w,W)}return Object.defineProperties({},w)}function Nz(b){return Bw(b._zod.def)}function Ez(b,w){if(!w)return b;return w.reduce(($,W)=>$?.[W],b)}function Tz(b){let w=Object.keys(b),$=w.map((W)=>b[W]);return Promise.all($).then((W)=>{let Q={};for(let G=0;G<w.length;G++)Q[w[G]]=W[G];return Q})}function Sz(b=10){let $="";for(let W=0;W<b;W++)$+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return $}function B0(b){return JSON.stringify(b)}var F0="captureStackTrace"in Error?Error.captureStackTrace:(...b)=>{};function vw(b){return typeof b==="object"&&b!==null&&!Array.isArray(b)}var G4=nw(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(b){return!1}});function Fw(b){if(vw(b)===!1)return!1;let w=b.constructor;if(w===void 0)return!0;let $=w.prototype;if(vw($)===!1)return!1;if(Object.prototype.hasOwnProperty.call($,"isPrototypeOf")===!1)return!1;return!0}function W9(b){if(Fw(b))return{...b};if(Array.isArray(b))return[...b];return b}function Rz(b){let w=0;for(let $ in b)if(Object.prototype.hasOwnProperty.call(b,$))w++;return w}var vz=(b)=>{let w=typeof b;switch(w){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(b)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(b))return"array";if(b===null)return"null";if(b.then&&typeof b.then==="function"&&b.catch&&typeof b.catch==="function")return"promise";if(typeof Map<"u"&&b instanceof Map)return"map";if(typeof Set<"u"&&b instanceof Set)return"set";if(typeof Date<"u"&&b instanceof Date)return"date";if(typeof File<"u"&&b instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${w}`)}},q4=new Set(["string","number","symbol"]),Q9=new Set(["string","number","bigint","boolean","symbol","undefined"]);function $w(b){return b.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function yb(b,w,$){let W=new b._zod.constr(w??b._zod.def);if(!w||$?.parent)W._zod.parent=b;return W}function S(b){let w=b;if(!w)return{};if(typeof w==="string")return{error:()=>w};if(w?.message!==void 0){if(w?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");w.error=w.message}if(delete w.message,typeof w.error==="string")return{...w,error:()=>w.error};return w}function kz(b){let w;return new Proxy({},{get($,W,Q){return w??(w=b()),Reflect.get(w,W,Q)},set($,W,Q,G){return w??(w=b()),Reflect.set(w,W,Q,G)},has($,W){return w??(w=b()),Reflect.has(w,W)},deleteProperty($,W){return w??(w=b()),Reflect.deleteProperty(w,W)},ownKeys($){return w??(w=b()),Reflect.ownKeys(w)},getOwnPropertyDescriptor($,W){return w??(w=b()),Reflect.getOwnPropertyDescriptor(w,W)},defineProperty($,W,Q){return w??(w=b()),Reflect.defineProperty(w,W,Q)}})}function K0(b){if(typeof b==="bigint")return b.toString()+"n";if(typeof b==="string")return`"${b}"`;return`${b}`}function X4(b){return Object.keys(b).filter((w)=>{return b[w]._zod.optin==="optional"&&b[w]._zod.optout==="optional"})}var Y4={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]},G9={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function Cz(b,w){let $=b._zod.def,W=Bw(b._zod.def,{get shape(){let Q={};for(let G in w){if(!(G in $.shape))throw Error(`Unrecognized key: "${G}"`);if(!w[G])continue;Q[G]=$.shape[G]}return Pw(this,"shape",Q),Q},checks:[]});return yb(b,W)}function uz(b,w){let $=b._zod.def,W=Bw(b._zod.def,{get shape(){let Q={...b._zod.def.shape};for(let G in w){if(!(G in $.shape))throw Error(`Unrecognized key: "${G}"`);if(!w[G])continue;delete Q[G]}return Pw(this,"shape",Q),Q},checks:[]});return yb(b,W)}function xz(b,w){if(!Fw(w))throw Error("Invalid input to extend: expected a plain object");let $=b._zod.def.checks;if($&&$.length>0)throw Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");let Q=Bw(b._zod.def,{get shape(){let G={...b._zod.def.shape,...w};return Pw(this,"shape",G),G},checks:[]});return yb(b,Q)}function yz(b,w){if(!Fw(w))throw Error("Invalid input to safeExtend: expected a plain object");let $={...b._zod.def,get shape(){let W={...b._zod.def.shape,...w};return Pw(this,"shape",W),W},checks:b._zod.def.checks};return yb(b,$)}function hz(b,w){let $=Bw(b._zod.def,{get shape(){let W={...b._zod.def.shape,...w._zod.def.shape};return Pw(this,"shape",W),W},get catchall(){return w._zod.def.catchall},checks:[]});return yb(b,$)}function cz(b,w,$){let W=Bw(w._zod.def,{get shape(){let Q=w._zod.def.shape,G={...Q};if($)for(let q in $){if(!(q in Q))throw Error(`Unrecognized key: "${q}"`);if(!$[q])continue;G[q]=b?new b({type:"optional",innerType:Q[q]}):Q[q]}else for(let q in Q)G[q]=b?new b({type:"optional",innerType:Q[q]}):Q[q];return Pw(this,"shape",G),G},checks:[]});return yb(w,W)}function fz(b,w,$){let W=Bw(w._zod.def,{get shape(){let Q=w._zod.def.shape,G={...Q};if($)for(let q in $){if(!(q in G))throw Error(`Unrecognized key: "${q}"`);if(!$[q])continue;G[q]=new b({type:"nonoptional",innerType:Q[q]})}else for(let q in Q)G[q]=new b({type:"nonoptional",innerType:Q[q]});return Pw(this,"shape",G),G},checks:[]});return yb(w,W)}function Kw(b,w=0){if(b.aborted===!0)return!0;for(let $=w;$<b.issues.length;$++)if(b.issues[$]?.continue!==!0)return!0;return!1}function Ww(b,w){return w.map(($)=>{var W;return(W=$).path??(W.path=[]),$.path.unshift(b),$})}function U1(b){return typeof b==="string"?b:b?.message}function hb(b,w,$){let W={...b,path:b.path??[]};if(!b.message){let Q=U1(b.inst?._zod.def?.error?.(b))??U1(w?.error?.(b))??U1($.customError?.(b))??U1($.localeError?.(b))??"Invalid input";W.message=Q}if(delete W.inst,delete W.continue,!w?.reportInput)delete W.input;return W}function q9(b){if(b instanceof Set)return"set";if(b instanceof Map)return"map";if(b instanceof File)return"file";return"unknown"}function B1(b){if(Array.isArray(b))return"array";if(typeof b==="string")return"string";return"unknown"}function iw(...b){let[w,$,W]=b;if(typeof w==="string")return{message:w,code:"custom",input:$,inst:W};return{...w}}function nz(b){return Object.entries(b).filter(([w,$])=>{return Number.isNaN(Number.parseInt(w,10))}).map((w)=>w[1])}function X9(b){let w=atob(b),$=new Uint8Array(w.length);for(let W=0;W<w.length;W++)$[W]=w.charCodeAt(W);return $}function Y9(b){let w="";for(let $=0;$<b.length;$++)w+=String.fromCharCode(b[$]);return btoa(w)}function iz(b){let w=b.replace(/-/g,"+").replace(/_/g,"/"),$="=".repeat((4-w.length%4)%4);return X9(w+$)}function mz(b){return Y9(b).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function lz(b){let w=b.replace(/^0x/,"");if(w.length%2!==0)throw Error("Invalid hex string length");let $=new Uint8Array(w.length/2);for(let W=0;W<w.length;W+=2)$[W/2]=Number.parseInt(w.slice(W,W+2),16);return $}function gz(b){return Array.from(b).map((w)=>w.toString(16).padStart(2,"0")).join("")}class J9{constructor(...b){}}var D9=(b,w)=>{b.name="$ZodError",Object.defineProperty(b,"_zod",{value:b._zod,enumerable:!1}),Object.defineProperty(b,"issues",{value:w,enumerable:!1}),b.message=JSON.stringify(w,fw,2),Object.defineProperty(b,"toString",{value:()=>b.message,enumerable:!1})},M0=P("$ZodError",D9),J4=P("$ZodError",D9,{Parent:Error});function H9(b,w=($)=>$.message){let $={},W=[];for(let Q of b.issues)if(Q.path.length>0)$[Q.path[0]]=$[Q.path[0]]||[],$[Q.path[0]].push(w(Q));else W.push(w(Q));return{formErrors:W,fieldErrors:$}}function z9(b,w=($)=>$.message){let $={_errors:[]},W=(Q)=>{for(let G of Q.issues)if(G.code==="invalid_union"&&G.errors.length)G.errors.map((q)=>W({issues:q}));else if(G.code==="invalid_key")W({issues:G.issues});else if(G.code==="invalid_element")W({issues:G.issues});else if(G.path.length===0)$._errors.push(w(G));else{let q=$,X=0;while(X<G.path.length){let Y=G.path[X];if(X!==G.path.length-1)q[Y]=q[Y]||{_errors:[]};else q[Y]=q[Y]||{_errors:[]},q[Y]._errors.push(w(G));q=q[Y],X++}}};return W(b),$}var I0=(b)=>(w,$,W,Q)=>{let G=W?Object.assign(W,{async:!1}):{async:!1},q=w._zod.run({value:$,issues:[]},G);if(q instanceof Promise)throw new ww;if(q.issues.length){let X=new(Q?.Err??b)(q.issues.map((Y)=>hb(Y,G,vb())));throw F0(X,Q?.callee),X}return q.value};var _0=(b)=>async(w,$,W,Q)=>{let G=W?Object.assign(W,{async:!0}):{async:!0},q=w._zod.run({value:$,issues:[]},G);if(q instanceof Promise)q=await q;if(q.issues.length){let X=new(Q?.Err??b)(q.issues.map((Y)=>hb(Y,G,vb())));throw F0(X,Q?.callee),X}return q.value};var F1=(b)=>(w,$,W)=>{let Q=W?{...W,async:!1}:{async:!1},G=w._zod.run({value:$,issues:[]},Q);if(G instanceof Promise)throw new ww;return G.issues.length?{success:!1,error:new(b??M0)(G.issues.map((q)=>hb(q,Q,vb())))}:{success:!0,data:G.value}},K1=F1(J4),M1=(b)=>async(w,$,W)=>{let Q=W?Object.assign(W,{async:!0}):{async:!0},G=w._zod.run({value:$,issues:[]},Q);if(G instanceof Promise)G=await G;return G.issues.length?{success:!1,error:new b(G.issues.map((q)=>hb(q,Q,vb())))}:{success:!0,data:G.value}},Z0=M1(J4),O9=(b)=>(w,$,W)=>{let Q=W?Object.assign(W,{direction:"backward"}):{direction:"backward"};return I0(b)(w,$,Q)};var A9=(b)=>(w,$,W)=>{return I0(b)(w,$,W)};var U9=(b)=>async(w,$,W)=>{let Q=W?Object.assign(W,{direction:"backward"}):{direction:"backward"};return _0(b)(w,$,Q)};var L9=(b)=>async(w,$,W)=>{return _0(b)(w,$,W)};var P9=(b)=>(w,$,W)=>{let Q=W?Object.assign(W,{direction:"backward"}):{direction:"backward"};return F1(b)(w,$,Q)};var B9=(b)=>(w,$,W)=>{return F1(b)(w,$,W)};var F9=(b)=>async(w,$,W)=>{let Q=W?Object.assign(W,{direction:"backward"}):{direction:"backward"};return M1(b)(w,$,Q)};var K9=(b)=>async(w,$,W)=>{return M1(b)(w,$,W)};var M9=/^[cC][^\s-]{8,}$/,I9=/^[0-9a-z]+$/,_9=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Z9=/^[0-9a-vA-V]{20}$/,j9=/^[A-Za-z0-9]{27}$/,V9=/^[a-zA-Z0-9_-]{21}$/,N9=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var E9=/^([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})$/,D4=(b)=>{if(!b)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${b}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)};var T9=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function S9(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}var R9=/^(?:(?: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])$/,v9=/^(([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}|:))$/,k9=/^((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])$/,C9=/^(([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])$/,u9=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,H4=/^[A-Za-z0-9_-]*$/,x9=/^(?=.{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 y9=/^\+(?:[0-9]){6,14}[0-9]$/,h9="(?:(?:\\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])))",c9=new RegExp(`^${h9}$`);function f9(b){return typeof b.precision==="number"?b.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":b.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${b.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function n9(b){return new RegExp(`^${f9(b)}$`)}function i9(b){let w=f9({precision:b.precision}),$=["Z"];if(b.local)$.push("");if(b.offset)$.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let W=`${w}(?:${$.join("|")})`;return new RegExp(`^${h9}T(?:${W})$`)}var m9=(b)=>{let w=b?`[\\s\\S]{${b?.minimum??0},${b?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${w}$`)};var l9=/^-?\d+$/,g9=/^-?\d+(?:\.\d+)?/,p9=/^(?:true|false)$/i,o9=/^null$/i;var d9=/^[^A-Z]*$/,t9=/^[^a-z]*$/;var Hb=P("$ZodCheck",(b,w)=>{var $;b._zod??(b._zod={}),b._zod.def=w,($=b._zod).onattach??($.onattach=[])}),r9={number:"number",bigint:"bigint",object:"date"},z4=P("$ZodCheckLessThan",(b,w)=>{Hb.init(b,w);let $=r9[typeof w.value];b._zod.onattach.push((W)=>{let Q=W._zod.bag,G=(w.inclusive?Q.maximum:Q.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(w.value<G)if(w.inclusive)Q.maximum=w.value;else Q.exclusiveMaximum=w.value}),b._zod.check=(W)=>{if(w.inclusive?W.value<=w.value:W.value<w.value)return;W.issues.push({origin:$,code:"too_big",maximum:w.value,input:W.value,inclusive:w.inclusive,inst:b,continue:!w.abort})}}),O4=P("$ZodCheckGreaterThan",(b,w)=>{Hb.init(b,w);let $=r9[typeof w.value];b._zod.onattach.push((W)=>{let Q=W._zod.bag,G=(w.inclusive?Q.minimum:Q.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(w.value>G)if(w.inclusive)Q.minimum=w.value;else Q.exclusiveMinimum=w.value}),b._zod.check=(W)=>{if(w.inclusive?W.value>=w.value:W.value>w.value)return;W.issues.push({origin:$,code:"too_small",minimum:w.value,input:W.value,inclusive:w.inclusive,inst:b,continue:!w.abort})}}),e9=P("$ZodCheckMultipleOf",(b,w)=>{Hb.init(b,w),b._zod.onattach.push(($)=>{var W;(W=$._zod.bag).multipleOf??(W.multipleOf=w.value)}),b._zod.check=($)=>{if(typeof $.value!==typeof w.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof $.value==="bigint"?$.value%w.value===BigInt(0):Q4($.value,w.value)===0)return;$.issues.push({origin:typeof $.value,code:"not_multiple_of",divisor:w.value,input:$.value,inst:b,continue:!w.abort})}}),s9=P("$ZodCheckNumberFormat",(b,w)=>{Hb.init(b,w),w.format=w.format||"float64";let $=w.format?.includes("int"),W=$?"int":"number",[Q,G]=Y4[w.format];b._zod.onattach.push((q)=>{let X=q._zod.bag;if(X.format=w.format,X.minimum=Q,X.maximum=G,$)X.pattern=l9}),b._zod.check=(q)=>{let X=q.value;if($){if(!Number.isInteger(X)){q.issues.push({expected:W,format:w.format,code:"invalid_type",continue:!1,input:X,inst:b});return}if(!Number.isSafeInteger(X)){if(X>0)q.issues.push({input:X,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:b,origin:W,continue:!w.abort});else q.issues.push({input:X,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:b,origin:W,continue:!w.abort});return}}if(X<Q)q.issues.push({origin:"number",input:X,code:"too_small",minimum:Q,inclusive:!0,inst:b,continue:!w.abort});if(X>G)q.issues.push({origin:"number",input:X,code:"too_big",maximum:G,inst:b})}});var a9=P("$ZodCheckMaxLength",(b,w)=>{var $;Hb.init(b,w),($=b._zod.def).when??($.when=(W)=>{let Q=W.value;return!L1(Q)&&Q.length!==void 0}),b._zod.onattach.push((W)=>{let Q=W._zod.bag.maximum??Number.POSITIVE_INFINITY;if(w.maximum<Q)W._zod.bag.maximum=w.maximum}),b._zod.check=(W)=>{let Q=W.value;if(Q.length<=w.maximum)return;let q=B1(Q);W.issues.push({origin:q,code:"too_big",maximum:w.maximum,inclusive:!0,input:Q,inst:b,continue:!w.abort})}}),bQ=P("$ZodCheckMinLength",(b,w)=>{var $;Hb.init(b,w),($=b._zod.def).when??($.when=(W)=>{let Q=W.value;return!L1(Q)&&Q.length!==void 0}),b._zod.onattach.push((W)=>{let Q=W._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(w.minimum>Q)W._zod.bag.minimum=w.minimum}),b._zod.check=(W)=>{let Q=W.value;if(Q.length>=w.minimum)return;let q=B1(Q);W.issues.push({origin:q,code:"too_small",minimum:w.minimum,inclusive:!0,input:Q,inst:b,continue:!w.abort})}}),wQ=P("$ZodCheckLengthEquals",(b,w)=>{var $;Hb.init(b,w),($=b._zod.def).when??($.when=(W)=>{let Q=W.value;return!L1(Q)&&Q.length!==void 0}),b._zod.onattach.push((W)=>{let Q=W._zod.bag;Q.minimum=w.length,Q.maximum=w.length,Q.length=w.length}),b._zod.check=(W)=>{let Q=W.value,G=Q.length;if(G===w.length)return;let q=B1(Q),X=G>w.length;W.issues.push({origin:q,...X?{code:"too_big",maximum:w.length}:{code:"too_small",minimum:w.length},inclusive:!0,exact:!0,input:W.value,inst:b,continue:!w.abort})}}),I1=P("$ZodCheckStringFormat",(b,w)=>{var $,W;if(Hb.init(b,w),b._zod.onattach.push((Q)=>{let G=Q._zod.bag;if(G.format=w.format,w.pattern)G.patterns??(G.patterns=new Set),G.patterns.add(w.pattern)}),w.pattern)($=b._zod).check??($.check=(Q)=>{if(w.pattern.lastIndex=0,w.pattern.test(Q.value))return;Q.issues.push({origin:"string",code:"invalid_format",format:w.format,input:Q.value,...w.pattern?{pattern:w.pattern.toString()}:{},inst:b,continue:!w.abort})});else(W=b._zod).check??(W.check=()=>{})}),$Q=P("$ZodCheckRegex",(b,w)=>{I1.init(b,w),b._zod.check=($)=>{if(w.pattern.lastIndex=0,w.pattern.test($.value))return;$.issues.push({origin:"string",code:"invalid_format",format:"regex",input:$.value,pattern:w.pattern.toString(),inst:b,continue:!w.abort})}}),WQ=P("$ZodCheckLowerCase",(b,w)=>{w.pattern??(w.pattern=d9),I1.init(b,w)}),QQ=P("$ZodCheckUpperCase",(b,w)=>{w.pattern??(w.pattern=t9),I1.init(b,w)}),GQ=P("$ZodCheckIncludes",(b,w)=>{Hb.init(b,w);let $=$w(w.includes),W=new RegExp(typeof w.position==="number"?`^.{${w.position}}${$}`:$);w.pattern=W,b._zod.onattach.push((Q)=>{let G=Q._zod.bag;G.patterns??(G.patterns=new Set),G.patterns.add(W)}),b._zod.check=(Q)=>{if(Q.value.includes(w.includes,w.position))return;Q.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:w.includes,input:Q.value,inst:b,continue:!w.abort})}}),qQ=P("$ZodCheckStartsWith",(b,w)=>{Hb.init(b,w);let $=new RegExp(`^${$w(w.prefix)}.*`);w.pattern??(w.pattern=$),b._zod.onattach.push((W)=>{let Q=W._zod.bag;Q.patterns??(Q.patterns=new Set),Q.patterns.add($)}),b._zod.check=(W)=>{if(W.value.startsWith(w.prefix))return;W.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:w.prefix,input:W.value,inst:b,continue:!w.abort})}}),XQ=P("$ZodCheckEndsWith",(b,w)=>{Hb.init(b,w);let $=new RegExp(`.*${$w(w.suffix)}$`);w.pattern??(w.pattern=$),b._zod.onattach.push((W)=>{let Q=W._zod.bag;Q.patterns??(Q.patterns=new Set),Q.patterns.add($)}),b._zod.check=(W)=>{if(W.value.endsWith(w.suffix))return;W.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:w.suffix,input:W.value,inst:b,continue:!w.abort})}});var YQ=P("$ZodCheckOverwrite",(b,w)=>{Hb.init(b,w),b._zod.check=($)=>{$.value=w.tx($.value)}});class A4{constructor(b=[]){if(this.content=[],this.indent=0,this)this.args=b}indented(b){this.indent+=1,b(this),this.indent-=1}write(b){if(typeof b==="function"){b(this,{execution:"sync"}),b(this,{execution:"async"});return}let $=b.split(`
|
|
11
|
-
`).filter((
|
|
12
|
-
`))}}var
|
|
9
|
+
deps: ${$}}`};var eB={keyword:"dependencies",type:"object",schemaType:"object",error:XJ.error,code(b){let[w,$]=sB(b);qJ(b,w),GJ(b,$)}};function sB({schema:b}){let w={},$={};for(let W in b){if(W==="__proto__")continue;let Q=Array.isArray(b[W])?w:$;Q[W]=b[W]}return[w,$]}function qJ(b,w=b.schema){let{gen:$,data:W,it:Q}=b;if(Object.keys(w).length===0)return;let q=$.let("missing");for(let G in w){let X=w[G];if(X.length===0)continue;let Y=(0,q0.propertyInData)($,W,G,Q.opts.ownProperties);if(b.setParams({property:G,depsCount:X.length,deps:X.join(", ")}),Q.allErrors)$.if(Y,()=>{for(let J of X)(0,q0.checkReportMissingProp)(b,J)});else $.if(r6._`${Y} && (${(0,q0.checkMissingProp)(b,X,q)})`),(0,q0.reportMissingProp)(b,q),$.else()}}XJ.validatePropertyDeps=qJ;function GJ(b,w=b.schema){let{gen:$,data:W,keyword:Q,it:q}=b,G=$.name("valid");for(let X in w){if((0,rB.alwaysValidSchema)(q,w[X]))continue;$.if((0,q0.propertyInData)($,W,X,q.opts.ownProperties),()=>{let Y=b.subschema({keyword:Q,schemaProp:X},G);b.mergeValidEvaluated(Y,G)},()=>$.var(G,!0)),b.ok(G)}}XJ.validateSchemaDeps=GJ;XJ.default=eB});var OJ=j((zJ)=>{Object.defineProperty(zJ,"__esModule",{value:!0});var HJ=y(),wF=g(),$F={message:"property name must be valid",params:({params:b})=>HJ._`{propertyName: ${b.propertyName}}`},WF={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:$F,code(b){let{gen:w,schema:$,data:W,it:Q}=b;if((0,wF.alwaysValidSchema)(Q,$))return;let q=w.name("valid");w.forIn("key",W,(G)=>{b.setParams({propertyName:G}),b.subschema({keyword:"propertyNames",data:G,dataTypes:["string"],propertyName:G,compositeRule:!0},q),w.if((0,HJ.not)(q),()=>{if(b.error(!0),!Q.allErrors)w.break()})}),b.ok(q)}};zJ.default=WF});var e6=j((AJ)=>{Object.defineProperty(AJ,"__esModule",{value:!0});var T$=ub(),mb=y(),qF=Gw(),S$=g(),GF={message:"must NOT have additional properties",params:({params:b})=>mb._`{additionalProperty: ${b.additionalProperty}}`},XF={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:GF,code(b){let{gen:w,schema:$,parentSchema:W,data:Q,errsCount:q,it:G}=b;if(!q)throw Error("ajv implementation error");let{allErrors:X,opts:Y}=G;if(G.props=!0,Y.removeAdditional!=="all"&&(0,S$.alwaysValidSchema)(G,$))return;let J=(0,T$.allSchemaProperties)(W.properties),D=(0,T$.allSchemaProperties)(W.patternProperties);H(),b.ok(mb._`${q} === ${qF.default.errors}`);function H(){w.forIn("key",Q,(_)=>{if(!J.length&&!D.length)B(_);else w.if(O(_),()=>B(_))})}function O(_){let I;if(J.length>8){let R=(0,S$.schemaRefOrVal)(G,W.properties,"properties");I=(0,T$.isOwnProperty)(w,R,_)}else if(J.length)I=(0,mb.or)(...J.map((R)=>mb._`${_} === ${R}`));else I=mb.nil;if(D.length)I=(0,mb.or)(I,...D.map((R)=>mb._`${(0,T$.usePattern)(b,R)}.test(${_})`));return(0,mb.not)(I)}function A(_){w.code(mb._`delete ${Q}[${_}]`)}function B(_){if(Y.removeAdditional==="all"||Y.removeAdditional&&$===!1){A(_);return}if($===!1){if(b.setParams({additionalProperty:_}),b.error(),!X)w.break();return}if(typeof $=="object"&&!(0,S$.alwaysValidSchema)(G,$)){let I=w.name("valid");if(Y.removeAdditional==="failing")K(_,I,!1),w.if((0,mb.not)(I),()=>{b.reset(),A(_)});else if(K(_,I),!X)w.if((0,mb.not)(I),()=>w.break())}}function K(_,I,R){let T={keyword:"additionalProperties",dataProp:_,dataPropType:S$.Type.Str};if(R===!1)Object.assign(T,{compositeRule:!0,createErrors:!1,allErrors:!1});b.subschema(T,I)}}};AJ.default=XF});var BJ=j((PJ)=>{Object.defineProperty(PJ,"__esModule",{value:!0});var JF=o1(),LJ=ub(),s6=g(),UJ=e6(),DF={keyword:"properties",type:"object",schemaType:"object",code(b){let{gen:w,schema:$,parentSchema:W,data:Q,it:q}=b;if(q.opts.removeAdditional==="all"&&W.additionalProperties===void 0)UJ.default.code(new JF.KeywordCxt(q,UJ.default,"additionalProperties"));let G=(0,LJ.allSchemaProperties)($);for(let H of G)q.definedProperties.add(H);if(q.opts.unevaluated&&G.length&&q.props!==!0)q.props=s6.mergeEvaluated.props(w,(0,s6.toHash)(G),q.props);let X=G.filter((H)=>!(0,s6.alwaysValidSchema)(q,$[H]));if(X.length===0)return;let Y=w.name("valid");for(let H of X){if(J(H))D(H);else{if(w.if((0,LJ.propertyInData)(w,Q,H,q.opts.ownProperties)),D(H),!q.allErrors)w.else().var(Y,!0);w.endIf()}b.it.definedProperties.add(H),b.ok(Y)}function J(H){return q.opts.useDefaults&&!q.compositeRule&&$[H].default!==void 0}function D(H){b.subschema({keyword:"properties",schemaProp:H,dataProp:H},Y)}}};PJ.default=DF});var _J=j((IJ)=>{Object.defineProperty(IJ,"__esModule",{value:!0});var FJ=ub(),R$=y(),KJ=g(),MJ=g(),zF={keyword:"patternProperties",type:"object",schemaType:"object",code(b){let{gen:w,schema:$,data:W,parentSchema:Q,it:q}=b,{opts:G}=q,X=(0,FJ.allSchemaProperties)($),Y=X.filter((K)=>(0,KJ.alwaysValidSchema)(q,$[K]));if(X.length===0||Y.length===X.length&&(!q.opts.unevaluated||q.props===!0))return;let J=G.strictSchema&&!G.allowMatchingProperties&&Q.properties,D=w.name("valid");if(q.props!==!0&&!(q.props instanceof R$.Name))q.props=(0,MJ.evaluatedPropsToName)(w,q.props);let{props:H}=q;O();function O(){for(let K of X){if(J)A(K);if(q.allErrors)B(K);else w.var(D,!0),B(K),w.if(D)}}function A(K){for(let _ in J)if(new RegExp(K).test(_))(0,KJ.checkStrictMode)(q,`property ${_} matches pattern ${K} (use allowMatchingProperties)`)}function B(K){w.forIn("key",W,(_)=>{w.if(R$._`${(0,FJ.usePattern)(b,K)}.test(${_})`,()=>{let I=Y.includes(K);if(!I)b.subschema({keyword:"patternProperties",schemaProp:K,dataProp:_,dataPropType:MJ.Type.Str},D);if(q.opts.unevaluated&&H!==!0)w.assign(R$._`${H}[${_}]`,!0);else if(!I&&!q.allErrors)w.if((0,R$.not)(D),()=>w.break())})})}}};IJ.default=zF});var ZJ=j((jJ)=>{Object.defineProperty(jJ,"__esModule",{value:!0});var AF=g(),LF={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(b){let{gen:w,schema:$,it:W}=b;if((0,AF.alwaysValidSchema)(W,$)){b.fail();return}let Q=w.name("valid");b.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},Q),b.failResult(Q,()=>b.reset(),()=>b.error())},error:{message:"must NOT be valid"}};jJ.default=LF});var NJ=j((VJ)=>{Object.defineProperty(VJ,"__esModule",{value:!0});var PF=ub(),BF={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:PF.validateUnion,error:{message:"must match a schema in anyOf"}};VJ.default=BF});var TJ=j((EJ)=>{Object.defineProperty(EJ,"__esModule",{value:!0});var v$=y(),KF=g(),MF={message:"must match exactly one schema in oneOf",params:({params:b})=>v$._`{passingSchemas: ${b.passing}}`},IF={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:MF,code(b){let{gen:w,schema:$,parentSchema:W,it:Q}=b;if(!Array.isArray($))throw Error("ajv implementation error");if(Q.opts.discriminator&&W.discriminator)return;let q=$,G=w.let("valid",!1),X=w.let("passing",null),Y=w.name("_valid");b.setParams({passing:X}),w.block(J),b.result(G,()=>b.reset(),()=>b.error(!0));function J(){q.forEach((D,H)=>{let O;if((0,KF.alwaysValidSchema)(Q,D))w.var(Y,!0);else O=b.subschema({keyword:"oneOf",schemaProp:H,compositeRule:!0},Y);if(H>0)w.if(v$._`${Y} && ${G}`).assign(G,!1).assign(X,v$._`[${X}, ${H}]`).else();w.if(Y,()=>{if(w.assign(G,!0),w.assign(X,H),O)b.mergeEvaluated(O,v$.Name)})})}}};EJ.default=IF});var RJ=j((SJ)=>{Object.defineProperty(SJ,"__esModule",{value:!0});var jF=g(),ZF={keyword:"allOf",schemaType:"array",code(b){let{gen:w,schema:$,it:W}=b;if(!Array.isArray($))throw Error("ajv implementation error");let Q=w.name("valid");$.forEach((q,G)=>{if((0,jF.alwaysValidSchema)(W,q))return;let X=b.subschema({keyword:"allOf",schemaProp:G},Q);b.ok(Q),b.mergeEvaluated(X)})}};SJ.default=ZF});var uJ=j((CJ)=>{Object.defineProperty(CJ,"__esModule",{value:!0});var k$=y(),kJ=g(),NF={message:({params:b})=>k$.str`must match "${b.ifClause}" schema`,params:({params:b})=>k$._`{failingKeyword: ${b.ifClause}}`},EF={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:NF,code(b){let{gen:w,parentSchema:$,it:W}=b;if($.then===void 0&&$.else===void 0)(0,kJ.checkStrictMode)(W,'"if" without "then" and "else" is ignored');let Q=vJ(W,"then"),q=vJ(W,"else");if(!Q&&!q)return;let G=w.let("valid",!0),X=w.name("_valid");if(Y(),b.reset(),Q&&q){let D=w.let("ifClause");b.setParams({ifClause:D}),w.if(X,J("then",D),J("else",D))}else if(Q)w.if(X,J("then"));else w.if((0,k$.not)(X),J("else"));b.pass(G,()=>b.error(!0));function Y(){let D=b.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},X);b.mergeEvaluated(D)}function J(D,H){return()=>{let O=b.subschema({keyword:D},X);if(w.assign(G,X),b.mergeValidEvaluated(O,G),H)w.assign(H,k$._`${D}`);else b.setParams({ifClause:D})}}}};function vJ(b,w){let $=b.schema[w];return $!==void 0&&!(0,kJ.alwaysValidSchema)(b,$)}CJ.default=EF});var yJ=j((xJ)=>{Object.defineProperty(xJ,"__esModule",{value:!0});var SF=g(),RF={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:b,parentSchema:w,it:$}){if(w.if===void 0)(0,SF.checkStrictMode)($,`"${b}" without "if" is ignored`)}};xJ.default=RF});var cJ=j((hJ)=>{Object.defineProperty(hJ,"__esModule",{value:!0});var kF=d6(),CF=aY(),uF=t6(),xF=$J(),yF=QJ(),hF=DJ(),cF=OJ(),fF=e6(),nF=BJ(),iF=_J(),mF=ZJ(),lF=NJ(),gF=TJ(),pF=RJ(),oF=uJ(),dF=yJ();function tF(b=!1){let w=[mF.default,lF.default,gF.default,pF.default,oF.default,dF.default,cF.default,fF.default,hF.default,nF.default,iF.default];if(b)w.push(CF.default,xF.default);else w.push(kF.default,uF.default);return w.push(yF.default),w}hJ.default=tF});var nJ=j((fJ)=>{Object.defineProperty(fJ,"__esModule",{value:!0});var Xb=y(),eF={message:({schemaCode:b})=>Xb.str`must match format "${b}"`,params:({schemaCode:b})=>Xb._`{format: ${b}}`},sF={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:eF,code(b,w){let{gen:$,data:W,$data:Q,schema:q,schemaCode:G,it:X}=b,{opts:Y,errSchemaPath:J,schemaEnv:D,self:H}=X;if(!Y.validateFormats)return;if(Q)O();else A();function O(){let B=$.scopeValue("formats",{ref:H.formats,code:Y.code.formats}),K=$.const("fDef",Xb._`${B}[${G}]`),_=$.let("fType"),I=$.let("format");$.if(Xb._`typeof ${K} == "object" && !(${K} instanceof RegExp)`,()=>$.assign(_,Xb._`${K}.type || "string"`).assign(I,Xb._`${K}.validate`),()=>$.assign(_,Xb._`"string"`).assign(I,K)),b.fail$data((0,Xb.or)(R(),T()));function R(){if(Y.strictSchema===!1)return Xb.nil;return Xb._`${G} && !${I}`}function T(){let h=D.$async?Xb._`(${K}.async ? await ${I}(${W}) : ${I}(${W}))`:Xb._`${I}(${W})`,v=Xb._`(typeof ${I} == "function" ? ${h} : ${I}.test(${W}))`;return Xb._`${I} && ${I} !== true && ${_} === ${w} && !${v}`}}function A(){let B=H.formats[q];if(!B){R();return}if(B===!0)return;let[K,_,I]=T(B);if(K===w)b.pass(h());function R(){if(Y.strictSchema===!1){H.logger.warn(v());return}throw Error(v());function v(){return`unknown format "${q}" ignored in schema at path "${J}"`}}function T(v){let ob=v instanceof RegExp?(0,Xb.regexpCode)(v):Y.code.formats?Xb._`${Y.code.formats}${(0,Xb.getProperty)(q)}`:void 0,bw=$.scopeValue("formats",{key:q,ref:v,code:ob});if(typeof v=="object"&&!(v instanceof RegExp))return[v.type||"string",v.validate,Xb._`${bw}.validate`];return["string",v,bw]}function h(){if(typeof B=="object"&&!(B instanceof RegExp)&&B.async){if(!D.$async)throw Error("async format in sync schema");return Xb._`await ${I}(${W})`}return typeof _=="function"?Xb._`${I}(${W})`:Xb._`${I}.test(${W})`}}}};fJ.default=sF});var mJ=j((iJ)=>{Object.defineProperty(iJ,"__esModule",{value:!0});var bK=nJ(),wK=[bK.default];iJ.default=wK});var pJ=j((lJ)=>{Object.defineProperty(lJ,"__esModule",{value:!0});lJ.contentVocabulary=lJ.metadataVocabulary=void 0;lJ.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];lJ.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var tJ=j((dJ)=>{Object.defineProperty(dJ,"__esModule",{value:!0});var QK=PY(),qK=lY(),GK=cJ(),XK=mJ(),oJ=pJ(),YK=[QK.default,qK.default,(0,GK.default)(),XK.default,oJ.metadataVocabulary,oJ.contentVocabulary];dJ.default=YK});var aJ=j((eJ)=>{Object.defineProperty(eJ,"__esModule",{value:!0});eJ.DiscrError=void 0;var rJ;(function(b){b.Tag="tag",b.Mapping="mapping"})(rJ||(eJ.DiscrError=rJ={}))});var $D=j((wD)=>{Object.defineProperty(wD,"__esModule",{value:!0});var $1=y(),a6=aJ(),bD=A$(),DK=d1(),HK=g(),zK={message:({params:{discrError:b,tagName:w}})=>b===a6.DiscrError.Tag?`tag "${w}" must be string`:`value of tag "${w}" must be in oneOf`,params:({params:{discrError:b,tag:w,tagName:$}})=>$1._`{error: ${b}, tag: ${$}, tagValue: ${w}}`},OK={keyword:"discriminator",type:"object",schemaType:"object",error:zK,code(b){let{gen:w,data:$,schema:W,parentSchema:Q,it:q}=b,{oneOf:G}=Q;if(!q.opts.discriminator)throw Error("discriminator: requires discriminator option");let X=W.propertyName;if(typeof X!="string")throw Error("discriminator: requires propertyName");if(W.mapping)throw Error("discriminator: mapping is not supported");if(!G)throw Error("discriminator: requires oneOf keyword");let Y=w.let("valid",!1),J=w.const("tag",$1._`${$}${(0,$1.getProperty)(X)}`);w.if($1._`typeof ${J} == "string"`,()=>D(),()=>b.error(!1,{discrError:a6.DiscrError.Tag,tag:J,tagName:X})),b.ok(Y);function D(){let A=O();w.if(!1);for(let B in A)w.elseIf($1._`${J} === ${B}`),w.assign(Y,H(A[B]));w.else(),b.error(!1,{discrError:a6.DiscrError.Mapping,tag:J,tagName:X}),w.endIf()}function H(A){let B=w.name("valid"),K=b.subschema({keyword:"oneOf",schemaProp:A},B);return b.mergeEvaluated(K,$1.Name),B}function O(){var A;let B={},K=I(Q),_=!0;for(let h=0;h<G.length;h++){let v=G[h];if((v===null||v===void 0?void 0:v.$ref)&&!(0,HK.schemaHasRulesButRef)(v,q.self.RULES)){let bw=v.$ref;if(v=bD.resolveRef.call(q.self,q.schemaEnv.root,q.baseId,bw),v instanceof bD.SchemaEnv)v=v.schema;if(v===void 0)throw new DK.default(q.opts.uriResolver,q.baseId,bw)}let ob=(A=v===null||v===void 0?void 0:v.properties)===null||A===void 0?void 0:A[X];if(typeof ob!="object")throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${X}"`);_=_&&(K||I(v)),R(ob,h)}if(!_)throw Error(`discriminator: "${X}" must be required`);return B;function I({required:h}){return Array.isArray(h)&&h.includes(X)}function R(h,v){if(h.const)T(h.const,v);else if(h.enum)for(let ob of h.enum)T(ob,v);else throw Error(`discriminator: "properties/${X}" must have "const" or "enum"`)}function T(h,v){if(typeof h!="string"||h in B)throw Error(`discriminator: "${X}" values must be unique strings`);B[h]=v}}}};wD.default=OK});var WD=j((BT,LK)=>{LK.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 wW=j((Vb,bW)=>{Object.defineProperty(Vb,"__esModule",{value:!0});Vb.MissingRefError=Vb.ValidationError=Vb.CodeGen=Vb.Name=Vb.nil=Vb.stringify=Vb.str=Vb._=Vb.KeywordCxt=Vb.Ajv=void 0;var UK=XY(),PK=tJ(),BK=$D(),QD=WD(),FK=["/properties"],C$="http://json-schema.org/draft-07/schema";class G0 extends UK.default{_addVocabularies(){if(super._addVocabularies(),PK.default.forEach((b)=>this.addVocabulary(b)),this.opts.discriminator)this.addKeyword(BK.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let b=this.opts.$data?this.$dataMetaSchema(QD,FK):QD;this.addMetaSchema(b,C$,!1),this.refs["http://json-schema.org/schema"]=C$}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(C$)?C$:void 0)}}Vb.Ajv=G0;bW.exports=Vb=G0;bW.exports.Ajv=G0;Object.defineProperty(Vb,"__esModule",{value:!0});Vb.default=G0;var KK=o1();Object.defineProperty(Vb,"KeywordCxt",{enumerable:!0,get:function(){return KK.KeywordCxt}});var W1=y();Object.defineProperty(Vb,"_",{enumerable:!0,get:function(){return W1._}});Object.defineProperty(Vb,"str",{enumerable:!0,get:function(){return W1.str}});Object.defineProperty(Vb,"stringify",{enumerable:!0,get:function(){return W1.stringify}});Object.defineProperty(Vb,"nil",{enumerable:!0,get:function(){return W1.nil}});Object.defineProperty(Vb,"Name",{enumerable:!0,get:function(){return W1.Name}});Object.defineProperty(Vb,"CodeGen",{enumerable:!0,get:function(){return W1.CodeGen}});var MK=z$();Object.defineProperty(Vb,"ValidationError",{enumerable:!0,get:function(){return MK.default}});var IK=d1();Object.defineProperty(Vb,"MissingRefError",{enumerable:!0,get:function(){return IK.default}})});var AD=j((zD)=>{Object.defineProperty(zD,"__esModule",{value:!0});zD.formatNames=zD.fastFormats=zD.fullFormats=void 0;function eb(b,w){return{validate:b,compare:w}}zD.fullFormats={date:eb(YD,qW),time:eb(WW(!0),GW),"date-time":eb(qD(!0),DD),"iso-time":eb(WW(),JD),"iso-date-time":eb(qD(),HD),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:SK,"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:yK,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:RK,int32:{type:"number",validate:CK},int64:{type:"number",validate:uK},float:{type:"number",validate:XD},double:{type:"number",validate:XD},password:!0,binary:!0};zD.fastFormats={...zD.fullFormats,date:eb(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,qW),time:eb(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,GW),"date-time":eb(/^\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,DD),"iso-time":eb(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,JD),"iso-date-time":eb(/^\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,HD),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};zD.formatNames=Object.keys(zD.fullFormats);function ZK(b){return b%4===0&&(b%100!==0||b%400===0)}var VK=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,NK=[0,31,28,31,30,31,30,31,31,30,31,30,31];function YD(b){let w=VK.exec(b);if(!w)return!1;let $=+w[1],W=+w[2],Q=+w[3];return W>=1&&W<=12&&Q>=1&&Q<=(W===2&&ZK($)?29:NK[W])}function qW(b,w){if(!(b&&w))return;if(b>w)return 1;if(b<w)return-1;return 0}var $W=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function WW(b){return function($){let W=$W.exec($);if(!W)return!1;let Q=+W[1],q=+W[2],G=+W[3],X=W[4],Y=W[5]==="-"?-1:1,J=+(W[6]||0),D=+(W[7]||0);if(J>23||D>59||b&&!X)return!1;if(Q<=23&&q<=59&&G<60)return!0;let H=q-D*Y,O=Q-J*Y-(H<0?1:0);return(O===23||O===-1)&&(H===59||H===-1)&&G<61}}function GW(b,w){if(!(b&&w))return;let $=new Date("2020-01-01T"+b).valueOf(),W=new Date("2020-01-01T"+w).valueOf();if(!($&&W))return;return $-W}function JD(b,w){if(!(b&&w))return;let $=$W.exec(b),W=$W.exec(w);if(!($&&W))return;if(b=$[1]+$[2]+$[3],w=W[1]+W[2]+W[3],b>w)return 1;if(b<w)return-1;return 0}var QW=/t|\s/i;function qD(b){let w=WW(b);return function(W){let Q=W.split(QW);return Q.length===2&&YD(Q[0])&&w(Q[1])}}function DD(b,w){if(!(b&&w))return;let $=new Date(b).valueOf(),W=new Date(w).valueOf();if(!($&&W))return;return $-W}function HD(b,w){if(!(b&&w))return;let[$,W]=b.split(QW),[Q,q]=w.split(QW),G=qW($,Q);if(G===void 0)return;return G||GW(W,q)}var EK=/\/|:/,TK=/^(?:[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 SK(b){return EK.test(b)&&TK.test(b)}var GD=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function RK(b){return GD.lastIndex=0,GD.test(b)}var vK=-2147483648,kK=2147483647;function CK(b){return Number.isInteger(b)&&b<=kK&&b>=vK}function uK(b){return Number.isInteger(b)}function XD(){return!0}var xK=/[^\\]\\Z/;function yK(b){if(xK.test(b))return!1;try{return new RegExp(b),!0}catch(w){return!1}}});var UD=j((LD)=>{Object.defineProperty(LD,"__esModule",{value:!0});LD.formatLimitDefinition=void 0;var cK=wW(),lb=y(),Sw=lb.operators,u$={formatMaximum:{okStr:"<=",ok:Sw.LTE,fail:Sw.GT},formatMinimum:{okStr:">=",ok:Sw.GTE,fail:Sw.LT},formatExclusiveMaximum:{okStr:"<",ok:Sw.LT,fail:Sw.GTE},formatExclusiveMinimum:{okStr:">",ok:Sw.GT,fail:Sw.LTE}},fK={message:({keyword:b,schemaCode:w})=>lb.str`should be ${u$[b].okStr} ${w}`,params:({keyword:b,schemaCode:w})=>lb._`{comparison: ${u$[b].okStr}, limit: ${w}}`};LD.formatLimitDefinition={keyword:Object.keys(u$),type:"string",schemaType:"string",$data:!0,error:fK,code(b){let{gen:w,data:$,schemaCode:W,keyword:Q,it:q}=b,{opts:G,self:X}=q;if(!G.validateFormats)return;let Y=new cK.KeywordCxt(q,X.RULES.all.format.definition,"format");if(Y.$data)J();else D();function J(){let O=w.scopeValue("formats",{ref:X.formats,code:G.code.formats}),A=w.const("fmt",lb._`${O}[${Y.schemaCode}]`);b.fail$data((0,lb.or)(lb._`typeof ${A} != "object"`,lb._`${A} instanceof RegExp`,lb._`typeof ${A}.compare != "function"`,H(A)))}function D(){let O=Y.schema,A=X.formats[O];if(!A||A===!0)return;if(typeof A!="object"||A instanceof RegExp||typeof A.compare!="function")throw Error(`"${Q}": format "${O}" does not define "compare" function`);let B=w.scopeValue("formats",{key:O,ref:A,code:G.code.formats?lb._`${G.code.formats}${(0,lb.getProperty)(O)}`:void 0});b.fail$data(H(B))}function H(O){return lb._`${O}.compare(${$}, ${W}) ${u$[Q].fail} 0`}},dependencies:["format"]};var nK=(b)=>{return b.addKeyword(LD.formatLimitDefinition),b};LD.default=nK});var KD=j((X0,FD)=>{Object.defineProperty(X0,"__esModule",{value:!0});var Q1=AD(),mK=UD(),JW=y(),PD=new JW.Name("fullFormats"),lK=new JW.Name("fastFormats"),DW=(b,w={keywords:!0})=>{if(Array.isArray(w))return BD(b,w,Q1.fullFormats,PD),b;let[$,W]=w.mode==="fast"?[Q1.fastFormats,lK]:[Q1.fullFormats,PD],Q=w.formats||Q1.formatNames;if(BD(b,Q,$,W),w.keywords)(0,mK.default)(b);return b};DW.get=(b,w="full")=>{let W=(w==="fast"?Q1.fastFormats:Q1.fullFormats)[b];if(!W)throw Error(`Unknown format "${b}"`);return W};function BD(b,w,$,W){var Q,q;(Q=(q=b.opts.code).formats)!==null&&Q!==void 0||(q.formats=JW._`require("ajv-formats/dist/formats").${W}`);for(let G of w)b.addFormat(G,$[G])}FD.exports=X0=DW;Object.defineProperty(X0,"__esModule",{value:!0});X0.default=DW});import{AsyncLocalStorage as Bz}from"node:async_hooks";class db extends Error{statusCode;rawDetails;code;context;constructor(b,w,$,W,Q){super(b);this.statusCode=w;this.rawDetails=$;this.code=W;this.context=Q;this.name="McpApiError"}}function Lz(b){if(b instanceof db)return{message:b.message,statusCode:b.statusCode,code:b.code,rawDetails:b.rawDetails,context:b.context};if(b instanceof Error)return{message:b.message};return{message:String(b)}}function Uz(b){let w=b.match(/api key is missing required scopes?:\s*(.+)$/i);if(!w?.[1])return[];return w[1].match(/[a-z_]+:[a-z_]+/gi)??[]}function Pz(b){let w=Lz(b),$=w.message.trim()||"Unknown error",W=$.toLowerCase(),Q=w.rawDetails?.trim()||$;if(w.context?.title||w.context?.description||w.context?.howToFix||w.context?.docsUrl)return{title:w.context.title??(w.statusCode===409?"Request conflict":"API request failed"),description:w.context.description??$,howToFix:w.context.howToFix??"Review the details below, adjust the tool input, and retry.",docsUrl:w.context.docsUrl??"https://docs.sequenzy.com/concepts/mcp",details:Q};if(w.code==="MCP_AUTH_REQUIRED"||W.includes("sequenzy_api_key environment variable is required"))return{title:"Missing MCP API key",description:"The MCP server started without a Sequenzy API key, so it cannot authenticate any tool or resource request.",howToFix:"Add `SEQUENZY_API_KEY` to the MCP server environment, or run `npx @sequenzy/setup` to configure the integration automatically.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(w.statusCode===401||w.code==="UNAUTHORIZED")return{title:"Authentication failed",description:"The MCP server reached Sequenzy, but the current API key was rejected.",howToFix:"Replace `SEQUENZY_API_KEY` with a valid personal API key, then restart the MCP client so it reconnects with fresh credentials.",docsUrl:"https://docs.sequenzy.com/authentication",details:Q};let q=Uz($);if(q.length>0){let G=q.map((Y)=>`\`${Y}\``).join(", "),X=q.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 ${q.length===1?"scope":"scopes"}: ${G}.`,howToFix:`For a local API-key connection, call \`get_account\` to inspect \`apiKeyPermissions\` and open \`apiKeyPermissions.manageUrl\` (or \`companies[].settingsUrl\` → API Keys). If \`get_account\` also requires \`account:read\`, open ${"https://sequenzy.com/dashboard"} directly and use the MCP setup or Settings → API Keys. Create a replacement key with ${X} including ${G}, replace \`SEQUENZY_API_KEY\`, and restart the client. For hosted OAuth MCP, disconnect and reauthorize the Sequenzy connection with a preset or Custom permissions including ${G}. Existing key permissions cannot be edited in place.`,docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q}}if(w.statusCode===403||W.includes("access denied"))return{title:"Access denied",description:"The current API key is valid, but it does not have permission to access the requested company or action.",howToFix:"Use an API key that belongs to the right account, or select a company the key can access before retrying the tool call.",docsUrl:"https://docs.sequenzy.com/authentication",details:Q};if(W.includes("no company available")||W.includes("company not found"))return{title:"Company selection required",description:"The MCP server could not resolve a company for this request.",howToFix:"Call `get_account` to inspect available companies, then call `select_company`, or pass `companyId` explicitly in the next tool call.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(w.statusCode===404||W.includes("not found"))return{title:"Requested resource not found",description:"Sequenzy could not find the requested campaign, template, sequence, company, or subscriber.",howToFix:"List or fetch the resource collection first, then retry the tool with a confirmed ID or email value.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(w.statusCode===409||W.includes("already exists"))return{title:"Resource already exists",description:"Sequenzy rejected this MCP request because it would create a duplicate resource.",howToFix:"List the existing resources first, reuse the matching resource when appropriate, or retry with a unique name or domain.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(w.statusCode===429||W.includes("rate limit"))return{title:"Rate limited",description:"Sequenzy temporarily slowed this MCP request because too many requests were sent too quickly.",howToFix:"Wait briefly before retrying. If the client is looping, reduce retries or add backoff before the next tool call.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(w.code==="NETWORK_ERROR"||W.includes("fetch failed"))return{title:"Network or configuration error",description:"The MCP server could not reach the Sequenzy API from this environment.",howToFix:"Check connectivity and verify `SEQUENZY_API_URL` if you override it in the MCP environment.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(W.includes("unknown tool")||W.includes("unknown resource"))return{title:"Unsupported MCP request",description:"The client asked for a tool or resource name that this Sequenzy MCP server does not expose.",howToFix:"Refresh the client's tool list and call only the names returned by `list_tools` or `list_resources`.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(W.includes("is required")||W.includes("invalid"))return{title:"Invalid MCP input",description:"The tool call was missing a required field or included an invalid value.",howToFix:"Review the tool schema, supply the missing argument, and retry the request with corrected input.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(w.statusCode&&w.statusCode>=500)return{title:"Sequenzy server error",description:"The request reached Sequenzy, but the server could not complete it successfully.",howToFix:"Retry once. If it still fails, keep the details below and consult the docs before escalating.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};return{title:"Tool execution failed",description:"The MCP server could not complete the requested operation.",howToFix:"Review the details below, adjust the tool input or credentials, and retry.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q}}function Lw(b){let w=Pz(b);return[`Sequenzy MCP error: ${w.title}`,`Description: ${w.description}`,`How to fix: ${w.howToFix}`,`Docs: ${w.docsUrl}`,`Details: ${w.details}`].join(`
|
|
10
|
+
`)}var Fz="https://api.sequenzy.com",Kz=new Set(["/api/v1/media/upload-bytes","/v1/media/upload-bytes"]),O1=new Bz,oW=!1;function dW(){oW=!0}function A0(){return oW}var tW=null;function Uw(){let b=O1.getStore();if(b)return b.selectedCompanyId??null;return tW}function L0(b){let w=O1.getStore();if(w){w.selectedCompanyId=b;return}tW=b}function w4(b,w){return O1.run(b,w)}function rW(){return O1.getStore()?.apiUrl??process.env.SEQUENZY_API_URL??Fz}function eW(){return O1.getStore()?.apiKey??process.env.SEQUENZY_API_KEY}function sW(b,w){let $=eW();if(!$)throw new db("SEQUENZY_API_KEY environment variable is required",401,void 0,"MCP_AUTH_REQUIRED");let W={"Content-Type":b,Authorization:`Bearer ${$}`},Q=w??Uw();if(Q)W["x-company-id"]=Q;return W}function aW(){if(eW())return;console.error(Lw(new db("SEQUENZY_API_KEY environment variable is required",401,void 0,"MCP_AUTH_REQUIRED"))),process.exit(1)}function Nb(b,w){let $=b[w];return typeof $==="string"&&$.trim()!==""?$.trim():void 0}function Mz(b){if(b===void 0)return;if(typeof b==="string")return b.trim()||void 0;return JSON.stringify(b)}function bQ(b){if(!b.trim())return{message:"Request failed"};try{let w=JSON.parse(b);if(typeof w==="string")return{message:w};let $=typeof w.error==="object"&&w.error!==null?w.error:void 0,W=Nb(w,"code")??($?Nb($,"code"):void 0),Q=(typeof w.error==="string"?w.error:void 0)??($?Nb($,"message"):void 0)??Nb(w,"message")??Nb(w,"error")??b,q=Nb(w,"howToFix")??Nb(w,"resolution"),G={...Nb(w,"title")?{title:Nb(w,"title")}:{},...Nb(w,"description")?{description:Nb(w,"description")}:{},...q?{howToFix:q}:{},...Nb(w,"docsUrl")?{docsUrl:Nb(w,"docsUrl")}:{}},X=Mz(w.details);if(Object.keys(G).length>0||X)return{message:Q,...W?{code:W}:{},...X?{details:X}:{},...Object.keys(G).length>0?{context:G}:{}};if(typeof w.error==="string")return{message:w.error,...W?{code:W}:{}};if($)return{message:Q,...W?{code:W}:{}};return{message:Q,...W?{code:W}:{}}}catch{return{message:b}}}async function z(b,w,$,W){let Q=sW("application/json",W),q;try{q=await fetch(`${rW()}${w}`,{method:b,headers:Q,body:$?JSON.stringify($):void 0})}catch(G){throw new db(G instanceof Error?G.message:"Failed to reach Sequenzy API",0,void 0,"NETWORK_ERROR")}if(!q.ok){let G=await q.text(),X=bQ(G);throw new db(X.message,q.status,X.details??G,X.code,X.context)}return q.json()}async function wQ(b,w,$,W){let Q=new URL(rW()).origin,q=new URL(b,`${Q}/`);if(q.origin!==Q){if(!Kz.has(q.pathname))throw new db("The image upload URL did not point to the configured Sequenzy API.",500,void 0,"INVALID_UPLOAD_URL");q=new URL(`${q.pathname}${q.search}`,`${Q}/`)}let G;try{G=await fetch(q,{method:"PUT",headers:sW($,W),body:w})}catch(X){throw new db(X instanceof Error?X.message:"Failed to upload image bytes",0,void 0,"NETWORK_ERROR")}if(!G.ok){let X=await G.text(),Y=bQ(X);throw new db(Y.message,G.status,Y.details??X,Y.code,Y.context)}}var qI=Object.freeze({status:"aborted"});function P(b,w,$){function W(X,Y){var J;Object.defineProperty(X,"_zod",{value:X._zod??{},enumerable:!1}),(J=X._zod).traits??(J.traits=new Set),X._zod.traits.add(b),w(X,Y);for(let D in G.prototype)if(!(D in X))Object.defineProperty(X,D,{value:G.prototype[D].bind(X)});X._zod.constr=G,X._zod.def=Y}let Q=$?.Parent??Object;class q extends Q{}Object.defineProperty(q,"name",{value:b});function G(X){var Y;let J=$?.Parent?new q:this;W(J,X),(Y=J._zod).deferred??(Y.deferred=[]);for(let D of J._zod.deferred)D();return J}return Object.defineProperty(G,"init",{value:W}),Object.defineProperty(G,Symbol.hasInstance,{value:(X)=>{if($?.Parent&&X instanceof $.Parent)return!0;return X?._zod?.traits?.has(b)}}),Object.defineProperty(G,"name",{value:b}),G}var GI=Symbol("zod_brand");class ww extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class A1 extends Error{constructor(b){super(`Encountered unidirectional transform during encode: ${b}`);this.name="ZodEncodeError"}}var U0={};function vb(b){if(b)Object.assign(U0,b);return U0}var l={};pW(l,{unwrapMessage:()=>L1,uint8ArrayToHex:()=>pz,uint8ArrayToBase64url:()=>lz,uint8ArrayToBase64:()=>YQ,stringifyPrimitive:()=>K0,shallowClone:()=>WQ,safeExtend:()=>hz,required:()=>nz,randomString:()=>Rz,propertyKeyTypes:()=>G4,promiseAllObject:()=>Sz,primitiveTypes:()=>QQ,prefixIssues:()=>Ww,pick:()=>uz,partial:()=>fz,optionalKeys:()=>X4,omit:()=>xz,objectClone:()=>Nz,numKeys:()=>vz,nullish:()=>U1,normalizeParams:()=>S,mergeDefs:()=>Bw,merge:()=>cz,jsonStringifyReplacer:()=>fw,joinValues:()=>P0,issue:()=>iw,isPlainObject:()=>Fw,isObject:()=>vw,hexToUint8Array:()=>gz,getSizableOrigin:()=>GQ,getParsedType:()=>kz,getLengthableOrigin:()=>B1,getEnumValues:()=>W4,getElementAtPath:()=>Tz,floatSafeRemainder:()=>Q4,finalizeIssue:()=>hb,extend:()=>yz,escapeRegex:()=>$w,esc:()=>B0,defineLazy:()=>d,createTransparentProxy:()=>Cz,cloneDef:()=>Ez,clone:()=>yb,cleanRegex:()=>P1,cleanEnum:()=>iz,captureStackTrace:()=>F0,cached:()=>nw,base64urlToUint8Array:()=>mz,base64ToUint8Array:()=>XQ,assignProp:()=>Pw,assertNotEqual:()=>_z,assertNever:()=>Zz,assertIs:()=>jz,assertEqual:()=>Iz,assert:()=>Vz,allowsEval:()=>q4,aborted:()=>Kw,NUMBER_FORMAT_RANGES:()=>Y4,Class:()=>JQ,BIGINT_FORMAT_RANGES:()=>qQ});function Iz(b){return b}function _z(b){return b}function jz(b){}function Zz(b){throw Error()}function Vz(b){}function W4(b){let w=Object.values(b).filter((W)=>typeof W==="number");return Object.entries(b).filter(([W,Q])=>w.indexOf(+W)===-1).map(([W,Q])=>Q)}function P0(b,w="|"){return b.map(($)=>K0($)).join(w)}function fw(b,w){if(typeof w==="bigint")return w.toString();return w}function nw(b){return{get value(){{let $=b();return Object.defineProperty(this,"value",{value:$}),$}throw Error("cached value already set")}}}function U1(b){return b===null||b===void 0}function P1(b){let w=b.startsWith("^")?1:0,$=b.endsWith("$")?b.length-1:b.length;return b.slice(w,$)}function Q4(b,w){let $=(b.toString().split(".")[1]||"").length,W=w.toString(),Q=(W.split(".")[1]||"").length;if(Q===0&&/\d?e-\d?/.test(W)){let Y=W.match(/\d?e-(\d?)/);if(Y?.[1])Q=Number.parseInt(Y[1])}let q=$>Q?$:Q,G=Number.parseInt(b.toFixed(q).replace(".","")),X=Number.parseInt(w.toFixed(q).replace(".",""));return G%X/10**q}var $Q=Symbol("evaluating");function d(b,w,$){let W=void 0;Object.defineProperty(b,w,{get(){if(W===$Q)return;if(W===void 0)W=$Q,W=$();return W},set(Q){Object.defineProperty(b,w,{value:Q})},configurable:!0})}function Nz(b){return Object.create(Object.getPrototypeOf(b),Object.getOwnPropertyDescriptors(b))}function Pw(b,w,$){Object.defineProperty(b,w,{value:$,writable:!0,enumerable:!0,configurable:!0})}function Bw(...b){let w={};for(let $ of b){let W=Object.getOwnPropertyDescriptors($);Object.assign(w,W)}return Object.defineProperties({},w)}function Ez(b){return Bw(b._zod.def)}function Tz(b,w){if(!w)return b;return w.reduce(($,W)=>$?.[W],b)}function Sz(b){let w=Object.keys(b),$=w.map((W)=>b[W]);return Promise.all($).then((W)=>{let Q={};for(let q=0;q<w.length;q++)Q[w[q]]=W[q];return Q})}function Rz(b=10){let $="";for(let W=0;W<b;W++)$+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return $}function B0(b){return JSON.stringify(b)}var F0="captureStackTrace"in Error?Error.captureStackTrace:(...b)=>{};function vw(b){return typeof b==="object"&&b!==null&&!Array.isArray(b)}var q4=nw(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(b){return!1}});function Fw(b){if(vw(b)===!1)return!1;let w=b.constructor;if(w===void 0)return!0;let $=w.prototype;if(vw($)===!1)return!1;if(Object.prototype.hasOwnProperty.call($,"isPrototypeOf")===!1)return!1;return!0}function WQ(b){if(Fw(b))return{...b};if(Array.isArray(b))return[...b];return b}function vz(b){let w=0;for(let $ in b)if(Object.prototype.hasOwnProperty.call(b,$))w++;return w}var kz=(b)=>{let w=typeof b;switch(w){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(b)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(b))return"array";if(b===null)return"null";if(b.then&&typeof b.then==="function"&&b.catch&&typeof b.catch==="function")return"promise";if(typeof Map<"u"&&b instanceof Map)return"map";if(typeof Set<"u"&&b instanceof Set)return"set";if(typeof Date<"u"&&b instanceof Date)return"date";if(typeof File<"u"&&b instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${w}`)}},G4=new Set(["string","number","symbol"]),QQ=new Set(["string","number","bigint","boolean","symbol","undefined"]);function $w(b){return b.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function yb(b,w,$){let W=new b._zod.constr(w??b._zod.def);if(!w||$?.parent)W._zod.parent=b;return W}function S(b){let w=b;if(!w)return{};if(typeof w==="string")return{error:()=>w};if(w?.message!==void 0){if(w?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");w.error=w.message}if(delete w.message,typeof w.error==="string")return{...w,error:()=>w.error};return w}function Cz(b){let w;return new Proxy({},{get($,W,Q){return w??(w=b()),Reflect.get(w,W,Q)},set($,W,Q,q){return w??(w=b()),Reflect.set(w,W,Q,q)},has($,W){return w??(w=b()),Reflect.has(w,W)},deleteProperty($,W){return w??(w=b()),Reflect.deleteProperty(w,W)},ownKeys($){return w??(w=b()),Reflect.ownKeys(w)},getOwnPropertyDescriptor($,W){return w??(w=b()),Reflect.getOwnPropertyDescriptor(w,W)},defineProperty($,W,Q){return w??(w=b()),Reflect.defineProperty(w,W,Q)}})}function K0(b){if(typeof b==="bigint")return b.toString()+"n";if(typeof b==="string")return`"${b}"`;return`${b}`}function X4(b){return Object.keys(b).filter((w)=>{return b[w]._zod.optin==="optional"&&b[w]._zod.optout==="optional"})}var Y4={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]},qQ={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function uz(b,w){let $=b._zod.def,W=Bw(b._zod.def,{get shape(){let Q={};for(let q in w){if(!(q in $.shape))throw Error(`Unrecognized key: "${q}"`);if(!w[q])continue;Q[q]=$.shape[q]}return Pw(this,"shape",Q),Q},checks:[]});return yb(b,W)}function xz(b,w){let $=b._zod.def,W=Bw(b._zod.def,{get shape(){let Q={...b._zod.def.shape};for(let q in w){if(!(q in $.shape))throw Error(`Unrecognized key: "${q}"`);if(!w[q])continue;delete Q[q]}return Pw(this,"shape",Q),Q},checks:[]});return yb(b,W)}function yz(b,w){if(!Fw(w))throw Error("Invalid input to extend: expected a plain object");let $=b._zod.def.checks;if($&&$.length>0)throw Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");let Q=Bw(b._zod.def,{get shape(){let q={...b._zod.def.shape,...w};return Pw(this,"shape",q),q},checks:[]});return yb(b,Q)}function hz(b,w){if(!Fw(w))throw Error("Invalid input to safeExtend: expected a plain object");let $={...b._zod.def,get shape(){let W={...b._zod.def.shape,...w};return Pw(this,"shape",W),W},checks:b._zod.def.checks};return yb(b,$)}function cz(b,w){let $=Bw(b._zod.def,{get shape(){let W={...b._zod.def.shape,...w._zod.def.shape};return Pw(this,"shape",W),W},get catchall(){return w._zod.def.catchall},checks:[]});return yb(b,$)}function fz(b,w,$){let W=Bw(w._zod.def,{get shape(){let Q=w._zod.def.shape,q={...Q};if($)for(let G in $){if(!(G in Q))throw Error(`Unrecognized key: "${G}"`);if(!$[G])continue;q[G]=b?new b({type:"optional",innerType:Q[G]}):Q[G]}else for(let G in Q)q[G]=b?new b({type:"optional",innerType:Q[G]}):Q[G];return Pw(this,"shape",q),q},checks:[]});return yb(w,W)}function nz(b,w,$){let W=Bw(w._zod.def,{get shape(){let Q=w._zod.def.shape,q={...Q};if($)for(let G in $){if(!(G in q))throw Error(`Unrecognized key: "${G}"`);if(!$[G])continue;q[G]=new b({type:"nonoptional",innerType:Q[G]})}else for(let G in Q)q[G]=new b({type:"nonoptional",innerType:Q[G]});return Pw(this,"shape",q),q},checks:[]});return yb(w,W)}function Kw(b,w=0){if(b.aborted===!0)return!0;for(let $=w;$<b.issues.length;$++)if(b.issues[$]?.continue!==!0)return!0;return!1}function Ww(b,w){return w.map(($)=>{var W;return(W=$).path??(W.path=[]),$.path.unshift(b),$})}function L1(b){return typeof b==="string"?b:b?.message}function hb(b,w,$){let W={...b,path:b.path??[]};if(!b.message){let Q=L1(b.inst?._zod.def?.error?.(b))??L1(w?.error?.(b))??L1($.customError?.(b))??L1($.localeError?.(b))??"Invalid input";W.message=Q}if(delete W.inst,delete W.continue,!w?.reportInput)delete W.input;return W}function GQ(b){if(b instanceof Set)return"set";if(b instanceof Map)return"map";if(b instanceof File)return"file";return"unknown"}function B1(b){if(Array.isArray(b))return"array";if(typeof b==="string")return"string";return"unknown"}function iw(...b){let[w,$,W]=b;if(typeof w==="string")return{message:w,code:"custom",input:$,inst:W};return{...w}}function iz(b){return Object.entries(b).filter(([w,$])=>{return Number.isNaN(Number.parseInt(w,10))}).map((w)=>w[1])}function XQ(b){let w=atob(b),$=new Uint8Array(w.length);for(let W=0;W<w.length;W++)$[W]=w.charCodeAt(W);return $}function YQ(b){let w="";for(let $=0;$<b.length;$++)w+=String.fromCharCode(b[$]);return btoa(w)}function mz(b){let w=b.replace(/-/g,"+").replace(/_/g,"/"),$="=".repeat((4-w.length%4)%4);return XQ(w+$)}function lz(b){return YQ(b).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function gz(b){let w=b.replace(/^0x/,"");if(w.length%2!==0)throw Error("Invalid hex string length");let $=new Uint8Array(w.length/2);for(let W=0;W<w.length;W+=2)$[W/2]=Number.parseInt(w.slice(W,W+2),16);return $}function pz(b){return Array.from(b).map((w)=>w.toString(16).padStart(2,"0")).join("")}class JQ{constructor(...b){}}var DQ=(b,w)=>{b.name="$ZodError",Object.defineProperty(b,"_zod",{value:b._zod,enumerable:!1}),Object.defineProperty(b,"issues",{value:w,enumerable:!1}),b.message=JSON.stringify(w,fw,2),Object.defineProperty(b,"toString",{value:()=>b.message,enumerable:!1})},M0=P("$ZodError",DQ),J4=P("$ZodError",DQ,{Parent:Error});function HQ(b,w=($)=>$.message){let $={},W=[];for(let Q of b.issues)if(Q.path.length>0)$[Q.path[0]]=$[Q.path[0]]||[],$[Q.path[0]].push(w(Q));else W.push(w(Q));return{formErrors:W,fieldErrors:$}}function zQ(b,w=($)=>$.message){let $={_errors:[]},W=(Q)=>{for(let q of Q.issues)if(q.code==="invalid_union"&&q.errors.length)q.errors.map((G)=>W({issues:G}));else if(q.code==="invalid_key")W({issues:q.issues});else if(q.code==="invalid_element")W({issues:q.issues});else if(q.path.length===0)$._errors.push(w(q));else{let G=$,X=0;while(X<q.path.length){let Y=q.path[X];if(X!==q.path.length-1)G[Y]=G[Y]||{_errors:[]};else G[Y]=G[Y]||{_errors:[]},G[Y]._errors.push(w(q));G=G[Y],X++}}};return W(b),$}var I0=(b)=>(w,$,W,Q)=>{let q=W?Object.assign(W,{async:!1}):{async:!1},G=w._zod.run({value:$,issues:[]},q);if(G instanceof Promise)throw new ww;if(G.issues.length){let X=new(Q?.Err??b)(G.issues.map((Y)=>hb(Y,q,vb())));throw F0(X,Q?.callee),X}return G.value};var _0=(b)=>async(w,$,W,Q)=>{let q=W?Object.assign(W,{async:!0}):{async:!0},G=w._zod.run({value:$,issues:[]},q);if(G instanceof Promise)G=await G;if(G.issues.length){let X=new(Q?.Err??b)(G.issues.map((Y)=>hb(Y,q,vb())));throw F0(X,Q?.callee),X}return G.value};var F1=(b)=>(w,$,W)=>{let Q=W?{...W,async:!1}:{async:!1},q=w._zod.run({value:$,issues:[]},Q);if(q instanceof Promise)throw new ww;return q.issues.length?{success:!1,error:new(b??M0)(q.issues.map((G)=>hb(G,Q,vb())))}:{success:!0,data:q.value}},K1=F1(J4),M1=(b)=>async(w,$,W)=>{let Q=W?Object.assign(W,{async:!0}):{async:!0},q=w._zod.run({value:$,issues:[]},Q);if(q instanceof Promise)q=await q;return q.issues.length?{success:!1,error:new b(q.issues.map((G)=>hb(G,Q,vb())))}:{success:!0,data:q.value}},j0=M1(J4),OQ=(b)=>(w,$,W)=>{let Q=W?Object.assign(W,{direction:"backward"}):{direction:"backward"};return I0(b)(w,$,Q)};var AQ=(b)=>(w,$,W)=>{return I0(b)(w,$,W)};var LQ=(b)=>async(w,$,W)=>{let Q=W?Object.assign(W,{direction:"backward"}):{direction:"backward"};return _0(b)(w,$,Q)};var UQ=(b)=>async(w,$,W)=>{return _0(b)(w,$,W)};var PQ=(b)=>(w,$,W)=>{let Q=W?Object.assign(W,{direction:"backward"}):{direction:"backward"};return F1(b)(w,$,Q)};var BQ=(b)=>(w,$,W)=>{return F1(b)(w,$,W)};var FQ=(b)=>async(w,$,W)=>{let Q=W?Object.assign(W,{direction:"backward"}):{direction:"backward"};return M1(b)(w,$,Q)};var KQ=(b)=>async(w,$,W)=>{return M1(b)(w,$,W)};var MQ=/^[cC][^\s-]{8,}$/,IQ=/^[0-9a-z]+$/,_Q=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,jQ=/^[0-9a-vA-V]{20}$/,ZQ=/^[A-Za-z0-9]{27}$/,VQ=/^[a-zA-Z0-9_-]{21}$/,NQ=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var EQ=/^([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})$/,D4=(b)=>{if(!b)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${b}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)};var TQ=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function SQ(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}var RQ=/^(?:(?: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])$/,vQ=/^(([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}|:))$/,kQ=/^((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])$/,CQ=/^(([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])$/,uQ=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,H4=/^[A-Za-z0-9_-]*$/,xQ=/^(?=.{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 yQ=/^\+(?:[0-9]){6,14}[0-9]$/,hQ="(?:(?:\\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])))",cQ=new RegExp(`^${hQ}$`);function fQ(b){return typeof b.precision==="number"?b.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":b.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${b.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function nQ(b){return new RegExp(`^${fQ(b)}$`)}function iQ(b){let w=fQ({precision:b.precision}),$=["Z"];if(b.local)$.push("");if(b.offset)$.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let W=`${w}(?:${$.join("|")})`;return new RegExp(`^${hQ}T(?:${W})$`)}var mQ=(b)=>{let w=b?`[\\s\\S]{${b?.minimum??0},${b?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${w}$`)};var lQ=/^-?\d+$/,gQ=/^-?\d+(?:\.\d+)?/,pQ=/^(?:true|false)$/i,oQ=/^null$/i;var dQ=/^[^A-Z]*$/,tQ=/^[^a-z]*$/;var Hb=P("$ZodCheck",(b,w)=>{var $;b._zod??(b._zod={}),b._zod.def=w,($=b._zod).onattach??($.onattach=[])}),rQ={number:"number",bigint:"bigint",object:"date"},z4=P("$ZodCheckLessThan",(b,w)=>{Hb.init(b,w);let $=rQ[typeof w.value];b._zod.onattach.push((W)=>{let Q=W._zod.bag,q=(w.inclusive?Q.maximum:Q.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(w.value<q)if(w.inclusive)Q.maximum=w.value;else Q.exclusiveMaximum=w.value}),b._zod.check=(W)=>{if(w.inclusive?W.value<=w.value:W.value<w.value)return;W.issues.push({origin:$,code:"too_big",maximum:w.value,input:W.value,inclusive:w.inclusive,inst:b,continue:!w.abort})}}),O4=P("$ZodCheckGreaterThan",(b,w)=>{Hb.init(b,w);let $=rQ[typeof w.value];b._zod.onattach.push((W)=>{let Q=W._zod.bag,q=(w.inclusive?Q.minimum:Q.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(w.value>q)if(w.inclusive)Q.minimum=w.value;else Q.exclusiveMinimum=w.value}),b._zod.check=(W)=>{if(w.inclusive?W.value>=w.value:W.value>w.value)return;W.issues.push({origin:$,code:"too_small",minimum:w.value,input:W.value,inclusive:w.inclusive,inst:b,continue:!w.abort})}}),eQ=P("$ZodCheckMultipleOf",(b,w)=>{Hb.init(b,w),b._zod.onattach.push(($)=>{var W;(W=$._zod.bag).multipleOf??(W.multipleOf=w.value)}),b._zod.check=($)=>{if(typeof $.value!==typeof w.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof $.value==="bigint"?$.value%w.value===BigInt(0):Q4($.value,w.value)===0)return;$.issues.push({origin:typeof $.value,code:"not_multiple_of",divisor:w.value,input:$.value,inst:b,continue:!w.abort})}}),sQ=P("$ZodCheckNumberFormat",(b,w)=>{Hb.init(b,w),w.format=w.format||"float64";let $=w.format?.includes("int"),W=$?"int":"number",[Q,q]=Y4[w.format];b._zod.onattach.push((G)=>{let X=G._zod.bag;if(X.format=w.format,X.minimum=Q,X.maximum=q,$)X.pattern=lQ}),b._zod.check=(G)=>{let X=G.value;if($){if(!Number.isInteger(X)){G.issues.push({expected:W,format:w.format,code:"invalid_type",continue:!1,input:X,inst:b});return}if(!Number.isSafeInteger(X)){if(X>0)G.issues.push({input:X,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:b,origin:W,continue:!w.abort});else G.issues.push({input:X,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:b,origin:W,continue:!w.abort});return}}if(X<Q)G.issues.push({origin:"number",input:X,code:"too_small",minimum:Q,inclusive:!0,inst:b,continue:!w.abort});if(X>q)G.issues.push({origin:"number",input:X,code:"too_big",maximum:q,inst:b})}});var aQ=P("$ZodCheckMaxLength",(b,w)=>{var $;Hb.init(b,w),($=b._zod.def).when??($.when=(W)=>{let Q=W.value;return!U1(Q)&&Q.length!==void 0}),b._zod.onattach.push((W)=>{let Q=W._zod.bag.maximum??Number.POSITIVE_INFINITY;if(w.maximum<Q)W._zod.bag.maximum=w.maximum}),b._zod.check=(W)=>{let Q=W.value;if(Q.length<=w.maximum)return;let G=B1(Q);W.issues.push({origin:G,code:"too_big",maximum:w.maximum,inclusive:!0,input:Q,inst:b,continue:!w.abort})}}),b9=P("$ZodCheckMinLength",(b,w)=>{var $;Hb.init(b,w),($=b._zod.def).when??($.when=(W)=>{let Q=W.value;return!U1(Q)&&Q.length!==void 0}),b._zod.onattach.push((W)=>{let Q=W._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(w.minimum>Q)W._zod.bag.minimum=w.minimum}),b._zod.check=(W)=>{let Q=W.value;if(Q.length>=w.minimum)return;let G=B1(Q);W.issues.push({origin:G,code:"too_small",minimum:w.minimum,inclusive:!0,input:Q,inst:b,continue:!w.abort})}}),w9=P("$ZodCheckLengthEquals",(b,w)=>{var $;Hb.init(b,w),($=b._zod.def).when??($.when=(W)=>{let Q=W.value;return!U1(Q)&&Q.length!==void 0}),b._zod.onattach.push((W)=>{let Q=W._zod.bag;Q.minimum=w.length,Q.maximum=w.length,Q.length=w.length}),b._zod.check=(W)=>{let Q=W.value,q=Q.length;if(q===w.length)return;let G=B1(Q),X=q>w.length;W.issues.push({origin:G,...X?{code:"too_big",maximum:w.length}:{code:"too_small",minimum:w.length},inclusive:!0,exact:!0,input:W.value,inst:b,continue:!w.abort})}}),I1=P("$ZodCheckStringFormat",(b,w)=>{var $,W;if(Hb.init(b,w),b._zod.onattach.push((Q)=>{let q=Q._zod.bag;if(q.format=w.format,w.pattern)q.patterns??(q.patterns=new Set),q.patterns.add(w.pattern)}),w.pattern)($=b._zod).check??($.check=(Q)=>{if(w.pattern.lastIndex=0,w.pattern.test(Q.value))return;Q.issues.push({origin:"string",code:"invalid_format",format:w.format,input:Q.value,...w.pattern?{pattern:w.pattern.toString()}:{},inst:b,continue:!w.abort})});else(W=b._zod).check??(W.check=()=>{})}),$9=P("$ZodCheckRegex",(b,w)=>{I1.init(b,w),b._zod.check=($)=>{if(w.pattern.lastIndex=0,w.pattern.test($.value))return;$.issues.push({origin:"string",code:"invalid_format",format:"regex",input:$.value,pattern:w.pattern.toString(),inst:b,continue:!w.abort})}}),W9=P("$ZodCheckLowerCase",(b,w)=>{w.pattern??(w.pattern=dQ),I1.init(b,w)}),Q9=P("$ZodCheckUpperCase",(b,w)=>{w.pattern??(w.pattern=tQ),I1.init(b,w)}),q9=P("$ZodCheckIncludes",(b,w)=>{Hb.init(b,w);let $=$w(w.includes),W=new RegExp(typeof w.position==="number"?`^.{${w.position}}${$}`:$);w.pattern=W,b._zod.onattach.push((Q)=>{let q=Q._zod.bag;q.patterns??(q.patterns=new Set),q.patterns.add(W)}),b._zod.check=(Q)=>{if(Q.value.includes(w.includes,w.position))return;Q.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:w.includes,input:Q.value,inst:b,continue:!w.abort})}}),G9=P("$ZodCheckStartsWith",(b,w)=>{Hb.init(b,w);let $=new RegExp(`^${$w(w.prefix)}.*`);w.pattern??(w.pattern=$),b._zod.onattach.push((W)=>{let Q=W._zod.bag;Q.patterns??(Q.patterns=new Set),Q.patterns.add($)}),b._zod.check=(W)=>{if(W.value.startsWith(w.prefix))return;W.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:w.prefix,input:W.value,inst:b,continue:!w.abort})}}),X9=P("$ZodCheckEndsWith",(b,w)=>{Hb.init(b,w);let $=new RegExp(`.*${$w(w.suffix)}$`);w.pattern??(w.pattern=$),b._zod.onattach.push((W)=>{let Q=W._zod.bag;Q.patterns??(Q.patterns=new Set),Q.patterns.add($)}),b._zod.check=(W)=>{if(W.value.endsWith(w.suffix))return;W.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:w.suffix,input:W.value,inst:b,continue:!w.abort})}});var Y9=P("$ZodCheckOverwrite",(b,w)=>{Hb.init(b,w),b._zod.check=($)=>{$.value=w.tx($.value)}});class A4{constructor(b=[]){if(this.content=[],this.indent=0,this)this.args=b}indented(b){this.indent+=1,b(this),this.indent-=1}write(b){if(typeof b==="function"){b(this,{execution:"sync"}),b(this,{execution:"async"});return}let $=b.split(`
|
|
11
|
+
`).filter((q)=>q),W=Math.min(...$.map((q)=>q.length-q.trimStart().length)),Q=$.map((q)=>q.slice(W)).map((q)=>" ".repeat(this.indent*2)+q);for(let q of Q)this.content.push(q)}compile(){let b=Function,w=this?.args,W=[...(this?.content??[""]).map((Q)=>` ${Q}`)];return new b(...w,W.join(`
|
|
12
|
+
`))}}var D9={major:4,minor:1,patch:12};var e=P("$ZodType",(b,w)=>{var $;b??(b={}),b._zod.def=w,b._zod.bag=b._zod.bag||{},b._zod.version=D9;let W=[...b._zod.def.checks??[]];if(b._zod.traits.has("$ZodCheck"))W.unshift(b);for(let Q of W)for(let q of Q._zod.onattach)q(b);if(W.length===0)($=b._zod).deferred??($.deferred=[]),b._zod.deferred?.push(()=>{b._zod.run=b._zod.parse});else{let Q=(G,X,Y)=>{let J=Kw(G),D;for(let H of X){if(H._zod.def.when){if(!H._zod.def.when(G))continue}else if(J)continue;let O=G.issues.length,A=H._zod.check(G);if(A instanceof Promise&&Y?.async===!1)throw new ww;if(D||A instanceof Promise)D=(D??Promise.resolve()).then(async()=>{if(await A,G.issues.length===O)return;if(!J)J=Kw(G,O)});else{if(G.issues.length===O)continue;if(!J)J=Kw(G,O)}}if(D)return D.then(()=>{return G});return G},q=(G,X,Y)=>{if(Kw(G))return G.aborted=!0,G;let J=Q(X,W,Y);if(J instanceof Promise){if(Y.async===!1)throw new ww;return J.then((D)=>b._zod.parse(D,Y))}return b._zod.parse(J,Y)};b._zod.run=(G,X)=>{if(X.skipChecks)return b._zod.parse(G,X);if(X.direction==="backward"){let J=b._zod.parse({value:G.value,issues:[]},{...X,skipChecks:!0});if(J instanceof Promise)return J.then((D)=>{return q(D,G,X)});return q(J,G,X)}let Y=b._zod.parse(G,X);if(Y instanceof Promise){if(X.async===!1)throw new ww;return Y.then((J)=>Q(J,W,X))}return Q(Y,W,X)}}b["~standard"]={validate:(Q)=>{try{let q=K1(b,Q);return q.success?{value:q.data}:{issues:q.error?.issues}}catch(q){return j0(b,Q).then((G)=>G.success?{value:G.data}:{issues:G.error?.issues})}},vendor:"zod",version:1}}),E0=P("$ZodString",(b,w)=>{e.init(b,w),b._zod.pattern=[...b?._zod.bag?.patterns??[]].pop()??mQ(b._zod.bag),b._zod.parse=($,W)=>{if(w.coerce)try{$.value=String($.value)}catch(Q){}if(typeof $.value==="string")return $;return $.issues.push({expected:"string",code:"invalid_type",input:$.value,inst:b}),$}}),s=P("$ZodStringFormat",(b,w)=>{I1.init(b,w),E0.init(b,w)}),F9=P("$ZodGUID",(b,w)=>{w.pattern??(w.pattern=EQ),s.init(b,w)}),K9=P("$ZodUUID",(b,w)=>{if(w.version){let W={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[w.version];if(W===void 0)throw Error(`Invalid UUID version: "${w.version}"`);w.pattern??(w.pattern=D4(W))}else w.pattern??(w.pattern=D4());s.init(b,w)}),M9=P("$ZodEmail",(b,w)=>{w.pattern??(w.pattern=TQ),s.init(b,w)}),I9=P("$ZodURL",(b,w)=>{s.init(b,w),b._zod.check=($)=>{try{let W=$.value.trim(),Q=new URL(W);if(w.hostname){if(w.hostname.lastIndex=0,!w.hostname.test(Q.hostname))$.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:xQ.source,input:$.value,inst:b,continue:!w.abort})}if(w.protocol){if(w.protocol.lastIndex=0,!w.protocol.test(Q.protocol.endsWith(":")?Q.protocol.slice(0,-1):Q.protocol))$.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:w.protocol.source,input:$.value,inst:b,continue:!w.abort})}if(w.normalize)$.value=Q.href;else $.value=W;return}catch(W){$.issues.push({code:"invalid_format",format:"url",input:$.value,inst:b,continue:!w.abort})}}}),_9=P("$ZodEmoji",(b,w)=>{w.pattern??(w.pattern=SQ()),s.init(b,w)}),j9=P("$ZodNanoID",(b,w)=>{w.pattern??(w.pattern=VQ),s.init(b,w)}),Z9=P("$ZodCUID",(b,w)=>{w.pattern??(w.pattern=MQ),s.init(b,w)}),V9=P("$ZodCUID2",(b,w)=>{w.pattern??(w.pattern=IQ),s.init(b,w)}),N9=P("$ZodULID",(b,w)=>{w.pattern??(w.pattern=_Q),s.init(b,w)}),E9=P("$ZodXID",(b,w)=>{w.pattern??(w.pattern=jQ),s.init(b,w)}),T9=P("$ZodKSUID",(b,w)=>{w.pattern??(w.pattern=ZQ),s.init(b,w)}),S9=P("$ZodISODateTime",(b,w)=>{w.pattern??(w.pattern=iQ(w)),s.init(b,w)}),R9=P("$ZodISODate",(b,w)=>{w.pattern??(w.pattern=cQ),s.init(b,w)}),v9=P("$ZodISOTime",(b,w)=>{w.pattern??(w.pattern=nQ(w)),s.init(b,w)}),k9=P("$ZodISODuration",(b,w)=>{w.pattern??(w.pattern=NQ),s.init(b,w)}),C9=P("$ZodIPv4",(b,w)=>{w.pattern??(w.pattern=RQ),s.init(b,w),b._zod.onattach.push(($)=>{let W=$._zod.bag;W.format="ipv4"})}),u9=P("$ZodIPv6",(b,w)=>{w.pattern??(w.pattern=vQ),s.init(b,w),b._zod.onattach.push(($)=>{let W=$._zod.bag;W.format="ipv6"}),b._zod.check=($)=>{try{new URL(`http://[${$.value}]`)}catch{$.issues.push({code:"invalid_format",format:"ipv6",input:$.value,inst:b,continue:!w.abort})}}}),x9=P("$ZodCIDRv4",(b,w)=>{w.pattern??(w.pattern=kQ),s.init(b,w)}),y9=P("$ZodCIDRv6",(b,w)=>{w.pattern??(w.pattern=CQ),s.init(b,w),b._zod.check=($)=>{let W=$.value.split("/");try{if(W.length!==2)throw Error();let[Q,q]=W;if(!q)throw Error();let G=Number(q);if(`${G}`!==q)throw Error();if(G<0||G>128)throw Error();new URL(`http://[${Q}]`)}catch{$.issues.push({code:"invalid_format",format:"cidrv6",input:$.value,inst:b,continue:!w.abort})}}});function h9(b){if(b==="")return!0;if(b.length%4!==0)return!1;try{return atob(b),!0}catch{return!1}}var c9=P("$ZodBase64",(b,w)=>{w.pattern??(w.pattern=uQ),s.init(b,w),b._zod.onattach.push(($)=>{$._zod.bag.contentEncoding="base64"}),b._zod.check=($)=>{if(h9($.value))return;$.issues.push({code:"invalid_format",format:"base64",input:$.value,inst:b,continue:!w.abort})}});function rz(b){if(!H4.test(b))return!1;let w=b.replace(/[-_]/g,(W)=>W==="-"?"+":"/"),$=w.padEnd(Math.ceil(w.length/4)*4,"=");return h9($)}var f9=P("$ZodBase64URL",(b,w)=>{w.pattern??(w.pattern=H4),s.init(b,w),b._zod.onattach.push(($)=>{$._zod.bag.contentEncoding="base64url"}),b._zod.check=($)=>{if(rz($.value))return;$.issues.push({code:"invalid_format",format:"base64url",input:$.value,inst:b,continue:!w.abort})}}),n9=P("$ZodE164",(b,w)=>{w.pattern??(w.pattern=yQ),s.init(b,w)});function ez(b,w=null){try{let $=b.split(".");if($.length!==3)return!1;let[W]=$;if(!W)return!1;let Q=JSON.parse(atob(W));if("typ"in Q&&Q?.typ!=="JWT")return!1;if(!Q.alg)return!1;if(w&&(!("alg"in Q)||Q.alg!==w))return!1;return!0}catch{return!1}}var i9=P("$ZodJWT",(b,w)=>{s.init(b,w),b._zod.check=($)=>{if(ez($.value,w.alg))return;$.issues.push({code:"invalid_format",format:"jwt",input:$.value,inst:b,continue:!w.abort})}});var U4=P("$ZodNumber",(b,w)=>{e.init(b,w),b._zod.pattern=b._zod.bag.pattern??gQ,b._zod.parse=($,W)=>{if(w.coerce)try{$.value=Number($.value)}catch(G){}let Q=$.value;if(typeof Q==="number"&&!Number.isNaN(Q)&&Number.isFinite(Q))return $;let q=typeof Q==="number"?Number.isNaN(Q)?"NaN":!Number.isFinite(Q)?"Infinity":void 0:void 0;return $.issues.push({expected:"number",code:"invalid_type",input:Q,inst:b,...q?{received:q}:{}}),$}}),m9=P("$ZodNumber",(b,w)=>{sQ.init(b,w),U4.init(b,w)}),l9=P("$ZodBoolean",(b,w)=>{e.init(b,w),b._zod.pattern=pQ,b._zod.parse=($,W)=>{if(w.coerce)try{$.value=Boolean($.value)}catch(q){}let Q=$.value;if(typeof Q==="boolean")return $;return $.issues.push({expected:"boolean",code:"invalid_type",input:Q,inst:b}),$}});var g9=P("$ZodNull",(b,w)=>{e.init(b,w),b._zod.pattern=oQ,b._zod.values=new Set([null]),b._zod.parse=($,W)=>{let Q=$.value;if(Q===null)return $;return $.issues.push({expected:"null",code:"invalid_type",input:Q,inst:b}),$}});var p9=P("$ZodUnknown",(b,w)=>{e.init(b,w),b._zod.parse=($)=>$}),o9=P("$ZodNever",(b,w)=>{e.init(b,w),b._zod.parse=($,W)=>{return $.issues.push({expected:"never",code:"invalid_type",input:$.value,inst:b}),$}});function H9(b,w,$){if(b.issues.length)w.issues.push(...Ww($,b.issues));w.value[$]=b.value}var d9=P("$ZodArray",(b,w)=>{e.init(b,w),b._zod.parse=($,W)=>{let Q=$.value;if(!Array.isArray(Q))return $.issues.push({expected:"array",code:"invalid_type",input:Q,inst:b}),$;$.value=Array(Q.length);let q=[];for(let G=0;G<Q.length;G++){let X=Q[G],Y=w.element._zod.run({value:X,issues:[]},W);if(Y instanceof Promise)q.push(Y.then((J)=>H9(J,$,G)));else H9(Y,$,G)}if(q.length)return Promise.all(q).then(()=>$);return $}});function N0(b,w,$,W){if(b.issues.length)w.issues.push(...Ww($,b.issues));if(b.value===void 0){if($ in W)w.value[$]=void 0}else w.value[$]=b.value}function t9(b){let w=Object.keys(b.shape);for(let W of w)if(!b.shape?.[W]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${W}": expected a Zod schema`);let $=X4(b.shape);return{...b,keys:w,keySet:new Set(w),numKeys:w.length,optionalKeys:new Set($)}}function r9(b,w,$,W,Q,q){let G=[],X=Q.keySet,Y=Q.catchall._zod,J=Y.def.type;for(let D of Object.keys(w)){if(X.has(D))continue;if(J==="never"){G.push(D);continue}let H=Y.run({value:w[D],issues:[]},W);if(H instanceof Promise)b.push(H.then((O)=>N0(O,$,D,w)));else N0(H,$,D,w)}if(G.length)$.issues.push({code:"unrecognized_keys",keys:G,input:w,inst:q});if(!b.length)return $;return Promise.all(b).then(()=>{return $})}var sz=P("$ZodObject",(b,w)=>{if(e.init(b,w),!Object.getOwnPropertyDescriptor(w,"shape")?.get){let X=w.shape;Object.defineProperty(w,"shape",{get:()=>{let Y={...X};return Object.defineProperty(w,"shape",{value:Y}),Y}})}let W=nw(()=>t9(w));d(b._zod,"propValues",()=>{let X=w.shape,Y={};for(let J in X){let D=X[J]._zod;if(D.values){Y[J]??(Y[J]=new Set);for(let H of D.values)Y[J].add(H)}}return Y});let Q=vw,q=w.catchall,G;b._zod.parse=(X,Y)=>{G??(G=W.value);let J=X.value;if(!Q(J))return X.issues.push({expected:"object",code:"invalid_type",input:J,inst:b}),X;X.value={};let D=[],H=G.shape;for(let O of G.keys){let B=H[O]._zod.run({value:J[O],issues:[]},Y);if(B instanceof Promise)D.push(B.then((K)=>N0(K,X,O,J)));else N0(B,X,O,J)}if(!q)return D.length?Promise.all(D).then(()=>X):X;return r9(D,J,X,Y,W.value,b)}}),e9=P("$ZodObjectJIT",(b,w)=>{sz.init(b,w);let $=b._zod.parse,W=nw(()=>t9(w)),Q=(O)=>{let A=new A4(["shape","payload","ctx"]),B=W.value,K=(T)=>{let h=B0(T);return`shape[${h}]._zod.run({ value: input[${h}], issues: [] }, ctx)`};A.write("const input = payload.value;");let _=Object.create(null),I=0;for(let T of B.keys)_[T]=`key_${I++}`;A.write("const newResult = {};");for(let T of B.keys){let h=_[T],v=B0(T);A.write(`const ${h} = ${K(T)};`),A.write(`
|
|
13
13
|
if (${h}.issues.length) {
|
|
14
14
|
payload.issues = payload.issues.concat(${h}.issues.map(iss => ({
|
|
15
15
|
...iss,
|
|
@@ -26,7 +26,7 @@ var qz=Object.create;var{getPrototypeOf:Xz,defineProperty:b4,getOwnPropertyNames
|
|
|
26
26
|
newResult[${v}] = ${h}.value;
|
|
27
27
|
}
|
|
28
28
|
|
|
29
|
-
`)}A.write("payload.value = newResult;"),A.write("return payload;");let R=A.compile();return(T,h)=>R(O,T,h)},G,q=vw,X=!L0.jitless,J=X&&G4.value,D=w.catchall,H;b._zod.parse=(O,A)=>{H??(H=W.value);let B=O.value;if(!q(B))return O.issues.push({expected:"object",code:"invalid_type",input:B,inst:b}),O;if(X&&J&&A?.async===!1&&A.jitless!==!0){if(!G)G=Q(w.shape);if(O=G(O,A),!D)return O;return rQ([],B,O,A,H,b)}return $(O,A)}});function zQ(b,w,$,W){for(let G of b)if(G.issues.length===0)return w.value=G.value,w;let Q=b.filter((G)=>!Kw(G));if(Q.length===1)return w.value=Q[0].value,Q[0];return w.issues.push({code:"invalid_union",input:w.value,inst:$,errors:b.map((G)=>G.issues.map((q)=>hb(q,W,vb())))}),w}var P4=P("$ZodUnion",(b,w)=>{e.init(b,w),d(b._zod,"optin",()=>w.options.some((Q)=>Q._zod.optin==="optional")?"optional":void 0),d(b._zod,"optout",()=>w.options.some((Q)=>Q._zod.optout==="optional")?"optional":void 0),d(b._zod,"values",()=>{if(w.options.every((Q)=>Q._zod.values))return new Set(w.options.flatMap((Q)=>Array.from(Q._zod.values)));return}),d(b._zod,"pattern",()=>{if(w.options.every((Q)=>Q._zod.pattern)){let Q=w.options.map((G)=>G._zod.pattern);return new RegExp(`^(${Q.map((G)=>P1(G.source)).join("|")})$`)}return});let $=w.options.length===1,W=w.options[0]._zod.run;b._zod.parse=(Q,G)=>{if($)return W(Q,G);let q=!1,X=[];for(let Y of w.options){let J=Y._zod.run({value:Q.value,issues:[]},G);if(J instanceof Promise)X.push(J),q=!0;else{if(J.issues.length===0)return J;X.push(J)}}if(!q)return zQ(X,Q,b,G);return Promise.all(X).then((Y)=>{return zQ(Y,Q,b,G)})}}),sQ=P("$ZodDiscriminatedUnion",(b,w)=>{P4.init(b,w);let $=b._zod.parse;d(b._zod,"propValues",()=>{let Q={};for(let G of w.options){let q=G._zod.propValues;if(!q||Object.keys(q).length===0)throw Error(`Invalid discriminated union option at index "${w.options.indexOf(G)}"`);for(let[X,Y]of Object.entries(q)){if(!Q[X])Q[X]=new Set;for(let J of Y)Q[X].add(J)}}return Q});let W=nw(()=>{let Q=w.options,G=new Map;for(let q of Q){let X=q._zod.propValues?.[w.discriminator];if(!X||X.size===0)throw Error(`Invalid discriminated union option at index "${w.options.indexOf(q)}"`);for(let Y of X){if(G.has(Y))throw Error(`Duplicate discriminator value "${String(Y)}"`);G.set(Y,q)}}return G});b._zod.parse=(Q,G)=>{let q=Q.value;if(!vw(q))return Q.issues.push({code:"invalid_type",expected:"object",input:q,inst:b}),Q;let X=W.value.get(q?.[w.discriminator]);if(X)return X._zod.run(Q,G);if(w.unionFallback)return $(Q,G);return Q.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:w.discriminator,input:q,path:[w.discriminator],inst:b}),Q}}),aQ=P("$ZodIntersection",(b,w)=>{e.init(b,w),b._zod.parse=($,W)=>{let Q=$.value,G=w.left._zod.run({value:Q,issues:[]},W),q=w.right._zod.run({value:Q,issues:[]},W);if(G instanceof Promise||q instanceof Promise)return Promise.all([G,q]).then(([Y,J])=>{return OQ($,Y,J)});return OQ($,G,q)}});function U4(b,w){if(b===w)return{valid:!0,data:b};if(b instanceof Date&&w instanceof Date&&+b===+w)return{valid:!0,data:b};if(Fw(b)&&Fw(w)){let $=Object.keys(w),W=Object.keys(b).filter((G)=>$.indexOf(G)!==-1),Q={...b,...w};for(let G of W){let q=U4(b[G],w[G]);if(!q.valid)return{valid:!1,mergeErrorPath:[G,...q.mergeErrorPath]};Q[G]=q.data}return{valid:!0,data:Q}}if(Array.isArray(b)&&Array.isArray(w)){if(b.length!==w.length)return{valid:!1,mergeErrorPath:[]};let $=[];for(let W=0;W<b.length;W++){let Q=b[W],G=w[W],q=U4(Q,G);if(!q.valid)return{valid:!1,mergeErrorPath:[W,...q.mergeErrorPath]};$.push(q.data)}return{valid:!0,data:$}}return{valid:!1,mergeErrorPath:[]}}function OQ(b,w,$){if(w.issues.length)b.issues.push(...w.issues);if($.issues.length)b.issues.push(...$.issues);if(Kw(b))return b;let W=U4(w.value,$.value);if(!W.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(W.mergeErrorPath)}`);return b.value=W.data,b}var bG=P("$ZodRecord",(b,w)=>{e.init(b,w),b._zod.parse=($,W)=>{let Q=$.value;if(!Fw(Q))return $.issues.push({expected:"record",code:"invalid_type",input:Q,inst:b}),$;let G=[];if(w.keyType._zod.values){let q=w.keyType._zod.values;$.value={};for(let Y of q)if(typeof Y==="string"||typeof Y==="number"||typeof Y==="symbol"){let J=w.valueType._zod.run({value:Q[Y],issues:[]},W);if(J instanceof Promise)G.push(J.then((D)=>{if(D.issues.length)$.issues.push(...Ww(Y,D.issues));$.value[Y]=D.value}));else{if(J.issues.length)$.issues.push(...Ww(Y,J.issues));$.value[Y]=J.value}}let X;for(let Y in Q)if(!q.has(Y))X=X??[],X.push(Y);if(X&&X.length>0)$.issues.push({code:"unrecognized_keys",input:Q,inst:b,keys:X})}else{$.value={};for(let q of Reflect.ownKeys(Q)){if(q==="__proto__")continue;let X=w.keyType._zod.run({value:q,issues:[]},W);if(X instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(X.issues.length){$.issues.push({code:"invalid_key",origin:"record",issues:X.issues.map((J)=>hb(J,W,vb())),input:q,path:[q],inst:b}),$.value[X.value]=X.value;continue}let Y=w.valueType._zod.run({value:Q[q],issues:[]},W);if(Y instanceof Promise)G.push(Y.then((J)=>{if(J.issues.length)$.issues.push(...Ww(q,J.issues));$.value[X.value]=J.value}));else{if(Y.issues.length)$.issues.push(...Ww(q,Y.issues));$.value[X.value]=Y.value}}}if(G.length)return Promise.all(G).then(()=>$);return $}});var wG=P("$ZodEnum",(b,w)=>{e.init(b,w);let $=W4(w.entries),W=new Set($);b._zod.values=W,b._zod.pattern=new RegExp(`^(${$.filter((Q)=>q4.has(typeof Q)).map((Q)=>typeof Q==="string"?$w(Q):Q.toString()).join("|")})$`),b._zod.parse=(Q,G)=>{let q=Q.value;if(W.has(q))return Q;return Q.issues.push({code:"invalid_value",values:$,input:q,inst:b}),Q}}),$G=P("$ZodLiteral",(b,w)=>{if(e.init(b,w),w.values.length===0)throw Error("Cannot create literal schema with no valid values");b._zod.values=new Set(w.values),b._zod.pattern=new RegExp(`^(${w.values.map(($)=>typeof $==="string"?$w($):$?$w($.toString()):String($)).join("|")})$`),b._zod.parse=($,W)=>{let Q=$.value;if(b._zod.values.has(Q))return $;return $.issues.push({code:"invalid_value",values:w.values,input:Q,inst:b}),$}});var WG=P("$ZodTransform",(b,w)=>{e.init(b,w),b._zod.parse=($,W)=>{if(W.direction==="backward")throw new A1(b.constructor.name);let Q=w.transform($.value,$);if(W.async)return(Q instanceof Promise?Q:Promise.resolve(Q)).then((q)=>{return $.value=q,$});if(Q instanceof Promise)throw new ww;return $.value=Q,$}});function AQ(b,w){if(b.issues.length&&w===void 0)return{issues:[],value:void 0};return b}var QG=P("$ZodOptional",(b,w)=>{e.init(b,w),b._zod.optin="optional",b._zod.optout="optional",d(b._zod,"values",()=>{return w.innerType._zod.values?new Set([...w.innerType._zod.values,void 0]):void 0}),d(b._zod,"pattern",()=>{let $=w.innerType._zod.pattern;return $?new RegExp(`^(${P1($.source)})?$`):void 0}),b._zod.parse=($,W)=>{if(w.innerType._zod.optin==="optional"){let Q=w.innerType._zod.run($,W);if(Q instanceof Promise)return Q.then((G)=>AQ(G,$.value));return AQ(Q,$.value)}if($.value===void 0)return $;return w.innerType._zod.run($,W)}}),GG=P("$ZodNullable",(b,w)=>{e.init(b,w),d(b._zod,"optin",()=>w.innerType._zod.optin),d(b._zod,"optout",()=>w.innerType._zod.optout),d(b._zod,"pattern",()=>{let $=w.innerType._zod.pattern;return $?new RegExp(`^(${P1($.source)}|null)$`):void 0}),d(b._zod,"values",()=>{return w.innerType._zod.values?new Set([...w.innerType._zod.values,null]):void 0}),b._zod.parse=($,W)=>{if($.value===null)return $;return w.innerType._zod.run($,W)}}),qG=P("$ZodDefault",(b,w)=>{e.init(b,w),b._zod.optin="optional",d(b._zod,"values",()=>w.innerType._zod.values),b._zod.parse=($,W)=>{if(W.direction==="backward")return w.innerType._zod.run($,W);if($.value===void 0)return $.value=w.defaultValue,$;let Q=w.innerType._zod.run($,W);if(Q instanceof Promise)return Q.then((G)=>UQ(G,w));return UQ(Q,w)}});function UQ(b,w){if(b.value===void 0)b.value=w.defaultValue;return b}var XG=P("$ZodPrefault",(b,w)=>{e.init(b,w),b._zod.optin="optional",d(b._zod,"values",()=>w.innerType._zod.values),b._zod.parse=($,W)=>{if(W.direction==="backward")return w.innerType._zod.run($,W);if($.value===void 0)$.value=w.defaultValue;return w.innerType._zod.run($,W)}}),YG=P("$ZodNonOptional",(b,w)=>{e.init(b,w),d(b._zod,"values",()=>{let $=w.innerType._zod.values;return $?new Set([...$].filter((W)=>W!==void 0)):void 0}),b._zod.parse=($,W)=>{let Q=w.innerType._zod.run($,W);if(Q instanceof Promise)return Q.then((G)=>LQ(G,b));return LQ(Q,b)}});function LQ(b,w){if(!b.issues.length&&b.value===void 0)b.issues.push({code:"invalid_type",expected:"nonoptional",input:b.value,inst:w});return b}var JG=P("$ZodCatch",(b,w)=>{e.init(b,w),d(b._zod,"optin",()=>w.innerType._zod.optin),d(b._zod,"optout",()=>w.innerType._zod.optout),d(b._zod,"values",()=>w.innerType._zod.values),b._zod.parse=($,W)=>{if(W.direction==="backward")return w.innerType._zod.run($,W);let Q=w.innerType._zod.run($,W);if(Q instanceof Promise)return Q.then((G)=>{if($.value=G.value,G.issues.length)$.value=w.catchValue({...$,error:{issues:G.issues.map((q)=>hb(q,W,vb()))},input:$.value}),$.issues=[];return $});if($.value=Q.value,Q.issues.length)$.value=w.catchValue({...$,error:{issues:Q.issues.map((G)=>hb(G,W,vb()))},input:$.value}),$.issues=[];return $}});var DG=P("$ZodPipe",(b,w)=>{e.init(b,w),d(b._zod,"values",()=>w.in._zod.values),d(b._zod,"optin",()=>w.in._zod.optin),d(b._zod,"optout",()=>w.out._zod.optout),d(b._zod,"propValues",()=>w.in._zod.propValues),b._zod.parse=($,W)=>{if(W.direction==="backward"){let G=w.out._zod.run($,W);if(G instanceof Promise)return G.then((q)=>V0(q,w.in,W));return V0(G,w.in,W)}let Q=w.in._zod.run($,W);if(Q instanceof Promise)return Q.then((G)=>V0(G,w.out,W));return V0(Q,w.out,W)}});function V0(b,w,$){if(b.issues.length)return b.aborted=!0,b;return w._zod.run({value:b.value,issues:b.issues},$)}var HG=P("$ZodReadonly",(b,w)=>{e.init(b,w),d(b._zod,"propValues",()=>w.innerType._zod.propValues),d(b._zod,"values",()=>w.innerType._zod.values),d(b._zod,"optin",()=>w.innerType._zod.optin),d(b._zod,"optout",()=>w.innerType._zod.optout),b._zod.parse=($,W)=>{if(W.direction==="backward")return w.innerType._zod.run($,W);let Q=w.innerType._zod.run($,W);if(Q instanceof Promise)return Q.then(PQ);return PQ(Q)}});function PQ(b){return b.value=Object.freeze(b.value),b}var zG=P("$ZodCustom",(b,w)=>{Hb.init(b,w),e.init(b,w),b._zod.parse=($,W)=>{return $},b._zod.check=($)=>{let W=$.value,Q=w.fn(W);if(Q instanceof Promise)return Q.then((G)=>BQ(G,$,W,b));BQ(Q,$,W,b);return}});function BQ(b,w,$,W){if(!b){let Q={code:"custom",input:$,inst:W,path:[...W._zod.def.path??[]],continue:!W._zod.def.abort};if(W._zod.def.params)Q.params=W._zod.def.params;w.issues.push(iw(Q))}}var sz=(b)=>{let w=typeof b;switch(w){case"number":return Number.isNaN(b)?"NaN":"number";case"object":{if(Array.isArray(b))return"array";if(b===null)return"null";if(Object.getPrototypeOf(b)!==Object.prototype&&b.constructor)return b.constructor.name}}return w},az=()=>{let b={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function w(W){return b[W]??null}let $={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return(W)=>{switch(W.code){case"invalid_type":return`Invalid input: expected ${W.expected}, received ${sz(W.input)}`;case"invalid_value":if(W.values.length===1)return`Invalid input: expected ${K0(W.values[0])}`;return`Invalid option: expected one of ${P0(W.values,"|")}`;case"too_big":{let Q=W.inclusive?"<=":"<",G=w(W.origin);if(G)return`Too big: expected ${W.origin??"value"} to have ${Q}${W.maximum.toString()} ${G.unit??"elements"}`;return`Too big: expected ${W.origin??"value"} to be ${Q}${W.maximum.toString()}`}case"too_small":{let Q=W.inclusive?">=":">",G=w(W.origin);if(G)return`Too small: expected ${W.origin} to have ${Q}${W.minimum.toString()} ${G.unit}`;return`Too small: expected ${W.origin} to be ${Q}${W.minimum.toString()}`}case"invalid_format":{let Q=W;if(Q.format==="starts_with")return`Invalid string: must start with "${Q.prefix}"`;if(Q.format==="ends_with")return`Invalid string: must end with "${Q.suffix}"`;if(Q.format==="includes")return`Invalid string: must include "${Q.includes}"`;if(Q.format==="regex")return`Invalid string: must match pattern ${Q.pattern}`;return`Invalid ${$[Q.format]??W.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${W.divisor}`;case"unrecognized_keys":return`Unrecognized key${W.keys.length>1?"s":""}: ${P0(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 B4(){return{localeError:az()}}var FI=Symbol("ZodOutput"),KI=Symbol("ZodInput");class OG{constructor(){this._map=new WeakMap,this._idmap=new Map}add(b,...w){let $=w[0];if(this._map.set(b,$),$&&typeof $==="object"&&"id"in $){if(this._idmap.has($.id))throw Error(`ID ${$.id} already exists in the registry`);this._idmap.set($.id,b)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(b){let w=this._map.get(b);if(w&&typeof w==="object"&&"id"in w)this._idmap.delete(w.id);return this._map.delete(b),this}get(b){let w=b._zod.parent;if(w){let $={...this.get(w)??{}};delete $.id;let W={...$,...this._map.get(b)};return Object.keys(W).length?W:void 0}return this._map.get(b)}has(b){return this._map.has(b)}}function bO(){return new OG}var _1=bO();function AG(b,w){return new b({type:"string",...S(w)})}function UG(b,w){return new b({type:"string",format:"email",check:"string_format",abort:!1,...S(w)})}function F4(b,w){return new b({type:"string",format:"guid",check:"string_format",abort:!1,...S(w)})}function LG(b,w){return new b({type:"string",format:"uuid",check:"string_format",abort:!1,...S(w)})}function PG(b,w){return new b({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...S(w)})}function BG(b,w){return new b({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...S(w)})}function FG(b,w){return new b({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...S(w)})}function KG(b,w){return new b({type:"string",format:"url",check:"string_format",abort:!1,...S(w)})}function MG(b,w){return new b({type:"string",format:"emoji",check:"string_format",abort:!1,...S(w)})}function IG(b,w){return new b({type:"string",format:"nanoid",check:"string_format",abort:!1,...S(w)})}function _G(b,w){return new b({type:"string",format:"cuid",check:"string_format",abort:!1,...S(w)})}function ZG(b,w){return new b({type:"string",format:"cuid2",check:"string_format",abort:!1,...S(w)})}function jG(b,w){return new b({type:"string",format:"ulid",check:"string_format",abort:!1,...S(w)})}function VG(b,w){return new b({type:"string",format:"xid",check:"string_format",abort:!1,...S(w)})}function NG(b,w){return new b({type:"string",format:"ksuid",check:"string_format",abort:!1,...S(w)})}function EG(b,w){return new b({type:"string",format:"ipv4",check:"string_format",abort:!1,...S(w)})}function TG(b,w){return new b({type:"string",format:"ipv6",check:"string_format",abort:!1,...S(w)})}function SG(b,w){return new b({type:"string",format:"cidrv4",check:"string_format",abort:!1,...S(w)})}function RG(b,w){return new b({type:"string",format:"cidrv6",check:"string_format",abort:!1,...S(w)})}function vG(b,w){return new b({type:"string",format:"base64",check:"string_format",abort:!1,...S(w)})}function kG(b,w){return new b({type:"string",format:"base64url",check:"string_format",abort:!1,...S(w)})}function CG(b,w){return new b({type:"string",format:"e164",check:"string_format",abort:!1,...S(w)})}function uG(b,w){return new b({type:"string",format:"jwt",check:"string_format",abort:!1,...S(w)})}function xG(b,w){return new b({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...S(w)})}function yG(b,w){return new b({type:"string",format:"date",check:"string_format",...S(w)})}function hG(b,w){return new b({type:"string",format:"time",check:"string_format",precision:null,...S(w)})}function cG(b,w){return new b({type:"string",format:"duration",check:"string_format",...S(w)})}function fG(b,w){return new b({type:"number",checks:[],...S(w)})}function nG(b,w){return new b({type:"number",check:"number_format",abort:!1,format:"safeint",...S(w)})}function iG(b,w){return new b({type:"boolean",...S(w)})}function mG(b,w){return new b({type:"null",...S(w)})}function lG(b){return new b({type:"unknown"})}function gG(b,w){return new b({type:"never",...S(w)})}function T0(b,w){return new z4({check:"less_than",...S(w),value:b,inclusive:!1})}function Z1(b,w){return new z4({check:"less_than",...S(w),value:b,inclusive:!0})}function S0(b,w){return new O4({check:"greater_than",...S(w),value:b,inclusive:!1})}function j1(b,w){return new O4({check:"greater_than",...S(w),value:b,inclusive:!0})}function R0(b,w){return new e9({check:"multiple_of",...S(w),value:b})}function v0(b,w){return new a9({check:"max_length",...S(w),maximum:b})}function mw(b,w){return new bQ({check:"min_length",...S(w),minimum:b})}function k0(b,w){return new wQ({check:"length_equals",...S(w),length:b})}function K4(b,w){return new $Q({check:"string_format",format:"regex",...S(w),pattern:b})}function M4(b){return new WQ({check:"string_format",format:"lowercase",...S(b)})}function I4(b){return new QQ({check:"string_format",format:"uppercase",...S(b)})}function _4(b,w){return new GQ({check:"string_format",format:"includes",...S(w),includes:b})}function Z4(b,w){return new qQ({check:"string_format",format:"starts_with",...S(w),prefix:b})}function j4(b,w){return new XQ({check:"string_format",format:"ends_with",...S(w),suffix:b})}function kw(b){return new YQ({check:"overwrite",tx:b})}function V4(b){return kw((w)=>w.normalize(b))}function N4(){return kw((b)=>b.trim())}function E4(){return kw((b)=>b.toLowerCase())}function T4(){return kw((b)=>b.toUpperCase())}function pG(b,w,$){return new b({type:"array",element:w,...S($)})}function oG(b,w,$){let W=S($);return W.abort??(W.abort=!0),new b({type:"custom",check:"custom",fn:w,...W})}function dG(b,w,$){return new b({type:"custom",check:"custom",fn:w,...S($)})}function tG(b){let w=wO(($)=>{return $.addIssue=(W)=>{if(typeof W==="string")$.issues.push(iw(W,$.value,w._zod.def));else{let Q=W;if(Q.fatal)Q.continue=!1;Q.code??(Q.code="custom"),Q.input??(Q.input=$.value),Q.inst??(Q.inst=w),Q.continue??(Q.continue=!w._zod.def.abort),$.issues.push(iw(Q))}},b($.value,$)});return w}function wO(b,w){let $=new Hb({check:"custom",...S(w)});return $._zod.check=b,$}function lw(b){return!!b._zod}function Mw(b,w){if(lw(b))return K1(b,w);return b.safeParse(w)}function C0(b){if(!b)return;let w;if(lw(b))w=b._zod?.def?.shape;else w=b.shape;if(!w)return;if(typeof w==="function")try{return w()}catch{return}return w}function rG(b){if(lw(b)){let G=b._zod?.def;if(G){if(G.value!==void 0)return G.value;if(Array.isArray(G.values)&&G.values.length>0)return G.values[0]}}let $=b._def;if($){if($.value!==void 0)return $.value;if(Array.isArray($.values)&&$.values.length>0)return $.values[0]}let W=b.value;if(W!==void 0)return W;return}var N1={};pW(N1,{time:()=>v4,duration:()=>k4,datetime:()=>S4,date:()=>R4,ZodISOTime:()=>aG,ZodISODuration:()=>b8,ZodISODateTime:()=>eG,ZodISODate:()=>sG});var eG=P("ZodISODateTime",(b,w)=>{SQ.init(b,w),bb.init(b,w)});function S4(b){return xG(eG,b)}var sG=P("ZodISODate",(b,w)=>{RQ.init(b,w),bb.init(b,w)});function R4(b){return yG(sG,b)}var aG=P("ZodISOTime",(b,w)=>{vQ.init(b,w),bb.init(b,w)});function v4(b){return hG(aG,b)}var b8=P("ZodISODuration",(b,w)=>{kQ.init(b,w),bb.init(b,w)});function k4(b){return cG(b8,b)}var w8=(b,w)=>{M0.init(b,w),b.name="ZodError",Object.defineProperties(b,{format:{value:($)=>z9(b,$)},flatten:{value:($)=>H9(b,$)},addIssue:{value:($)=>{b.issues.push($),b.message=JSON.stringify(b.issues,fw,2)}},addIssues:{value:($)=>{b.issues.push(...$),b.message=JSON.stringify(b.issues,fw,2)}},isEmpty:{get(){return b.issues.length===0}}})},G_=P("ZodError",w8),Eb=P("ZodError",w8,{Parent:Error});var $8=I0(Eb),W8=_0(Eb),Q8=F1(Eb),G8=M1(Eb),q8=O9(Eb),X8=A9(Eb),Y8=U9(Eb),J8=L9(Eb),D8=P9(Eb),H8=B9(Eb),z8=F9(Eb),O8=K9(Eb);var Qb=P("ZodType",(b,w)=>{return e.init(b,w),b.def=w,b.type=w.type,Object.defineProperty(b,"_def",{value:w}),b.check=(...$)=>{return b.clone(l.mergeDefs(w,{checks:[...w.checks??[],...$.map((W)=>typeof W==="function"?{_zod:{check:W,def:{check:"custom"},onattach:[]}}:W)]}))},b.clone=($,W)=>yb(b,$,W),b.brand=()=>b,b.register=($,W)=>{return $.add(b,W),b},b.parse=($,W)=>$8(b,$,W,{callee:b.parse}),b.safeParse=($,W)=>Q8(b,$,W),b.parseAsync=async($,W)=>W8(b,$,W,{callee:b.parseAsync}),b.safeParseAsync=async($,W)=>G8(b,$,W),b.spa=b.safeParseAsync,b.encode=($,W)=>q8(b,$,W),b.decode=($,W)=>X8(b,$,W),b.encodeAsync=async($,W)=>Y8(b,$,W),b.decodeAsync=async($,W)=>J8(b,$,W),b.safeEncode=($,W)=>D8(b,$,W),b.safeDecode=($,W)=>H8(b,$,W),b.safeEncodeAsync=async($,W)=>z8(b,$,W),b.safeDecodeAsync=async($,W)=>O8(b,$,W),b.refine=($,W)=>b.check(eO($,W)),b.superRefine=($)=>b.check(sO($)),b.overwrite=($)=>b.check(kw($)),b.optional=()=>Wb(b),b.nullable=()=>L8(b),b.nullish=()=>Wb(L8(b)),b.nonoptional=($)=>gO(b,$),b.array=()=>c(b),b.or=($)=>r([b,$]),b.and=($)=>x0(b,$),b.transform=($)=>u4(b,M8($)),b.default=($)=>iO(b,$),b.prefault=($)=>lO(b,$),b.catch=($)=>oO(b,$),b.pipe=($)=>u4(b,$),b.readonly=()=>rO(b),b.describe=($)=>{let W=b.clone();return _1.add(W,{description:$}),W},Object.defineProperty(b,"description",{get(){return _1.get(b)?.description},configurable:!0}),b.meta=(...$)=>{if($.length===0)return _1.get(b);let W=b.clone();return _1.add(W,$[0]),W},b.isOptional=()=>b.safeParse(void 0).success,b.isNullable=()=>b.safeParse(null).success,b}),P8=P("_ZodString",(b,w)=>{E0.init(b,w),Qb.init(b,w);let $=b._zod.bag;b.format=$.format??null,b.minLength=$.minimum??null,b.maxLength=$.maximum??null,b.regex=(...W)=>b.check(K4(...W)),b.includes=(...W)=>b.check(_4(...W)),b.startsWith=(...W)=>b.check(Z4(...W)),b.endsWith=(...W)=>b.check(j4(...W)),b.min=(...W)=>b.check(mw(...W)),b.max=(...W)=>b.check(v0(...W)),b.length=(...W)=>b.check(k0(...W)),b.nonempty=(...W)=>b.check(mw(1,...W)),b.lowercase=(W)=>b.check(M4(W)),b.uppercase=(W)=>b.check(I4(W)),b.trim=()=>b.check(N4()),b.normalize=(...W)=>b.check(V4(...W)),b.toLowerCase=()=>b.check(E4()),b.toUpperCase=()=>b.check(T4())}),DO=P("ZodString",(b,w)=>{E0.init(b,w),P8.init(b,w),b.email=($)=>b.check(UG(HO,$)),b.url=($)=>b.check(KG(zO,$)),b.jwt=($)=>b.check(uG(NO,$)),b.emoji=($)=>b.check(MG(OO,$)),b.guid=($)=>b.check(F4(A8,$)),b.uuid=($)=>b.check(LG(u0,$)),b.uuidv4=($)=>b.check(PG(u0,$)),b.uuidv6=($)=>b.check(BG(u0,$)),b.uuidv7=($)=>b.check(FG(u0,$)),b.nanoid=($)=>b.check(IG(AO,$)),b.guid=($)=>b.check(F4(A8,$)),b.cuid=($)=>b.check(_G(UO,$)),b.cuid2=($)=>b.check(ZG(LO,$)),b.ulid=($)=>b.check(jG(PO,$)),b.base64=($)=>b.check(vG(ZO,$)),b.base64url=($)=>b.check(kG(jO,$)),b.xid=($)=>b.check(VG(BO,$)),b.ksuid=($)=>b.check(NG(FO,$)),b.ipv4=($)=>b.check(EG(KO,$)),b.ipv6=($)=>b.check(TG(MO,$)),b.cidrv4=($)=>b.check(SG(IO,$)),b.cidrv6=($)=>b.check(RG(_O,$)),b.e164=($)=>b.check(CG(VO,$)),b.datetime=($)=>b.check(S4($)),b.date=($)=>b.check(R4($)),b.time=($)=>b.check(v4($)),b.duration=($)=>b.check(k4($))});function L(b){return AG(DO,b)}var bb=P("ZodStringFormat",(b,w)=>{s.init(b,w),P8.init(b,w)}),HO=P("ZodEmail",(b,w)=>{MQ.init(b,w),bb.init(b,w)});var A8=P("ZodGUID",(b,w)=>{FQ.init(b,w),bb.init(b,w)});var u0=P("ZodUUID",(b,w)=>{KQ.init(b,w),bb.init(b,w)});var zO=P("ZodURL",(b,w)=>{IQ.init(b,w),bb.init(b,w)});var OO=P("ZodEmoji",(b,w)=>{_Q.init(b,w),bb.init(b,w)});var AO=P("ZodNanoID",(b,w)=>{ZQ.init(b,w),bb.init(b,w)});var UO=P("ZodCUID",(b,w)=>{jQ.init(b,w),bb.init(b,w)});var LO=P("ZodCUID2",(b,w)=>{VQ.init(b,w),bb.init(b,w)});var PO=P("ZodULID",(b,w)=>{NQ.init(b,w),bb.init(b,w)});var BO=P("ZodXID",(b,w)=>{EQ.init(b,w),bb.init(b,w)});var FO=P("ZodKSUID",(b,w)=>{TQ.init(b,w),bb.init(b,w)});var KO=P("ZodIPv4",(b,w)=>{CQ.init(b,w),bb.init(b,w)});var MO=P("ZodIPv6",(b,w)=>{uQ.init(b,w),bb.init(b,w)});var IO=P("ZodCIDRv4",(b,w)=>{xQ.init(b,w),bb.init(b,w)});var _O=P("ZodCIDRv6",(b,w)=>{yQ.init(b,w),bb.init(b,w)});var ZO=P("ZodBase64",(b,w)=>{cQ.init(b,w),bb.init(b,w)});var jO=P("ZodBase64URL",(b,w)=>{fQ.init(b,w),bb.init(b,w)});var VO=P("ZodE164",(b,w)=>{nQ.init(b,w),bb.init(b,w)});var NO=P("ZodJWT",(b,w)=>{iQ.init(b,w),bb.init(b,w)});var B8=P("ZodNumber",(b,w)=>{L4.init(b,w),Qb.init(b,w),b.gt=(W,Q)=>b.check(S0(W,Q)),b.gte=(W,Q)=>b.check(j1(W,Q)),b.min=(W,Q)=>b.check(j1(W,Q)),b.lt=(W,Q)=>b.check(T0(W,Q)),b.lte=(W,Q)=>b.check(Z1(W,Q)),b.max=(W,Q)=>b.check(Z1(W,Q)),b.int=(W)=>b.check(U8(W)),b.safe=(W)=>b.check(U8(W)),b.positive=(W)=>b.check(S0(0,W)),b.nonnegative=(W)=>b.check(j1(0,W)),b.negative=(W)=>b.check(T0(0,W)),b.nonpositive=(W)=>b.check(Z1(0,W)),b.multipleOf=(W,Q)=>b.check(R0(W,Q)),b.step=(W,Q)=>b.check(R0(W,Q)),b.finite=()=>b;let $=b._zod.bag;b.minValue=Math.max($.minimum??Number.NEGATIVE_INFINITY,$.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,b.maxValue=Math.min($.maximum??Number.POSITIVE_INFINITY,$.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,b.isInt=($.format??"").includes("int")||Number.isSafeInteger($.multipleOf??0.5),b.isFinite=!0,b.format=$.format??null});function o(b){return fG(B8,b)}var EO=P("ZodNumberFormat",(b,w)=>{mQ.init(b,w),B8.init(b,w)});function U8(b){return nG(EO,b)}var TO=P("ZodBoolean",(b,w)=>{lQ.init(b,w),Qb.init(b,w)});function Db(b){return iG(TO,b)}var SO=P("ZodNull",(b,w)=>{gQ.init(b,w),Qb.init(b,w)});function x4(b){return mG(SO,b)}var RO=P("ZodUnknown",(b,w)=>{pQ.init(b,w),Qb.init(b,w)});function wb(){return lG(RO)}var vO=P("ZodNever",(b,w)=>{oQ.init(b,w),Qb.init(b,w)});function kO(b){return gG(vO,b)}var CO=P("ZodArray",(b,w)=>{dQ.init(b,w),Qb.init(b,w),b.element=w.element,b.min=($,W)=>b.check(mw($,W)),b.nonempty=($)=>b.check(mw(1,$)),b.max=($,W)=>b.check(v0($,W)),b.length=($,W)=>b.check(k0($,W)),b.unwrap=()=>b.element});function c(b,w){return pG(CO,b,w)}var F8=P("ZodObject",(b,w)=>{eQ.init(b,w),Qb.init(b,w),l.defineLazy(b,"shape",()=>{return w.shape}),b.keyof=()=>Ib(Object.keys(b._zod.def.shape)),b.catchall=($)=>b.clone({...b._zod.def,catchall:$}),b.passthrough=()=>b.clone({...b._zod.def,catchall:wb()}),b.loose=()=>b.clone({...b._zod.def,catchall:wb()}),b.strict=()=>b.clone({...b._zod.def,catchall:kO()}),b.strip=()=>b.clone({...b._zod.def,catchall:void 0}),b.extend=($)=>{return l.extend(b,$)},b.safeExtend=($)=>{return l.safeExtend(b,$)},b.merge=($)=>l.merge(b,$),b.pick=($)=>l.pick(b,$),b.omit=($)=>l.omit(b,$),b.partial=(...$)=>l.partial(I8,b,$[0]),b.required=(...$)=>l.required(_8,b,$[0])});function j(b,w){let $={type:"object",shape:b??{},...l.normalizeParams(w)};return new F8($)}function Bb(b,w){return new F8({type:"object",shape:b,catchall:wb(),...l.normalizeParams(w)})}var K8=P("ZodUnion",(b,w)=>{P4.init(b,w),Qb.init(b,w),b.options=w.options});function r(b,w){return new K8({type:"union",options:b,...l.normalizeParams(w)})}var uO=P("ZodDiscriminatedUnion",(b,w)=>{K8.init(b,w),sQ.init(b,w)});function y4(b,w,$){return new uO({type:"union",options:w,discriminator:b,...l.normalizeParams($)})}var xO=P("ZodIntersection",(b,w)=>{aQ.init(b,w),Qb.init(b,w)});function x0(b,w){return new xO({type:"intersection",left:b,right:w})}var yO=P("ZodRecord",(b,w)=>{bG.init(b,w),Qb.init(b,w),b.keyType=w.keyType,b.valueType=w.valueType});function $b(b,w,$){return new yO({type:"record",keyType:b,valueType:w,...l.normalizeParams($)})}var C4=P("ZodEnum",(b,w)=>{wG.init(b,w),Qb.init(b,w),b.enum=w.entries,b.options=Object.values(w.entries);let $=new Set(Object.keys(w.entries));b.extract=(W,Q)=>{let G={};for(let q of W)if($.has(q))G[q]=w.entries[q];else throw Error(`Key ${q} not found in enum`);return new C4({...w,checks:[],...l.normalizeParams(Q),entries:G})},b.exclude=(W,Q)=>{let G={...w.entries};for(let q of W)if($.has(q))delete G[q];else throw Error(`Key ${q} not found in enum`);return new C4({...w,checks:[],...l.normalizeParams(Q),entries:G})}});function Ib(b,w){let $=Array.isArray(b)?Object.fromEntries(b.map((W)=>[W,W])):b;return new C4({type:"enum",entries:$,...l.normalizeParams(w)})}var hO=P("ZodLiteral",(b,w)=>{$G.init(b,w),Qb.init(b,w),b.values=new Set(w.values),Object.defineProperty(b,"value",{get(){if(w.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return w.values[0]}})});function N(b,w){return new hO({type:"literal",values:Array.isArray(b)?b:[b],...l.normalizeParams(w)})}var cO=P("ZodTransform",(b,w)=>{WG.init(b,w),Qb.init(b,w),b._zod.parse=($,W)=>{if(W.direction==="backward")throw new A1(b.constructor.name);$.addIssue=(G)=>{if(typeof G==="string")$.issues.push(l.issue(G,$.value,w));else{let q=G;if(q.fatal)q.continue=!1;q.code??(q.code="custom"),q.input??(q.input=$.value),q.inst??(q.inst=b),$.issues.push(l.issue(q))}};let Q=w.transform($.value,$);if(Q instanceof Promise)return Q.then((G)=>{return $.value=G,$});return $.value=Q,$}});function M8(b){return new cO({type:"transform",transform:b})}var I8=P("ZodOptional",(b,w)=>{QG.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType});function Wb(b){return new I8({type:"optional",innerType:b})}var fO=P("ZodNullable",(b,w)=>{GG.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType});function L8(b){return new fO({type:"nullable",innerType:b})}var nO=P("ZodDefault",(b,w)=>{qG.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType,b.removeDefault=b.unwrap});function iO(b,w){return new nO({type:"default",innerType:b,get defaultValue(){return typeof w==="function"?w():l.shallowClone(w)}})}var mO=P("ZodPrefault",(b,w)=>{XG.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType});function lO(b,w){return new mO({type:"prefault",innerType:b,get defaultValue(){return typeof w==="function"?w():l.shallowClone(w)}})}var _8=P("ZodNonOptional",(b,w)=>{YG.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType});function gO(b,w){return new _8({type:"nonoptional",innerType:b,...l.normalizeParams(w)})}var pO=P("ZodCatch",(b,w)=>{JG.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType,b.removeCatch=b.unwrap});function oO(b,w){return new pO({type:"catch",innerType:b,catchValue:typeof w==="function"?w:()=>w})}var dO=P("ZodPipe",(b,w)=>{DG.init(b,w),Qb.init(b,w),b.in=w.in,b.out=w.out});function u4(b,w){return new dO({type:"pipe",in:b,out:w})}var tO=P("ZodReadonly",(b,w)=>{HG.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType});function rO(b){return new tO({type:"readonly",innerType:b})}var Z8=P("ZodCustom",(b,w)=>{zG.init(b,w),Qb.init(b,w)});function j8(b,w){return oG(Z8,b??(()=>!0),w)}function eO(b,w={}){return dG(Z8,b,w)}function sO(b){return tG(b)}function h4(b,w){return u4(M8(b),w)}vb(B4());var c4="2025-11-25";var V8=[c4,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Iw="io.modelcontextprotocol/related-task",h0="2.0",zb=j8((b)=>b!==null&&(typeof b==="object"||typeof b==="function")),N8=r([L(),o().int()]),E8=L(),bZ=Bb({ttl:r([o(),x4()]).optional(),pollInterval:o().optional()}),aO=j({ttl:o().optional()}),bA=j({taskId:L()}),f4=Bb({progressToken:N8.optional(),[Iw]:bA.optional()}),Tb=j({_meta:f4.optional()}),E1=Tb.extend({task:aO.optional()}),T8=(b)=>E1.safeParse(b).success,Ob=j({method:L(),params:Tb.loose().optional()}),kb=j({_meta:f4.optional()}),Cb=j({method:L(),params:kb.loose().optional()}),Ab=Bb({_meta:f4.optional()}),c0=r([L(),o().int()]),S8=j({jsonrpc:N(h0),id:c0,...Ob.shape}).strict(),n4=(b)=>S8.safeParse(b).success,R8=j({jsonrpc:N(h0),...Cb.shape}).strict(),v8=(b)=>R8.safeParse(b).success,i4=j({jsonrpc:N(h0),id:c0,result:Ab}).strict(),T1=(b)=>i4.safeParse(b).success;var f;(function(b){b[b.ConnectionClosed=-32000]="ConnectionClosed",b[b.RequestTimeout=-32001]="RequestTimeout",b[b.ParseError=-32700]="ParseError",b[b.InvalidRequest=-32600]="InvalidRequest",b[b.MethodNotFound=-32601]="MethodNotFound",b[b.InvalidParams=-32602]="InvalidParams",b[b.InternalError=-32603]="InternalError",b[b.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(f||(f={}));var m4=j({jsonrpc:N(h0),id:c0.optional(),error:j({code:o().int(),message:L(),data:wb().optional()})}).strict();var k8=(b)=>m4.safeParse(b).success;var C8=r([S8,R8,i4,m4]),wZ=r([i4,m4]),f0=Ab.strict(),wA=kb.extend({requestId:c0.optional(),reason:L().optional()}),n0=Cb.extend({method:N("notifications/cancelled"),params:wA}),$A=j({src:L(),mimeType:L().optional(),sizes:c(L()).optional(),theme:Ib(["light","dark"]).optional()}),S1=j({icons:c($A).optional()}),gw=j({name:L(),title:L().optional()}),u8=gw.extend({...gw.shape,...S1.shape,version:L(),websiteUrl:L().optional(),description:L().optional()}),WA=x0(j({applyDefaults:Db().optional()}),$b(L(),wb())),QA=h4((b)=>{if(b&&typeof b==="object"&&!Array.isArray(b)){if(Object.keys(b).length===0)return{form:{}}}return b},x0(j({form:WA.optional(),url:zb.optional()}),$b(L(),wb()).optional())),GA=Bb({list:zb.optional(),cancel:zb.optional(),requests:Bb({sampling:Bb({createMessage:zb.optional()}).optional(),elicitation:Bb({create:zb.optional()}).optional()}).optional()}),qA=Bb({list:zb.optional(),cancel:zb.optional(),requests:Bb({tools:Bb({call:zb.optional()}).optional()}).optional()}),XA=j({experimental:$b(L(),zb).optional(),sampling:j({context:zb.optional(),tools:zb.optional()}).optional(),elicitation:QA.optional(),roots:j({listChanged:Db().optional()}).optional(),tasks:GA.optional()}),YA=Tb.extend({protocolVersion:L(),capabilities:XA,clientInfo:u8}),l4=Ob.extend({method:N("initialize"),params:YA});var JA=j({experimental:$b(L(),zb).optional(),logging:zb.optional(),completions:zb.optional(),prompts:j({listChanged:Db().optional()}).optional(),resources:j({subscribe:Db().optional(),listChanged:Db().optional()}).optional(),tools:j({listChanged:Db().optional()}).optional(),tasks:qA.optional()}),DA=Ab.extend({protocolVersion:L(),capabilities:JA,serverInfo:u8,instructions:L().optional()}),g4=Cb.extend({method:N("notifications/initialized"),params:kb.optional()});var i0=Ob.extend({method:N("ping"),params:Tb.optional()}),HA=j({progress:o(),total:Wb(o()),message:Wb(L())}),zA=j({...kb.shape,...HA.shape,progressToken:N8}),m0=Cb.extend({method:N("notifications/progress"),params:zA}),OA=Tb.extend({cursor:E8.optional()}),R1=Ob.extend({params:OA.optional()}),v1=Ab.extend({nextCursor:E8.optional()}),AA=Ib(["working","input_required","completed","failed","cancelled"]),k1=j({taskId:L(),status:AA,ttl:r([o(),x4()]),createdAt:L(),lastUpdatedAt:L(),pollInterval:Wb(o()),statusMessage:Wb(L())}),pw=Ab.extend({task:k1}),UA=kb.merge(k1),C1=Cb.extend({method:N("notifications/tasks/status"),params:UA}),l0=Ob.extend({method:N("tasks/get"),params:Tb.extend({taskId:L()})}),g0=Ab.merge(k1),p0=Ob.extend({method:N("tasks/result"),params:Tb.extend({taskId:L()})}),$Z=Ab.loose(),o0=R1.extend({method:N("tasks/list")}),d0=v1.extend({tasks:c(k1)}),t0=Ob.extend({method:N("tasks/cancel"),params:Tb.extend({taskId:L()})}),x8=Ab.merge(k1),y8=j({uri:L(),mimeType:Wb(L()),_meta:$b(L(),wb()).optional()}),h8=y8.extend({text:L()}),p4=L().refine((b)=>{try{return atob(b),!0}catch{return!1}},{message:"Invalid Base64 string"}),c8=y8.extend({blob:p4}),u1=Ib(["user","assistant"]),ow=j({audience:c(u1).optional(),priority:o().min(0).max(1).optional(),lastModified:N1.datetime({offset:!0}).optional()}),f8=j({...gw.shape,...S1.shape,uri:L(),description:Wb(L()),mimeType:Wb(L()),annotations:ow.optional(),_meta:Wb(Bb({}))}),LA=j({...gw.shape,...S1.shape,uriTemplate:L(),description:Wb(L()),mimeType:Wb(L()),annotations:ow.optional(),_meta:Wb(Bb({}))}),o4=R1.extend({method:N("resources/list")}),PA=v1.extend({resources:c(f8)}),BA=R1.extend({method:N("resources/templates/list")}),FA=v1.extend({resourceTemplates:c(LA)}),d4=Tb.extend({uri:L()}),KA=d4,t4=Ob.extend({method:N("resources/read"),params:KA}),MA=Ab.extend({contents:c(r([h8,c8]))}),IA=Cb.extend({method:N("notifications/resources/list_changed"),params:kb.optional()}),_A=d4,ZA=Ob.extend({method:N("resources/subscribe"),params:_A}),jA=d4,VA=Ob.extend({method:N("resources/unsubscribe"),params:jA}),NA=kb.extend({uri:L()}),EA=Cb.extend({method:N("notifications/resources/updated"),params:NA}),TA=j({name:L(),description:Wb(L()),required:Wb(Db())}),SA=j({...gw.shape,...S1.shape,description:Wb(L()),arguments:Wb(c(TA)),_meta:Wb(Bb({}))}),RA=R1.extend({method:N("prompts/list")}),vA=v1.extend({prompts:c(SA)}),kA=Tb.extend({name:L(),arguments:$b(L(),L()).optional()}),CA=Ob.extend({method:N("prompts/get"),params:kA}),r4=j({type:N("text"),text:L(),annotations:ow.optional(),_meta:$b(L(),wb()).optional()}),e4=j({type:N("image"),data:p4,mimeType:L(),annotations:ow.optional(),_meta:$b(L(),wb()).optional()}),s4=j({type:N("audio"),data:p4,mimeType:L(),annotations:ow.optional(),_meta:$b(L(),wb()).optional()}),uA=j({type:N("tool_use"),name:L(),id:L(),input:$b(L(),wb()),_meta:$b(L(),wb()).optional()}),xA=j({type:N("resource"),resource:r([h8,c8]),annotations:ow.optional(),_meta:$b(L(),wb()).optional()}),yA=f8.extend({type:N("resource_link")}),a4=r([r4,e4,s4,yA,xA]),hA=j({role:u1,content:a4}),cA=Ab.extend({description:L().optional(),messages:c(hA)}),fA=Cb.extend({method:N("notifications/prompts/list_changed"),params:kb.optional()}),nA=j({title:L().optional(),readOnlyHint:Db().optional(),destructiveHint:Db().optional(),idempotentHint:Db().optional(),openWorldHint:Db().optional()}),iA=j({taskSupport:Ib(["required","optional","forbidden"]).optional()}),n8=j({...gw.shape,...S1.shape,description:L().optional(),inputSchema:j({type:N("object"),properties:$b(L(),zb).optional(),required:c(L()).optional()}).catchall(wb()),outputSchema:j({type:N("object"),properties:$b(L(),zb).optional(),required:c(L()).optional()}).catchall(wb()).optional(),annotations:nA.optional(),execution:iA.optional(),_meta:$b(L(),wb()).optional()}),b6=R1.extend({method:N("tools/list")}),mA=v1.extend({tools:c(n8)}),r0=Ab.extend({content:c(a4).default([]),structuredContent:$b(L(),wb()).optional(),isError:Db().optional()}),WZ=r0.or(Ab.extend({toolResult:wb()})),lA=E1.extend({name:L(),arguments:$b(L(),wb()).optional()}),x1=Ob.extend({method:N("tools/call"),params:lA}),gA=Cb.extend({method:N("notifications/tools/list_changed"),params:kb.optional()}),QZ=j({autoRefresh:Db().default(!0),debounceMs:o().int().nonnegative().default(300)}),y1=Ib(["debug","info","notice","warning","error","critical","alert","emergency"]),pA=Tb.extend({level:y1}),w6=Ob.extend({method:N("logging/setLevel"),params:pA}),oA=kb.extend({level:y1,logger:L().optional(),data:wb()}),dA=Cb.extend({method:N("notifications/message"),params:oA}),tA=j({name:L().optional()}),rA=j({hints:c(tA).optional(),costPriority:o().min(0).max(1).optional(),speedPriority:o().min(0).max(1).optional(),intelligencePriority:o().min(0).max(1).optional()}),eA=j({mode:Ib(["auto","required","none"]).optional()}),sA=j({type:N("tool_result"),toolUseId:L().describe("The unique identifier for the corresponding tool call."),content:c(a4).default([]),structuredContent:j({}).loose().optional(),isError:Db().optional(),_meta:$b(L(),wb()).optional()}),aA=y4("type",[r4,e4,s4]),y0=y4("type",[r4,e4,s4,uA,sA]),b7=j({role:u1,content:r([y0,c(y0)]),_meta:$b(L(),wb()).optional()}),w7=E1.extend({messages:c(b7),modelPreferences:rA.optional(),systemPrompt:L().optional(),includeContext:Ib(["none","thisServer","allServers"]).optional(),temperature:o().optional(),maxTokens:o().int(),stopSequences:c(L()).optional(),metadata:zb.optional(),tools:c(n8).optional(),toolChoice:eA.optional()}),$7=Ob.extend({method:N("sampling/createMessage"),params:w7}),$6=Ab.extend({model:L(),stopReason:Wb(Ib(["endTurn","stopSequence","maxTokens"]).or(L())),role:u1,content:aA}),W6=Ab.extend({model:L(),stopReason:Wb(Ib(["endTurn","stopSequence","maxTokens","toolUse"]).or(L())),role:u1,content:r([y0,c(y0)])}),W7=j({type:N("boolean"),title:L().optional(),description:L().optional(),default:Db().optional()}),Q7=j({type:N("string"),title:L().optional(),description:L().optional(),minLength:o().optional(),maxLength:o().optional(),format:Ib(["email","uri","date","date-time"]).optional(),default:L().optional()}),G7=j({type:Ib(["number","integer"]),title:L().optional(),description:L().optional(),minimum:o().optional(),maximum:o().optional(),default:o().optional()}),q7=j({type:N("string"),title:L().optional(),description:L().optional(),enum:c(L()),default:L().optional()}),X7=j({type:N("string"),title:L().optional(),description:L().optional(),oneOf:c(j({const:L(),title:L()})),default:L().optional()}),Y7=j({type:N("string"),title:L().optional(),description:L().optional(),enum:c(L()),enumNames:c(L()).optional(),default:L().optional()}),J7=r([q7,X7]),D7=j({type:N("array"),title:L().optional(),description:L().optional(),minItems:o().optional(),maxItems:o().optional(),items:j({type:N("string"),enum:c(L())}),default:c(L()).optional()}),H7=j({type:N("array"),title:L().optional(),description:L().optional(),minItems:o().optional(),maxItems:o().optional(),items:j({anyOf:c(j({const:L(),title:L()}))}),default:c(L()).optional()}),z7=r([D7,H7]),O7=r([Y7,J7,z7]),A7=r([O7,W7,Q7,G7]),U7=E1.extend({mode:N("form").optional(),message:L(),requestedSchema:j({type:N("object"),properties:$b(L(),A7),required:c(L()).optional()})}),L7=E1.extend({mode:N("url"),message:L(),elicitationId:L(),url:L().url()}),P7=r([U7,L7]),B7=Ob.extend({method:N("elicitation/create"),params:P7}),F7=kb.extend({elicitationId:L()}),K7=Cb.extend({method:N("notifications/elicitation/complete"),params:F7}),e0=Ab.extend({action:Ib(["accept","decline","cancel"]),content:h4((b)=>b===null?void 0:b,$b(L(),r([L(),o(),Db(),c(L())])).optional())}),M7=j({type:N("ref/resource"),uri:L()});var I7=j({type:N("ref/prompt"),name:L()}),_7=Tb.extend({ref:r([I7,M7]),argument:j({name:L(),value:L()}),context:j({arguments:$b(L(),L()).optional()}).optional()}),Z7=Ob.extend({method:N("completion/complete"),params:_7});var j7=Ab.extend({completion:Bb({values:c(L()).max(100),total:Wb(o().int()),hasMore:Wb(Db())})}),V7=j({uri:L().startsWith("file://"),name:L().optional(),_meta:$b(L(),wb()).optional()}),N7=Ob.extend({method:N("roots/list"),params:Tb.optional()}),Q6=Ab.extend({roots:c(V7)}),E7=Cb.extend({method:N("notifications/roots/list_changed"),params:kb.optional()}),GZ=r([i0,l4,Z7,w6,CA,RA,o4,BA,t4,ZA,VA,x1,b6,l0,p0,o0,t0]),qZ=r([n0,m0,g4,E7,C1]),XZ=r([f0,$6,W6,e0,Q6,g0,d0,pw]),YZ=r([i0,$7,B7,N7,l0,p0,o0,t0]),JZ=r([n0,m0,dA,EA,IA,gA,fA,C1,K7]),DZ=r([f0,DA,j7,cA,vA,PA,FA,MA,r0,mA,g0,d0,pw]);class x extends Error{constructor(b,w,$){super(`MCP error ${b}: ${w}`);this.code=b,this.data=$,this.name="McpError"}static fromError(b,w,$){if(b===f.UrlElicitationRequired&&$){let W=$;if(W.elicitations)return new i8(W.elicitations,w)}return new x(b,w,$)}}class i8 extends x{constructor(b,w=`URL elicitation${b.length>1?"s":""} required`){super(f.UrlElicitationRequired,w,{elicitations:b})}get elicitations(){return this.data?.elicitations??[]}}function _w(b){return b==="completed"||b==="failed"||b==="cancelled"}var T7=Symbol("Let zodToJsonSchema decide on which parser to use");var mZ=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function G6(b){let $=C0(b)?.method;if(!$)throw Error("Schema is missing a method literal");let W=rG($);if(typeof W!=="string")throw Error("Schema method literal must be a string");return W}function q6(b,w){let $=Mw(b,w);if(!$.success)throw $.error;return $.data}var u7=60000;class X6{constructor(b){if(this._options=b,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(n0,(w)=>{this._oncancel(w)}),this.setNotificationHandler(m0,(w)=>{this._onprogress(w)}),this.setRequestHandler(i0,(w)=>({})),this._taskStore=b?.taskStore,this._taskMessageQueue=b?.taskMessageQueue,this._taskStore)this.setRequestHandler(l0,async(w,$)=>{let W=await this._taskStore.getTask(w.params.taskId,$.sessionId);if(!W)throw new x(f.InvalidParams,"Failed to retrieve task: Task not found");return{...W}}),this.setRequestHandler(p0,async(w,$)=>{let W=async()=>{let Q=w.params.taskId;if(this._taskMessageQueue){let q;while(q=await this._taskMessageQueue.dequeue(Q,$.sessionId)){if(q.type==="response"||q.type==="error"){let X=q.message,Y=X.id,J=this._requestResolvers.get(Y);if(J)if(this._requestResolvers.delete(Y),q.type==="response")J(X);else{let D=X,H=new x(D.error.code,D.error.message,D.error.data);J(H)}else{let D=q.type==="response"?"Response":"Error";this._onerror(Error(`${D} handler missing for request ${Y}`))}continue}await this._transport?.send(q.message,{relatedRequestId:$.requestId})}}let G=await this._taskStore.getTask(Q,$.sessionId);if(!G)throw new x(f.InvalidParams,`Task not found: ${Q}`);if(!_w(G.status))return await this._waitForTaskUpdate(Q,$.signal),await W();if(_w(G.status)){let q=await this._taskStore.getTaskResult(Q,$.sessionId);return this._clearTaskQueue(Q),{...q,_meta:{...q._meta,[Iw]:{taskId:Q}}}}return await W()};return await W()}),this.setRequestHandler(o0,async(w,$)=>{try{let{tasks:W,nextCursor:Q}=await this._taskStore.listTasks(w.params?.cursor,$.sessionId);return{tasks:W,nextCursor:Q,_meta:{}}}catch(W){throw new x(f.InvalidParams,`Failed to list tasks: ${W instanceof Error?W.message:String(W)}`)}}),this.setRequestHandler(t0,async(w,$)=>{try{let W=await this._taskStore.getTask(w.params.taskId,$.sessionId);if(!W)throw new x(f.InvalidParams,`Task not found: ${w.params.taskId}`);if(_w(W.status))throw new x(f.InvalidParams,`Cannot cancel task in terminal status: ${W.status}`);await this._taskStore.updateTaskStatus(w.params.taskId,"cancelled","Client cancelled task execution.",$.sessionId),this._clearTaskQueue(w.params.taskId);let Q=await this._taskStore.getTask(w.params.taskId,$.sessionId);if(!Q)throw new x(f.InvalidParams,`Task not found after cancellation: ${w.params.taskId}`);return{_meta:{},...Q}}catch(W){if(W instanceof x)throw W;throw new x(f.InvalidRequest,`Failed to cancel task: ${W instanceof Error?W.message:String(W)}`)}})}async _oncancel(b){if(!b.params.requestId)return;this._requestHandlerAbortControllers.get(b.params.requestId)?.abort(b.params.reason)}_setupTimeout(b,w,$,W,Q=!1){this._timeoutInfo.set(b,{timeoutId:setTimeout(W,w),startTime:Date.now(),timeout:w,maxTotalTimeout:$,resetTimeoutOnProgress:Q,onTimeout:W})}_resetTimeout(b){let w=this._timeoutInfo.get(b);if(!w)return!1;let $=Date.now()-w.startTime;if(w.maxTotalTimeout&&$>=w.maxTotalTimeout)throw this._timeoutInfo.delete(b),x.fromError(f.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:w.maxTotalTimeout,totalElapsed:$});return clearTimeout(w.timeoutId),w.timeoutId=setTimeout(w.onTimeout,w.timeout),!0}_cleanupTimeout(b){let w=this._timeoutInfo.get(b);if(w)clearTimeout(w.timeoutId),this._timeoutInfo.delete(b)}async connect(b){this._transport=b;let w=this.transport?.onclose;this._transport.onclose=()=>{w?.(),this._onclose()};let $=this.transport?.onerror;this._transport.onerror=(Q)=>{$?.(Q),this._onerror(Q)};let W=this._transport?.onmessage;this._transport.onmessage=(Q,G)=>{if(W?.(Q,G),T1(Q)||k8(Q))this._onresponse(Q);else if(n4(Q))this._onrequest(Q,G);else if(v8(Q))this._onnotification(Q);else this._onerror(Error(`Unknown message type: ${JSON.stringify(Q)}`))},await this._transport.start()}_onclose(){let b=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();let w=x.fromError(f.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let $ of b.values())$(w)}_onerror(b){this.onerror?.(b)}_onnotification(b){let w=this._notificationHandlers.get(b.method)??this.fallbackNotificationHandler;if(w===void 0)return;Promise.resolve().then(()=>w(b)).catch(($)=>this._onerror(Error(`Uncaught error in notification handler: ${$}`)))}_onrequest(b,w){let $=this._requestHandlers.get(b.method)??this.fallbackRequestHandler,W=this._transport,Q=b.params?._meta?.[Iw]?.taskId;if($===void 0){let J={jsonrpc:"2.0",id:b.id,error:{code:f.MethodNotFound,message:"Method not found"}};if(Q&&this._taskMessageQueue)this._enqueueTaskMessage(Q,{type:"error",message:J,timestamp:Date.now()},W?.sessionId).catch((D)=>this._onerror(Error(`Failed to enqueue error response: ${D}`)));else W?.send(J).catch((D)=>this._onerror(Error(`Failed to send an error response: ${D}`)));return}let G=new AbortController;this._requestHandlerAbortControllers.set(b.id,G);let q=T8(b.params)?b.params.task:void 0,X=this._taskStore?this.requestTaskStore(b,W?.sessionId):void 0,Y={signal:G.signal,sessionId:W?.sessionId,_meta:b.params?._meta,sendNotification:async(J)=>{let D={relatedRequestId:b.id};if(Q)D.relatedTask={taskId:Q};await this.notification(J,D)},sendRequest:async(J,D,H)=>{let O={...H,relatedRequestId:b.id};if(Q&&!O.relatedTask)O.relatedTask={taskId:Q};let A=O.relatedTask?.taskId??Q;if(A&&X)await X.updateTaskStatus(A,"input_required");return await this.request(J,D,O)},authInfo:w?.authInfo,requestId:b.id,requestInfo:w?.requestInfo,taskId:Q,taskStore:X,taskRequestedTtl:q?.ttl,closeSSEStream:w?.closeSSEStream,closeStandaloneSSEStream:w?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(q)this.assertTaskHandlerCapability(b.method)}).then(()=>$(b,Y)).then(async(J)=>{if(G.signal.aborted)return;let D={result:J,jsonrpc:"2.0",id:b.id};if(Q&&this._taskMessageQueue)await this._enqueueTaskMessage(Q,{type:"response",message:D,timestamp:Date.now()},W?.sessionId);else await W?.send(D)},async(J)=>{if(G.signal.aborted)return;let D={jsonrpc:"2.0",id:b.id,error:{code:Number.isSafeInteger(J.code)?J.code:f.InternalError,message:J.message??"Internal error",...J.data!==void 0&&{data:J.data}}};if(Q&&this._taskMessageQueue)await this._enqueueTaskMessage(Q,{type:"error",message:D,timestamp:Date.now()},W?.sessionId);else await W?.send(D)}).catch((J)=>this._onerror(Error(`Failed to send response: ${J}`))).finally(()=>{this._requestHandlerAbortControllers.delete(b.id)})}_onprogress(b){let{progressToken:w,...$}=b.params,W=Number(w),Q=this._progressHandlers.get(W);if(!Q){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(b)}`));return}let G=this._responseHandlers.get(W),q=this._timeoutInfo.get(W);if(q&&G&&q.resetTimeoutOnProgress)try{this._resetTimeout(W)}catch(X){this._responseHandlers.delete(W),this._progressHandlers.delete(W),this._cleanupTimeout(W),G(X);return}Q($)}_onresponse(b){let w=Number(b.id),$=this._requestResolvers.get(w);if($){if(this._requestResolvers.delete(w),T1(b))$(b);else{let G=new x(b.error.code,b.error.message,b.error.data);$(G)}return}let W=this._responseHandlers.get(w);if(W===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(b)}`));return}this._responseHandlers.delete(w),this._cleanupTimeout(w);let Q=!1;if(T1(b)&&b.result&&typeof b.result==="object"){let G=b.result;if(G.task&&typeof G.task==="object"){let q=G.task;if(typeof q.taskId==="string")Q=!0,this._taskProgressTokens.set(q.taskId,w)}}if(!Q)this._progressHandlers.delete(w);if(T1(b))W(b);else{let G=x.fromError(b.error.code,b.error.message,b.error.data);W(G)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(b,w,$){let{task:W}=$??{};if(!W){try{yield{type:"result",result:await this.request(b,w,$)}}catch(G){yield{type:"error",error:G instanceof x?G:new x(f.InternalError,String(G))}}return}let Q;try{let G=await this.request(b,pw,$);if(G.task)Q=G.task.taskId,yield{type:"taskCreated",task:G.task};else throw new x(f.InternalError,"Task creation did not return a task");while(!0){let q=await this.getTask({taskId:Q},$);if(yield{type:"taskStatus",task:q},_w(q.status)){if(q.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:Q},w,$)};else if(q.status==="failed")yield{type:"error",error:new x(f.InternalError,`Task ${Q} failed`)};else if(q.status==="cancelled")yield{type:"error",error:new x(f.InternalError,`Task ${Q} was cancelled`)};return}if(q.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:Q},w,$)};return}let X=q.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((Y)=>setTimeout(Y,X)),$?.signal?.throwIfAborted()}}catch(G){yield{type:"error",error:G instanceof x?G:new x(f.InternalError,String(G))}}}request(b,w,$){let{relatedRequestId:W,resumptionToken:Q,onresumptiontoken:G,task:q,relatedTask:X}=$??{};return new Promise((Y,J)=>{let D=(I)=>{J(I)};if(!this._transport){D(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(b.method),q)this.assertTaskCapability(b.method)}catch(I){D(I);return}$?.signal?.throwIfAborted();let H=this._requestMessageId++,O={...b,jsonrpc:"2.0",id:H};if($?.onprogress)this._progressHandlers.set(H,$.onprogress),O.params={...b.params,_meta:{...b.params?._meta||{},progressToken:H}};if(q)O.params={...O.params,task:q};if(X)O.params={...O.params,_meta:{...O.params?._meta||{},[Iw]:X}};let A=(I)=>{this._responseHandlers.delete(H),this._progressHandlers.delete(H),this._cleanupTimeout(H),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:H,reason:String(I)}},{relatedRequestId:W,resumptionToken:Q,onresumptiontoken:G}).catch((T)=>this._onerror(Error(`Failed to send cancellation: ${T}`)));let R=I instanceof x?I:new x(f.RequestTimeout,String(I));J(R)};this._responseHandlers.set(H,(I)=>{if($?.signal?.aborted)return;if(I instanceof Error)return J(I);try{let R=Mw(w,I.result);if(!R.success)J(R.error);else Y(R.data)}catch(R){J(R)}}),$?.signal?.addEventListener("abort",()=>{A($?.signal?.reason)});let B=$?.timeout??u7,K=()=>A(x.fromError(f.RequestTimeout,"Request timed out",{timeout:B}));this._setupTimeout(H,B,$?.maxTotalTimeout,K,$?.resetTimeoutOnProgress??!1);let _=X?.taskId;if(_){let I=(R)=>{let T=this._responseHandlers.get(H);if(T)T(R);else this._onerror(Error(`Response handler missing for side-channeled request ${H}`))};this._requestResolvers.set(H,I),this._enqueueTaskMessage(_,{type:"request",message:O,timestamp:Date.now()}).catch((R)=>{this._cleanupTimeout(H),J(R)})}else this._transport.send(O,{relatedRequestId:W,resumptionToken:Q,onresumptiontoken:G}).catch((I)=>{this._cleanupTimeout(H),J(I)})})}async getTask(b,w){return this.request({method:"tasks/get",params:b},g0,w)}async getTaskResult(b,w,$){return this.request({method:"tasks/result",params:b},w,$)}async listTasks(b,w){return this.request({method:"tasks/list",params:b},d0,w)}async cancelTask(b,w){return this.request({method:"tasks/cancel",params:b},x8,w)}async notification(b,w){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(b.method);let $=w?.relatedTask?.taskId;if($){let q={...b,jsonrpc:"2.0",params:{...b.params,_meta:{...b.params?._meta||{},[Iw]:w.relatedTask}}};await this._enqueueTaskMessage($,{type:"notification",message:q,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(b.method)&&!b.params&&!w?.relatedRequestId&&!w?.relatedTask){if(this._pendingDebouncedNotifications.has(b.method))return;this._pendingDebouncedNotifications.add(b.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(b.method),!this._transport)return;let q={...b,jsonrpc:"2.0"};if(w?.relatedTask)q={...q,params:{...q.params,_meta:{...q.params?._meta||{},[Iw]:w.relatedTask}}};this._transport?.send(q,w).catch((X)=>this._onerror(X))});return}let G={...b,jsonrpc:"2.0"};if(w?.relatedTask)G={...G,params:{...G.params,_meta:{...G.params?._meta||{},[Iw]:w.relatedTask}}};await this._transport.send(G,w)}setRequestHandler(b,w){let $=G6(b);this.assertRequestHandlerCapability($),this._requestHandlers.set($,(W,Q)=>{let G=q6(b,W);return Promise.resolve(w(G,Q))})}removeRequestHandler(b){this._requestHandlers.delete(b)}assertCanSetRequestHandler(b){if(this._requestHandlers.has(b))throw Error(`A request handler for ${b} already exists, which would be overridden`)}setNotificationHandler(b,w){let $=G6(b);this._notificationHandlers.set($,(W)=>{let Q=q6(b,W);return Promise.resolve(w(Q))})}removeNotificationHandler(b){this._notificationHandlers.delete(b)}_cleanupTaskProgressHandler(b){let w=this._taskProgressTokens.get(b);if(w!==void 0)this._progressHandlers.delete(w),this._taskProgressTokens.delete(b)}async _enqueueTaskMessage(b,w,$){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let W=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(b,w,$,W)}async _clearTaskQueue(b,w){if(this._taskMessageQueue){let $=await this._taskMessageQueue.dequeueAll(b,w);for(let W of $)if(W.type==="request"&&n4(W.message)){let Q=W.message.id,G=this._requestResolvers.get(Q);if(G)G(new x(f.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(Q);else this._onerror(Error(`Resolver missing for request ${Q} during task ${b} cleanup`))}}}async _waitForTaskUpdate(b,w){let $=this._options?.defaultTaskPollInterval??1000;try{let W=await this._taskStore?.getTask(b);if(W?.pollInterval)$=W.pollInterval}catch{}return new Promise((W,Q)=>{if(w.aborted){Q(new x(f.InvalidRequest,"Request cancelled"));return}let G=setTimeout(W,$);w.addEventListener("abort",()=>{clearTimeout(G),Q(new x(f.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(b,w){let $=this._taskStore;if(!$)throw Error("No task store configured");return{createTask:async(W)=>{if(!b)throw Error("No request provided");return await $.createTask(W,b.id,{method:b.method,params:b.params},w)},getTask:async(W)=>{let Q=await $.getTask(W,w);if(!Q)throw new x(f.InvalidParams,"Failed to retrieve task: Task not found");return Q},storeTaskResult:async(W,Q,G)=>{await $.storeTaskResult(W,Q,G,w);let q=await $.getTask(W,w);if(q){let X=C1.parse({method:"notifications/tasks/status",params:q});if(await this.notification(X),_w(q.status))this._cleanupTaskProgressHandler(W)}},getTaskResult:(W)=>{return $.getTaskResult(W,w)},updateTaskStatus:async(W,Q,G)=>{let q=await $.getTask(W,w);if(!q)throw new x(f.InvalidParams,`Task "${W}" not found - it may have been cleaned up`);if(_w(q.status))throw new x(f.InvalidParams,`Cannot update task "${W}" from terminal status "${q.status}" to "${Q}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await $.updateTaskStatus(W,Q,G,w);let X=await $.getTask(W,w);if(X){let Y=C1.parse({method:"notifications/tasks/status",params:X});if(await this.notification(Y),_w(X.status))this._cleanupTaskProgressHandler(W)}},listTasks:(W)=>{return $.listTasks(W,w)}}}}function m8(b){return b!==null&&typeof b==="object"&&!Array.isArray(b)}function l8(b,w){let $={...b};for(let W in w){let Q=W,G=w[Q];if(G===void 0)continue;let q=$[Q];if(m8(q)&&m8(G))$[Q]={...q,...G};else $[Q]=G}return $}var MD=gW(wW(),1),ID=gW(KD(),1);function lK(){let b=new MD.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return ID.default(b),b}class HW{constructor(b){this._ajv=b??lK()}getValidator(b){let w="$id"in b&&typeof b.$id==="string"?this._ajv.getSchema(b.$id)??this._ajv.compile(b):this._ajv.compile(b);return($)=>{if(w($))return{valid:!0,data:$,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(w.errors)}}}}class zW{constructor(b){this._server=b}requestStream(b,w,$){return this._server.requestStream(b,w,$)}async getTask(b,w){return this._server.getTask({taskId:b},w)}async getTaskResult(b,w,$){return this._server.getTaskResult({taskId:b},w,$)}async listTasks(b,w){return this._server.listTasks(b?{cursor:b}:void 0,w)}async cancelTask(b,w){return this._server.cancelTask({taskId:b},w)}}function _D(b,w,$){if(!b)throw Error(`${$} does not support task creation (required for ${w})`);switch(w){case"tools/call":if(!b.tools?.call)throw Error(`${$} does not support task creation for tools/call (required for ${w})`);break;default:break}}function ZD(b,w,$){if(!b)throw Error(`${$} does not support task creation (required for ${w})`);switch(w){case"sampling/createMessage":if(!b.sampling?.createMessage)throw Error(`${$} does not support task creation for sampling/createMessage (required for ${w})`);break;case"elicitation/create":if(!b.elicitation?.create)throw Error(`${$} does not support task creation for elicitation/create (required for ${w})`);break;default:break}}class OW extends X6{constructor(b,w){super(w);if(this._serverInfo=b,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(y1.options.map(($,W)=>[$,W])),this.isMessageIgnored=($,W)=>{let Q=this._loggingLevels.get(W);return Q?this.LOG_LEVEL_SEVERITY.get($)<this.LOG_LEVEL_SEVERITY.get(Q):!1},this._capabilities=w?.capabilities??{},this._instructions=w?.instructions,this._jsonSchemaValidator=w?.jsonSchemaValidator??new HW,this.setRequestHandler(l4,($)=>this._oninitialize($)),this.setNotificationHandler(g4,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(w6,async($,W)=>{let Q=W.sessionId||W.requestInfo?.headers["mcp-session-id"]||void 0,{level:G}=$.params,q=y1.safeParse(G);if(q.success)this._loggingLevels.set(Q,q.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new zW(this)};return this._experimental}registerCapabilities(b){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=l8(this._capabilities,b)}setRequestHandler(b,w){let W=C0(b)?.method;if(!W)throw Error("Schema is missing a method literal");let Q;if(lw(W)){let q=W;Q=q._zod?.def?.value??q.value}else{let q=W;Q=q._def?.value??q.value}if(typeof Q!=="string")throw Error("Schema method literal must be a string");if(Q==="tools/call"){let q=async(X,Y)=>{let J=Mw(x1,X);if(!J.success){let A=J.error instanceof Error?J.error.message:String(J.error);throw new x(f.InvalidParams,`Invalid tools/call request: ${A}`)}let{params:D}=J.data,H=await Promise.resolve(w(X,Y));if(D.task){let A=Mw(pw,H);if(!A.success){let B=A.error instanceof Error?A.error.message:String(A.error);throw new x(f.InvalidParams,`Invalid task creation result: ${B}`)}return A.data}let O=Mw(r0,H);if(!O.success){let A=O.error instanceof Error?O.error.message:String(O.error);throw new x(f.InvalidParams,`Invalid tools/call result: ${A}`)}return O.data};return super.setRequestHandler(b,q)}return super.setRequestHandler(b,w)}assertCapabilityForMethod(b){switch(b){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${b})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${b})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${b})`);break;case"ping":break}}assertNotificationCapability(b){switch(b){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${b})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${b})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${b})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${b})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${b})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(b){if(!this._capabilities)return;switch(b){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${b})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${b})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${b})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${b})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${b})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${b})`);break;case"ping":case"initialize":break}}assertTaskCapability(b){ZD(this._clientCapabilities?.tasks?.requests,b,"Client")}assertTaskHandlerCapability(b){if(!this._capabilities)return;_D(this._capabilities.tasks?.requests,b,"Server")}async _oninitialize(b){let w=b.params.protocolVersion;return this._clientCapabilities=b.params.capabilities,this._clientVersion=b.params.clientInfo,{protocolVersion:V8.includes(w)?w:c4,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},f0)}async createMessage(b,w){if(b.tools||b.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if(b.messages.length>0){let $=b.messages[b.messages.length-1],W=Array.isArray($.content)?$.content:[$.content],Q=W.some((Y)=>Y.type==="tool_result"),G=b.messages.length>1?b.messages[b.messages.length-2]:void 0,q=G?Array.isArray(G.content)?G.content:[G.content]:[],X=q.some((Y)=>Y.type==="tool_use");if(Q){if(W.some((Y)=>Y.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!X)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(X){let Y=new Set(q.filter((D)=>D.type==="tool_use").map((D)=>D.id)),J=new Set(W.filter((D)=>D.type==="tool_result").map((D)=>D.toolUseId));if(Y.size!==J.size||![...Y].every((D)=>J.has(D)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if(b.tools)return this.request({method:"sampling/createMessage",params:b},W6,w);return this.request({method:"sampling/createMessage",params:b},$6,w)}async elicitInput(b,w){switch(b.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let W=b;return this.request({method:"elicitation/create",params:W},e0,w)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let W=b.mode==="form"?b:{...b,mode:"form"},Q=await this.request({method:"elicitation/create",params:W},e0,w);if(Q.action==="accept"&&Q.content&&W.requestedSchema)try{let q=this._jsonSchemaValidator.getValidator(W.requestedSchema)(Q.content);if(!q.valid)throw new x(f.InvalidParams,`Elicitation response content does not match requested schema: ${q.errorMessage}`)}catch(G){if(G instanceof x)throw G;throw new x(f.InternalError,`Error validating elicitation response: ${G instanceof Error?G.message:String(G)}`)}return Q}}}createElicitationCompletionNotifier(b,w){if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:b}},w)}async listRoots(b,w){return this.request({method:"roots/list",params:b},Q6,w)}async sendLoggingMessage(b,w){if(this._capabilities.logging){if(!this.isMessageIgnored(b.level,w))return this.notification({method:"notifications/message",params:b})}}async sendResourceUpdated(b){return this.notification({method:"notifications/resources/updated",params:b})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}var jD={name:"@sequenzy/mcp",version:"0.0.119",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 AW=["product-info","domain","tracking","localization","integrations","products","events","tags","labels","goals","sync-rules","api-keys","widgets","team","danger"],VD={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 pK(b){let $=(b??process.env.SEQUENZY_APP_URL??"https://sequenzy.com").trim().replace(/\/+$/,"");return $.length>0?$:"https://sequenzy.com"}function gb(b){let w=b?.trim();return w?w:void 0}function sb(b){return encodeURIComponent(b)}function Yb(b,w){return`${b}${w}`}function Jb(b,w=""){return`/dashboard/company/${sb(b)}${w}`}function ND(b,w,$){return Yb(b,`${Jb(w,"/settings")}?tab=${encodeURIComponent($)}`)}function oK(b,w){let $=AW.map((W)=>[W,w?ND(b,w,W):""]);return Object.fromEntries($)}function Dw(b={},w){let $=pK(w),W=gb(b.companyId),Q={},G=oK($,W);if(!W)return{appUrl:$,routeTemplates:VD,settingsTabValues:AW,urls:Q,settingsUrls:G};Q.dashboard=Yb($,Jb(W)),Q.campaigns=Yb($,Jb(W,"/campaign")),Q.landingPages=Yb($,Jb(W,"/landing-pages")),Q.sequences=Yb($,Jb(W,"/sequences")),Q.settings=Yb($,Jb(W,"/settings")),Q.emails=Yb($,Jb(W,"/emails")),Q.subscribers=Yb($,Jb(W,"/subscribers")),Q.sentEmails=Yb($,Jb(W,"/sent-emails")),Q.segments=Yb($,Jb(W,"/segments")),Q.metrics=Yb($,Jb(W,"/metrics")),Q.transactional=Yb($,Jb(W,"/transactional"));let q=gb(b.campaignId);if(q)Q.campaign=Yb($,Jb(W,`/campaign/${sb(q)}`)),Q.campaignPreview=`${Q.campaign}?step=review`;let X=gb(b.landingPageId);if(X)Q.landingPage=Yb($,Jb(W,`/landing-pages/${sb(X)}`));let Y=gb(b.sequenceId);if(Y)Q.sequence=Yb($,Jb(W,`/sequences/${sb(Y)}`));let J=gb(b.emailId)??gb(b.templateId);if(J)Q.email=Yb($,Jb(W,`/emails/${sb(J)}`)),Q.template=Q.email;let D=gb(b.transactionalId);if(D)Q.transactionalEmail=Yb($,Jb(W,`/transactional/${sb(D)}`));let H=gb(b.emailSendId);if(H)Q.emailSend=Yb($,Jb(W,`/sent-emails/${sb(H)}`));let O=gb(b.domainId);if(O)Q.domain=Yb($,Jb(W,`/settings/domain/${sb(O)}`)),Q.domainVerify=`${Q.domain}/verify`;let A=gb(b.status);if(A)Q.campaignList=Yb($,Jb(W,`/campaign/list/${sb(A)}`)),Q.sequenceList=Yb($,Jb(W,`/sequences/list/${sb(A)}`));let B=gb(b.settingsTab);if(B)Q.settingsTab=ND($,W,B);return{appUrl:$,routeTemplates:VD,settingsTabValues:AW,urls:Q,settingsUrls:G}}var ED=[{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 TD(b){try{let w;switch(b){case"sequenzy://dashboard":w=await z("GET","/api/v1/metrics?period=7d");break;case"sequenzy://company":{let $=await z("GET","/api/v1/account"),W=Lw()??$.currentCompanyId;if(!W)throw Error("No company available. Create or select a company first.");w=await z("GET",`/api/v1/companies/${W}`);break}case"sequenzy://campaigns/recent":w=await z("GET","/api/v1/campaigns?limit=10");break;case"sequenzy://subscribers/recent":w=await z("GET","/api/v1/subscribers?sort=createdAt&limit=20");break;case"sequenzy://subscribers/engaged":w=await z("GET","/api/v1/subscribers?sort=engagement&limit=20");break;case"sequenzy://sequences":w=await z("GET","/api/v1/sequences");break;case"sequenzy://templates":w=await z("GET","/api/v1/templates");break;case"sequenzy://segments":w=await z("GET","/api/v1/segments");break;case"sequenzy://tags":w=await z("GET","/api/v1/tags");break;case"sequenzy://health":w=await z("GET","/api/v1/health/deliverability");break;case"sequenzy://app-routes":w=Dw();break;default:throw Error(`Unknown resource: ${b}`)}return{contents:[{uri:b,mimeType:"application/json",text:JSON.stringify(w,null,2)}]}}catch(w){return{contents:[{uri:b,mimeType:"text/plain",text:Uw(w)}]}}}function k(b){return typeof b==="object"&&b!==null&&!Array.isArray(b)}function U(b,w){let $=b[w];if(typeof $!=="string")return;let W=$.trim();return W.length>0?W:void 0}function M(b,w,$){let W=U(w,$);if(W===void 0)throw Error(`\`${$}\` is required when calling \`${b}\`.`);return W}var x$=' 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 UW=' Any block accepts a `conditions` array so it only renders for matching recipients. To branch on a value passed in transactional `variables` or an automation `event` payload, use { "id": "c1", "field": "variable", "operator": "is", "value": "plan:pro" }; "attribute" uses the same "name:value" form, while "email"/"firstName"/"lastName" use a plain comparison value. Live subscriber fields are "status", "tag", "list", "segment", "event", "emailProvider", "phone", "smsStatus", "added", "stripeProduct", "stripeCurrentProduct", "stripeTrialProduct", "commerceProduct", "emailSent", "emailDelivered", "emailOpened", "emailClicked", "emailBounced", and "emailComplained". They use the same field-specific values and operators as segment filters, for example { "id": "c2", "field": "segment", "operator": "is", "value": "seg_123" }, { "id": "c3", "field": "tag", "operator": "contains", "value": "vip" }, or { "id": "c4", "field": "event", "operator": "at_least", "value": "purchase:3:30d" }. Supported operators across fields are is, is_not, contains, not_contains, gt, gte, lt, lte, less_than, more_than, at_least, less_than_count, is_empty, is_not_empty, is_temporary_bounce, and is_permanent_bounce; each field accepts only its segment-filter operators. Recipients without a stored subscriber match use the OTHERWISE branch or hide a conditionally displayed block. For if/else, use a { type: "conditional-group", conditions: [...], ifBranch: { children: [...] }, elseBranch: { children: [...] } } block.',LW=' Polls and NPS surveys use a native poll block. For answer buttons use { "type": "poll", "variant": "options", "question": "What did you think?", "options": [{ "label": "Loved it", "value": "loved" }, { "label": "Not for me", "value": "not_for_me" }], "attributeKey": "email_feedback" }. For NPS use { "type": "poll", "variant": "nps", "question": "How likely are you to recommend us?", "options": [], "attributeKey": "nps_score", "npsLowLabel": "Not likely", "npsHighLabel": "Very likely" }. `attributeKey` stores the latest response for segmentation. Optional `appearance` picks the answer style: "soft" (default), "pill", "outline", "filled", "pop" (hard-shadow boxes), "brutal" (square uppercase slabs), "quiz" (A/B/C letter badges), or "minimal" (bare ruled rows). Optional `confirmationMessage` customizes the hosted thank-you page; set `redirectUrl` only when respondents should land on another page.',PW=' 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" }.',qb="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.",Rw='For exact historical Poll/NPS respondents, use field `pollResponse`, operator `is`, and a JSON value shaped like {"v":1,"campaignId":"camp_123","blockId":"poll_1","match":{"kind":"answer","value":"loved"}}. For NPS buckets, use match {"kind":"npsBucket","bucket":"promoters"}; bucket may be `promoters`, `passives`, or `detractors`.',Hw=`Sequenzy email blocks. Use this for editor-compatible content, including conditional and repeat blocks. For provider-migrated HTML from another email platform, prefer the \`html\` field instead; Sequenzy stores it as one raw HTML block to preserve the original design. Use \`styles\` for per-block background, background opacity, text color, padding, border radius, border width, and border color. Top-level style aliases such as \`backgroundColor\`, \`backgroundOpacity\`, \`borderColor\`, \`borderWidth\`, and \`borderRadius\` are also accepted and saved under \`styles\`. Repeat blocks use { type: 'repeat', source: 'items', itemAlias: 'item', children: [...] }.${UW}${LW}${PW}${x$}`,zw=`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\`.${UW}${LW}${PW}${x$}`,G1=`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.${UW}${LW}${PW}${x$}`,Y0="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.",SD="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.",BW=500,FW=500,pb={type:"boolean",description:"If true, include machine-classified bot/scanner opens and clicks. Defaults to false, so metrics and activity are human-only."},y$=["send","delivery","bounce","complaint","open","click","unsubscribe","delivery_delay"],h$={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},dK={type:"object",description:"Offset relative to a wait-until date.",properties:{days:{type:"number"},hours:{type:"number"},minutes:{type:"number"}},additionalProperties:!1},q1={type:"object",description:"Wait until a date from the trigger event before this step. Use this for renewal reminders, appointment follow-ups, trial-expiry nudges, and other subscriber-specific dates. The field value must be an ISO date string or Unix timestamp.",properties:{field:{type:"string",description:"Dot-path into the trigger event properties, e.g. renews_at or booking.startsAt."},untilDateField:{type:"string",description:"Alias for field."},offset:dK,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},X1={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},KW={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, 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.",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. A standalone raw HTML email does not support this field, and emailPreset must not be combined with html/htmlContent."}},additionalProperties:!0},c$={type:"object",properties:{nodeId:{type:"string",description:"Existing node ID from get_sequence.sequence.nodes[].id."},changes:KW,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},Y1=["gray","red","orange","amber","yellow","lime","green","emerald","teal","cyan","sky","blue","indigo","violet","purple","fuchsia","pink","rose"],J1=["email.sent","email.delivered","email.delivery_delayed","email.bounced","email.complained","email.opened","email.clicked","email.replied","email.unsubscribed","sms.sent","sms.delivered","sms.failed","sms.opted_out","subscriber.invalid","subscriber.updated","subscriber.unsubscribed","subscriber.list_subscribed","subscriber.list_unsubscribed","sequence.finished","sequence.failed","poll.answered"];var tK=new Set(["get_account","get_app_urls","get_company","get_sync_rules","get_shopify_automation_settings","list_api_keys","list_websites","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_email_send","list_forms","get_form_embed","get_recipient_suppression","list_landing_pages","get_landing_page","list_sequences","get_sequence","list_sequence_goals","get_sequence_inbound_webhook","list_transactional_emails","get_transactional_email","get_stats","get_campaign_stats","get_sequence_stats","list_campaign_events","list_sequence_events","get_subscriber_activity","list_team_members","list_conversations","get_conversation","list_webhooks","list_webhook_deliveries","generate_email","generate_subject_lines","generate_sms","get_sms_settings"]),rK=new Set(["select_company","create_company","update_company","update_sync_rules","update_shopify_automation_settings","create_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","upsert_products","delete_product","attach_product_file","remove_product_file","upload_image_asset","sync_products","create_tag","update_tag","delete_tag","create_list","update_list","delete_list","add_subscribers_to_list","remove_subscribers_from_list","create_segment","update_segment","delete_segment","create_audience_sync","update_audience_sync","delete_audience_sync","sync_audience_now","create_template","update_template","set_template_localization","sync_template_localizations","delete_template","restart_ab_test","update_ab_test_variant","create_ab_test","add_ab_test_variant","delete_ab_test_variant","delete_ab_test","create_campaign","update_campaign","schedule_campaign","send_test_email","send_test_sms","cancel_campaign","pause_campaign","resume_campaign","delete_campaign","duplicate_campaign","resend_campaign_to_non_openers","create_form","create_landing_page","update_landing_page","delete_landing_page","publish_landing_page","unpublish_landing_page","connect_landing_page_domain","update_landing_page_domain_settings","create_sequence","generate_sequence","update_sequence","update_sequence_node","update_sequence_nodes","edit_sequence_graph","insert_sequence_step","enable_sequence","disable_sequence","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","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"]),eK=new Set(["send_test_email","send_test_sms","schedule_campaign","resume_campaign","publish_landing_page","connect_landing_page_domain","update_landing_page_domain_settings","add_sending_domain","add_website","verify_sending_domain","enable_sequence","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"]),sK=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","delete_segment","delete_audience_sync","delete_template","restart_ab_test","delete_ab_test_variant","delete_ab_test","cancel_campaign","delete_campaign","delete_landing_page","unpublish_landing_page","disable_sequence","archive_sequence","delete_sequence_goal","rotate_sequence_inbound_webhook_secret","edit_sequence_graph","cancel_sequence_enrollments","delete_sequence","cancel_team_invitation","delete_webhook","remove_recipient_suppression"]);function aK(b){let w=tK.has(b),$=rK.has(b);if(w===$)throw Error(`MCP tool "${b}" must be classified as exactly one of read-only or mutating.`);return{readOnlyHint:w,destructiveHint:w?!1:sK.has(b),openWorldHint:eK.has(b)}}function RD(b){return{...b,annotations:{...b.annotations,...aK(b.name)}}}var MW={status:["is","is_not"],phone:["is_not_empty","is_empty"],smsStatus:["is","is_not"],tag:["contains","not_contains","is_empty","is_not_empty"],email:["contains","not_contains"],emailProvider:["is","is_not","is_empty","is_not_empty"],added:["less_than","more_than"],firstName:["contains","not_contains","is_empty","is_not_empty"],lastName:["contains","not_contains","is_empty","is_not_empty"],list:["is","is_not","is_empty","is_not_empty"],emailSent:["is","is_not","at_least","less_than_count"],emailDelivered:["is","is_not","at_least","less_than_count"],emailOpened:["is","is_not","at_least","less_than_count"],emailClicked:["is","is_not","at_least","less_than_count"],emailBounced:["is","is_temporary_bounce","is_permanent_bounce","is_not","at_least","less_than_count"],emailComplained:["is","is_not","at_least","less_than_count"],attribute:["is","is_not","is_empty","is_not_empty","gte","lte","gt","lt","contains","not_contains"],event:["is","is_not","at_least","less_than_count"],pollResponse:["is"],segment:["is","is_not"],stripeProduct:["is","is_not","at_least","less_than_count"],stripeCurrentProduct:["is","is_not","gte","lte","gt","lt"],stripeTrialProduct:["is","is_not","gte","lte","gt","lt"],commerceProduct:["is","is_not","at_least","less_than_count"]},bM=Object.entries(MW).map(([b,w])=>`${b}: ${w.join(", ")}`).join("; "),IW={type:"object",properties:{id:{type:"string",description:"Optional filter ID. Any stable string works; one will be generated if omitted."},field:{type:"string",enum:["status","phone","smsStatus","tag","email","emailProvider","added","firstName","lastName","list","emailSent","emailDelivered","emailOpened","emailClicked","emailBounced","emailComplained","attribute","event","pollResponse","segment","stripeProduct","stripeCurrentProduct","stripeTrialProduct","commerceProduct"],description:`Filter field. Use \`phone\` with is_not_empty/is_empty to check whether a subscriber has a phone number, and \`smsStatus\` (is/is_not one of \`subscribed\`, \`unsubscribed\`, \`not_subscribed\`) for SMS marketing consent. Use \`event\` for custom subscriber events, \`segment\` for saved segment membership, \`stripeProduct\`/\`stripeCurrentProduct\`/\`stripeTrialProduct\` for Stripe product-based segments, and \`commerceProduct\` for products purchased through commerce orders - the value is \`provider:productId\` (provider one of \`shopify\`, \`woocommerce\`, \`api\`; product ids are provider-scoped), optionally with an order-count threshold (\`provider:productId:count\`) for at_least/less_than_count; a bare product id matches the id on any provider. Engagement fields (\`emailSent\`, \`emailDelivered\`, \`emailOpened\`, \`emailClicked\`, \`emailBounced\`, \`emailComplained\`) accept a time range as the value, a specific campaign via \`campaign:<campaign_id>\`, or \`count:timeRange\` (e.g. \`10:30d\`, \`10:all\`) with at_least/less_than_count to segment by number of opens/clicks. ${Rw}`},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: ${bM}.`},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). ${Rw}`}},required:["field","operator","value"],additionalProperties:!1},_W={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 f$(b){if(!Array.isArray(b))return b;return b.map((w)=>{if(typeof w!=="object"||w===null)return w;let $=w;if(typeof $.id==="string"&&$.id.trim()!=="")return $;return{...$,id:crypto.randomUUID()}})}function n$(b){if(typeof b!=="object"||b===null)return b;let w=b;if(w.kind==="filter"||"field"in w||"operator"in w||"value"in w){let $=f$([w]);return Array.isArray($)?$[0]:w}if(w.kind!=="group")return b;return{...w,id:typeof w.id==="string"&&w.id.trim()!==""?w.id:crypto.randomUUID(),children:Array.isArray(w.children)?w.children.map(n$):[]}}function wM(b){let w=b.indexOf(":");return w!==-1&&b.substring(0,w).trim().length>0}function $M(b){let w=b.indexOf(":");return w!==-1&&b.substring(w+1).trim().length>0}function vD(b){if(b==="all")return!0;let w=b.match(/^(\d+)d$/);if(!w?.[1])return!1;let $=Number.parseInt(w[1],10);return Number.isInteger($)&&$>0}function WM(b,w){let $=w.split(":");if(b==="at_least"||b==="less_than_count"){if($.length<3)return'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".';let G=$.slice(0,-2).join(":").trim(),q=$.at(-2),X=$.at(-1),Y=q===void 0?Number.NaN:Number.parseInt(q,10);return G&&Number.isInteger(Y)&&Y>0&&X!==void 0&&vD(X)?null:'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".'}if($.length<2)return'Event filters must use "eventName:timeRange", like "saas.purchase:30d".';let W=$.slice(0,-1).join(":").trim(),Q=$.at(-1);return W&&Q!==void 0&&vD(Q)?null:'Event filters must use "eventName:timeRange", like "saas.purchase:30d".'}function QM(b){let w=b.indexOf(":");if(w===-1)return{productId:b,subfilter:null,rawValue:null};let $=b.substring(0,w),W=b.substring(w+1),Q=W.indexOf(":");if(Q===-1)return{productId:$,subfilter:W,rawValue:null};return{productId:$,subfilter:W.substring(0,Q),rawValue:W.substring(Q+1)}}function GM(b){return b.trim().toLowerCase().replace(/[-\s]+/g,"_")}function qM(b){return["is_canceled","is_cancelled","canceled","cancelled","will_cancel","cancel_at_period_end","is_not_canceled","is_not_cancelled","not_canceled","not_cancelled","will_not_cancel"].includes(b)}function XM(b,w){if(w==="cancels_at"||w==="cancel_at"||w==="cancellation_at")return!0;if(b==="stripeCurrentProduct")return["end_at","ends_at","period_end","period_ends_at","current_period_end"].includes(w);return["start_at","started_at","trial_start","trial_started_at","end_at","ends_at","trial_end","trial_ends_at"].includes(w)}function YM(b){return["is","is_not","gte","lte","gt","lt"].includes(b)}function JM(b,w,$){if(b==="stripeProduct"){if(w!=="at_least"&&w!=="less_than_count")return null;let X=$.indexOf(":");if(X===-1)return null;let Y=$.substring(0,X).trim(),J=Number.parseInt($.substring(X+1).trim(),10);return Y&&Number.isInteger(J)&&J>=1?null:'Stripe Product threshold filters must use "productId:count" with a count of at least 1.'}if(b!=="stripeCurrentProduct"&&b!=="stripeTrialProduct")return null;let{productId:W,subfilter:Q,rawValue:G}=QM($);if(!W.trim())return"Stripe product filters must include a product ID.";if(!Q)return w==="is"||w==="is_not"?null:'Stripe current/trial date filters must use "productId:dateField:value".';let q=GM(Q);if(qM(q))return w==="is"||w==="is_not"?null:"Stripe cancellation flag filters only support is and is_not operators.";if(!XM(b,q))return`Unsupported Stripe product subfilter "${Q}".`;if(!YM(w))return"Stripe date filters only support is, is_not, gte, lte, gt, and lt operators.";return G?.trim()?null:'Stripe date filters must include a value like "productId:end_at:2026-05-26".'}var DM=new Set(["shopify","woocommerce","api"]);function HM(b,w){let $=w.trim(),W=$.indexOf(":");if(W!==-1&&DM.has($.substring(0,W).trim()))$=$.substring(W+1).trim();if(!$)return'Purchased Product filters must include a product ID, like "shopify:42".';if(b!=="at_least"&&b!=="less_than_count")return null;let Q=$.lastIndexOf(":");if(Q===-1)return null;let G=$.substring(0,Q).trim(),q=Number.parseInt($.substring(Q+1).trim(),10);return G&&Number.isInteger(q)&&q>=1?null:'Purchased Product threshold filters must use "provider:productId:count" with a count of at least 1.'}function zM(b){let w;try{w=JSON.parse(b)}catch{return`Poll response filters must use valid JSON. ${Rw}`}if(!k(w)||w.v!==1||typeof w.campaignId!=="string"||!w.campaignId.trim()||typeof w.blockId!=="string"||!w.blockId.trim()||!k(w.match))return`Poll response filter context is invalid. ${Rw}`;let $=w.match;if($.kind==="answer"&&typeof $.value==="string"&&$.value.length>0)return null;if($.kind==="npsBucket"&&($.bucket==="promoters"||$.bucket==="passives"||$.bucket==="detractors"))return null;return`Poll response filter match is invalid. ${Rw}`}function i$(b){if(typeof b!=="object"||b===null)return"Segment filters must be objects.";let w=b,$=w.field,W=w.operator,Q=w.value;if(typeof $!=="string"||!($ in MW))return`Unsupported segment filter field "${String($)}".`;if(typeof W!=="string")return`Segment filter "${$}" must include an operator.`;let G=MW[$];if(!G.includes(W))return`Operator "${W}" is not supported for ${$} filters. Use one of: ${G.join(", ")}.`;if(W!=="is_empty"&&W!=="is_not_empty"&&(typeof Q!=="string"||Q.trim().length===0))return`Segment filter "${$}" must include a value.`;if($==="attribute"&&typeof Q==="string"){if(!wM(Q))return'Attribute filters must use "attributeName:value" or "attributeName:" for empty checks.';if(W!=="is_empty"&&W!=="is_not_empty"&&!$M(Q))return'Attribute filters must include a value after "attributeName:".'}if($==="event"&&typeof Q==="string"){let q=WM(W,Q);if(q)return q}if($==="pollResponse"&&typeof Q==="string"){let q=zM(Q);if(q)return q}if(($==="stripeProduct"||$==="stripeCurrentProduct"||$==="stripeTrialProduct")&&typeof Q==="string"){let q=JM($,W,Q);if(q)return q}if($==="commerceProduct"&&typeof Q==="string"){let q=HM(W,Q);if(q)return q}if($==="tag"&&(W==="contains"||W==="not_contains")){if(!(typeof Q==="string"&&Q.split(",").map((X)=>X.trim()).some(Boolean)))return"Tag filters must include at least one tag name."}return null}function m$(b){if(typeof b!=="object"||b===null)return[];let w=b;if(w.kind==="filter"||"field"in w||"operator"in w||"value"in w){let $=i$(w);return $?[$]:[]}if(Array.isArray(w.children))return w.children.flatMap(m$);return[]}function Sb(b,w,$){if(w.html!==void 0&&w.blocks!==void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${b}\`, not both.`);if(w.blocks!==void 0&&!Array.isArray(w.blocks))throw Error(`\`blocks\` must be an array when calling \`${b}\`.`);if($?.requireContent&&w.html===void 0&&w.blocks===void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${b}\`.`)}function Ow(b,w){if(w.labels===void 0)return;if(!Array.isArray(w.labels))throw Error(`\`labels\` must be an array when calling \`${b}\`.`);if(w.labels.some(($)=>typeof $!=="string"||$.trim().length===0))throw Error(`\`labels\` must contain only non-empty strings when calling \`${b}\`.`)}function uD(b){let w=b.filters!==void 0,$=b.root!==void 0;if(w&&$)throw Error("Provide either `filters` or `root` when calling `create_segment`, not both.");if(!w&&!$)throw Error("Provide either `filters` or `root` when calling `create_segment`.");if(w){if(!Array.isArray(b.filters))throw Error("`filters` must be an array when calling `create_segment`.");if(b.filters.length===0)throw Error("`filters` must include at least one filter when calling `create_segment`.")}if($&&(typeof b.root!=="object"||b.root===null))throw Error("`root` must be an object when calling `create_segment`.");let W=w?b.filters.flatMap((Q)=>{let G=i$(Q);return G?[G]:[]}):m$(b.root);if(W.length>0)throw Error(W[0]??"Invalid segment filter in `create_segment`.")}function xD(b){let w=b.filters!==void 0,$=b.root!==void 0;if(w&&$)throw Error("Provide either `filters` or `root` when calling `update_segment`, not both.");if(b.name===void 0&&b.filterJoinOperator===void 0&&!w&&!$)throw Error("Provide at least one of `name`, `filters`, `root`, or `filterJoinOperator` when calling `update_segment`.");if(w){if(!Array.isArray(b.filters))throw Error("`filters` must be an array when calling `update_segment`.");if(b.filters.length===0)throw Error("`filters` must include at least one filter when calling `update_segment`.")}if($&&(typeof b.root!=="object"||b.root===null))throw Error("`root` must be an object when calling `update_segment`.");let W=w?b.filters.flatMap((Q)=>{let G=i$(Q);return G?[G]:[]}):$?m$(b.root):[];if(W.length>0)throw Error(W[0]??"Invalid segment filter in `update_segment`.")}var ZW=["name","description","logoUrl","founderName","primaryColor","brandColors","valueProps","testimonials","toneVoice","companyContext","emailLengthPreference","socialLinks","privacyPolicyUrl","termsUrl","address","language","pricing","fontFamily","emailTheme","emailDirection","fromEmail","fromName","replyTo","replyToName","replyTrackingEnabled","replyTrackingDomainMode","forwardReplies"];function jW(b,w,$){if(w[$]!==void 0&&!k(w[$]))throw Error(`\`${$}\` must be an object when calling \`${b}\`.`)}function kD(b,w,$){if(w[$]!==void 0&&!Array.isArray(w[$]))throw Error(`\`${$}\` must be an array when calling \`${b}\`.`)}function yD(b){let w=new Set(["companyId",...ZW]),$=Object.keys(b).filter((Q)=>!w.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 ZW)if(b[Q]!==void 0)W[Q]=b[Q];if(Object.keys(W).length===0)throw Error(`Provide at least one of ${ZW.map((Q)=>`\`${Q}\``).join(", ")} when calling \`update_company\`.`);for(let Q of["name","description","logoUrl","founderName","primaryColor","toneVoice","companyContext","emailLengthPreference","privacyPolicyUrl","termsUrl","address","language","fontFamily","emailDirection","fromEmail","fromName","replyTo","replyToName","replyTrackingDomainMode"])if(b[Q]!==void 0&&typeof b[Q]!=="string")throw Error(`\`${Q}\` must be a string when calling \`update_company\`.`);if(jW("update_company",b,"brandColors"),jW("update_company",b,"socialLinks"),jW("update_company",b,"pricing"),b.emailTheme!==void 0&&b.emailTheme!==null&&!k(b.emailTheme))throw Error("`emailTheme` must be an object or null when calling `update_company`.");kD("update_company",b,"valueProps"),kD("update_company",b,"testimonials");for(let Q of["replyTrackingEnabled","forwardReplies"])if(b[Q]!==void 0&&typeof b[Q]!=="boolean")throw Error(`\`${Q}\` must be a boolean when calling \`update_company\`.`);if(b.replyTrackingDomainMode!==void 0&&b.replyTrackingDomainMode!=="sequenzy"&&b.replyTrackingDomainMode!=="custom")throw Error("`replyTrackingDomainMode` must be `sequenzy` or `custom` when calling `update_company`.");if(typeof b.primaryColor==="string"&&!/^#[0-9a-f]{6}$/i.test(b.primaryColor.trim()))throw Error("`primaryColor` must be a 6-digit hex color such as #f97316 when calling `update_company`.");for(let Q of["fromEmail","replyTo"]){let G=b[Q];if(typeof G==="string"&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(G.trim()))throw Error(`\`${Q}\` must be a valid email address when calling \`update_company\`.`)}if(b.fromName!==void 0&&b.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `update_company`.");if(b.replyToName!==void 0&&b.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `update_company`.");return W}var hD=["senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName"];function OM(b){return hD.some((w)=>b[w]!==void 0)}function AM(b){if(typeof b.nodeType==="string")return b.nodeType==="action_email";return b.type===void 0||b.type==="email"}function l$(b,w,$){for(let W of hD){let Q=$[W];if(Q!==void 0&&typeof Q!=="string")throw Error(`\`${W}\` must be a string for ${w} when calling \`${b}\`.`)}if($.senderProfileId!==void 0&&$.fromEmail!==void 0)throw Error(`Provide either \`senderProfileId\` or \`fromEmail\` for ${w} when calling \`${b}\`, not both.`);if($.replyProfileId!==void 0&&$.replyTo!==void 0)throw Error(`Provide either \`replyProfileId\` or \`replyTo\` for ${w} when calling \`${b}\`, not both.`);if($.replyToName!==void 0&&$.replyTo===void 0)throw Error(`\`replyToName\` requires \`replyTo\` for ${w} when calling \`${b}\`.`)}function NW(b,w,$){if(OM($)&&!AM($))throw Error(`Sender identity fields are only supported for email steps at ${w} when calling \`${b}\`.`);l$(b,w,$)}function CD(b,w,$){if(!Array.isArray($))return;$.forEach((W,Q)=>{if(k(W))l$(b,`${w}[${Q}]`,W)})}function VW(b,w,$){if(!Array.isArray($))return;$.forEach((W,Q)=>{if(k(W))NW(b,`${w}[${Q}]`,W)})}function UM(b){if(CD("update_sequence","emails",b.emails),CD("update_sequence","steps",b.steps),k(b.insertSteps))VW("update_sequence","insertSteps.steps",b.insertSteps.steps);if(!k(b.branch))return;if(Array.isArray(b.branch.branches))b.branch.branches.forEach(($,W)=>{if(k($))VW("update_sequence",`branch.branches[${W}].steps`,$.steps)});VW("update_sequence","branch.elseSteps",b.branch.elseSteps)}function cD(b){Ow("update_sequence",b);let w=["listId","tagName","segmentId","stopOnSegmentExit","eventName","propertyFilters","integrationSlug","integrationEventKey","customIntegration","inactiveDays","inactivityBaseline","minCount","timeWindowDays"];if(b.trigger===void 0&&w.some((W)=>b[W]!==void 0))throw Error("Provide `trigger` when replacing sequence trigger configuration with `update_sequence`.");if(b.fromEmail!==void 0&&b.senderProfileId!==void 0)throw Error("Provide either `fromEmail` or `senderProfileId` when calling `update_sequence`, not both.");if(b.replyTo!==void 0&&b.replyProfileId!==void 0)throw Error("Provide either `replyTo` or `replyProfileId` when calling `update_sequence`, not both.");if(b.fromName!==void 0&&b.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `update_sequence`.");if(b.replyToName!==void 0&&b.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `update_sequence`.");if(b.clearEnrollmentFieldPath===!0&&b.enrollmentFieldPath!==void 0)throw Error("Provide either `enrollmentFieldPath` or `clearEnrollmentFieldPath` when calling `update_sequence`, not both.");if(b.clearSendingWindow===!0&&b.sendingWindow!==void 0)throw Error("Provide either `sendingWindow` or `clearSendingWindow` when calling `update_sequence`, not both.");if(b.clearBccEmails===!0&&b.bccEmails!==void 0)throw Error("Provide either `bccEmails` or `clearBccEmails` when calling `update_sequence`, not both.");if(b.branch!==void 0&&b.insertSteps!==void 0)throw Error("Provide either `branch` or `insertSteps` when calling `update_sequence`, not both.");UM(b);let $={...b};if(delete $.clearEnrollmentFieldPath,delete $.clearSendingWindow,delete $.clearBccEmails,b.clearEnrollmentFieldPath===!0)$.enrollmentFieldPath=null;if(b.clearSendingWindow===!0)$.sendingWindow=null;if(b.clearBccEmails===!0)$.bccEmails=null;return $}function LM(b,w){if((w.triggerType??"event")==="event"){if(typeof w.triggerEventName!=="string"||w.triggerEventName.trim().length===0)throw Error(`\`triggerEventName\` is required when calling \`${b}\` with an event goal (the default \`triggerType\`).`);return}if(typeof w.attributePath!=="string"||w.attributePath.trim().length===0)throw Error(`\`attributePath\` is required when calling \`${b}\` with \`triggerType: "attribute_change"\`.`);let W=w.attributeCondition??"changed",Q=typeof w.attributeValue==="string"&&w.attributeValue.trim().length>0,G=typeof w.attributePreviousValue==="string"&&w.attributePreviousValue.trim().length>0;if((W==="changed_to"||W==="changed_from_to")&&!Q)throw Error(`\`attributeValue\` is required when calling \`${b}\` with \`attributeCondition\` \`changed_to\` or \`changed_from_to\`.`);if(W==="changed_from_to"&&!G)throw Error(`\`attributePreviousValue\` is required when calling \`${b}\` with \`attributeCondition: "changed_from_to"\`.`)}function fD(b){LM("create_sequence_goal",b)}function nD(b){if(typeof b.triggerEventName==="string"&&b.triggerEventName.trim().length===0)throw Error("`triggerEventName` must be a non-empty string when provided to `update_sequence_goal`.");if(typeof b.attributePath==="string"&&b.attributePath.trim().length===0)throw Error("`attributePath` must be a non-empty string when provided to `update_sequence_goal`.")}function iD(b,w,$){let W=M(b,w,"nodeId");if(!k(w.changes)||Object.keys(w.changes).length===0)throw Error(`\`changes\` must be a non-empty object for ${$} when calling \`${b}\`.`);let Q=M(b,w,"expectedUpdatedAt");return{nodeId:W,changes:w.changes,expectedUpdatedAt:Q}}function mD(b){let w=iD("update_sequence_node",b,"the node update");return{...b.confirmLiveChange!==void 0&&{confirmLiveChange:b.confirmLiveChange},nodeUpdates:[w]}}function lD(b){if(!Array.isArray(b.updates)||b.updates.length===0)throw Error("`updates` must be a non-empty array when calling `update_sequence_nodes`.");let w=new Set,$=b.updates.map((W,Q)=>{if(!k(W))throw Error(`\`updates[${Q}]\` must be an object when calling \`update_sequence_nodes\`.`);let G=iD("update_sequence_nodes",W,`updates[${Q}]`),q=String(G.nodeId);if(w.has(q))throw Error(`\`updates[${Q}]\` targets duplicate nodeId '${q}' when calling \`update_sequence_nodes\`.`);return w.add(q),G});return{...b.confirmLiveChange!==void 0&&{confirmLiveChange:b.confirmLiveChange},nodeUpdates:$}}function gD(b){let w=M("edit_sequence_graph",b,"action"),$=M("edit_sequence_graph",b,"graphRevision");if(!new Set(["move_node","delete_node","duplicate_node","replace_edges"]).has(w))throw Error("`action` must be `move_node`, `delete_node`, `duplicate_node`, or `replace_edges` when calling `edit_sequence_graph`.");let Q=U(b,"nodeId"),G=U(b,"afterNodeId"),q=U(b,"beforeNodeId"),X=b.edges;if(w!=="replace_edges"&&!Q)throw Error(`\`nodeId\` is required for ${w} when calling \`edit_sequence_graph\`.`);if(w==="replace_edges"&&Q)throw Error("`nodeId` is not used with `replace_edges` when calling `edit_sequence_graph`.");let Y=w==="move_node"||w==="duplicate_node";if(Y&&(G?1:0)+(q?1:0)!==1)throw Error(`Provide exactly one of \`afterNodeId\` or \`beforeNodeId\` for ${w} when calling \`edit_sequence_graph\`.`);if(!Y&&(G||q))throw Error(`\`afterNodeId\` and \`beforeNodeId\` are not used with ${w} when calling \`edit_sequence_graph\`.`);if((w==="replace_edges"||w==="delete_node"&&X!==void 0)&&(!Array.isArray(X)||X.length===0))throw Error(`\`edges\` must contain the complete replacement topology for ${w} when calling \`edit_sequence_graph\`.`);if((w==="move_node"||w==="duplicate_node")&&X!==void 0)throw Error(`\`edges\` is not used with ${w} when calling \`edit_sequence_graph\`.`);let J=Array.isArray(X)?X.map((D,H)=>{if(!k(D))throw Error(`\`edges\` item ${H+1} must be an object when calling \`edit_sequence_graph\`.`);let O=M("edit_sequence_graph",D,"sourceNodeId"),A=M("edit_sequence_graph",D,"targetNodeId");if(D.condition!==void 0&&D.condition!==null&&!k(D.condition))throw Error(`\`edges\` item ${H+1} \`condition\` must be an object when calling \`edit_sequence_graph\`.`);return{sourceNodeId:O,targetNodeId:A,...k(D.condition)?{condition:D.condition}:{}}}):void 0;return{...b.confirmStructuralChange!==void 0&&{confirmStructuralChange:b.confirmStructuralChange},graphEdit:{action:w,expectedRevision:$,...Q?{nodeId:Q}:{},...G?{afterNodeId:G}:{},...q?{beforeNodeId:q}:{},...J?{edges:J}:{}}}}function pD(b){let w=U(b,"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(w))throw Error("`type` is not a supported dashboard sequence step when calling `insert_sequence_step`.");if(w==="logic_wait_for_event"){let q=M("insert_sequence_step",b,"eventName"),X=b.timeoutDays,Y=X===void 0?7:X;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 J=U(b,"timeoutAction")??"continue";if(J!=="continue"&&J!=="exit")throw Error("`timeoutAction` must be `continue` or `exit` when inserting `logic_wait_for_event` with `insert_sequence_step`.");let D={steps:[{nodeType:"logic_wait_for_event",config:{label:U(b,"label")??`Wait for ${q}`,eventName:q,timeoutDays:Y,timeoutAction:J}}]},H=U(b,"afterNodeId");if(H)D.afterNodeId=H;return{...b.confirmStructuralChange!==void 0&&{confirmStructuralChange:b.confirmStructuralChange},insertSteps:D}}if(w==="logic_branch"){let q=M("insert_sequence_step",b,"afterNodeId");if(!Array.isArray(b.branches)||b.branches.length===0)throw Error("`branches` must contain at least one typed condition when inserting `logic_branch` with `insert_sequence_step`.");let X=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"],J=b.allowEmptyPaths===!0,D=b.branches.map((A,B)=>{if(!k(A))throw Error(`\`branches[${B}]\` must be an object when calling \`insert_sequence_step\`.`);let K=M("insert_sequence_step",A,"conditionType");if(!X.has(K))throw Error(`\`branches[${B}].conditionType\` is not supported when calling \`insert_sequence_step\`.`);let _=`branches[${B}]`;if((K==="has_tag"||K==="does_not_have_tag")&&!U(A,"tagId")&&!U(A,"tagName"))throw Error(`\`${_}\` must provide \`tagId\` or \`tagName\` for ${K} when calling \`insert_sequence_step\`.`);if(K==="in_list"&&!U(A,"listId"))throw Error(`\`${_}.listId\` is required for in_list when calling \`insert_sequence_step\`.`);if(K==="in_segment"&&!U(A,"segmentId"))throw Error(`\`${_}.segmentId\` is required for in_segment when calling \`insert_sequence_step\`.`);if(K==="event_received"&&!U(A,"eventName"))throw Error(`\`${_}.eventName\` is required for event_received when calling \`insert_sequence_step\`.`);if(K.startsWith("field_")&&(!U(A,"fieldName")||!U(A,"fieldValue")))throw Error(`\`${_}\` must provide \`fieldName\` and \`fieldValue\` for ${K} when calling \`insert_sequence_step\`.`);if(A.steps!==void 0&&!Array.isArray(A.steps))throw Error(`\`branches[${B}].steps\` must be an array when calling \`insert_sequence_step\`.`);let I=U(A,"targetNodeId"),R=Array.isArray(A.steps)&&A.steps.length>0;if(!I&&!R&&!J)throw Error(`\`branches[${B}]\` must provide \`targetNodeId\` or non-empty \`steps\` when inserting \`logic_branch\` with \`insert_sequence_step\`.`);return Object.fromEntries(Y.flatMap((T)=>A[T]===void 0?[]:[[T,A[T]]]))});if(b.elseSteps!==void 0&&!Array.isArray(b.elseSteps))throw Error("`elseSteps` must be an array when calling `insert_sequence_step`.");let H=U(b,"elseTargetNodeId"),O=Array.isArray(b.elseSteps)&&b.elseSteps.length>0;if(!H&&!O&&!J)throw Error("Provide `elseTargetNodeId` or non-empty `elseSteps` when inserting `logic_branch` with `insert_sequence_step`.");return{...b.confirmStructuralChange!==void 0&&{confirmStructuralChange:b.confirmStructuralChange},branch:{afterNodeId:q,...U(b,"label")?{label:U(b,"label")}:{},branches:D,...Array.isArray(b.elseSteps)?{elseSteps:b.elseSteps}:{},...H?{elseTargetNodeId:H}:{},...J?{allowEmptyPaths:!0}:{}}}}if(w==="delay"||w==="create_discount"||w==="update_subscriber"||w==="condition"||w==="add_tag"||w==="remove_tag"||w==="add_to_list"||w==="remove_from_list"||w==="webhook"){let q;if(w==="delay"){q={type:"delay"};for(let J of["delay","delayMs","waitUntil"])if(b[J]!==void 0)q[J]=b[J];if(q.delay===void 0&&q.delayMs===void 0&&q.waitUntil===void 0)throw Error("Provide `delay`, `delayMs`, or `waitUntil` when inserting a delay step.")}else if(w==="create_discount"){q={type:"create_discount"};for(let J of["discount","label","provider","discountType","percentOff","amountOff","currency","duration","durationInMonths","appliesToAllPlans","planIds","codePrefix","maxRedemptions","lockToSubscriber","expiresAt","expiresInHours"])if(b[J]!==void 0)q[J]=b[J]}else if(w==="update_subscriber"){if(!k(b.config))throw Error("`config` is required when inserting an update_subscriber step.");q={type:"update_subscriber",nodeType:"action_update_attributes",config:b.config}}else if(w==="webhook"){let J=U(b,"method")??"POST";if(J!=="POST"&&J!=="GET")throw Error("`method` must be `POST` or `GET` when inserting a webhook step.");if(b.headers!==void 0&&(!k(b.headers)||Object.values(b.headers).some((D)=>typeof D!=="string")))throw Error("`headers` must be an object with string values when inserting a webhook step.");q={type:"webhook",nodeType:"action_webhook",config:{label:U(b,"label")??"Webhook",url:M("insert_sequence_step",b,"url"),method:J,...b.headers!==void 0?{headers:b.headers}:{}}}}else if(w==="condition"){let J=M("insert_sequence_step",b,"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(J))throw Error("`conditionType` is not supported for condition steps.");if((J==="has_tag"||J==="does_not_have_tag")&&!U(b,"tagId")&&!U(b,"tagName"))throw Error("Provide `tagId` or `tagName` for this condition step.");if(J==="in_list"&&!U(b,"listId"))throw Error("`listId` is required for an in_list condition.");if(J==="in_segment"&&!U(b,"segmentId"))throw Error("`segmentId` is required for an in_segment condition.");if(J==="event_received"&&!U(b,"eventName"))throw Error("`eventName` is required for an event_received condition.");if(J.startsWith("field_")&&(!U(b,"fieldName")||!U(b,"fieldValue")))throw Error("`fieldName` and `fieldValue` are required for field conditions.");let H={label:U(b,"label")??"Condition",conditionType:J};for(let O of["tagId","tagName","listId","segmentId","segmentName","eventName","linkUrl","activityScope","fieldName","fieldValue"])if(b[O]!==void 0)H[O]=b[O];q={type:"condition",nodeType:"logic_condition",config:H}}else{let J=w==="add_tag"||w==="remove_tag",D=w==="add_tag"?"action_add_tag":w==="remove_tag"?"action_remove_tag":w==="add_to_list"?"action_add_to_list":"action_remove_from_list",H={label:U(b,"label")??(w==="add_tag"?"Add Tag":w==="remove_tag"?"Remove Tag":w==="add_to_list"?"Add to List":"Remove from List")};if(J){let O=U(b,"tagId"),A=U(b,"tagName");if(!O&&!A)throw Error("Provide `tagId` or `tagName` when inserting a tag action.");if(O)H.tagId=O;if(A)H.tagName=A}else{H.listId=M("insert_sequence_step",b,"listId");let O=U(b,"listName");if(O)H.listName=O}q={nodeType:D,config:H}}for(let J of["delay","delayMs","waitUntil"])if(w!=="delay"&&b[J]!==void 0)q[J]=b[J];let X={steps:[q]},Y=U(b,"afterNodeId");if(Y)X.afterNodeId=Y;return{...b.confirmStructuralChange!==void 0&&{confirmStructuralChange:b.confirmStructuralChange},insertSteps:X}}let W=w==="sms",Q;if(W){NW("insert_sequence_step","SMS step",b);let q=U(b,"text"),X=Array.isArray(b.blocks)&&b.blocks.length>0;if(q===void 0&&!X)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(b[Y]!==void 0)Q[Y]=b[Y]}else{Sb("insert_sequence_step",b,{requireContent:!0}),l$("insert_sequence_step","email step",b),Q={subject:M("insert_sequence_step",b,"subject")};for(let q of["name","previewText","html","blocks","delay","delayMs","waitUntil","senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName","isTransactional","ccEmails","bccEmails"])if(b[q]!==void 0)Q[q]=b[q]}let G={steps:[Q]};if(b.afterNodeId!==void 0)G.afterNodeId=b.afterNodeId;return{...b.confirmStructuralChange!==void 0&&{confirmStructuralChange:b.confirmStructuralChange},insertSteps:G}}function oD(b){let w=U(b,"subscriberId"),$=b.fieldValues,W=$===void 0?void 0:Array.isArray($)?$:void 0;if($!==void 0&&W===void 0)throw Error("`fieldValues` must be an array when calling `cancel_sequence_enrollments`.");let Q=W?.map((X)=>typeof X==="string"?X.trim():"").filter((X)=>X.length>0)??[];if(W?.some((X)=>typeof X!=="string")||W!==void 0&&Q.length===0)throw Error("`fieldValues` must contain at least one non-empty string when calling `cancel_sequence_enrollments`.");if(w!==void 0===Q.length>0)throw Error("Provide exactly one target when calling `cancel_sequence_enrollments`: `subscriberId` or `fieldValues`.");let G=U(b,"fieldPath"),q=U(b,"reason");return{...w!==void 0&&{subscriberId:w},...G!==void 0&&{fieldPath:G},...Q.length>0&&{fieldValues:Q},...typeof b.dryRun==="boolean"&&{dryRun:b.dryRun},...q!==void 0&&{reason:q}}}function dD(b){Sb("create_campaign",b),Ow("create_campaign",b);let w=U(b,"prompt")!==void 0,$=b.html!==void 0,W=b.blocks!==void 0,Q=b.templateId!==void 0;if(b.prompt!==void 0&&!w)throw Error("`prompt` cannot be empty when calling `create_campaign`.");if(w&&($||W||Q))throw Error("Provide either `prompt`, `html`, `blocks`, or `templateId` when calling `create_campaign`, not multiple content sources.");if(!w&&(b.style!==void 0||b.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_campaign`.");if(!w&&U(b,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_campaign`.")}function tD(b){Sb("create_template",b),Ow("create_template",b);let w=U(b,"prompt")!==void 0,$=[w,b.html!==void 0,b.blocks!==void 0].filter(Boolean).length;if(b.prompt!==void 0&&!w)throw Error("`prompt` cannot be empty when calling `create_template`.");if($!==1)throw Error("Provide exactly one of `prompt`, `html`, or `blocks` when calling `create_template`.");if(!w&&(b.style!==void 0||b.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_template`.");if(!w&&U(b,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_template`.")}function rD(b){if(U(b,"scheduledAt")===void 0)throw Error("`scheduledAt` is required when calling `schedule_campaign`.");if(b.targetLists!==void 0&&!k(b.targetLists))throw Error("`targetLists` must be an object when calling `schedule_campaign`.");if(b.sendTimeOptimization!==void 0){if(typeof b.sendTimeOptimization!=="boolean")throw Error("`sendTimeOptimization` must be a boolean when calling `schedule_campaign`.")}if(b.spreadOverHours!==void 0){if(typeof b.spreadOverHours!=="number"||!Number.isInteger(b.spreadOverHours)||b.spreadOverHours<1||b.spreadOverHours>72)throw Error("`spreadOverHours` must be an integer between 1 and 72 when calling `schedule_campaign`.")}if(b.recurringInterval!==void 0&&b.recurringInterval!=="weekly"&&b.recurringInterval!=="monthly")throw Error("`recurringInterval` must be 'weekly' or 'monthly' when calling `schedule_campaign`.")}function g$(b,w,$){let W=new Set(["companyId","landingPageId","name","slug","content"]),Q=Object.keys(w).filter((G)=>!W.has(G));if(Q.length>0)throw Error(`\`${b}\` accepts only \`name\`, \`slug\`, and \`content\` update fields. Unsupported field${Q.length===1?"":"s"}: ${Q.map((G)=>`\`${G}\``).join(", ")}.`);if($.requireUpdate&&w.name===void 0&&w.slug===void 0&&w.content===void 0)throw Error(`Provide at least one of \`name\`, \`slug\`, or \`content\` when calling \`${b}\`.`);return{...w.name!==void 0&&{name:w.name},...w.slug!==void 0&&{slug:w.slug},...w.content!==void 0&&{content:w.content}}}function eD(b){let w=new Set(["companyId","domain","verify"]),$=Object.keys(b).filter((W)=>!w.has(W));if($.length>0)throw Error(`\`update_landing_page_domain_settings\` accepts only \`domain\` and \`verify\`. Unsupported field${$.length===1?"":"s"}: ${$.map((W)=>`\`${W}\``).join(", ")}.`);if(b.domain===void 0&&b.verify!==!0)throw Error("Provide `domain` or `verify: true` when calling `update_landing_page_domain_settings`.");return{...b.domain!==void 0&&{domain:b.domain},...typeof b.verify==="boolean"&&{verify:b.verify}}}function sD(b){Sb("create_transactional_email",b);let w=U(b,"prompt")!==void 0,$=b.html!==void 0,W=b.blocks!==void 0;if(b.prompt!==void 0&&!w)throw Error("`prompt` cannot be empty when calling `create_transactional_email`.");if(w&&($||W))throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`, not multiple content sources.");if(!w&&(b.style!==void 0||b.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_transactional_email`.");if(!w&&!$&&!W)throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`.");if(!w&&U(b,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_transactional_email`.")}var D1={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},J0={senderProfileId:{type:"string",description:"Sender profile for this step's From identity. Mutually exclusive with fromEmail."},fromEmail:{type:"string",description:"From address for this step. Its domain must be configured and verified. Mutually exclusive with senderProfileId."},fromName:{type:"string",description:"Display name override for this step. Alone it only changes the visible name; with fromEmail it also names a newly created sender profile."},replyProfileId:{type:"string",description:"Reply profile for this step's Reply-To. Mutually exclusive with replyTo."},replyTo:{type:"string",description:"Reply-To address for this step. Mutually exclusive with replyProfileId."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo."}},D0={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."},config:{...D1,description:"Config for advanced nodeType steps. For action_update_attributes, use the documented Update Subscriber fields and trigger-event merge tags; other node types accept their normal config fields.",additionalProperties:!0},subject:{type:"string",description:"Email subject. Required for email steps."},previewText:{type:"string",description:"Email preview text."},blocks:{type:"array",description:G1,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."},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:X1,delayMs:{type:"number",description:"Delay in milliseconds. Useful for standalone type:'delay' steps."},waitUntil:q1,name:{type:"string",description:"Email template name for email steps."},senderProfileId:{type:"string",description:"Sender profile for this email step. Omit to inherit the effective identity of the nearest sequence email. After a branch merge, only fields shared by every incoming path are inherited; conflicting fields use sequence or company defaults."},fromEmail:{type:"string",description:"From address for this email step. Its domain must be verified. Mutually exclusive with senderProfileId."},fromName:{type:"string",description:"Display name override for this email step. With fromEmail, also names a newly created sender profile."},replyProfileId:{type:"string",description:"Reply profile for this email step. Omit to inherit the effective Reply-To of the nearest sequence email. After a branch merge, only fields shared by every incoming path are inherited; conflicting fields use sequence or company defaults."},replyTo:{type:"string",description:"Reply-To address for this email step. Mutually exclusive with replyProfileId."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo."},discount:{type:"object",description:"Discount configuration for create_discount steps. Same shape as create_sequence steps.",additionalProperties:!0},label:{type:"string",description:"Node label for discount or advanced node steps."},provider:{type:"string",enum:["stripe","shopify"],description:"Discount provider. Use stripe to dynamically create a Stripe coupon plus promotion code, or shopify to dynamically create a Shopify Admin discount code."},discountType:{type:"string",enum:["percent","amount"]},percentOff:{type:"number"},amountOff:{type:"number"},currency:{type:"string"},duration:{type:"string",enum:["once","forever","repeating"]},durationInMonths:{type:"number"},appliesToAllPlans:{type:"boolean"},planIds:{type:"array",items:{type:"string"}},codePrefix:{type:"string"},maxRedemptions:{type:"number"},lockToSubscriber:{type:"boolean"},expiresAt:{type:"string"},expiresInHours:{type:"number"}},additionalProperties:!1},EW={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:D0}},required:["conditionType"],additionalProperties:!1};function aD(b){if(!b||typeof b!=="object")return null;let w=b;if(w.success!==!1)return null;if(typeof w.error==="string")return Error(w.error);if(w.error&&typeof w.error==="object"&&typeof w.error.message==="string")return Error(w.error.message);if(typeof w.message==="string")return Error(w.message);return Error("The tool returned an unsuccessful response.")}function TW(b){return b.trim().toLowerCase().replace(/\s+/g,"-")}function PM(b){let w=new URLSearchParams;if(typeof b.query==="string"&&b.query.trim()!=="")w.set("query",b.query.trim());if(Array.isArray(b.tags)&&b.tags.length>0)w.set("tags",b.tags.filter(($)=>typeof $==="string"&&$.trim()!=="").join(","));if(typeof b.list==="string"&&b.list.trim()!=="")w.set("list",b.list.trim());if(typeof b.listId==="string"&&b.listId.trim()!=="")w.set("listId",b.listId.trim());if(typeof b.listName==="string"&&b.listName.trim()!=="")w.set("listName",b.listName.trim());if(typeof b.segmentId==="string"&&b.segmentId.trim()!=="")w.set("segmentId",b.segmentId);if(typeof b.status==="string"&&b.status.trim()!=="")w.set("status",b.status.trim());return w.set("page",String(b.page)),w.set("limit",String(b.pageSize)),w}async function wH(b,w){let $=typeof b.limit==="number"&&Number.isFinite(b.limit)?Math.max(1,Math.trunc(b.limit)):void 0,W=Math.min(100,Math.max(1,$??100)),Q=[],G=1,q=0,X=0,Y=0;while(!0){let D=PM({query:b.query,tags:b.tags,list:b.list,listId:b.listId,listName:b.listName,segmentId:b.segmentId,status:b.status,page:G,pageSize:W}),H=await z("GET",`/api/v1/subscribers?${D.toString()}`,void 0,w);q=H.pagination?.total??H.subscribers.length,X=H.pagination?.totalPages??1,Y+=1,Q.push(...H.subscribers??[]);let O=$!==void 0&&Q.length>=$,A=H.pagination?G>=H.pagination.totalPages:(H.subscribers??[]).length<W;if(O||A)break;G+=1}let J=$!==void 0?Q.slice(0,$):Q;return{success:!0,subscribers:J,pagination:{page:1,limit:W,total:q,totalPages:X,fetchedPages:Y},returned:J.length,truncated:$!==void 0&&q>0&&J.length<q}}function BM(b){let w=typeof b.email==="string"&&b.email.trim()!==""?b.email.trim():void 0,$=typeof b.externalId==="string"&&b.externalId.trim()!==""?b.externalId.trim():void 0;return{...w?{email:w}:{},...$?{externalId:$}:{}}}function Aw(b,w){let $=BM(w);if(!$.email&&!$.externalId)throw Error(`Provide either \`email\` or \`externalId\` when calling \`${b}\`.`);return $}function p$(b,w){let $=new URLSearchParams;if(w?.includeMachineEngagement)$.set("includeMachineEngagement","true");let W=$.toString(),Q=W?`?${W}`:"";if(b.email)return`/api/v1/subscribers/${encodeURIComponent(b.email)}${Q}`;return $.set("externalId",String(b.externalId)),`/api/v1/subscribers/external?${$.toString()}`}function SW(b){if(b.email)return`/api/v1/subscribers/${encodeURIComponent(b.email)}/notes`;let w=new URLSearchParams;return w.set("externalId",String(b.externalId)),`/api/v1/subscribers/external/notes?${w.toString()}`}async function H0(b,w,$){return z("GET",p$(b,$),void 0,w)}function Gb(b,w,$,W){let Q=U(w,$);if(Q===void 0)return;if(!W.includes(Q))throw Error(`\`${$}\` must be one of ${W.join(", ")} when calling \`${b}\`.`);return Q}function z0(b,w,$,W){let Q=M(b,w,$);if(!W.includes(Q))throw Error(`\`${$}\` must be one of ${W.join(", ")} when calling \`${b}\`.`);return Q}function ab(b,w,$,W,Q){let G=w[$];if(G===void 0)return;if(typeof G!=="number"||!Number.isInteger(G)||G<W||G>Q)throw Error(`\`${$}\` must be an integer between ${W} and ${Q} when calling \`${b}\`.`);return G}function FM(b,w){let $=[],W=Gb(b,w,"eventType",y$);if(W)$.push(W);if(w.eventTypes!==void 0){if(!Array.isArray(w.eventTypes))throw Error(`\`eventTypes\` must be an array when calling \`${b}\`.`);w.eventTypes.forEach((Q,G)=>{if(typeof Q!=="string")throw Error(`\`eventTypes\` item ${G+1} must be a string when calling \`${b}\`.`);let q=Q.trim();if(!y$.includes(q))throw Error(`\`eventTypes\` item ${G+1} must be one of ${y$.join(", ")} when calling \`${b}\`.`);$.push(q)})}return[...new Set($)]}function RW(b,w){let $=new URLSearchParams,W=FM(b,w);if(W.length>0)$.set("eventTypes",W.join(","));let Q=Gb(b,w,"period",["1h","24h","7d","30d","90d"]);if(Q)$.set("period",Q);let G=U(w,"start");if(G)$.set("start",G);let q=U(w,"end");if(q)$.set("end",q);let X=ab(b,w,"page",1,1e6);if(X!==void 0)$.set("page",String(X));let Y=ab(b,w,"limit",1,500);if(Y!==void 0)$.set("limit",String(Y));if(w.includeMachineEngagement===!0)$.set("includeMachineEngagement","true");return $}function vW(b,w){if(w.events===void 0)return;if(!Array.isArray(w.events))throw Error(`\`events\` must be an array when calling \`${b}\`.`);let $=w.events.map((W,Q)=>{if(typeof W!=="string"||!J1.includes(W))throw Error(`\`events\` item ${Q+1} must be one of ${J1.join(", ")} when calling \`${b}\`.`);return W});if($.length===0)throw Error(`\`events\` must include at least one event type when calling \`${b}\`.`);return $}function kW(b,w){if(!Array.isArray(w.emails))throw Error(`\`emails\` must be an array when calling \`${b}\`.`);let $=[];if(w.emails.forEach((W,Q)=>{if(typeof W!=="string")throw Error(`\`emails\` item ${Q+1} must be a string when calling \`${b}\`.`);let G=W.trim();if(G.length>0)$.push(G)}),$.length===0)throw Error(`\`emails\` must include at least one email address when calling \`${b}\`.`);if($.length>BW)throw Error(`\`emails\` must include no more than ${BW} email addresses when calling \`${b}\`. Split larger batches into multiple calls.`);return $}function bH(b,w,$,W){let Q=w[$];if(Q===void 0)return;if(!Array.isArray(Q))throw Error(`\`${$}\` must be an array when calling \`${b}\`.`);let G=[];if(Q.forEach((q,X)=>{if(typeof q!=="string")throw Error(`\`${$}\` item ${X+1} must be a string when calling \`${b}\`.`);let Y=q.trim();if(Y.length>0)G.push(Y)}),G.length===0)throw Error(`\`${$}\` must include at least one ${W} when calling \`${b}\`.`);return G}function $H(b){let $=bH("enroll_subscribers_in_sequence",b,"emails","email address"),W=bH("enroll_subscribers_in_sequence",b,"subscriberIds","subscriber ID"),Q=($?.length??0)+(W?.length??0);if(Q===0)throw Error("Provide `emails` or `subscriberIds` when calling `enroll_subscribers_in_sequence`.");if(Q>FW)throw Error(`\`emails\` and \`subscriberIds\` must include no more than ${FW} total targets when calling \`enroll_subscribers_in_sequence\`. Split larger batches into multiple calls.`);let G=U(b,"targetNodeId");return{...$!==void 0&&{emails:$},...W!==void 0&&{subscriberIds:W},...G!==void 0&&{targetNodeId:G}}}import{readFileSync as KM,statSync as MM}from"node:fs";import{basename as IM}from"node:path";var _M={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 ZM(b){let w=b.split(".").pop()?.toLowerCase()??"";return _M[w]??null}var jM=104857600;async function WH(b,w){if(!A0())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 $=ZM(b);if(!$)throw Error("Unsupported file type. Use PDF, ePub, ZIP, image, audio, video, or text files.");let W=MM(b).size;if(W>jM)throw Error(`File is too large (${Math.round(W/1048576)}MB). Delivery files must be 100MB or smaller.`);let Q=KM(b),G=await z("POST","/api/v1/products/delivery/upload-url",{filename:IM(b),contentType:$,fileSizeBytes:W},w),q=await fetch(G.uploadUrl,{method:"PUT",headers:{"Content-Type":$},body:Q});if(!q.ok)throw Error(`File upload failed (${q.status})`);return{url:G.publicUrl,fileName:G.fileName,fileSizeBytes:W,mimeType:$}}async function o$(b){let w=U(b,"companyId");if(w)return w;let $=Lw();if($)return $;try{return(await z("GET","/api/v1/account")).currentCompanyId??void 0}catch{return}}async function d$(b,w){let $=await o$(w);if(!$)throw Error(`A company is required when calling \`${b}\`. Call \`get_account\`, then \`select_company\`, or pass \`companyId\` explicitly.`);return $}function H1(b,w){if(!k(b)||!w)return b;return{...b,url:w}}function QH(b,w){if(!k(b))return b;return{...b,...w.campaign!==void 0&&{url:w.campaign},...w.campaignPreview!==void 0&&{previewUrl:w.campaignPreview}}}function O0(b,w,$){if(!Array.isArray(b)||!w)return b;return b.map((W)=>{if(!k(W))return W;let Q=U(W,"id");if(!Q)return W;let G=Dw({companyId:w,...$==="campaign"&&{campaignId:Q},...$==="landingPage"&&{landingPageId:Q},...$==="sequence"&&{sequenceId:Q},...$==="template"&&{emailId:Q},...$==="transactional"&&{transactionalId:Q}});if($==="campaign")return QH(W,G.urls);let q=$==="sequence"?G.urls.sequence:$==="landingPage"?G.urls.landingPage:$==="template"?G.urls.email:G.urls.transactionalEmail;return H1(W,q)})}function VM(b){if(!Array.isArray(b))return b;return b.map((w)=>{if(!k(w))return w;let $=U(w,"id");if(!$)return w;let W=Dw({companyId:$});return{...w,url:W.urls.dashboard,settingsUrl:W.urls.settings}})}var CW=new Set(["get_account","select_company","create_company","get_company","update_company","list_campaigns","get_campaign","get_email_send","create_campaign","update_campaign","schedule_campaign","send_test_email","cancel_campaign","pause_campaign","resume_campaign","duplicate_campaign","resend_campaign_to_non_openers","list_landing_pages","get_landing_page","create_landing_page","update_landing_page","publish_landing_page","unpublish_landing_page","delete_landing_page","list_sequences","get_sequence","create_sequence","generate_sequence","update_sequence","update_sequence_node","update_sequence_nodes","edit_sequence_graph","insert_sequence_step","enable_sequence","disable_sequence","pause_sequence_enrollments","resume_sequence_enrollments","cancel_sequence_enrollments","list_ab_tests","get_ab_test","get_ab_test_stats","update_ab_test_variant","list_templates","get_template","create_template","update_template","set_template_localization","sync_template_localizations","list_transactional_emails","get_transactional_email","create_transactional_email","update_transactional_email"]);async function GH(b,w,$){if(!k($)||!CW.has(b))return $;let W=k($.company)?$.company:void 0,G=U($,"selectedCompanyId")??U($,"currentCompanyId")??U($,"companyId")??(W?U(W,"id"):void 0)??(W?U(W,"companyId"):void 0)??await o$(w);if(!G)return $;let q=k($.campaign)?$.campaign:void 0,X=k($.sequence)?$.sequence:void 0,Y=k($.landingPage)?$.landingPage:void 0,J=k($.template)?$.template:void 0,D=k($.transactional)&&!Array.isArray($.transactional)?$.transactional:void 0,H={companyId:G,campaignId:U(w,"campaignId")??U($,"campaignId")??(q?U(q,"id"):void 0),landingPageId:U(w,"landingPageId")??U($,"landingPageId")??(Y?U(Y,"id"):void 0),sequenceId:U(w,"sequenceId")??U($,"sequenceId")??(X?U(X,"id"):void 0),emailId:U($,"templateId")??(J?U(J,"id"):void 0)??(D?U(D,"emailId"):void 0)??U(w,"templateId"),transactionalId:U(w,"transactionalId")??(D?U(D,"id"):void 0)??U(w,"idOrSlug"),emailSendId:U(w,"emailSendId")??U($,"emailSendId")??(k($.emailSend)?U($.emailSend,"id"):void 0),status:U(w,"status")},O=Dw(H),A=W?Dw({companyId:G}):void 0;return{...$,...Array.isArray($.companies)&&{companies:VM($.companies)},...Array.isArray($.campaigns)&&{campaigns:O0($.campaigns,G,"campaign")},...Array.isArray($.landingPages)&&{landingPages:O0($.landingPages,G,"landingPage")},...Array.isArray($.sequences)&&{sequences:O0($.sequences,G,"sequence")},...Array.isArray($.templates)&&{templates:O0($.templates,G,"template")},...Array.isArray($.transactional)&&{transactional:O0($.transactional,G,"transactional")},...W&&A!==void 0&&{company:{...W,url:A.urls.dashboard,settingsUrl:A.urls.settings}},...q&&O.urls.campaign!==void 0&&{campaign:QH(q,O.urls)},...X&&O.urls.sequence!==void 0&&{sequence:H1(X,O.urls.sequence)},...Y&&O.urls.landingPage!==void 0&&{landingPage:H1(Y,O.urls.landingPage)},...J&&O.urls.email!==void 0&&{template:H1(J,O.urls.email)},...D&&O.urls.transactionalEmail!==void 0&&{transactional:H1(D,O.urls.transactionalEmail)},...k($.emailSend)&&O.urls.emailSend!==void 0&&{emailSend:H1($.emailSend,O.urls.emailSend)},appUrls:O.urls}}import{readFileSync as NM,statSync as EM}from"node:fs";import{basename as TM,extname as XH}from"node:path";var xW=5242880,SM=Math.ceil(xW/3)*4,RM=Math.ceil(SM*1.05)+256,YH={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"},vM=new Set(Object.values(YH));function uW(b){return b?.split(";")[0]?.trim().toLowerCase()||void 0}function kM(b){return YH[XH(b).toLowerCase()]}function CM(b){let w=XH(b);return(w?b.slice(0,-w.length):b).replace(/[-_]+/g," ").trim()||"Image"}function uM(b){if(b.length>RM)throw Error("Image assets must be 5MB or smaller.")}function xM(b){let w=0,$=0;for(let Q=0;Q<b.length;Q+=1){let G=b.charCodeAt(Q);if(G===9||G===10||G===11||G===12||G===13||G===32)continue;w+=1,$=G===61?$+1:0}if(Math.floor(w*3/4)-Math.min($,2)>xW)throw Error("Image assets must be 5MB or smaller.")}function yM(b){uM(b);let w=b.trim(),$=/^data:([^;,]+);base64,([\s\S]+)$/i.exec(w),W=$?.[2]??w;xM(W);let Q=W.replace(/\s+/g,"");if(Q.length===0||Q.length%4===1||!/^[A-Za-z0-9+/]*={0,2}$/.test(Q))throw Error("`imageBase64` must contain valid base64 image bytes.");return{bytes:Buffer.from(Q,"base64"),...$?.[1]?{dataUrlContentType:uW($[1])}:{}}}function qH(b){if(b<=0)throw Error("The image file is empty.");if(b>xW)throw Error("Image assets must be 5MB or smaller.")}function hM(b){let w=kM(b.filename)??uW(b.explicitContentType)??uW(b.dataUrlContentType);if(!w||!vM.has(w))throw Error("Unsupported image type. Use PNG, JPEG, GIF, or WebP.");return w}function cM(b){let w,$,W;if(b.filePath!==void 0){if(!A0())throw Error("`filePath` is only supported when the MCP server runs locally on your machine. For a remote MCP connection, pass `imageBase64` and `filename` instead.");let G=EM(b.filePath).size;qH(G),w=NM(b.filePath),$=b.filename??TM(b.filePath)}else{if(!b.imageBase64)throw Error("Provide either `filePath` or `imageBase64` when uploading an image asset.");if(!b.filename)throw Error("`filename` is required with `imageBase64` when uploading an image asset.");let G=yM(b.imageBase64);w=G.bytes,W=G.dataUrlContentType,$=b.filename,qH(w.byteLength)}let Q=hM({filename:$,explicitContentType:b.contentType,dataUrlContentType:W});return{bytes:w,filename:$,contentType:Q,altText:b.altText??CM($)}}async function JH(b){let w=cM(b),$=w.bytes.byteLength,W=await z("POST","/api/v1/media/upload-url",{filename:w.filename,contentType:w.contentType,fileSizeBytes:$},b.companyId);return await w9(W.uploadUrl,w.bytes,w.contentType,b.companyId),(await z("POST","/api/v1/media/complete-upload",{key:W.key,filename:W.fileName,contentType:w.contentType,fileSizeBytes:$,...b.sourceWidth!==void 0&&{width:b.sourceWidth},...b.sourceHeight!==void 0&&{height:b.sourceHeight},altText:w.altText},b.companyId)).asset}var fM={type:"boolean",description:"Whether the Sequenzy operation succeeded."},nM={type:"string",description:"Human-readable status, confirmation, or next-step message."},iM={type:"string",description:"Additional context about the result."};function p(b){return{type:"object",description:b,additionalProperties:!0}}function mM(b){return{type:"array",description:b,items:p("One item in the returned collection.")}}function V(b){return{type:"string",description:b}}function Mb(b){return{type:"number",description:b}}function Rb(b){return{type:"boolean",description:b}}function F(b){return p(`The ${b} record returned by Sequenzy.`)}function i(b){return mM(`List of ${b} records returned by Sequenzy.`)}var lM={appUrls:p("Dashboard URLs for relevant Sequenzy resources."),url:V("Primary dashboard URL for this result."),settingsUrl:V("Company settings URL when available.")},gM={success:fM,message:nM,note:iM,warnings:{type:"array",description:"Non-fatal cautions about content, permissions, or follow-up actions.",items:V("One warning.")},items:{type:"array",description:"Fallback array wrapper used only when a tool returns a bare array.",items:p("One returned item.")},value:p("Fallback object wrapper used only when a tool returns a non-object value.")},pM={get_account:{account:F("account"),companies:i("company"),apiKeyPermissions:p("Current API key preset and scopes, whether common marketing work is discoverable, any missing marketing read scopes, and the API Keys management URL."),currentCompanyId:V("Company ID selected by the authenticated API key, when available."),selectedCompanyId:V("Company ID selected locally for subsequent MCP calls, when available.")},select_company:{companyId:V("Selected company ID."),companyName:V("Selected company name.")},get_app_urls:{dashboard:V("Company dashboard URL."),settings:V("Company settings URL."),campaign:V("Campaign editor URL."),landingPage:V("Landing page editor URL."),sequence:V("Sequence editor URL."),email:V("Email editor URL."),transactionalEmail:V("Transactional email URL."),emailSend:V("Sent email detail URL."),domain:V("Sending domain settings URL."),urls:p("All generated URLs keyed by resource type.")},create_company:{company:F("company"),autoSelected:Rb("Whether the new company was selected for subsequent MCP calls.")},update_company:{company:F("company")},get_company:{company:F("company")},get_sync_rules:{syncRules:{type:"array",description:"Effective sync rules for the company.",items:p("One sync rule.")},isDefault:Rb("Whether the company uses the inherited SaaS/ecommerce platform preset.")},update_sync_rules:{syncRules:{type:"array",description:"Effective sync rules after the update.",items:p("One sync rule.")},isDefault:Rb("Whether the company now uses the inherited SaaS/ecommerce platform preset.")},get_shopify_automation_settings:{browseAbandonment:p("Effective browse-abandonment settings (defaults applied)."),priceDrop:p("Effective price-drop settings (defaults applied)."),shopDomain:V("Connected Shopify store domain.")},update_shopify_automation_settings:{browseAbandonment:p("Effective browse-abandonment settings after the update."),priceDrop:p("Effective price-drop settings after the update."),shopDomain:V("Connected Shopify store domain.")},create_api_key:{apiKey:p("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:V("Newly created API key if the API response uses the short key field.")},list_api_keys:{apiKeys:i("non-secret API key metadata, including ID, name, prefix, permissions, timestamps, and active-credential status")},revoke_api_key:{apiKey:F("revoked non-secret API key metadata")},delete_api_key:{apiKey:F("deleted non-secret API key metadata")},list_websites:{websites:i("sender website")},add_website:{website:F("Sending domain with the SPF, DKIM, MAIL FROM, and inbound DNS records required for setup.")},add_sending_domain:{website:F("Sending domain with the SPF, DKIM, MAIL FROM, and inbound DNS records required for setup.")},check_website:{website:F("sender website"),ready:Rb("Whether the sender website is ready."),status:V("Current processing or verification status.")},verify_sending_domain:{website:F("Sending domain with current aggregate, SPF, DKIM, and MAIL FROM verification details."),verified:Rb("Whether the sending domain passed the fresh verification check."),message:V("Verification result summary.")},get_integration_guide:{guide:F("integration guide"),code:V("Generated integration code or example."),steps:{type:"array",description:"Setup steps for the requested integration.",items:p("One setup step.")}},add_subscriber:{subscriber:F("subscriber")},create_subscriber_import:{import:F("subscriber import")},get_subscriber_import:{import:F("subscriber import")},update_subscriber:{subscriber:F("subscriber")},remove_subscriber:{subscriber:F("subscriber"),hardDeleted:Rb("Whether the subscriber was permanently deleted.")},get_subscriber:{subscriber:F("subscriber")},list_subscriber_notes:{notes:i("subscriber note")},add_subscriber_note:{note:F("subscriber note")},delete_subscriber_note:{id:V("Deleted subscriber note ID."),deleted:Rb("Whether the subscriber note was deleted.")},search_subscribers:{subscribers:i("subscriber"),pagination:p("Pagination metadata."),returned:Mb("Number of subscribers returned."),truncated:Rb("Whether the result was truncated by the requested limit.")},list_products:{products:i("product")},upsert_products:{products:i("product"),created:Mb("Number of products created."),updated:Mb("Number of products updated.")},delete_product:{productId:V("Deleted product ID.")},attach_product_file:{product:F("product"),delivery:F("digital delivery file")},remove_product_file:{product:F("product")},upload_image_asset:{asset:F("hosted image asset"),imageBlock:p("Ready-to-insert Sequenzy image block using the hosted asset URL.")},sync_products:{job:F("product sync job"),jobId:V("Queued product sync job ID.")},list_tags:{tags:i("tag")},create_tag:{tag:F("tag")},update_tag:{tag:F("tag")},delete_tag:{tagId:V("Deleted tag ID.")},list_lists:{lists:i("list")},create_list:{list:F("list")},update_list:{list:F("list")},delete_list:{listId:V("Deleted list ID.")},add_subscribers_to_list:{list:F("list"),added:Mb("Number of subscribers added to the list."),skipped:Mb("Number of subscribers skipped.")},remove_subscribers_from_list:{list:F("list"),removed:Mb("Number of subscribers removed from the list."),skipped:Mb("Number of subscribers skipped.")},list_segments:{segments:i("segment")},create_segment:{segment:F("segment")},update_segment:{segment:F("segment")},delete_segment:{segmentId:V("Deleted segment ID.")},get_segment_count:{count:Mb("Number of subscribers matching the segment."),segmentId:V("Segment ID that was counted.")},list_audience_syncs:{audienceSyncs:i("audience sync")},list_ad_accounts:{adAccounts:i("ad account")},create_audience_sync:{audienceSync:F("audience sync")},update_audience_sync:{audienceSync:F("audience sync")},delete_audience_sync:{audienceSyncId:V("Deleted audience sync ID.")},sync_audience_now:{audienceSync:F("audience sync"),job:F("audience sync job"),jobId:V("Queued audience sync job ID.")},list_templates:{templates:i("email template")},get_template:{template:F("email template")},create_template:{template:F("email template")},update_template:{template:F("email template")},set_template_localization:{templateId:V("Localized template ID."),localization:F("template localization")},sync_template_localizations:{templateId:V("Template ID queued for localization."),queuedLocales:{type:"array",description:"Locale codes queued for AI translation.",items:V("One queued locale code.")},queuedVariantCount:Mb("Number of localized variants queued for translation.")},delete_template:{templateId:V("Deleted template ID.")},list_ab_tests:{abTests:i("A/B test")},get_ab_test:{abTest:F("A/B test")},get_ab_test_stats:{abTest:F("A/B test"),stats:F("A/B test statistics")},restart_ab_test:{abTest:F("A/B test")},update_ab_test_variant:{abTest:F("A/B test"),variant:F("A/B test variant")},create_ab_test:{abTest:F("A/B test")},add_ab_test_variant:{abTest:F("A/B test"),variant:F("A/B test variant")},delete_ab_test_variant:{abTest:F("A/B test"),variantId:V("Deleted A/B test variant ID.")},delete_ab_test:{abTestId:V("Deleted A/B test ID.")},list_campaigns:{campaigns:i("campaign")},get_campaign:{campaign:F("campaign")},get_email_send:{emailSend:F("email send"),events:i("email delivery event")},get_recipient_suppression:{suppression:F("recipient suppression status")},remove_recipient_suppression:{removed:Rb("Whether stale bounce suppression was removed."),removedLocalBounce:Rb("Whether the platform-local bounce block was removed."),removedSesRegions:{type:"array",description:"AWS SES regions where a bounce suppression was removed.",items:V("One AWS SES region.")},remainingSuppression:F("recipient suppression status after cleanup")},create_campaign:{campaign:F("campaign")},update_campaign:{campaign:F("campaign")},schedule_campaign:{campaign:F("campaign"),scheduledAt:V("Scheduled send timestamp.")},send_test_email:{emailSendId:V("Durable test email delivery ID."),recipientEmail:V("Test email recipient.")},send_test_sms:{smsSendId:V("Created test SMS send ID."),toPhone:V("Normalized E.164 destination phone.")},cancel_campaign:{campaign:F("campaign")},pause_campaign:{campaign:F("campaign")},resume_campaign:{campaign:F("campaign")},delete_campaign:{campaignId:V("Deleted campaign ID.")},duplicate_campaign:{campaign:F("duplicated campaign")},resend_campaign_to_non_openers:{campaign:F("non-opener resend draft campaign"),estimatedNonOpenerCount:Mb("Estimated number of subscribers who haven't opened the original campaign.")},list_forms:{forms:i("saved form")},create_form:{form:F("saved form"),embed:p("Public action URL plus JavaScript, native form, and fetch snippets.")},get_form_embed:{form:F("saved form"),embed:p("Public action URL plus JavaScript, native form, and fetch snippets.")},list_landing_pages:{landingPages:i("landing page")},get_landing_page:{landingPage:F("landing page")},create_landing_page:{landingPage:F("landing page")},update_landing_page:{landingPage:F("landing page")},delete_landing_page:{landingPageId:V("Deleted landing page ID.")},publish_landing_page:{landingPage:F("landing page")},unpublish_landing_page:{landingPage:F("landing page")},connect_landing_page_domain:{landingPage:F("landing page"),domain:V("Connected landing page domain.")},update_landing_page_domain_settings:{landingPage:F("landing page"),domain:V("Landing page domain.")},list_sequences:{sequences:i("sequence")},get_sequence:{sequence:F("sequence")},create_sequence:{sequence:F("sequence"),eventTrackingCode:V("Ready-to-adapt code for sending a custom trigger event, including any matching-field property."),eventTracking:p("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:V("One required event name.")}},update_sequence:{sequence:F("sequence")},update_sequence_node:{sequence:F("sequence")},update_sequence_nodes:{sequence:F("sequence")},edit_sequence_graph:{sequence:F("sequence")},insert_sequence_step:{sequence:F("sequence"),insertedNodeIds:{type:"array",description:"Node IDs created for a linear inserted step, including any delay or wait-for-event node.",items:V("Inserted automation node ID.")},insertedEmailIds:{type:"array",description:"Email template IDs created for the inserted step.",items:V("Inserted email template ID.")},insertedEmailCount:Mb("Number of email steps inserted."),addedBranchNodeId:V("New logic_branch node ID when the inserted step is a branch."),addedBranchPathNodeIds:p("Created path node IDs keyed by branch ID, plus else. Directly wired paths have empty arrays.")},enable_sequence:{sequence:F("sequence")},disable_sequence:{sequence:F("sequence")},duplicate_sequence:{sequence:F("sequence"),nodes:i("sequence node"),edges:i("sequence edge")},archive_sequence:{sequence:F("sequence")},unarchive_sequence:{sequence:F("sequence")},list_sequence_goals:{goals:i("sequence goal")},create_sequence_goal:{goal:F("sequence goal")},update_sequence_goal:{goal:F("sequence goal")},delete_sequence_goal:{goalId:V("Deleted sequence goal ID.")},get_sequence_inbound_webhook:{webhook:F("sequence inbound webhook")},configure_sequence_inbound_webhook:{webhook:F("sequence inbound webhook")},rotate_sequence_inbound_webhook_secret:{webhook:F("sequence inbound webhook")},pause_sequence_enrollments:{sequenceId:V("Sequence ID."),enrollmentPaused:Rb("Whether new sequence enrollments are paused.")},resume_sequence_enrollments:{sequenceId:V("Sequence ID."),enrollmentPaused:Rb("Whether new sequence enrollments are paused.")},enroll_subscribers_in_sequence:{sequence:F("sequence"),enrollments:i("sequence enrollment"),enrolled:Mb("Number of subscribers enrolled."),skipped:Mb("Number of subscribers skipped.")},cancel_sequence_enrollments:{sequence:F("sequence"),cancelled:Mb("Number of enrollments cancelled."),skipped:Mb("Number of enrollments skipped.")},delete_sequence:{sequenceId:V("Deleted sequence ID.")},list_transactional_emails:{transactional:i("transactional email")},get_transactional_email:{transactional:F("transactional email")},create_transactional_email:{transactional:F("transactional email")},update_transactional_email:{transactional:F("transactional email")},send_email:{emailSendId:V("Durable transactional delivery ID."),transactional:F("transactional email")},get_stats:{stats:F("account or company statistics")},get_campaign_stats:{campaign:F("campaign"),stats:F("campaign statistics"),clickedLinks:{type:"array",description:"Per-link click breakdown, most clicked first (top 20). Each entry has url, clicks, and percentage (that link's share of every recorded link click). Present only when the campaign has tracked link clicks.",items:p("One clicked link with url/clicks/share.")},polls:{type:"array",description:`Poll and NPS summaries. Each subscriber counts once per campaign poll block using their latest answer to that block; NPS entries include score, average, and promoter/passive/detractor counts. To list the exact historical respondents behind a count, use the summary blockId and the get_campaign_stats campaignId with create_segment. ${Rw} A summary's attributeKey identifies the subscriber attribute that stores their current/latest response and may be overwritten by a later poll that reuses the key.`,items:p("One poll or NPS results summary.")}},get_sequence_stats:{sequence:F("sequence"),stats:F("sequence statistics")},list_campaign_events:{events:i("campaign email event"),pagination:p("Pagination metadata.")},list_sequence_events:{events:i("sequence email event"),pagination:p("Pagination metadata.")},get_subscriber_activity:{activity:i("subscriber activity event"),subscribers:i("subscriber"),pagination:p("Pagination metadata.")},list_team_members:{members:i("team member"),invitations:i("team invitation")},invite_team_member:{invitation:F("team invitation")},cancel_team_invitation:{invitationId:V("Cancelled invitation ID.")},list_conversations:{conversations:i("inbox conversation"),pagination:p("Pagination metadata.")},get_conversation:{conversation:F("inbox conversation"),messages:i("conversation message")},reply_to_conversation:{conversation:F("inbox conversation"),message:F("conversation message")},update_conversation_status:{conversation:F("inbox conversation")},mark_conversation_read:{conversation:F("inbox conversation")},list_webhooks:{webhooks:i("outbound webhook")},create_webhook:{webhook:F("outbound webhook")},update_webhook:{webhook:F("outbound webhook")},delete_webhook:{webhookId:V("Deleted outbound webhook ID.")},test_webhook:{webhook:F("outbound webhook"),delivery:F("test webhook delivery")},list_webhook_deliveries:{deliveries:i("webhook delivery")},replay_webhook_delivery:{delivery:F("webhook delivery"),job:F("webhook replay job")},generate_email:{email:F("generated email"),html:V("Generated HTML email body."),blocks:{type:"array",description:"Generated Sequenzy email blocks, wrapped with company branding (logo + footer) unless applyBranding was false.",items:p("One generated email block.")},subject:V("Generated subject line."),previewText:V("Generated inbox preview text.")},generate_sequence:{sequence:F("persisted AI-generated sequence draft"),deprecated:Rb("Always true for this deprecated alias."),deprecationMessage:V("Migration guidance directing callers to create_sequence.")},generate_subject_lines:{subjectLines:{type:"array",description:"Generated subject line variants.",items:V("One generated subject line.")},variants:i("generated subject line variant")},generate_sms:{prompt:V("The prompt the messages were generated for."),messages:{type:"array",description:"Generated SMS message variants with encoding and segment counts.",items:p("One generated SMS message.")}},get_sms_settings:{sms:p("SMS add-on status: enabled, planEligible, creditsBalance, brandPrefix, numbers, readyToSend (paid plan or credits plus an active number).")},submit_feedback:{}};function oM(b){let w=pM[b];if(w===void 0)throw Error(`MCP tool "${b}" must define outputSchema properties.`);return{type:"object",description:`Structured content returned by the \`${b}\` MCP tool.`,properties:{...gM,...w,...CW.has(b)?lM:{}},additionalProperties:!0}}function DH(b){return{...b,outputSchema:oM(b.name)}}function HH(b){if(k(b))return b;if(Array.isArray(b))return{items:b};return{value:b}}var zH=[{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:pb},required:["abTestId"]}},{name:"restart_ab_test",description:"Run another sequence A/B test after a winner is selected. By default the winner becomes the new control; pass sourceVariantId to use another variant as the control email.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID to restart"},sourceVariantId:{type:"string",description:"Optional variant ID to use as the new control email. Defaults to the selected winner."},testType:{type:"string",description:"Optional test type: subject or content."},winnerThreshold:{type:"number",description:"Optional number of subscribers before selecting a winner. Must be from 10 to 1000."},variantCount:{type:"number",description:"Optional total variants including the control. Must be from 2 to 4."}},required:["abTestId"],additionalProperties:!1}},{name:"update_ab_test_variant",description:"Update a draft A/B test variant. Provide at least one of subject, previewText, html, or blocks. Use either html or blocks, not both. 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"},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. ${qb}`},blocks:{type:"array",description:`${zw} Mutually exclusive with html.`,items:{type:"object"}},confirmLiveChange:{type:"boolean",description:"Required as true when the A/B test belongs to an active sequence, because the content change immediately affects live rotation."}},required:["abTestId","variantId"],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:"Percentage of the audience used for the test phase, from 5 to 50. Defaults to 20."},testDurationMinutes:{type:"number",description:"Test phase duration in minutes before the winner is selected, from 15 to 1440. Defaults to 240."},winnerCriteria:{type:"string",enum:["open_rate","click_rate"],description:"Winner selection criteria. Defaults to open_rate."},testType:{type:"string",enum:["subject","content"],description:"Sequence A/B test type. Subject tests use open_rate; content tests use click_rate. 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:zw,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:zw,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 OH=[{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
|
+
`)}A.write("payload.value = newResult;"),A.write("return payload;");let R=A.compile();return(T,h)=>R(O,T,h)},q,G=vw,X=!U0.jitless,J=X&&q4.value,D=w.catchall,H;b._zod.parse=(O,A)=>{H??(H=W.value);let B=O.value;if(!G(B))return O.issues.push({expected:"object",code:"invalid_type",input:B,inst:b}),O;if(X&&J&&A?.async===!1&&A.jitless!==!0){if(!q)q=Q(w.shape);if(O=q(O,A),!D)return O;return r9([],B,O,A,H,b)}return $(O,A)}});function z9(b,w,$,W){for(let q of b)if(q.issues.length===0)return w.value=q.value,w;let Q=b.filter((q)=>!Kw(q));if(Q.length===1)return w.value=Q[0].value,Q[0];return w.issues.push({code:"invalid_union",input:w.value,inst:$,errors:b.map((q)=>q.issues.map((G)=>hb(G,W,vb())))}),w}var P4=P("$ZodUnion",(b,w)=>{e.init(b,w),d(b._zod,"optin",()=>w.options.some((Q)=>Q._zod.optin==="optional")?"optional":void 0),d(b._zod,"optout",()=>w.options.some((Q)=>Q._zod.optout==="optional")?"optional":void 0),d(b._zod,"values",()=>{if(w.options.every((Q)=>Q._zod.values))return new Set(w.options.flatMap((Q)=>Array.from(Q._zod.values)));return}),d(b._zod,"pattern",()=>{if(w.options.every((Q)=>Q._zod.pattern)){let Q=w.options.map((q)=>q._zod.pattern);return new RegExp(`^(${Q.map((q)=>P1(q.source)).join("|")})$`)}return});let $=w.options.length===1,W=w.options[0]._zod.run;b._zod.parse=(Q,q)=>{if($)return W(Q,q);let G=!1,X=[];for(let Y of w.options){let J=Y._zod.run({value:Q.value,issues:[]},q);if(J instanceof Promise)X.push(J),G=!0;else{if(J.issues.length===0)return J;X.push(J)}}if(!G)return z9(X,Q,b,q);return Promise.all(X).then((Y)=>{return z9(Y,Q,b,q)})}}),s9=P("$ZodDiscriminatedUnion",(b,w)=>{P4.init(b,w);let $=b._zod.parse;d(b._zod,"propValues",()=>{let Q={};for(let q of w.options){let G=q._zod.propValues;if(!G||Object.keys(G).length===0)throw Error(`Invalid discriminated union option at index "${w.options.indexOf(q)}"`);for(let[X,Y]of Object.entries(G)){if(!Q[X])Q[X]=new Set;for(let J of Y)Q[X].add(J)}}return Q});let W=nw(()=>{let Q=w.options,q=new Map;for(let G of Q){let X=G._zod.propValues?.[w.discriminator];if(!X||X.size===0)throw Error(`Invalid discriminated union option at index "${w.options.indexOf(G)}"`);for(let Y of X){if(q.has(Y))throw Error(`Duplicate discriminator value "${String(Y)}"`);q.set(Y,G)}}return q});b._zod.parse=(Q,q)=>{let G=Q.value;if(!vw(G))return Q.issues.push({code:"invalid_type",expected:"object",input:G,inst:b}),Q;let X=W.value.get(G?.[w.discriminator]);if(X)return X._zod.run(Q,q);if(w.unionFallback)return $(Q,q);return Q.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:w.discriminator,input:G,path:[w.discriminator],inst:b}),Q}}),a9=P("$ZodIntersection",(b,w)=>{e.init(b,w),b._zod.parse=($,W)=>{let Q=$.value,q=w.left._zod.run({value:Q,issues:[]},W),G=w.right._zod.run({value:Q,issues:[]},W);if(q instanceof Promise||G instanceof Promise)return Promise.all([q,G]).then(([Y,J])=>{return O9($,Y,J)});return O9($,q,G)}});function L4(b,w){if(b===w)return{valid:!0,data:b};if(b instanceof Date&&w instanceof Date&&+b===+w)return{valid:!0,data:b};if(Fw(b)&&Fw(w)){let $=Object.keys(w),W=Object.keys(b).filter((q)=>$.indexOf(q)!==-1),Q={...b,...w};for(let q of W){let G=L4(b[q],w[q]);if(!G.valid)return{valid:!1,mergeErrorPath:[q,...G.mergeErrorPath]};Q[q]=G.data}return{valid:!0,data:Q}}if(Array.isArray(b)&&Array.isArray(w)){if(b.length!==w.length)return{valid:!1,mergeErrorPath:[]};let $=[];for(let W=0;W<b.length;W++){let Q=b[W],q=w[W],G=L4(Q,q);if(!G.valid)return{valid:!1,mergeErrorPath:[W,...G.mergeErrorPath]};$.push(G.data)}return{valid:!0,data:$}}return{valid:!1,mergeErrorPath:[]}}function O9(b,w,$){if(w.issues.length)b.issues.push(...w.issues);if($.issues.length)b.issues.push(...$.issues);if(Kw(b))return b;let W=L4(w.value,$.value);if(!W.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(W.mergeErrorPath)}`);return b.value=W.data,b}var b8=P("$ZodRecord",(b,w)=>{e.init(b,w),b._zod.parse=($,W)=>{let Q=$.value;if(!Fw(Q))return $.issues.push({expected:"record",code:"invalid_type",input:Q,inst:b}),$;let q=[];if(w.keyType._zod.values){let G=w.keyType._zod.values;$.value={};for(let Y of G)if(typeof Y==="string"||typeof Y==="number"||typeof Y==="symbol"){let J=w.valueType._zod.run({value:Q[Y],issues:[]},W);if(J instanceof Promise)q.push(J.then((D)=>{if(D.issues.length)$.issues.push(...Ww(Y,D.issues));$.value[Y]=D.value}));else{if(J.issues.length)$.issues.push(...Ww(Y,J.issues));$.value[Y]=J.value}}let X;for(let Y in Q)if(!G.has(Y))X=X??[],X.push(Y);if(X&&X.length>0)$.issues.push({code:"unrecognized_keys",input:Q,inst:b,keys:X})}else{$.value={};for(let G of Reflect.ownKeys(Q)){if(G==="__proto__")continue;let X=w.keyType._zod.run({value:G,issues:[]},W);if(X instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(X.issues.length){$.issues.push({code:"invalid_key",origin:"record",issues:X.issues.map((J)=>hb(J,W,vb())),input:G,path:[G],inst:b}),$.value[X.value]=X.value;continue}let Y=w.valueType._zod.run({value:Q[G],issues:[]},W);if(Y instanceof Promise)q.push(Y.then((J)=>{if(J.issues.length)$.issues.push(...Ww(G,J.issues));$.value[X.value]=J.value}));else{if(Y.issues.length)$.issues.push(...Ww(G,Y.issues));$.value[X.value]=Y.value}}}if(q.length)return Promise.all(q).then(()=>$);return $}});var w8=P("$ZodEnum",(b,w)=>{e.init(b,w);let $=W4(w.entries),W=new Set($);b._zod.values=W,b._zod.pattern=new RegExp(`^(${$.filter((Q)=>G4.has(typeof Q)).map((Q)=>typeof Q==="string"?$w(Q):Q.toString()).join("|")})$`),b._zod.parse=(Q,q)=>{let G=Q.value;if(W.has(G))return Q;return Q.issues.push({code:"invalid_value",values:$,input:G,inst:b}),Q}}),$8=P("$ZodLiteral",(b,w)=>{if(e.init(b,w),w.values.length===0)throw Error("Cannot create literal schema with no valid values");b._zod.values=new Set(w.values),b._zod.pattern=new RegExp(`^(${w.values.map(($)=>typeof $==="string"?$w($):$?$w($.toString()):String($)).join("|")})$`),b._zod.parse=($,W)=>{let Q=$.value;if(b._zod.values.has(Q))return $;return $.issues.push({code:"invalid_value",values:w.values,input:Q,inst:b}),$}});var W8=P("$ZodTransform",(b,w)=>{e.init(b,w),b._zod.parse=($,W)=>{if(W.direction==="backward")throw new A1(b.constructor.name);let Q=w.transform($.value,$);if(W.async)return(Q instanceof Promise?Q:Promise.resolve(Q)).then((G)=>{return $.value=G,$});if(Q instanceof Promise)throw new ww;return $.value=Q,$}});function A9(b,w){if(b.issues.length&&w===void 0)return{issues:[],value:void 0};return b}var Q8=P("$ZodOptional",(b,w)=>{e.init(b,w),b._zod.optin="optional",b._zod.optout="optional",d(b._zod,"values",()=>{return w.innerType._zod.values?new Set([...w.innerType._zod.values,void 0]):void 0}),d(b._zod,"pattern",()=>{let $=w.innerType._zod.pattern;return $?new RegExp(`^(${P1($.source)})?$`):void 0}),b._zod.parse=($,W)=>{if(w.innerType._zod.optin==="optional"){let Q=w.innerType._zod.run($,W);if(Q instanceof Promise)return Q.then((q)=>A9(q,$.value));return A9(Q,$.value)}if($.value===void 0)return $;return w.innerType._zod.run($,W)}}),q8=P("$ZodNullable",(b,w)=>{e.init(b,w),d(b._zod,"optin",()=>w.innerType._zod.optin),d(b._zod,"optout",()=>w.innerType._zod.optout),d(b._zod,"pattern",()=>{let $=w.innerType._zod.pattern;return $?new RegExp(`^(${P1($.source)}|null)$`):void 0}),d(b._zod,"values",()=>{return w.innerType._zod.values?new Set([...w.innerType._zod.values,null]):void 0}),b._zod.parse=($,W)=>{if($.value===null)return $;return w.innerType._zod.run($,W)}}),G8=P("$ZodDefault",(b,w)=>{e.init(b,w),b._zod.optin="optional",d(b._zod,"values",()=>w.innerType._zod.values),b._zod.parse=($,W)=>{if(W.direction==="backward")return w.innerType._zod.run($,W);if($.value===void 0)return $.value=w.defaultValue,$;let Q=w.innerType._zod.run($,W);if(Q instanceof Promise)return Q.then((q)=>L9(q,w));return L9(Q,w)}});function L9(b,w){if(b.value===void 0)b.value=w.defaultValue;return b}var X8=P("$ZodPrefault",(b,w)=>{e.init(b,w),b._zod.optin="optional",d(b._zod,"values",()=>w.innerType._zod.values),b._zod.parse=($,W)=>{if(W.direction==="backward")return w.innerType._zod.run($,W);if($.value===void 0)$.value=w.defaultValue;return w.innerType._zod.run($,W)}}),Y8=P("$ZodNonOptional",(b,w)=>{e.init(b,w),d(b._zod,"values",()=>{let $=w.innerType._zod.values;return $?new Set([...$].filter((W)=>W!==void 0)):void 0}),b._zod.parse=($,W)=>{let Q=w.innerType._zod.run($,W);if(Q instanceof Promise)return Q.then((q)=>U9(q,b));return U9(Q,b)}});function U9(b,w){if(!b.issues.length&&b.value===void 0)b.issues.push({code:"invalid_type",expected:"nonoptional",input:b.value,inst:w});return b}var J8=P("$ZodCatch",(b,w)=>{e.init(b,w),d(b._zod,"optin",()=>w.innerType._zod.optin),d(b._zod,"optout",()=>w.innerType._zod.optout),d(b._zod,"values",()=>w.innerType._zod.values),b._zod.parse=($,W)=>{if(W.direction==="backward")return w.innerType._zod.run($,W);let Q=w.innerType._zod.run($,W);if(Q instanceof Promise)return Q.then((q)=>{if($.value=q.value,q.issues.length)$.value=w.catchValue({...$,error:{issues:q.issues.map((G)=>hb(G,W,vb()))},input:$.value}),$.issues=[];return $});if($.value=Q.value,Q.issues.length)$.value=w.catchValue({...$,error:{issues:Q.issues.map((q)=>hb(q,W,vb()))},input:$.value}),$.issues=[];return $}});var D8=P("$ZodPipe",(b,w)=>{e.init(b,w),d(b._zod,"values",()=>w.in._zod.values),d(b._zod,"optin",()=>w.in._zod.optin),d(b._zod,"optout",()=>w.out._zod.optout),d(b._zod,"propValues",()=>w.in._zod.propValues),b._zod.parse=($,W)=>{if(W.direction==="backward"){let q=w.out._zod.run($,W);if(q instanceof Promise)return q.then((G)=>V0(G,w.in,W));return V0(q,w.in,W)}let Q=w.in._zod.run($,W);if(Q instanceof Promise)return Q.then((q)=>V0(q,w.out,W));return V0(Q,w.out,W)}});function V0(b,w,$){if(b.issues.length)return b.aborted=!0,b;return w._zod.run({value:b.value,issues:b.issues},$)}var H8=P("$ZodReadonly",(b,w)=>{e.init(b,w),d(b._zod,"propValues",()=>w.innerType._zod.propValues),d(b._zod,"values",()=>w.innerType._zod.values),d(b._zod,"optin",()=>w.innerType._zod.optin),d(b._zod,"optout",()=>w.innerType._zod.optout),b._zod.parse=($,W)=>{if(W.direction==="backward")return w.innerType._zod.run($,W);let Q=w.innerType._zod.run($,W);if(Q instanceof Promise)return Q.then(P9);return P9(Q)}});function P9(b){return b.value=Object.freeze(b.value),b}var z8=P("$ZodCustom",(b,w)=>{Hb.init(b,w),e.init(b,w),b._zod.parse=($,W)=>{return $},b._zod.check=($)=>{let W=$.value,Q=w.fn(W);if(Q instanceof Promise)return Q.then((q)=>B9(q,$,W,b));B9(Q,$,W,b);return}});function B9(b,w,$,W){if(!b){let Q={code:"custom",input:$,inst:W,path:[...W._zod.def.path??[]],continue:!W._zod.def.abort};if(W._zod.def.params)Q.params=W._zod.def.params;w.issues.push(iw(Q))}}var az=(b)=>{let w=typeof b;switch(w){case"number":return Number.isNaN(b)?"NaN":"number";case"object":{if(Array.isArray(b))return"array";if(b===null)return"null";if(Object.getPrototypeOf(b)!==Object.prototype&&b.constructor)return b.constructor.name}}return w},bO=()=>{let b={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function w(W){return b[W]??null}let $={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return(W)=>{switch(W.code){case"invalid_type":return`Invalid input: expected ${W.expected}, received ${az(W.input)}`;case"invalid_value":if(W.values.length===1)return`Invalid input: expected ${K0(W.values[0])}`;return`Invalid option: expected one of ${P0(W.values,"|")}`;case"too_big":{let Q=W.inclusive?"<=":"<",q=w(W.origin);if(q)return`Too big: expected ${W.origin??"value"} to have ${Q}${W.maximum.toString()} ${q.unit??"elements"}`;return`Too big: expected ${W.origin??"value"} to be ${Q}${W.maximum.toString()}`}case"too_small":{let Q=W.inclusive?">=":">",q=w(W.origin);if(q)return`Too small: expected ${W.origin} to have ${Q}${W.minimum.toString()} ${q.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":""}: ${P0(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 B4(){return{localeError:bO()}}var KI=Symbol("ZodOutput"),MI=Symbol("ZodInput");class O8{constructor(){this._map=new WeakMap,this._idmap=new Map}add(b,...w){let $=w[0];if(this._map.set(b,$),$&&typeof $==="object"&&"id"in $){if(this._idmap.has($.id))throw Error(`ID ${$.id} already exists in the registry`);this._idmap.set($.id,b)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(b){let w=this._map.get(b);if(w&&typeof w==="object"&&"id"in w)this._idmap.delete(w.id);return this._map.delete(b),this}get(b){let w=b._zod.parent;if(w){let $={...this.get(w)??{}};delete $.id;let W={...$,...this._map.get(b)};return Object.keys(W).length?W:void 0}return this._map.get(b)}has(b){return this._map.has(b)}}function wO(){return new O8}var _1=wO();function A8(b,w){return new b({type:"string",...S(w)})}function L8(b,w){return new b({type:"string",format:"email",check:"string_format",abort:!1,...S(w)})}function F4(b,w){return new b({type:"string",format:"guid",check:"string_format",abort:!1,...S(w)})}function U8(b,w){return new b({type:"string",format:"uuid",check:"string_format",abort:!1,...S(w)})}function P8(b,w){return new b({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...S(w)})}function B8(b,w){return new b({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...S(w)})}function F8(b,w){return new b({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...S(w)})}function K8(b,w){return new b({type:"string",format:"url",check:"string_format",abort:!1,...S(w)})}function M8(b,w){return new b({type:"string",format:"emoji",check:"string_format",abort:!1,...S(w)})}function I8(b,w){return new b({type:"string",format:"nanoid",check:"string_format",abort:!1,...S(w)})}function _8(b,w){return new b({type:"string",format:"cuid",check:"string_format",abort:!1,...S(w)})}function j8(b,w){return new b({type:"string",format:"cuid2",check:"string_format",abort:!1,...S(w)})}function Z8(b,w){return new b({type:"string",format:"ulid",check:"string_format",abort:!1,...S(w)})}function V8(b,w){return new b({type:"string",format:"xid",check:"string_format",abort:!1,...S(w)})}function N8(b,w){return new b({type:"string",format:"ksuid",check:"string_format",abort:!1,...S(w)})}function E8(b,w){return new b({type:"string",format:"ipv4",check:"string_format",abort:!1,...S(w)})}function T8(b,w){return new b({type:"string",format:"ipv6",check:"string_format",abort:!1,...S(w)})}function S8(b,w){return new b({type:"string",format:"cidrv4",check:"string_format",abort:!1,...S(w)})}function R8(b,w){return new b({type:"string",format:"cidrv6",check:"string_format",abort:!1,...S(w)})}function v8(b,w){return new b({type:"string",format:"base64",check:"string_format",abort:!1,...S(w)})}function k8(b,w){return new b({type:"string",format:"base64url",check:"string_format",abort:!1,...S(w)})}function C8(b,w){return new b({type:"string",format:"e164",check:"string_format",abort:!1,...S(w)})}function u8(b,w){return new b({type:"string",format:"jwt",check:"string_format",abort:!1,...S(w)})}function x8(b,w){return new b({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...S(w)})}function y8(b,w){return new b({type:"string",format:"date",check:"string_format",...S(w)})}function h8(b,w){return new b({type:"string",format:"time",check:"string_format",precision:null,...S(w)})}function c8(b,w){return new b({type:"string",format:"duration",check:"string_format",...S(w)})}function f8(b,w){return new b({type:"number",checks:[],...S(w)})}function n8(b,w){return new b({type:"number",check:"number_format",abort:!1,format:"safeint",...S(w)})}function i8(b,w){return new b({type:"boolean",...S(w)})}function m8(b,w){return new b({type:"null",...S(w)})}function l8(b){return new b({type:"unknown"})}function g8(b,w){return new b({type:"never",...S(w)})}function T0(b,w){return new z4({check:"less_than",...S(w),value:b,inclusive:!1})}function j1(b,w){return new z4({check:"less_than",...S(w),value:b,inclusive:!0})}function S0(b,w){return new O4({check:"greater_than",...S(w),value:b,inclusive:!1})}function Z1(b,w){return new O4({check:"greater_than",...S(w),value:b,inclusive:!0})}function R0(b,w){return new eQ({check:"multiple_of",...S(w),value:b})}function v0(b,w){return new aQ({check:"max_length",...S(w),maximum:b})}function mw(b,w){return new b9({check:"min_length",...S(w),minimum:b})}function k0(b,w){return new w9({check:"length_equals",...S(w),length:b})}function K4(b,w){return new $9({check:"string_format",format:"regex",...S(w),pattern:b})}function M4(b){return new W9({check:"string_format",format:"lowercase",...S(b)})}function I4(b){return new Q9({check:"string_format",format:"uppercase",...S(b)})}function _4(b,w){return new q9({check:"string_format",format:"includes",...S(w),includes:b})}function j4(b,w){return new G9({check:"string_format",format:"starts_with",...S(w),prefix:b})}function Z4(b,w){return new X9({check:"string_format",format:"ends_with",...S(w),suffix:b})}function kw(b){return new Y9({check:"overwrite",tx:b})}function V4(b){return kw((w)=>w.normalize(b))}function N4(){return kw((b)=>b.trim())}function E4(){return kw((b)=>b.toLowerCase())}function T4(){return kw((b)=>b.toUpperCase())}function p8(b,w,$){return new b({type:"array",element:w,...S($)})}function o8(b,w,$){let W=S($);return W.abort??(W.abort=!0),new b({type:"custom",check:"custom",fn:w,...W})}function d8(b,w,$){return new b({type:"custom",check:"custom",fn:w,...S($)})}function t8(b){let w=$O(($)=>{return $.addIssue=(W)=>{if(typeof W==="string")$.issues.push(iw(W,$.value,w._zod.def));else{let Q=W;if(Q.fatal)Q.continue=!1;Q.code??(Q.code="custom"),Q.input??(Q.input=$.value),Q.inst??(Q.inst=w),Q.continue??(Q.continue=!w._zod.def.abort),$.issues.push(iw(Q))}},b($.value,$)});return w}function $O(b,w){let $=new Hb({check:"custom",...S(w)});return $._zod.check=b,$}function lw(b){return!!b._zod}function Mw(b,w){if(lw(b))return K1(b,w);return b.safeParse(w)}function C0(b){if(!b)return;let w;if(lw(b))w=b._zod?.def?.shape;else w=b.shape;if(!w)return;if(typeof w==="function")try{return w()}catch{return}return w}function r8(b){if(lw(b)){let q=b._zod?.def;if(q){if(q.value!==void 0)return q.value;if(Array.isArray(q.values)&&q.values.length>0)return q.values[0]}}let $=b._def;if($){if($.value!==void 0)return $.value;if(Array.isArray($.values)&&$.values.length>0)return $.values[0]}let W=b.value;if(W!==void 0)return W;return}var N1={};pW(N1,{time:()=>v4,duration:()=>k4,datetime:()=>S4,date:()=>R4,ZodISOTime:()=>a8,ZodISODuration:()=>bq,ZodISODateTime:()=>e8,ZodISODate:()=>s8});var e8=P("ZodISODateTime",(b,w)=>{S9.init(b,w),bb.init(b,w)});function S4(b){return x8(e8,b)}var s8=P("ZodISODate",(b,w)=>{R9.init(b,w),bb.init(b,w)});function R4(b){return y8(s8,b)}var a8=P("ZodISOTime",(b,w)=>{v9.init(b,w),bb.init(b,w)});function v4(b){return h8(a8,b)}var bq=P("ZodISODuration",(b,w)=>{k9.init(b,w),bb.init(b,w)});function k4(b){return c8(bq,b)}var wq=(b,w)=>{M0.init(b,w),b.name="ZodError",Object.defineProperties(b,{format:{value:($)=>zQ(b,$)},flatten:{value:($)=>HQ(b,$)},addIssue:{value:($)=>{b.issues.push($),b.message=JSON.stringify(b.issues,fw,2)}},addIssues:{value:($)=>{b.issues.push(...$),b.message=JSON.stringify(b.issues,fw,2)}},isEmpty:{get(){return b.issues.length===0}}})},G_=P("ZodError",wq),Eb=P("ZodError",wq,{Parent:Error});var $q=I0(Eb),Wq=_0(Eb),Qq=F1(Eb),qq=M1(Eb),Gq=OQ(Eb),Xq=AQ(Eb),Yq=LQ(Eb),Jq=UQ(Eb),Dq=PQ(Eb),Hq=BQ(Eb),zq=FQ(Eb),Oq=KQ(Eb);var Qb=P("ZodType",(b,w)=>{return e.init(b,w),b.def=w,b.type=w.type,Object.defineProperty(b,"_def",{value:w}),b.check=(...$)=>{return b.clone(l.mergeDefs(w,{checks:[...w.checks??[],...$.map((W)=>typeof W==="function"?{_zod:{check:W,def:{check:"custom"},onattach:[]}}:W)]}))},b.clone=($,W)=>yb(b,$,W),b.brand=()=>b,b.register=($,W)=>{return $.add(b,W),b},b.parse=($,W)=>$q(b,$,W,{callee:b.parse}),b.safeParse=($,W)=>Qq(b,$,W),b.parseAsync=async($,W)=>Wq(b,$,W,{callee:b.parseAsync}),b.safeParseAsync=async($,W)=>qq(b,$,W),b.spa=b.safeParseAsync,b.encode=($,W)=>Gq(b,$,W),b.decode=($,W)=>Xq(b,$,W),b.encodeAsync=async($,W)=>Yq(b,$,W),b.decodeAsync=async($,W)=>Jq(b,$,W),b.safeEncode=($,W)=>Dq(b,$,W),b.safeDecode=($,W)=>Hq(b,$,W),b.safeEncodeAsync=async($,W)=>zq(b,$,W),b.safeDecodeAsync=async($,W)=>Oq(b,$,W),b.refine=($,W)=>b.check(sO($,W)),b.superRefine=($)=>b.check(aO($)),b.overwrite=($)=>b.check(kw($)),b.optional=()=>Wb(b),b.nullable=()=>Uq(b),b.nullish=()=>Wb(Uq(b)),b.nonoptional=($)=>pO(b,$),b.array=()=>c(b),b.or=($)=>r([b,$]),b.and=($)=>x0(b,$),b.transform=($)=>u4(b,Mq($)),b.default=($)=>mO(b,$),b.prefault=($)=>gO(b,$),b.catch=($)=>dO(b,$),b.pipe=($)=>u4(b,$),b.readonly=()=>eO(b),b.describe=($)=>{let W=b.clone();return _1.add(W,{description:$}),W},Object.defineProperty(b,"description",{get(){return _1.get(b)?.description},configurable:!0}),b.meta=(...$)=>{if($.length===0)return _1.get(b);let W=b.clone();return _1.add(W,$[0]),W},b.isOptional=()=>b.safeParse(void 0).success,b.isNullable=()=>b.safeParse(null).success,b}),Pq=P("_ZodString",(b,w)=>{E0.init(b,w),Qb.init(b,w);let $=b._zod.bag;b.format=$.format??null,b.minLength=$.minimum??null,b.maxLength=$.maximum??null,b.regex=(...W)=>b.check(K4(...W)),b.includes=(...W)=>b.check(_4(...W)),b.startsWith=(...W)=>b.check(j4(...W)),b.endsWith=(...W)=>b.check(Z4(...W)),b.min=(...W)=>b.check(mw(...W)),b.max=(...W)=>b.check(v0(...W)),b.length=(...W)=>b.check(k0(...W)),b.nonempty=(...W)=>b.check(mw(1,...W)),b.lowercase=(W)=>b.check(M4(W)),b.uppercase=(W)=>b.check(I4(W)),b.trim=()=>b.check(N4()),b.normalize=(...W)=>b.check(V4(...W)),b.toLowerCase=()=>b.check(E4()),b.toUpperCase=()=>b.check(T4())}),HO=P("ZodString",(b,w)=>{E0.init(b,w),Pq.init(b,w),b.email=($)=>b.check(L8(zO,$)),b.url=($)=>b.check(K8(OO,$)),b.jwt=($)=>b.check(u8(EO,$)),b.emoji=($)=>b.check(M8(AO,$)),b.guid=($)=>b.check(F4(Aq,$)),b.uuid=($)=>b.check(U8(u0,$)),b.uuidv4=($)=>b.check(P8(u0,$)),b.uuidv6=($)=>b.check(B8(u0,$)),b.uuidv7=($)=>b.check(F8(u0,$)),b.nanoid=($)=>b.check(I8(LO,$)),b.guid=($)=>b.check(F4(Aq,$)),b.cuid=($)=>b.check(_8(UO,$)),b.cuid2=($)=>b.check(j8(PO,$)),b.ulid=($)=>b.check(Z8(BO,$)),b.base64=($)=>b.check(v8(ZO,$)),b.base64url=($)=>b.check(k8(VO,$)),b.xid=($)=>b.check(V8(FO,$)),b.ksuid=($)=>b.check(N8(KO,$)),b.ipv4=($)=>b.check(E8(MO,$)),b.ipv6=($)=>b.check(T8(IO,$)),b.cidrv4=($)=>b.check(S8(_O,$)),b.cidrv6=($)=>b.check(R8(jO,$)),b.e164=($)=>b.check(C8(NO,$)),b.datetime=($)=>b.check(S4($)),b.date=($)=>b.check(R4($)),b.time=($)=>b.check(v4($)),b.duration=($)=>b.check(k4($))});function U(b){return A8(HO,b)}var bb=P("ZodStringFormat",(b,w)=>{s.init(b,w),Pq.init(b,w)}),zO=P("ZodEmail",(b,w)=>{M9.init(b,w),bb.init(b,w)});var Aq=P("ZodGUID",(b,w)=>{F9.init(b,w),bb.init(b,w)});var u0=P("ZodUUID",(b,w)=>{K9.init(b,w),bb.init(b,w)});var OO=P("ZodURL",(b,w)=>{I9.init(b,w),bb.init(b,w)});var AO=P("ZodEmoji",(b,w)=>{_9.init(b,w),bb.init(b,w)});var LO=P("ZodNanoID",(b,w)=>{j9.init(b,w),bb.init(b,w)});var UO=P("ZodCUID",(b,w)=>{Z9.init(b,w),bb.init(b,w)});var PO=P("ZodCUID2",(b,w)=>{V9.init(b,w),bb.init(b,w)});var BO=P("ZodULID",(b,w)=>{N9.init(b,w),bb.init(b,w)});var FO=P("ZodXID",(b,w)=>{E9.init(b,w),bb.init(b,w)});var KO=P("ZodKSUID",(b,w)=>{T9.init(b,w),bb.init(b,w)});var MO=P("ZodIPv4",(b,w)=>{C9.init(b,w),bb.init(b,w)});var IO=P("ZodIPv6",(b,w)=>{u9.init(b,w),bb.init(b,w)});var _O=P("ZodCIDRv4",(b,w)=>{x9.init(b,w),bb.init(b,w)});var jO=P("ZodCIDRv6",(b,w)=>{y9.init(b,w),bb.init(b,w)});var ZO=P("ZodBase64",(b,w)=>{c9.init(b,w),bb.init(b,w)});var VO=P("ZodBase64URL",(b,w)=>{f9.init(b,w),bb.init(b,w)});var NO=P("ZodE164",(b,w)=>{n9.init(b,w),bb.init(b,w)});var EO=P("ZodJWT",(b,w)=>{i9.init(b,w),bb.init(b,w)});var Bq=P("ZodNumber",(b,w)=>{U4.init(b,w),Qb.init(b,w),b.gt=(W,Q)=>b.check(S0(W,Q)),b.gte=(W,Q)=>b.check(Z1(W,Q)),b.min=(W,Q)=>b.check(Z1(W,Q)),b.lt=(W,Q)=>b.check(T0(W,Q)),b.lte=(W,Q)=>b.check(j1(W,Q)),b.max=(W,Q)=>b.check(j1(W,Q)),b.int=(W)=>b.check(Lq(W)),b.safe=(W)=>b.check(Lq(W)),b.positive=(W)=>b.check(S0(0,W)),b.nonnegative=(W)=>b.check(Z1(0,W)),b.negative=(W)=>b.check(T0(0,W)),b.nonpositive=(W)=>b.check(j1(0,W)),b.multipleOf=(W,Q)=>b.check(R0(W,Q)),b.step=(W,Q)=>b.check(R0(W,Q)),b.finite=()=>b;let $=b._zod.bag;b.minValue=Math.max($.minimum??Number.NEGATIVE_INFINITY,$.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,b.maxValue=Math.min($.maximum??Number.POSITIVE_INFINITY,$.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,b.isInt=($.format??"").includes("int")||Number.isSafeInteger($.multipleOf??0.5),b.isFinite=!0,b.format=$.format??null});function o(b){return f8(Bq,b)}var TO=P("ZodNumberFormat",(b,w)=>{m9.init(b,w),Bq.init(b,w)});function Lq(b){return n8(TO,b)}var SO=P("ZodBoolean",(b,w)=>{l9.init(b,w),Qb.init(b,w)});function Db(b){return i8(SO,b)}var RO=P("ZodNull",(b,w)=>{g9.init(b,w),Qb.init(b,w)});function x4(b){return m8(RO,b)}var vO=P("ZodUnknown",(b,w)=>{p9.init(b,w),Qb.init(b,w)});function wb(){return l8(vO)}var kO=P("ZodNever",(b,w)=>{o9.init(b,w),Qb.init(b,w)});function CO(b){return g8(kO,b)}var uO=P("ZodArray",(b,w)=>{d9.init(b,w),Qb.init(b,w),b.element=w.element,b.min=($,W)=>b.check(mw($,W)),b.nonempty=($)=>b.check(mw(1,$)),b.max=($,W)=>b.check(v0($,W)),b.length=($,W)=>b.check(k0($,W)),b.unwrap=()=>b.element});function c(b,w){return p8(uO,b,w)}var Fq=P("ZodObject",(b,w)=>{e9.init(b,w),Qb.init(b,w),l.defineLazy(b,"shape",()=>{return w.shape}),b.keyof=()=>Ib(Object.keys(b._zod.def.shape)),b.catchall=($)=>b.clone({...b._zod.def,catchall:$}),b.passthrough=()=>b.clone({...b._zod.def,catchall:wb()}),b.loose=()=>b.clone({...b._zod.def,catchall:wb()}),b.strict=()=>b.clone({...b._zod.def,catchall:CO()}),b.strip=()=>b.clone({...b._zod.def,catchall:void 0}),b.extend=($)=>{return l.extend(b,$)},b.safeExtend=($)=>{return l.safeExtend(b,$)},b.merge=($)=>l.merge(b,$),b.pick=($)=>l.pick(b,$),b.omit=($)=>l.omit(b,$),b.partial=(...$)=>l.partial(Iq,b,$[0]),b.required=(...$)=>l.required(_q,b,$[0])});function Z(b,w){let $={type:"object",shape:b??{},...l.normalizeParams(w)};return new Fq($)}function Bb(b,w){return new Fq({type:"object",shape:b,catchall:wb(),...l.normalizeParams(w)})}var Kq=P("ZodUnion",(b,w)=>{P4.init(b,w),Qb.init(b,w),b.options=w.options});function r(b,w){return new Kq({type:"union",options:b,...l.normalizeParams(w)})}var xO=P("ZodDiscriminatedUnion",(b,w)=>{Kq.init(b,w),s9.init(b,w)});function y4(b,w,$){return new xO({type:"union",options:w,discriminator:b,...l.normalizeParams($)})}var yO=P("ZodIntersection",(b,w)=>{a9.init(b,w),Qb.init(b,w)});function x0(b,w){return new yO({type:"intersection",left:b,right:w})}var hO=P("ZodRecord",(b,w)=>{b8.init(b,w),Qb.init(b,w),b.keyType=w.keyType,b.valueType=w.valueType});function $b(b,w,$){return new hO({type:"record",keyType:b,valueType:w,...l.normalizeParams($)})}var C4=P("ZodEnum",(b,w)=>{w8.init(b,w),Qb.init(b,w),b.enum=w.entries,b.options=Object.values(w.entries);let $=new Set(Object.keys(w.entries));b.extract=(W,Q)=>{let q={};for(let G of W)if($.has(G))q[G]=w.entries[G];else throw Error(`Key ${G} not found in enum`);return new C4({...w,checks:[],...l.normalizeParams(Q),entries:q})},b.exclude=(W,Q)=>{let q={...w.entries};for(let G of W)if($.has(G))delete q[G];else throw Error(`Key ${G} not found in enum`);return new C4({...w,checks:[],...l.normalizeParams(Q),entries:q})}});function Ib(b,w){let $=Array.isArray(b)?Object.fromEntries(b.map((W)=>[W,W])):b;return new C4({type:"enum",entries:$,...l.normalizeParams(w)})}var cO=P("ZodLiteral",(b,w)=>{$8.init(b,w),Qb.init(b,w),b.values=new Set(w.values),Object.defineProperty(b,"value",{get(){if(w.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return w.values[0]}})});function N(b,w){return new cO({type:"literal",values:Array.isArray(b)?b:[b],...l.normalizeParams(w)})}var fO=P("ZodTransform",(b,w)=>{W8.init(b,w),Qb.init(b,w),b._zod.parse=($,W)=>{if(W.direction==="backward")throw new A1(b.constructor.name);$.addIssue=(q)=>{if(typeof q==="string")$.issues.push(l.issue(q,$.value,w));else{let G=q;if(G.fatal)G.continue=!1;G.code??(G.code="custom"),G.input??(G.input=$.value),G.inst??(G.inst=b),$.issues.push(l.issue(G))}};let Q=w.transform($.value,$);if(Q instanceof Promise)return Q.then((q)=>{return $.value=q,$});return $.value=Q,$}});function Mq(b){return new fO({type:"transform",transform:b})}var Iq=P("ZodOptional",(b,w)=>{Q8.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType});function Wb(b){return new Iq({type:"optional",innerType:b})}var nO=P("ZodNullable",(b,w)=>{q8.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType});function Uq(b){return new nO({type:"nullable",innerType:b})}var iO=P("ZodDefault",(b,w)=>{G8.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType,b.removeDefault=b.unwrap});function mO(b,w){return new iO({type:"default",innerType:b,get defaultValue(){return typeof w==="function"?w():l.shallowClone(w)}})}var lO=P("ZodPrefault",(b,w)=>{X8.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType});function gO(b,w){return new lO({type:"prefault",innerType:b,get defaultValue(){return typeof w==="function"?w():l.shallowClone(w)}})}var _q=P("ZodNonOptional",(b,w)=>{Y8.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType});function pO(b,w){return new _q({type:"nonoptional",innerType:b,...l.normalizeParams(w)})}var oO=P("ZodCatch",(b,w)=>{J8.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType,b.removeCatch=b.unwrap});function dO(b,w){return new oO({type:"catch",innerType:b,catchValue:typeof w==="function"?w:()=>w})}var tO=P("ZodPipe",(b,w)=>{D8.init(b,w),Qb.init(b,w),b.in=w.in,b.out=w.out});function u4(b,w){return new tO({type:"pipe",in:b,out:w})}var rO=P("ZodReadonly",(b,w)=>{H8.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType});function eO(b){return new rO({type:"readonly",innerType:b})}var jq=P("ZodCustom",(b,w)=>{z8.init(b,w),Qb.init(b,w)});function Zq(b,w){return o8(jq,b??(()=>!0),w)}function sO(b,w={}){return d8(jq,b,w)}function aO(b){return t8(b)}function h4(b,w){return u4(Mq(b),w)}vb(B4());var c4="2025-11-25";var Vq=[c4,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Iw="io.modelcontextprotocol/related-task",h0="2.0",zb=Zq((b)=>b!==null&&(typeof b==="object"||typeof b==="function")),Nq=r([U(),o().int()]),Eq=U(),wj=Bb({ttl:r([o(),x4()]).optional(),pollInterval:o().optional()}),b7=Z({ttl:o().optional()}),w7=Z({taskId:U()}),f4=Bb({progressToken:Nq.optional(),[Iw]:w7.optional()}),Tb=Z({_meta:f4.optional()}),E1=Tb.extend({task:b7.optional()}),Tq=(b)=>E1.safeParse(b).success,Ob=Z({method:U(),params:Tb.loose().optional()}),kb=Z({_meta:f4.optional()}),Cb=Z({method:U(),params:kb.loose().optional()}),Ab=Bb({_meta:f4.optional()}),c0=r([U(),o().int()]),Sq=Z({jsonrpc:N(h0),id:c0,...Ob.shape}).strict(),n4=(b)=>Sq.safeParse(b).success,Rq=Z({jsonrpc:N(h0),...Cb.shape}).strict(),vq=(b)=>Rq.safeParse(b).success,i4=Z({jsonrpc:N(h0),id:c0,result:Ab}).strict(),T1=(b)=>i4.safeParse(b).success;var f;(function(b){b[b.ConnectionClosed=-32000]="ConnectionClosed",b[b.RequestTimeout=-32001]="RequestTimeout",b[b.ParseError=-32700]="ParseError",b[b.InvalidRequest=-32600]="InvalidRequest",b[b.MethodNotFound=-32601]="MethodNotFound",b[b.InvalidParams=-32602]="InvalidParams",b[b.InternalError=-32603]="InternalError",b[b.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(f||(f={}));var m4=Z({jsonrpc:N(h0),id:c0.optional(),error:Z({code:o().int(),message:U(),data:wb().optional()})}).strict();var kq=(b)=>m4.safeParse(b).success;var Cq=r([Sq,Rq,i4,m4]),$j=r([i4,m4]),f0=Ab.strict(),$7=kb.extend({requestId:c0.optional(),reason:U().optional()}),n0=Cb.extend({method:N("notifications/cancelled"),params:$7}),W7=Z({src:U(),mimeType:U().optional(),sizes:c(U()).optional(),theme:Ib(["light","dark"]).optional()}),S1=Z({icons:c(W7).optional()}),gw=Z({name:U(),title:U().optional()}),uq=gw.extend({...gw.shape,...S1.shape,version:U(),websiteUrl:U().optional(),description:U().optional()}),Q7=x0(Z({applyDefaults:Db().optional()}),$b(U(),wb())),q7=h4((b)=>{if(b&&typeof b==="object"&&!Array.isArray(b)){if(Object.keys(b).length===0)return{form:{}}}return b},x0(Z({form:Q7.optional(),url:zb.optional()}),$b(U(),wb()).optional())),G7=Bb({list:zb.optional(),cancel:zb.optional(),requests:Bb({sampling:Bb({createMessage:zb.optional()}).optional(),elicitation:Bb({create:zb.optional()}).optional()}).optional()}),X7=Bb({list:zb.optional(),cancel:zb.optional(),requests:Bb({tools:Bb({call:zb.optional()}).optional()}).optional()}),Y7=Z({experimental:$b(U(),zb).optional(),sampling:Z({context:zb.optional(),tools:zb.optional()}).optional(),elicitation:q7.optional(),roots:Z({listChanged:Db().optional()}).optional(),tasks:G7.optional()}),J7=Tb.extend({protocolVersion:U(),capabilities:Y7,clientInfo:uq}),l4=Ob.extend({method:N("initialize"),params:J7});var D7=Z({experimental:$b(U(),zb).optional(),logging:zb.optional(),completions:zb.optional(),prompts:Z({listChanged:Db().optional()}).optional(),resources:Z({subscribe:Db().optional(),listChanged:Db().optional()}).optional(),tools:Z({listChanged:Db().optional()}).optional(),tasks:X7.optional()}),H7=Ab.extend({protocolVersion:U(),capabilities:D7,serverInfo:uq,instructions:U().optional()}),g4=Cb.extend({method:N("notifications/initialized"),params:kb.optional()});var i0=Ob.extend({method:N("ping"),params:Tb.optional()}),z7=Z({progress:o(),total:Wb(o()),message:Wb(U())}),O7=Z({...kb.shape,...z7.shape,progressToken:Nq}),m0=Cb.extend({method:N("notifications/progress"),params:O7}),A7=Tb.extend({cursor:Eq.optional()}),R1=Ob.extend({params:A7.optional()}),v1=Ab.extend({nextCursor:Eq.optional()}),L7=Ib(["working","input_required","completed","failed","cancelled"]),k1=Z({taskId:U(),status:L7,ttl:r([o(),x4()]),createdAt:U(),lastUpdatedAt:U(),pollInterval:Wb(o()),statusMessage:Wb(U())}),pw=Ab.extend({task:k1}),U7=kb.merge(k1),C1=Cb.extend({method:N("notifications/tasks/status"),params:U7}),l0=Ob.extend({method:N("tasks/get"),params:Tb.extend({taskId:U()})}),g0=Ab.merge(k1),p0=Ob.extend({method:N("tasks/result"),params:Tb.extend({taskId:U()})}),Wj=Ab.loose(),o0=R1.extend({method:N("tasks/list")}),d0=v1.extend({tasks:c(k1)}),t0=Ob.extend({method:N("tasks/cancel"),params:Tb.extend({taskId:U()})}),xq=Ab.merge(k1),yq=Z({uri:U(),mimeType:Wb(U()),_meta:$b(U(),wb()).optional()}),hq=yq.extend({text:U()}),p4=U().refine((b)=>{try{return atob(b),!0}catch{return!1}},{message:"Invalid Base64 string"}),cq=yq.extend({blob:p4}),u1=Ib(["user","assistant"]),ow=Z({audience:c(u1).optional(),priority:o().min(0).max(1).optional(),lastModified:N1.datetime({offset:!0}).optional()}),fq=Z({...gw.shape,...S1.shape,uri:U(),description:Wb(U()),mimeType:Wb(U()),annotations:ow.optional(),_meta:Wb(Bb({}))}),P7=Z({...gw.shape,...S1.shape,uriTemplate:U(),description:Wb(U()),mimeType:Wb(U()),annotations:ow.optional(),_meta:Wb(Bb({}))}),o4=R1.extend({method:N("resources/list")}),B7=v1.extend({resources:c(fq)}),F7=R1.extend({method:N("resources/templates/list")}),K7=v1.extend({resourceTemplates:c(P7)}),d4=Tb.extend({uri:U()}),M7=d4,t4=Ob.extend({method:N("resources/read"),params:M7}),I7=Ab.extend({contents:c(r([hq,cq]))}),_7=Cb.extend({method:N("notifications/resources/list_changed"),params:kb.optional()}),j7=d4,Z7=Ob.extend({method:N("resources/subscribe"),params:j7}),V7=d4,N7=Ob.extend({method:N("resources/unsubscribe"),params:V7}),E7=kb.extend({uri:U()}),T7=Cb.extend({method:N("notifications/resources/updated"),params:E7}),S7=Z({name:U(),description:Wb(U()),required:Wb(Db())}),R7=Z({...gw.shape,...S1.shape,description:Wb(U()),arguments:Wb(c(S7)),_meta:Wb(Bb({}))}),v7=R1.extend({method:N("prompts/list")}),k7=v1.extend({prompts:c(R7)}),C7=Tb.extend({name:U(),arguments:$b(U(),U()).optional()}),u7=Ob.extend({method:N("prompts/get"),params:C7}),r4=Z({type:N("text"),text:U(),annotations:ow.optional(),_meta:$b(U(),wb()).optional()}),e4=Z({type:N("image"),data:p4,mimeType:U(),annotations:ow.optional(),_meta:$b(U(),wb()).optional()}),s4=Z({type:N("audio"),data:p4,mimeType:U(),annotations:ow.optional(),_meta:$b(U(),wb()).optional()}),x7=Z({type:N("tool_use"),name:U(),id:U(),input:$b(U(),wb()),_meta:$b(U(),wb()).optional()}),y7=Z({type:N("resource"),resource:r([hq,cq]),annotations:ow.optional(),_meta:$b(U(),wb()).optional()}),h7=fq.extend({type:N("resource_link")}),a4=r([r4,e4,s4,h7,y7]),c7=Z({role:u1,content:a4}),f7=Ab.extend({description:U().optional(),messages:c(c7)}),n7=Cb.extend({method:N("notifications/prompts/list_changed"),params:kb.optional()}),i7=Z({title:U().optional(),readOnlyHint:Db().optional(),destructiveHint:Db().optional(),idempotentHint:Db().optional(),openWorldHint:Db().optional()}),m7=Z({taskSupport:Ib(["required","optional","forbidden"]).optional()}),nq=Z({...gw.shape,...S1.shape,description:U().optional(),inputSchema:Z({type:N("object"),properties:$b(U(),zb).optional(),required:c(U()).optional()}).catchall(wb()),outputSchema:Z({type:N("object"),properties:$b(U(),zb).optional(),required:c(U()).optional()}).catchall(wb()).optional(),annotations:i7.optional(),execution:m7.optional(),_meta:$b(U(),wb()).optional()}),b6=R1.extend({method:N("tools/list")}),l7=v1.extend({tools:c(nq)}),r0=Ab.extend({content:c(a4).default([]),structuredContent:$b(U(),wb()).optional(),isError:Db().optional()}),Qj=r0.or(Ab.extend({toolResult:wb()})),g7=E1.extend({name:U(),arguments:$b(U(),wb()).optional()}),x1=Ob.extend({method:N("tools/call"),params:g7}),p7=Cb.extend({method:N("notifications/tools/list_changed"),params:kb.optional()}),qj=Z({autoRefresh:Db().default(!0),debounceMs:o().int().nonnegative().default(300)}),y1=Ib(["debug","info","notice","warning","error","critical","alert","emergency"]),o7=Tb.extend({level:y1}),w6=Ob.extend({method:N("logging/setLevel"),params:o7}),d7=kb.extend({level:y1,logger:U().optional(),data:wb()}),t7=Cb.extend({method:N("notifications/message"),params:d7}),r7=Z({name:U().optional()}),e7=Z({hints:c(r7).optional(),costPriority:o().min(0).max(1).optional(),speedPriority:o().min(0).max(1).optional(),intelligencePriority:o().min(0).max(1).optional()}),s7=Z({mode:Ib(["auto","required","none"]).optional()}),a7=Z({type:N("tool_result"),toolUseId:U().describe("The unique identifier for the corresponding tool call."),content:c(a4).default([]),structuredContent:Z({}).loose().optional(),isError:Db().optional(),_meta:$b(U(),wb()).optional()}),bA=y4("type",[r4,e4,s4]),y0=y4("type",[r4,e4,s4,x7,a7]),wA=Z({role:u1,content:r([y0,c(y0)]),_meta:$b(U(),wb()).optional()}),$A=E1.extend({messages:c(wA),modelPreferences:e7.optional(),systemPrompt:U().optional(),includeContext:Ib(["none","thisServer","allServers"]).optional(),temperature:o().optional(),maxTokens:o().int(),stopSequences:c(U()).optional(),metadata:zb.optional(),tools:c(nq).optional(),toolChoice:s7.optional()}),WA=Ob.extend({method:N("sampling/createMessage"),params:$A}),$6=Ab.extend({model:U(),stopReason:Wb(Ib(["endTurn","stopSequence","maxTokens"]).or(U())),role:u1,content:bA}),W6=Ab.extend({model:U(),stopReason:Wb(Ib(["endTurn","stopSequence","maxTokens","toolUse"]).or(U())),role:u1,content:r([y0,c(y0)])}),QA=Z({type:N("boolean"),title:U().optional(),description:U().optional(),default:Db().optional()}),qA=Z({type:N("string"),title:U().optional(),description:U().optional(),minLength:o().optional(),maxLength:o().optional(),format:Ib(["email","uri","date","date-time"]).optional(),default:U().optional()}),GA=Z({type:Ib(["number","integer"]),title:U().optional(),description:U().optional(),minimum:o().optional(),maximum:o().optional(),default:o().optional()}),XA=Z({type:N("string"),title:U().optional(),description:U().optional(),enum:c(U()),default:U().optional()}),YA=Z({type:N("string"),title:U().optional(),description:U().optional(),oneOf:c(Z({const:U(),title:U()})),default:U().optional()}),JA=Z({type:N("string"),title:U().optional(),description:U().optional(),enum:c(U()),enumNames:c(U()).optional(),default:U().optional()}),DA=r([XA,YA]),HA=Z({type:N("array"),title:U().optional(),description:U().optional(),minItems:o().optional(),maxItems:o().optional(),items:Z({type:N("string"),enum:c(U())}),default:c(U()).optional()}),zA=Z({type:N("array"),title:U().optional(),description:U().optional(),minItems:o().optional(),maxItems:o().optional(),items:Z({anyOf:c(Z({const:U(),title:U()}))}),default:c(U()).optional()}),OA=r([HA,zA]),AA=r([JA,DA,OA]),LA=r([AA,QA,qA,GA]),UA=E1.extend({mode:N("form").optional(),message:U(),requestedSchema:Z({type:N("object"),properties:$b(U(),LA),required:c(U()).optional()})}),PA=E1.extend({mode:N("url"),message:U(),elicitationId:U(),url:U().url()}),BA=r([UA,PA]),FA=Ob.extend({method:N("elicitation/create"),params:BA}),KA=kb.extend({elicitationId:U()}),MA=Cb.extend({method:N("notifications/elicitation/complete"),params:KA}),e0=Ab.extend({action:Ib(["accept","decline","cancel"]),content:h4((b)=>b===null?void 0:b,$b(U(),r([U(),o(),Db(),c(U())])).optional())}),IA=Z({type:N("ref/resource"),uri:U()});var _A=Z({type:N("ref/prompt"),name:U()}),jA=Tb.extend({ref:r([_A,IA]),argument:Z({name:U(),value:U()}),context:Z({arguments:$b(U(),U()).optional()}).optional()}),ZA=Ob.extend({method:N("completion/complete"),params:jA});var VA=Ab.extend({completion:Bb({values:c(U()).max(100),total:Wb(o().int()),hasMore:Wb(Db())})}),NA=Z({uri:U().startsWith("file://"),name:U().optional(),_meta:$b(U(),wb()).optional()}),EA=Ob.extend({method:N("roots/list"),params:Tb.optional()}),Q6=Ab.extend({roots:c(NA)}),TA=Cb.extend({method:N("notifications/roots/list_changed"),params:kb.optional()}),Gj=r([i0,l4,ZA,w6,u7,v7,o4,F7,t4,Z7,N7,x1,b6,l0,p0,o0,t0]),Xj=r([n0,m0,g4,TA,C1]),Yj=r([f0,$6,W6,e0,Q6,g0,d0,pw]),Jj=r([i0,WA,FA,EA,l0,p0,o0,t0]),Dj=r([n0,m0,t7,T7,_7,p7,n7,C1,MA]),Hj=r([f0,H7,VA,f7,k7,B7,K7,I7,r0,l7,g0,d0,pw]);class x extends Error{constructor(b,w,$){super(`MCP error ${b}: ${w}`);this.code=b,this.data=$,this.name="McpError"}static fromError(b,w,$){if(b===f.UrlElicitationRequired&&$){let W=$;if(W.elicitations)return new iq(W.elicitations,w)}return new x(b,w,$)}}class iq extends x{constructor(b,w=`URL elicitation${b.length>1?"s":""} required`){super(f.UrlElicitationRequired,w,{elicitations:b})}get elicitations(){return this.data?.elicitations??[]}}function _w(b){return b==="completed"||b==="failed"||b==="cancelled"}var SA=Symbol("Let zodToJsonSchema decide on which parser to use");var lj=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function q6(b){let $=C0(b)?.method;if(!$)throw Error("Schema is missing a method literal");let W=r8($);if(typeof W!=="string")throw Error("Schema method literal must be a string");return W}function G6(b,w){let $=Mw(b,w);if(!$.success)throw $.error;return $.data}var xA=60000;class X6{constructor(b){if(this._options=b,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(n0,(w)=>{this._oncancel(w)}),this.setNotificationHandler(m0,(w)=>{this._onprogress(w)}),this.setRequestHandler(i0,(w)=>({})),this._taskStore=b?.taskStore,this._taskMessageQueue=b?.taskMessageQueue,this._taskStore)this.setRequestHandler(l0,async(w,$)=>{let W=await this._taskStore.getTask(w.params.taskId,$.sessionId);if(!W)throw new x(f.InvalidParams,"Failed to retrieve task: Task not found");return{...W}}),this.setRequestHandler(p0,async(w,$)=>{let W=async()=>{let Q=w.params.taskId;if(this._taskMessageQueue){let G;while(G=await this._taskMessageQueue.dequeue(Q,$.sessionId)){if(G.type==="response"||G.type==="error"){let X=G.message,Y=X.id,J=this._requestResolvers.get(Y);if(J)if(this._requestResolvers.delete(Y),G.type==="response")J(X);else{let D=X,H=new x(D.error.code,D.error.message,D.error.data);J(H)}else{let D=G.type==="response"?"Response":"Error";this._onerror(Error(`${D} handler missing for request ${Y}`))}continue}await this._transport?.send(G.message,{relatedRequestId:$.requestId})}}let q=await this._taskStore.getTask(Q,$.sessionId);if(!q)throw new x(f.InvalidParams,`Task not found: ${Q}`);if(!_w(q.status))return await this._waitForTaskUpdate(Q,$.signal),await W();if(_w(q.status)){let G=await this._taskStore.getTaskResult(Q,$.sessionId);return this._clearTaskQueue(Q),{...G,_meta:{...G._meta,[Iw]:{taskId:Q}}}}return await W()};return await W()}),this.setRequestHandler(o0,async(w,$)=>{try{let{tasks:W,nextCursor:Q}=await this._taskStore.listTasks(w.params?.cursor,$.sessionId);return{tasks:W,nextCursor:Q,_meta:{}}}catch(W){throw new x(f.InvalidParams,`Failed to list tasks: ${W instanceof Error?W.message:String(W)}`)}}),this.setRequestHandler(t0,async(w,$)=>{try{let W=await this._taskStore.getTask(w.params.taskId,$.sessionId);if(!W)throw new x(f.InvalidParams,`Task not found: ${w.params.taskId}`);if(_w(W.status))throw new x(f.InvalidParams,`Cannot cancel task in terminal status: ${W.status}`);await this._taskStore.updateTaskStatus(w.params.taskId,"cancelled","Client cancelled task execution.",$.sessionId),this._clearTaskQueue(w.params.taskId);let Q=await this._taskStore.getTask(w.params.taskId,$.sessionId);if(!Q)throw new x(f.InvalidParams,`Task not found after cancellation: ${w.params.taskId}`);return{_meta:{},...Q}}catch(W){if(W instanceof x)throw W;throw new x(f.InvalidRequest,`Failed to cancel task: ${W instanceof Error?W.message:String(W)}`)}})}async _oncancel(b){if(!b.params.requestId)return;this._requestHandlerAbortControllers.get(b.params.requestId)?.abort(b.params.reason)}_setupTimeout(b,w,$,W,Q=!1){this._timeoutInfo.set(b,{timeoutId:setTimeout(W,w),startTime:Date.now(),timeout:w,maxTotalTimeout:$,resetTimeoutOnProgress:Q,onTimeout:W})}_resetTimeout(b){let w=this._timeoutInfo.get(b);if(!w)return!1;let $=Date.now()-w.startTime;if(w.maxTotalTimeout&&$>=w.maxTotalTimeout)throw this._timeoutInfo.delete(b),x.fromError(f.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:w.maxTotalTimeout,totalElapsed:$});return clearTimeout(w.timeoutId),w.timeoutId=setTimeout(w.onTimeout,w.timeout),!0}_cleanupTimeout(b){let w=this._timeoutInfo.get(b);if(w)clearTimeout(w.timeoutId),this._timeoutInfo.delete(b)}async connect(b){this._transport=b;let w=this.transport?.onclose;this._transport.onclose=()=>{w?.(),this._onclose()};let $=this.transport?.onerror;this._transport.onerror=(Q)=>{$?.(Q),this._onerror(Q)};let W=this._transport?.onmessage;this._transport.onmessage=(Q,q)=>{if(W?.(Q,q),T1(Q)||kq(Q))this._onresponse(Q);else if(n4(Q))this._onrequest(Q,q);else if(vq(Q))this._onnotification(Q);else this._onerror(Error(`Unknown message type: ${JSON.stringify(Q)}`))},await this._transport.start()}_onclose(){let b=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();let w=x.fromError(f.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let $ of b.values())$(w)}_onerror(b){this.onerror?.(b)}_onnotification(b){let w=this._notificationHandlers.get(b.method)??this.fallbackNotificationHandler;if(w===void 0)return;Promise.resolve().then(()=>w(b)).catch(($)=>this._onerror(Error(`Uncaught error in notification handler: ${$}`)))}_onrequest(b,w){let $=this._requestHandlers.get(b.method)??this.fallbackRequestHandler,W=this._transport,Q=b.params?._meta?.[Iw]?.taskId;if($===void 0){let J={jsonrpc:"2.0",id:b.id,error:{code:f.MethodNotFound,message:"Method not found"}};if(Q&&this._taskMessageQueue)this._enqueueTaskMessage(Q,{type:"error",message:J,timestamp:Date.now()},W?.sessionId).catch((D)=>this._onerror(Error(`Failed to enqueue error response: ${D}`)));else W?.send(J).catch((D)=>this._onerror(Error(`Failed to send an error response: ${D}`)));return}let q=new AbortController;this._requestHandlerAbortControllers.set(b.id,q);let G=Tq(b.params)?b.params.task:void 0,X=this._taskStore?this.requestTaskStore(b,W?.sessionId):void 0,Y={signal:q.signal,sessionId:W?.sessionId,_meta:b.params?._meta,sendNotification:async(J)=>{let D={relatedRequestId:b.id};if(Q)D.relatedTask={taskId:Q};await this.notification(J,D)},sendRequest:async(J,D,H)=>{let O={...H,relatedRequestId:b.id};if(Q&&!O.relatedTask)O.relatedTask={taskId:Q};let A=O.relatedTask?.taskId??Q;if(A&&X)await X.updateTaskStatus(A,"input_required");return await this.request(J,D,O)},authInfo:w?.authInfo,requestId:b.id,requestInfo:w?.requestInfo,taskId:Q,taskStore:X,taskRequestedTtl:G?.ttl,closeSSEStream:w?.closeSSEStream,closeStandaloneSSEStream:w?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(G)this.assertTaskHandlerCapability(b.method)}).then(()=>$(b,Y)).then(async(J)=>{if(q.signal.aborted)return;let D={result:J,jsonrpc:"2.0",id:b.id};if(Q&&this._taskMessageQueue)await this._enqueueTaskMessage(Q,{type:"response",message:D,timestamp:Date.now()},W?.sessionId);else await W?.send(D)},async(J)=>{if(q.signal.aborted)return;let D={jsonrpc:"2.0",id:b.id,error:{code:Number.isSafeInteger(J.code)?J.code:f.InternalError,message:J.message??"Internal error",...J.data!==void 0&&{data:J.data}}};if(Q&&this._taskMessageQueue)await this._enqueueTaskMessage(Q,{type:"error",message:D,timestamp:Date.now()},W?.sessionId);else await W?.send(D)}).catch((J)=>this._onerror(Error(`Failed to send response: ${J}`))).finally(()=>{this._requestHandlerAbortControllers.delete(b.id)})}_onprogress(b){let{progressToken:w,...$}=b.params,W=Number(w),Q=this._progressHandlers.get(W);if(!Q){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(b)}`));return}let q=this._responseHandlers.get(W),G=this._timeoutInfo.get(W);if(G&&q&&G.resetTimeoutOnProgress)try{this._resetTimeout(W)}catch(X){this._responseHandlers.delete(W),this._progressHandlers.delete(W),this._cleanupTimeout(W),q(X);return}Q($)}_onresponse(b){let w=Number(b.id),$=this._requestResolvers.get(w);if($){if(this._requestResolvers.delete(w),T1(b))$(b);else{let q=new x(b.error.code,b.error.message,b.error.data);$(q)}return}let W=this._responseHandlers.get(w);if(W===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(b)}`));return}this._responseHandlers.delete(w),this._cleanupTimeout(w);let Q=!1;if(T1(b)&&b.result&&typeof b.result==="object"){let q=b.result;if(q.task&&typeof q.task==="object"){let G=q.task;if(typeof G.taskId==="string")Q=!0,this._taskProgressTokens.set(G.taskId,w)}}if(!Q)this._progressHandlers.delete(w);if(T1(b))W(b);else{let q=x.fromError(b.error.code,b.error.message,b.error.data);W(q)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(b,w,$){let{task:W}=$??{};if(!W){try{yield{type:"result",result:await this.request(b,w,$)}}catch(q){yield{type:"error",error:q instanceof x?q:new x(f.InternalError,String(q))}}return}let Q;try{let q=await this.request(b,pw,$);if(q.task)Q=q.task.taskId,yield{type:"taskCreated",task:q.task};else throw new x(f.InternalError,"Task creation did not return a task");while(!0){let G=await this.getTask({taskId:Q},$);if(yield{type:"taskStatus",task:G},_w(G.status)){if(G.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:Q},w,$)};else if(G.status==="failed")yield{type:"error",error:new x(f.InternalError,`Task ${Q} failed`)};else if(G.status==="cancelled")yield{type:"error",error:new x(f.InternalError,`Task ${Q} was cancelled`)};return}if(G.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:Q},w,$)};return}let X=G.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((Y)=>setTimeout(Y,X)),$?.signal?.throwIfAborted()}}catch(q){yield{type:"error",error:q instanceof x?q:new x(f.InternalError,String(q))}}}request(b,w,$){let{relatedRequestId:W,resumptionToken:Q,onresumptiontoken:q,task:G,relatedTask:X}=$??{};return new Promise((Y,J)=>{let D=(I)=>{J(I)};if(!this._transport){D(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(b.method),G)this.assertTaskCapability(b.method)}catch(I){D(I);return}$?.signal?.throwIfAborted();let H=this._requestMessageId++,O={...b,jsonrpc:"2.0",id:H};if($?.onprogress)this._progressHandlers.set(H,$.onprogress),O.params={...b.params,_meta:{...b.params?._meta||{},progressToken:H}};if(G)O.params={...O.params,task:G};if(X)O.params={...O.params,_meta:{...O.params?._meta||{},[Iw]:X}};let A=(I)=>{this._responseHandlers.delete(H),this._progressHandlers.delete(H),this._cleanupTimeout(H),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:H,reason:String(I)}},{relatedRequestId:W,resumptionToken:Q,onresumptiontoken:q}).catch((T)=>this._onerror(Error(`Failed to send cancellation: ${T}`)));let R=I instanceof x?I:new x(f.RequestTimeout,String(I));J(R)};this._responseHandlers.set(H,(I)=>{if($?.signal?.aborted)return;if(I instanceof Error)return J(I);try{let R=Mw(w,I.result);if(!R.success)J(R.error);else Y(R.data)}catch(R){J(R)}}),$?.signal?.addEventListener("abort",()=>{A($?.signal?.reason)});let B=$?.timeout??xA,K=()=>A(x.fromError(f.RequestTimeout,"Request timed out",{timeout:B}));this._setupTimeout(H,B,$?.maxTotalTimeout,K,$?.resetTimeoutOnProgress??!1);let _=X?.taskId;if(_){let I=(R)=>{let T=this._responseHandlers.get(H);if(T)T(R);else this._onerror(Error(`Response handler missing for side-channeled request ${H}`))};this._requestResolvers.set(H,I),this._enqueueTaskMessage(_,{type:"request",message:O,timestamp:Date.now()}).catch((R)=>{this._cleanupTimeout(H),J(R)})}else this._transport.send(O,{relatedRequestId:W,resumptionToken:Q,onresumptiontoken:q}).catch((I)=>{this._cleanupTimeout(H),J(I)})})}async getTask(b,w){return this.request({method:"tasks/get",params:b},g0,w)}async getTaskResult(b,w,$){return this.request({method:"tasks/result",params:b},w,$)}async listTasks(b,w){return this.request({method:"tasks/list",params:b},d0,w)}async cancelTask(b,w){return this.request({method:"tasks/cancel",params:b},xq,w)}async notification(b,w){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(b.method);let $=w?.relatedTask?.taskId;if($){let G={...b,jsonrpc:"2.0",params:{...b.params,_meta:{...b.params?._meta||{},[Iw]:w.relatedTask}}};await this._enqueueTaskMessage($,{type:"notification",message:G,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(b.method)&&!b.params&&!w?.relatedRequestId&&!w?.relatedTask){if(this._pendingDebouncedNotifications.has(b.method))return;this._pendingDebouncedNotifications.add(b.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(b.method),!this._transport)return;let G={...b,jsonrpc:"2.0"};if(w?.relatedTask)G={...G,params:{...G.params,_meta:{...G.params?._meta||{},[Iw]:w.relatedTask}}};this._transport?.send(G,w).catch((X)=>this._onerror(X))});return}let q={...b,jsonrpc:"2.0"};if(w?.relatedTask)q={...q,params:{...q.params,_meta:{...q.params?._meta||{},[Iw]:w.relatedTask}}};await this._transport.send(q,w)}setRequestHandler(b,w){let $=q6(b);this.assertRequestHandlerCapability($),this._requestHandlers.set($,(W,Q)=>{let q=G6(b,W);return Promise.resolve(w(q,Q))})}removeRequestHandler(b){this._requestHandlers.delete(b)}assertCanSetRequestHandler(b){if(this._requestHandlers.has(b))throw Error(`A request handler for ${b} already exists, which would be overridden`)}setNotificationHandler(b,w){let $=q6(b);this._notificationHandlers.set($,(W)=>{let Q=G6(b,W);return Promise.resolve(w(Q))})}removeNotificationHandler(b){this._notificationHandlers.delete(b)}_cleanupTaskProgressHandler(b){let w=this._taskProgressTokens.get(b);if(w!==void 0)this._progressHandlers.delete(w),this._taskProgressTokens.delete(b)}async _enqueueTaskMessage(b,w,$){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let W=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(b,w,$,W)}async _clearTaskQueue(b,w){if(this._taskMessageQueue){let $=await this._taskMessageQueue.dequeueAll(b,w);for(let W of $)if(W.type==="request"&&n4(W.message)){let Q=W.message.id,q=this._requestResolvers.get(Q);if(q)q(new x(f.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(Q);else this._onerror(Error(`Resolver missing for request ${Q} during task ${b} cleanup`))}}}async _waitForTaskUpdate(b,w){let $=this._options?.defaultTaskPollInterval??1000;try{let W=await this._taskStore?.getTask(b);if(W?.pollInterval)$=W.pollInterval}catch{}return new Promise((W,Q)=>{if(w.aborted){Q(new x(f.InvalidRequest,"Request cancelled"));return}let q=setTimeout(W,$);w.addEventListener("abort",()=>{clearTimeout(q),Q(new x(f.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(b,w){let $=this._taskStore;if(!$)throw Error("No task store configured");return{createTask:async(W)=>{if(!b)throw Error("No request provided");return await $.createTask(W,b.id,{method:b.method,params:b.params},w)},getTask:async(W)=>{let Q=await $.getTask(W,w);if(!Q)throw new x(f.InvalidParams,"Failed to retrieve task: Task not found");return Q},storeTaskResult:async(W,Q,q)=>{await $.storeTaskResult(W,Q,q,w);let G=await $.getTask(W,w);if(G){let X=C1.parse({method:"notifications/tasks/status",params:G});if(await this.notification(X),_w(G.status))this._cleanupTaskProgressHandler(W)}},getTaskResult:(W)=>{return $.getTaskResult(W,w)},updateTaskStatus:async(W,Q,q)=>{let G=await $.getTask(W,w);if(!G)throw new x(f.InvalidParams,`Task "${W}" not found - it may have been cleaned up`);if(_w(G.status))throw new x(f.InvalidParams,`Cannot update task "${W}" from terminal status "${G.status}" to "${Q}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await $.updateTaskStatus(W,Q,q,w);let X=await $.getTask(W,w);if(X){let Y=C1.parse({method:"notifications/tasks/status",params:X});if(await this.notification(Y),_w(X.status))this._cleanupTaskProgressHandler(W)}},listTasks:(W)=>{return $.listTasks(W,w)}}}}function mq(b){return b!==null&&typeof b==="object"&&!Array.isArray(b)}function lq(b,w){let $={...b};for(let W in w){let Q=W,q=w[Q];if(q===void 0)continue;let G=$[Q];if(mq(G)&&mq(q))$[Q]={...G,...q};else $[Q]=q}return $}var MD=gW(wW(),1),ID=gW(KD(),1);function gK(){let b=new MD.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return ID.default(b),b}class HW{constructor(b){this._ajv=b??gK()}getValidator(b){let w="$id"in b&&typeof b.$id==="string"?this._ajv.getSchema(b.$id)??this._ajv.compile(b):this._ajv.compile(b);return($)=>{if(w($))return{valid:!0,data:$,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(w.errors)}}}}class zW{constructor(b){this._server=b}requestStream(b,w,$){return this._server.requestStream(b,w,$)}async getTask(b,w){return this._server.getTask({taskId:b},w)}async getTaskResult(b,w,$){return this._server.getTaskResult({taskId:b},w,$)}async listTasks(b,w){return this._server.listTasks(b?{cursor:b}:void 0,w)}async cancelTask(b,w){return this._server.cancelTask({taskId:b},w)}}function _D(b,w,$){if(!b)throw Error(`${$} does not support task creation (required for ${w})`);switch(w){case"tools/call":if(!b.tools?.call)throw Error(`${$} does not support task creation for tools/call (required for ${w})`);break;default:break}}function jD(b,w,$){if(!b)throw Error(`${$} does not support task creation (required for ${w})`);switch(w){case"sampling/createMessage":if(!b.sampling?.createMessage)throw Error(`${$} does not support task creation for sampling/createMessage (required for ${w})`);break;case"elicitation/create":if(!b.elicitation?.create)throw Error(`${$} does not support task creation for elicitation/create (required for ${w})`);break;default:break}}class OW extends X6{constructor(b,w){super(w);if(this._serverInfo=b,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(y1.options.map(($,W)=>[$,W])),this.isMessageIgnored=($,W)=>{let Q=this._loggingLevels.get(W);return Q?this.LOG_LEVEL_SEVERITY.get($)<this.LOG_LEVEL_SEVERITY.get(Q):!1},this._capabilities=w?.capabilities??{},this._instructions=w?.instructions,this._jsonSchemaValidator=w?.jsonSchemaValidator??new HW,this.setRequestHandler(l4,($)=>this._oninitialize($)),this.setNotificationHandler(g4,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(w6,async($,W)=>{let Q=W.sessionId||W.requestInfo?.headers["mcp-session-id"]||void 0,{level:q}=$.params,G=y1.safeParse(q);if(G.success)this._loggingLevels.set(Q,G.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new zW(this)};return this._experimental}registerCapabilities(b){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=lq(this._capabilities,b)}setRequestHandler(b,w){let W=C0(b)?.method;if(!W)throw Error("Schema is missing a method literal");let Q;if(lw(W)){let G=W;Q=G._zod?.def?.value??G.value}else{let G=W;Q=G._def?.value??G.value}if(typeof Q!=="string")throw Error("Schema method literal must be a string");if(Q==="tools/call"){let G=async(X,Y)=>{let J=Mw(x1,X);if(!J.success){let A=J.error instanceof Error?J.error.message:String(J.error);throw new x(f.InvalidParams,`Invalid tools/call request: ${A}`)}let{params:D}=J.data,H=await Promise.resolve(w(X,Y));if(D.task){let A=Mw(pw,H);if(!A.success){let B=A.error instanceof Error?A.error.message:String(A.error);throw new x(f.InvalidParams,`Invalid task creation result: ${B}`)}return A.data}let O=Mw(r0,H);if(!O.success){let A=O.error instanceof Error?O.error.message:String(O.error);throw new x(f.InvalidParams,`Invalid tools/call result: ${A}`)}return O.data};return super.setRequestHandler(b,G)}return super.setRequestHandler(b,w)}assertCapabilityForMethod(b){switch(b){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${b})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${b})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${b})`);break;case"ping":break}}assertNotificationCapability(b){switch(b){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${b})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${b})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${b})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${b})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${b})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(b){if(!this._capabilities)return;switch(b){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${b})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${b})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${b})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${b})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${b})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${b})`);break;case"ping":case"initialize":break}}assertTaskCapability(b){jD(this._clientCapabilities?.tasks?.requests,b,"Client")}assertTaskHandlerCapability(b){if(!this._capabilities)return;_D(this._capabilities.tasks?.requests,b,"Server")}async _oninitialize(b){let w=b.params.protocolVersion;return this._clientCapabilities=b.params.capabilities,this._clientVersion=b.params.clientInfo,{protocolVersion:Vq.includes(w)?w:c4,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},f0)}async createMessage(b,w){if(b.tools||b.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if(b.messages.length>0){let $=b.messages[b.messages.length-1],W=Array.isArray($.content)?$.content:[$.content],Q=W.some((Y)=>Y.type==="tool_result"),q=b.messages.length>1?b.messages[b.messages.length-2]:void 0,G=q?Array.isArray(q.content)?q.content:[q.content]:[],X=G.some((Y)=>Y.type==="tool_use");if(Q){if(W.some((Y)=>Y.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!X)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(X){let Y=new Set(G.filter((D)=>D.type==="tool_use").map((D)=>D.id)),J=new Set(W.filter((D)=>D.type==="tool_result").map((D)=>D.toolUseId));if(Y.size!==J.size||![...Y].every((D)=>J.has(D)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if(b.tools)return this.request({method:"sampling/createMessage",params:b},W6,w);return this.request({method:"sampling/createMessage",params:b},$6,w)}async elicitInput(b,w){switch(b.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let W=b;return this.request({method:"elicitation/create",params:W},e0,w)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let W=b.mode==="form"?b:{...b,mode:"form"},Q=await this.request({method:"elicitation/create",params:W},e0,w);if(Q.action==="accept"&&Q.content&&W.requestedSchema)try{let G=this._jsonSchemaValidator.getValidator(W.requestedSchema)(Q.content);if(!G.valid)throw new x(f.InvalidParams,`Elicitation response content does not match requested schema: ${G.errorMessage}`)}catch(q){if(q instanceof x)throw q;throw new x(f.InternalError,`Error validating elicitation response: ${q instanceof Error?q.message:String(q)}`)}return Q}}}createElicitationCompletionNotifier(b,w){if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:b}},w)}async listRoots(b,w){return this.request({method:"roots/list",params:b},Q6,w)}async sendLoggingMessage(b,w){if(this._capabilities.logging){if(!this.isMessageIgnored(b.level,w))return this.notification({method:"notifications/message",params:b})}}async sendResourceUpdated(b){return this.notification({method:"notifications/resources/updated",params:b})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}var ZD={name:"@sequenzy/mcp",version:"0.0.121",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 AW=["product-info","domain","tracking","localization","integrations","products","events","tags","labels","goals","sync-rules","api-keys","widgets","team","danger"],VD={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 oK(b){let $=(b??process.env.SEQUENZY_APP_URL??"https://sequenzy.com").trim().replace(/\/+$/,"");return $.length>0?$:"https://sequenzy.com"}function gb(b){let w=b?.trim();return w?w:void 0}function sb(b){return encodeURIComponent(b)}function Yb(b,w){return`${b}${w}`}function Jb(b,w=""){return`/dashboard/company/${sb(b)}${w}`}function ND(b,w,$){return Yb(b,`${Jb(w,"/settings")}?tab=${encodeURIComponent($)}`)}function dK(b,w){let $=AW.map((W)=>[W,w?ND(b,w,W):""]);return Object.fromEntries($)}function Dw(b={},w){let $=oK(w),W=gb(b.companyId),Q={},q=dK($,W);if(!W)return{appUrl:$,routeTemplates:VD,settingsTabValues:AW,urls:Q,settingsUrls:q};Q.dashboard=Yb($,Jb(W)),Q.campaigns=Yb($,Jb(W,"/campaign")),Q.landingPages=Yb($,Jb(W,"/landing-pages")),Q.sequences=Yb($,Jb(W,"/sequences")),Q.settings=Yb($,Jb(W,"/settings")),Q.emails=Yb($,Jb(W,"/emails")),Q.subscribers=Yb($,Jb(W,"/subscribers")),Q.sentEmails=Yb($,Jb(W,"/sent-emails")),Q.segments=Yb($,Jb(W,"/segments")),Q.metrics=Yb($,Jb(W,"/metrics")),Q.transactional=Yb($,Jb(W,"/transactional"));let G=gb(b.campaignId);if(G)Q.campaign=Yb($,Jb(W,`/campaign/${sb(G)}`)),Q.campaignPreview=`${Q.campaign}?step=review`;let X=gb(b.landingPageId);if(X)Q.landingPage=Yb($,Jb(W,`/landing-pages/${sb(X)}`));let Y=gb(b.sequenceId);if(Y)Q.sequence=Yb($,Jb(W,`/sequences/${sb(Y)}`));let J=gb(b.emailId)??gb(b.templateId);if(J)Q.email=Yb($,Jb(W,`/emails/${sb(J)}`)),Q.template=Q.email;let D=gb(b.transactionalId);if(D)Q.transactionalEmail=Yb($,Jb(W,`/transactional/${sb(D)}`));let H=gb(b.emailSendId);if(H)Q.emailSend=Yb($,Jb(W,`/sent-emails/${sb(H)}`));let O=gb(b.domainId);if(O)Q.domain=Yb($,Jb(W,`/settings/domain/${sb(O)}`)),Q.domainVerify=`${Q.domain}/verify`;let A=gb(b.status);if(A)Q.campaignList=Yb($,Jb(W,`/campaign/list/${sb(A)}`)),Q.sequenceList=Yb($,Jb(W,`/sequences/list/${sb(A)}`));let B=gb(b.settingsTab);if(B)Q.settingsTab=ND($,W,B);return{appUrl:$,routeTemplates:VD,settingsTabValues:AW,urls:Q,settingsUrls:q}}var ED=[{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 TD(b){try{let w;switch(b){case"sequenzy://dashboard":w=await z("GET","/api/v1/metrics?period=7d");break;case"sequenzy://company":{let $=await z("GET","/api/v1/account"),W=Uw()??$.currentCompanyId;if(!W)throw Error("No company available. Create or select a company first.");w=await z("GET",`/api/v1/companies/${W}`);break}case"sequenzy://campaigns/recent":w=await z("GET","/api/v1/campaigns?limit=10");break;case"sequenzy://subscribers/recent":w=await z("GET","/api/v1/subscribers?sort=createdAt&limit=20");break;case"sequenzy://subscribers/engaged":w=await z("GET","/api/v1/subscribers?sort=engagement&limit=20");break;case"sequenzy://sequences":w=await z("GET","/api/v1/sequences");break;case"sequenzy://templates":w=await z("GET","/api/v1/templates");break;case"sequenzy://segments":w=await z("GET","/api/v1/segments");break;case"sequenzy://tags":w=await z("GET","/api/v1/tags");break;case"sequenzy://health":w=await z("GET","/api/v1/health/deliverability");break;case"sequenzy://app-routes":w=Dw();break;default:throw Error(`Unknown resource: ${b}`)}return{contents:[{uri:b,mimeType:"application/json",text:JSON.stringify(w,null,2)}]}}catch(w){return{contents:[{uri:b,mimeType:"text/plain",text:Lw(w)}]}}}function k(b){return typeof b==="object"&&b!==null&&!Array.isArray(b)}function L(b,w){let $=b[w];if(typeof $!=="string")return;let W=$.trim();return W.length>0?W:void 0}function M(b,w,$){let W=L(w,$);if(W===void 0)throw Error(`\`${$}\` is required when calling \`${b}\`.`);return W}var x$=' 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 LW=' Any block accepts a `conditions` array so it only renders for matching recipients. To branch on a value passed in transactional `variables` or an automation `event` payload, use { "id": "c1", "field": "variable", "operator": "is", "value": "plan:pro" }; "attribute" uses the same "name:value" form, while "email"/"firstName"/"lastName" use a plain comparison value. Live subscriber fields are "status", "tag", "list", "segment", "event", "emailProvider", "phone", "smsStatus", "added", "stripeProduct", "stripeCurrentProduct", "stripeTrialProduct", "commerceProduct", "emailSent", "emailDelivered", "emailOpened", "emailClicked", "emailBounced", and "emailComplained". They use the same field-specific values and operators as segment filters, for example { "id": "c2", "field": "segment", "operator": "is", "value": "seg_123" }, { "id": "c3", "field": "tag", "operator": "contains", "value": "vip" }, or { "id": "c4", "field": "event", "operator": "at_least", "value": "purchase:3:30d" }. Supported operators across fields are is, is_not, contains, not_contains, gt, gte, lt, lte, less_than, more_than, at_least, less_than_count, is_empty, is_not_empty, is_temporary_bounce, and is_permanent_bounce; each field accepts only its segment-filter operators. Recipients without a stored subscriber match use the OTHERWISE branch or hide a conditionally displayed block. For if/else, use a { type: "conditional-group", conditions: [...], ifBranch: { children: [...] }, elseBranch: { children: [...] } } block.',UW=' Polls and NPS surveys use a native poll block. For answer buttons use { "type": "poll", "variant": "options", "question": "What did you think?", "options": [{ "label": "Loved it", "value": "loved" }, { "label": "Not for me", "value": "not_for_me" }], "attributeKey": "email_feedback" }. For NPS use { "type": "poll", "variant": "nps", "question": "How likely are you to recommend us?", "options": [], "attributeKey": "nps_score", "npsLowLabel": "Not likely", "npsHighLabel": "Very likely" }. `attributeKey` stores the latest response for segmentation. Optional `appearance` picks the answer style: "soft" (default), "pill", "outline", "filled", "pop" (hard-shadow boxes), "brutal" (square uppercase slabs), "quiz" (A/B/C letter badges), or "minimal" (bare ruled rows). Optional `confirmationMessage` customizes the hosted thank-you page; set `redirectUrl` only when respondents should land on another page.',PW=' 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" }.',Gb="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.",Rw='For exact historical Poll/NPS respondents, use field `pollResponse`, operator `is`, and a JSON value shaped like {"v":1,"campaignId":"camp_123","blockId":"poll_1","match":{"kind":"answer","value":"loved"}}. For NPS buckets, use match {"kind":"npsBucket","bucket":"promoters"}; bucket may be `promoters`, `passives`, or `detractors`.',Hw=`Sequenzy email blocks. Use this for editor-compatible content, including conditional and repeat blocks. For provider-migrated HTML from another email platform, prefer the \`html\` field instead; Sequenzy stores it as one raw HTML block to preserve the original design. Use \`styles\` for per-block background, background opacity, text color, padding, border radius, border width, and border color. Top-level style aliases such as \`backgroundColor\`, \`backgroundOpacity\`, \`borderColor\`, \`borderWidth\`, and \`borderRadius\` are also accepted and saved under \`styles\`. Repeat blocks use { type: 'repeat', source: 'items', itemAlias: 'item', children: [...] }.${LW}${UW}${PW}${x$}`,zw=`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\`.${LW}${UW}${PW}${x$}`,q1=`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.${LW}${UW}${PW}${x$}`,Y0="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.",SD="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.",BW=500,FW=500,pb={type:"boolean",description:"If true, include machine-classified bot/scanner opens and clicks. Defaults to false, so metrics and activity are human-only."},y$=["send","delivery","bounce","complaint","open","click","unsubscribe","delivery_delay"],h$={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},tK={type:"object",description:"Offset relative to a wait-until date.",properties:{days:{type:"number"},hours:{type:"number"},minutes:{type:"number"}},additionalProperties:!1},G1={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:tK,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},X1={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},KW={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; [] 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.",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. A standalone raw HTML email does not support this field, and emailPreset must not be combined with html/htmlContent."}},additionalProperties:!0},c$={type:"object",properties:{nodeId:{type:"string",description:"Existing node ID from get_sequence.sequence.nodes[].id."},changes:KW,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},Y1=["gray","red","orange","amber","yellow","lime","green","emerald","teal","cyan","sky","blue","indigo","violet","purple","fuchsia","pink","rose"],J1=["email.sent","email.delivered","email.delivery_delayed","email.bounced","email.complained","email.opened","email.clicked","email.replied","email.unsubscribed","sms.sent","sms.delivered","sms.failed","sms.opted_out","subscriber.invalid","subscriber.updated","subscriber.unsubscribed","subscriber.list_subscribed","subscriber.list_unsubscribed","sequence.finished","sequence.failed","poll.answered"];var rK=new Set(["get_account","get_app_urls","get_company","get_sync_rules","get_shopify_automation_settings","list_api_keys","list_websites","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_email_send","list_forms","get_form_embed","get_recipient_suppression","list_landing_pages","get_landing_page","list_sequences","get_sequence","list_sequence_goals","get_sequence_inbound_webhook","list_transactional_emails","get_transactional_email","get_stats","get_campaign_stats","get_sequence_stats","list_campaign_events","list_sequence_events","get_subscriber_activity","list_team_members","list_conversations","get_conversation","list_webhooks","list_webhook_deliveries","generate_email","generate_subject_lines","generate_sms","get_sms_settings"]),eK=new Set(["select_company","create_company","update_company","update_sync_rules","update_shopify_automation_settings","create_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","upsert_products","delete_product","attach_product_file","remove_product_file","upload_image_asset","sync_products","create_tag","update_tag","delete_tag","create_list","update_list","delete_list","add_subscribers_to_list","remove_subscribers_from_list","create_segment","update_segment","delete_segment","create_audience_sync","update_audience_sync","delete_audience_sync","sync_audience_now","create_template","update_template","set_template_localization","sync_template_localizations","delete_template","restart_ab_test","update_ab_test_variant","create_ab_test","add_ab_test_variant","delete_ab_test_variant","delete_ab_test","create_campaign","update_campaign","schedule_campaign","send_test_email","send_test_sms","cancel_campaign","pause_campaign","resume_campaign","delete_campaign","duplicate_campaign","resend_campaign_to_non_openers","create_form","create_landing_page","update_landing_page","delete_landing_page","publish_landing_page","unpublish_landing_page","connect_landing_page_domain","update_landing_page_domain_settings","create_sequence","generate_sequence","update_sequence","update_sequence_node","update_sequence_nodes","edit_sequence_graph","insert_sequence_step","enable_sequence","disable_sequence","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","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"]),sK=new Set(["send_test_email","send_test_sms","schedule_campaign","resume_campaign","publish_landing_page","connect_landing_page_domain","update_landing_page_domain_settings","add_sending_domain","add_website","verify_sending_domain","enable_sequence","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"]),aK=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","delete_segment","delete_audience_sync","delete_template","restart_ab_test","delete_ab_test_variant","delete_ab_test","cancel_campaign","delete_campaign","delete_landing_page","unpublish_landing_page","disable_sequence","archive_sequence","delete_sequence_goal","rotate_sequence_inbound_webhook_secret","edit_sequence_graph","cancel_sequence_enrollments","delete_sequence","cancel_team_invitation","delete_webhook","remove_recipient_suppression"]);function bM(b){let w=rK.has(b),$=eK.has(b);if(w===$)throw Error(`MCP tool "${b}" must be classified as exactly one of read-only or mutating.`);return{readOnlyHint:w,destructiveHint:w?!1:aK.has(b),openWorldHint:sK.has(b)}}function RD(b){return{...b,annotations:{...b.annotations,...bM(b.name)}}}var MW={status:["is","is_not"],phone:["is_not_empty","is_empty"],smsStatus:["is","is_not"],tag:["contains","not_contains","is_empty","is_not_empty"],email:["contains","not_contains"],emailProvider:["is","is_not","is_empty","is_not_empty"],added:["less_than","more_than"],firstName:["contains","not_contains","is_empty","is_not_empty"],lastName:["contains","not_contains","is_empty","is_not_empty"],list:["is","is_not","is_empty","is_not_empty"],emailSent:["is","is_not","at_least","less_than_count"],emailDelivered:["is","is_not","at_least","less_than_count"],emailOpened:["is","is_not","at_least","less_than_count"],emailClicked:["is","is_not","at_least","less_than_count"],emailBounced:["is","is_temporary_bounce","is_permanent_bounce","is_not","at_least","less_than_count"],emailComplained:["is","is_not","at_least","less_than_count"],attribute:["is","is_not","is_empty","is_not_empty","gte","lte","gt","lt","contains","not_contains"],event:["is","is_not","at_least","less_than_count"],pollResponse:["is"],segment:["is","is_not"],stripeProduct:["is","is_not","at_least","less_than_count"],stripeCurrentProduct:["is","is_not","gte","lte","gt","lt"],stripeTrialProduct:["is","is_not","gte","lte","gt","lt"],commerceProduct:["is","is_not","at_least","less_than_count"]},wM=Object.entries(MW).map(([b,w])=>`${b}: ${w.join(", ")}`).join("; "),IW={type:"object",properties:{id:{type:"string",description:"Optional filter ID. Any stable string works; one will be generated if omitted."},field:{type:"string",enum:["status","phone","smsStatus","tag","email","emailProvider","added","firstName","lastName","list","emailSent","emailDelivered","emailOpened","emailClicked","emailBounced","emailComplained","attribute","event","pollResponse","segment","stripeProduct","stripeCurrentProduct","stripeTrialProduct","commerceProduct"],description:`Filter field. Use \`phone\` with is_not_empty/is_empty to check whether a subscriber has a phone number, and \`smsStatus\` (is/is_not one of \`subscribed\`, \`unsubscribed\`, \`not_subscribed\`) for SMS marketing consent. Use \`event\` for custom subscriber events, \`segment\` for saved segment membership, \`stripeProduct\`/\`stripeCurrentProduct\`/\`stripeTrialProduct\` for Stripe product-based segments, and \`commerceProduct\` for products purchased through commerce orders - the value is \`provider:productId\` (provider one of \`shopify\`, \`woocommerce\`, \`api\`; product ids are provider-scoped), optionally with an order-count threshold (\`provider:productId:count\`) for at_least/less_than_count; a bare product id matches the id on any provider. Engagement fields (\`emailSent\`, \`emailDelivered\`, \`emailOpened\`, \`emailClicked\`, \`emailBounced\`, \`emailComplained\`) accept a time range as the value, a specific campaign via \`campaign:<campaign_id>\`, or \`count:timeRange\` (e.g. \`10:30d\`, \`10:all\`) with at_least/less_than_count to segment by number of opens/clicks. ${Rw}`},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: ${wM}.`},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). ${Rw}`}},required:["field","operator","value"],additionalProperties:!1},_W={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 f$(b){if(!Array.isArray(b))return b;return b.map((w)=>{if(typeof w!=="object"||w===null)return w;let $=w;if(typeof $.id==="string"&&$.id.trim()!=="")return $;return{...$,id:crypto.randomUUID()}})}function n$(b){if(typeof b!=="object"||b===null)return b;let w=b;if(w.kind==="filter"||"field"in w||"operator"in w||"value"in w){let $=f$([w]);return Array.isArray($)?$[0]:w}if(w.kind!=="group")return b;return{...w,id:typeof w.id==="string"&&w.id.trim()!==""?w.id:crypto.randomUUID(),children:Array.isArray(w.children)?w.children.map(n$):[]}}function $M(b){let w=b.indexOf(":");return w!==-1&&b.substring(0,w).trim().length>0}function WM(b){let w=b.indexOf(":");return w!==-1&&b.substring(w+1).trim().length>0}function vD(b){if(b==="all")return!0;let w=b.match(/^(\d+)d$/);if(!w?.[1])return!1;let $=Number.parseInt(w[1],10);return Number.isInteger($)&&$>0}function QM(b,w){let $=w.split(":");if(b==="at_least"||b==="less_than_count"){if($.length<3)return'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".';let q=$.slice(0,-2).join(":").trim(),G=$.at(-2),X=$.at(-1),Y=G===void 0?Number.NaN:Number.parseInt(G,10);return q&&Number.isInteger(Y)&&Y>0&&X!==void 0&&vD(X)?null:'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".'}if($.length<2)return'Event filters must use "eventName:timeRange", like "saas.purchase:30d".';let W=$.slice(0,-1).join(":").trim(),Q=$.at(-1);return W&&Q!==void 0&&vD(Q)?null:'Event filters must use "eventName:timeRange", like "saas.purchase:30d".'}function qM(b){let w=b.indexOf(":");if(w===-1)return{productId:b,subfilter:null,rawValue:null};let $=b.substring(0,w),W=b.substring(w+1),Q=W.indexOf(":");if(Q===-1)return{productId:$,subfilter:W,rawValue:null};return{productId:$,subfilter:W.substring(0,Q),rawValue:W.substring(Q+1)}}function GM(b){return b.trim().toLowerCase().replace(/[-\s]+/g,"_")}function XM(b){return["is_canceled","is_cancelled","canceled","cancelled","will_cancel","cancel_at_period_end","is_not_canceled","is_not_cancelled","not_canceled","not_cancelled","will_not_cancel"].includes(b)}function YM(b,w){if(w==="cancels_at"||w==="cancel_at"||w==="cancellation_at")return!0;if(b==="stripeCurrentProduct")return["end_at","ends_at","period_end","period_ends_at","current_period_end"].includes(w);return["start_at","started_at","trial_start","trial_started_at","end_at","ends_at","trial_end","trial_ends_at"].includes(w)}function JM(b){return["is","is_not","gte","lte","gt","lt"].includes(b)}function DM(b,w,$){if(b==="stripeProduct"){if(w!=="at_least"&&w!=="less_than_count")return null;let X=$.indexOf(":");if(X===-1)return null;let Y=$.substring(0,X).trim(),J=Number.parseInt($.substring(X+1).trim(),10);return Y&&Number.isInteger(J)&&J>=1?null:'Stripe Product threshold filters must use "productId:count" with a count of at least 1.'}if(b!=="stripeCurrentProduct"&&b!=="stripeTrialProduct")return null;let{productId:W,subfilter:Q,rawValue:q}=qM($);if(!W.trim())return"Stripe product filters must include a product ID.";if(!Q)return w==="is"||w==="is_not"?null:'Stripe current/trial date filters must use "productId:dateField:value".';let G=GM(Q);if(XM(G))return w==="is"||w==="is_not"?null:"Stripe cancellation flag filters only support is and is_not operators.";if(!YM(b,G))return`Unsupported Stripe product subfilter "${Q}".`;if(!JM(w))return"Stripe date filters only support is, is_not, gte, lte, gt, and lt operators.";return q?.trim()?null:'Stripe date filters must include a value like "productId:end_at:2026-05-26".'}var HM=new Set(["shopify","woocommerce","api"]);function zM(b,w){let $=w.trim(),W=$.indexOf(":");if(W!==-1&&HM.has($.substring(0,W).trim()))$=$.substring(W+1).trim();if(!$)return'Purchased Product filters must include a product ID, like "shopify:42".';if(b!=="at_least"&&b!=="less_than_count")return null;let Q=$.lastIndexOf(":");if(Q===-1)return null;let q=$.substring(0,Q).trim(),G=Number.parseInt($.substring(Q+1).trim(),10);return q&&Number.isInteger(G)&&G>=1?null:'Purchased Product threshold filters must use "provider:productId:count" with a count of at least 1.'}function OM(b){let w;try{w=JSON.parse(b)}catch{return`Poll response filters must use valid JSON. ${Rw}`}if(!k(w)||w.v!==1||typeof w.campaignId!=="string"||!w.campaignId.trim()||typeof w.blockId!=="string"||!w.blockId.trim()||!k(w.match))return`Poll response filter context is invalid. ${Rw}`;let $=w.match;if($.kind==="answer"&&typeof $.value==="string"&&$.value.length>0)return null;if($.kind==="npsBucket"&&($.bucket==="promoters"||$.bucket==="passives"||$.bucket==="detractors"))return null;return`Poll response filter match is invalid. ${Rw}`}function i$(b){if(typeof b!=="object"||b===null)return"Segment filters must be objects.";let w=b,$=w.field,W=w.operator,Q=w.value;if(typeof $!=="string"||!($ in MW))return`Unsupported segment filter field "${String($)}".`;if(typeof W!=="string")return`Segment filter "${$}" must include an operator.`;let q=MW[$];if(!q.includes(W))return`Operator "${W}" is not supported for ${$} filters. Use one of: ${q.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(!$M(Q))return'Attribute filters must use "attributeName:value" or "attributeName:" for empty checks.';if(W!=="is_empty"&&W!=="is_not_empty"&&!WM(Q))return'Attribute filters must include a value after "attributeName:".'}if($==="event"&&typeof Q==="string"){let G=QM(W,Q);if(G)return G}if($==="pollResponse"&&typeof Q==="string"){let G=OM(Q);if(G)return G}if(($==="stripeProduct"||$==="stripeCurrentProduct"||$==="stripeTrialProduct")&&typeof Q==="string"){let G=DM($,W,Q);if(G)return G}if($==="commerceProduct"&&typeof Q==="string"){let G=zM(W,Q);if(G)return G}if($==="tag"&&(W==="contains"||W==="not_contains")){if(!(typeof Q==="string"&&Q.split(",").map((X)=>X.trim()).some(Boolean)))return"Tag filters must include at least one tag name."}return null}function m$(b){if(typeof b!=="object"||b===null)return[];let w=b;if(w.kind==="filter"||"field"in w||"operator"in w||"value"in w){let $=i$(w);return $?[$]:[]}if(Array.isArray(w.children))return w.children.flatMap(m$);return[]}function Sb(b,w,$){if(w.html!==void 0&&w.blocks!==void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${b}\`, not both.`);if(w.blocks!==void 0&&!Array.isArray(w.blocks))throw Error(`\`blocks\` must be an array when calling \`${b}\`.`);if($?.requireContent&&w.html===void 0&&w.blocks===void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${b}\`.`)}function Ow(b,w){if(w.labels===void 0)return;if(!Array.isArray(w.labels))throw Error(`\`labels\` must be an array when calling \`${b}\`.`);if(w.labels.some(($)=>typeof $!=="string"||$.trim().length===0))throw Error(`\`labels\` must contain only non-empty strings when calling \`${b}\`.`)}function uD(b){let w=b.filters!==void 0,$=b.root!==void 0;if(w&&$)throw Error("Provide either `filters` or `root` when calling `create_segment`, not both.");if(!w&&!$)throw Error("Provide either `filters` or `root` when calling `create_segment`.");if(w){if(!Array.isArray(b.filters))throw Error("`filters` must be an array when calling `create_segment`.");if(b.filters.length===0)throw Error("`filters` must include at least one filter when calling `create_segment`.")}if($&&(typeof b.root!=="object"||b.root===null))throw Error("`root` must be an object when calling `create_segment`.");let W=w?b.filters.flatMap((Q)=>{let q=i$(Q);return q?[q]:[]}):m$(b.root);if(W.length>0)throw Error(W[0]??"Invalid segment filter in `create_segment`.")}function xD(b){let w=b.filters!==void 0,$=b.root!==void 0;if(w&&$)throw Error("Provide either `filters` or `root` when calling `update_segment`, not both.");if(b.name===void 0&&b.filterJoinOperator===void 0&&!w&&!$)throw Error("Provide at least one of `name`, `filters`, `root`, or `filterJoinOperator` when calling `update_segment`.");if(w){if(!Array.isArray(b.filters))throw Error("`filters` must be an array when calling `update_segment`.");if(b.filters.length===0)throw Error("`filters` must include at least one filter when calling `update_segment`.")}if($&&(typeof b.root!=="object"||b.root===null))throw Error("`root` must be an object when calling `update_segment`.");let W=w?b.filters.flatMap((Q)=>{let q=i$(Q);return q?[q]:[]}):$?m$(b.root):[];if(W.length>0)throw Error(W[0]??"Invalid segment filter in `update_segment`.")}var jW=["name","description","logoUrl","founderName","primaryColor","brandColors","valueProps","testimonials","toneVoice","companyContext","emailLengthPreference","socialLinks","privacyPolicyUrl","termsUrl","address","language","pricing","fontFamily","emailTheme","emailDirection","fromEmail","fromName","replyTo","replyToName","replyTrackingEnabled","replyTrackingDomainMode","forwardReplies"];function ZW(b,w,$){if(w[$]!==void 0&&!k(w[$]))throw Error(`\`${$}\` must be an object when calling \`${b}\`.`)}function kD(b,w,$){if(w[$]!==void 0&&!Array.isArray(w[$]))throw Error(`\`${$}\` must be an array when calling \`${b}\`.`)}function yD(b){let w=new Set(["companyId",...jW]),$=Object.keys(b).filter((Q)=>!w.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 jW)if(b[Q]!==void 0)W[Q]=b[Q];if(Object.keys(W).length===0)throw Error(`Provide at least one of ${jW.map((Q)=>`\`${Q}\``).join(", ")} when calling \`update_company\`.`);for(let Q of["name","description","logoUrl","founderName","primaryColor","toneVoice","companyContext","emailLengthPreference","privacyPolicyUrl","termsUrl","address","language","fontFamily","emailDirection","fromEmail","fromName","replyTo","replyToName","replyTrackingDomainMode"])if(b[Q]!==void 0&&typeof b[Q]!=="string")throw Error(`\`${Q}\` must be a string when calling \`update_company\`.`);if(ZW("update_company",b,"brandColors"),ZW("update_company",b,"socialLinks"),ZW("update_company",b,"pricing"),b.emailTheme!==void 0&&b.emailTheme!==null&&!k(b.emailTheme))throw Error("`emailTheme` must be an object or null when calling `update_company`.");kD("update_company",b,"valueProps"),kD("update_company",b,"testimonials");for(let Q of["replyTrackingEnabled","forwardReplies"])if(b[Q]!==void 0&&typeof b[Q]!=="boolean")throw Error(`\`${Q}\` must be a boolean when calling \`update_company\`.`);if(b.replyTrackingDomainMode!==void 0&&b.replyTrackingDomainMode!=="sequenzy"&&b.replyTrackingDomainMode!=="custom")throw Error("`replyTrackingDomainMode` must be `sequenzy` or `custom` when calling `update_company`.");if(typeof b.primaryColor==="string"&&!/^#[0-9a-f]{6}$/i.test(b.primaryColor.trim()))throw Error("`primaryColor` must be a 6-digit hex color such as #f97316 when calling `update_company`.");for(let Q of["fromEmail","replyTo"]){let q=b[Q];if(typeof q==="string"&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(q.trim()))throw Error(`\`${Q}\` must be a valid email address when calling \`update_company\`.`)}if(b.fromName!==void 0&&b.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `update_company`.");if(b.replyToName!==void 0&&b.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `update_company`.");return W}var hD=["senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName"];function AM(b){return hD.some((w)=>b[w]!==void 0)}function LM(b){if(typeof b.nodeType==="string")return b.nodeType==="action_email";return b.type===void 0||b.type==="email"}function l$(b,w,$){for(let W of hD){let Q=$[W];if(Q!==void 0&&typeof Q!=="string")throw Error(`\`${W}\` must be a string for ${w} when calling \`${b}\`.`)}if($.senderProfileId!==void 0&&$.fromEmail!==void 0)throw Error(`Provide either \`senderProfileId\` or \`fromEmail\` for ${w} when calling \`${b}\`, not both.`);if($.replyProfileId!==void 0&&$.replyTo!==void 0)throw Error(`Provide either \`replyProfileId\` or \`replyTo\` for ${w} when calling \`${b}\`, not both.`);if($.replyToName!==void 0&&$.replyTo===void 0)throw Error(`\`replyToName\` requires \`replyTo\` for ${w} when calling \`${b}\`.`)}function NW(b,w,$){if(AM($)&&!LM($))throw Error(`Sender identity fields are only supported for email steps at ${w} when calling \`${b}\`.`);l$(b,w,$)}function CD(b,w,$){if(!Array.isArray($))return;$.forEach((W,Q)=>{if(k(W))l$(b,`${w}[${Q}]`,W)})}function VW(b,w,$){if(!Array.isArray($))return;$.forEach((W,Q)=>{if(k(W))NW(b,`${w}[${Q}]`,W)})}function UM(b){if(CD("update_sequence","emails",b.emails),CD("update_sequence","steps",b.steps),k(b.insertSteps))VW("update_sequence","insertSteps.steps",b.insertSteps.steps);if(!k(b.branch))return;if(Array.isArray(b.branch.branches))b.branch.branches.forEach(($,W)=>{if(k($))VW("update_sequence",`branch.branches[${W}].steps`,$.steps)});VW("update_sequence","branch.elseSteps",b.branch.elseSteps)}function cD(b){Ow("update_sequence",b);let w=["listId","tagName","segmentId","stopOnSegmentExit","eventName","propertyFilters","integrationSlug","integrationEventKey","customIntegration","inactiveDays","inactivityBaseline","minCount","timeWindowDays"];if(b.trigger===void 0&&w.some((W)=>b[W]!==void 0))throw Error("Provide `trigger` when replacing sequence trigger configuration with `update_sequence`.");if(b.fromEmail!==void 0&&b.senderProfileId!==void 0)throw Error("Provide either `fromEmail` or `senderProfileId` when calling `update_sequence`, not both.");if(b.replyTo!==void 0&&b.replyProfileId!==void 0)throw Error("Provide either `replyTo` or `replyProfileId` when calling `update_sequence`, not both.");if(b.fromName!==void 0&&b.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `update_sequence`.");if(b.replyToName!==void 0&&b.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `update_sequence`.");if(b.clearEnrollmentFieldPath===!0&&b.enrollmentFieldPath!==void 0)throw Error("Provide either `enrollmentFieldPath` or `clearEnrollmentFieldPath` when calling `update_sequence`, not both.");if(b.clearSendingWindow===!0&&b.sendingWindow!==void 0)throw Error("Provide either `sendingWindow` or `clearSendingWindow` when calling `update_sequence`, not both.");if(b.clearBccEmails===!0&&b.bccEmails!==void 0)throw Error("Provide either `bccEmails` or `clearBccEmails` when calling `update_sequence`, not both.");if(b.branch!==void 0&&b.insertSteps!==void 0)throw Error("Provide either `branch` or `insertSteps` when calling `update_sequence`, not both.");UM(b);let $={...b};if(delete $.clearEnrollmentFieldPath,delete $.clearSendingWindow,delete $.clearBccEmails,b.clearEnrollmentFieldPath===!0)$.enrollmentFieldPath=null;if(b.clearSendingWindow===!0)$.sendingWindow=null;if(b.clearBccEmails===!0)$.bccEmails=null;return $}function PM(b,w){if((w.triggerType??"event")==="event"){if(typeof w.triggerEventName!=="string"||w.triggerEventName.trim().length===0)throw Error(`\`triggerEventName\` is required when calling \`${b}\` with an event goal (the default \`triggerType\`).`);return}if(typeof w.attributePath!=="string"||w.attributePath.trim().length===0)throw Error(`\`attributePath\` is required when calling \`${b}\` with \`triggerType: "attribute_change"\`.`);let W=w.attributeCondition??"changed",Q=typeof w.attributeValue==="string"&&w.attributeValue.trim().length>0,q=typeof w.attributePreviousValue==="string"&&w.attributePreviousValue.trim().length>0;if((W==="changed_to"||W==="changed_from_to")&&!Q)throw Error(`\`attributeValue\` is required when calling \`${b}\` with \`attributeCondition\` \`changed_to\` or \`changed_from_to\`.`);if(W==="changed_from_to"&&!q)throw Error(`\`attributePreviousValue\` is required when calling \`${b}\` with \`attributeCondition: "changed_from_to"\`.`)}function fD(b){PM("create_sequence_goal",b)}function nD(b){if(typeof b.triggerEventName==="string"&&b.triggerEventName.trim().length===0)throw Error("`triggerEventName` must be a non-empty string when provided to `update_sequence_goal`.");if(typeof b.attributePath==="string"&&b.attributePath.trim().length===0)throw Error("`attributePath` must be a non-empty string when provided to `update_sequence_goal`.")}function iD(b,w,$){let W=M(b,w,"nodeId");if(!k(w.changes)||Object.keys(w.changes).length===0)throw Error(`\`changes\` must be a non-empty object for ${$} when calling \`${b}\`.`);let Q=M(b,w,"expectedUpdatedAt");return{nodeId:W,changes:w.changes,expectedUpdatedAt:Q}}function mD(b){let w=iD("update_sequence_node",b,"the node update");return{...b.confirmLiveChange!==void 0&&{confirmLiveChange:b.confirmLiveChange},nodeUpdates:[w]}}function lD(b){if(!Array.isArray(b.updates)||b.updates.length===0)throw Error("`updates` must be a non-empty array when calling `update_sequence_nodes`.");let w=new Set,$=b.updates.map((W,Q)=>{if(!k(W))throw Error(`\`updates[${Q}]\` must be an object when calling \`update_sequence_nodes\`.`);let q=iD("update_sequence_nodes",W,`updates[${Q}]`),G=String(q.nodeId);if(w.has(G))throw Error(`\`updates[${Q}]\` targets duplicate nodeId '${G}' when calling \`update_sequence_nodes\`.`);return w.add(G),q});return{...b.confirmLiveChange!==void 0&&{confirmLiveChange:b.confirmLiveChange},nodeUpdates:$}}function gD(b){let w=M("edit_sequence_graph",b,"action"),$=M("edit_sequence_graph",b,"graphRevision");if(!new Set(["move_node","delete_node","duplicate_node","replace_edges"]).has(w))throw Error("`action` must be `move_node`, `delete_node`, `duplicate_node`, or `replace_edges` when calling `edit_sequence_graph`.");let Q=L(b,"nodeId"),q=L(b,"afterNodeId"),G=L(b,"beforeNodeId"),X=b.edges;if(w!=="replace_edges"&&!Q)throw Error(`\`nodeId\` is required for ${w} when calling \`edit_sequence_graph\`.`);if(w==="replace_edges"&&Q)throw Error("`nodeId` is not used with `replace_edges` when calling `edit_sequence_graph`.");let Y=w==="move_node"||w==="duplicate_node";if(Y&&(q?1:0)+(G?1:0)!==1)throw Error(`Provide exactly one of \`afterNodeId\` or \`beforeNodeId\` for ${w} when calling \`edit_sequence_graph\`.`);if(!Y&&(q||G))throw Error(`\`afterNodeId\` and \`beforeNodeId\` are not used with ${w} when calling \`edit_sequence_graph\`.`);if((w==="replace_edges"||w==="delete_node"&&X!==void 0)&&(!Array.isArray(X)||X.length===0))throw Error(`\`edges\` must contain the complete replacement topology for ${w} when calling \`edit_sequence_graph\`.`);if((w==="move_node"||w==="duplicate_node")&&X!==void 0)throw Error(`\`edges\` is not used with ${w} when calling \`edit_sequence_graph\`.`);let J=Array.isArray(X)?X.map((D,H)=>{if(!k(D))throw Error(`\`edges\` item ${H+1} must be an object when calling \`edit_sequence_graph\`.`);let O=M("edit_sequence_graph",D,"sourceNodeId"),A=M("edit_sequence_graph",D,"targetNodeId");if(D.condition!==void 0&&D.condition!==null&&!k(D.condition))throw Error(`\`edges\` item ${H+1} \`condition\` must be an object when calling \`edit_sequence_graph\`.`);return{sourceNodeId:O,targetNodeId:A,...k(D.condition)?{condition:D.condition}:{}}}):void 0;return{...b.confirmStructuralChange!==void 0&&{confirmStructuralChange:b.confirmStructuralChange},graphEdit:{action:w,expectedRevision:$,...Q?{nodeId:Q}:{},...q?{afterNodeId:q}:{},...G?{beforeNodeId:G}:{},...J?{edges:J}:{}}}}function pD(b){let w=L(b,"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(w))throw Error("`type` is not a supported dashboard sequence step when calling `insert_sequence_step`.");if(w==="logic_wait_for_event"){let G=M("insert_sequence_step",b,"eventName"),X=b.timeoutDays,Y=X===void 0?7:X;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 J=L(b,"timeoutAction")??"continue";if(J!=="continue"&&J!=="exit")throw Error("`timeoutAction` must be `continue` or `exit` when inserting `logic_wait_for_event` with `insert_sequence_step`.");let D={steps:[{nodeType:"logic_wait_for_event",config:{label:L(b,"label")??`Wait for ${G}`,eventName:G,timeoutDays:Y,timeoutAction:J}}]},H=L(b,"afterNodeId");if(H)D.afterNodeId=H;return{...b.confirmStructuralChange!==void 0&&{confirmStructuralChange:b.confirmStructuralChange},insertSteps:D}}if(w==="logic_branch"){let G=M("insert_sequence_step",b,"afterNodeId");if(!Array.isArray(b.branches)||b.branches.length===0)throw Error("`branches` must contain at least one typed condition when inserting `logic_branch` with `insert_sequence_step`.");let X=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"],J=b.allowEmptyPaths===!0,D=b.branches.map((A,B)=>{if(!k(A))throw Error(`\`branches[${B}]\` must be an object when calling \`insert_sequence_step\`.`);let K=M("insert_sequence_step",A,"conditionType");if(!X.has(K))throw Error(`\`branches[${B}].conditionType\` is not supported when calling \`insert_sequence_step\`.`);let _=`branches[${B}]`;if((K==="has_tag"||K==="does_not_have_tag")&&!L(A,"tagId")&&!L(A,"tagName"))throw Error(`\`${_}\` must provide \`tagId\` or \`tagName\` for ${K} when calling \`insert_sequence_step\`.`);if(K==="in_list"&&!L(A,"listId"))throw Error(`\`${_}.listId\` is required for in_list when calling \`insert_sequence_step\`.`);if(K==="in_segment"&&!L(A,"segmentId"))throw Error(`\`${_}.segmentId\` is required for in_segment when calling \`insert_sequence_step\`.`);if(K==="event_received"&&!L(A,"eventName"))throw Error(`\`${_}.eventName\` is required for event_received when calling \`insert_sequence_step\`.`);if(K.startsWith("field_")&&(!L(A,"fieldName")||!L(A,"fieldValue")))throw Error(`\`${_}\` must provide \`fieldName\` and \`fieldValue\` for ${K} when calling \`insert_sequence_step\`.`);if(A.steps!==void 0&&!Array.isArray(A.steps))throw Error(`\`branches[${B}].steps\` must be an array when calling \`insert_sequence_step\`.`);let I=L(A,"targetNodeId"),R=Array.isArray(A.steps)&&A.steps.length>0;if(!I&&!R&&!J)throw Error(`\`branches[${B}]\` must provide \`targetNodeId\` or non-empty \`steps\` when inserting \`logic_branch\` with \`insert_sequence_step\`.`);return Object.fromEntries(Y.flatMap((T)=>A[T]===void 0?[]:[[T,A[T]]]))});if(b.elseSteps!==void 0&&!Array.isArray(b.elseSteps))throw Error("`elseSteps` must be an array when calling `insert_sequence_step`.");let H=L(b,"elseTargetNodeId"),O=Array.isArray(b.elseSteps)&&b.elseSteps.length>0;if(!H&&!O&&!J)throw Error("Provide `elseTargetNodeId` or non-empty `elseSteps` when inserting `logic_branch` with `insert_sequence_step`.");return{...b.confirmStructuralChange!==void 0&&{confirmStructuralChange:b.confirmStructuralChange},branch:{afterNodeId:G,...L(b,"label")?{label:L(b,"label")}:{},branches:D,...Array.isArray(b.elseSteps)?{elseSteps:b.elseSteps}:{},...H?{elseTargetNodeId:H}:{},...J?{allowEmptyPaths:!0}:{}}}}if(w==="delay"||w==="create_discount"||w==="update_subscriber"||w==="condition"||w==="add_tag"||w==="remove_tag"||w==="add_to_list"||w==="remove_from_list"||w==="webhook"){let G;if(w==="delay"){G={type:"delay"};for(let J of["delay","delayMs","waitUntil"])if(b[J]!==void 0)G[J]=b[J];if(G.delay===void 0&&G.delayMs===void 0&&G.waitUntil===void 0)throw Error("Provide `delay`, `delayMs`, or `waitUntil` when inserting a delay step.")}else if(w==="create_discount"){G={type:"create_discount"};for(let J of["discount","label","provider","discountType","percentOff","amountOff","currency","duration","durationInMonths","appliesToAllPlans","planIds","codePrefix","maxRedemptions","lockToSubscriber","expiresAt","expiresInHours"])if(b[J]!==void 0)G[J]=b[J]}else if(w==="update_subscriber"){if(!k(b.config))throw Error("`config` is required when inserting an update_subscriber step.");G={type:"update_subscriber",nodeType:"action_update_attributes",config:b.config}}else if(w==="webhook"){let J=L(b,"method")??"POST";if(J!=="POST"&&J!=="GET")throw Error("`method` must be `POST` or `GET` when inserting a webhook step.");if(b.headers!==void 0&&(!k(b.headers)||Object.values(b.headers).some((D)=>typeof D!=="string")))throw Error("`headers` must be an object with string values when inserting a webhook step.");G={type:"webhook",nodeType:"action_webhook",config:{label:L(b,"label")??"Webhook",url:M("insert_sequence_step",b,"url"),method:J,...b.headers!==void 0?{headers:b.headers}:{}}}}else if(w==="condition"){let J=M("insert_sequence_step",b,"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(J))throw Error("`conditionType` is not supported for condition steps.");if((J==="has_tag"||J==="does_not_have_tag")&&!L(b,"tagId")&&!L(b,"tagName"))throw Error("Provide `tagId` or `tagName` for this condition step.");if(J==="in_list"&&!L(b,"listId"))throw Error("`listId` is required for an in_list condition.");if(J==="in_segment"&&!L(b,"segmentId"))throw Error("`segmentId` is required for an in_segment condition.");if(J==="event_received"&&!L(b,"eventName"))throw Error("`eventName` is required for an event_received condition.");if(J.startsWith("field_")&&(!L(b,"fieldName")||!L(b,"fieldValue")))throw Error("`fieldName` and `fieldValue` are required for field conditions.");let H={label:L(b,"label")??"Condition",conditionType:J};for(let O of["tagId","tagName","listId","segmentId","segmentName","eventName","linkUrl","activityScope","fieldName","fieldValue"])if(b[O]!==void 0)H[O]=b[O];G={type:"condition",nodeType:"logic_condition",config:H}}else{let J=w==="add_tag"||w==="remove_tag",D=w==="add_tag"?"action_add_tag":w==="remove_tag"?"action_remove_tag":w==="add_to_list"?"action_add_to_list":"action_remove_from_list",H={label:L(b,"label")??(w==="add_tag"?"Add Tag":w==="remove_tag"?"Remove Tag":w==="add_to_list"?"Add to List":"Remove from List")};if(J){let O=L(b,"tagId"),A=L(b,"tagName");if(!O&&!A)throw Error("Provide `tagId` or `tagName` when inserting a tag action.");if(O)H.tagId=O;if(A)H.tagName=A}else{H.listId=M("insert_sequence_step",b,"listId");let O=L(b,"listName");if(O)H.listName=O}G={nodeType:D,config:H}}for(let J of["delay","delayMs","waitUntil"])if(w!=="delay"&&b[J]!==void 0)G[J]=b[J];let X={steps:[G]},Y=L(b,"afterNodeId");if(Y)X.afterNodeId=Y;return{...b.confirmStructuralChange!==void 0&&{confirmStructuralChange:b.confirmStructuralChange},insertSteps:X}}let W=w==="sms",Q;if(W){NW("insert_sequence_step","SMS step",b);let G=L(b,"text"),X=Array.isArray(b.blocks)&&b.blocks.length>0;if(G===void 0&&!X)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(b[Y]!==void 0)Q[Y]=b[Y]}else{Sb("insert_sequence_step",b,{requireContent:!0}),l$("insert_sequence_step","email step",b),Q={subject:M("insert_sequence_step",b,"subject")};for(let G of["name","previewText","html","blocks","delay","delayMs","waitUntil","senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName","isTransactional","ccEmails","bccEmails","attachments"])if(b[G]!==void 0)Q[G]=b[G]}let q={steps:[Q]};if(b.afterNodeId!==void 0)q.afterNodeId=b.afterNodeId;return{...b.confirmStructuralChange!==void 0&&{confirmStructuralChange:b.confirmStructuralChange},insertSteps:q}}function oD(b){let w=L(b,"subscriberId"),$=b.fieldValues,W=$===void 0?void 0:Array.isArray($)?$:void 0;if($!==void 0&&W===void 0)throw Error("`fieldValues` must be an array when calling `cancel_sequence_enrollments`.");let Q=W?.map((X)=>typeof X==="string"?X.trim():"").filter((X)=>X.length>0)??[];if(W?.some((X)=>typeof X!=="string")||W!==void 0&&Q.length===0)throw Error("`fieldValues` must contain at least one non-empty string when calling `cancel_sequence_enrollments`.");if(w!==void 0===Q.length>0)throw Error("Provide exactly one target when calling `cancel_sequence_enrollments`: `subscriberId` or `fieldValues`.");let q=L(b,"fieldPath"),G=L(b,"reason");return{...w!==void 0&&{subscriberId:w},...q!==void 0&&{fieldPath:q},...Q.length>0&&{fieldValues:Q},...typeof b.dryRun==="boolean"&&{dryRun:b.dryRun},...G!==void 0&&{reason:G}}}function dD(b){Sb("create_campaign",b),Ow("create_campaign",b);let w=L(b,"prompt")!==void 0,$=b.html!==void 0,W=b.blocks!==void 0,Q=b.templateId!==void 0;if(b.prompt!==void 0&&!w)throw Error("`prompt` cannot be empty when calling `create_campaign`.");if(w&&($||W||Q))throw Error("Provide either `prompt`, `html`, `blocks`, or `templateId` when calling `create_campaign`, not multiple content sources.");if(!w&&(b.style!==void 0||b.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_campaign`.");if(!w&&L(b,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_campaign`.")}function tD(b){Sb("create_template",b),Ow("create_template",b);let w=L(b,"prompt")!==void 0,$=[w,b.html!==void 0,b.blocks!==void 0].filter(Boolean).length;if(b.prompt!==void 0&&!w)throw Error("`prompt` cannot be empty when calling `create_template`.");if($!==1)throw Error("Provide exactly one of `prompt`, `html`, or `blocks` when calling `create_template`.");if(!w&&(b.style!==void 0||b.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_template`.");if(!w&&L(b,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_template`.")}function rD(b){if(L(b,"scheduledAt")===void 0)throw Error("`scheduledAt` is required when calling `schedule_campaign`.");if(b.targetLists!==void 0&&!k(b.targetLists))throw Error("`targetLists` must be an object when calling `schedule_campaign`.");if(b.sendTimeOptimization!==void 0){if(typeof b.sendTimeOptimization!=="boolean")throw Error("`sendTimeOptimization` must be a boolean when calling `schedule_campaign`.")}if(b.spreadOverHours!==void 0){if(typeof b.spreadOverHours!=="number"||!Number.isInteger(b.spreadOverHours)||b.spreadOverHours<1||b.spreadOverHours>72)throw Error("`spreadOverHours` must be an integer between 1 and 72 when calling `schedule_campaign`.")}if(b.recurringInterval!==void 0&&b.recurringInterval!=="weekly"&&b.recurringInterval!=="monthly")throw Error("`recurringInterval` must be 'weekly' or 'monthly' when calling `schedule_campaign`.")}function g$(b,w,$){let W=new Set(["companyId","landingPageId","name","slug","content"]),Q=Object.keys(w).filter((q)=>!W.has(q));if(Q.length>0)throw Error(`\`${b}\` accepts only \`name\`, \`slug\`, and \`content\` update fields. Unsupported field${Q.length===1?"":"s"}: ${Q.map((q)=>`\`${q}\``).join(", ")}.`);if($.requireUpdate&&w.name===void 0&&w.slug===void 0&&w.content===void 0)throw Error(`Provide at least one of \`name\`, \`slug\`, or \`content\` when calling \`${b}\`.`);return{...w.name!==void 0&&{name:w.name},...w.slug!==void 0&&{slug:w.slug},...w.content!==void 0&&{content:w.content}}}function eD(b){let w=new Set(["companyId","domain","verify"]),$=Object.keys(b).filter((W)=>!w.has(W));if($.length>0)throw Error(`\`update_landing_page_domain_settings\` accepts only \`domain\` and \`verify\`. Unsupported field${$.length===1?"":"s"}: ${$.map((W)=>`\`${W}\``).join(", ")}.`);if(b.domain===void 0&&b.verify!==!0)throw Error("Provide `domain` or `verify: true` when calling `update_landing_page_domain_settings`.");return{...b.domain!==void 0&&{domain:b.domain},...typeof b.verify==="boolean"&&{verify:b.verify}}}function sD(b){Sb("create_transactional_email",b);let w=L(b,"prompt")!==void 0,$=b.html!==void 0,W=b.blocks!==void 0;if(b.prompt!==void 0&&!w)throw Error("`prompt` cannot be empty when calling `create_transactional_email`.");if(w&&($||W))throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`, not multiple content sources.");if(!w&&(b.style!==void 0||b.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_transactional_email`.");if(!w&&!$&&!W)throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`.");if(!w&&L(b,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_transactional_email`.")}var D1={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},J0={senderProfileId:{type:"string",description:"Sender profile for this step's From identity. Mutually exclusive with fromEmail."},fromEmail:{type:"string",description:"From address for this step. Its domain must be configured and verified. Mutually exclusive with senderProfileId."},fromName:{type:"string",description:"Display name override for this step. Alone it only changes the visible name; with fromEmail it also names a newly created sender profile."},replyProfileId:{type:"string",description:"Reply profile for this step's Reply-To. Mutually exclusive with replyTo."},replyTo:{type:"string",description:"Reply-To address for this step. Mutually exclusive with replyProfileId."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo."}},D0={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."},config:{...D1,description:"Config for advanced nodeType steps. For action_update_attributes, use the documented Update Subscriber fields and trigger-event merge tags; other node types accept their normal config fields.",additionalProperties:!0},subject:{type:"string",description:"Email subject. Required for email steps."},previewText:{type:"string",description:"Email preview text."},blocks:{type:"array",description:q1,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); each file is fetched from its public HTTPS URL 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:X1,delayMs:{type:"number",description:"Delay in milliseconds. Useful for standalone type:'delay' steps."},waitUntil:G1,name:{type:"string",description:"Email template name for email steps."},senderProfileId:{type:"string",description:"Sender profile for this email step. Omit to inherit the effective identity of the nearest sequence email. After a branch merge, only fields shared by every incoming path are inherited; conflicting fields use sequence or company defaults."},fromEmail:{type:"string",description:"From address for this email step. Its domain must be verified. Mutually exclusive with senderProfileId."},fromName:{type:"string",description:"Display name override for this email step. With fromEmail, also names a newly created sender profile."},replyProfileId:{type:"string",description:"Reply profile for this email step. Omit to inherit the effective Reply-To of the nearest sequence email. After a branch merge, only fields shared by every incoming path are inherited; conflicting fields use sequence or company defaults."},replyTo:{type:"string",description:"Reply-To address for this email step. Mutually exclusive with replyProfileId."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo."},discount:{type:"object",description:"Discount configuration for create_discount steps. Same shape as create_sequence steps.",additionalProperties:!0},label:{type:"string",description:"Node label for discount or advanced node steps."},provider:{type:"string",enum:["stripe","shopify"],description:"Discount provider. Use stripe to dynamically create a Stripe coupon plus promotion code, or shopify to dynamically create a Shopify Admin discount code."},discountType:{type:"string",enum:["percent","amount"]},percentOff:{type:"number"},amountOff:{type:"number"},currency:{type:"string"},duration:{type:"string",enum:["once","forever","repeating"]},durationInMonths:{type:"number"},appliesToAllPlans:{type:"boolean"},planIds:{type:"array",items:{type:"string"}},codePrefix:{type:"string"},maxRedemptions:{type:"number"},lockToSubscriber:{type:"boolean"},expiresAt:{type:"string"},expiresInHours:{type:"number"}},additionalProperties:!1},EW={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:D0}},required:["conditionType"],additionalProperties:!1};function aD(b){if(!b||typeof b!=="object")return null;let w=b;if(w.success!==!1)return null;if(typeof w.error==="string")return Error(w.error);if(w.error&&typeof w.error==="object"&&typeof w.error.message==="string")return Error(w.error.message);if(typeof w.message==="string")return Error(w.message);return Error("The tool returned an unsuccessful response.")}function TW(b){return b.trim().toLowerCase().replace(/\s+/g,"-")}function BM(b){let w=new URLSearchParams;if(typeof b.query==="string"&&b.query.trim()!=="")w.set("query",b.query.trim());if(Array.isArray(b.tags)&&b.tags.length>0)w.set("tags",b.tags.filter(($)=>typeof $==="string"&&$.trim()!=="").join(","));if(typeof b.list==="string"&&b.list.trim()!=="")w.set("list",b.list.trim());if(typeof b.listId==="string"&&b.listId.trim()!=="")w.set("listId",b.listId.trim());if(typeof b.listName==="string"&&b.listName.trim()!=="")w.set("listName",b.listName.trim());if(typeof b.segmentId==="string"&&b.segmentId.trim()!=="")w.set("segmentId",b.segmentId);if(typeof b.status==="string"&&b.status.trim()!=="")w.set("status",b.status.trim());return w.set("page",String(b.page)),w.set("limit",String(b.pageSize)),w}async function wH(b,w){let $=typeof b.limit==="number"&&Number.isFinite(b.limit)?Math.max(1,Math.trunc(b.limit)):void 0,W=Math.min(100,Math.max(1,$??100)),Q=[],q=1,G=0,X=0,Y=0;while(!0){let D=BM({query:b.query,tags:b.tags,list:b.list,listId:b.listId,listName:b.listName,segmentId:b.segmentId,status:b.status,page:q,pageSize:W}),H=await z("GET",`/api/v1/subscribers?${D.toString()}`,void 0,w);G=H.pagination?.total??H.subscribers.length,X=H.pagination?.totalPages??1,Y+=1,Q.push(...H.subscribers??[]);let O=$!==void 0&&Q.length>=$,A=H.pagination?q>=H.pagination.totalPages:(H.subscribers??[]).length<W;if(O||A)break;q+=1}let J=$!==void 0?Q.slice(0,$):Q;return{success:!0,subscribers:J,pagination:{page:1,limit:W,total:G,totalPages:X,fetchedPages:Y},returned:J.length,truncated:$!==void 0&&G>0&&J.length<G}}function FM(b){let w=typeof b.email==="string"&&b.email.trim()!==""?b.email.trim():void 0,$=typeof b.externalId==="string"&&b.externalId.trim()!==""?b.externalId.trim():void 0;return{...w?{email:w}:{},...$?{externalId:$}:{}}}function Aw(b,w){let $=FM(w);if(!$.email&&!$.externalId)throw Error(`Provide either \`email\` or \`externalId\` when calling \`${b}\`.`);return $}function p$(b,w){let $=new URLSearchParams;if(w?.includeMachineEngagement)$.set("includeMachineEngagement","true");let W=$.toString(),Q=W?`?${W}`:"";if(b.email)return`/api/v1/subscribers/${encodeURIComponent(b.email)}${Q}`;return $.set("externalId",String(b.externalId)),`/api/v1/subscribers/external?${$.toString()}`}function SW(b){if(b.email)return`/api/v1/subscribers/${encodeURIComponent(b.email)}/notes`;let w=new URLSearchParams;return w.set("externalId",String(b.externalId)),`/api/v1/subscribers/external/notes?${w.toString()}`}async function H0(b,w,$){return z("GET",p$(b,$),void 0,w)}function qb(b,w,$,W){let Q=L(w,$);if(Q===void 0)return;if(!W.includes(Q))throw Error(`\`${$}\` must be one of ${W.join(", ")} when calling \`${b}\`.`);return Q}function z0(b,w,$,W){let Q=M(b,w,$);if(!W.includes(Q))throw Error(`\`${$}\` must be one of ${W.join(", ")} when calling \`${b}\`.`);return Q}function ab(b,w,$,W,Q){let q=w[$];if(q===void 0)return;if(typeof q!=="number"||!Number.isInteger(q)||q<W||q>Q)throw Error(`\`${$}\` must be an integer between ${W} and ${Q} when calling \`${b}\`.`);return q}function KM(b,w){let $=[],W=qb(b,w,"eventType",y$);if(W)$.push(W);if(w.eventTypes!==void 0){if(!Array.isArray(w.eventTypes))throw Error(`\`eventTypes\` must be an array when calling \`${b}\`.`);w.eventTypes.forEach((Q,q)=>{if(typeof Q!=="string")throw Error(`\`eventTypes\` item ${q+1} must be a string when calling \`${b}\`.`);let G=Q.trim();if(!y$.includes(G))throw Error(`\`eventTypes\` item ${q+1} must be one of ${y$.join(", ")} when calling \`${b}\`.`);$.push(G)})}return[...new Set($)]}function RW(b,w){let $=new URLSearchParams,W=KM(b,w);if(W.length>0)$.set("eventTypes",W.join(","));let Q=qb(b,w,"period",["1h","24h","7d","30d","90d"]);if(Q)$.set("period",Q);let q=L(w,"start");if(q)$.set("start",q);let G=L(w,"end");if(G)$.set("end",G);let X=ab(b,w,"page",1,1e6);if(X!==void 0)$.set("page",String(X));let Y=ab(b,w,"limit",1,500);if(Y!==void 0)$.set("limit",String(Y));if(w.includeMachineEngagement===!0)$.set("includeMachineEngagement","true");return $}function vW(b,w){if(w.events===void 0)return;if(!Array.isArray(w.events))throw Error(`\`events\` must be an array when calling \`${b}\`.`);let $=w.events.map((W,Q)=>{if(typeof W!=="string"||!J1.includes(W))throw Error(`\`events\` item ${Q+1} must be one of ${J1.join(", ")} when calling \`${b}\`.`);return W});if($.length===0)throw Error(`\`events\` must include at least one event type when calling \`${b}\`.`);return $}function kW(b,w){if(!Array.isArray(w.emails))throw Error(`\`emails\` must be an array when calling \`${b}\`.`);let $=[];if(w.emails.forEach((W,Q)=>{if(typeof W!=="string")throw Error(`\`emails\` item ${Q+1} must be a string when calling \`${b}\`.`);let q=W.trim();if(q.length>0)$.push(q)}),$.length===0)throw Error(`\`emails\` must include at least one email address when calling \`${b}\`.`);if($.length>BW)throw Error(`\`emails\` must include no more than ${BW} email addresses when calling \`${b}\`. Split larger batches into multiple calls.`);return $}function bH(b,w,$,W){let Q=w[$];if(Q===void 0)return;if(!Array.isArray(Q))throw Error(`\`${$}\` must be an array when calling \`${b}\`.`);let q=[];if(Q.forEach((G,X)=>{if(typeof G!=="string")throw Error(`\`${$}\` item ${X+1} must be a string when calling \`${b}\`.`);let Y=G.trim();if(Y.length>0)q.push(Y)}),q.length===0)throw Error(`\`${$}\` must include at least one ${W} when calling \`${b}\`.`);return q}function $H(b){let $=bH("enroll_subscribers_in_sequence",b,"emails","email address"),W=bH("enroll_subscribers_in_sequence",b,"subscriberIds","subscriber ID"),Q=($?.length??0)+(W?.length??0);if(Q===0)throw Error("Provide `emails` or `subscriberIds` when calling `enroll_subscribers_in_sequence`.");if(Q>FW)throw Error(`\`emails\` and \`subscriberIds\` must include no more than ${FW} total targets when calling \`enroll_subscribers_in_sequence\`. Split larger batches into multiple calls.`);let q=L(b,"targetNodeId");return{...$!==void 0&&{emails:$},...W!==void 0&&{subscriberIds:W},...q!==void 0&&{targetNodeId:q}}}import{readFileSync as MM,statSync as IM}from"node:fs";import{basename as _M}from"node:path";var jM={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 ZM(b){let w=b.split(".").pop()?.toLowerCase()??"";return jM[w]??null}var VM=104857600;async function WH(b,w){if(!A0())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 $=ZM(b);if(!$)throw Error("Unsupported file type. Use PDF, ePub, ZIP, image, audio, video, or text files.");let W=IM(b).size;if(W>VM)throw Error(`File is too large (${Math.round(W/1048576)}MB). Delivery files must be 100MB or smaller.`);let Q=MM(b),q=await z("POST","/api/v1/products/delivery/upload-url",{filename:_M(b),contentType:$,fileSizeBytes:W},w),G=await fetch(q.uploadUrl,{method:"PUT",headers:{"Content-Type":$},body:Q});if(!G.ok)throw Error(`File upload failed (${G.status})`);return{url:q.publicUrl,fileName:q.fileName,fileSizeBytes:W,mimeType:$}}async function o$(b){let w=L(b,"companyId");if(w)return w;let $=Uw();if($)return $;try{return(await z("GET","/api/v1/account")).currentCompanyId??void 0}catch{return}}async function d$(b,w){let $=await o$(w);if(!$)throw Error(`A company is required when calling \`${b}\`. Call \`get_account\`, then \`select_company\`, or pass \`companyId\` explicitly.`);return $}function H1(b,w){if(!k(b)||!w)return b;return{...b,url:w}}function QH(b,w){if(!k(b))return b;return{...b,...w.campaign!==void 0&&{url:w.campaign},...w.campaignPreview!==void 0&&{previewUrl:w.campaignPreview}}}function O0(b,w,$){if(!Array.isArray(b)||!w)return b;return b.map((W)=>{if(!k(W))return W;let Q=L(W,"id");if(!Q)return W;let q=Dw({companyId:w,...$==="campaign"&&{campaignId:Q},...$==="landingPage"&&{landingPageId:Q},...$==="sequence"&&{sequenceId:Q},...$==="template"&&{emailId:Q},...$==="transactional"&&{transactionalId:Q}});if($==="campaign")return QH(W,q.urls);let G=$==="sequence"?q.urls.sequence:$==="landingPage"?q.urls.landingPage:$==="template"?q.urls.email:q.urls.transactionalEmail;return H1(W,G)})}function NM(b){if(!Array.isArray(b))return b;return b.map((w)=>{if(!k(w))return w;let $=L(w,"id");if(!$)return w;let W=Dw({companyId:$});return{...w,url:W.urls.dashboard,settingsUrl:W.urls.settings}})}var CW=new Set(["get_account","select_company","create_company","get_company","update_company","list_campaigns","get_campaign","get_email_send","create_campaign","update_campaign","schedule_campaign","send_test_email","cancel_campaign","pause_campaign","resume_campaign","duplicate_campaign","resend_campaign_to_non_openers","list_landing_pages","get_landing_page","create_landing_page","update_landing_page","publish_landing_page","unpublish_landing_page","delete_landing_page","list_sequences","get_sequence","create_sequence","generate_sequence","update_sequence","update_sequence_node","update_sequence_nodes","edit_sequence_graph","insert_sequence_step","enable_sequence","disable_sequence","pause_sequence_enrollments","resume_sequence_enrollments","cancel_sequence_enrollments","list_ab_tests","get_ab_test","get_ab_test_stats","update_ab_test_variant","list_templates","get_template","create_template","update_template","set_template_localization","sync_template_localizations","list_transactional_emails","get_transactional_email","create_transactional_email","update_transactional_email"]);async function qH(b,w,$){if(!k($)||!CW.has(b))return $;let W=k($.company)?$.company:void 0,q=L($,"selectedCompanyId")??L($,"currentCompanyId")??L($,"companyId")??(W?L(W,"id"):void 0)??(W?L(W,"companyId"):void 0)??await o$(w);if(!q)return $;let G=k($.campaign)?$.campaign:void 0,X=k($.sequence)?$.sequence:void 0,Y=k($.landingPage)?$.landingPage:void 0,J=k($.template)?$.template:void 0,D=k($.transactional)&&!Array.isArray($.transactional)?$.transactional:void 0,H={companyId:q,campaignId:L(w,"campaignId")??L($,"campaignId")??(G?L(G,"id"):void 0),landingPageId:L(w,"landingPageId")??L($,"landingPageId")??(Y?L(Y,"id"):void 0),sequenceId:L(w,"sequenceId")??L($,"sequenceId")??(X?L(X,"id"):void 0),emailId:L($,"templateId")??(J?L(J,"id"):void 0)??(D?L(D,"emailId"):void 0)??L(w,"templateId"),transactionalId:L(w,"transactionalId")??(D?L(D,"id"):void 0)??L(w,"idOrSlug"),emailSendId:L(w,"emailSendId")??L($,"emailSendId")??(k($.emailSend)?L($.emailSend,"id"):void 0),status:L(w,"status")},O=Dw(H),A=W?Dw({companyId:q}):void 0;return{...$,...Array.isArray($.companies)&&{companies:NM($.companies)},...Array.isArray($.campaigns)&&{campaigns:O0($.campaigns,q,"campaign")},...Array.isArray($.landingPages)&&{landingPages:O0($.landingPages,q,"landingPage")},...Array.isArray($.sequences)&&{sequences:O0($.sequences,q,"sequence")},...Array.isArray($.templates)&&{templates:O0($.templates,q,"template")},...Array.isArray($.transactional)&&{transactional:O0($.transactional,q,"transactional")},...W&&A!==void 0&&{company:{...W,url:A.urls.dashboard,settingsUrl:A.urls.settings}},...G&&O.urls.campaign!==void 0&&{campaign:QH(G,O.urls)},...X&&O.urls.sequence!==void 0&&{sequence:H1(X,O.urls.sequence)},...Y&&O.urls.landingPage!==void 0&&{landingPage:H1(Y,O.urls.landingPage)},...J&&O.urls.email!==void 0&&{template:H1(J,O.urls.email)},...D&&O.urls.transactionalEmail!==void 0&&{transactional:H1(D,O.urls.transactionalEmail)},...k($.emailSend)&&O.urls.emailSend!==void 0&&{emailSend:H1($.emailSend,O.urls.emailSend)},appUrls:O.urls}}import{readFileSync as EM,statSync as TM}from"node:fs";import{basename as SM,extname as XH}from"node:path";var xW=5242880,RM=Math.ceil(xW/3)*4,vM=Math.ceil(RM*1.05)+256,YH={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"},kM=new Set(Object.values(YH));function uW(b){return b?.split(";")[0]?.trim().toLowerCase()||void 0}function CM(b){return YH[XH(b).toLowerCase()]}function uM(b){let w=XH(b);return(w?b.slice(0,-w.length):b).replace(/[-_]+/g," ").trim()||"Image"}function xM(b){if(b.length>vM)throw Error("Image assets must be 5MB or smaller.")}function yM(b){let w=0,$=0;for(let Q=0;Q<b.length;Q+=1){let q=b.charCodeAt(Q);if(q===9||q===10||q===11||q===12||q===13||q===32)continue;w+=1,$=q===61?$+1:0}if(Math.floor(w*3/4)-Math.min($,2)>xW)throw Error("Image assets must be 5MB or smaller.")}function hM(b){xM(b);let w=b.trim(),$=/^data:([^;,]+);base64,([\s\S]+)$/i.exec(w),W=$?.[2]??w;yM(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:uW($[1])}:{}}}function GH(b){if(b<=0)throw Error("The image file is empty.");if(b>xW)throw Error("Image assets must be 5MB or smaller.")}function cM(b){let w=CM(b.filename)??uW(b.explicitContentType)??uW(b.dataUrlContentType);if(!w||!kM.has(w))throw Error("Unsupported image type. Use PNG, JPEG, GIF, or WebP.");return w}function fM(b){let w,$,W;if(b.filePath!==void 0){if(!A0())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 q=TM(b.filePath).size;GH(q),w=EM(b.filePath),$=b.filename??SM(b.filePath)}else{if(!b.imageBase64)throw Error("Provide either `filePath` or `imageBase64` when uploading an image asset.");if(!b.filename)throw Error("`filename` is required with `imageBase64` when uploading an image asset.");let q=hM(b.imageBase64);w=q.bytes,W=q.dataUrlContentType,$=b.filename,GH(w.byteLength)}let Q=cM({filename:$,explicitContentType:b.contentType,dataUrlContentType:W});return{bytes:w,filename:$,contentType:Q,altText:b.altText??uM($)}}async function JH(b){let w=fM(b),$=w.bytes.byteLength,W=await z("POST","/api/v1/media/upload-url",{filename:w.filename,contentType:w.contentType,fileSizeBytes:$},b.companyId);return await wQ(W.uploadUrl,w.bytes,w.contentType,b.companyId),(await z("POST","/api/v1/media/complete-upload",{key:W.key,filename:W.fileName,contentType:w.contentType,fileSizeBytes:$,...b.sourceWidth!==void 0&&{width:b.sourceWidth},...b.sourceHeight!==void 0&&{height:b.sourceHeight},altText:w.altText},b.companyId)).asset}var nM={type:"boolean",description:"Whether the Sequenzy operation succeeded."},iM={type:"string",description:"Human-readable status, confirmation, or next-step message."},mM={type:"string",description:"Additional context about the result."};function p(b){return{type:"object",description:b,additionalProperties:!0}}function lM(b){return{type:"array",description:b,items:p("One item in the returned collection.")}}function V(b){return{type:"string",description:b}}function Mb(b){return{type:"number",description:b}}function Rb(b){return{type:"boolean",description:b}}function F(b){return p(`The ${b} record returned by Sequenzy.`)}function i(b){return lM(`List of ${b} records returned by Sequenzy.`)}var gM={appUrls:p("Dashboard URLs for relevant Sequenzy resources."),url:V("Primary dashboard URL for this result."),settingsUrl:V("Company settings URL when available.")},pM={success:nM,message:iM,note:mM,warnings:{type:"array",description:"Non-fatal cautions about content, permissions, or follow-up actions.",items:V("One warning.")},items:{type:"array",description:"Fallback array wrapper used only when a tool returns a bare array.",items:p("One returned item.")},value:p("Fallback object wrapper used only when a tool returns a non-object value.")},oM={get_account:{account:F("account"),companies:i("company"),apiKeyPermissions:p("Current API key preset and scopes, whether common marketing work is discoverable, any missing marketing read scopes, and the API Keys management URL."),currentCompanyId:V("Company ID selected by the authenticated API key, when available."),selectedCompanyId:V("Company ID selected locally for subsequent MCP calls, when available.")},select_company:{companyId:V("Selected company ID."),companyName:V("Selected company name.")},get_app_urls:{dashboard:V("Company dashboard URL."),settings:V("Company settings URL."),campaign:V("Campaign editor URL."),landingPage:V("Landing page editor URL."),sequence:V("Sequence editor URL."),email:V("Email editor URL."),transactionalEmail:V("Transactional email URL."),emailSend:V("Sent email detail URL."),domain:V("Sending domain settings URL."),urls:p("All generated URLs keyed by resource type.")},create_company:{company:F("company"),autoSelected:Rb("Whether the new company was selected for subsequent MCP calls.")},update_company:{company:F("company")},get_company:{company:F("company")},get_sync_rules:{syncRules:{type:"array",description:"Effective sync rules for the company.",items:p("One sync rule.")},isDefault:Rb("Whether the company uses the inherited SaaS/ecommerce platform preset.")},update_sync_rules:{syncRules:{type:"array",description:"Effective sync rules after the update.",items:p("One sync rule.")},isDefault:Rb("Whether the company now uses the inherited SaaS/ecommerce platform preset.")},get_shopify_automation_settings:{browseAbandonment:p("Effective browse-abandonment settings (defaults applied)."),priceDrop:p("Effective price-drop settings (defaults applied)."),shopDomain:V("Connected Shopify store domain.")},update_shopify_automation_settings:{browseAbandonment:p("Effective browse-abandonment settings after the update."),priceDrop:p("Effective price-drop settings after the update."),shopDomain:V("Connected Shopify store domain.")},create_api_key:{apiKey:p("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:V("Newly created API key if the API response uses the short key field.")},list_api_keys:{apiKeys:i("non-secret API key metadata, including ID, name, prefix, permissions, timestamps, and active-credential status")},revoke_api_key:{apiKey:F("revoked non-secret API key metadata")},delete_api_key:{apiKey:F("deleted non-secret API key metadata")},list_websites:{websites:i("sender website")},add_website:{website:F("Sending domain with the SPF, DKIM, MAIL FROM, and inbound DNS records required for setup.")},add_sending_domain:{website:F("Sending domain with the SPF, DKIM, MAIL FROM, and inbound DNS records required for setup.")},check_website:{website:F("sender website"),ready:Rb("Whether the sender website is ready."),status:V("Current processing or verification status.")},verify_sending_domain:{website:F("Sending domain with current aggregate, SPF, DKIM, and MAIL FROM verification details."),verified:Rb("Whether the sending domain passed the fresh verification check."),message:V("Verification result summary.")},get_integration_guide:{guide:F("integration guide"),code:V("Generated integration code or example."),steps:{type:"array",description:"Setup steps for the requested integration.",items:p("One setup step.")}},add_subscriber:{subscriber:F("subscriber")},create_subscriber_import:{import:F("subscriber import")},get_subscriber_import:{import:F("subscriber import")},update_subscriber:{subscriber:F("subscriber")},remove_subscriber:{subscriber:F("subscriber"),hardDeleted:Rb("Whether the subscriber was permanently deleted.")},get_subscriber:{subscriber:F("subscriber")},list_subscriber_notes:{notes:i("subscriber note")},add_subscriber_note:{note:F("subscriber note")},delete_subscriber_note:{id:V("Deleted subscriber note ID."),deleted:Rb("Whether the subscriber note was deleted.")},search_subscribers:{subscribers:i("subscriber"),pagination:p("Pagination metadata."),returned:Mb("Number of subscribers returned."),truncated:Rb("Whether the result was truncated by the requested limit.")},list_products:{products:i("product")},upsert_products:{products:i("product"),created:Mb("Number of products created."),updated:Mb("Number of products updated.")},delete_product:{productId:V("Deleted product ID.")},attach_product_file:{product:F("product"),delivery:F("digital delivery file")},remove_product_file:{product:F("product")},upload_image_asset:{asset:F("hosted image asset"),imageBlock:p("Ready-to-insert Sequenzy image block using the hosted asset URL.")},sync_products:{job:F("product sync job"),jobId:V("Queued product sync job ID.")},list_tags:{tags:i("tag")},create_tag:{tag:F("tag")},update_tag:{tag:F("tag")},delete_tag:{tagId:V("Deleted tag ID.")},list_lists:{lists:i("list")},create_list:{list:F("list")},update_list:{list:F("list")},delete_list:{listId:V("Deleted list ID.")},add_subscribers_to_list:{list:F("list"),added:Mb("Number of subscribers added to the list."),skipped:Mb("Number of subscribers skipped.")},remove_subscribers_from_list:{list:F("list"),removed:Mb("Number of subscribers removed from the list."),skipped:Mb("Number of subscribers skipped.")},list_segments:{segments:i("segment")},create_segment:{segment:F("segment")},update_segment:{segment:F("segment")},delete_segment:{segmentId:V("Deleted segment ID.")},get_segment_count:{count:Mb("Number of subscribers matching the segment."),segmentId:V("Segment ID that was counted.")},list_audience_syncs:{audienceSyncs:i("audience sync")},list_ad_accounts:{adAccounts:i("ad account")},create_audience_sync:{audienceSync:F("audience sync")},update_audience_sync:{audienceSync:F("audience sync")},delete_audience_sync:{audienceSyncId:V("Deleted audience sync ID.")},sync_audience_now:{audienceSync:F("audience sync"),job:F("audience sync job"),jobId:V("Queued audience sync job ID.")},list_templates:{templates:i("email template")},get_template:{template:F("email template")},create_template:{template:F("email template")},update_template:{template:F("email template")},set_template_localization:{templateId:V("Localized template ID."),localization:F("template localization")},sync_template_localizations:{templateId:V("Template ID queued for localization."),queuedLocales:{type:"array",description:"Locale codes queued for AI translation.",items:V("One queued locale code.")},queuedVariantCount:Mb("Number of localized variants queued for translation.")},delete_template:{templateId:V("Deleted template ID.")},list_ab_tests:{abTests:i("A/B test")},get_ab_test:{abTest:F("A/B test")},get_ab_test_stats:{abTest:F("A/B test"),stats:F("A/B test statistics")},restart_ab_test:{abTest:F("A/B test")},update_ab_test_variant:{abTest:F("A/B test"),variant:F("A/B test variant")},create_ab_test:{abTest:F("A/B test")},add_ab_test_variant:{abTest:F("A/B test"),variant:F("A/B test variant")},delete_ab_test_variant:{abTest:F("A/B test"),variantId:V("Deleted A/B test variant ID.")},delete_ab_test:{abTestId:V("Deleted A/B test ID.")},list_campaigns:{campaigns:i("campaign")},get_campaign:{campaign:F("campaign")},get_email_send:{emailSend:F("email send"),events:i("email delivery event")},get_recipient_suppression:{suppression:F("recipient suppression status")},remove_recipient_suppression:{removed:Rb("Whether stale bounce suppression was removed."),removedLocalBounce:Rb("Whether the platform-local bounce block was removed."),removedSesRegions:{type:"array",description:"AWS SES regions where a bounce suppression was removed.",items:V("One AWS SES region.")},remainingSuppression:F("recipient suppression status after cleanup")},create_campaign:{campaign:F("campaign")},update_campaign:{campaign:F("campaign")},schedule_campaign:{campaign:F("campaign"),scheduledAt:V("Scheduled send timestamp.")},send_test_email:{emailSendId:V("Durable test email delivery ID."),recipientEmail:V("Test email recipient.")},send_test_sms:{smsSendId:V("Created test SMS send ID."),toPhone:V("Normalized E.164 destination phone.")},cancel_campaign:{campaign:F("campaign")},pause_campaign:{campaign:F("campaign")},resume_campaign:{campaign:F("campaign")},delete_campaign:{campaignId:V("Deleted campaign ID.")},duplicate_campaign:{campaign:F("duplicated campaign")},resend_campaign_to_non_openers:{campaign:F("non-opener resend draft campaign"),estimatedNonOpenerCount:Mb("Estimated number of subscribers who haven't opened the original campaign.")},list_forms:{forms:i("saved form")},create_form:{form:F("saved form"),embed:p("Public action URL plus JavaScript, native form, and fetch snippets.")},get_form_embed:{form:F("saved form"),embed:p("Public action URL plus JavaScript, native form, and fetch snippets.")},list_landing_pages:{landingPages:i("landing page")},get_landing_page:{landingPage:F("landing page")},create_landing_page:{landingPage:F("landing page")},update_landing_page:{landingPage:F("landing page")},delete_landing_page:{landingPageId:V("Deleted landing page ID.")},publish_landing_page:{landingPage:F("landing page")},unpublish_landing_page:{landingPage:F("landing page")},connect_landing_page_domain:{landingPage:F("landing page"),domain:V("Connected landing page domain.")},update_landing_page_domain_settings:{landingPage:F("landing page"),domain:V("Landing page domain.")},list_sequences:{sequences:i("sequence")},get_sequence:{sequence:F("sequence")},create_sequence:{sequence:F("sequence"),eventTrackingCode:V("Ready-to-adapt code for sending a custom trigger event, including any matching-field property."),eventTracking:p("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:V("One required event name.")}},update_sequence:{sequence:F("sequence")},update_sequence_node:{sequence:F("sequence")},update_sequence_nodes:{sequence:F("sequence")},edit_sequence_graph:{sequence:F("sequence")},insert_sequence_step:{sequence:F("sequence"),insertedNodeIds:{type:"array",description:"Node IDs created for a linear inserted step, including any delay or wait-for-event node.",items:V("Inserted automation node ID.")},insertedEmailIds:{type:"array",description:"Email template IDs created for the inserted step.",items:V("Inserted email template ID.")},insertedEmailCount:Mb("Number of email steps inserted."),addedBranchNodeId:V("New logic_branch node ID when the inserted step is a branch."),addedBranchPathNodeIds:p("Created path node IDs keyed by branch ID, plus else. Directly wired paths have empty arrays.")},enable_sequence:{sequence:F("sequence")},disable_sequence:{sequence:F("sequence")},duplicate_sequence:{sequence:F("sequence"),nodes:i("sequence node"),edges:i("sequence edge")},archive_sequence:{sequence:F("sequence")},unarchive_sequence:{sequence:F("sequence")},list_sequence_goals:{goals:i("sequence goal")},create_sequence_goal:{goal:F("sequence goal")},update_sequence_goal:{goal:F("sequence goal")},delete_sequence_goal:{goalId:V("Deleted sequence goal ID.")},get_sequence_inbound_webhook:{webhook:F("sequence inbound webhook")},configure_sequence_inbound_webhook:{webhook:F("sequence inbound webhook")},rotate_sequence_inbound_webhook_secret:{webhook:F("sequence inbound webhook")},pause_sequence_enrollments:{sequenceId:V("Sequence ID."),enrollmentPaused:Rb("Whether new sequence enrollments are paused.")},resume_sequence_enrollments:{sequenceId:V("Sequence ID."),enrollmentPaused:Rb("Whether new sequence enrollments are paused.")},enroll_subscribers_in_sequence:{sequence:F("sequence"),enrollments:i("sequence enrollment"),enrolled:Mb("Number of subscribers enrolled."),skipped:Mb("Number of subscribers skipped.")},cancel_sequence_enrollments:{sequence:F("sequence"),cancelled:Mb("Number of enrollments cancelled."),skipped:Mb("Number of enrollments skipped.")},delete_sequence:{sequenceId:V("Deleted sequence ID.")},list_transactional_emails:{transactional:i("transactional email")},get_transactional_email:{transactional:F("transactional email")},create_transactional_email:{transactional:F("transactional email")},update_transactional_email:{transactional:F("transactional email")},send_email:{emailSendId:V("Durable transactional delivery ID."),transactional:F("transactional email")},get_stats:{stats:F("account or company statistics")},get_campaign_stats:{campaign:F("campaign"),stats:F("campaign statistics"),clickedLinks:{type:"array",description:"Per-link click breakdown, most clicked first (top 20). Each entry has url, clicks, and percentage (that link's share of every recorded link click). Present only when the campaign has tracked link clicks.",items:p("One clicked link with url/clicks/share.")},polls:{type:"array",description:`Poll and NPS summaries. Each subscriber counts once per campaign poll block using their latest answer to that block; NPS entries include score, average, and promoter/passive/detractor counts. To list the exact historical respondents behind a count, use the summary blockId and the get_campaign_stats campaignId with create_segment. ${Rw} A summary's attributeKey identifies the subscriber attribute that stores their current/latest response and may be overwritten by a later poll that reuses the key.`,items:p("One poll or NPS results summary.")}},get_sequence_stats:{sequence:F("sequence"),stats:F("sequence statistics")},list_campaign_events:{events:i("campaign email event"),pagination:p("Pagination metadata.")},list_sequence_events:{events:i("sequence email event"),pagination:p("Pagination metadata.")},get_subscriber_activity:{activity:i("subscriber activity event"),subscribers:i("subscriber"),pagination:p("Pagination metadata.")},list_team_members:{members:i("team member"),invitations:i("team invitation")},invite_team_member:{invitation:F("team invitation")},cancel_team_invitation:{invitationId:V("Cancelled invitation ID.")},list_conversations:{conversations:i("inbox conversation"),pagination:p("Pagination metadata.")},get_conversation:{conversation:F("inbox conversation"),messages:i("conversation message")},reply_to_conversation:{conversation:F("inbox conversation"),message:F("conversation message")},update_conversation_status:{conversation:F("inbox conversation")},mark_conversation_read:{conversation:F("inbox conversation")},list_webhooks:{webhooks:i("outbound webhook")},create_webhook:{webhook:F("outbound webhook")},update_webhook:{webhook:F("outbound webhook")},delete_webhook:{webhookId:V("Deleted outbound webhook ID.")},test_webhook:{webhook:F("outbound webhook"),delivery:F("test webhook delivery")},list_webhook_deliveries:{deliveries:i("webhook delivery")},replay_webhook_delivery:{delivery:F("webhook delivery"),job:F("webhook replay job")},generate_email:{email:F("generated email"),html:V("Generated HTML email body."),blocks:{type:"array",description:"Generated Sequenzy email blocks, wrapped with company branding (logo + footer) unless applyBranding was false.",items:p("One generated email block.")},subject:V("Generated subject line."),previewText:V("Generated inbox preview text.")},generate_sequence:{sequence:F("persisted AI-generated sequence draft"),deprecated:Rb("Always true for this deprecated alias."),deprecationMessage:V("Migration guidance directing callers to create_sequence.")},generate_subject_lines:{subjectLines:{type:"array",description:"Generated subject line variants.",items:V("One generated subject line.")},variants:i("generated subject line variant")},generate_sms:{prompt:V("The prompt the messages were generated for."),messages:{type:"array",description:"Generated SMS message variants with encoding and segment counts.",items:p("One generated SMS message.")}},get_sms_settings:{sms:p("SMS add-on status: enabled, planEligible, creditsBalance, brandPrefix, numbers, readyToSend (paid plan or credits plus an active number).")},submit_feedback:{}};function dM(b){let w=oM[b];if(w===void 0)throw Error(`MCP tool "${b}" must define outputSchema properties.`);return{type:"object",description:`Structured content returned by the \`${b}\` MCP tool.`,properties:{...pM,...w,...CW.has(b)?gM:{}},additionalProperties:!0}}function DH(b){return{...b,outputSchema:dM(b.name)}}function HH(b){if(k(b))return b;if(Array.isArray(b))return{items:b};return{value:b}}var zH=[{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:pb},required:["abTestId"]}},{name:"restart_ab_test",description:"Run another sequence A/B test after a winner is selected. By default the winner becomes the new control; pass sourceVariantId to use another variant as the control email.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID to restart"},sourceVariantId:{type:"string",description:"Optional variant ID to use as the new control email. Defaults to the selected winner."},testType:{type:"string",description:"Optional test type: subject or content."},winnerThreshold:{type:"number",description:"Optional number of subscribers before selecting a winner. Must be from 10 to 1000."},variantCount:{type:"number",description:"Optional total variants including the control. Must be from 2 to 4."}},required:["abTestId"],additionalProperties:!1}},{name:"update_ab_test_variant",description:"Update a draft A/B test variant. Provide at least one of subject, previewText, html, or blocks. Use either html or blocks, not both. 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"},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. ${Gb}`},blocks:{type:"array",description:`${zw} Mutually exclusive with html.`,items:{type:"object"}},confirmLiveChange:{type:"boolean",description:"Required as true when the A/B test belongs to an active sequence, because the content change immediately affects live rotation."}},required:["abTestId","variantId"],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:"Percentage of the audience used for the test phase, from 5 to 50. Defaults to 20."},testDurationMinutes:{type:"number",description:"Test phase duration in minutes before the winner is selected, from 15 to 1440. Defaults to 240."},winnerCriteria:{type:"string",enum:["open_rate","click_rate"],description:"Winner selection criteria. Defaults to open_rate."},testType:{type:"string",enum:["subject","content"],description:"Sequence A/B test type. Subject tests use open_rate; content tests use click_rate. 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:zw,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:zw,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 OH=[{name:"get_account",description:`Get current account information including available companies, the current API key's permission scopes, and the API Keys management URL. Call this after a missing-scope error to inspect access and find the replacement-key settings. IMPORTANT: If you have access to multiple companies, you MUST either:
|
|
30
30
|
1. Call select_company first to choose which company to work with, OR
|
|
31
31
|
2. Pass companyId explicitly in each tool call
|
|
32
32
|
|
|
@@ -48,7 +48,7 @@ Use cases:
|
|
|
48
48
|
- 'event_tracking': Tracking CUSTOM events only (not payment events - those come from the integration)
|
|
49
49
|
- 'ecommerce': Connecting a custom e-commerce platform via the Commerce API (sync products, push orders/checkouts, power abandoned cart + back-in-stock automations)
|
|
50
50
|
|
|
51
|
-
Before 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 AH=[{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 UH=[{name:"get_stats",description:"Get overview statistics for a time period, including reply count and reply rate",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},period:{type:"string",description:"Time period: 7d, 30d, or 90d (default: 7d)"},includeMachineEngagement:pb}}},{name:"get_campaign_stats",description:"Get detailed statistics for a campaign, including replies and reply rate, attributed conversions, revenue (revenueCents), a per-link click breakdown in the top-level clickedLinks array, and any Poll or NPS survey summaries in the top-level polls array",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"},includeMachineEngagement:pb},required:["campaignId"]}},{name:"get_sequence_stats",description:"Get statistics for a sequence, including aggregate and per-step replies and reply rates, attributed conversions and revenue (revenueCents), plus per-step failed subscribers and failure reasons",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"},includeMachineEngagement:pb},required:["sequenceId"]}},{name:"list_campaign_events",description:"List paginated raw email events for a campaign. Defaults to deliveries; use eventType or eventTypes to include opens, clicks, bounces, complaints, unsubscribes, sends, or delivery delays.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"},eventType:{type:"string",description:"Optional single event type. Supported values: send, delivery, bounce, complaint, open, click, unsubscribe, delivery_delay. Defaults to delivery."},eventTypes:{type:"array",description:"Optional event types to include. Supported values: send, delivery, bounce, complaint, open, click, unsubscribe, delivery_delay. Defaults to delivery.",items:{type:"string"}},period:{type:"string",description:"Optional sliding time window: 1h, 24h, 7d, 30d, or 90d. Ignored when start/end are provided."},start:{type:"string",description:"Optional ISO 8601 start time. Must be used with end; max range is 90 days."},end:{type:"string",description:"Optional ISO 8601 end time. Must be used with start; max range is 90 days."},page:{type:"number",description:"Page number, starting at 1. Defaults to 1."},limit:{type:"number",description:"Events per page. Defaults to 100; maximum 500."},includeMachineEngagement:pb},required:["campaignId"]}},{name:"list_sequence_events",description:"List paginated raw email events for every email step in a sequence. Defaults to deliveries; use eventType or eventTypes to include opens, clicks, bounces, complaints, unsubscribes, sends, or delivery delays.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"},eventType:{type:"string",description:"Optional single event type. Supported values: send, delivery, bounce, complaint, open, click, unsubscribe, delivery_delay. Defaults to delivery."},eventTypes:{type:"array",description:"Optional event types to include. Supported values: send, delivery, bounce, complaint, open, click, unsubscribe, delivery_delay. Defaults to delivery.",items:{type:"string"}},period:{type:"string",description:"Optional sliding time window: 1h, 24h, 7d, 30d, or 90d. Ignored when start/end are provided."},start:{type:"string",description:"Optional ISO 8601 start time. Must be used with end; max range is 90 days."},end:{type:"string",description:"Optional ISO 8601 end time. Must be used with start; max range is 90 days."},page:{type:"number",description:"Page number, starting at 1. Defaults to 1."},limit:{type:"number",description:"Events per page. Defaults to 100; maximum 500."},includeMachineEngagement:pb},required:["sequenceId"]}},{name:"get_subscriber_activity",description:"Get recent activity, email stats, and current sequence enrollments for a subscriber",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},includeMachineEngagement:pb},required:[]}}];var LH=[{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 PH=[{name:"list_campaigns",description:"List all campaigns",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list campaigns for. If not provided, uses the currently selected company."},status:{type:"string",description:"Filter by status (draft, scheduled, sent, 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."}}}},{name:"get_campaign",description:"Get campaign details and stats, including rejectionComment reviewer feedback for rejected campaigns",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"}},required:["campaignId"]}},{name:"get_email_send",description:"Get an email delivery by emailSendId, including queued and test sends, delivery status, provider failure reason, stored HTML, and the ClickHouse event timeline. Queue jobs are internal execution details and are not exposed.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},emailSendId:{type:"string",description:"Durable email delivery ID to inspect."}},required:["emailSendId"]}},{name:"create_campaign",description:"Create a new campaign. Omit all content fields to create an empty draft. For net-new natural-language content use `prompt`; do not author HTML or blocks. `blocks` are finished caller-supplied Sequenzy content and `html` is preserved/imported markup. Defaults to draft; status 'sent' only archives an already-sent campaign.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the campaign in. If not provided, uses the currently selected company."},name:{type:"string",description:"Campaign name"},subject:{type:"string",description:"Email subject line. Optional when `prompt` is provided because the generated subject will be used."},previewText:{type:["string","null"],description:"Email preview text. Optional when `prompt` is provided because the generated preview text will be used."},trackingCode:{type:"string",description:"Optional campaign tracking code for UTM templates. Use only when explicitly requested."},status:{type:"string",description:"Initial status: draft or sent. Defaults to draft. Use sent only for imported/already-sent campaigns; it does not send email or create delivery history."},sentAt:{type:"string",description:"ISO date-time for an imported/already-sent campaign. Only valid when status is sent; defaults to now if omitted."},html:{type:"string",description:`Email HTML content. Mutually exclusive with \`blocks\`. Use this for imported provider campaigns. ${qb}`},blocks:{type:"array",description:Hw,items:{type:"object"}},prompt:{type:"string",description:"Generate campaign blocks from a prompt. Generated blocks include the company's logo and footer, and the created campaign inherits the company brand font. Mutually exclusive with `html`, `blocks`, and `templateId`."},style:{type:"string",description:"Prompt generation style: minimal, branded, promotional. Only used with `prompt`."},tone:{type:"string",description:"Prompt generation tone: professional, casual, friendly. Only used with `prompt`."},templateId:{type:"string",description:"Use a template instead of html"},segmentId:{type:"string",description:"Target segment ID"},fromEmail:{type:"string",description:"From address for this campaign. Its domain must be configured and verified; a sender profile is created when needed."},fromName:{type:"string",description:"Display name for a newly created sender profile. Requires fromEmail."},senderProfileId:{type:"string",description:"Existing sender profile ID. Mutually exclusive with fromEmail."},replyTo:{type:"string",description:"Reply-To address for this campaign. A reply profile is created when needed."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo."},replyProfileId:{type:"string",description:"Existing reply profile ID. Mutually exclusive with replyTo."},campaignData:{type:"object",description:"Optional campaign-scoped JSON data for repeat blocks and personalization."},computedLists:{type:"array",description:"Optional computed list definitions derived from campaignData at send time.",items:{type:"object"}},labels:{type:"array",description:"Optional label names to assign. Missing labels are created automatically.",items:{type:"string"}}},required:["name"]}},{name:"update_campaign",description:"Update a draft campaign",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"},name:{type:"string",description:"Campaign name"},subject:{type:"string",description:"Email subject line"},trackingCode:{type:"string",description:"Optional campaign tracking code for UTM templates. Use only when explicitly requested. Send an empty string to clear it."},html:{type:"string",description:`Email HTML content. Mutually exclusive with \`blocks\`. Use this for imported provider campaigns. ${qb}`},blocks:{type:"array",description:Hw,items:{type:"object"}},replyTo:{type:"string",description:"Set reply-to using an existing reply profile email address for this company."},replyProfileId:{type:"string",description:"Set reply-to using a reply profile ID for this company."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo."},fromEmail:{type:"string",description:"Set this campaign's From address. Its domain must be configured and verified."},fromName:{type:"string",description:"Display name for a newly created sender profile. Requires fromEmail."},senderProfileId:{type:"string",description:"Set an existing sender profile. Mutually exclusive with fromEmail."},ccEmails:{type:["array","null"],description:"Addresses CC'd on every recipient's campaign email (max 10). Send an empty array or null to clear them; omit to leave unchanged.",items:{type:"string"},maxItems:10},bccEmails:{type:["array","null"],description:"Addresses BCC'd on every recipient's campaign email (max 10). Send an empty array or null to clear them; omit to leave unchanged.",items:{type:"string"},maxItems:10},campaignData:{type:"object",description:"Set campaign-scoped JSON data for repeat blocks and personalization."},computedLists:{type:"array",description:"Set computed list definitions derived from campaignData at send time.",items:{type:"object"}},labels:{type:"array",description:"Replacement label names. Send an empty array to clear labels. Missing labels are created automatically.",items:{type:"string"}}},required:["campaignId"],additionalProperties:!1}},{name:"schedule_campaign",description:"Schedule a draft or already scheduled campaign. Returns dashboard edit and preview URLs.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"},scheduledAt:{type:"string",description:"Future ISO 8601 timestamp for the send, for example 2026-06-01T14:00:00Z."},targetLists:{type:"object",description:"Optional campaign targeting object. Omit to use saved targeting or all active subscribers. Examples: {type:'all'}, {type:'lists', listIds:['list_123']}, {type:'segment', segmentId:'seg_123'}, {type:'filtered', filters:[...], filterJoinOperator:'and'}, or {type:'rules', include:[{type:'lists', listIds:['list_123']}], exclude:[{type:'segments', segmentIds:['seg_123']}]}. Rules audiences require at least one include rule.",additionalProperties:!0},sendTimeOptimization:{type:"boolean",description:"Whether to use send-time optimization."},spreadOverHours:{type:"number",description:"Spread delivery over an integer number of hours from 1 to 72. When set, spread delivery takes precedence over send-time optimization."},recurringInterval:{type:"string",enum:["weekly","monthly"],description:"Repeat this campaign on a cadence starting at scheduledAt. The campaign becomes a recurring template: each run is duplicated and sent automatically, re-evaluating audience membership every time. Omit for a one-shot send; scheduling again without it stops the recurrence."}},required:["campaignId","scheduledAt"],additionalProperties:!1}},{name:"send_test_email",description:"Queue a campaign test email to a single address. Returns a durable emailSendId; pass it to get_email_send for delivery status and failure details.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to test"},to:{type:"string",description:"Email address to send test to"}},required:["campaignId","to"]}},{name:"cancel_campaign",description:"Cancel a campaign. Stops scheduled and sending campaigns (also works for paused and approval-pending ones). Remaining emails will not be sent and the campaign cannot be restarted - this cannot be undone.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to cancel."}},required:["campaignId"]}},{name:"pause_campaign",description:"Pause a campaign that is currently sending. Only campaigns in sending status can be paused. Use resume_campaign to continue delivery later.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to pause."}},required:["campaignId"]}},{name:"resume_campaign",description:"Resume a paused campaign. Only campaigns in paused status can be resumed. Optionally spread the remaining delivery over a number of hours.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to resume."},spreadOverHours:{type:"number",description:"Spread the remaining delivery over an integer number of hours from 1 to 72."}},required:["campaignId"]}},{name:"delete_campaign",description:"Permanently delete a campaign. This cannot be undone. Sending, scheduled, or paused campaigns must be cancelled with cancel_campaign first.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to delete."}},required:["campaignId"]}},{name:"duplicate_campaign",description:"Duplicate a campaign as a new draft. mode 'campaign' (default) copies the campaign and its email, 'ab_test' also duplicates the campaign's A/B test with all variants, and 'variant' copies a single variant's content as the new campaign email (requires variantId).",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to duplicate."},mode:{type:"string",enum:["campaign","ab_test","variant"],description:"Duplication mode. Defaults to campaign."},variantId:{type:"string",description:"A/B test variant ID whose content becomes the new campaign email. Required when mode is variant."}},required:["campaignId"]}},{name:"resend_campaign_to_non_openers",description:"Create a draft that resends a sent campaign to everyone in the same audience who didn't open it. Copies the campaign email and reuses the original audience with a 'didn't open this campaign' rule added. Only available 6 hours after the campaign finishes sending. The draft must be scheduled or sent separately. Returns the new draft and an estimate of how many subscribers haven't opened the original.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"ID of the sent campaign to resend to non-openers."}},required:["campaignId"]}}];var BH=[{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 FH=[{name:"list_forms",description:"List saved signup forms for a company, including their server-managed audience settings and public action URLs.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list forms for. If not provided, uses the currently selected company."}},additionalProperties:!1}},{name:"create_form",description:"Create and publish a saved signup form whose opaque formId is a client-safe public capability. The selected lists, tags, duplicate behavior, and success action stay server-side; no API key is needed in the deployed form.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the form in. If not provided, uses the currently selected company."},name:{type:"string",description:"Internal saved-form name."},listIds:{type:"array",description:"One or more list IDs that every public submission will be added to. Use list_lists to resolve IDs.",items:{type:"string"}},tagIds:{type:"array",description:"Optional existing tag IDs applied by the saved form. Use list_tags to resolve IDs.",items:{type:"string"}},duplicateStrategy:{type:"string",enum:["skip","merge","overwrite"],description:"How to handle an existing subscriber. Defaults to skip."},buttonText:{type:"string",description:"Optional submit button label."},headline:{type:"string",description:"Optional form headline."},description:{type:"string",description:"Optional supporting form copy."},successMessage:{type:"string",description:"Confirmation shown after a successful submission when redirectUrl is omitted."},redirectUrl:{type:"string",description:"Optional HTTP or HTTPS URL for successful submissions. Omit it to show the saved confirmation message."},showFirstName:{type:"boolean",description:"Whether the generated form also collects first name."},showLastName:{type:"boolean",description:"Whether the generated form also collects last name."}},required:["name","listIds"],additionalProperties:!1}},{name:"get_form_embed",description:"Get a published saved form's action URL, one-line JavaScript embed, minimal native form action, and fetch example. Use this for Astro, Hugo, Jekyll, Cloudflare Pages, Netlify, GitHub Pages, or any browser integration.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},formId:{type:"string",description:"Saved form ID returned by list_forms or create_form."}},required:["formId"],additionalProperties:!1}}];var KH=[{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 MH=[{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 IH=[{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:SD},content:{type:"object",description:Y0,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:Y0,additionalProperties:!0}},required:["landingPageId"],additionalProperties:!1}},{name:"delete_landing_page",description:"Delete a landing page",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID."}},required:["landingPageId"],additionalProperties:!1}},{name:"publish_landing_page",description:"Publish a landing page. Optional name, slug, or content updates are saved before publishing.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID."},name:{type:"string",description:"Optional landing page name update."},slug:{type:"string",description:"Optional slug update before publishing."},content:{type:"object",description:Y0,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:Y0,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 _H=[{name:"list_products",description:"List synced products (Stripe, Shopify, WooCommerce) including any attached digital delivery file. Useful before attaching a file or building a purchase sequence for a specific product.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list products for. If not provided, uses the currently selected company."},provider:{type:"string",description:"Filter by provider: stripe, shopify, woocommerce, or manual."},search:{type:"string",description:"Filter products by title."}}}},{name:"upsert_products",description:"Create or update products in the catalog (Commerce API, keyed by your productId, stored under the api provider). Use this to add products that are not synced from Stripe/Shopify/WooCommerce, then attach a deliverable file with attach_product_file and build a purchase sequence for them.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},products:{type:"array",description:"Products to create or update (max 100).",items:{type:"object",properties:{productId:{type:"string",description:"Your stable product identifier (used for upserts and order line items)."},title:{type:"string",description:"Product title."},description:{type:"string",description:"Product description."},imageUrl:{type:"string",description:"Product image URL."},url:{type:"string",description:"Product page URL."},priceCents:{type:"number",description:"Price in the smallest currency unit."},currency:{type:"string",description:"ISO currency code, e.g. USD."},inStock:{type:"boolean",description:"Whether the product is in stock."}},required:["productId","title"]}}},required:["products"]}},{name:"delete_product",description:"Delete a product previously pushed via upsert_products (Commerce API products only), identified by your productId.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},productId:{type:"string",description:"Your productId used when upserting the product."}},required:["productId"]}},{name:"attach_product_file",description:"Attach a distributable file to a product, either by public URL or by uploading a local file (filePath, local MCP server only). After a purchase of the product, sequence emails can link to it with {{event.download.url}} and {{event.download.name}}.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},productId:{type:"string",description:"Product ID from list_products, or your own productId for products pushed via upsert_products."},url:{type:"string",description:"Public http(s) URL of the file to deliver. Provide url or filePath, not both."},filePath:{type:"string",description:"Local path of a file to upload and attach (PDF, ePub, ZIP, image, audio, video, or text, up to 100MB). Only available when the MCP server runs locally on this machine."},fileName:{type:"string",description:"Display name for the file (e.g. guide.pdf). Used as {{event.download.name}}."}},required:["productId"]}},{name:"remove_product_file",description:"Remove the attached distributable file from a product.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},productId:{type:"string",description:"Product ID from list_products, or your own productId for products pushed via upsert_products."}},required:["productId"]}},{name:"sync_products",description:"Queue a sync of the Stripe product catalog into the products list. Requires an active Stripe integration.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}}];var t$={companyId:{type:"string",description:"Company ID. If omitted, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID."}},ZH={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."}},jH=[{name:"list_sequence_goals",description:"List persisted conversion goals attached to one sequence in the dashboard.",inputSchema:{type:"object",properties:t$,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:{...t$,...ZH},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:{...t$,goalId:{type:"string",description:"Sequence goal ID."},...ZH},required:["sequenceId","goalId"],additionalProperties:!1}},{name:"delete_sequence_goal",description:"Delete one persisted sequence conversion goal.",inputSchema:{type:"object",properties:{...t$,goalId:{type:"string",description:"Sequence goal ID."}},required:["sequenceId","goalId"],additionalProperties:!1}}];var yW={companyId:{type:"string",description:"Company ID. If omitted, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence with an inbound_webhook trigger."}},VH=[{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:yW,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:{...yW,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:yW,required:["sequenceId"],additionalProperties:!1}}];var NH=[{name:"list_sequences",description:"List all email sequences (automations)",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list sequences for. If not provided, uses the currently selected company."},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. 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:"create_sequence",description:"Create and persist a disabled draft email sequence, follow-up series, drip campaign, nurture flow, or automation workflow. For natural-language content, provide goal and emailCount. Use explicit steps for finished caller-supplied content, exact workflows, or migrations. Configure trigger plus its relevant field, such as listId, tagName, segmentId, or eventName. Supports email and SMS steps, delays and date waits, actions that dynamically create a provider discount/code, subscriber updates, event filters, enrollment rules, sending windows, and stop conditions. The saved draft appears in list_sequences. Never call enable_sequence unless the user explicitly asks to activate it.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the sequence in. If not provided, uses the currently selected company."},fromEmail:{type:"string",description:"From address for all emails in this sequence. Its domain must be configured and verified."},fromName:{type:"string",description:"Display name for a newly created sender profile. Requires fromEmail."},senderProfileId:{type:"string",description:"Existing sender profile ID. Mutually exclusive with fromEmail."},replyTo:{type:"string",description:"Reply-To address for all emails in this sequence. A reply profile is created when needed."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo."},replyProfileId:{type:"string",description:"Existing reply profile ID. Mutually exclusive with replyTo."},name:{type:"string",description:"Sequence name (e.g., 'User Onboarding', 'Welcome Series')"},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. Use 'matching_field' only for event_received triggers when duplicate active runs should be blocked per event field value."},enrollmentFieldPath:{type:"string",description:"Scalar dot-path event property used by enrollmentMode='matching_field', such as 'order.id' or 'product.providerVariantId'. Array traversal with [] is not supported; use propertyFilters for array matching. Leave omitted for Shopify back-in-stock/replenishment product-variant defaults."},sendingWindow:h$,stopCondition:{type:"object",description:"Optional explicit auto-stop condition. Use { type: 'has_tag', value: 'customer' } to end the sequence when a subscriber gets a tag, { type: 'does_not_have_tag', value: 'trial' } when a tag is removed, { type: 'entered_segment', value: 'segment_123' } when they enter a segment, { type: 'field_changed', value: 'plan' } when a subscriber field changes, { type: 'removed_from_list', value: 'list_123' } when they leave a list, { type: 'event_received', value: 'onboarding.completed' } when an event is tracked, or { type: 'none', value: null } for no auto-stop.",properties:{type:{type:"string",enum:["none","has_tag","does_not_have_tag","added_to_list","removed_from_list","entered_segment","field_changed","event_received"],description:"Stop condition type."},value:{type:["string","null"],description:"Tag name, list ID, segment ID, field path, or event name for the stop condition. Use null or omit for type 'none'."},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:D1,subject:{type:"string",description:"Email subject. Required for email steps."},previewText:{type:"string",description:"Email preview text."},blocks:{type:"array",description:G1,items:{type:"object"}},html:{type:"string",description:`HTML content for email steps. Use this for imported provider HTML. ${qb}`},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."},...J0,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:X1,delayMs:{type:"number",description:"Delay before this step in milliseconds. Prefer delay for readability; use delayMs when importing provider waits."},waitUntil:q1,name:{type:"string",description:"Email template name for email steps."},discount:{type:"object",description:"Discount configuration for create_discount steps. Prefer this nested shape for new integrations; legacy top-level discount fields are still accepted.",properties:{label:{type:"string",description:"Builder label for the discount step."},provider:{type:"string",enum:["stripe","shopify"],description:"Discount provider. Use 'stripe' to dynamically create a Stripe coupon plus promotion code, or 'shopify' to dynamically create a Shopify Admin discount code. Defaults to 'stripe' when omitted."},discountType:{type:"string",enum:["percent","amount"],description:"Discount type."},percentOff:{type:"number",description:"Percent discount from 1 to 100. Required when discountType is percent."},amountOff:{type:"number",description:"Fixed amount discount in the smallest currency unit, for example 500 for $5. Required when discountType is amount."},currency:{type:"string",description:"ISO currency for amount discounts. Defaults to usd."},duration:{type:"string",enum:["once","forever","repeating"],description:"Discount duration. Defaults to once."},durationInMonths:{type:"number",description:"Required for repeating discounts."},appliesToAllPlans:{type:"boolean",description:"Whether the discount applies to all plans. Defaults to true."},planIds:{type:"array",description:"Provider product IDs when appliesToAllPlans is false. Stripe uses IDs like prod_abc123; Shopify accepts numeric product IDs or gid://shopify/Product/... IDs.",items:{type:"string"}},codePrefix:{type:"string",description:"Optional prefix for generated dynamic codes. The final code also includes a subscriber/token suffix."},maxRedemptions:{type:"number",description:"Maximum redemptions for each generated code. Use 1 for subscriber-specific codes."},lockToSubscriber:{type:"boolean",description:"Stripe-only. Restrict each generated promotion code to the matched subscriber's Stripe customer."},expiresAt:{type:"string",description:"Optional future expiration date or ISO timestamp."},expiresInHours:{type:"number",description:"Optional relative expiration in hours, resolved when each subscriber's code is created (e.g., 48 for a 48-hour window per subscriber). Takes precedence over expiresAt."},name:{type:"string",description:"Optional display name for each dynamically generated provider discount."}}},label:{type:"string",description:"Legacy top-level discount label. Prefer discount.label."},provider:{type:"string",enum:["stripe","shopify"],description:"Legacy top-level discount provider. Prefer discount.provider. Supports 'stripe' and 'shopify'."},discountType:{type:"string",enum:["percent","amount"],description:"Legacy top-level discount type. Prefer discount.discountType."},percentOff:{type:"number",description:"Percent discount from 1 to 100. Required when discountType is percent."},amountOff:{type:"number",description:"Fixed amount discount in the smallest currency unit, for example 500 for $5. Required when discountType is amount."},currency:{type:"string",description:"ISO currency for amount discounts. Defaults to usd."},duration:{type:"string",enum:["once","forever","repeating"],description:"Discount duration. Defaults to once."},durationInMonths:{type:"number",description:"Required for repeating discounts."},appliesToAllPlans:{type:"boolean",description:"Whether the discount applies to all plans. Defaults to true."},planIds:{type:"array",description:"Provider product IDs when appliesToAllPlans is false. Stripe uses IDs like prod_abc123; Shopify accepts numeric product IDs or gid://shopify/Product/... IDs.",items:{type:"string"}},codePrefix:{type:"string",description:"Optional prefix for generated dynamic codes. The final code also includes a subscriber/token suffix."},maxRedemptions:{type:"number",description:"Maximum redemptions for each generated code. Use 1 for subscriber-specific codes."},lockToSubscriber:{type:"boolean",description:"Legacy top-level Stripe-only flag. Prefer discount.lockToSubscriber."},expiresAt:{type:"string",description:"Optional future expiration date or ISO timestamp."},expiresInHours:{type:"number",description:"Optional relative expiration in hours, resolved when each subscriber's code is created (e.g., 48 for a 48-hour window per subscriber). Takes precedence over expiresAt."}}}}},required:["name"]}}];var EH=[{name:"update_sequence",description:"Update an existing sequence. To target a specific existing step, use IDs returned by get_sequence. The emails/steps arrays edit email steps, smsSteps edits SMS steps, and subscriberUpdateSteps replaces the config of action_update_attributes steps. To insert new linear steps, use insertSteps with an afterNodeId from get_sequence; omit afterNodeId only to append to an unambiguous linear tail. For active sequences, structural changes such as insertSteps or branch require confirmStructuralChange:true after the user confirms the live-flow impact.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"},name:{type:"string",description:"Sequence name"},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:"Display name for a newly created sender profile. Requires fromEmail."},senderProfileId:{type:"string",description:"Set an existing sender profile. Mutually exclusive with fromEmail."},replyTo:{type:"string",description:"Set the Reply-To address for all emails in this sequence."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo."},replyProfileId:{type:"string",description:"Set an existing reply profile. Mutually exclusive with replyTo."},enrollmentPaused:{type:"boolean",description:"Set true to stop new enrollments for an active sequence while current recipients continue. Set false to resume new enrollments. The sequence must already be active."},confirmStructuralChange:{type:"boolean",description:"Set true only after the user explicitly confirms a structural edit to an active sequence. Required for insertSteps or branch when the sequence is active; not needed for content-only email edits."},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. '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:h$,clearSendingWindow:{type:"boolean",description:"Set true to remove the sequence sending window. Do not provide this together with sendingWindow."},bccEmails:{type:"array",items:{type:"string"},description:"Email addresses that receive a blind copy of every email this sequence sends, such as a customer support inbox (max 10). Omit to leave unchanged. Use clearBccEmails to remove them."},clearBccEmails:{type:"boolean",description:"Set true to remove the sequence BCC addresses. Do not provide this together with bccEmails."},stopCondition:{type:"object",description:"Update the sequence auto-stop condition. Example: { type: 'has_tag', value: 'customer' } ends the sequence when the subscriber has that tag. Use { type: 'entered_segment', value: 'segment_123' } to stop when they enter a segment, { type: 'field_changed', value: 'plan' } to stop when a subscriber field changes, { type: 'removed_from_list', value: 'list_123' } to stop when they leave a list, or { type: 'none', value: null } to clear it.",properties:{type:{type:"string",enum:["none","has_tag","does_not_have_tag","added_to_list","removed_from_list","entered_segment","field_changed","event_received"]},value:{type:["string","null"],description:"Tag name, list ID, segment ID, field path, or event name for the stop condition."},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:EW},elseSteps:{type:"array",description:"Optional new steps inside the else fallback path.",items:D0},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:D0}},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. ${qb}`},htmlContent:{type:"string",description:`Alias for html for imported provider markup. ${qb}`},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 supported when the entire email is standalone raw HTML and must not be combined with html/htmlContent."},blocks:{type:"array",description:zw,items:{type:"object"}},isTransactional:{type:"boolean"},ccEmails:{type:"array",items:{type:"string"}},bccEmails:{type:"array",items:{type:"string"}},...J0}}},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. ${qb}`},htmlContent:{type:"string",description:`Alias for html. ${qb}`},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 supported when the entire email is standalone raw HTML and must not be combined with html/htmlContent."},blocks:{type:"array",description:zw,items:{type:"object"}},isTransactional:{type:"boolean"},ccEmails:{type:"array",items:{type:"string"}},bccEmails:{type:"array",items:{type:"string"}},...J0}}},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:D1},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:c$.properties.nodeId,changes:KW,expectedUpdatedAt:c$.properties.expectedUpdatedAt,confirmLiveChange:{type:"boolean",description:"Set true only after the user explicitly confirms changing a node in an active sequence."}},required:["sequenceId","nodeId","changes","expectedUpdatedAt"],additionalProperties:!1}},{name:"update_sequence_nodes",description:"Atomically patch multiple existing sequence nodes. Call get_sequence first and include each node's id plus its updatedAt as expectedUpdatedAt. Every patch follows update_sequence_node's type-aware rules. Either every node update commits or none do, making this the preferred tool for changes such as replacing all 5-minute delays with 7-day delays 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:c$},confirmLiveChange:{type:"boolean",description:"Set true only after the user explicitly confirms changing nodes in an active sequence."}},required:["sequenceId","updates"],additionalProperties:!1}},{name:"edit_sequence_graph",description:"Restructure an existing sequence graph using node IDs, edges, and graphRevision from get_sequence. move_node repositions one non-split step; duplicate_node creates an independent copy; delete_node safely splices a node; replace_edges replaces the complete topology. 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, 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:G1,items:{type:"object"}},html:{type:"string",description:`HTML content for an imported provider step. Provide either html or blocks, not both. ${qb}`},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."},senderProfileId:{type:"string",description:"Email steps only: sender profile for the new step. Omit to inherit the effective identity of the nearest sequence email. After a branch merge, only fields shared by every incoming path are inherited; conflicting fields use sequence or company defaults."},fromEmail:{type:"string",description:"Email steps only: From address for the new step. Its domain must be verified. Mutually exclusive with senderProfileId."},fromName:{type:"string",description:"Email steps only: display name override for the new step. With fromEmail, also names a newly created sender profile."},replyProfileId:{type:"string",description:"Email steps only: reply profile for the new step. Omit to inherit the effective Reply-To of the nearest sequence email. After a branch merge, only fields shared by every incoming path are inherited; conflicting fields use sequence or company defaults. Mutually exclusive with replyTo."},replyTo:{type:"string",description:"Email steps only: Reply-To address for the new step. Mutually exclusive with replyProfileId."},replyToName:{type:"string",description:"Email steps only: display name for a newly created reply profile. Requires replyTo."},text:{type:"string",description:"SMS steps only: plain-text message body. Merge tags like {{FIRST_NAME}} work. Do not include opt-out text or a brand prefix - the platform adds those automatically."},imageUrls:{type:"array",items:{type:"string"},description:"SMS steps only: up to 2 publicly reachable image URLs sent as MMS media."},label:{type:"string",description:"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:{...D1,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 URL called when a subscriber reaches this step."},method:{type:"string",enum:["POST","GET"],description:"webhook only: HTTP method. Defaults to POST."},headers:{type:"object",description:"webhook only: optional string-valued request headers. Secret values are redacted on sequence reads.",additionalProperties:{type:"string"}},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:X1,delayMs:{type:"number",description:"Optional wait in milliseconds before the new step. Prefer delay for readability."},waitUntil:q1,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:EW},elseSteps:{type:"array",description:"logic_branch only: optional new steps for the else path.",items:D0},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: subscriberId for one subscriber, or fieldValues to match stored entry event properties. For fieldValues, fieldPath is optional when the sequence has enrollmentFieldPath configured; otherwise provide a dot path such as order.id.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID whose enrollments should be cancelled."},subscriberId:{type:"string",description:"Subscriber ID to cancel in this sequence. Provide subscriberId or fieldValues, not both."},fieldPath:{type:"string",description:"Dot-path inside the token's stored entry event properties, such as order.id or event.id. Optional when the sequence has enrollmentFieldPath configured."},fieldValues:{type:"array",items:{type:"string"},description:"Entry field values to match. Cancels all active/waiting enrollments in the sequence whose entry field value is in this list. Provide fieldValues or subscriberId, not both."},dryRun:{type:"boolean",description:"When true, returns matching enrollments without cancelling them. Field-value cancellation defaults to dryRun on the API unless explicitly false."},reason:{type:"string",description:"Optional cancellation reason stored on matched enrollment tokens."}},required:["sequenceId"],additionalProperties:!1}},{name:"delete_sequence",description:"Delete a sequence",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}}];var dM={type:"object",properties:{email:{type:"string",description:"Subscriber email address"},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}},required:["email"],additionalProperties:!1},TH=[{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"},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide this with email when creating, or instead of email for an existing subscriber."},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."}},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:dM,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, status, attributes, or tags. 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."},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",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:pb},required:[]}},{name:"list_subscriber_notes",description:"List internal notes for a subscriber. Provide email or externalId to identify the subscriber.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."}},required:[]}},{name:"add_subscriber_note",description:"Add an internal note to a subscriber. Provide email or externalId to identify the subscriber.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},body:{type:"string",description:"Internal note body, up to 5000 characters."}},required:["body"]}},{name:"delete_subscriber_note",description:"Delete one internal subscriber note by note ID.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},noteId:{type:"string",description:"Subscriber note ID to delete."}},required:["noteId"]}},{name:"search_subscribers",description:"Search subscribers by free-text query, tags, list, or segment. If you omit limit, the tool fetches all pages and returns every match.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},query:{type:"string",description:"Search query (email or name)"},tags:{type:"array",items:{type:"string"},description:"Filter by tags"},list:{type:"string",description:"Filter by subscriber list ID or exact list name. Prefer listId when known."},listId:{type:"string",description:"Filter by subscriber list ID."},listName:{type:"string",description:"Filter by exact subscriber list name when the list ID is not known."},segmentId:{type:"string",description:"Filter by segment ID"},status:{type:"string",description:"Filter by subscriber status: active, unsubscribed, or bounced."},limit:{type:"number",description:"Maximum results to return. If omitted, the tool returns all matches across pages."}}}}];var SH={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."}},RH=[{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:SH,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:SH,required:["email"],additionalProperties:!1}}];var vH=[{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:[...Y1],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:[...Y1],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:IW,minItems:1,description:'Array of segment filters. Example custom attribute empty check: [{"id":"filter-1","field":"attribute","operator":"is_empty","value":"last_logged_in:"}]. Example Stripe purchase filter: [{"id":"filter-1","field":"stripeProduct","operator":"is","value":"prod_123"}]. Example threshold filter: [{"id":"filter-1","field":"stripeProduct","operator":"at_least","value":"prod_123:3"}]. Example commerce product purchase filter (value is provider:productId since product ids are provider-scoped): [{"id":"filter-1","field":"commerceProduct","operator":"is","value":"api:prod-starter-kit"}]. Example repeat-buyer filter: [{"id":"filter-1","field":"commerceProduct","operator":"at_least","value":"shopify:42:2"}]. Example trial cancellation filter: [{"id":"filter-1","field":"stripeTrialProduct","operator":"is","value":"prod_123:is_canceled"}]. Example trial end filter: [{"id":"filter-1","field":"stripeTrialProduct","operator":"is","value":"prod_123:end_at:2026-05-26"}]. Example campaign-specific engagement combo: [{"id":"filter-1","field":"emailBounced","operator":"is","value":"campaign:cmp_abc"},{"id":"filter-2","field":"emailBounced","operator":"is_not","value":"campaign:cmp_xyz"}]. Combine them with `filterJoinOperator: "or"` to match any filter.'},root:{..._W,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:IW,minItems:1,description:"Replacement segment filters. Same shape and validation rules as create_segment. Mutually exclusive with `root`."},root:{..._W,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 kH=[{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 CH=[{name:"list_templates",description:"List all email templates, including per-locale localization sync status",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"get_template",description:"Get a template's details, content, and all localized variants with sync status",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID"}},required:["templateId"]}},{name:"create_template",description:"Create a new email template. For net-new email content requested in natural language, use `prompt`; do not write HTML or construct blocks yourself. Use `blocks` only for finished caller-supplied Sequenzy content and `html` only for supplied or explicitly requested preserved HTML.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},name:{type:"string",description:"Template name"},subject:{type:"string",description:"Email subject line. Optional with `prompt`."},previewText:{type:["string","null"],description:"Optional preview text override."},html:{type:"string",description:`Email HTML content. Mutually exclusive with \`blocks\`. Use this for imported provider templates. ${qb}`},blocks:{type:"array",description:Hw,items:{type:"object"}},prompt:{type:"string",description:"Natural-language request for Sequenzy to generate branded native template blocks."},style:{type:"string",description:"Generation style; valid only with `prompt`."},tone:{type:"string",description:"Generation tone; valid only with `prompt`."},labels:{type:"array",description:"Optional label names to assign. Missing labels are created automatically.",items:{type:"string"}}},required:["name"]}},{name:"update_template",description:"Update an existing template. At least one of `name`, `subject`, `html`, `blocks`, or `labels` is required, and only those update fields are accepted.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID"},name:{type:"string",description:"Template name"},subject:{type:"string",description:"Email subject line"},html:{type:"string",description:`Email HTML content. Mutually exclusive with \`blocks\`. Use this for imported provider templates. ${qb}`},blocks:{type:"array",description:Hw,items:{type:"object"}},labels:{type:"array",description:"Replacement label names. Send an empty array to clear labels. Missing labels are created automatically.",items:{type:"string"}}},required:["templateId"],additionalProperties:!1}},{name:"set_template_localization",description:"Create or replace one caller-supplied localized variant of a template. The locale must be enabled for the company and cannot be its primary locale. Provide exactly one of `html` or `blocks`.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID, transactional email ID, or slug."},locale:{type:"string",description:"Enabled non-primary locale code such as es, fr, or pt-BR."},subject:{type:"string",description:"Localized email subject line."},previewText:{type:["string","null"],description:"Optional localized inbox preview text."},html:{type:"string",description:`Localized email HTML. Mutually exclusive with \`blocks\`. ${qb}`},blocks:{type:"array",description:Hw,items:{type:"object"}}},required:["templateId","locale","subject"],additionalProperties:!1}},{name:"sync_template_localizations",description:"Queue AI translation for selected template locales. Omit `locales` to sync every enabled non-primary locale. This works even when automatic on-save localization is disabled.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID, transactional email ID, or slug."},locales:{type:"array",description:"Optional enabled non-primary locale codes to sync. Omit to sync all enabled non-primary locales.",items:{type:"string"}}},required:["templateId"],additionalProperties:!1}},{name:"delete_template",description:"Delete a template",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID"}},required:["templateId"]}}];var uH=[{name:"list_transactional_emails",description:"List transactional email templates, including their API slugs and linked email IDs",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"get_transactional_email",description:"Get a transactional email by ID or slug, including subject, preview text, blocks, variables, and linked dashboard URLs",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},idOrSlug:{type:"string",description:"Transactional email ID or API slug, for example `welcome-email`."}},required:["idOrSlug"]}},{name:"create_transactional_email",description:"Create a saved transactional email template with an API slug. For net-new natural-language content use `prompt`; do not author HTML or blocks. `blocks` are finished caller-supplied Sequenzy content and `html` is preserved/imported markup.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},name:{type:"string",description:"Transactional email name."},slug:{type:"string",description:"Optional API slug used when sending by slug, for example `password-reset`. If omitted, Sequenzy generates one from the name."},subject:{type:"string",description:"Email subject line. Optional when `prompt` is provided because the generated subject will be used."},previewText:{type:["string","null"],description:"Email preview text."},html:{type:"string",description:`Email HTML content. Mutually exclusive with \`blocks\`. ${qb}`},blocks:{type:"array",description:`${Hw} Mutually exclusive with \`html\`.`,items:{type:"object"}},prompt:{type:"string",description:"Generate transactional email blocks from a prompt. Generated blocks include the company's branding (logo and a footer without an unsubscribe link). Mutually exclusive with `html` and `blocks`."},style:{type:"string",description:"Prompt generation style: minimal, branded, promotional. Only used with `prompt`."},tone:{type:"string",description:"Prompt generation tone: professional, casual, friendly. Only used with `prompt`."},enabled:{type:"boolean",description:"Whether this transactional email can be sent immediately. Prompt-created templates default to false; explicit HTML/blocks retain the compatibility default of true."}},required:["name"],additionalProperties:!1}},{name:"update_transactional_email",description:"Update a transactional email by ID or slug. At least one of `name`, `enabled`, `subject`, `previewText`, `html`, or `blocks` is required. Use `html` or `blocks` to replace the linked email body.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},idOrSlug:{type:"string",description:"Transactional email ID or API slug, for example `welcome-email`."},name:{type:"string",description:"Transactional email name."},enabled:{type:"boolean",description:"Whether this transactional email can be sent."},subject:{type:"string",description:"Email subject line."},previewText:{type:["string","null"],description:"Email preview text."},html:{type:"string",description:`Email HTML content. Mutually exclusive with \`blocks\`. ${qb}`},blocks:{type:"array",description:`${zw} Mutually exclusive with \`html\`.`,items:{type:"object"}}},required:["idOrSlug"],additionalProperties:!1}},{name:"send_email",description:"Queue one transactional email using either a saved transactional email API slug (`templateId`) or direct `subject` and `html` content. Returns a durable emailSendId; pass it to get_email_send for delivery status and failure details.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},to:{type:"string",description:"Recipient email address"},subject:{type:"string",description:"Email subject line. Required with `html` when `templateId` is omitted."},html:{type:"string",description:"Direct-send HTML body. Required with `subject` when `templateId` is omitted; the MCP server maps this to the transactional API `body` field."},templateId:{type:"string",description:"Saved transactional email API slug, for example `welcome-email`. The field name is retained for MCP compatibility and is mapped to the transactional API `slug` field."},variables:{type:"object",description:"Variables for template personalization. Nested objects and arrays are supported for repeat blocks, for example { items: [...] }."},subscriberExternalId:{type:"string",description:"Customer-owned subscriber ID for attaching analytics/localization on single-recipient sends. Maximum length: 255 characters."}},required:["to"],additionalProperties:!1}}];var xH=[{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:[...J1]},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:[...J1]},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 yH=[...OH,...TH,...RH,..._H,...vH,...LH,...CH,...zH,...PH,...FH,...IH,...KH,...NH,...EH,...jH,...VH,...uH,...UH,...kH,...MH,...xH,...AH,...BH];async function hH(b,w){let $;switch(b){case"get_account":{let W=await z("GET","/api/v1/account"),Q=Lw();$={...W,selectedCompanyId:Q??W.currentCompanyId};break}case"select_company":{let W=w.companyId,Q=await z("GET","/api/v1/account"),G=Q.companies?.find((q)=>q.id===W);if(!G)throw Error(`Company not found. Available companies: ${Q.companies?.map((q)=>`${q.name} (${q.id})`).join(", ")??"none"}`);U0(W),$={success:!0,message:`Switched to company: ${G.name}`,companyId:G.id,companyName:G.name};break}case"get_app_urls":{let W=await o$(w);$={...Dw({companyId:W,campaignId:U(w,"campaignId"),landingPageId:U(w,"landingPageId"),sequenceId:U(w,"sequenceId"),emailId:U(w,"emailId")??U(w,"templateId"),transactionalId:U(w,"transactionalId"),emailSendId:U(w,"emailSendId"),domainId:U(w,"domainId"),status:U(w,"status"),settingsTab:U(w,"settingsTab")}),...W===void 0&&{note:"No company ID is selected. Call get_account, select_company, or pass companyId to get concrete dashboard URLs."}};break}case"create_company":{let W=await z("POST","/api/v1/companies",{name:w.name,domain:w.domain});if(!W.success)throw Error("Failed to create company");let Q=W.company.id,G=6,q=0,X=W.company.status;while(X==="processing"&&q<G){await new Promise((D)=>setTimeout(D,20000)),q++;let J=await z("GET",`/api/v1/companies/${Q}`);if(J.success)X=J.company.status}U0(Q);let Y=await z("GET",`/api/v1/companies/${Q}`);$={success:!0,company:Y.company,message:X==="processing"?"Company created but still processing. You can continue using it while processing completes.":`Company '${Y.company.name}' created and ready to use.`,autoSelected:!0};break}case"get_company":{let W=w.companyId;$=await z("GET",`/api/v1/companies/${W}`);break}case"update_company":{let W=await d$("update_company",w),Q=yD(w);$=await z("PATCH",`/api/v1/companies/${W}`,Q);break}case"get_sync_rules":{let W=w.companyId;$=await z("GET","/api/v1/sync-rules",void 0,W);break}case"update_sync_rules":{let W=w.companyId;if(w.syncRules!==null&&!Array.isArray(w.syncRules))throw Error("`syncRules` must be an array of rules or null when calling `update_sync_rules`.");$=await z("PUT","/api/v1/sync-rules",{syncRules:w.syncRules},W);break}case"get_shopify_automation_settings":{let W=w.companyId;$=await z("GET","/api/v1/shopify/automation-settings",void 0,W);break}case"update_shopify_automation_settings":{let W=w.companyId,Q={};if(w.browseAbandonment!==void 0)Q.browseAbandonment=w.browseAbandonment;if(w.priceDrop!==void 0)Q.priceDrop=w.priceDrop;if(Object.keys(Q).length===0)throw Error("Provide `browseAbandonment` and/or `priceDrop` when calling `update_shopify_automation_settings`.");$=await z("PUT","/api/v1/shopify/automation-settings",Q,W);break}case"create_api_key":{let W=w.companyId,Q={};if(typeof w.name==="string")Q.name=w.name;if(typeof w.preset==="string")Q.preset=w.preset;if(Array.isArray(w.scopes))Q.scopes=w.scopes;$=await z("POST","/api/v1/api-keys",Q,W);break}case"list_api_keys":{let W=await d$(b,w);$=await z("GET","/api/v1/api-keys",void 0,W);break}case"revoke_api_key":case"delete_api_key":{let W=await d$(b,w);$=await z("DELETE",`/api/v1/api-keys/${encodeURIComponent(String(w.apiKeyId))}`,void 0,W);break}case"list_websites":{let W=w.companyId;$=await z("GET","/api/v1/websites",void 0,W);break}case"add_sending_domain":case"add_website":{let W=w.companyId;$=await z("POST","/api/v1/websites",{domain:w.domain},W);break}case"check_website":{let W=w.companyId;$=await z("GET",`/api/v1/websites/${encodeURIComponent(String(w.domain))}`,void 0,W);break}case"verify_sending_domain":{let W=w.companyId;$=await z("POST",`/api/v1/websites/${encodeURIComponent(String(w.domain))}/verify`,void 0,W);break}case"get_integration_guide":$=await z("POST","/api/v1/integration-guide",w);break;default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function cH(b,w){let $;switch(b){case"generate_email":{let W=w.companyId;$=await z("POST","/api/v1/generate/email",w,W);break}case"generate_subject_lines":{let W=w.companyId;$=await z("POST","/api/v1/generate/subjects",w,W);break}case"generate_sms":{let W=w.companyId;$=await z("POST","/api/v1/generate/sms",w,W);break}case"get_sms_settings":{let W=w.companyId;$=await z("GET","/api/v1/sms/settings",void 0,W);break}case"send_test_sms":{let W=w.companyId,Q={to:M("send_test_sms",w,"to")};for(let G of["text","imageUrls","blocks"])if(w[G]!==void 0)Q[G]=w[G];$=await z("POST","/api/v1/sms/test",Q,W);break}case"submit_feedback":{let W=w.companyId,Q={message:M("submit_feedback",w,"message"),source:"mcp"};for(let G of["category","context"])if(w[G]!==void 0)Q[G]=w[G];$=await z("POST","/api/v1/feedback",Q,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function fH(b,w){let $;switch(b){case"list_transactional_emails":{let W=w.companyId;$=await z("GET","/api/v1/transactional",void 0,W);break}case"get_transactional_email":{let W=w.companyId;$=await z("GET",`/api/v1/transactional/${w.idOrSlug}`,void 0,W);break}case"create_transactional_email":{let W=w.companyId,Q=new Set(["companyId","name","slug","subject","previewText","html","blocks","prompt","style","tone","enabled"]),G=Object.keys(w).filter((X)=>!Q.has(X));if(G.length>0)throw Error(`\`create_transactional_email\` accepts only \`name\`, \`slug\`, \`subject\`, \`previewText\`, \`html\`, \`blocks\`, \`prompt\`, \`style\`, \`tone\`, and \`enabled\` fields. Unsupported field${G.length===1?"":"s"}: ${G.map((X)=>`\`${X}\``).join(", ")}.`);sD(w);let q=Object.fromEntries(Object.entries(w).filter(([X])=>X!=="companyId"));$=await z("POST","/api/v1/transactional",q,W);break}case"update_transactional_email":{let W=w.companyId,Q=new Set(["companyId","idOrSlug","name","enabled","subject","previewText","html","blocks"]),G=Object.keys(w).filter((X)=>!Q.has(X));if(G.length>0)throw Error(`\`update_transactional_email\` accepts only \`name\`, \`enabled\`, \`subject\`, \`previewText\`, \`html\`, and \`blocks\` update fields. Unsupported field${G.length===1?"":"s"}: ${G.map((X)=>`\`${X}\``).join(", ")}.`);if(Sb("update_transactional_email",w),w.name===void 0&&w.enabled===void 0&&w.subject===void 0&&w.previewText===void 0&&w.html===void 0&&w.blocks===void 0)throw Error("Provide at least one of `name`, `enabled`, `subject`, `previewText`, `html`, or `blocks` when calling `update_transactional_email`.");let q=Object.fromEntries(Object.entries(w).filter(([X])=>X!=="companyId"&&X!=="idOrSlug"));$=await z("PATCH",`/api/v1/transactional/${w.idOrSlug}`,q,W);break}case"send_email":{let W=w.companyId,Q=M("send_email",w,"to"),G=w.templateId===void 0?void 0:M("send_email",w,"templateId"),q=w.subject===void 0?void 0:M("send_email",w,"subject"),X=w.html===void 0?void 0:M("send_email",w,"html");if(G!==void 0&&(q!==void 0||X!==void 0))throw Error("`templateId` cannot be combined with `subject` or `html` when calling `send_email`.");if(G===void 0&&(q===void 0||X===void 0))throw Error("Provide either `templateId` or both `subject` and `html` when calling `send_email`.");let Y=Object.fromEntries(Object.entries({to:Q,slug:G,subject:q,body:X,variables:w.variables,subscriberExternalId:w.subscriberExternalId}).filter(([,J])=>J!==void 0));$=await z("POST","/api/v1/transactional/send",Y,W);break}case"get_stats":{let W=w.companyId,Q=w.period??"7d",G=new URLSearchParams({period:String(Q)});if(w.includeMachineEngagement===!0)G.set("includeMachineEngagement","true");$=await z("GET",`/api/v1/metrics?${G.toString()}`,void 0,W);break}case"get_campaign_stats":{let W=w.companyId,Q=new URLSearchParams;if(w.includeMachineEngagement===!0)Q.set("includeMachineEngagement","true");let G=Q.toString();$=await z("GET",`/api/v1/metrics/campaigns/${w.campaignId}${G?`?${G}`:""}`,void 0,W);break}case"get_sequence_stats":{let W=w.companyId,Q=new URLSearchParams;if(w.includeMachineEngagement===!0)Q.set("includeMachineEngagement","true");let G=Q.toString();$=await z("GET",`/api/v1/metrics/sequences/${w.sequenceId}${G?`?${G}`:""}`,void 0,W);break}case"list_campaign_events":{let W=w.companyId,Q=M("list_campaign_events",w,"campaignId"),q=RW("list_campaign_events",w).toString();$=await z("GET",`/api/v1/metrics/campaigns/${encodeURIComponent(Q)}/events${q?`?${q}`:""}`,void 0,W);break}case"list_sequence_events":{let W=w.companyId,Q=M("list_sequence_events",w,"sequenceId"),q=RW("list_sequence_events",w).toString();$=await z("GET",`/api/v1/metrics/sequences/${encodeURIComponent(Q)}/events${q?`?${q}`:""}`,void 0,W);break}case"get_subscriber_activity":{let W=w.companyId,Q=Aw("get_subscriber_activity",w),G=await H0(Q,W,{includeMachineEngagement:w.includeMachineEngagement===!0});$={success:G.success,email:G.subscriber.email,emailStats:G.subscriber.emailStats??null,activity:G.subscriber.activity??[],sequenceEnrollments:G.subscriber.sequenceEnrollments??[]};break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function nH(b,w){let $;switch(b){case"list_tags":{let W=w.companyId;$=await z("GET","/api/v1/tags",void 0,W);break}case"create_tag":{let W=w.companyId,Q=M("create_tag",w,"name"),G=Gb("create_tag",w,"color",Y1);$=await z("POST","/api/v1/tags",{name:Q,...G!==void 0&&{color:G}},W);break}case"update_tag":{let W=w.companyId,Q=M("update_tag",w,"tagId"),G=z0("update_tag",w,"color",Y1);$=await z("PATCH",`/api/v1/tags/${encodeURIComponent(Q)}`,{color:G},W);break}case"delete_tag":{let W=w.companyId,Q=M("delete_tag",w,"tagId");$=await z("DELETE",`/api/v1/tags/${encodeURIComponent(Q)}`,void 0,W);break}case"list_lists":{let W=w.companyId;$=await z("GET","/api/v1/lists",void 0,W);break}case"create_list":{let W=w.companyId;$=await z("POST","/api/v1/lists",w,W);break}case"update_list":{let W=w.companyId,Q=M("update_list",w,"listId");if(w.name===void 0&&w.description===void 0&&w.isPrivate===void 0)throw Error("Provide at least one of `name`, `description`, or `isPrivate` when calling `update_list`.");if(w.name!==void 0&&U(w,"name")===void 0)throw Error("`name` cannot be empty when calling `update_list`.");if(w.description!==void 0&&w.description!==null&&typeof w.description!=="string")throw Error("`description` must be a string or null when calling `update_list`.");if(w.isPrivate!==void 0&&typeof w.isPrivate!=="boolean")throw Error("`isPrivate` must be a boolean when calling `update_list`.");$=await z("PATCH",`/api/v1/lists/${encodeURIComponent(Q)}`,{...w.name!==void 0&&{name:U(w,"name")},...w.description!==void 0&&{description:w.description},...w.isPrivate!==void 0&&{isPrivate:w.isPrivate}},W);break}case"delete_list":{let W=w.companyId,Q=M("delete_list",w,"listId");$=await z("DELETE",`/api/v1/lists/${encodeURIComponent(Q)}`,void 0,W);break}case"add_subscribers_to_list":{let W=w.companyId,Q=M("add_subscribers_to_list",w,"listId"),G=kW("add_subscribers_to_list",w),q=Gb("add_subscribers_to_list",w,"duplicateStrategy",["skip","merge","overwrite"])??"skip",X=Gb("add_subscribers_to_list",w,"optInMode",["default","confirmed","double_opt_in"])??"default";$=await z("POST",`/api/v1/lists/${encodeURIComponent(Q)}/subscribers`,{emails:G,duplicateStrategy:q,enrollInSequences:w.enrollInSequences===!0,optInMode:X},W);break}case"remove_subscribers_from_list":{let W=w.companyId,Q=M("remove_subscribers_from_list",w,"listId"),G=kW("remove_subscribers_from_list",w);$=await z("POST",`/api/v1/lists/${encodeURIComponent(Q)}/subscribers/remove`,{emails:G},W);break}case"list_segments":{let W=w.companyId;$=await z("GET","/api/v1/segments",void 0,W);break}case"create_segment":{uD(w);let W=w.companyId;$=await z("POST","/api/v1/segments",{...w,...w.filters!==void 0?{filters:f$(w.filters)}:{},...w.root!==void 0?{root:n$(w.root)}:{}},W);break}case"update_segment":{xD(w);let W=w.companyId,Q=M("update_segment",w,"segmentId"),G=U(w,"name"),q=Gb("update_segment",w,"filterJoinOperator",["and","or"]);$=await z("PATCH",`/api/v1/segments/${encodeURIComponent(Q)}`,{...G!==void 0&&{name:G},...q!==void 0&&{filterJoinOperator:q},...w.filters!==void 0?{filters:f$(w.filters)}:{},...w.root!==void 0?{root:n$(w.root)}:{}},W);break}case"delete_segment":{let W=w.companyId,Q=M("delete_segment",w,"segmentId");$=await z("DELETE",`/api/v1/segments/${encodeURIComponent(Q)}`,void 0,W);break}case"get_segment_count":{let W=w.companyId;$=await z("GET",`/api/v1/segments/${w.segmentId}/count`,void 0,W);break}case"list_audience_syncs":{let W=w.companyId;$=await z("GET","/api/v1/audience-syncs",void 0,W);break}case"list_ad_accounts":{let W=w.companyId;$=await z("GET","/api/v1/ad-accounts",void 0,W);break}case"create_audience_sync":{let W=w.companyId,Q=U(w,"segmentId"),G=U(w,"predefinedSegmentId");if(Q&&G)throw Error("Provide either `segmentId` or `predefinedSegmentId` when calling `create_audience_sync`, not both.");if(!Q&&!G)throw Error("Provide either `segmentId` or `predefinedSegmentId` when calling `create_audience_sync`.");$=await z("POST","/api/v1/audience-syncs",{segmentId:Q,predefinedSegmentId:G,adAccountId:M("create_audience_sync",w,"adAccountId"),audienceName:M("create_audience_sync",w,"audienceName"),...w.frequency!==void 0?{frequency:w.frequency}:{}},W);break}case"update_audience_sync":{let W=w.companyId,Q=M("update_audience_sync",w,"syncId");$=await z("PATCH",`/api/v1/audience-syncs/${encodeURIComponent(Q)}`,{...w.frequency!==void 0?{frequency:w.frequency}:{},...w.isActive!==void 0?{isActive:w.isActive}:{}},W);break}case"delete_audience_sync":{let W=w.companyId,Q=M("delete_audience_sync",w,"syncId");$=await z("DELETE",`/api/v1/audience-syncs/${encodeURIComponent(Q)}`,void 0,W);break}case"sync_audience_now":{let W=w.companyId,Q=M("sync_audience_now",w,"syncId");$=await z("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 iH(b,w){let $;switch(b){case"list_templates":{let W=w.companyId,Q=new URLSearchParams,G=U(w,"label");if(G)Q.set("label",G);$=await z("GET",`/api/v1/templates${Q.size>0?`?${Q}`:""}`,void 0,W);break}case"get_template":{let W=w.companyId;$=await z("GET",`/api/v1/templates/${w.templateId}`,void 0,W);break}case"create_template":{let W=w.companyId;tD(w);let Q=Object.fromEntries(Object.entries(w).filter(([G])=>G!=="companyId"));$=await z("POST","/api/v1/templates",Q,W);break}case"update_template":{let W=w.companyId,Q=new Set(["companyId","templateId","name","subject","html","blocks","labels"]),G=Object.keys(w).filter((q)=>!Q.has(q));if(G.length>0)throw Error(`\`update_template\` accepts only \`name\`, \`subject\`, \`html\`, \`blocks\`, and \`labels\` update fields. Unsupported field${G.length===1?"":"s"}: ${G.map((q)=>`\`${q}\``).join(", ")}.`);if(Sb("update_template",w),Ow("update_template",w),w.name===void 0&&w.subject===void 0&&w.html===void 0&&w.blocks===void 0&&w.labels===void 0)throw Error("Provide at least one of `name`, `subject`, `html`, `blocks`, or `labels` when calling `update_template`.");$=await z("PUT",`/api/v1/templates/${w.templateId}`,w,W);break}case"set_template_localization":{let W=w.companyId,Q=M("set_template_localization",w,"templateId"),G=M("set_template_localization",w,"locale"),q=M("set_template_localization",w,"subject"),X=new Set(["companyId","templateId","locale","subject","previewText","html","blocks"]),Y=Object.keys(w).filter((D)=>!X.has(D));if(Y.length>0)throw Error(`\`set_template_localization\` received unsupported field${Y.length===1?"":"s"}: ${Y.map((D)=>`\`${D}\``).join(", ")}.`);Sb("set_template_localization",w,{requireContent:!0});let J={subject:q};if(w.previewText!==void 0)J.previewText=w.previewText;if(w.html!==void 0)J.html=w.html;if(w.blocks!==void 0)J.blocks=w.blocks;$=await z("PUT",`/api/v1/templates/${encodeURIComponent(Q)}/localizations/${encodeURIComponent(G)}`,J,W);break}case"sync_template_localizations":{let W=w.companyId,Q=M("sync_template_localizations",w,"templateId"),G=new Set(["companyId","templateId","locales"]),q=Object.keys(w).filter((Y)=>!G.has(Y));if(q.length>0)throw Error(`\`sync_template_localizations\` received unsupported field${q.length===1?"":"s"}: ${q.map((Y)=>`\`${Y}\``).join(", ")}.`);let X;if(w.locales!==void 0){if(!Array.isArray(w.locales)||w.locales.length===0||w.locales.some((Y)=>typeof Y!=="string"||Y.trim().length===0))throw Error("`locales` must contain at least one non-empty locale string when calling `sync_template_localizations`.");X=w.locales.map((Y)=>Y.trim())}$=await z("POST",`/api/v1/templates/${encodeURIComponent(Q)}/localizations/sync`,X===void 0?{}:{locales:X},W);break}case"delete_template":{let W=w.companyId;$=await z("DELETE",`/api/v1/templates/${w.templateId}`,void 0,W);break}case"list_ab_tests":{let W=w.companyId,Q=new URLSearchParams,G=U(w,"sequenceId");if(G)Q.set("sequenceId",G);$=await z("GET",`/api/v1/ab-tests${Q.size>0?`?${Q}`:""}`,void 0,W);break}case"get_ab_test":{let W=w.companyId;$=await z("GET",`/api/v1/ab-tests/${w.abTestId}`,void 0,W);break}case"get_ab_test_stats":{let W=w.companyId,Q=new URLSearchParams,G=U(w,"period"),q=U(w,"start"),X=U(w,"end");if(G)Q.set("period",G);if(q)Q.set("start",q);if(X)Q.set("end",X);if(w.includeMachineEngagement===!0)Q.set("includeMachineEngagement","true");$=await z("GET",`/api/v1/ab-tests/${w.abTestId}/stats${Q.size>0?`?${Q}`:""}`,void 0,W);break}case"restart_ab_test":{let W=w.companyId,Q=new Set(["companyId","abTestId","sourceVariantId","testType","winnerThreshold","variantCount"]),G=Object.keys(w).filter((J)=>!Q.has(J));if(G.length>0)throw Error(`\`restart_ab_test\` accepts only \`sourceVariantId\`, \`testType\`, \`winnerThreshold\`, and \`variantCount\` option fields. Unsupported field${G.length===1?"":"s"}: ${G.map((J)=>`\`${J}\``).join(", ")}.`);let q=U(w,"testType");if(q!==void 0&&q!=="subject"&&q!=="content")throw Error("`restart_ab_test` testType must be `subject` or `content`.");let X=w.winnerThreshold===void 0?void 0:Number(w.winnerThreshold);if(X!==void 0&&(!Number.isInteger(X)||X<10||X>1000))throw Error("`restart_ab_test` winnerThreshold must be an integer from 10 to 1000.");let Y=w.variantCount===void 0?void 0:Number(w.variantCount);if(Y!==void 0&&(!Number.isInteger(Y)||Y<2||Y>4))throw Error("`restart_ab_test` variantCount must be an integer from 2 to 4.");$=await z("POST",`/api/v1/ab-tests/${w.abTestId}/restart`,{sourceVariantId:U(w,"sourceVariantId"),testType:q,winnerThreshold:X,variantCount:Y},W);break}case"update_ab_test_variant":{let W=w.companyId,Q=new Set(["companyId","abTestId","variantId","subject","previewText","html","blocks","confirmLiveChange"]),G=Object.keys(w).filter((q)=>!Q.has(q));if(G.length>0)throw Error(`\`update_ab_test_variant\` accepts only \`subject\`, \`previewText\`, \`html\`, \`blocks\`, and \`confirmLiveChange\` fields. Unsupported field${G.length===1?"":"s"}: ${G.map((q)=>`\`${q}\``).join(", ")}.`);if(Sb("update_ab_test_variant",w),w.confirmLiveChange!==void 0&&typeof w.confirmLiveChange!=="boolean")throw Error("`confirmLiveChange` must be a boolean when calling `update_ab_test_variant`.");if(w.subject===void 0&&w.previewText===void 0&&w.html===void 0&&w.blocks===void 0)throw Error("Provide at least one of `subject`, `previewText`, `html`, or `blocks` when calling `update_ab_test_variant`.");$=await z("PATCH",`/api/v1/ab-tests/${w.abTestId}/variants/${w.variantId}`,w,W);break}case"create_ab_test":{let W=w.companyId,Q=U(w,"campaignId"),G=U(w,"automationNodeId");if(w.confirmLiveChange!==void 0&&typeof w.confirmLiveChange!=="boolean")throw Error("`confirmLiveChange` must be a boolean when calling `create_ab_test`.");if(Boolean(Q)===Boolean(G))throw Error("Provide exactly one of `campaignId` or `automationNodeId` when calling `create_ab_test`.");let q=U(w,"name"),X=ab("create_ab_test",w,"testPercentage",5,50),Y=ab("create_ab_test",w,"testDurationMinutes",15,1440),J=Gb("create_ab_test",w,"winnerCriteria",["open_rate","click_rate"]),D=Gb("create_ab_test",w,"testType",["subject","content"]),H=ab("create_ab_test",w,"winnerThreshold",10,1000);if(w.variants!==void 0){if(!Array.isArray(w.variants))throw Error("`variants` must be an array when calling `create_ab_test`.");w.variants.forEach((A,B)=>{if(!k(A)||typeof A.subject!=="string"||A.subject.trim()==="")throw Error(`\`variants\` item ${B+1} must include a non-empty \`subject\` when calling \`create_ab_test\`.`);if(A.blocks!==void 0&&!Array.isArray(A.blocks))throw Error(`\`variants\` item ${B+1} \`blocks\` must be an array when calling \`create_ab_test\`.`)})}let O=Array.isArray(w.variants)?w.variants:void 0;if(G!==void 0&&(!O||O.length<1))throw Error("`variants` must include at least one competing variant when calling `create_ab_test` with `automationNodeId`.");if(O&&O.length>4)throw Error("`variants` supports at most four extra variants when calling `create_ab_test`.");$=await z("POST","/api/v1/ab-tests",{...Q!==void 0&&{campaignId:Q},...G!==void 0&&{automationNodeId:G},...w.confirmLiveChange===!0&&{confirmLiveChange:!0},...q!==void 0&&{name:q},...X!==void 0&&{testPercentage:X},...Y!==void 0&&{testDurationMinutes:Y},...J!==void 0&&{winnerCriteria:J},...D!==void 0&&{testType:D},...H!==void 0&&{winnerThreshold:H},...w.variants!==void 0&&{variants:w.variants}},W);break}case"add_ab_test_variant":{let W=w.companyId,Q=M("add_ab_test_variant",w,"abTestId"),G=M("add_ab_test_variant",w,"subject"),q=U(w,"previewText");if(w.blocks!==void 0&&!Array.isArray(w.blocks))throw Error("`blocks` must be an array when calling `add_ab_test_variant`.");if(w.confirmLiveChange!==void 0&&typeof w.confirmLiveChange!=="boolean")throw Error("`confirmLiveChange` must be a boolean when calling `add_ab_test_variant`.");$=await z("POST",`/api/v1/ab-tests/${encodeURIComponent(Q)}/variants`,{subject:G,...q!==void 0&&{previewText:q},...w.blocks!==void 0&&{blocks:w.blocks},...w.confirmLiveChange===!0&&{confirmLiveChange:!0}},W);break}case"delete_ab_test_variant":{let W=w.companyId,Q=M("delete_ab_test_variant",w,"abTestId"),G=M("delete_ab_test_variant",w,"variantId");if(w.confirmLiveChange!==void 0&&typeof w.confirmLiveChange!=="boolean")throw Error("`confirmLiveChange` must be a boolean when calling `delete_ab_test_variant`.");$=await z("DELETE",`/api/v1/ab-tests/${encodeURIComponent(Q)}/variants/${encodeURIComponent(G)}${w.confirmLiveChange===!0?"?confirmLiveChange=true":""}`,void 0,W);break}case"delete_ab_test":{let W=w.companyId,Q=M("delete_ab_test",w,"abTestId");$=await z("DELETE",`/api/v1/ab-tests/${encodeURIComponent(Q)}`,void 0,W);break}case"list_campaigns":{let W=w.companyId,Q=new URLSearchParams;if(w.status)Q.set("status",String(w.status));let G=U(w,"label");if(G)Q.set("label",G);$=await z("GET",`/api/v1/campaigns?${Q}`,void 0,W);break}case"get_campaign":{let W=w.companyId;$=await z("GET",`/api/v1/campaigns/${w.campaignId}`,void 0,W);break}case"get_email_send":{let W=w.companyId;$=await z("GET",`/api/v1/email-sends/${encodeURIComponent(String(w.emailSendId))}`,void 0,W);break}case"create_campaign":{let W=w.companyId;if(dD(w),w.fromEmail!==void 0&&w.senderProfileId!==void 0)throw Error("Provide either `fromEmail` or `senderProfileId` when calling `create_campaign`, not both.");if(w.replyTo!==void 0&&w.replyProfileId!==void 0)throw Error("Provide either `replyTo` or `replyProfileId` when calling `create_campaign`, not both.");if(w.fromName!==void 0&&w.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `create_campaign`.");if(w.replyToName!==void 0&&w.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `create_campaign`.");let Q=Object.fromEntries(Object.entries(w).filter(([G])=>G!=="companyId"));$=await z("POST","/api/v1/campaigns",Q,W);break}case"update_campaign":{let W=w.companyId,Q=new Set(["companyId","campaignId","name","subject","trackingCode","html","blocks","fromEmail","fromName","senderProfileId","replyTo","replyToName","replyProfileId","ccEmails","bccEmails","campaignData","computedLists","labels"]),G=Object.keys(w).filter((q)=>!Q.has(q));if(G.length>0)throw Error(`\`update_campaign\` accepts only content, sending identity, campaign data, computed list, and label update fields. Unsupported field${G.length===1?"":"s"}: ${G.map((q)=>`\`${q}\``).join(", ")}.`);if(Sb("update_campaign",w),Ow("update_campaign",w),w.replyTo!==void 0&&w.replyProfileId!==void 0)throw Error("Provide either `replyTo` or `replyProfileId` when calling `update_campaign`, not both.");if(w.fromEmail!==void 0&&w.senderProfileId!==void 0)throw Error("Provide either `fromEmail` or `senderProfileId` when calling `update_campaign`, not both.");if(w.fromName!==void 0&&w.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `update_campaign`.");if(w.replyToName!==void 0&&w.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `update_campaign`.");if(w.name===void 0&&w.subject===void 0&&w.trackingCode===void 0&&w.html===void 0&&w.blocks===void 0&&w.fromEmail===void 0&&w.senderProfileId===void 0&&w.replyTo===void 0&&w.replyProfileId===void 0&&w.ccEmails===void 0&&w.bccEmails===void 0&&w.campaignData===void 0&&w.computedLists===void 0&&w.labels===void 0)throw Error("Provide at least one campaign content, sending identity, campaign data, computed list, or label field when calling `update_campaign`.");$=await z("PUT",`/api/v1/campaigns/${w.campaignId}`,w,W);break}case"schedule_campaign":{let W=w.companyId,Q=new Set(["companyId","campaignId","scheduledAt","targetLists","sendTimeOptimization","spreadOverHours","recurringInterval"]),G=Object.keys(w).filter((q)=>!Q.has(q));if(G.length>0)throw Error(`\`schedule_campaign\` accepts only \`campaignId\`, \`scheduledAt\`, \`targetLists\`, \`sendTimeOptimization\`, \`spreadOverHours\`, and \`recurringInterval\`. Unsupported field${G.length===1?"":"s"}: ${G.map((q)=>`\`${q}\``).join(", ")}.`);rD(w),$=await z("POST",`/api/v1/campaigns/${w.campaignId}/schedule`,{scheduledAt:w.scheduledAt,...w.targetLists!==void 0&&{targetLists:w.targetLists},...w.sendTimeOptimization!==void 0&&{sendTimeOptimization:w.sendTimeOptimization},...w.spreadOverHours!==void 0&&{spreadOverHours:w.spreadOverHours},...w.recurringInterval!==void 0&&{recurringInterval:w.recurringInterval}},W);break}case"send_test_email":{let W=w.companyId;$=await z("POST",`/api/v1/campaigns/${w.campaignId}/test`,{to:w.to},W);break}case"cancel_campaign":{let W=w.companyId,Q=M("cancel_campaign",w,"campaignId");$=await z("POST",`/api/v1/campaigns/${encodeURIComponent(Q)}/cancel`,void 0,W);break}case"pause_campaign":{let W=w.companyId,Q=M("pause_campaign",w,"campaignId");$=await z("POST",`/api/v1/campaigns/${encodeURIComponent(Q)}/pause`,void 0,W);break}case"resume_campaign":{let W=w.companyId,Q=M("resume_campaign",w,"campaignId"),G=ab("resume_campaign",w,"spreadOverHours",1,72);$=await z("POST",`/api/v1/campaigns/${encodeURIComponent(Q)}/resume`,{...G!==void 0&&{spreadOverHours:G}},W);break}case"delete_campaign":{let W=w.companyId,Q=M("delete_campaign",w,"campaignId");$=await z("DELETE",`/api/v1/campaigns/${encodeURIComponent(Q)}`,void 0,W);break}case"duplicate_campaign":{let W=w.companyId,Q=M("duplicate_campaign",w,"campaignId"),G=Gb("duplicate_campaign",w,"mode",["campaign","ab_test","variant"]),q=U(w,"variantId");if(G==="variant"&&q===void 0)throw Error("`variantId` is required when calling `duplicate_campaign` with mode `variant`.");$=await z("POST",`/api/v1/campaigns/${encodeURIComponent(Q)}/duplicate`,{...G!==void 0&&{mode:G},...q!==void 0&&{variantId:q}},W);break}case"resend_campaign_to_non_openers":{let W=w.companyId,Q=M("resend_campaign_to_non_openers",w,"campaignId");$=await z("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 mH(b,w){let $;switch(b){case"list_forms":{let W=w.companyId;$=await z("GET","/api/v1/forms",void 0,W);break}case"create_form":{let W=w.companyId,Q=M("create_form",w,"name"),G=Array.isArray(w.listIds)?w.listIds.filter((Y)=>typeof Y==="string").map((Y)=>Y.trim()).filter(Boolean):[];if(G.length===0)throw Error("`listIds` must contain at least one list ID when calling `create_form`.");let q=Gb("create_form",w,"duplicateStrategy",["skip","merge","overwrite"]),X={name:Q,listIds:G};for(let Y of["tagIds","buttonText","headline","description","successMessage","redirectUrl","showFirstName","showLastName"])if(w[Y]!==void 0)X[Y]=w[Y];if(q!==void 0)X.duplicateStrategy=q;$=await z("POST","/api/v1/forms",X,W);break}case"get_form_embed":{let W=w.companyId,Q=M("get_form_embed",w,"formId");$=await z("GET",`/api/v1/forms/embed/${encodeURIComponent(Q)}`,void 0,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}function r$(b,w,$,W,Q){let G=b[w];if(G===void 0)return;if(typeof G!=="number"||!Number.isFinite(G)||G<$||G>W||Q&&!Number.isInteger(G))throw Error(`\`${w}\` must be a ${Q?"integer":"number"} between ${$} and ${W} when calling \`upload_image_asset\`.`);return G}async function lH(b,w){if(b!=="upload_image_asset")return{handled:!1,result:void 0};let $=U(w,"filePath"),W=U(w,"imageBase64");if($===void 0===(W===void 0))throw Error("Provide either `filePath` or `imageBase64` (not both) when calling `upload_image_asset`.");let Q=U(w,"filename");if(W!==void 0&&Q===void 0)throw Error("`filename` is required with `imageBase64` when calling `upload_image_asset`.");let G=r$(w,"sourceWidth",1,20000,!0),q=r$(w,"sourceHeight",1,20000,!0);if(G===void 0!==(q===void 0))throw Error("Provide both `sourceWidth` and `sourceHeight` when calling `upload_image_asset`.");let X=r$(w,"displayWidthPercent",1,100,!1)??100,Y=r$(w,"cropHeight",1,2000,!0),J=U(w,"objectFit");if(J!==void 0&&J!=="cover"&&J!=="contain")throw Error("`objectFit` must be 'cover' or 'contain' when calling `upload_image_asset`.");if(J!==void 0&&Y===void 0)throw Error("`objectFit` can only be used with `cropHeight` when calling `upload_image_asset`.");let D=U(w,"align");if(D!==void 0&&!["left","center","right"].includes(D))throw Error("`align` must be 'left', 'center', or 'right' when calling `upload_image_asset`.");let H=typeof w.altText==="string"?w.altText.trim():void 0;if(H!==void 0&&H.length>500)throw Error("`altText` must be 500 characters or fewer when calling `upload_image_asset`.");let O=await JH({companyId:U(w,"companyId"),filePath:$,imageBase64:W,filename:Q,contentType:U(w,"contentType"),altText:H,sourceWidth:G,sourceHeight:q}),A={type:"image",src:O.url,alt:O.altText??"",width:X,widthType:"percent",...Y!==void 0&&{height:Y,objectFit:J??"cover"},...D!==void 0&&{align:D}};return{handled:!0,result:{success:!0,asset:O,imageBlock:A,message:"Insert imageBlock into the target email's blocks array with its create or update tool."}}}async function gH(b,w){let $;switch(b){case"list_landing_pages":{let W=w.companyId;$=await z("GET","/api/v1/landing-pages",void 0,W);break}case"get_landing_page":{let W=w.companyId;$=await z("GET",`/api/v1/landing-pages/${w.landingPageId}`,void 0,W);break}case"create_landing_page":{let W=w.companyId,Q=new Set(["companyId","name","slug","template","content"]),G=Object.keys(w).filter((q)=>!Q.has(q));if(G.length>0)throw Error(`\`create_landing_page\` accepts only \`name\`, \`slug\`, \`template\`, and \`content\` fields. Unsupported field${G.length===1?"":"s"}: ${G.map((q)=>`\`${q}\``).join(", ")}.`);$=await z("POST","/api/v1/landing-pages",{...w.name!==void 0&&{name:w.name},...w.slug!==void 0&&{slug:w.slug},...w.template!==void 0&&{template:w.template},...w.content!==void 0&&{content:w.content}},W);break}case"update_landing_page":{let W=w.companyId,Q=g$("update_landing_page",w,{requireUpdate:!0});$=await z("PUT",`/api/v1/landing-pages/${w.landingPageId}`,Q,W);break}case"publish_landing_page":{let W=w.companyId,Q=g$("publish_landing_page",w,{requireUpdate:!1});$=await z("POST",`/api/v1/landing-pages/${w.landingPageId}/publish`,Q,W);break}case"unpublish_landing_page":{let W=w.companyId,Q=g$("unpublish_landing_page",w,{requireUpdate:!1});$=await z("POST",`/api/v1/landing-pages/${w.landingPageId}/unpublish`,Q,W);break}case"delete_landing_page":{let W=w.companyId;$=await z("DELETE",`/api/v1/landing-pages/${w.landingPageId}`,void 0,W);break}case"connect_landing_page_domain":{let W=w.companyId;$=await z("POST","/api/v1/landing-pages/domain",{domain:w.domain},W);break}case"update_landing_page_domain_settings":{let W=w.companyId,Q=eD(w);$=await z("PUT","/api/v1/landing-pages/domain",Q,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function pH(b,w){let $;switch(b){case"list_products":{let W=w.companyId,Q=new URLSearchParams;if(typeof w.provider==="string"&&w.provider.trim())Q.set("provider",w.provider.trim());if(typeof w.search==="string"&&w.search.trim())Q.set("search",w.search.trim());let G=Q.size>0?`?${Q.toString()}`:"";$=await z("GET",`/api/v1/products${G}`,void 0,W);break}case"upsert_products":{let W=w.companyId;if(!Array.isArray(w.products)||w.products.length===0)throw Error("`products` must be a non-empty array when calling `upsert_products`.");$=await z("POST","/api/v1/products",{products:w.products},W);break}case"delete_product":{let W=w.companyId,Q=M("delete_product",w,"productId");$=await z("DELETE",`/api/v1/products/${encodeURIComponent(Q)}`,void 0,W);break}case"attach_product_file":{let W=w.companyId,Q=M("attach_product_file",w,"productId"),G=U(w,"url"),q=U(w,"filePath");if(G===void 0===(q===void 0))throw Error("Provide either `url` or `filePath` (not both) when calling `attach_product_file`.");let X;if(q!==void 0){let Y=await WH(q,W);X={url:Y.url,source:"upload",fileName:U(w,"fileName")??Y.fileName,fileSizeBytes:Y.fileSizeBytes,mimeType:Y.mimeType}}else{X={url:G};let Y=U(w,"fileName");if(Y)X.fileName=Y}$=await z("PUT",`/api/v1/products/${encodeURIComponent(Q)}/delivery`,X,W);break}case"remove_product_file":{let W=w.companyId,Q=M("remove_product_file",w,"productId");$=await z("DELETE",`/api/v1/products/${encodeURIComponent(Q)}/delivery`,void 0,W);break}case"sync_products":{let W=w.companyId;$=await z("POST","/api/v1/products/sync",void 0,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}var oH=80;function tM(b){let w=b.trim().replace(/\s+/g," ");if(w.length<=oH)return w;return`${w.slice(0,oH-3).trimEnd()}...`}async function hW(b,w){let $;switch(b){case"generate_sequence":{let W=M("generate_sequence",w,"goal"),Q=typeof w.name==="string"&&w.name.trim().length>0?w.name.trim():void 0,q=(await hW("create_sequence",{...w,goal:W,name:Q??tM(W),trigger:"contact_added",durationDays:w.durationDays??14})).result;return{handled:!0,result:typeof q==="object"&&q!==null?{...q,deprecated:!0,deprecationMessage:"generate_sequence is deprecated. Use create_sequence for new integrations."}:q}}case"list_sequences":{let W=w.companyId,Q=new URLSearchParams;for(let q of["status","search","limit","offset"])if(w[q]!==void 0)Q.set(q,String(w[q]));if(Array.isArray(w.labels)&&w.labels.length>0)Q.set("labels",w.labels.join(","));let G=Q.size>0?`?${Q.toString()}`:"";$=await z("GET",`/api/v1/sequences${G}`,void 0,W);break}case"get_sequence":{let W=w.companyId;$=await z("GET",`/api/v1/sequences/${w.sequenceId}`,void 0,W);break}case"create_sequence":{let W=w.companyId;if(Ow("create_sequence",w),w.fromEmail!==void 0&&w.senderProfileId!==void 0)throw Error("Provide either `fromEmail` or `senderProfileId` when calling `create_sequence`, not both.");if(w.replyTo!==void 0&&w.replyProfileId!==void 0)throw Error("Provide either `replyTo` or `replyProfileId` when calling `create_sequence`, not both.");if(w.fromName!==void 0&&w.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `create_sequence`.");if(w.replyToName!==void 0&&w.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `create_sequence`.");let Q=Array.isArray(w.steps),G=w.goal===void 0&&w.steps===void 0,q=await z("POST","/api/v1/sequences",w,W);if(!q.success){$=q;break}let X=q.sequence.id;if(Q||G){let O=await z("GET",`/api/v1/sequences/${X}`,void 0,W);if(O.success)$={...q,success:!0,sequence:O.sequence,message:`Sequence "${O.sequence.name}" created ${G?"as a blank draft":"with explicit steps"}. Review it before enabling.${q.eventTrackingCode?" Add the custom event feed using eventTrackingCode and eventTracking before enabling.":""}`};else $=O;break}let Y=7,J=0,D="pending";while(D!=="complete"&&J<Y){let O=await z("GET",`/api/v1/sequences/${X}`,void 0,W);if(O.success)D=O.sequence.enrichmentStatus;if(J++,D!=="complete"&&J<Y)await new Promise((A)=>setTimeout(A,20000))}let H=await z("GET",`/api/v1/sequences/${X}`,void 0,W);if(H.success)$={...q,success:!0,sequence:H.sequence,message:H.sequence.enrichmentStatus==="complete"?`Sequence "${H.sequence.name}" created with ${H.sequence.emailCount} AI-generated emails. The sequence is ready to review and enable.${q.eventTrackingCode?" Add the custom event feed using eventTrackingCode and eventTracking before enabling.":""}`:`Sequence "${H.sequence.name}" created. Email enrichment is still in progress (${H.sequence.enrichedCount}/${H.sequence.emailCount} emails generated). You can check status with get_sequence.${q.eventTrackingCode?" Add the custom event feed using eventTrackingCode and eventTracking before enabling.":""}`};else $=H;break}case"update_sequence":{let W=w.companyId,Q=cD(w);$=await z("PUT",`/api/v1/sequences/${w.sequenceId}`,Q,W);break}case"update_sequence_node":{let W=w.companyId,Q=M("update_sequence_node",w,"sequenceId"),G=mD(w);$=await z("PUT",`/api/v1/sequences/${Q}`,G,W);break}case"update_sequence_nodes":{let W=w.companyId,Q=M("update_sequence_nodes",w,"sequenceId"),G=lD(w);$=await z("PUT",`/api/v1/sequences/${Q}`,G,W);break}case"edit_sequence_graph":{let W=w.companyId,Q=gD(w);$=await z("PUT",`/api/v1/sequences/${w.sequenceId}`,Q,W);break}case"insert_sequence_step":{let W=w.companyId,Q=pD(w),G=await z("PUT",`/api/v1/sequences/${w.sequenceId}`,Q,W);if(typeof G==="object"&&G!==null){let q=G,X=q.sequence;if(typeof X==="object"&&X!==null){let Y=X;$={...q,...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}}$=G;break}case"enable_sequence":{let W=w.companyId;$=await z("POST",`/api/v1/sequences/${w.sequenceId}/enable`,void 0,W);break}case"disable_sequence":{let W=w.companyId;$=await z("POST",`/api/v1/sequences/${w.sequenceId}/disable`,void 0,W);break}case"duplicate_sequence":{let W=w.companyId,Q=M("duplicate_sequence",w,"sequenceId"),G=U(w,"name");$=await z("POST",`/api/v1/sequences/${encodeURIComponent(Q)}/duplicate`,G===void 0?void 0:{name:G},W);break}case"archive_sequence":case"unarchive_sequence":{let W=w.companyId,Q=M(b,w,"sequenceId"),G=b==="archive_sequence"?"archive":"unarchive";$=await z("POST",`/api/v1/sequences/${encodeURIComponent(Q)}/${G}`,void 0,W);break}case"list_sequence_goals":{let W=w.companyId,Q=M(b,w,"sequenceId");$=await z("GET",`/api/v1/sequences/${encodeURIComponent(Q)}/goals`,void 0,W);break}case"create_sequence_goal":case"update_sequence_goal":{let W=w.companyId,Q=M(b,w,"sequenceId");if(b==="create_sequence_goal")M(b,w,"name"),fD(w);else nD(w);let G=b==="update_sequence_goal"?M(b,w,"goalId"):void 0,q={...w};delete q.companyId,delete q.sequenceId,delete q.goalId,$=await z(b==="create_sequence_goal"?"POST":"PATCH",`/api/v1/sequences/${encodeURIComponent(Q)}/goals${G?`/${encodeURIComponent(G)}`:""}`,q,W);break}case"delete_sequence_goal":{let W=w.companyId,Q=M(b,w,"sequenceId"),G=M(b,w,"goalId");$=await z("DELETE",`/api/v1/sequences/${encodeURIComponent(Q)}/goals/${encodeURIComponent(G)}`,void 0,W);break}case"get_sequence_inbound_webhook":case"configure_sequence_inbound_webhook":case"rotate_sequence_inbound_webhook_secret":{let W=w.companyId,Q=M(b,w,"sequenceId");if(w.clearFieldMapping===!0&&w.fieldMapping!==void 0)throw Error("Provide either `fieldMapping` or `clearFieldMapping`, not both.");if(w.clearSamplePayload===!0&&w.samplePayload!==void 0)throw Error("Provide either `samplePayload` or `clearSamplePayload`, not both.");let G=b==="configure_sequence_inbound_webhook",q=b==="rotate_sequence_inbound_webhook_secret",X=G?{...w.clearFieldMapping===!0?{fieldMapping:null}:w.fieldMapping!==void 0?{fieldMapping:w.fieldMapping}:{},...w.clearSamplePayload===!0?{samplePayload:null}:w.samplePayload!==void 0?{samplePayload:w.samplePayload}:{}}:void 0;$=await z(q?"POST":G?"PUT":"GET",`/api/v1/sequences/${encodeURIComponent(Q)}/inbound-webhook${q?"/rotate-secret":""}`,X,W);break}case"pause_sequence_enrollments":{let W=w.companyId;$=await z("POST",`/api/v1/sequences/${w.sequenceId}/pause-enrollments`,void 0,W);break}case"resume_sequence_enrollments":{let W=w.companyId;$=await z("POST",`/api/v1/sequences/${w.sequenceId}/resume-enrollments`,void 0,W);break}case"enroll_subscribers_in_sequence":{let W=w.companyId,Q=M("enroll_subscribers_in_sequence",w,"sequenceId"),G=$H(w);$=await z("POST",`/api/v1/sequences/${encodeURIComponent(Q)}/enroll`,G,W);break}case"cancel_sequence_enrollments":{let W=w.companyId,Q=oD(w);$=await z("POST",`/api/v1/sequences/${w.sequenceId}/enrollments/cancel`,Q,W);break}case"delete_sequence":{let W=w.companyId;$=await z("DELETE",`/api/v1/sequences/${w.sequenceId}`,void 0,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function dH(b,w){let $;switch(b){case"add_subscriber":{let W=w.companyId,Q=Aw("add_subscriber",w),G=Gb("add_subscriber",w,"status",["active","unsubscribed","bounced"]),q=Gb("add_subscriber",w,"optInMode",["default","confirmed","double_opt_in"]);if($=await z("POST","/api/v1/subscribers",{...Q,...w.firstName!==void 0&&{firstName:w.firstName},...w.lastName!==void 0&&{lastName:w.lastName},customAttributes:w.attributes,tags:w.tags,lists:w.listIds,...G!==void 0&&{status:G},...q!==void 0&&{optInMode:q}},W),G!==void 0&&k($)&&k($.subscriber)&&$.subscriber.skipped===!0&&$.subscriber.status!==G)throw Error(`Existing subscriber was not changed to status '${G}'. Use update_subscriber to change an existing contact's status.`);break}case"create_subscriber_import":{let W=w.companyId;if(!Array.isArray(w.subscribers)||w.subscribers.length===0)throw Error("`subscribers` must be a non-empty array when calling `create_subscriber_import`.");if(w.subscribers.length>5000)throw Error("`create_subscriber_import` accepts at most 5000 subscriber records per call.");for(let q=0;q<w.subscribers.length;q+=1){let X=w.subscribers[q];if(!k(X)||typeof X.email!=="string"||X.email.trim()==="")throw Error(`Subscriber record ${q} must include a non-empty email string.`)}let Q=Gb("create_subscriber_import",w,"duplicateStrategy",["skip","merge","overwrite"]),G=Gb("create_subscriber_import",w,"optInMode",["default","confirmed","double_opt_in"]);$=await z("POST","/api/v1/subscribers/imports",{subscribers:w.subscribers,...Q!==void 0&&{duplicateStrategy:Q},...w.fileName!==void 0&&{fileName:w.fileName},...w.listIds!==void 0&&{listIds:w.listIds},...w.enrollInSequences!==void 0&&{enrollInSequences:w.enrollInSequences},...w.defaultPhoneCountry!==void 0&&{defaultPhoneCountry:w.defaultPhoneCountry},...w.smsConsent!==void 0&&{smsConsent:w.smsConsent},...G!==void 0&&{optInMode:G}},W);break}case"get_subscriber_import":{let W=w.companyId,Q=M("get_subscriber_import",w,"importId");$=await z("GET",`/api/v1/subscribers/imports/${encodeURIComponent(Q)}`,void 0,W);break}case"update_subscriber":{let W=w.companyId,Q=Aw("update_subscriber",w),G=Gb("update_subscriber",w,"status",["active","unsubscribed","bounced"]),X=k(w.attributes)||w.addTags!==void 0||w.removeTags!==void 0?await H0(Q,W):null,Y=Array.isArray(X?.subscriber.tags)?X.subscriber.tags.filter((A)=>typeof A==="string"):[],J=Array.isArray(w.addTags)?w.addTags.filter((A)=>typeof A==="string"&&A.trim()!=="").map(TW):[],D=new Set(Array.isArray(w.removeTags)?w.removeTags.filter((A)=>typeof A==="string"&&A.trim()!=="").map(TW):[]),H=Y.filter((A)=>!D.has(A));for(let A of J)if(!H.includes(A))H.push(A);let O={};if(Q.email&&Q.externalId)O.externalId=Q.externalId;if(w.firstName!==void 0)O.firstName=w.firstName;if(w.lastName!==void 0)O.lastName=w.lastName;if(G!==void 0)O.status=G;if(k(w.attributes))O.customAttributes={...k(X?.subscriber.customAttributes)?X.subscriber.customAttributes:{},...w.attributes};if(w.addTags||w.removeTags)O.tags=H;$=await z("PATCH",p$(Q),O,W);break}case"remove_subscriber":{let W=w.companyId,Q=Aw("remove_subscriber",w),G=p$(Q);if(w.hardDelete===!0)$=await z("DELETE",G,void 0,W);else $=await z("PATCH",G,{status:"unsubscribed"},W);break}case"get_subscriber":{let W=w.companyId,Q=Aw("get_subscriber",w);$=await H0(Q,W,{includeMachineEngagement:w.includeMachineEngagement===!0});break}case"list_subscriber_notes":{let W=w.companyId,Q=Aw("list_subscriber_notes",w);$=await z("GET",SW(Q),void 0,W);break}case"add_subscriber_note":{let W=w.companyId,Q=Aw("add_subscriber_note",w),G=typeof w.body==="string"?w.body.trim():void 0;if(!G)throw Error("`body` is required when calling `add_subscriber_note`.");if(G.length>5000)throw Error("`body` must be 5000 characters or fewer when calling `add_subscriber_note`.");$=await z("POST",SW(Q),{body:G},W);break}case"delete_subscriber_note":{let W=w.companyId,Q=typeof w.noteId==="string"?w.noteId.trim():"";if(!Q)throw Error("`noteId` is required when calling `delete_subscriber_note`.");$=await z("DELETE",`/api/v1/subscribers/notes/${encodeURIComponent(Q)}`,void 0,W);break}case"search_subscribers":{let W=w.companyId;$=await wH(w,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function tH(b,w){if(b!=="get_recipient_suppression"&&b!=="remove_recipient_suppression")return{handled:!1,result:void 0};let $=U(w,"companyId"),W=M(b,w,"email"),Q=U(w,"region"),G=new URLSearchParams;if(Q)G.set("region",Q);let q=`/api/v1/suppressions/${encodeURIComponent(W)}${G.size>0?`?${G}`:""}`;return{handled:!0,result:await z(b==="get_recipient_suppression"?"GET":"DELETE",q,void 0,$)}}async function rH(b,w){let $;switch(b){case"list_team_members":{let W=w.companyId;$=await z("GET","/api/v1/team",void 0,W);break}case"invite_team_member":{let W=w.companyId,Q=M("invite_team_member",w,"email"),G=z0("invite_team_member",w,"role",["admin","viewer","restricted"]);if(w.canManageBilling!==void 0&&typeof w.canManageBilling!=="boolean")throw Error("`canManageBilling` must be a boolean when calling `invite_team_member`.");$=await z("POST","/api/v1/team/invitations",{email:Q,role:G,...w.canManageBilling!==void 0&&{canManageBilling:w.canManageBilling}},W);break}case"cancel_team_invitation":{let W=w.companyId,Q=M("cancel_team_invitation",w,"invitationId");$=await z("DELETE",`/api/v1/team/invitations/${encodeURIComponent(Q)}`,void 0,W);break}case"list_conversations":{let W=w.companyId,Q=new URLSearchParams,G=Gb("list_conversations",w,"status",["open","closed","all"]);if(G)Q.set("status",G);let q=U(w,"search");if(q)Q.set("search",q);if(w.unread!==void 0){if(typeof w.unread!=="boolean")throw Error("`unread` must be a boolean when calling `list_conversations`.");if(w.unread)Q.set("unread","true")}if(w.page!==void 0){if(typeof w.page!=="number"||!Number.isInteger(w.page)||w.page<1)throw Error("`page` must be a positive integer when calling `list_conversations`.");Q.set("page",String(w.page))}let X=ab("list_conversations",w,"limit",1,100);if(X!==void 0)Q.set("limit",String(X));$=await z("GET",`/api/v1/conversations${Q.size>0?`?${Q}`:""}`,void 0,W);break}case"get_conversation":{let W=w.companyId,Q=M("get_conversation",w,"conversationId");$=await z("GET",`/api/v1/conversations/${encodeURIComponent(Q)}`,void 0,W);break}case"reply_to_conversation":{let W=w.companyId,Q=M("reply_to_conversation",w,"conversationId"),G=Gb("reply_to_conversation",w,"type",["outbound","note"])??"outbound",q=U(w,"subject"),X=U(w,"bodyText"),Y=U(w,"bodyHtml");if(G==="outbound"&&X===void 0&&Y===void 0)throw Error("Provide `bodyText` or `bodyHtml` when calling `reply_to_conversation` with an outbound message.");$=await z("POST",`/api/v1/conversations/${encodeURIComponent(Q)}/messages`,{type:G,...q!==void 0&&{subject:q},...X!==void 0&&{bodyText:X},...Y!==void 0&&{bodyHtml:Y}},W);break}case"update_conversation_status":{let W=w.companyId,Q=M("update_conversation_status",w,"conversationId"),G=z0("update_conversation_status",w,"status",["open","closed"]);$=await z("POST",`/api/v1/conversations/${encodeURIComponent(Q)}/status`,{status:G},W);break}case"mark_conversation_read":{let W=w.companyId,Q=M("mark_conversation_read",w,"conversationId");$=await z("POST",`/api/v1/conversations/${encodeURIComponent(Q)}/read`,void 0,W);break}case"list_webhooks":{let W=w.companyId;$=await z("GET","/api/v1/webhooks",void 0,W);break}case"create_webhook":{let W=w.companyId,Q=M("create_webhook",w,"name"),G=M("create_webhook",w,"url"),q=vW("create_webhook",w);$=await z("POST","/api/v1/webhooks",{name:Q,url:G,...q!==void 0&&{events:q}},W);break}case"update_webhook":{let W=w.companyId,Q=M("update_webhook",w,"webhookId"),G=U(w,"name"),q=U(w,"url"),X=vW("update_webhook",w),Y=Gb("update_webhook",w,"status",["enabled","disabled"]);if(G===void 0&&q===void 0&&X===void 0&&Y===void 0)throw Error("Provide at least one of `name`, `url`, `events`, or `status` when calling `update_webhook`.");$=await z("PATCH",`/api/v1/webhooks/${encodeURIComponent(Q)}`,{...G!==void 0&&{name:G},...q!==void 0&&{url:q},...X!==void 0&&{events:X},...Y!==void 0&&{status:Y}},W);break}case"delete_webhook":{let W=w.companyId,Q=M("delete_webhook",w,"webhookId");$=await z("DELETE",`/api/v1/webhooks/${encodeURIComponent(Q)}`,void 0,W);break}case"test_webhook":{let W=w.companyId,Q=M("test_webhook",w,"webhookId");$=await z("POST",`/api/v1/webhooks/${encodeURIComponent(Q)}/test`,void 0,W);break}case"list_webhook_deliveries":{let W=w.companyId,Q=M("list_webhook_deliveries",w,"webhookId"),G=ab("list_webhook_deliveries",w,"limit",1,100),q=new URLSearchParams;if(G!==void 0)q.set("limit",String(G));$=await z("GET",`/api/v1/webhooks/${encodeURIComponent(Q)}/deliveries${q.size>0?`?${q}`:""}`,void 0,W);break}case"replay_webhook_delivery":{let W=w.companyId,Q=M("replay_webhook_delivery",w,"webhookId"),G=M("replay_webhook_delivery",w,"deliveryId");$=await z("POST",`/api/v1/webhooks/${encodeURIComponent(Q)}/deliveries/${encodeURIComponent(G)}/replay`,void 0,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}var eH=[hH,dH,tH,pH,nH,iH,mH,gH,lH,hW,fH,rH,cH];var rM=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 sH(b){return typeof b==="object"&&b!==null&&!Array.isArray(b)}function cW(b){if(Array.isArray(b))return b.some(cW);if(!sH(b))return!1;for(let[w,$]of Object.entries(b)){if((w==="html"||w==="htmlContent")&&typeof $==="string"&&$.trim().length>0)return!0;if(cW($))return!0}return!1}function aH(b,w,$){if(!rM.has(b)||!cW(w)||!sH($))return $;let W=Array.isArray($.warnings)?$.warnings.filter((Q)=>typeof Q==="string"):[];return{...$,warnings:[...new Set([...W,qb])]}}var bz=yH.map(DH).map(RD);async function wz(b,w){try{let $,W=!1;for(let G of eH){let q=await G(b,w);if(q.handled){$=q.result,W=!0;break}}if(!W)throw Error(`Unknown tool: ${b}`);let Q=aD($);if(Q)throw Q;return $=aH(b,w,$),$=await GH(b,w,$),{structuredContent:HH($),content:[{type:"text",text:JSON.stringify($,null,2)}]}}catch($){return{isError:!0,content:[{type:"text",text:Uw($)}]}}}async function $z(b,w,$){let W=w.getRequestContext?.(b)??{};try{return await w4(W,$)}finally{await w.onRequestContextUpdated?.(W,b)}}function fW(b={}){let w=new OW({name:"sequenzy",version:jD.version},{capabilities:{tools:{},resources:{}},instructions:["Sequenzy email marketing MCP server: manage subscribers, campaigns, sequences, templates, and delivery stats.","If you have access to multiple companies, call get_account and then select_company (or pass companyId per call) before other tools.","IMPORTANT: whenever the user wanted to accomplish something and these tools did not expose functionality for it (missing tool, missing argument, unsupported workflow, or broken behavior), call submit_feedback describing the gap before finishing the task. The Sequenzy team reads every submission and uses it to decide what to build next."].join(`
|
|
52
|
-
`)});return w.setRequestHandler(b6,async()=>{return{tools:bz}}),w.setRequestHandler(x1,async($,W)=>{let{name:Q,arguments:
|
|
53
|
-
`);if(b===-1)return null;let w=this._buffer.toString("utf8",0,b).replace(/\r$/,"");return this._buffer=this._buffer.subarray(b+1),
|
|
54
|
-
`}class iW{constructor(b=Qz.stdin,w=Qz.stdout){this._stdin=b,this._stdout=w,this._readBuffer=new nW,this._started=!1,this._ondata=($)=>{this._readBuffer.append($),this.processReadBuffer()},this._onerror=($)=>{this.onerror?.($)}}async start(){if(this._started)throw Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){while(!0)try{let b=this._readBuffer.readMessage();if(b===null)break;this.onmessage?.(b)}catch(b){this.onerror?.(b)}}async close(){if(this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0)this._stdin.pause();this._readBuffer.clear(),this.onclose?.()}send(b){return new Promise((w)=>{let $=Wz(b);if(this._stdout.write($))w();else this._stdout.once("drain",w)})}}async function
|
|
51
|
+
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 AH=[{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 LH=[{name:"get_stats",description:"Get overview statistics for a time period, including reply count and reply rate",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},period:{type:"string",description:"Time period: 7d, 30d, or 90d (default: 7d)"},includeMachineEngagement:pb}}},{name:"get_campaign_stats",description:"Get detailed statistics for a campaign, including replies and reply rate, attributed conversions, revenue (revenueCents), a per-link click breakdown in the top-level clickedLinks array, and any Poll or NPS survey summaries in the top-level polls array",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"},includeMachineEngagement:pb},required:["campaignId"]}},{name:"get_sequence_stats",description:"Get statistics for a sequence, including aggregate and per-step replies and reply rates, attributed conversions and revenue (revenueCents), plus per-step failed subscribers and failure reasons",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"},includeMachineEngagement:pb},required:["sequenceId"]}},{name:"list_campaign_events",description:"List paginated raw email events for a campaign. Defaults to deliveries; use eventType or eventTypes to include opens, clicks, bounces, complaints, unsubscribes, sends, or delivery delays.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"},eventType:{type:"string",description:"Optional single event type. Supported values: send, delivery, bounce, complaint, open, click, unsubscribe, delivery_delay. Defaults to delivery."},eventTypes:{type:"array",description:"Optional event types to include. Supported values: send, delivery, bounce, complaint, open, click, unsubscribe, delivery_delay. Defaults to delivery.",items:{type:"string"}},period:{type:"string",description:"Optional sliding time window: 1h, 24h, 7d, 30d, or 90d. Ignored when start/end are provided."},start:{type:"string",description:"Optional ISO 8601 start time. Must be used with end; max range is 90 days."},end:{type:"string",description:"Optional ISO 8601 end time. Must be used with start; max range is 90 days."},page:{type:"number",description:"Page number, starting at 1. Defaults to 1."},limit:{type:"number",description:"Events per page. Defaults to 100; maximum 500."},includeMachineEngagement:pb},required:["campaignId"]}},{name:"list_sequence_events",description:"List paginated raw email events for every email step in a sequence. Defaults to deliveries; use eventType or eventTypes to include opens, clicks, bounces, complaints, unsubscribes, sends, or delivery delays.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"},eventType:{type:"string",description:"Optional single event type. Supported values: send, delivery, bounce, complaint, open, click, unsubscribe, delivery_delay. Defaults to delivery."},eventTypes:{type:"array",description:"Optional event types to include. Supported values: send, delivery, bounce, complaint, open, click, unsubscribe, delivery_delay. Defaults to delivery.",items:{type:"string"}},period:{type:"string",description:"Optional sliding time window: 1h, 24h, 7d, 30d, or 90d. Ignored when start/end are provided."},start:{type:"string",description:"Optional ISO 8601 start time. Must be used with end; max range is 90 days."},end:{type:"string",description:"Optional ISO 8601 end time. Must be used with start; max range is 90 days."},page:{type:"number",description:"Page number, starting at 1. Defaults to 1."},limit:{type:"number",description:"Events per page. Defaults to 100; maximum 500."},includeMachineEngagement:pb},required:["sequenceId"]}},{name:"get_subscriber_activity",description:"Get recent activity, email stats, and current sequence enrollments for a subscriber",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},includeMachineEngagement:pb},required:[]}}];var UH=[{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 PH=[{name:"list_campaigns",description:"List all campaigns",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list campaigns for. If not provided, uses the currently selected company."},status:{type:"string",description:"Filter by status (draft, scheduled, sent, 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."}}}},{name:"get_campaign",description:"Get campaign details and stats, including rejectionComment reviewer feedback for rejected campaigns",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"}},required:["campaignId"]}},{name:"get_email_send",description:"Get an email delivery by emailSendId, including queued and test sends, delivery status, provider failure reason, stored HTML, and the ClickHouse event timeline. Queue jobs are internal execution details and are not exposed.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},emailSendId:{type:"string",description:"Durable email delivery ID to inspect."}},required:["emailSendId"]}},{name:"create_campaign",description:"Create a new campaign. Omit all content fields to create an empty draft. For net-new natural-language content use `prompt`; do not author HTML or blocks. `blocks` are finished caller-supplied Sequenzy content and `html` is preserved/imported markup. Defaults to draft; status 'sent' only archives an already-sent campaign.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the campaign in. If not provided, uses the currently selected company."},name:{type:"string",description:"Campaign name"},subject:{type:"string",description:"Email subject line. Optional when `prompt` is provided because the generated subject will be used."},previewText:{type:["string","null"],description:"Email preview text. Optional when `prompt` is provided because the generated preview text will be used."},trackingCode:{type:"string",description:"Optional campaign tracking code for UTM templates. Use only when explicitly requested."},status:{type:"string",description:"Initial status: draft or sent. Defaults to draft. Use sent only for imported/already-sent campaigns; it does not send email or create delivery history."},sentAt:{type:"string",description:"ISO date-time for an imported/already-sent campaign. Only valid when status is sent; defaults to now if omitted."},html:{type:"string",description:`Email HTML content. Mutually exclusive with \`blocks\`. Use this for imported provider campaigns. ${Gb}`},blocks:{type:"array",description:Hw,items:{type:"object"}},prompt:{type:"string",description:"Generate campaign blocks from a prompt. Generated blocks include the company's logo and footer, and the created campaign inherits the company brand font. Mutually exclusive with `html`, `blocks`, and `templateId`."},style:{type:"string",description:"Prompt generation style: minimal, branded, promotional. Only used with `prompt`."},tone:{type:"string",description:"Prompt generation tone: professional, casual, friendly. Only used with `prompt`."},templateId:{type:"string",description:"Use a template instead of html"},segmentId:{type:"string",description:"Target segment ID"},fromEmail:{type:"string",description:"From address for this campaign. Its domain must be configured and verified; a sender profile is created when needed."},fromName:{type:"string",description:"Display name for a newly created sender profile. Requires fromEmail."},senderProfileId:{type:"string",description:"Existing sender profile ID. Mutually exclusive with fromEmail."},replyTo:{type:"string",description:"Reply-To address for this campaign. A reply profile is created when needed."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo."},replyProfileId:{type:"string",description:"Existing reply profile ID. Mutually exclusive with replyTo."},campaignData:{type:"object",description:"Optional campaign-scoped JSON data for repeat blocks and personalization."},computedLists:{type:"array",description:"Optional computed list definitions derived from campaignData at send time.",items:{type:"object"}},labels:{type:"array",description:"Optional label names to assign. Missing labels are created automatically.",items:{type:"string"}}},required:["name"]}},{name:"update_campaign",description:"Update a draft campaign",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"},name:{type:"string",description:"Campaign name"},subject:{type:"string",description:"Email subject line"},trackingCode:{type:"string",description:"Optional campaign tracking code for UTM templates. Use only when explicitly requested. Send an empty string to clear it."},html:{type:"string",description:`Email HTML content. Mutually exclusive with \`blocks\`. Use this for imported provider campaigns. ${Gb}`},blocks:{type:"array",description:Hw,items:{type:"object"}},replyTo:{type:"string",description:"Set reply-to using an existing reply profile email address for this company."},replyProfileId:{type:"string",description:"Set reply-to using a reply profile ID for this company."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo."},fromEmail:{type:"string",description:"Set this campaign's From address. Its domain must be configured and verified."},fromName:{type:"string",description:"Display name for a newly created sender profile. Requires fromEmail."},senderProfileId:{type:"string",description:"Set an existing sender profile. Mutually exclusive with fromEmail."},ccEmails:{type:["array","null"],description:"Addresses CC'd on every recipient's campaign email (max 10). Send an empty array or null to clear them; omit to leave unchanged.",items:{type:"string"},maxItems:10},bccEmails:{type:["array","null"],description:"Addresses BCC'd on every recipient's campaign email (max 10). Send an empty array or null to clear them; omit to leave unchanged.",items:{type:"string"},maxItems:10},campaignData:{type:"object",description:"Set campaign-scoped JSON data for repeat blocks and personalization."},computedLists:{type:"array",description:"Set computed list definitions derived from campaignData at send time.",items:{type:"object"}},labels:{type:"array",description:"Replacement label names. Send an empty array to clear labels. Missing labels are created automatically.",items:{type:"string"}}},required:["campaignId"],additionalProperties:!1}},{name:"schedule_campaign",description:"Schedule a draft or already scheduled campaign. Returns dashboard edit and preview URLs.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"},scheduledAt:{type:"string",description:"Future ISO 8601 timestamp for the send, for example 2026-06-01T14:00:00Z."},targetLists:{type:"object",description:"Optional campaign targeting object. Omit to use saved targeting or all active subscribers. Examples: {type:'all'}, {type:'lists', listIds:['list_123']}, {type:'segment', segmentId:'seg_123'}, {type:'filtered', filters:[...], filterJoinOperator:'and'}, or {type:'rules', include:[{type:'lists', listIds:['list_123']}], exclude:[{type:'segments', segmentIds:['seg_123']}]}. Rules audiences require at least one include rule.",additionalProperties:!0},sendTimeOptimization:{type:"boolean",description:"Whether to use send-time optimization."},spreadOverHours:{type:"number",description:"Spread delivery over an integer number of hours from 1 to 72. When set, spread delivery takes precedence over send-time optimization."},recurringInterval:{type:"string",enum:["weekly","monthly"],description:"Repeat this campaign on a cadence starting at scheduledAt. The campaign becomes a recurring template: each run is duplicated and sent automatically, re-evaluating audience membership every time. Omit for a one-shot send; scheduling again without it stops the recurrence."}},required:["campaignId","scheduledAt"],additionalProperties:!1}},{name:"send_test_email",description:"Queue a campaign test email to a single address. Returns a durable emailSendId; pass it to get_email_send for delivery status and failure details.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to test"},to:{type:"string",description:"Email address to send test to"}},required:["campaignId","to"]}},{name:"cancel_campaign",description:"Cancel a campaign. Stops scheduled and sending campaigns (also works for paused and approval-pending ones). Remaining emails will not be sent and the campaign cannot be restarted - this cannot be undone.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to cancel."}},required:["campaignId"]}},{name:"pause_campaign",description:"Pause a campaign that is currently sending. Only campaigns in sending status can be paused. Use resume_campaign to continue delivery later.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to pause."}},required:["campaignId"]}},{name:"resume_campaign",description:"Resume a paused campaign. Only campaigns in paused status can be resumed. Optionally spread the remaining delivery over a number of hours.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to resume."},spreadOverHours:{type:"number",description:"Spread the remaining delivery over an integer number of hours from 1 to 72."}},required:["campaignId"]}},{name:"delete_campaign",description:"Permanently delete a campaign. This cannot be undone. Sending, scheduled, or paused campaigns must be cancelled with cancel_campaign first.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to delete."}},required:["campaignId"]}},{name:"duplicate_campaign",description:"Duplicate a campaign as a new draft. mode 'campaign' (default) copies the campaign and its email, 'ab_test' also duplicates the campaign's A/B test with all variants, and 'variant' copies a single variant's content as the new campaign email (requires variantId).",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to duplicate."},mode:{type:"string",enum:["campaign","ab_test","variant"],description:"Duplication mode. Defaults to campaign."},variantId:{type:"string",description:"A/B test variant ID whose content becomes the new campaign email. Required when mode is variant."}},required:["campaignId"]}},{name:"resend_campaign_to_non_openers",description:"Create a draft that resends a sent campaign to everyone in the same audience who didn't open it. Copies the campaign email and reuses the original audience with a 'didn't open this campaign' rule added. Only available 6 hours after the campaign finishes sending. The draft must be scheduled or sent separately. Returns the new draft and an estimate of how many subscribers haven't opened the original.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"ID of the sent campaign to resend to non-openers."}},required:["campaignId"]}}];var BH=[{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 FH=[{name:"list_forms",description:"List saved signup forms for a company, including their server-managed audience settings and public action URLs.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list forms for. If not provided, uses the currently selected company."}},additionalProperties:!1}},{name:"create_form",description:"Create and publish a saved signup form whose opaque formId is a client-safe public capability. The selected lists, tags, duplicate behavior, and success action stay server-side; no API key is needed in the deployed form.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the form in. If not provided, uses the currently selected company."},name:{type:"string",description:"Internal saved-form name."},listIds:{type:"array",description:"One or more list IDs that every public submission will be added to. Use list_lists to resolve IDs.",items:{type:"string"}},tagIds:{type:"array",description:"Optional existing tag IDs applied by the saved form. Use list_tags to resolve IDs.",items:{type:"string"}},duplicateStrategy:{type:"string",enum:["skip","merge","overwrite"],description:"How to handle an existing subscriber. Defaults to skip."},buttonText:{type:"string",description:"Optional submit button label."},headline:{type:"string",description:"Optional form headline."},description:{type:"string",description:"Optional supporting form copy."},successMessage:{type:"string",description:"Confirmation shown after a successful submission when redirectUrl is omitted."},redirectUrl:{type:"string",description:"Optional HTTP or HTTPS URL for successful submissions. Omit it to show the saved confirmation message."},showFirstName:{type:"boolean",description:"Whether the generated form also collects first name."},showLastName:{type:"boolean",description:"Whether the generated form also collects last name."}},required:["name","listIds"],additionalProperties:!1}},{name:"get_form_embed",description:"Get a published saved form's action URL, one-line JavaScript embed, minimal native form action, and fetch example. Use this for Astro, Hugo, Jekyll, Cloudflare Pages, Netlify, GitHub Pages, or any browser integration.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},formId:{type:"string",description:"Saved form ID returned by list_forms or create_form."}},required:["formId"],additionalProperties:!1}}];var KH=[{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 MH=[{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 IH=[{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:SD},content:{type:"object",description:Y0,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:Y0,additionalProperties:!0}},required:["landingPageId"],additionalProperties:!1}},{name:"delete_landing_page",description:"Delete a landing page",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID."}},required:["landingPageId"],additionalProperties:!1}},{name:"publish_landing_page",description:"Publish a landing page. Optional name, slug, or content updates are saved before publishing.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID."},name:{type:"string",description:"Optional landing page name update."},slug:{type:"string",description:"Optional slug update before publishing."},content:{type:"object",description:Y0,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:Y0,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 _H=[{name:"list_products",description:"List synced products (Stripe, Shopify, WooCommerce) including any attached digital delivery file. Useful before attaching a file or building a purchase sequence for a specific product.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list products for. If not provided, uses the currently selected company."},provider:{type:"string",description:"Filter by provider: stripe, shopify, woocommerce, or manual."},search:{type:"string",description:"Filter products by title."}}}},{name:"upsert_products",description:"Create or update products in the catalog (Commerce API, keyed by your productId, stored under the api provider). Use this to add products that are not synced from Stripe/Shopify/WooCommerce, then attach a deliverable file with attach_product_file and build a purchase sequence for them.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},products:{type:"array",description:"Products to create or update (max 100).",items:{type:"object",properties:{productId:{type:"string",description:"Your stable product identifier (used for upserts and order line items)."},title:{type:"string",description:"Product title."},description:{type:"string",description:"Product description."},imageUrl:{type:"string",description:"Product image URL."},url:{type:"string",description:"Product page URL."},priceCents:{type:"number",description:"Price in the smallest currency unit."},currency:{type:"string",description:"ISO currency code, e.g. USD."},inStock:{type:"boolean",description:"Whether the product is in stock."}},required:["productId","title"]}}},required:["products"]}},{name:"delete_product",description:"Delete a product previously pushed via upsert_products (Commerce API products only), identified by your productId.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},productId:{type:"string",description:"Your productId used when upserting the product."}},required:["productId"]}},{name:"attach_product_file",description:"Attach a distributable file to a product, either by public URL or by uploading a local file (filePath, local MCP server only). After a purchase of the product, sequence emails can link to it with {{event.download.url}} and {{event.download.name}}.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},productId:{type:"string",description:"Product ID from list_products, or your own productId for products pushed via upsert_products."},url:{type:"string",description:"Public http(s) URL of the file to deliver. Provide url or filePath, not both."},filePath:{type:"string",description:"Local path of a file to upload and attach (PDF, ePub, ZIP, image, audio, video, or text, up to 100MB). Only available when the MCP server runs locally on this machine."},fileName:{type:"string",description:"Display name for the file (e.g. guide.pdf). Used as {{event.download.name}}."}},required:["productId"]}},{name:"remove_product_file",description:"Remove the attached distributable file from a product.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},productId:{type:"string",description:"Product ID from list_products, or your own productId for products pushed via upsert_products."}},required:["productId"]}},{name:"sync_products",description:"Queue a sync of the Stripe product catalog into the products list. Requires an active Stripe integration.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}}];var t$={companyId:{type:"string",description:"Company ID. If omitted, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID."}},jH={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."}},ZH=[{name:"list_sequence_goals",description:"List persisted conversion goals attached to one sequence in the dashboard.",inputSchema:{type:"object",properties:t$,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:{...t$,...jH},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:{...t$,goalId:{type:"string",description:"Sequence goal ID."},...jH},required:["sequenceId","goalId"],additionalProperties:!1}},{name:"delete_sequence_goal",description:"Delete one persisted sequence conversion goal.",inputSchema:{type:"object",properties:{...t$,goalId:{type:"string",description:"Sequence goal ID."}},required:["sequenceId","goalId"],additionalProperties:!1}}];var yW={companyId:{type:"string",description:"Company ID. If omitted, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence with an inbound_webhook trigger."}},VH=[{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:yW,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:{...yW,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:yW,required:["sequenceId"],additionalProperties:!1}}];var NH=[{name:"list_sequences",description:"List all email sequences (automations)",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list sequences for. If not provided, uses the currently selected company."},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. 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:"create_sequence",description:"Create and persist a disabled draft email sequence, follow-up series, drip campaign, nurture flow, or automation workflow. For natural-language content, provide goal and emailCount. Use explicit steps for finished caller-supplied content, exact workflows, or migrations. Configure trigger plus its relevant field, such as listId, tagName, segmentId, or eventName. Supports email and SMS steps, delays and date waits, actions that dynamically create a provider discount/code, subscriber updates, event filters, enrollment rules, sending windows, and stop conditions. The saved draft appears in list_sequences. Never call enable_sequence unless the user explicitly asks to activate it.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the sequence in. If not provided, uses the currently selected company."},fromEmail:{type:"string",description:"From address for all emails in this sequence. Its domain must be configured and verified."},fromName:{type:"string",description:"Display name for a newly created sender profile. Requires fromEmail."},senderProfileId:{type:"string",description:"Existing sender profile ID. Mutually exclusive with fromEmail."},replyTo:{type:"string",description:"Reply-To address for all emails in this sequence. A reply profile is created when needed."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo."},replyProfileId:{type:"string",description:"Existing reply profile ID. Mutually exclusive with replyTo."},name:{type:"string",description:"Sequence name (e.g., 'User Onboarding', 'Welcome Series')"},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. Use 'matching_field' only for event_received triggers when duplicate active runs should be blocked per event field value."},enrollmentFieldPath:{type:"string",description:"Scalar dot-path event property used by enrollmentMode='matching_field', such as 'order.id' or 'product.providerVariantId'. Array traversal with [] is not supported; use propertyFilters for array matching. Leave omitted for Shopify back-in-stock/replenishment product-variant defaults."},sendingWindow:h$,stopCondition:{type:"object",description:"Optional explicit auto-stop condition. Use { type: 'has_tag', value: 'customer' } to end the sequence when a subscriber gets a tag, { type: 'does_not_have_tag', value: 'trial' } when a tag is removed, { type: 'entered_segment', value: 'segment_123' } when they enter a segment, { type: 'field_changed', value: 'plan' } when a subscriber field changes, { type: 'removed_from_list', value: 'list_123' } when they leave a list, { type: 'event_received', value: 'onboarding.completed' } when an event is tracked, or { type: 'none', value: null } for no auto-stop.",properties:{type:{type:"string",enum:["none","has_tag","does_not_have_tag","added_to_list","removed_from_list","entered_segment","field_changed","event_received"],description:"Stop condition type."},value:{type:["string","null"],description:"Tag name, list ID, segment ID, field path, or event name for the stop condition. Use null or omit for type 'none'."},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:D1,subject:{type:"string",description:"Email subject. Required for email steps."},previewText:{type:"string",description:"Email preview text."},blocks:{type:"array",description:q1,items:{type:"object"}},html:{type:"string",description:`HTML content for email steps. Use this for imported provider HTML. ${Gb}`},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 (e.g. guide.pdf)."},path:{type:"string",description:"Public HTTPS URL of the file; fetched at send time."}},required:["filename","path"]},description:"URL-backed file attachments for this email step (max 10, 7MB total per email). The file is fetched from the URL at send time and attached to the email."},...J0,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:X1,delayMs:{type:"number",description:"Delay before this step in milliseconds. Prefer delay for readability; use delayMs when importing provider waits."},waitUntil:G1,name:{type:"string",description:"Email template name for email steps."},discount:{type:"object",description:"Discount configuration for create_discount steps. Prefer this nested shape for new integrations; legacy top-level discount fields are still accepted.",properties:{label:{type:"string",description:"Builder label for the discount step."},provider:{type:"string",enum:["stripe","shopify"],description:"Discount provider. Use 'stripe' to dynamically create a Stripe coupon plus promotion code, or 'shopify' to dynamically create a Shopify Admin discount code. Defaults to 'stripe' when omitted."},discountType:{type:"string",enum:["percent","amount"],description:"Discount type."},percentOff:{type:"number",description:"Percent discount from 1 to 100. Required when discountType is percent."},amountOff:{type:"number",description:"Fixed amount discount in the smallest currency unit, for example 500 for $5. Required when discountType is amount."},currency:{type:"string",description:"ISO currency for amount discounts. Defaults to usd."},duration:{type:"string",enum:["once","forever","repeating"],description:"Discount duration. Defaults to once."},durationInMonths:{type:"number",description:"Required for repeating discounts."},appliesToAllPlans:{type:"boolean",description:"Whether the discount applies to all plans. Defaults to true."},planIds:{type:"array",description:"Provider product IDs when appliesToAllPlans is false. Stripe uses IDs like prod_abc123; Shopify accepts numeric product IDs or gid://shopify/Product/... IDs.",items:{type:"string"}},codePrefix:{type:"string",description:"Optional prefix for generated dynamic codes. The final code also includes a subscriber/token suffix."},maxRedemptions:{type:"number",description:"Maximum redemptions for each generated code. Use 1 for subscriber-specific codes."},lockToSubscriber:{type:"boolean",description:"Stripe-only. Restrict each generated promotion code to the matched subscriber's Stripe customer."},expiresAt:{type:"string",description:"Optional future expiration date or ISO timestamp."},expiresInHours:{type:"number",description:"Optional relative expiration in hours, resolved when each subscriber's code is created (e.g., 48 for a 48-hour window per subscriber). Takes precedence over expiresAt."},name:{type:"string",description:"Optional display name for each dynamically generated provider discount."}}},label:{type:"string",description:"Legacy top-level discount label. Prefer discount.label."},provider:{type:"string",enum:["stripe","shopify"],description:"Legacy top-level discount provider. Prefer discount.provider. Supports 'stripe' and 'shopify'."},discountType:{type:"string",enum:["percent","amount"],description:"Legacy top-level discount type. Prefer discount.discountType."},percentOff:{type:"number",description:"Percent discount from 1 to 100. Required when discountType is percent."},amountOff:{type:"number",description:"Fixed amount discount in the smallest currency unit, for example 500 for $5. Required when discountType is amount."},currency:{type:"string",description:"ISO currency for amount discounts. Defaults to usd."},duration:{type:"string",enum:["once","forever","repeating"],description:"Discount duration. Defaults to once."},durationInMonths:{type:"number",description:"Required for repeating discounts."},appliesToAllPlans:{type:"boolean",description:"Whether the discount applies to all plans. Defaults to true."},planIds:{type:"array",description:"Provider product IDs when appliesToAllPlans is false. Stripe uses IDs like prod_abc123; Shopify accepts numeric product IDs or gid://shopify/Product/... IDs.",items:{type:"string"}},codePrefix:{type:"string",description:"Optional prefix for generated dynamic codes. The final code also includes a subscriber/token suffix."},maxRedemptions:{type:"number",description:"Maximum redemptions for each generated code. Use 1 for subscriber-specific codes."},lockToSubscriber:{type:"boolean",description:"Legacy top-level Stripe-only flag. Prefer discount.lockToSubscriber."},expiresAt:{type:"string",description:"Optional future expiration date or ISO timestamp."},expiresInHours:{type:"number",description:"Optional relative expiration in hours, resolved when each subscriber's code is created (e.g., 48 for a 48-hour window per subscriber). Takes precedence over expiresAt."}}}}},required:["name"]}}];var EH=[{name:"update_sequence",description:"Update an existing sequence. To target a specific existing step, use IDs returned by get_sequence. The emails/steps arrays edit email steps, smsSteps edits SMS steps, and subscriberUpdateSteps replaces the config of action_update_attributes steps. To insert new linear steps, use insertSteps with an afterNodeId from get_sequence; omit afterNodeId only to append to an unambiguous linear tail. For active sequences, structural changes such as insertSteps or branch require confirmStructuralChange:true after the user confirms the live-flow impact.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"},name:{type:"string",description:"Sequence name"},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:"Display name for a newly created sender profile. Requires fromEmail."},senderProfileId:{type:"string",description:"Set an existing sender profile. Mutually exclusive with fromEmail."},replyTo:{type:"string",description:"Set the Reply-To address for all emails in this sequence."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo."},replyProfileId:{type:"string",description:"Set an existing reply profile. Mutually exclusive with replyTo."},enrollmentPaused:{type:"boolean",description:"Set true to stop new enrollments for an active sequence while current recipients continue. Set false to resume new enrollments. The sequence must already be active."},confirmStructuralChange:{type:"boolean",description:"Set true only after the user explicitly confirms a structural edit to an active sequence. Required for insertSteps or branch when the sequence is active; not needed for content-only email edits."},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. '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:h$,clearSendingWindow:{type:"boolean",description:"Set true to remove the sequence sending window. Do not provide this together with sendingWindow."},bccEmails:{type:"array",items:{type:"string"},description:"Email addresses that receive a blind copy of every email this sequence sends, such as a customer support inbox (max 10). Omit to leave unchanged. Use clearBccEmails to remove them."},clearBccEmails:{type:"boolean",description:"Set true to remove the sequence BCC addresses. Do not provide this together with bccEmails."},stopCondition:{type:"object",description:"Update the sequence auto-stop condition. Example: { type: 'has_tag', value: 'customer' } ends the sequence when the subscriber has that tag. Use { type: 'entered_segment', value: 'segment_123' } to stop when they enter a segment, { type: 'field_changed', value: 'plan' } to stop when a subscriber field changes, { type: 'removed_from_list', value: 'list_123' } to stop when they leave a list, or { type: 'none', value: null } to clear it.",properties:{type:{type:"string",enum:["none","has_tag","does_not_have_tag","added_to_list","removed_from_list","entered_segment","field_changed","event_received"]},value:{type:["string","null"],description:"Tag name, list ID, segment ID, field path, or event name for the stop condition."},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:EW},elseSteps:{type:"array",description:"Optional new steps inside the else fallback path.",items:D0},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:D0}},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. ${Gb}`},htmlContent:{type:"string",description:`Alias for html for imported provider markup. ${Gb}`},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 supported when the entire email is standalone raw HTML and must not be combined with html/htmlContent."},blocks:{type:"array",description:zw,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); each file is fetched from its HTTPS URL at send time. Pass [] to remove all attachments."},...J0}}},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. ${Gb}`},htmlContent:{type:"string",description:`Alias for html. ${Gb}`},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 supported when the entire email is standalone raw HTML and must not be combined with html/htmlContent."},blocks:{type:"array",description:zw,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); each file is fetched from its HTTPS URL at send time. Pass [] to remove all attachments."},...J0}}},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:D1},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:c$.properties.nodeId,changes:KW,expectedUpdatedAt:c$.properties.expectedUpdatedAt,confirmLiveChange:{type:"boolean",description:"Set true only after the user explicitly confirms changing a node in an active sequence."}},required:["sequenceId","nodeId","changes","expectedUpdatedAt"],additionalProperties:!1}},{name:"update_sequence_nodes",description:"Atomically patch multiple existing sequence nodes. Call get_sequence first and include each node's id plus its updatedAt as expectedUpdatedAt. Every patch follows update_sequence_node's type-aware rules. Either every node update commits or none do, making this the preferred tool for changes such as replacing all 5-minute delays with 7-day delays 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:c$},confirmLiveChange:{type:"boolean",description:"Set true only after the user explicitly confirms changing nodes in an active sequence."}},required:["sequenceId","updates"],additionalProperties:!1}},{name:"edit_sequence_graph",description:"Restructure an existing sequence graph using node IDs, edges, and graphRevision from get_sequence. move_node repositions one non-split step; duplicate_node creates an independent copy; delete_node safely splices a node; replace_edges replaces the complete topology. 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, 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:q1,items:{type:"object"}},html:{type:"string",description:`HTML content for an imported provider step. Provide either html or blocks, not both. ${Gb}`},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); each file is fetched from its HTTPS URL 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: display name for a newly created reply profile. Requires replyTo."},text:{type:"string",description:"SMS steps only: plain-text message body. Merge tags like {{FIRST_NAME}} work. Do not include opt-out text or a brand prefix - the platform adds those automatically."},imageUrls:{type:"array",items:{type:"string"},description:"SMS steps only: up to 2 publicly reachable image URLs sent as MMS media."},label:{type:"string",description:"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:{...D1,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 URL called when a subscriber reaches this step."},method:{type:"string",enum:["POST","GET"],description:"webhook only: HTTP method. Defaults to POST."},headers:{type:"object",description:"webhook only: optional string-valued request headers. Secret values are redacted on sequence reads.",additionalProperties:{type:"string"}},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:X1,delayMs:{type:"number",description:"Optional wait in milliseconds before the new step. Prefer delay for readability."},waitUntil:G1,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:EW},elseSteps:{type:"array",description:"logic_branch only: optional new steps for the else path.",items:D0},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: subscriberId for one subscriber, or fieldValues to match stored entry event properties. For fieldValues, fieldPath is optional when the sequence has enrollmentFieldPath configured; otherwise provide a dot path such as order.id.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID whose enrollments should be cancelled."},subscriberId:{type:"string",description:"Subscriber ID to cancel in this sequence. Provide subscriberId or fieldValues, not both."},fieldPath:{type:"string",description:"Dot-path inside the token's stored entry event properties, such as order.id or event.id. Optional when the sequence has enrollmentFieldPath configured."},fieldValues:{type:"array",items:{type:"string"},description:"Entry field values to match. Cancels all active/waiting enrollments in the sequence whose entry field value is in this list. Provide fieldValues or subscriberId, not both."},dryRun:{type:"boolean",description:"When true, returns matching enrollments without cancelling them. Field-value cancellation defaults to dryRun on the API unless explicitly false."},reason:{type:"string",description:"Optional cancellation reason stored on matched enrollment tokens."}},required:["sequenceId"],additionalProperties:!1}},{name:"delete_sequence",description:"Delete a sequence",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}}];var tM={type:"object",properties:{email:{type:"string",description:"Subscriber email address"},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}},required:["email"],additionalProperties:!1},TH=[{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"},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide this with email when creating, or instead of email for an existing subscriber."},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."}},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:tM,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, status, attributes, or tags. 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."},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",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:pb},required:[]}},{name:"list_subscriber_notes",description:"List internal notes for a subscriber. Provide email or externalId to identify the subscriber.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."}},required:[]}},{name:"add_subscriber_note",description:"Add an internal note to a subscriber. Provide email or externalId to identify the subscriber.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},body:{type:"string",description:"Internal note body, up to 5000 characters."}},required:["body"]}},{name:"delete_subscriber_note",description:"Delete one internal subscriber note by note ID.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},noteId:{type:"string",description:"Subscriber note ID to delete."}},required:["noteId"]}},{name:"search_subscribers",description:"Search subscribers by free-text query, tags, list, or segment. If you omit limit, the tool fetches all pages and returns every match.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},query:{type:"string",description:"Search query (email or name)"},tags:{type:"array",items:{type:"string"},description:"Filter by tags"},list:{type:"string",description:"Filter by subscriber list ID or exact list name. Prefer listId when known."},listId:{type:"string",description:"Filter by subscriber list ID."},listName:{type:"string",description:"Filter by exact subscriber list name when the list ID is not known."},segmentId:{type:"string",description:"Filter by segment ID"},status:{type:"string",description:"Filter by subscriber status: active, unsubscribed, or bounced."},limit:{type:"number",description:"Maximum results to return. If omitted, the tool returns all matches across pages."}}}}];var SH={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."}},RH=[{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:SH,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:SH,required:["email"],additionalProperties:!1}}];var vH=[{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:[...Y1],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:[...Y1],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:IW,minItems:1,description:'Array of segment filters. Example custom attribute empty check: [{"id":"filter-1","field":"attribute","operator":"is_empty","value":"last_logged_in:"}]. Example Stripe purchase filter: [{"id":"filter-1","field":"stripeProduct","operator":"is","value":"prod_123"}]. Example threshold filter: [{"id":"filter-1","field":"stripeProduct","operator":"at_least","value":"prod_123:3"}]. Example commerce product purchase filter (value is provider:productId since product ids are provider-scoped): [{"id":"filter-1","field":"commerceProduct","operator":"is","value":"api:prod-starter-kit"}]. Example repeat-buyer filter: [{"id":"filter-1","field":"commerceProduct","operator":"at_least","value":"shopify:42:2"}]. Example trial cancellation filter: [{"id":"filter-1","field":"stripeTrialProduct","operator":"is","value":"prod_123:is_canceled"}]. Example trial end filter: [{"id":"filter-1","field":"stripeTrialProduct","operator":"is","value":"prod_123:end_at:2026-05-26"}]. Example campaign-specific engagement combo: [{"id":"filter-1","field":"emailBounced","operator":"is","value":"campaign:cmp_abc"},{"id":"filter-2","field":"emailBounced","operator":"is_not","value":"campaign:cmp_xyz"}]. Combine them with `filterJoinOperator: "or"` to match any filter.'},root:{..._W,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:IW,minItems:1,description:"Replacement segment filters. Same shape and validation rules as create_segment. Mutually exclusive with `root`."},root:{..._W,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 kH=[{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 CH=[{name:"list_templates",description:"List all email templates, including per-locale localization sync status",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"get_template",description:"Get a template's details, content, and all localized variants with sync status",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID"}},required:["templateId"]}},{name:"create_template",description:"Create a new email template. For net-new email content requested in natural language, use `prompt`; do not write HTML or construct blocks yourself. Use `blocks` only for finished caller-supplied Sequenzy content and `html` only for supplied or explicitly requested preserved HTML.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},name:{type:"string",description:"Template name"},subject:{type:"string",description:"Email subject line. Optional with `prompt`."},previewText:{type:["string","null"],description:"Optional preview text override."},html:{type:"string",description:`Email HTML content. Mutually exclusive with \`blocks\`. Use this for imported provider templates. ${Gb}`},blocks:{type:"array",description:Hw,items:{type:"object"}},prompt:{type:"string",description:"Natural-language request for Sequenzy to generate branded native template blocks."},style:{type:"string",description:"Generation style; valid only with `prompt`."},tone:{type:"string",description:"Generation tone; valid only with `prompt`."},labels:{type:"array",description:"Optional label names to assign. Missing labels are created automatically.",items:{type:"string"}}},required:["name"]}},{name:"update_template",description:"Update an existing template. At least one of `name`, `subject`, `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. ${Gb}`},blocks:{type:"array",description:Hw,items:{type:"object"}},labels:{type:"array",description:"Replacement label names. Send an empty array to clear labels. Missing labels are created automatically.",items:{type:"string"}}},required:["templateId"],additionalProperties:!1}},{name:"set_template_localization",description:"Create or replace one caller-supplied localized variant of a template. The locale must be enabled for the company and cannot be its primary locale. Provide exactly one of `html` or `blocks`.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID, transactional email ID, or slug."},locale:{type:"string",description:"Enabled non-primary locale code such as es, fr, or pt-BR."},subject:{type:"string",description:"Localized email subject line."},previewText:{type:["string","null"],description:"Optional localized inbox preview text."},html:{type:"string",description:`Localized email HTML. Mutually exclusive with \`blocks\`. ${Gb}`},blocks:{type:"array",description:Hw,items:{type:"object"}}},required:["templateId","locale","subject"],additionalProperties:!1}},{name:"sync_template_localizations",description:"Queue AI translation for selected template locales. Omit `locales` to sync every enabled non-primary locale. This works even when automatic on-save localization is disabled.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID, transactional email ID, or slug."},locales:{type:"array",description:"Optional enabled non-primary locale codes to sync. Omit to sync all enabled non-primary locales.",items:{type:"string"}}},required:["templateId"],additionalProperties:!1}},{name:"delete_template",description:"Delete a template",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID"}},required:["templateId"]}}];var uH=[{name:"list_transactional_emails",description:"List transactional email templates, including their API slugs and linked email IDs",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"get_transactional_email",description:"Get a transactional email by ID or slug, including subject, preview text, blocks, variables, and linked dashboard URLs",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},idOrSlug:{type:"string",description:"Transactional email ID or API slug, for example `welcome-email`."}},required:["idOrSlug"]}},{name:"create_transactional_email",description:"Create a saved transactional email template with an API slug. For net-new natural-language content use `prompt`; do not author HTML or blocks. `blocks` are finished caller-supplied Sequenzy content and `html` is preserved/imported markup.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},name:{type:"string",description:"Transactional email name."},slug:{type:"string",description:"Optional API slug used when sending by slug, for example `password-reset`. If omitted, Sequenzy generates one from the name."},subject:{type:"string",description:"Email subject line. Optional when `prompt` is provided because the generated subject will be used."},previewText:{type:["string","null"],description:"Email preview text."},html:{type:"string",description:`Email HTML content. Mutually exclusive with \`blocks\`. ${Gb}`},blocks:{type:"array",description:`${Hw} Mutually exclusive with \`html\`.`,items:{type:"object"}},prompt:{type:"string",description:"Generate transactional email blocks from a prompt. Generated blocks include the company's branding (logo and a footer without an unsubscribe link). Mutually exclusive with `html` and `blocks`."},style:{type:"string",description:"Prompt generation style: minimal, branded, promotional. Only used with `prompt`."},tone:{type:"string",description:"Prompt generation tone: professional, casual, friendly. Only used with `prompt`."},enabled:{type:"boolean",description:"Whether this transactional email can be sent immediately. Prompt-created templates default to false; explicit HTML/blocks retain the compatibility default of true."}},required:["name"],additionalProperties:!1}},{name:"update_transactional_email",description:"Update a transactional email by ID or slug. At least one of `name`, `enabled`, `subject`, `previewText`, `html`, or `blocks` is required. Use `html` or `blocks` to replace the linked email body.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},idOrSlug:{type:"string",description:"Transactional email ID or API slug, for example `welcome-email`."},name:{type:"string",description:"Transactional email name."},enabled:{type:"boolean",description:"Whether this transactional email can be sent."},subject:{type:"string",description:"Email subject line."},previewText:{type:["string","null"],description:"Email preview text."},html:{type:"string",description:`Email HTML content. Mutually exclusive with \`blocks\`. ${Gb}`},blocks:{type:"array",description:`${zw} Mutually exclusive with \`html\`.`,items:{type:"object"}}},required:["idOrSlug"],additionalProperties:!1}},{name:"send_email",description:"Queue one transactional email using either a saved transactional email API slug (`templateId`) or direct `subject` and `html` content. Returns a durable emailSendId; pass it to get_email_send for delivery status and failure details.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},to:{type:"string",description:"Recipient email address"},subject:{type:"string",description:"Email subject line. Required with `html` when `templateId` is omitted."},html:{type:"string",description:"Direct-send HTML body. Required with `subject` when `templateId` is omitted; the MCP server maps this to the transactional API `body` field."},templateId:{type:"string",description:"Saved transactional email API slug, for example `welcome-email`. The field name is retained for MCP compatibility and is mapped to the transactional API `slug` field."},variables:{type:"object",description:"Variables for template personalization. Nested objects and arrays are supported for repeat blocks, for example { items: [...] }."},subscriberExternalId:{type:"string",description:"Customer-owned subscriber ID for attaching analytics/localization on single-recipient sends. Maximum length: 255 characters."}},required:["to"],additionalProperties:!1}}];var xH=[{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:[...J1]},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:[...J1]},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 yH=[...OH,...TH,...RH,..._H,...vH,...UH,...CH,...zH,...PH,...FH,...IH,...KH,...NH,...EH,...ZH,...VH,...uH,...LH,...kH,...MH,...xH,...AH,...BH];async function hH(b,w){let $;switch(b){case"get_account":{let W=await z("GET","/api/v1/account"),Q=Uw();$={...W,selectedCompanyId:Q??W.currentCompanyId};break}case"select_company":{let W=w.companyId,Q=await z("GET","/api/v1/account"),q=Q.companies?.find((G)=>G.id===W);if(!q)throw Error(`Company not found. Available companies: ${Q.companies?.map((G)=>`${G.name} (${G.id})`).join(", ")??"none"}`);L0(W),$={success:!0,message:`Switched to company: ${q.name}`,companyId:q.id,companyName:q.name};break}case"get_app_urls":{let W=await o$(w);$={...Dw({companyId:W,campaignId:L(w,"campaignId"),landingPageId:L(w,"landingPageId"),sequenceId:L(w,"sequenceId"),emailId:L(w,"emailId")??L(w,"templateId"),transactionalId:L(w,"transactionalId"),emailSendId:L(w,"emailSendId"),domainId:L(w,"domainId"),status:L(w,"status"),settingsTab:L(w,"settingsTab")}),...W===void 0&&{note:"No company ID is selected. Call get_account, select_company, or pass companyId to get concrete dashboard URLs."}};break}case"create_company":{let W=await z("POST","/api/v1/companies",{name:w.name,domain:w.domain});if(!W.success)throw Error("Failed to create company");let Q=W.company.id,q=6,G=0,X=W.company.status;while(X==="processing"&&G<q){await new Promise((D)=>setTimeout(D,20000)),G++;let J=await z("GET",`/api/v1/companies/${Q}`);if(J.success)X=J.company.status}L0(Q);let Y=await z("GET",`/api/v1/companies/${Q}`);$={success:!0,company:Y.company,message:X==="processing"?"Company created but still processing. You can continue using it while processing completes.":`Company '${Y.company.name}' created and ready to use.`,autoSelected:!0};break}case"get_company":{let W=w.companyId;$=await z("GET",`/api/v1/companies/${W}`);break}case"update_company":{let W=await d$("update_company",w),Q=yD(w);$=await z("PATCH",`/api/v1/companies/${W}`,Q);break}case"get_sync_rules":{let W=w.companyId;$=await z("GET","/api/v1/sync-rules",void 0,W);break}case"update_sync_rules":{let W=w.companyId;if(w.syncRules!==null&&!Array.isArray(w.syncRules))throw Error("`syncRules` must be an array of rules or null when calling `update_sync_rules`.");$=await z("PUT","/api/v1/sync-rules",{syncRules:w.syncRules},W);break}case"get_shopify_automation_settings":{let W=w.companyId;$=await z("GET","/api/v1/shopify/automation-settings",void 0,W);break}case"update_shopify_automation_settings":{let W=w.companyId,Q={};if(w.browseAbandonment!==void 0)Q.browseAbandonment=w.browseAbandonment;if(w.priceDrop!==void 0)Q.priceDrop=w.priceDrop;if(Object.keys(Q).length===0)throw Error("Provide `browseAbandonment` and/or `priceDrop` when calling `update_shopify_automation_settings`.");$=await z("PUT","/api/v1/shopify/automation-settings",Q,W);break}case"create_api_key":{let W=w.companyId,Q={};if(typeof w.name==="string")Q.name=w.name;if(typeof w.preset==="string")Q.preset=w.preset;if(Array.isArray(w.scopes))Q.scopes=w.scopes;$=await z("POST","/api/v1/api-keys",Q,W);break}case"list_api_keys":{let W=await d$(b,w);$=await z("GET","/api/v1/api-keys",void 0,W);break}case"revoke_api_key":case"delete_api_key":{let W=await d$(b,w);$=await z("DELETE",`/api/v1/api-keys/${encodeURIComponent(String(w.apiKeyId))}`,void 0,W);break}case"list_websites":{let W=w.companyId;$=await z("GET","/api/v1/websites",void 0,W);break}case"add_sending_domain":case"add_website":{let W=w.companyId;$=await z("POST","/api/v1/websites",{domain:w.domain},W);break}case"check_website":{let W=w.companyId;$=await z("GET",`/api/v1/websites/${encodeURIComponent(String(w.domain))}`,void 0,W);break}case"verify_sending_domain":{let W=w.companyId;$=await z("POST",`/api/v1/websites/${encodeURIComponent(String(w.domain))}/verify`,void 0,W);break}case"get_integration_guide":$=await z("POST","/api/v1/integration-guide",w);break;default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function cH(b,w){let $;switch(b){case"generate_email":{let W=w.companyId;$=await z("POST","/api/v1/generate/email",w,W);break}case"generate_subject_lines":{let W=w.companyId;$=await z("POST","/api/v1/generate/subjects",w,W);break}case"generate_sms":{let W=w.companyId;$=await z("POST","/api/v1/generate/sms",w,W);break}case"get_sms_settings":{let W=w.companyId;$=await z("GET","/api/v1/sms/settings",void 0,W);break}case"send_test_sms":{let W=w.companyId,Q={to:M("send_test_sms",w,"to")};for(let q of["text","imageUrls","blocks"])if(w[q]!==void 0)Q[q]=w[q];$=await z("POST","/api/v1/sms/test",Q,W);break}case"submit_feedback":{let W=w.companyId,Q={message:M("submit_feedback",w,"message"),source:"mcp"};for(let q of["category","context"])if(w[q]!==void 0)Q[q]=w[q];$=await z("POST","/api/v1/feedback",Q,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function fH(b,w){let $;switch(b){case"list_transactional_emails":{let W=w.companyId;$=await z("GET","/api/v1/transactional",void 0,W);break}case"get_transactional_email":{let W=w.companyId;$=await z("GET",`/api/v1/transactional/${w.idOrSlug}`,void 0,W);break}case"create_transactional_email":{let W=w.companyId,Q=new Set(["companyId","name","slug","subject","previewText","html","blocks","prompt","style","tone","enabled"]),q=Object.keys(w).filter((X)=>!Q.has(X));if(q.length>0)throw Error(`\`create_transactional_email\` accepts only \`name\`, \`slug\`, \`subject\`, \`previewText\`, \`html\`, \`blocks\`, \`prompt\`, \`style\`, \`tone\`, and \`enabled\` fields. Unsupported field${q.length===1?"":"s"}: ${q.map((X)=>`\`${X}\``).join(", ")}.`);sD(w);let G=Object.fromEntries(Object.entries(w).filter(([X])=>X!=="companyId"));$=await z("POST","/api/v1/transactional",G,W);break}case"update_transactional_email":{let W=w.companyId,Q=new Set(["companyId","idOrSlug","name","enabled","subject","previewText","html","blocks"]),q=Object.keys(w).filter((X)=>!Q.has(X));if(q.length>0)throw Error(`\`update_transactional_email\` accepts only \`name\`, \`enabled\`, \`subject\`, \`previewText\`, \`html\`, and \`blocks\` update fields. Unsupported field${q.length===1?"":"s"}: ${q.map((X)=>`\`${X}\``).join(", ")}.`);if(Sb("update_transactional_email",w),w.name===void 0&&w.enabled===void 0&&w.subject===void 0&&w.previewText===void 0&&w.html===void 0&&w.blocks===void 0)throw Error("Provide at least one of `name`, `enabled`, `subject`, `previewText`, `html`, or `blocks` when calling `update_transactional_email`.");let G=Object.fromEntries(Object.entries(w).filter(([X])=>X!=="companyId"&&X!=="idOrSlug"));$=await z("PATCH",`/api/v1/transactional/${w.idOrSlug}`,G,W);break}case"send_email":{let W=w.companyId,Q=M("send_email",w,"to"),q=w.templateId===void 0?void 0:M("send_email",w,"templateId"),G=w.subject===void 0?void 0:M("send_email",w,"subject"),X=w.html===void 0?void 0:M("send_email",w,"html");if(q!==void 0&&(G!==void 0||X!==void 0))throw Error("`templateId` cannot be combined with `subject` or `html` when calling `send_email`.");if(q===void 0&&(G===void 0||X===void 0))throw Error("Provide either `templateId` or both `subject` and `html` when calling `send_email`.");let Y=Object.fromEntries(Object.entries({to:Q,slug:q,subject:G,body:X,variables:w.variables,subscriberExternalId:w.subscriberExternalId}).filter(([,J])=>J!==void 0));$=await z("POST","/api/v1/transactional/send",Y,W);break}case"get_stats":{let W=w.companyId,Q=w.period??"7d",q=new URLSearchParams({period:String(Q)});if(w.includeMachineEngagement===!0)q.set("includeMachineEngagement","true");$=await z("GET",`/api/v1/metrics?${q.toString()}`,void 0,W);break}case"get_campaign_stats":{let W=w.companyId,Q=new URLSearchParams;if(w.includeMachineEngagement===!0)Q.set("includeMachineEngagement","true");let q=Q.toString();$=await z("GET",`/api/v1/metrics/campaigns/${w.campaignId}${q?`?${q}`:""}`,void 0,W);break}case"get_sequence_stats":{let W=w.companyId,Q=new URLSearchParams;if(w.includeMachineEngagement===!0)Q.set("includeMachineEngagement","true");let q=Q.toString();$=await z("GET",`/api/v1/metrics/sequences/${w.sequenceId}${q?`?${q}`:""}`,void 0,W);break}case"list_campaign_events":{let W=w.companyId,Q=M("list_campaign_events",w,"campaignId"),G=RW("list_campaign_events",w).toString();$=await z("GET",`/api/v1/metrics/campaigns/${encodeURIComponent(Q)}/events${G?`?${G}`:""}`,void 0,W);break}case"list_sequence_events":{let W=w.companyId,Q=M("list_sequence_events",w,"sequenceId"),G=RW("list_sequence_events",w).toString();$=await z("GET",`/api/v1/metrics/sequences/${encodeURIComponent(Q)}/events${G?`?${G}`:""}`,void 0,W);break}case"get_subscriber_activity":{let W=w.companyId,Q=Aw("get_subscriber_activity",w),q=await H0(Q,W,{includeMachineEngagement:w.includeMachineEngagement===!0});$={success:q.success,email:q.subscriber.email,emailStats:q.subscriber.emailStats??null,activity:q.subscriber.activity??[],sequenceEnrollments:q.subscriber.sequenceEnrollments??[]};break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function nH(b,w){let $;switch(b){case"list_tags":{let W=w.companyId;$=await z("GET","/api/v1/tags",void 0,W);break}case"create_tag":{let W=w.companyId,Q=M("create_tag",w,"name"),q=qb("create_tag",w,"color",Y1);$=await z("POST","/api/v1/tags",{name:Q,...q!==void 0&&{color:q}},W);break}case"update_tag":{let W=w.companyId,Q=M("update_tag",w,"tagId"),q=z0("update_tag",w,"color",Y1);$=await z("PATCH",`/api/v1/tags/${encodeURIComponent(Q)}`,{color:q},W);break}case"delete_tag":{let W=w.companyId,Q=M("delete_tag",w,"tagId");$=await z("DELETE",`/api/v1/tags/${encodeURIComponent(Q)}`,void 0,W);break}case"list_lists":{let W=w.companyId;$=await z("GET","/api/v1/lists",void 0,W);break}case"create_list":{let W=w.companyId;$=await z("POST","/api/v1/lists",w,W);break}case"update_list":{let W=w.companyId,Q=M("update_list",w,"listId");if(w.name===void 0&&w.description===void 0&&w.isPrivate===void 0)throw Error("Provide at least one of `name`, `description`, or `isPrivate` when calling `update_list`.");if(w.name!==void 0&&L(w,"name")===void 0)throw Error("`name` cannot be empty when calling `update_list`.");if(w.description!==void 0&&w.description!==null&&typeof w.description!=="string")throw Error("`description` must be a string or null when calling `update_list`.");if(w.isPrivate!==void 0&&typeof w.isPrivate!=="boolean")throw Error("`isPrivate` must be a boolean when calling `update_list`.");$=await z("PATCH",`/api/v1/lists/${encodeURIComponent(Q)}`,{...w.name!==void 0&&{name:L(w,"name")},...w.description!==void 0&&{description:w.description},...w.isPrivate!==void 0&&{isPrivate:w.isPrivate}},W);break}case"delete_list":{let W=w.companyId,Q=M("delete_list",w,"listId");$=await z("DELETE",`/api/v1/lists/${encodeURIComponent(Q)}`,void 0,W);break}case"add_subscribers_to_list":{let W=w.companyId,Q=M("add_subscribers_to_list",w,"listId"),q=kW("add_subscribers_to_list",w),G=qb("add_subscribers_to_list",w,"duplicateStrategy",["skip","merge","overwrite"])??"skip",X=qb("add_subscribers_to_list",w,"optInMode",["default","confirmed","double_opt_in"])??"default";$=await z("POST",`/api/v1/lists/${encodeURIComponent(Q)}/subscribers`,{emails:q,duplicateStrategy:G,enrollInSequences:w.enrollInSequences===!0,optInMode:X},W);break}case"remove_subscribers_from_list":{let W=w.companyId,Q=M("remove_subscribers_from_list",w,"listId"),q=kW("remove_subscribers_from_list",w);$=await z("POST",`/api/v1/lists/${encodeURIComponent(Q)}/subscribers/remove`,{emails:q},W);break}case"list_segments":{let W=w.companyId;$=await z("GET","/api/v1/segments",void 0,W);break}case"create_segment":{uD(w);let W=w.companyId;$=await z("POST","/api/v1/segments",{...w,...w.filters!==void 0?{filters:f$(w.filters)}:{},...w.root!==void 0?{root:n$(w.root)}:{}},W);break}case"update_segment":{xD(w);let W=w.companyId,Q=M("update_segment",w,"segmentId"),q=L(w,"name"),G=qb("update_segment",w,"filterJoinOperator",["and","or"]);$=await z("PATCH",`/api/v1/segments/${encodeURIComponent(Q)}`,{...q!==void 0&&{name:q},...G!==void 0&&{filterJoinOperator:G},...w.filters!==void 0?{filters:f$(w.filters)}:{},...w.root!==void 0?{root:n$(w.root)}:{}},W);break}case"delete_segment":{let W=w.companyId,Q=M("delete_segment",w,"segmentId");$=await z("DELETE",`/api/v1/segments/${encodeURIComponent(Q)}`,void 0,W);break}case"get_segment_count":{let W=w.companyId;$=await z("GET",`/api/v1/segments/${w.segmentId}/count`,void 0,W);break}case"list_audience_syncs":{let W=w.companyId;$=await z("GET","/api/v1/audience-syncs",void 0,W);break}case"list_ad_accounts":{let W=w.companyId;$=await z("GET","/api/v1/ad-accounts",void 0,W);break}case"create_audience_sync":{let W=w.companyId,Q=L(w,"segmentId"),q=L(w,"predefinedSegmentId");if(Q&&q)throw Error("Provide either `segmentId` or `predefinedSegmentId` when calling `create_audience_sync`, not both.");if(!Q&&!q)throw Error("Provide either `segmentId` or `predefinedSegmentId` when calling `create_audience_sync`.");$=await z("POST","/api/v1/audience-syncs",{segmentId:Q,predefinedSegmentId:q,adAccountId:M("create_audience_sync",w,"adAccountId"),audienceName:M("create_audience_sync",w,"audienceName"),...w.frequency!==void 0?{frequency:w.frequency}:{}},W);break}case"update_audience_sync":{let W=w.companyId,Q=M("update_audience_sync",w,"syncId");$=await z("PATCH",`/api/v1/audience-syncs/${encodeURIComponent(Q)}`,{...w.frequency!==void 0?{frequency:w.frequency}:{},...w.isActive!==void 0?{isActive:w.isActive}:{}},W);break}case"delete_audience_sync":{let W=w.companyId,Q=M("delete_audience_sync",w,"syncId");$=await z("DELETE",`/api/v1/audience-syncs/${encodeURIComponent(Q)}`,void 0,W);break}case"sync_audience_now":{let W=w.companyId,Q=M("sync_audience_now",w,"syncId");$=await z("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 iH(b,w){let $;switch(b){case"list_templates":{let W=w.companyId,Q=new URLSearchParams,q=L(w,"label");if(q)Q.set("label",q);$=await z("GET",`/api/v1/templates${Q.size>0?`?${Q}`:""}`,void 0,W);break}case"get_template":{let W=w.companyId;$=await z("GET",`/api/v1/templates/${w.templateId}`,void 0,W);break}case"create_template":{let W=w.companyId;tD(w);let Q=Object.fromEntries(Object.entries(w).filter(([q])=>q!=="companyId"));$=await z("POST","/api/v1/templates",Q,W);break}case"update_template":{let W=w.companyId,Q=new Set(["companyId","templateId","name","subject","previewText","html","blocks","labels"]),q=Object.keys(w).filter((G)=>!Q.has(G));if(q.length>0)throw Error(`\`update_template\` accepts only \`name\`, \`subject\`, \`previewText\`, \`html\`, \`blocks\`, and \`labels\` update fields. Unsupported field${q.length===1?"":"s"}: ${q.map((G)=>`\`${G}\``).join(", ")}.`);if(Sb("update_template",w),Ow("update_template",w),w.name===void 0&&w.subject===void 0&&w.previewText===void 0&&w.html===void 0&&w.blocks===void 0&&w.labels===void 0)throw Error("Provide at least one of `name`, `subject`, `previewText`, `html`, `blocks`, or `labels` when calling `update_template`.");$=await z("PUT",`/api/v1/templates/${w.templateId}`,w,W);break}case"set_template_localization":{let W=w.companyId,Q=M("set_template_localization",w,"templateId"),q=M("set_template_localization",w,"locale"),G=M("set_template_localization",w,"subject"),X=new Set(["companyId","templateId","locale","subject","previewText","html","blocks"]),Y=Object.keys(w).filter((D)=>!X.has(D));if(Y.length>0)throw Error(`\`set_template_localization\` received unsupported field${Y.length===1?"":"s"}: ${Y.map((D)=>`\`${D}\``).join(", ")}.`);Sb("set_template_localization",w,{requireContent:!0});let J={subject:G};if(w.previewText!==void 0)J.previewText=w.previewText;if(w.html!==void 0)J.html=w.html;if(w.blocks!==void 0)J.blocks=w.blocks;$=await z("PUT",`/api/v1/templates/${encodeURIComponent(Q)}/localizations/${encodeURIComponent(q)}`,J,W);break}case"sync_template_localizations":{let W=w.companyId,Q=M("sync_template_localizations",w,"templateId"),q=new Set(["companyId","templateId","locales"]),G=Object.keys(w).filter((Y)=>!q.has(Y));if(G.length>0)throw Error(`\`sync_template_localizations\` received unsupported field${G.length===1?"":"s"}: ${G.map((Y)=>`\`${Y}\``).join(", ")}.`);let X;if(w.locales!==void 0){if(!Array.isArray(w.locales)||w.locales.length===0||w.locales.some((Y)=>typeof Y!=="string"||Y.trim().length===0))throw Error("`locales` must contain at least one non-empty locale string when calling `sync_template_localizations`.");X=w.locales.map((Y)=>Y.trim())}$=await z("POST",`/api/v1/templates/${encodeURIComponent(Q)}/localizations/sync`,X===void 0?{}:{locales:X},W);break}case"delete_template":{let W=w.companyId;$=await z("DELETE",`/api/v1/templates/${w.templateId}`,void 0,W);break}case"list_ab_tests":{let W=w.companyId,Q=new URLSearchParams,q=L(w,"sequenceId");if(q)Q.set("sequenceId",q);$=await z("GET",`/api/v1/ab-tests${Q.size>0?`?${Q}`:""}`,void 0,W);break}case"get_ab_test":{let W=w.companyId;$=await z("GET",`/api/v1/ab-tests/${w.abTestId}`,void 0,W);break}case"get_ab_test_stats":{let W=w.companyId,Q=new URLSearchParams,q=L(w,"period"),G=L(w,"start"),X=L(w,"end");if(q)Q.set("period",q);if(G)Q.set("start",G);if(X)Q.set("end",X);if(w.includeMachineEngagement===!0)Q.set("includeMachineEngagement","true");$=await z("GET",`/api/v1/ab-tests/${w.abTestId}/stats${Q.size>0?`?${Q}`:""}`,void 0,W);break}case"restart_ab_test":{let W=w.companyId,Q=new Set(["companyId","abTestId","sourceVariantId","testType","winnerThreshold","variantCount"]),q=Object.keys(w).filter((J)=>!Q.has(J));if(q.length>0)throw Error(`\`restart_ab_test\` accepts only \`sourceVariantId\`, \`testType\`, \`winnerThreshold\`, and \`variantCount\` option fields. Unsupported field${q.length===1?"":"s"}: ${q.map((J)=>`\`${J}\``).join(", ")}.`);let G=L(w,"testType");if(G!==void 0&&G!=="subject"&&G!=="content")throw Error("`restart_ab_test` testType must be `subject` or `content`.");let X=w.winnerThreshold===void 0?void 0:Number(w.winnerThreshold);if(X!==void 0&&(!Number.isInteger(X)||X<10||X>1000))throw Error("`restart_ab_test` winnerThreshold must be an integer from 10 to 1000.");let Y=w.variantCount===void 0?void 0:Number(w.variantCount);if(Y!==void 0&&(!Number.isInteger(Y)||Y<2||Y>4))throw Error("`restart_ab_test` variantCount must be an integer from 2 to 4.");$=await z("POST",`/api/v1/ab-tests/${w.abTestId}/restart`,{sourceVariantId:L(w,"sourceVariantId"),testType:G,winnerThreshold:X,variantCount:Y},W);break}case"update_ab_test_variant":{let W=w.companyId,Q=new Set(["companyId","abTestId","variantId","subject","previewText","html","blocks","confirmLiveChange"]),q=Object.keys(w).filter((G)=>!Q.has(G));if(q.length>0)throw Error(`\`update_ab_test_variant\` accepts only \`subject\`, \`previewText\`, \`html\`, \`blocks\`, and \`confirmLiveChange\` fields. Unsupported field${q.length===1?"":"s"}: ${q.map((G)=>`\`${G}\``).join(", ")}.`);if(Sb("update_ab_test_variant",w),w.confirmLiveChange!==void 0&&typeof w.confirmLiveChange!=="boolean")throw Error("`confirmLiveChange` must be a boolean when calling `update_ab_test_variant`.");if(w.subject===void 0&&w.previewText===void 0&&w.html===void 0&&w.blocks===void 0)throw Error("Provide at least one of `subject`, `previewText`, `html`, or `blocks` when calling `update_ab_test_variant`.");$=await z("PATCH",`/api/v1/ab-tests/${w.abTestId}/variants/${w.variantId}`,w,W);break}case"create_ab_test":{let W=w.companyId,Q=L(w,"campaignId"),q=L(w,"automationNodeId");if(w.confirmLiveChange!==void 0&&typeof w.confirmLiveChange!=="boolean")throw Error("`confirmLiveChange` must be a boolean when calling `create_ab_test`.");if(Boolean(Q)===Boolean(q))throw Error("Provide exactly one of `campaignId` or `automationNodeId` when calling `create_ab_test`.");let G=L(w,"name"),X=ab("create_ab_test",w,"testPercentage",5,50),Y=ab("create_ab_test",w,"testDurationMinutes",15,1440),J=qb("create_ab_test",w,"winnerCriteria",["open_rate","click_rate"]),D=qb("create_ab_test",w,"testType",["subject","content"]),H=ab("create_ab_test",w,"winnerThreshold",10,1000);if(w.variants!==void 0){if(!Array.isArray(w.variants))throw Error("`variants` must be an array when calling `create_ab_test`.");w.variants.forEach((A,B)=>{if(!k(A)||typeof A.subject!=="string"||A.subject.trim()==="")throw Error(`\`variants\` item ${B+1} must include a non-empty \`subject\` when calling \`create_ab_test\`.`);if(A.blocks!==void 0&&!Array.isArray(A.blocks))throw Error(`\`variants\` item ${B+1} \`blocks\` must be an array when calling \`create_ab_test\`.`)})}let O=Array.isArray(w.variants)?w.variants:void 0;if(q!==void 0&&(!O||O.length<1))throw Error("`variants` must include at least one competing variant when calling `create_ab_test` with `automationNodeId`.");if(O&&O.length>4)throw Error("`variants` supports at most four extra variants when calling `create_ab_test`.");$=await z("POST","/api/v1/ab-tests",{...Q!==void 0&&{campaignId:Q},...q!==void 0&&{automationNodeId:q},...w.confirmLiveChange===!0&&{confirmLiveChange:!0},...G!==void 0&&{name:G},...X!==void 0&&{testPercentage:X},...Y!==void 0&&{testDurationMinutes:Y},...J!==void 0&&{winnerCriteria:J},...D!==void 0&&{testType:D},...H!==void 0&&{winnerThreshold:H},...w.variants!==void 0&&{variants:w.variants}},W);break}case"add_ab_test_variant":{let W=w.companyId,Q=M("add_ab_test_variant",w,"abTestId"),q=M("add_ab_test_variant",w,"subject"),G=L(w,"previewText");if(w.blocks!==void 0&&!Array.isArray(w.blocks))throw Error("`blocks` must be an array when calling `add_ab_test_variant`.");if(w.confirmLiveChange!==void 0&&typeof w.confirmLiveChange!=="boolean")throw Error("`confirmLiveChange` must be a boolean when calling `add_ab_test_variant`.");$=await z("POST",`/api/v1/ab-tests/${encodeURIComponent(Q)}/variants`,{subject:q,...G!==void 0&&{previewText:G},...w.blocks!==void 0&&{blocks:w.blocks},...w.confirmLiveChange===!0&&{confirmLiveChange:!0}},W);break}case"delete_ab_test_variant":{let W=w.companyId,Q=M("delete_ab_test_variant",w,"abTestId"),q=M("delete_ab_test_variant",w,"variantId");if(w.confirmLiveChange!==void 0&&typeof w.confirmLiveChange!=="boolean")throw Error("`confirmLiveChange` must be a boolean when calling `delete_ab_test_variant`.");$=await z("DELETE",`/api/v1/ab-tests/${encodeURIComponent(Q)}/variants/${encodeURIComponent(q)}${w.confirmLiveChange===!0?"?confirmLiveChange=true":""}`,void 0,W);break}case"delete_ab_test":{let W=w.companyId,Q=M("delete_ab_test",w,"abTestId");$=await z("DELETE",`/api/v1/ab-tests/${encodeURIComponent(Q)}`,void 0,W);break}case"list_campaigns":{let W=w.companyId,Q=new URLSearchParams;if(w.status)Q.set("status",String(w.status));let q=L(w,"label");if(q)Q.set("label",q);$=await z("GET",`/api/v1/campaigns?${Q}`,void 0,W);break}case"get_campaign":{let W=w.companyId;$=await z("GET",`/api/v1/campaigns/${w.campaignId}`,void 0,W);break}case"get_email_send":{let W=w.companyId;$=await z("GET",`/api/v1/email-sends/${encodeURIComponent(String(w.emailSendId))}`,void 0,W);break}case"create_campaign":{let W=w.companyId;if(dD(w),w.fromEmail!==void 0&&w.senderProfileId!==void 0)throw Error("Provide either `fromEmail` or `senderProfileId` when calling `create_campaign`, not both.");if(w.replyTo!==void 0&&w.replyProfileId!==void 0)throw Error("Provide either `replyTo` or `replyProfileId` when calling `create_campaign`, not both.");if(w.fromName!==void 0&&w.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `create_campaign`.");if(w.replyToName!==void 0&&w.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `create_campaign`.");let Q=Object.fromEntries(Object.entries(w).filter(([q])=>q!=="companyId"));$=await z("POST","/api/v1/campaigns",Q,W);break}case"update_campaign":{let W=w.companyId,Q=new Set(["companyId","campaignId","name","subject","trackingCode","html","blocks","fromEmail","fromName","senderProfileId","replyTo","replyToName","replyProfileId","ccEmails","bccEmails","campaignData","computedLists","labels"]),q=Object.keys(w).filter((G)=>!Q.has(G));if(q.length>0)throw Error(`\`update_campaign\` accepts only content, sending identity, campaign data, computed list, and label update fields. Unsupported field${q.length===1?"":"s"}: ${q.map((G)=>`\`${G}\``).join(", ")}.`);if(Sb("update_campaign",w),Ow("update_campaign",w),w.replyTo!==void 0&&w.replyProfileId!==void 0)throw Error("Provide either `replyTo` or `replyProfileId` when calling `update_campaign`, not both.");if(w.fromEmail!==void 0&&w.senderProfileId!==void 0)throw Error("Provide either `fromEmail` or `senderProfileId` when calling `update_campaign`, not both.");if(w.fromName!==void 0&&w.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `update_campaign`.");if(w.replyToName!==void 0&&w.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `update_campaign`.");if(w.name===void 0&&w.subject===void 0&&w.trackingCode===void 0&&w.html===void 0&&w.blocks===void 0&&w.fromEmail===void 0&&w.senderProfileId===void 0&&w.replyTo===void 0&&w.replyProfileId===void 0&&w.ccEmails===void 0&&w.bccEmails===void 0&&w.campaignData===void 0&&w.computedLists===void 0&&w.labels===void 0)throw Error("Provide at least one campaign content, sending identity, campaign data, computed list, or label field when calling `update_campaign`.");$=await z("PUT",`/api/v1/campaigns/${w.campaignId}`,w,W);break}case"schedule_campaign":{let W=w.companyId,Q=new Set(["companyId","campaignId","scheduledAt","targetLists","sendTimeOptimization","spreadOverHours","recurringInterval"]),q=Object.keys(w).filter((G)=>!Q.has(G));if(q.length>0)throw Error(`\`schedule_campaign\` accepts only \`campaignId\`, \`scheduledAt\`, \`targetLists\`, \`sendTimeOptimization\`, \`spreadOverHours\`, and \`recurringInterval\`. Unsupported field${q.length===1?"":"s"}: ${q.map((G)=>`\`${G}\``).join(", ")}.`);rD(w),$=await z("POST",`/api/v1/campaigns/${w.campaignId}/schedule`,{scheduledAt:w.scheduledAt,...w.targetLists!==void 0&&{targetLists:w.targetLists},...w.sendTimeOptimization!==void 0&&{sendTimeOptimization:w.sendTimeOptimization},...w.spreadOverHours!==void 0&&{spreadOverHours:w.spreadOverHours},...w.recurringInterval!==void 0&&{recurringInterval:w.recurringInterval}},W);break}case"send_test_email":{let W=w.companyId;$=await z("POST",`/api/v1/campaigns/${w.campaignId}/test`,{to:w.to},W);break}case"cancel_campaign":{let W=w.companyId,Q=M("cancel_campaign",w,"campaignId");$=await z("POST",`/api/v1/campaigns/${encodeURIComponent(Q)}/cancel`,void 0,W);break}case"pause_campaign":{let W=w.companyId,Q=M("pause_campaign",w,"campaignId");$=await z("POST",`/api/v1/campaigns/${encodeURIComponent(Q)}/pause`,void 0,W);break}case"resume_campaign":{let W=w.companyId,Q=M("resume_campaign",w,"campaignId"),q=ab("resume_campaign",w,"spreadOverHours",1,72);$=await z("POST",`/api/v1/campaigns/${encodeURIComponent(Q)}/resume`,{...q!==void 0&&{spreadOverHours:q}},W);break}case"delete_campaign":{let W=w.companyId,Q=M("delete_campaign",w,"campaignId");$=await z("DELETE",`/api/v1/campaigns/${encodeURIComponent(Q)}`,void 0,W);break}case"duplicate_campaign":{let W=w.companyId,Q=M("duplicate_campaign",w,"campaignId"),q=qb("duplicate_campaign",w,"mode",["campaign","ab_test","variant"]),G=L(w,"variantId");if(q==="variant"&&G===void 0)throw Error("`variantId` is required when calling `duplicate_campaign` with mode `variant`.");$=await z("POST",`/api/v1/campaigns/${encodeURIComponent(Q)}/duplicate`,{...q!==void 0&&{mode:q},...G!==void 0&&{variantId:G}},W);break}case"resend_campaign_to_non_openers":{let W=w.companyId,Q=M("resend_campaign_to_non_openers",w,"campaignId");$=await z("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 mH(b,w){let $;switch(b){case"list_forms":{let W=w.companyId;$=await z("GET","/api/v1/forms",void 0,W);break}case"create_form":{let W=w.companyId,Q=M("create_form",w,"name"),q=Array.isArray(w.listIds)?w.listIds.filter((Y)=>typeof Y==="string").map((Y)=>Y.trim()).filter(Boolean):[];if(q.length===0)throw Error("`listIds` must contain at least one list ID when calling `create_form`.");let G=qb("create_form",w,"duplicateStrategy",["skip","merge","overwrite"]),X={name:Q,listIds:q};for(let Y of["tagIds","buttonText","headline","description","successMessage","redirectUrl","showFirstName","showLastName"])if(w[Y]!==void 0)X[Y]=w[Y];if(G!==void 0)X.duplicateStrategy=G;$=await z("POST","/api/v1/forms",X,W);break}case"get_form_embed":{let W=w.companyId,Q=M("get_form_embed",w,"formId");$=await z("GET",`/api/v1/forms/embed/${encodeURIComponent(Q)}`,void 0,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}function r$(b,w,$,W,Q){let q=b[w];if(q===void 0)return;if(typeof q!=="number"||!Number.isFinite(q)||q<$||q>W||Q&&!Number.isInteger(q))throw Error(`\`${w}\` must be a ${Q?"integer":"number"} between ${$} and ${W} when calling \`upload_image_asset\`.`);return q}async function lH(b,w){if(b!=="upload_image_asset")return{handled:!1,result:void 0};let $=L(w,"filePath"),W=L(w,"imageBase64");if($===void 0===(W===void 0))throw Error("Provide either `filePath` or `imageBase64` (not both) when calling `upload_image_asset`.");let Q=L(w,"filename");if(W!==void 0&&Q===void 0)throw Error("`filename` is required with `imageBase64` when calling `upload_image_asset`.");let q=r$(w,"sourceWidth",1,20000,!0),G=r$(w,"sourceHeight",1,20000,!0);if(q===void 0!==(G===void 0))throw Error("Provide both `sourceWidth` and `sourceHeight` when calling `upload_image_asset`.");let X=r$(w,"displayWidthPercent",1,100,!1)??100,Y=r$(w,"cropHeight",1,2000,!0),J=L(w,"objectFit");if(J!==void 0&&J!=="cover"&&J!=="contain")throw Error("`objectFit` must be 'cover' or 'contain' when calling `upload_image_asset`.");if(J!==void 0&&Y===void 0)throw Error("`objectFit` can only be used with `cropHeight` when calling `upload_image_asset`.");let D=L(w,"align");if(D!==void 0&&!["left","center","right"].includes(D))throw Error("`align` must be 'left', 'center', or 'right' when calling `upload_image_asset`.");let H=typeof w.altText==="string"?w.altText.trim():void 0;if(H!==void 0&&H.length>500)throw Error("`altText` must be 500 characters or fewer when calling `upload_image_asset`.");let O=await JH({companyId:L(w,"companyId"),filePath:$,imageBase64:W,filename:Q,contentType:L(w,"contentType"),altText:H,sourceWidth:q,sourceHeight:G}),A={type:"image",src:O.url,alt:O.altText??"",width:X,widthType:"percent",...Y!==void 0&&{height:Y,objectFit:J??"cover"},...D!==void 0&&{align:D}};return{handled:!0,result:{success:!0,asset:O,imageBlock:A,message:"Insert imageBlock into the target email's blocks array with its create or update tool."}}}async function gH(b,w){let $;switch(b){case"list_landing_pages":{let W=w.companyId;$=await z("GET","/api/v1/landing-pages",void 0,W);break}case"get_landing_page":{let W=w.companyId;$=await z("GET",`/api/v1/landing-pages/${w.landingPageId}`,void 0,W);break}case"create_landing_page":{let W=w.companyId,Q=new Set(["companyId","name","slug","template","content"]),q=Object.keys(w).filter((G)=>!Q.has(G));if(q.length>0)throw Error(`\`create_landing_page\` accepts only \`name\`, \`slug\`, \`template\`, and \`content\` fields. Unsupported field${q.length===1?"":"s"}: ${q.map((G)=>`\`${G}\``).join(", ")}.`);$=await z("POST","/api/v1/landing-pages",{...w.name!==void 0&&{name:w.name},...w.slug!==void 0&&{slug:w.slug},...w.template!==void 0&&{template:w.template},...w.content!==void 0&&{content:w.content}},W);break}case"update_landing_page":{let W=w.companyId,Q=g$("update_landing_page",w,{requireUpdate:!0});$=await z("PUT",`/api/v1/landing-pages/${w.landingPageId}`,Q,W);break}case"publish_landing_page":{let W=w.companyId,Q=g$("publish_landing_page",w,{requireUpdate:!1});$=await z("POST",`/api/v1/landing-pages/${w.landingPageId}/publish`,Q,W);break}case"unpublish_landing_page":{let W=w.companyId,Q=g$("unpublish_landing_page",w,{requireUpdate:!1});$=await z("POST",`/api/v1/landing-pages/${w.landingPageId}/unpublish`,Q,W);break}case"delete_landing_page":{let W=w.companyId;$=await z("DELETE",`/api/v1/landing-pages/${w.landingPageId}`,void 0,W);break}case"connect_landing_page_domain":{let W=w.companyId;$=await z("POST","/api/v1/landing-pages/domain",{domain:w.domain},W);break}case"update_landing_page_domain_settings":{let W=w.companyId,Q=eD(w);$=await z("PUT","/api/v1/landing-pages/domain",Q,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function pH(b,w){let $;switch(b){case"list_products":{let W=w.companyId,Q=new URLSearchParams;if(typeof w.provider==="string"&&w.provider.trim())Q.set("provider",w.provider.trim());if(typeof w.search==="string"&&w.search.trim())Q.set("search",w.search.trim());let q=Q.size>0?`?${Q.toString()}`:"";$=await z("GET",`/api/v1/products${q}`,void 0,W);break}case"upsert_products":{let W=w.companyId;if(!Array.isArray(w.products)||w.products.length===0)throw Error("`products` must be a non-empty array when calling `upsert_products`.");$=await z("POST","/api/v1/products",{products:w.products},W);break}case"delete_product":{let W=w.companyId,Q=M("delete_product",w,"productId");$=await z("DELETE",`/api/v1/products/${encodeURIComponent(Q)}`,void 0,W);break}case"attach_product_file":{let W=w.companyId,Q=M("attach_product_file",w,"productId"),q=L(w,"url"),G=L(w,"filePath");if(q===void 0===(G===void 0))throw Error("Provide either `url` or `filePath` (not both) when calling `attach_product_file`.");let X;if(G!==void 0){let Y=await WH(G,W);X={url:Y.url,source:"upload",fileName:L(w,"fileName")??Y.fileName,fileSizeBytes:Y.fileSizeBytes,mimeType:Y.mimeType}}else{X={url:q};let Y=L(w,"fileName");if(Y)X.fileName=Y}$=await z("PUT",`/api/v1/products/${encodeURIComponent(Q)}/delivery`,X,W);break}case"remove_product_file":{let W=w.companyId,Q=M("remove_product_file",w,"productId");$=await z("DELETE",`/api/v1/products/${encodeURIComponent(Q)}/delivery`,void 0,W);break}case"sync_products":{let W=w.companyId;$=await z("POST","/api/v1/products/sync",void 0,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}var oH=80;function rM(b){let w=b.trim().replace(/\s+/g," ");if(w.length<=oH)return w;return`${w.slice(0,oH-3).trimEnd()}...`}async function hW(b,w){let $;switch(b){case"generate_sequence":{let W=M("generate_sequence",w,"goal"),Q=typeof w.name==="string"&&w.name.trim().length>0?w.name.trim():void 0,G=(await hW("create_sequence",{...w,goal:W,name:Q??rM(W),trigger:"contact_added",durationDays:w.durationDays??14})).result;return{handled:!0,result:typeof G==="object"&&G!==null?{...G,deprecated:!0,deprecationMessage:"generate_sequence is deprecated. Use create_sequence for new integrations."}:G}}case"list_sequences":{let W=w.companyId,Q=new URLSearchParams;for(let G of["status","search","limit","offset"])if(w[G]!==void 0)Q.set(G,String(w[G]));if(Array.isArray(w.labels)&&w.labels.length>0)Q.set("labels",w.labels.join(","));let q=Q.size>0?`?${Q.toString()}`:"";$=await z("GET",`/api/v1/sequences${q}`,void 0,W);break}case"get_sequence":{let W=w.companyId;$=await z("GET",`/api/v1/sequences/${w.sequenceId}`,void 0,W);break}case"create_sequence":{let W=w.companyId;if(Ow("create_sequence",w),w.fromEmail!==void 0&&w.senderProfileId!==void 0)throw Error("Provide either `fromEmail` or `senderProfileId` when calling `create_sequence`, not both.");if(w.replyTo!==void 0&&w.replyProfileId!==void 0)throw Error("Provide either `replyTo` or `replyProfileId` when calling `create_sequence`, not both.");if(w.fromName!==void 0&&w.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `create_sequence`.");if(w.replyToName!==void 0&&w.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `create_sequence`.");let Q=Array.isArray(w.steps),q=w.goal===void 0&&w.steps===void 0,G=await z("POST","/api/v1/sequences",w,W);if(!G.success){$=G;break}let X=G.sequence.id;if(Q||q){let O=await z("GET",`/api/v1/sequences/${X}`,void 0,W);if(O.success)$={...G,success:!0,sequence:O.sequence,message:`Sequence "${O.sequence.name}" created ${q?"as a blank draft":"with explicit steps"}. Review it before enabling.${G.eventTrackingCode?" Add the custom event feed using eventTrackingCode and eventTracking before enabling.":""}`};else $=O;break}let Y=7,J=0,D="pending";while(D!=="complete"&&J<Y){let O=await z("GET",`/api/v1/sequences/${X}`,void 0,W);if(O.success)D=O.sequence.enrichmentStatus;if(J++,D!=="complete"&&J<Y)await new Promise((A)=>setTimeout(A,20000))}let H=await z("GET",`/api/v1/sequences/${X}`,void 0,W);if(H.success)$={...G,success:!0,sequence:H.sequence,message:H.sequence.enrichmentStatus==="complete"?`Sequence "${H.sequence.name}" created with ${H.sequence.emailCount} AI-generated emails. The sequence is ready to review and enable.${G.eventTrackingCode?" Add the custom event feed using eventTrackingCode and eventTracking before enabling.":""}`:`Sequence "${H.sequence.name}" created. Email enrichment is still in progress (${H.sequence.enrichedCount}/${H.sequence.emailCount} emails generated). You can check status with get_sequence.${G.eventTrackingCode?" Add the custom event feed using eventTrackingCode and eventTracking before enabling.":""}`};else $=H;break}case"update_sequence":{let W=w.companyId,Q=cD(w);$=await z("PUT",`/api/v1/sequences/${w.sequenceId}`,Q,W);break}case"update_sequence_node":{let W=w.companyId,Q=M("update_sequence_node",w,"sequenceId"),q=mD(w);$=await z("PUT",`/api/v1/sequences/${Q}`,q,W);break}case"update_sequence_nodes":{let W=w.companyId,Q=M("update_sequence_nodes",w,"sequenceId"),q=lD(w);$=await z("PUT",`/api/v1/sequences/${Q}`,q,W);break}case"edit_sequence_graph":{let W=w.companyId,Q=gD(w);$=await z("PUT",`/api/v1/sequences/${w.sequenceId}`,Q,W);break}case"insert_sequence_step":{let W=w.companyId,Q=pD(w),q=await z("PUT",`/api/v1/sequences/${w.sequenceId}`,Q,W);if(typeof q==="object"&&q!==null){let G=q,X=G.sequence;if(typeof X==="object"&&X!==null){let Y=X;$={...G,...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}}$=q;break}case"enable_sequence":{let W=w.companyId;$=await z("POST",`/api/v1/sequences/${w.sequenceId}/enable`,void 0,W);break}case"disable_sequence":{let W=w.companyId;$=await z("POST",`/api/v1/sequences/${w.sequenceId}/disable`,void 0,W);break}case"duplicate_sequence":{let W=w.companyId,Q=M("duplicate_sequence",w,"sequenceId"),q=L(w,"name");$=await z("POST",`/api/v1/sequences/${encodeURIComponent(Q)}/duplicate`,q===void 0?void 0:{name:q},W);break}case"archive_sequence":case"unarchive_sequence":{let W=w.companyId,Q=M(b,w,"sequenceId"),q=b==="archive_sequence"?"archive":"unarchive";$=await z("POST",`/api/v1/sequences/${encodeURIComponent(Q)}/${q}`,void 0,W);break}case"list_sequence_goals":{let W=w.companyId,Q=M(b,w,"sequenceId");$=await z("GET",`/api/v1/sequences/${encodeURIComponent(Q)}/goals`,void 0,W);break}case"create_sequence_goal":case"update_sequence_goal":{let W=w.companyId,Q=M(b,w,"sequenceId");if(b==="create_sequence_goal")M(b,w,"name"),fD(w);else nD(w);let q=b==="update_sequence_goal"?M(b,w,"goalId"):void 0,G={...w};delete G.companyId,delete G.sequenceId,delete G.goalId,$=await z(b==="create_sequence_goal"?"POST":"PATCH",`/api/v1/sequences/${encodeURIComponent(Q)}/goals${q?`/${encodeURIComponent(q)}`:""}`,G,W);break}case"delete_sequence_goal":{let W=w.companyId,Q=M(b,w,"sequenceId"),q=M(b,w,"goalId");$=await z("DELETE",`/api/v1/sequences/${encodeURIComponent(Q)}/goals/${encodeURIComponent(q)}`,void 0,W);break}case"get_sequence_inbound_webhook":case"configure_sequence_inbound_webhook":case"rotate_sequence_inbound_webhook_secret":{let W=w.companyId,Q=M(b,w,"sequenceId");if(w.clearFieldMapping===!0&&w.fieldMapping!==void 0)throw Error("Provide either `fieldMapping` or `clearFieldMapping`, not both.");if(w.clearSamplePayload===!0&&w.samplePayload!==void 0)throw Error("Provide either `samplePayload` or `clearSamplePayload`, not both.");let q=b==="configure_sequence_inbound_webhook",G=b==="rotate_sequence_inbound_webhook_secret",X=q?{...w.clearFieldMapping===!0?{fieldMapping:null}:w.fieldMapping!==void 0?{fieldMapping:w.fieldMapping}:{},...w.clearSamplePayload===!0?{samplePayload:null}:w.samplePayload!==void 0?{samplePayload:w.samplePayload}:{}}:void 0;$=await z(G?"POST":q?"PUT":"GET",`/api/v1/sequences/${encodeURIComponent(Q)}/inbound-webhook${G?"/rotate-secret":""}`,X,W);break}case"pause_sequence_enrollments":{let W=w.companyId;$=await z("POST",`/api/v1/sequences/${w.sequenceId}/pause-enrollments`,void 0,W);break}case"resume_sequence_enrollments":{let W=w.companyId;$=await z("POST",`/api/v1/sequences/${w.sequenceId}/resume-enrollments`,void 0,W);break}case"enroll_subscribers_in_sequence":{let W=w.companyId,Q=M("enroll_subscribers_in_sequence",w,"sequenceId"),q=$H(w);$=await z("POST",`/api/v1/sequences/${encodeURIComponent(Q)}/enroll`,q,W);break}case"cancel_sequence_enrollments":{let W=w.companyId,Q=oD(w);$=await z("POST",`/api/v1/sequences/${w.sequenceId}/enrollments/cancel`,Q,W);break}case"delete_sequence":{let W=w.companyId;$=await z("DELETE",`/api/v1/sequences/${w.sequenceId}`,void 0,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function dH(b,w){let $;switch(b){case"add_subscriber":{let W=w.companyId,Q=Aw("add_subscriber",w),q=qb("add_subscriber",w,"status",["active","unsubscribed","bounced"]),G=qb("add_subscriber",w,"optInMode",["default","confirmed","double_opt_in"]);if($=await z("POST","/api/v1/subscribers",{...Q,...w.firstName!==void 0&&{firstName:w.firstName},...w.lastName!==void 0&&{lastName:w.lastName},customAttributes:w.attributes,tags:w.tags,lists:w.listIds,...q!==void 0&&{status:q},...G!==void 0&&{optInMode:G}},W),q!==void 0&&k($)&&k($.subscriber)&&$.subscriber.skipped===!0&&$.subscriber.status!==q)throw Error(`Existing subscriber was not changed to status '${q}'. Use update_subscriber to change an existing contact's status.`);break}case"create_subscriber_import":{let W=w.companyId;if(!Array.isArray(w.subscribers)||w.subscribers.length===0)throw Error("`subscribers` must be a non-empty array when calling `create_subscriber_import`.");if(w.subscribers.length>5000)throw Error("`create_subscriber_import` accepts at most 5000 subscriber records per call.");for(let G=0;G<w.subscribers.length;G+=1){let X=w.subscribers[G];if(!k(X)||typeof X.email!=="string"||X.email.trim()==="")throw Error(`Subscriber record ${G} must include a non-empty email string.`)}let Q=qb("create_subscriber_import",w,"duplicateStrategy",["skip","merge","overwrite"]),q=qb("create_subscriber_import",w,"optInMode",["default","confirmed","double_opt_in"]);$=await z("POST","/api/v1/subscribers/imports",{subscribers:w.subscribers,...Q!==void 0&&{duplicateStrategy:Q},...w.fileName!==void 0&&{fileName:w.fileName},...w.listIds!==void 0&&{listIds:w.listIds},...w.enrollInSequences!==void 0&&{enrollInSequences:w.enrollInSequences},...w.defaultPhoneCountry!==void 0&&{defaultPhoneCountry:w.defaultPhoneCountry},...w.smsConsent!==void 0&&{smsConsent:w.smsConsent},...q!==void 0&&{optInMode:q}},W);break}case"get_subscriber_import":{let W=w.companyId,Q=M("get_subscriber_import",w,"importId");$=await z("GET",`/api/v1/subscribers/imports/${encodeURIComponent(Q)}`,void 0,W);break}case"update_subscriber":{let W=w.companyId,Q=Aw("update_subscriber",w),q=qb("update_subscriber",w,"status",["active","unsubscribed","bounced"]),X=k(w.attributes)||w.addTags!==void 0||w.removeTags!==void 0?await H0(Q,W):null,Y=Array.isArray(X?.subscriber.tags)?X.subscriber.tags.filter((A)=>typeof A==="string"):[],J=Array.isArray(w.addTags)?w.addTags.filter((A)=>typeof A==="string"&&A.trim()!=="").map(TW):[],D=new Set(Array.isArray(w.removeTags)?w.removeTags.filter((A)=>typeof A==="string"&&A.trim()!=="").map(TW):[]),H=Y.filter((A)=>!D.has(A));for(let A of J)if(!H.includes(A))H.push(A);let O={};if(Q.email&&Q.externalId)O.externalId=Q.externalId;if(w.firstName!==void 0)O.firstName=w.firstName;if(w.lastName!==void 0)O.lastName=w.lastName;if(q!==void 0)O.status=q;if(k(w.attributes))O.customAttributes={...k(X?.subscriber.customAttributes)?X.subscriber.customAttributes:{},...w.attributes};if(w.addTags||w.removeTags)O.tags=H;$=await z("PATCH",p$(Q),O,W);break}case"remove_subscriber":{let W=w.companyId,Q=Aw("remove_subscriber",w),q=p$(Q);if(w.hardDelete===!0)$=await z("DELETE",q,void 0,W);else $=await z("PATCH",q,{status:"unsubscribed"},W);break}case"get_subscriber":{let W=w.companyId,Q=Aw("get_subscriber",w);$=await H0(Q,W,{includeMachineEngagement:w.includeMachineEngagement===!0});break}case"list_subscriber_notes":{let W=w.companyId,Q=Aw("list_subscriber_notes",w);$=await z("GET",SW(Q),void 0,W);break}case"add_subscriber_note":{let W=w.companyId,Q=Aw("add_subscriber_note",w),q=typeof w.body==="string"?w.body.trim():void 0;if(!q)throw Error("`body` is required when calling `add_subscriber_note`.");if(q.length>5000)throw Error("`body` must be 5000 characters or fewer when calling `add_subscriber_note`.");$=await z("POST",SW(Q),{body:q},W);break}case"delete_subscriber_note":{let W=w.companyId,Q=typeof w.noteId==="string"?w.noteId.trim():"";if(!Q)throw Error("`noteId` is required when calling `delete_subscriber_note`.");$=await z("DELETE",`/api/v1/subscribers/notes/${encodeURIComponent(Q)}`,void 0,W);break}case"search_subscribers":{let W=w.companyId;$=await wH(w,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function tH(b,w){if(b!=="get_recipient_suppression"&&b!=="remove_recipient_suppression")return{handled:!1,result:void 0};let $=L(w,"companyId"),W=M(b,w,"email"),Q=L(w,"region"),q=new URLSearchParams;if(Q)q.set("region",Q);let G=`/api/v1/suppressions/${encodeURIComponent(W)}${q.size>0?`?${q}`:""}`;return{handled:!0,result:await z(b==="get_recipient_suppression"?"GET":"DELETE",G,void 0,$)}}async function rH(b,w){let $;switch(b){case"list_team_members":{let W=w.companyId;$=await z("GET","/api/v1/team",void 0,W);break}case"invite_team_member":{let W=w.companyId,Q=M("invite_team_member",w,"email"),q=z0("invite_team_member",w,"role",["admin","viewer","restricted"]);if(w.canManageBilling!==void 0&&typeof w.canManageBilling!=="boolean")throw Error("`canManageBilling` must be a boolean when calling `invite_team_member`.");$=await z("POST","/api/v1/team/invitations",{email:Q,role:q,...w.canManageBilling!==void 0&&{canManageBilling:w.canManageBilling}},W);break}case"cancel_team_invitation":{let W=w.companyId,Q=M("cancel_team_invitation",w,"invitationId");$=await z("DELETE",`/api/v1/team/invitations/${encodeURIComponent(Q)}`,void 0,W);break}case"list_conversations":{let W=w.companyId,Q=new URLSearchParams,q=qb("list_conversations",w,"status",["open","closed","all"]);if(q)Q.set("status",q);let G=L(w,"search");if(G)Q.set("search",G);if(w.unread!==void 0){if(typeof w.unread!=="boolean")throw Error("`unread` must be a boolean when calling `list_conversations`.");if(w.unread)Q.set("unread","true")}if(w.page!==void 0){if(typeof w.page!=="number"||!Number.isInteger(w.page)||w.page<1)throw Error("`page` must be a positive integer when calling `list_conversations`.");Q.set("page",String(w.page))}let X=ab("list_conversations",w,"limit",1,100);if(X!==void 0)Q.set("limit",String(X));$=await z("GET",`/api/v1/conversations${Q.size>0?`?${Q}`:""}`,void 0,W);break}case"get_conversation":{let W=w.companyId,Q=M("get_conversation",w,"conversationId");$=await z("GET",`/api/v1/conversations/${encodeURIComponent(Q)}`,void 0,W);break}case"reply_to_conversation":{let W=w.companyId,Q=M("reply_to_conversation",w,"conversationId"),q=qb("reply_to_conversation",w,"type",["outbound","note"])??"outbound",G=L(w,"subject"),X=L(w,"bodyText"),Y=L(w,"bodyHtml");if(q==="outbound"&&X===void 0&&Y===void 0)throw Error("Provide `bodyText` or `bodyHtml` when calling `reply_to_conversation` with an outbound message.");$=await z("POST",`/api/v1/conversations/${encodeURIComponent(Q)}/messages`,{type:q,...G!==void 0&&{subject:G},...X!==void 0&&{bodyText:X},...Y!==void 0&&{bodyHtml:Y}},W);break}case"update_conversation_status":{let W=w.companyId,Q=M("update_conversation_status",w,"conversationId"),q=z0("update_conversation_status",w,"status",["open","closed"]);$=await z("POST",`/api/v1/conversations/${encodeURIComponent(Q)}/status`,{status:q},W);break}case"mark_conversation_read":{let W=w.companyId,Q=M("mark_conversation_read",w,"conversationId");$=await z("POST",`/api/v1/conversations/${encodeURIComponent(Q)}/read`,void 0,W);break}case"list_webhooks":{let W=w.companyId;$=await z("GET","/api/v1/webhooks",void 0,W);break}case"create_webhook":{let W=w.companyId,Q=M("create_webhook",w,"name"),q=M("create_webhook",w,"url"),G=vW("create_webhook",w);$=await z("POST","/api/v1/webhooks",{name:Q,url:q,...G!==void 0&&{events:G}},W);break}case"update_webhook":{let W=w.companyId,Q=M("update_webhook",w,"webhookId"),q=L(w,"name"),G=L(w,"url"),X=vW("update_webhook",w),Y=qb("update_webhook",w,"status",["enabled","disabled"]);if(q===void 0&&G===void 0&&X===void 0&&Y===void 0)throw Error("Provide at least one of `name`, `url`, `events`, or `status` when calling `update_webhook`.");$=await z("PATCH",`/api/v1/webhooks/${encodeURIComponent(Q)}`,{...q!==void 0&&{name:q},...G!==void 0&&{url:G},...X!==void 0&&{events:X},...Y!==void 0&&{status:Y}},W);break}case"delete_webhook":{let W=w.companyId,Q=M("delete_webhook",w,"webhookId");$=await z("DELETE",`/api/v1/webhooks/${encodeURIComponent(Q)}`,void 0,W);break}case"test_webhook":{let W=w.companyId,Q=M("test_webhook",w,"webhookId");$=await z("POST",`/api/v1/webhooks/${encodeURIComponent(Q)}/test`,void 0,W);break}case"list_webhook_deliveries":{let W=w.companyId,Q=M("list_webhook_deliveries",w,"webhookId"),q=ab("list_webhook_deliveries",w,"limit",1,100),G=new URLSearchParams;if(q!==void 0)G.set("limit",String(q));$=await z("GET",`/api/v1/webhooks/${encodeURIComponent(Q)}/deliveries${G.size>0?`?${G}`:""}`,void 0,W);break}case"replay_webhook_delivery":{let W=w.companyId,Q=M("replay_webhook_delivery",w,"webhookId"),q=M("replay_webhook_delivery",w,"deliveryId");$=await z("POST",`/api/v1/webhooks/${encodeURIComponent(Q)}/deliveries/${encodeURIComponent(q)}/replay`,void 0,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}var eH=[hH,dH,tH,pH,nH,iH,mH,gH,lH,hW,fH,rH,cH];var eM=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 sH(b){return typeof b==="object"&&b!==null&&!Array.isArray(b)}function cW(b){if(Array.isArray(b))return b.some(cW);if(!sH(b))return!1;for(let[w,$]of Object.entries(b)){if((w==="html"||w==="htmlContent")&&typeof $==="string"&&$.trim().length>0)return!0;if(cW($))return!0}return!1}function aH(b,w,$){if(!eM.has(b)||!cW(w)||!sH($))return $;let W=Array.isArray($.warnings)?$.warnings.filter((Q)=>typeof Q==="string"):[];return{...$,warnings:[...new Set([...W,Gb])]}}var bz=yH.map(DH).map(RD);async function wz(b,w){try{let $,W=!1;for(let q of eH){let G=await q(b,w);if(G.handled){$=G.result,W=!0;break}}if(!W)throw Error(`Unknown tool: ${b}`);let Q=aD($);if(Q)throw Q;return $=aH(b,w,$),$=await qH(b,w,$),{structuredContent:HH($),content:[{type:"text",text:JSON.stringify($,null,2)}]}}catch($){return{isError:!0,content:[{type:"text",text:Lw($)}]}}}async function $z(b,w,$){let W=w.getRequestContext?.(b)??{};try{return await w4(W,$)}finally{await w.onRequestContextUpdated?.(W,b)}}function fW(b={}){let w=new OW({name:"sequenzy",version:ZD.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(`
|
|
52
|
+
`)});return w.setRequestHandler(b6,async()=>{return{tools:bz}}),w.setRequestHandler(x1,async($,W)=>{let{name:Q,arguments:q}=$.params;return $z(W,b,()=>wz(Q,q??{}))}),w.setRequestHandler(o4,async()=>{return{resources:ED}}),w.setRequestHandler(t4,async($,W)=>{let{uri:Q}=$.params;return $z(W,b,()=>TD(Q))}),w}import Qz from"node:process";class nW{append(b){this._buffer=this._buffer?Buffer.concat([this._buffer,b]):b}readMessage(){if(!this._buffer)return null;let b=this._buffer.indexOf(`
|
|
53
|
+
`);if(b===-1)return null;let w=this._buffer.toString("utf8",0,b).replace(/\r$/,"");return this._buffer=this._buffer.subarray(b+1),sM(w)}clear(){this._buffer=void 0}}function sM(b){return Cq.parse(JSON.parse(b))}function Wz(b){return JSON.stringify(b)+`
|
|
54
|
+
`}class iW{constructor(b=Qz.stdin,w=Qz.stdout){this._stdin=b,this._stdout=w,this._readBuffer=new nW,this._started=!1,this._ondata=($)=>{this._readBuffer.append($),this.processReadBuffer()},this._onerror=($)=>{this.onerror?.($)}}async start(){if(this._started)throw Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){while(!0)try{let b=this._readBuffer.readMessage();if(b===null)break;this.onmessage?.(b)}catch(b){this.onerror?.(b)}}async close(){if(this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0)this._stdin.pause();this._readBuffer.clear(),this.onclose?.()}send(b){return new Promise((w)=>{let $=Wz(b);if(this._stdout.write($))w();else this._stdout.once("drain",w)})}}async function aM(){aW(),dW();let b=fW(),w=new iW;await b.connect(w),console.error("Sequenzy MCP server running on stdio")}aM().catch((b)=>{console.error(Lw(b)),process.exit(1)});export{w4 as withMcpRequestContext,L0 as setSelectedCompanyId,Uw as getSelectedCompanyId,fW as createSequenzyMcpServer,z as apiRequest};
|