@sequenzy/mcp 0.0.116 → 0.0.117

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,15 +1,15 @@
1
1
  #!/usr/bin/env node
2
- var iz=Object.create;var{getPrototypeOf:lz,defineProperty:t$,getOwnPropertyNames:pz}=Object;var oz=Object.prototype.hasOwnProperty;function dz(b){return this[b]}var tz,rz,uW=(b,w,$)=>{var W=b!=null&&typeof b==="object";if(W){var Q=w?tz??=new WeakMap:rz??=new WeakMap,G=Q.get(b);if(G)return G}$=b!=null?iz(lz(b)):{};let D=w||!b||!b.__esModule?t$($,"default",{value:b,enumerable:!0}):$;for(let X of pz(b))if(!oz.call(D,X))t$(D,X,{get:dz.bind(b,X),enumerable:!0});if(W)Q.set(b,D);return D};var j=(b,w)=>()=>(w||b((w={exports:{}}).exports,w),w.exports);var ez=(b)=>b;function sz(b,w){this[b]=ez.bind(null,w)}var xW=(b,w)=>{for(var $ in w)t$(b,$,{get:w[$],enumerable:!0,configurable:!0,set:sz.bind(w,$)})};var h1=j((yG)=>{Object.defineProperty(yG,"__esModule",{value:!0});yG.regexpCode=yG.getEsmExportName=yG.getProperty=yG.safeStringify=yG.stringify=yG.strConcat=yG.addCodeArg=yG.str=yG._=yG.nil=yG._Code=yG.Name=yG.IDENTIFIER=yG._CodeOrName=void 0;class t0{}yG._CodeOrName=t0;yG.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class pw extends t0{constructor(b){super();if(!yG.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}}}yG.Name=pw;class hb extends t0{constructor(b){super();this._items=typeof b==="string"?[b]:b}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let b=this._items[0];return b===""||b==='""'}get str(){var b;return(b=this._str)!==null&&b!==void 0?b:this._str=this._items.reduce((w,$)=>`${w}${$}`,"")}get names(){var b;return(b=this._names)!==null&&b!==void 0?b:this._names=this._items.reduce((w,$)=>{if($ instanceof pw)w[$.str]=(w[$.str]||0)+1;return w},{})}}yG._Code=hb;yG.nil=new hb("");function uG(b,...w){let $=[b[0]],W=0;while(W<w.length)Q4($,w[W]),$.push(b[++W]);return new hb($)}yG._=uG;var W4=new hb("+");function xG(b,...w){let $=[y1(b[0])],W=0;while(W<w.length)$.push(W4),Q4($,w[W]),$.push(W4,y1(b[++W]));return KO($),new hb($)}yG.str=xG;function Q4(b,w){if(w instanceof hb)b.push(...w._items);else if(w instanceof pw)b.push(w);else b.push(ZO(w))}yG.addCodeArg=Q4;function KO(b){let w=1;while(w<b.length-1){if(b[w]===W4){let $=MO(b[w-1],b[w+1]);if($!==void 0){b.splice(w-1,3,$);continue}b[w++]="+"}w++}}function MO(b,w){if(w==='""')return b;if(b==='""')return w;if(typeof b=="string"){if(w instanceof pw||b[b.length-1]!=='"')return;if(typeof w!="string")return`${b.slice(0,-1)}${w}"`;if(w[0]==='"')return b.slice(0,-1)+w.slice(1);return}if(typeof w=="string"&&w[0]==='"'&&!(b instanceof pw))return`"${b}${w.slice(1)}`;return}function IO(b,w){return w.emptyStr()?b:b.emptyStr()?w:xG`${b}${w}`}yG.strConcat=IO;function ZO(b){return typeof b=="number"||typeof b=="boolean"||b===null?b:y1(Array.isArray(b)?b.join(","):b)}function jO(b){return new hb(y1(b))}yG.stringify=jO;function y1(b){return JSON.stringify(b).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}yG.safeStringify=y1;function VO(b){return typeof b=="string"&&yG.IDENTIFIER.test(b)?new hb(`.${b}`):uG`[${b}]`}yG.getProperty=VO;function NO(b){if(typeof b=="string"&&yG.IDENTIFIER.test(b))return new hb(`${b}`);throw Error(`CodeGen: invalid export name: ${b}, use explicit $id name mapping`)}yG.getEsmExportName=NO;function TO(b){return new hb(b.toString())}yG.regexpCode=TO});var Y4=j((nG)=>{Object.defineProperty(nG,"__esModule",{value:!0});nG.ValueScope=nG.ValueScopeName=nG.Scope=nG.varKinds=nG.UsedValueState=void 0;var Ib=h1();class fG extends Error{constructor(b){super(`CodeGen: "code" for ${b} not defined`);this.value=b.value}}var e0;(function(b){b[b.Started=0]="Started",b[b.Completed=1]="Completed"})(e0||(nG.UsedValueState=e0={}));nG.varKinds={const:new Ib.Name("const"),let:new Ib.Name("let"),var:new Ib.Name("var")};class D4{constructor({prefixes:b,parent:w}={}){this._names={},this._prefixes=b,this._parent=w}toName(b){return b instanceof Ib.Name?b:this.name(b)}name(b){return new Ib.Name(this._newName(b))}_newName(b){let w=this._names[b]||this._nameGroup(b);return`${b}${w.index++}`}_nameGroup(b){var w,$;if((($=(w=this._parent)===null||w===void 0?void 0:w._prefixes)===null||$===void 0?void 0:$.has(b))||this._prefixes&&!this._prefixes.has(b))throw Error(`CodeGen: prefix "${b}" is not allowed in this scope`);return this._names[b]={prefix:b,index:0}}}nG.Scope=D4;class X4 extends Ib.Name{constructor(b,w){super(w);this.prefix=b}setValue(b,{property:w,itemIndex:$}){this.value=b,this.scopePath=Ib._`.${new Ib.Name(w)}[${$}]`}}nG.ValueScopeName=X4;var cO=Ib._`\n`;class cG extends D4{constructor(b){super(b);this._values={},this._scope=b.scope,this.opts={...b,_n:b.lines?cO:Ib.nil}}get(){return this._scope}name(b){return new X4(b,this._newName(b))}value(b,w){var $;if(w.ref===void 0)throw Error("CodeGen: ref must be passed in value");let W=this.toName(b),{prefix:Q}=W,G=($=w.key)!==null&&$!==void 0?$:w.ref,D=this._values[Q];if(D){let H=D.get(G);if(H)return H}else D=this._values[Q]=new Map;D.set(G,W);let X=this._scope[Q]||(this._scope[Q]=[]),Y=X.length;return X[Y]=w.ref,W.setValue(w,{property:Q,itemIndex:Y}),W}getValue(b,w){let $=this._values[b];if(!$)return;return $.get(w)}scopeRefs(b,w=this._values){return this._reduceValues(w,($)=>{if($.scopePath===void 0)throw Error(`CodeGen: name "${$}" has no value`);return Ib._`${b}${$.scopePath}`})}scopeCode(b=this._values,w,$){return this._reduceValues(b,(W)=>{if(W.value===void 0)throw Error(`CodeGen: name "${W}" has no value`);return W.value.code},w,$)}_reduceValues(b,w,$={},W){let Q=Ib.nil;for(let G in b){let D=b[G];if(!D)continue;let X=$[G]=$[G]||new Map;D.forEach((Y)=>{if(X.has(Y))return;X.set(Y,e0.Started);let H=w(Y);if(H){let J=this.opts.es5?nG.varKinds.var:nG.varKinds.const;Q=Ib._`${Q}${J} ${Y} = ${H};${this.opts._n}`}else if(H=W===null||W===void 0?void 0:W(Y))Q=Ib._`${Q}${H}${this.opts._n}`;else throw new fG(Y);X.set(Y,e0.Completed)})}return Q}}nG.ValueScope=cG});var x=j((Zb)=>{Object.defineProperty(Zb,"__esModule",{value:!0});Zb.or=Zb.and=Zb.not=Zb.CodeGen=Zb.operators=Zb.varKinds=Zb.ValueScopeName=Zb.ValueScope=Zb.Scope=Zb.Name=Zb.regexpCode=Zb.stringify=Zb.getProperty=Zb.nil=Zb.strConcat=Zb.str=Zb._=void 0;var n=h1(),fb=Y4(),Iw=h1();Object.defineProperty(Zb,"_",{enumerable:!0,get:function(){return Iw._}});Object.defineProperty(Zb,"str",{enumerable:!0,get:function(){return Iw.str}});Object.defineProperty(Zb,"strConcat",{enumerable:!0,get:function(){return Iw.strConcat}});Object.defineProperty(Zb,"nil",{enumerable:!0,get:function(){return Iw.nil}});Object.defineProperty(Zb,"getProperty",{enumerable:!0,get:function(){return Iw.getProperty}});Object.defineProperty(Zb,"stringify",{enumerable:!0,get:function(){return Iw.stringify}});Object.defineProperty(Zb,"regexpCode",{enumerable:!0,get:function(){return Iw.regexpCode}});Object.defineProperty(Zb,"Name",{enumerable:!0,get:function(){return Iw.Name}});var W$=Y4();Object.defineProperty(Zb,"Scope",{enumerable:!0,get:function(){return W$.Scope}});Object.defineProperty(Zb,"ValueScope",{enumerable:!0,get:function(){return W$.ValueScope}});Object.defineProperty(Zb,"ValueScopeName",{enumerable:!0,get:function(){return W$.ValueScopeName}});Object.defineProperty(Zb,"varKinds",{enumerable:!0,get:function(){return W$.varKinds}});Zb.operators={GT:new 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 mG 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=dw(this.rhs,b,w);return this}get names(){return this.rhs instanceof n._CodeOrName?this.rhs.names:{}}}class z4 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=dw(this.rhs,b,w),this}get names(){let b=this.lhs instanceof n.Name?{}:{...this.lhs.names};return $$(b,this.rhs)}}class iG extends z4{constructor(b,w,$,W){super(b,$,W);this.op=w}render({_n:b}){return`${this.lhs} ${this.op}= ${this.rhs};`+b}}class lG extends Zw{constructor(b){super();this.label=b,this.names={}}render({_n:b}){return`${this.label}:`+b}}class pG extends Zw{constructor(b){super();this.label=b,this.names={}}render({_n:b}){return`break${this.label?` ${this.label}`:""};`+b}}class oG extends Zw{constructor(b){super();this.error=b}render({_n:b}){return`throw ${this.error};`+b}get names(){return this.error.names}}class dG extends Zw{constructor(b){super();this.code=b}render({_n:b}){return`${this.code};`+b}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(b,w){return this.code=dw(this.code,b,w),this}get names(){return this.code instanceof n._CodeOrName?this.code.names:{}}}class Q$ extends Zw{constructor(b=[]){super();this.nodes=b}render(b){return this.nodes.reduce((w,$)=>w+$.render(b),"")}optimizeNodes(){let{nodes:b}=this,w=b.length;while(w--){let $=b[w].optimizeNodes();if(Array.isArray($))b.splice(w,1,...$);else if($)b[w]=$;else b.splice(w,1)}return b.length>0?this:void 0}optimizeNames(b,w){let{nodes:$}=this,W=$.length;while(W--){let Q=$[W];if(Q.optimizeNames(b,w))continue;iO(b,Q.names),$.splice(W,1)}return $.length>0?this:void 0}get names(){return this.nodes.reduce((b,w)=>vw(b,w.names),{})}}class jw extends Q${render(b){return"{"+b._n+super.render(b)+"}"+b._n}}class tG extends Q${}class f1 extends jw{}f1.kind="else";class Ww extends jw{constructor(b,w){super(w);this.condition=b}render(b){let w=`if(${this.condition})`+super.render(b);if(this.else)w+="else "+this.else.render(b);return w}optimizeNodes(){super.optimizeNodes();let b=this.condition;if(b===!0)return this.nodes;let w=this.else;if(w){let $=w.optimizeNodes();w=this.else=Array.isArray($)?new f1($):$}if(w){if(b===!1)return w instanceof Ww?w:w.nodes;if(this.nodes.length)return this;return new Ww(bD(b),w instanceof Ww?[w]:w.nodes)}if(b===!1||!this.nodes.length)return;return this}optimizeNames(b,w){var $;if(this.else=($=this.else)===null||$===void 0?void 0:$.optimizeNames(b,w),!(super.optimizeNames(b,w)||this.else))return;return this.condition=dw(this.condition,b,w),this}get names(){let b=super.names;if($$(b,this.condition),this.else)vw(b,this.else.names);return b}}Ww.kind="if";class ow extends jw{}ow.kind="for";class rG extends ow{constructor(b){super();this.iteration=b}render(b){return`for(${this.iteration})`+super.render(b)}optimizeNames(b,w){if(!super.optimizeNames(b,w))return;return this.iteration=dw(this.iteration,b,w),this}get names(){return vw(super.names,this.iteration.names)}}class eG extends ow{constructor(b,w,$,W){super();this.varKind=b,this.name=w,this.from=$,this.to=W}render(b){let w=b.es5?fb.varKinds.var:this.varKind,{name:$,from:W,to:Q}=this;return`for(${w} ${$}=${W}; ${$}<${Q}; ${$}++)`+super.render(b)}get names(){let b=$$(super.names,this.from);return $$(b,this.to)}}class H4 extends ow{constructor(b,w,$,W){super();this.loop=b,this.varKind=w,this.name=$,this.iterable=W}render(b){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(b)}optimizeNames(b,w){if(!super.optimizeNames(b,w))return;return this.iterable=dw(this.iterable,b,w),this}get names(){return vw(super.names,this.iterable.names)}}class s0 extends jw{constructor(b,w,$){super();this.name=b,this.args=w,this.async=$}render(b){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(b)}}s0.kind="func";class a0 extends Q${render(b){return"return "+super.render(b)}}a0.kind="return";class sG extends jw{render(b){let w="try"+super.render(b);if(this.catch)w+=this.catch.render(b);if(this.finally)w+=this.finally.render(b);return w}optimizeNodes(){var b,w;return super.optimizeNodes(),(b=this.catch)===null||b===void 0||b.optimizeNodes(),(w=this.finally)===null||w===void 0||w.optimizeNodes(),this}optimizeNames(b,w){var $,W;return super.optimizeNames(b,w),($=this.catch)===null||$===void 0||$.optimizeNames(b,w),(W=this.finally)===null||W===void 0||W.optimizeNames(b,w),this}get names(){let b=super.names;if(this.catch)vw(b,this.catch.names);if(this.finally)vw(b,this.finally.names);return b}}class b$ extends jw{constructor(b){super();this.error=b}render(b){return`catch(${this.error})`+super.render(b)}}b$.kind="catch";class w$ extends jw{render(b){return"finally"+super.render(b)}}w$.kind="finally";class aG{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 tG]}toString(){return this._root.render(this.opts)}name(b){return this._scope.name(b)}scopeName(b){return this._extScope.name(b)}scopeValue(b,w){let $=this._extScope.value(b,w);return(this._values[$.prefix]||(this._values[$.prefix]=new Set)).add($),$}getScopeValue(b,w){return this._extScope.getValue(b,w)}scopeRefs(b){return this._extScope.scopeRefs(b,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(b,w,$,W){let Q=this._scope.toName(w);if($!==void 0&&W)this._constants[Q.str]=$;return this._leafNode(new mG(b,Q,$)),Q}const(b,w,$){return this._def(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 z4(b,w,$))}add(b,w){return this._leafNode(new iG(b,Zb.operators.ADD,w))}code(b){if(typeof b=="function")b();else if(b!==n.nil)this._leafNode(new dG(b));return this}object(...b){let w=["{"];for(let[$,W]of b){if(w.length>1)w.push(",");if(w.push($),$!==W||this.opts.es5)w.push(":"),(0,n.addCodeArg)(w,W)}return w.push("}"),new n._Code(w)}if(b,w,$){if(this._blockNode(new Ww(b)),w&&$)this.code(w).else().code($).endIf();else if(w)this.code(w).endIf();else if($)throw Error('CodeGen: "else" body without "then" body');return this}elseIf(b){return this._elseNode(new Ww(b))}else(){return this._elseNode(new f1)}endIf(){return this._endBlockNode(Ww,f1)}_for(b,w){if(this._blockNode(b),w)this.code(w).endFor();return this}for(b,w){return this._for(new rG(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 eG(Q,G,w,$),()=>W(G))}forOf(b,w,$,W=fb.varKinds.const){let Q=this._scope.toName(b);if(this.opts.es5){let G=w instanceof n.Name?w:this.var("_arr",w);return this.forRange("_i",0,n._`${G}.length`,(D)=>{this.var(Q,n._`${G}[${D}]`),$(Q)})}return this._for(new H4("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 H4("in",W,Q,w),()=>$(Q))}endFor(){return this._endBlockNode(ow)}label(b){return this._leafNode(new lG(b))}break(b){return this._leafNode(new pG(b))}return(b){let w=new a0;if(this._blockNode(w),this.code(b),w.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(a0)}try(b,w,$){if(!w&&!$)throw Error('CodeGen: "try" without "catch" and "finally"');let W=new sG;if(this._blockNode(W),this.code(b),w){let Q=this.name("e");this._currNode=W.catch=new b$(Q),w(Q)}if($)this._currNode=W.finally=new w$,this.code($);return this._endBlockNode(b$,w$)}throw(b){return this._leafNode(new oG(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 s0(b,w,$)),W)this.code(W).endFunc();return this}endFunc(){return this._endBlockNode(s0)}optimize(b=1){while(b-- >0)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(b){return this._currNode.nodes.push(b),this}_blockNode(b){this._currNode.nodes.push(b),this._nodes.push(b)}_endBlockNode(b,w){let $=this._currNode;if($ instanceof b||w&&$ instanceof w)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${w?`${b.kind}/${w.kind}`:b.kind}"`)}_elseNode(b){let w=this._currNode;if(!(w instanceof Ww))throw Error('CodeGen: "else" without "if"');return this._currNode=w.else=b,this}get _root(){return this._nodes[0]}get _currNode(){let b=this._nodes;return b[b.length-1]}set _currNode(b){let w=this._nodes;w[w.length-1]=b}}Zb.CodeGen=aG;function vw(b,w){for(let $ in w)b[$]=(b[$]||0)+(w[$]||0);return b}function $$(b,w){return w instanceof n._CodeOrName?vw(b,w.names):b}function dw(b,w,$){if(b instanceof n.Name)return W(b);if(!Q(b))return b;return new n._Code(b._items.reduce((G,D)=>{if(D instanceof n.Name)D=W(D);if(D instanceof n._Code)G.push(...D._items);else G.push(D);return G},[]));function W(G){let D=$[G.str];if(D===void 0||w[G.str]!==1)return G;return delete w[G.str],D}function Q(G){return G instanceof n._Code&&G._items.some((D)=>D instanceof n.Name&&w[D.str]===1&&$[D.str]!==void 0)}}function iO(b,w){for(let $ in w)b[$]=(b[$]||0)-(w[$]||0)}function bD(b){return typeof b=="boolean"||typeof b=="number"||b===null?!b:n._`!${J4(b)}`}Zb.not=bD;var lO=wD(Zb.operators.AND);function pO(...b){return b.reduce(lO)}Zb.and=pO;var oO=wD(Zb.operators.OR);function dO(...b){return b.reduce(oO)}Zb.or=dO;function wD(b){return(w,$)=>w===n.nil?$:$===n.nil?w:n._`${J4(w)} ${b} ${J4($)}`}function J4(b){return b instanceof n.Name?b:n._`(${b})`}});var i=j((JD)=>{Object.defineProperty(JD,"__esModule",{value:!0});JD.checkStrictMode=JD.getErrorPath=JD.Type=JD.useFunc=JD.setEvaluated=JD.evaluatedPropsToName=JD.mergeEvaluated=JD.eachItem=JD.unescapeJsonPointer=JD.escapeJsonPointer=JD.escapeFragment=JD.unescapeFragment=JD.schemaRefOrVal=JD.schemaHasRulesButRef=JD.schemaHasRules=JD.checkUnknownRules=JD.alwaysValidSchema=JD.toHash=void 0;var t=x(),sO=h1();function aO(b){let w={};for(let $ of b)w[$]=!0;return w}JD.toHash=aO;function bq(b,w){if(typeof w=="boolean")return w;if(Object.keys(w).length===0)return!0;return GD(b,w),!DD(w,b.self.RULES.all)}JD.alwaysValidSchema=bq;function GD(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])HD(b,`unknown keyword: "${G}"`)}JD.checkUnknownRules=GD;function DD(b,w){if(typeof b=="boolean")return!b;for(let $ in b)if(w[$])return!0;return!1}JD.schemaHasRules=DD;function wq(b,w){if(typeof b=="boolean")return!b;for(let $ in b)if($!=="$ref"&&w.all[$])return!0;return!1}JD.schemaHasRulesButRef=wq;function $q({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)}`}JD.schemaRefOrVal=$q;function Wq(b){return XD(decodeURIComponent(b))}JD.unescapeFragment=Wq;function Qq(b){return encodeURIComponent(O4(b))}JD.escapeFragment=Qq;function O4(b){if(typeof b=="number")return`${b}`;return b.replace(/~/g,"~0").replace(/\//g,"~1")}JD.escapeJsonPointer=O4;function XD(b){return b.replace(/~1/g,"/").replace(/~0/g,"~")}JD.unescapeJsonPointer=XD;function Gq(b,w){if(Array.isArray(b))for(let $ of b)w($);else w(b)}JD.eachItem=Gq;function WD({mergeNames:b,mergeToName:w,mergeValues:$,resultToName:W}){return(Q,G,D,X)=>{let Y=D===void 0?G:D instanceof t.Name?(G instanceof t.Name?b(Q,G,D):w(Q,G,D),D):G instanceof t.Name?(w(Q,D,G),G):$(G,D);return X===t.Name&&!(Y instanceof t.Name)?W(Q,Y):Y}}JD.mergeEvaluated={props:WD({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._`${$} || {}`),q4(b,$,w)}),mergeValues:(b,w)=>b===!0?!0:{...b,...w},resultToName:YD}),items:WD({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 YD(b,w){if(w===!0)return b.var("props",!0);let $=b.var("props",t._`{}`);if(w!==void 0)q4(b,$,w);return $}JD.evaluatedPropsToName=YD;function q4(b,w,$){Object.keys($).forEach((W)=>b.assign(t._`${w}${(0,t.getProperty)(W)}`,!0))}JD.setEvaluated=q4;var QD={};function Dq(b,w){return b.scopeValue("func",{ref:w,code:QD[w.code]||(QD[w.code]=new sO._Code(w.code))})}JD.useFunc=Dq;var A4;(function(b){b[b.Num=0]="Num",b[b.Str=1]="Str"})(A4||(JD.Type=A4={}));function Xq(b,w,$){if(b instanceof t.Name){let W=w===A4.Num;return $?W?t._`"[" + ${b} + "]"`:t._`"['" + ${b} + "']"`:W?t._`"/" + ${b}`:t._`"/" + ${b}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return $?(0,t.getProperty)(b).toString():"/"+O4(b)}JD.getErrorPath=Xq;function HD(b,w,$=b.opts.strictSchema){if(!$)return;if(w=`strict mode: ${w}`,$===!0)throw Error(w);b.self.logger.warn(w)}JD.checkStrictMode=HD});var Qw=j((AD)=>{Object.defineProperty(AD,"__esModule",{value:!0});var Lb=x(),Vq={data:new Lb.Name("data"),valCxt:new Lb.Name("valCxt"),instancePath:new Lb.Name("instancePath"),parentData:new Lb.Name("parentData"),parentDataProperty:new Lb.Name("parentDataProperty"),rootData:new Lb.Name("rootData"),dynamicAnchors:new Lb.Name("dynamicAnchors"),vErrors:new Lb.Name("vErrors"),errors:new Lb.Name("errors"),this:new Lb.Name("this"),self:new Lb.Name("self"),scope:new Lb.Name("scope"),json:new Lb.Name("json"),jsonPos:new Lb.Name("jsonPos"),jsonLen:new Lb.Name("jsonLen"),jsonPart:new Lb.Name("jsonPart")};AD.default=Vq});var c1=j((UD)=>{Object.defineProperty(UD,"__esModule",{value:!0});UD.extendErrors=UD.resetErrorsCount=UD.reportExtraError=UD.reportError=UD.keyword$DataError=UD.keywordError=void 0;var g=x(),D$=i(),Pb=Qw();UD.keywordError={message:({keyword:b})=>g.str`must pass "${b}" keyword validation`};UD.keyword$DataError={message:({keyword:b,schemaType:w})=>w?g.str`"${b}" keyword must be ${w} ($data)`:g.str`"${b}" keyword is invalid ($data)`};function Tq(b,w=UD.keywordError,$,W){let{it:Q}=b,{gen:G,compositeRule:D,allErrors:X}=Q,Y=LD(b,w,$);if(W!==null&&W!==void 0?W:D||X)OD(G,Y);else qD(Q,g._`[${Y}]`)}UD.reportError=Tq;function Eq(b,w=UD.keywordError,$){let{it:W}=b,{gen:Q,compositeRule:G,allErrors:D}=W,X=LD(b,w,$);if(OD(Q,X),!(G||D))qD(W,Pb.default.vErrors)}UD.reportExtraError=Eq;function _q(b,w){b.assign(Pb.default.errors,w),b.if(g._`${Pb.default.vErrors} !== null`,()=>b.if(w,()=>b.assign(g._`${Pb.default.vErrors}.length`,w),()=>b.assign(Pb.default.vErrors,null)))}UD.resetErrorsCount=_q;function Sq({gen:b,keyword:w,schemaValue:$,data:W,errsCount:Q,it:G}){if(Q===void 0)throw Error("ajv implementation error");let D=b.name("err");b.forRange("i",Q,Pb.default.errors,(X)=>{if(b.const(D,g._`${Pb.default.vErrors}[${X}]`),b.if(g._`${D}.instancePath === undefined`,()=>b.assign(g._`${D}.instancePath`,(0,g.strConcat)(Pb.default.instancePath,G.errorPath))),b.assign(g._`${D}.schemaPath`,g.str`${G.errSchemaPath}/${w}`),G.opts.verbose)b.assign(g._`${D}.schema`,$),b.assign(g._`${D}.data`,W)})}UD.extendErrors=Sq;function OD(b,w){let $=b.const("err",w);b.if(g._`${Pb.default.vErrors} === null`,()=>b.assign(Pb.default.vErrors,g._`[${$}]`),g._`${Pb.default.vErrors}.push(${$})`),b.code(g._`${Pb.default.errors}++`)}function qD(b,w){let{gen:$,validateName:W,schemaEnv:Q}=b;if(Q.$async)$.throw(g._`new ${b.ValidationError}(${w})`);else $.assign(g._`${W}.errors`,w),$.return(!1)}var kw={keyword:new g.Name("keyword"),schemaPath:new g.Name("schemaPath"),params:new g.Name("params"),propertyName:new g.Name("propertyName"),message:new g.Name("message"),schema:new g.Name("schema"),parentSchema:new g.Name("parentSchema")};function LD(b,w,$){let{createErrors:W}=b.it;if(W===!1)return g._`{}`;return Rq(b,w,$)}function Rq(b,w,$={}){let{gen:W,it:Q}=b,G=[vq(Q,$),kq(b,$)];return Cq(b,w,G),W.object(...G)}function vq({errorPath:b},{instancePath:w}){let $=w?g.str`${b}${(0,D$.getErrorPath)(w,D$.Type.Str)}`:b;return[Pb.default.instancePath,(0,g.strConcat)(Pb.default.instancePath,$)]}function kq({keyword:b,it:{errSchemaPath:w}},{schemaPath:$,parentSchema:W}){let Q=W?w:g.str`${w}/${b}`;if($)Q=g.str`${Q}${(0,D$.getErrorPath)($,D$.Type.Str)}`;return[kw.schemaPath,Q]}function Cq(b,{params:w,message:$},W){let{keyword:Q,data:G,schemaValue:D,it:X}=b,{opts:Y,propertyName:H,topSchemaRef:J,schemaPath:z}=X;if(W.push([kw.keyword,Q],[kw.params,typeof w=="function"?w(b):w||g._`{}`]),Y.messages)W.push([kw.message,typeof $=="function"?$(b):$]);if(Y.verbose)W.push([kw.schema,D],[kw.parentSchema,g._`${J}${z}`],[Pb.default.data,G]);if(H)W.push([kw.propertyName,H])}});var MD=j((FD)=>{Object.defineProperty(FD,"__esModule",{value:!0});FD.boolOrEmptySchema=FD.topBoolOrEmptySchema=void 0;var fq=c1(),cq=x(),nq=Qw(),gq={message:"boolean schema is false"};function mq(b){let{gen:w,schema:$,validateName:W}=b;if($===!1)PD(b,!1);else if(typeof $=="object"&&$.$async===!0)w.return(nq.default.data);else w.assign(cq._`${W}.errors`,null),w.return(!0)}FD.topBoolOrEmptySchema=mq;function iq(b,w){let{gen:$,schema:W}=b;if(W===!1)$.var(w,!1),PD(b);else $.var(w,!0)}FD.boolOrEmptySchema=iq;function PD(b,w){let{gen:$,data:W}=b,Q={gen:$,keyword:"false schema",data:W,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:b};(0,fq.reportError)(Q,gq,void 0,w)}});var U4=j((ID)=>{Object.defineProperty(ID,"__esModule",{value:!0});ID.getRules=ID.isJSONType=void 0;var pq=["string","number","integer","boolean","null","object","array"],oq=new Set(pq);function dq(b){return typeof b=="string"&&oq.has(b)}ID.isJSONType=dq;function tq(){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:{}}}ID.getRules=tq});var B4=j((ND)=>{Object.defineProperty(ND,"__esModule",{value:!0});ND.shouldUseRule=ND.shouldUseGroup=ND.schemaHasRulesForType=void 0;function eq({schema:b,self:w},$){let W=w.RULES.types[$];return W&&W!==!0&&jD(b,W)}ND.schemaHasRulesForType=eq;function jD(b,w){return w.rules.some(($)=>VD(b,$))}ND.shouldUseGroup=jD;function VD(b,w){var $;return b[w.keyword]!==void 0||(($=w.definition.implements)===null||$===void 0?void 0:$.some((W)=>b[W]!==void 0))}ND.shouldUseRule=VD});var n1=j((RD)=>{Object.defineProperty(RD,"__esModule",{value:!0});RD.reportTypeError=RD.checkDataTypes=RD.checkDataType=RD.coerceAndCheckDataType=RD.getJSONTypes=RD.getSchemaTypes=RD.DataType=void 0;var bL=U4(),wL=B4(),$L=c1(),C=x(),ED=i(),tw;(function(b){b[b.Correct=0]="Correct",b[b.Wrong=1]="Wrong"})(tw||(RD.DataType=tw={}));function WL(b){let w=_D(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}RD.getSchemaTypes=WL;function _D(b){let w=Array.isArray(b)?b:b?[b]:[];if(w.every(bL.isJSONType))return w;throw Error("type must be JSONType or JSONType[]: "+w.join(","))}RD.getJSONTypes=_D;function QL(b,w){let{gen:$,data:W,opts:Q}=b,G=GL(w,Q.coerceTypes),D=w.length>0&&!(G.length===0&&w.length===1&&(0,wL.schemaHasRulesForType)(b,w[0]));if(D){let X=F4(w,W,Q.strictNumbers,tw.Wrong);$.if(X,()=>{if(G.length)DL(b,w,G);else K4(b)})}return D}RD.coerceAndCheckDataType=QL;var SD=new Set(["string","number","integer","boolean","null"]);function GL(b,w){return w?b.filter(($)=>SD.has($)||w==="array"&&$==="array"):[]}function DL(b,w,$){let{gen:W,data:Q,opts:G}=b,D=W.let("dataType",C._`typeof ${Q}`),X=W.let("coerced",C._`undefined`);if(G.coerceTypes==="array")W.if(C._`${D} == 'object' && Array.isArray(${Q}) && ${Q}.length == 1`,()=>W.assign(Q,C._`${Q}[0]`).assign(D,C._`typeof ${Q}`).if(F4(w,Q,G.strictNumbers),()=>W.assign(X,Q)));W.if(C._`${X} !== undefined`);for(let H of $)if(SD.has(H)||H==="array"&&G.coerceTypes==="array")Y(H);W.else(),K4(b),W.endIf(),W.if(C._`${X} !== undefined`,()=>{W.assign(Q,X),XL(b,X)});function Y(H){switch(H){case"string":W.elseIf(C._`${D} == "number" || ${D} == "boolean"`).assign(X,C._`"" + ${Q}`).elseIf(C._`${Q} === null`).assign(X,C._`""`);return;case"number":W.elseIf(C._`${D} == "boolean" || ${Q} === null
2
+ var iz=Object.create;var{getPrototypeOf:lz,defineProperty:t$,getOwnPropertyNames:pz}=Object;var oz=Object.prototype.hasOwnProperty;function dz(b){return this[b]}var tz,rz,uW=(b,w,$)=>{var W=b!=null&&typeof b==="object";if(W){var Q=w?tz??=new WeakMap:rz??=new WeakMap,G=Q.get(b);if(G)return G}$=b!=null?iz(lz(b)):{};let D=w||!b||!b.__esModule?t$($,"default",{value:b,enumerable:!0}):$;for(let X of pz(b))if(!oz.call(D,X))t$(D,X,{get:dz.bind(b,X),enumerable:!0});if(W)Q.set(b,D);return D};var j=(b,w)=>()=>(w||b((w={exports:{}}).exports,w),w.exports);var ez=(b)=>b;function sz(b,w){this[b]=ez.bind(null,w)}var xW=(b,w)=>{for(var $ in w)t$(b,$,{get:w[$],enumerable:!0,configurable:!0,set:sz.bind(w,$)})};var h1=j((yG)=>{Object.defineProperty(yG,"__esModule",{value:!0});yG.regexpCode=yG.getEsmExportName=yG.getProperty=yG.safeStringify=yG.stringify=yG.strConcat=yG.addCodeArg=yG.str=yG._=yG.nil=yG._Code=yG.Name=yG.IDENTIFIER=yG._CodeOrName=void 0;class t0{}yG._CodeOrName=t0;yG.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class pw extends t0{constructor(b){super();if(!yG.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}}}yG.Name=pw;class hb extends t0{constructor(b){super();this._items=typeof b==="string"?[b]:b}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let b=this._items[0];return b===""||b==='""'}get str(){var b;return(b=this._str)!==null&&b!==void 0?b:this._str=this._items.reduce((w,$)=>`${w}${$}`,"")}get names(){var b;return(b=this._names)!==null&&b!==void 0?b:this._names=this._items.reduce((w,$)=>{if($ instanceof pw)w[$.str]=(w[$.str]||0)+1;return w},{})}}yG._Code=hb;yG.nil=new hb("");function uG(b,...w){let $=[b[0]],W=0;while(W<w.length)Q6($,w[W]),$.push(b[++W]);return new hb($)}yG._=uG;var W6=new hb("+");function xG(b,...w){let $=[y1(b[0])],W=0;while(W<w.length)$.push(W6),Q6($,w[W]),$.push(W6,y1(b[++W]));return KO($),new hb($)}yG.str=xG;function Q6(b,w){if(w instanceof hb)b.push(...w._items);else if(w instanceof pw)b.push(w);else b.push(ZO(w))}yG.addCodeArg=Q6;function KO(b){let w=1;while(w<b.length-1){if(b[w]===W6){let $=MO(b[w-1],b[w+1]);if($!==void 0){b.splice(w-1,3,$);continue}b[w++]="+"}w++}}function MO(b,w){if(w==='""')return b;if(b==='""')return w;if(typeof b=="string"){if(w instanceof pw||b[b.length-1]!=='"')return;if(typeof w!="string")return`${b.slice(0,-1)}${w}"`;if(w[0]==='"')return b.slice(0,-1)+w.slice(1);return}if(typeof w=="string"&&w[0]==='"'&&!(b instanceof pw))return`"${b}${w.slice(1)}`;return}function IO(b,w){return w.emptyStr()?b:b.emptyStr()?w:xG`${b}${w}`}yG.strConcat=IO;function ZO(b){return typeof b=="number"||typeof b=="boolean"||b===null?b:y1(Array.isArray(b)?b.join(","):b)}function jO(b){return new hb(y1(b))}yG.stringify=jO;function y1(b){return JSON.stringify(b).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}yG.safeStringify=y1;function VO(b){return typeof b=="string"&&yG.IDENTIFIER.test(b)?new hb(`.${b}`):uG`[${b}]`}yG.getProperty=VO;function NO(b){if(typeof b=="string"&&yG.IDENTIFIER.test(b))return new hb(`${b}`);throw Error(`CodeGen: invalid export name: ${b}, use explicit $id name mapping`)}yG.getEsmExportName=NO;function TO(b){return new hb(b.toString())}yG.regexpCode=TO});var Y6=j((nG)=>{Object.defineProperty(nG,"__esModule",{value:!0});nG.ValueScope=nG.ValueScopeName=nG.Scope=nG.varKinds=nG.UsedValueState=void 0;var Ib=h1();class fG extends Error{constructor(b){super(`CodeGen: "code" for ${b} not defined`);this.value=b.value}}var e0;(function(b){b[b.Started=0]="Started",b[b.Completed=1]="Completed"})(e0||(nG.UsedValueState=e0={}));nG.varKinds={const:new Ib.Name("const"),let:new Ib.Name("let"),var:new Ib.Name("var")};class D6{constructor({prefixes:b,parent:w}={}){this._names={},this._prefixes=b,this._parent=w}toName(b){return b instanceof Ib.Name?b:this.name(b)}name(b){return new Ib.Name(this._newName(b))}_newName(b){let w=this._names[b]||this._nameGroup(b);return`${b}${w.index++}`}_nameGroup(b){var w,$;if((($=(w=this._parent)===null||w===void 0?void 0:w._prefixes)===null||$===void 0?void 0:$.has(b))||this._prefixes&&!this._prefixes.has(b))throw Error(`CodeGen: prefix "${b}" is not allowed in this scope`);return this._names[b]={prefix:b,index:0}}}nG.Scope=D6;class X6 extends Ib.Name{constructor(b,w){super(w);this.prefix=b}setValue(b,{property:w,itemIndex:$}){this.value=b,this.scopePath=Ib._`.${new Ib.Name(w)}[${$}]`}}nG.ValueScopeName=X6;var cO=Ib._`\n`;class cG extends D6{constructor(b){super(b);this._values={},this._scope=b.scope,this.opts={...b,_n:b.lines?cO:Ib.nil}}get(){return this._scope}name(b){return new X6(b,this._newName(b))}value(b,w){var $;if(w.ref===void 0)throw Error("CodeGen: ref must be passed in value");let W=this.toName(b),{prefix:Q}=W,G=($=w.key)!==null&&$!==void 0?$:w.ref,D=this._values[Q];if(D){let H=D.get(G);if(H)return H}else D=this._values[Q]=new Map;D.set(G,W);let X=this._scope[Q]||(this._scope[Q]=[]),Y=X.length;return X[Y]=w.ref,W.setValue(w,{property:Q,itemIndex:Y}),W}getValue(b,w){let $=this._values[b];if(!$)return;return $.get(w)}scopeRefs(b,w=this._values){return this._reduceValues(w,($)=>{if($.scopePath===void 0)throw Error(`CodeGen: name "${$}" has no value`);return Ib._`${b}${$.scopePath}`})}scopeCode(b=this._values,w,$){return this._reduceValues(b,(W)=>{if(W.value===void 0)throw Error(`CodeGen: name "${W}" has no value`);return W.value.code},w,$)}_reduceValues(b,w,$={},W){let Q=Ib.nil;for(let G in b){let D=b[G];if(!D)continue;let X=$[G]=$[G]||new Map;D.forEach((Y)=>{if(X.has(Y))return;X.set(Y,e0.Started);let H=w(Y);if(H){let J=this.opts.es5?nG.varKinds.var:nG.varKinds.const;Q=Ib._`${Q}${J} ${Y} = ${H};${this.opts._n}`}else if(H=W===null||W===void 0?void 0:W(Y))Q=Ib._`${Q}${H}${this.opts._n}`;else throw new fG(Y);X.set(Y,e0.Completed)})}return Q}}nG.ValueScope=cG});var x=j((Zb)=>{Object.defineProperty(Zb,"__esModule",{value:!0});Zb.or=Zb.and=Zb.not=Zb.CodeGen=Zb.operators=Zb.varKinds=Zb.ValueScopeName=Zb.ValueScope=Zb.Scope=Zb.Name=Zb.regexpCode=Zb.stringify=Zb.getProperty=Zb.nil=Zb.strConcat=Zb.str=Zb._=void 0;var n=h1(),fb=Y6(),Iw=h1();Object.defineProperty(Zb,"_",{enumerable:!0,get:function(){return Iw._}});Object.defineProperty(Zb,"str",{enumerable:!0,get:function(){return Iw.str}});Object.defineProperty(Zb,"strConcat",{enumerable:!0,get:function(){return Iw.strConcat}});Object.defineProperty(Zb,"nil",{enumerable:!0,get:function(){return Iw.nil}});Object.defineProperty(Zb,"getProperty",{enumerable:!0,get:function(){return Iw.getProperty}});Object.defineProperty(Zb,"stringify",{enumerable:!0,get:function(){return Iw.stringify}});Object.defineProperty(Zb,"regexpCode",{enumerable:!0,get:function(){return Iw.regexpCode}});Object.defineProperty(Zb,"Name",{enumerable:!0,get:function(){return Iw.Name}});var W$=Y6();Object.defineProperty(Zb,"Scope",{enumerable:!0,get:function(){return W$.Scope}});Object.defineProperty(Zb,"ValueScope",{enumerable:!0,get:function(){return W$.ValueScope}});Object.defineProperty(Zb,"ValueScopeName",{enumerable:!0,get:function(){return W$.ValueScopeName}});Object.defineProperty(Zb,"varKinds",{enumerable:!0,get:function(){return W$.varKinds}});Zb.operators={GT:new 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 mG 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=dw(this.rhs,b,w);return this}get names(){return this.rhs instanceof n._CodeOrName?this.rhs.names:{}}}class z6 extends Zw{constructor(b,w,$){super();this.lhs=b,this.rhs=w,this.sideEffects=$}render({_n:b}){return`${this.lhs} = ${this.rhs};`+b}optimizeNames(b,w){if(this.lhs instanceof n.Name&&!b[this.lhs.str]&&!this.sideEffects)return;return this.rhs=dw(this.rhs,b,w),this}get names(){let b=this.lhs instanceof n.Name?{}:{...this.lhs.names};return $$(b,this.rhs)}}class iG extends z6{constructor(b,w,$,W){super(b,$,W);this.op=w}render({_n:b}){return`${this.lhs} ${this.op}= ${this.rhs};`+b}}class lG extends Zw{constructor(b){super();this.label=b,this.names={}}render({_n:b}){return`${this.label}:`+b}}class pG extends Zw{constructor(b){super();this.label=b,this.names={}}render({_n:b}){return`break${this.label?` ${this.label}`:""};`+b}}class oG extends Zw{constructor(b){super();this.error=b}render({_n:b}){return`throw ${this.error};`+b}get names(){return this.error.names}}class dG extends Zw{constructor(b){super();this.code=b}render({_n:b}){return`${this.code};`+b}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(b,w){return this.code=dw(this.code,b,w),this}get names(){return this.code instanceof n._CodeOrName?this.code.names:{}}}class Q$ extends Zw{constructor(b=[]){super();this.nodes=b}render(b){return this.nodes.reduce((w,$)=>w+$.render(b),"")}optimizeNodes(){let{nodes:b}=this,w=b.length;while(w--){let $=b[w].optimizeNodes();if(Array.isArray($))b.splice(w,1,...$);else if($)b[w]=$;else b.splice(w,1)}return b.length>0?this:void 0}optimizeNames(b,w){let{nodes:$}=this,W=$.length;while(W--){let Q=$[W];if(Q.optimizeNames(b,w))continue;iO(b,Q.names),$.splice(W,1)}return $.length>0?this:void 0}get names(){return this.nodes.reduce((b,w)=>vw(b,w.names),{})}}class jw extends Q${render(b){return"{"+b._n+super.render(b)+"}"+b._n}}class tG extends Q${}class f1 extends jw{}f1.kind="else";class Ww extends jw{constructor(b,w){super(w);this.condition=b}render(b){let w=`if(${this.condition})`+super.render(b);if(this.else)w+="else "+this.else.render(b);return w}optimizeNodes(){super.optimizeNodes();let b=this.condition;if(b===!0)return this.nodes;let w=this.else;if(w){let $=w.optimizeNodes();w=this.else=Array.isArray($)?new f1($):$}if(w){if(b===!1)return w instanceof Ww?w:w.nodes;if(this.nodes.length)return this;return new Ww(bD(b),w instanceof Ww?[w]:w.nodes)}if(b===!1||!this.nodes.length)return;return this}optimizeNames(b,w){var $;if(this.else=($=this.else)===null||$===void 0?void 0:$.optimizeNames(b,w),!(super.optimizeNames(b,w)||this.else))return;return this.condition=dw(this.condition,b,w),this}get names(){let b=super.names;if($$(b,this.condition),this.else)vw(b,this.else.names);return b}}Ww.kind="if";class ow extends jw{}ow.kind="for";class rG extends ow{constructor(b){super();this.iteration=b}render(b){return`for(${this.iteration})`+super.render(b)}optimizeNames(b,w){if(!super.optimizeNames(b,w))return;return this.iteration=dw(this.iteration,b,w),this}get names(){return vw(super.names,this.iteration.names)}}class eG extends ow{constructor(b,w,$,W){super();this.varKind=b,this.name=w,this.from=$,this.to=W}render(b){let w=b.es5?fb.varKinds.var:this.varKind,{name:$,from:W,to:Q}=this;return`for(${w} ${$}=${W}; ${$}<${Q}; ${$}++)`+super.render(b)}get names(){let b=$$(super.names,this.from);return $$(b,this.to)}}class H6 extends ow{constructor(b,w,$,W){super();this.loop=b,this.varKind=w,this.name=$,this.iterable=W}render(b){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(b)}optimizeNames(b,w){if(!super.optimizeNames(b,w))return;return this.iterable=dw(this.iterable,b,w),this}get names(){return vw(super.names,this.iterable.names)}}class s0 extends jw{constructor(b,w,$){super();this.name=b,this.args=w,this.async=$}render(b){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(b)}}s0.kind="func";class a0 extends Q${render(b){return"return "+super.render(b)}}a0.kind="return";class sG extends jw{render(b){let w="try"+super.render(b);if(this.catch)w+=this.catch.render(b);if(this.finally)w+=this.finally.render(b);return w}optimizeNodes(){var b,w;return super.optimizeNodes(),(b=this.catch)===null||b===void 0||b.optimizeNodes(),(w=this.finally)===null||w===void 0||w.optimizeNodes(),this}optimizeNames(b,w){var $,W;return super.optimizeNames(b,w),($=this.catch)===null||$===void 0||$.optimizeNames(b,w),(W=this.finally)===null||W===void 0||W.optimizeNames(b,w),this}get names(){let b=super.names;if(this.catch)vw(b,this.catch.names);if(this.finally)vw(b,this.finally.names);return b}}class b$ extends jw{constructor(b){super();this.error=b}render(b){return`catch(${this.error})`+super.render(b)}}b$.kind="catch";class w$ extends jw{render(b){return"finally"+super.render(b)}}w$.kind="finally";class aG{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 tG]}toString(){return this._root.render(this.opts)}name(b){return this._scope.name(b)}scopeName(b){return this._extScope.name(b)}scopeValue(b,w){let $=this._extScope.value(b,w);return(this._values[$.prefix]||(this._values[$.prefix]=new Set)).add($),$}getScopeValue(b,w){return this._extScope.getValue(b,w)}scopeRefs(b){return this._extScope.scopeRefs(b,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(b,w,$,W){let Q=this._scope.toName(w);if($!==void 0&&W)this._constants[Q.str]=$;return this._leafNode(new mG(b,Q,$)),Q}const(b,w,$){return this._def(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 z6(b,w,$))}add(b,w){return this._leafNode(new iG(b,Zb.operators.ADD,w))}code(b){if(typeof b=="function")b();else if(b!==n.nil)this._leafNode(new dG(b));return this}object(...b){let w=["{"];for(let[$,W]of b){if(w.length>1)w.push(",");if(w.push($),$!==W||this.opts.es5)w.push(":"),(0,n.addCodeArg)(w,W)}return w.push("}"),new n._Code(w)}if(b,w,$){if(this._blockNode(new Ww(b)),w&&$)this.code(w).else().code($).endIf();else if(w)this.code(w).endIf();else if($)throw Error('CodeGen: "else" body without "then" body');return this}elseIf(b){return this._elseNode(new Ww(b))}else(){return this._elseNode(new f1)}endIf(){return this._endBlockNode(Ww,f1)}_for(b,w){if(this._blockNode(b),w)this.code(w).endFor();return this}for(b,w){return this._for(new rG(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 eG(Q,G,w,$),()=>W(G))}forOf(b,w,$,W=fb.varKinds.const){let Q=this._scope.toName(b);if(this.opts.es5){let G=w instanceof n.Name?w:this.var("_arr",w);return this.forRange("_i",0,n._`${G}.length`,(D)=>{this.var(Q,n._`${G}[${D}]`),$(Q)})}return this._for(new H6("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 H6("in",W,Q,w),()=>$(Q))}endFor(){return this._endBlockNode(ow)}label(b){return this._leafNode(new lG(b))}break(b){return this._leafNode(new pG(b))}return(b){let w=new a0;if(this._blockNode(w),this.code(b),w.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(a0)}try(b,w,$){if(!w&&!$)throw Error('CodeGen: "try" without "catch" and "finally"');let W=new sG;if(this._blockNode(W),this.code(b),w){let Q=this.name("e");this._currNode=W.catch=new b$(Q),w(Q)}if($)this._currNode=W.finally=new w$,this.code($);return this._endBlockNode(b$,w$)}throw(b){return this._leafNode(new oG(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 s0(b,w,$)),W)this.code(W).endFunc();return this}endFunc(){return this._endBlockNode(s0)}optimize(b=1){while(b-- >0)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(b){return this._currNode.nodes.push(b),this}_blockNode(b){this._currNode.nodes.push(b),this._nodes.push(b)}_endBlockNode(b,w){let $=this._currNode;if($ instanceof b||w&&$ instanceof w)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${w?`${b.kind}/${w.kind}`:b.kind}"`)}_elseNode(b){let w=this._currNode;if(!(w instanceof Ww))throw Error('CodeGen: "else" without "if"');return this._currNode=w.else=b,this}get _root(){return this._nodes[0]}get _currNode(){let b=this._nodes;return b[b.length-1]}set _currNode(b){let w=this._nodes;w[w.length-1]=b}}Zb.CodeGen=aG;function vw(b,w){for(let $ in w)b[$]=(b[$]||0)+(w[$]||0);return b}function $$(b,w){return w instanceof n._CodeOrName?vw(b,w.names):b}function dw(b,w,$){if(b instanceof n.Name)return W(b);if(!Q(b))return b;return new n._Code(b._items.reduce((G,D)=>{if(D instanceof n.Name)D=W(D);if(D instanceof n._Code)G.push(...D._items);else G.push(D);return G},[]));function W(G){let D=$[G.str];if(D===void 0||w[G.str]!==1)return G;return delete w[G.str],D}function Q(G){return G instanceof n._Code&&G._items.some((D)=>D instanceof n.Name&&w[D.str]===1&&$[D.str]!==void 0)}}function iO(b,w){for(let $ in w)b[$]=(b[$]||0)-(w[$]||0)}function bD(b){return typeof b=="boolean"||typeof b=="number"||b===null?!b:n._`!${J6(b)}`}Zb.not=bD;var lO=wD(Zb.operators.AND);function pO(...b){return b.reduce(lO)}Zb.and=pO;var oO=wD(Zb.operators.OR);function dO(...b){return b.reduce(oO)}Zb.or=dO;function wD(b){return(w,$)=>w===n.nil?$:$===n.nil?w:n._`${J6(w)} ${b} ${J6($)}`}function J6(b){return b instanceof n.Name?b:n._`(${b})`}});var i=j((JD)=>{Object.defineProperty(JD,"__esModule",{value:!0});JD.checkStrictMode=JD.getErrorPath=JD.Type=JD.useFunc=JD.setEvaluated=JD.evaluatedPropsToName=JD.mergeEvaluated=JD.eachItem=JD.unescapeJsonPointer=JD.escapeJsonPointer=JD.escapeFragment=JD.unescapeFragment=JD.schemaRefOrVal=JD.schemaHasRulesButRef=JD.schemaHasRules=JD.checkUnknownRules=JD.alwaysValidSchema=JD.toHash=void 0;var t=x(),sO=h1();function aO(b){let w={};for(let $ of b)w[$]=!0;return w}JD.toHash=aO;function bq(b,w){if(typeof w=="boolean")return w;if(Object.keys(w).length===0)return!0;return GD(b,w),!DD(w,b.self.RULES.all)}JD.alwaysValidSchema=bq;function GD(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])HD(b,`unknown keyword: "${G}"`)}JD.checkUnknownRules=GD;function DD(b,w){if(typeof b=="boolean")return!b;for(let $ in b)if(w[$])return!0;return!1}JD.schemaHasRules=DD;function wq(b,w){if(typeof b=="boolean")return!b;for(let $ in b)if($!=="$ref"&&w.all[$])return!0;return!1}JD.schemaHasRulesButRef=wq;function $q({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)}`}JD.schemaRefOrVal=$q;function Wq(b){return XD(decodeURIComponent(b))}JD.unescapeFragment=Wq;function Qq(b){return encodeURIComponent(O6(b))}JD.escapeFragment=Qq;function O6(b){if(typeof b=="number")return`${b}`;return b.replace(/~/g,"~0").replace(/\//g,"~1")}JD.escapeJsonPointer=O6;function XD(b){return b.replace(/~1/g,"/").replace(/~0/g,"~")}JD.unescapeJsonPointer=XD;function Gq(b,w){if(Array.isArray(b))for(let $ of b)w($);else w(b)}JD.eachItem=Gq;function WD({mergeNames:b,mergeToName:w,mergeValues:$,resultToName:W}){return(Q,G,D,X)=>{let Y=D===void 0?G:D instanceof t.Name?(G instanceof t.Name?b(Q,G,D):w(Q,G,D),D):G instanceof t.Name?(w(Q,D,G),G):$(G,D);return X===t.Name&&!(Y instanceof t.Name)?W(Q,Y):Y}}JD.mergeEvaluated={props:WD({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._`${$} || {}`),q6(b,$,w)}),mergeValues:(b,w)=>b===!0?!0:{...b,...w},resultToName:YD}),items:WD({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 YD(b,w){if(w===!0)return b.var("props",!0);let $=b.var("props",t._`{}`);if(w!==void 0)q6(b,$,w);return $}JD.evaluatedPropsToName=YD;function q6(b,w,$){Object.keys($).forEach((W)=>b.assign(t._`${w}${(0,t.getProperty)(W)}`,!0))}JD.setEvaluated=q6;var QD={};function Dq(b,w){return b.scopeValue("func",{ref:w,code:QD[w.code]||(QD[w.code]=new sO._Code(w.code))})}JD.useFunc=Dq;var A6;(function(b){b[b.Num=0]="Num",b[b.Str=1]="Str"})(A6||(JD.Type=A6={}));function Xq(b,w,$){if(b instanceof t.Name){let W=w===A6.Num;return $?W?t._`"[" + ${b} + "]"`:t._`"['" + ${b} + "']"`:W?t._`"/" + ${b}`:t._`"/" + ${b}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return $?(0,t.getProperty)(b).toString():"/"+O6(b)}JD.getErrorPath=Xq;function HD(b,w,$=b.opts.strictSchema){if(!$)return;if(w=`strict mode: ${w}`,$===!0)throw Error(w);b.self.logger.warn(w)}JD.checkStrictMode=HD});var Qw=j((AD)=>{Object.defineProperty(AD,"__esModule",{value:!0});var Lb=x(),Vq={data:new Lb.Name("data"),valCxt:new Lb.Name("valCxt"),instancePath:new Lb.Name("instancePath"),parentData:new Lb.Name("parentData"),parentDataProperty:new Lb.Name("parentDataProperty"),rootData:new Lb.Name("rootData"),dynamicAnchors:new Lb.Name("dynamicAnchors"),vErrors:new Lb.Name("vErrors"),errors:new Lb.Name("errors"),this:new Lb.Name("this"),self:new Lb.Name("self"),scope:new Lb.Name("scope"),json:new Lb.Name("json"),jsonPos:new Lb.Name("jsonPos"),jsonLen:new Lb.Name("jsonLen"),jsonPart:new Lb.Name("jsonPart")};AD.default=Vq});var c1=j((UD)=>{Object.defineProperty(UD,"__esModule",{value:!0});UD.extendErrors=UD.resetErrorsCount=UD.reportExtraError=UD.reportError=UD.keyword$DataError=UD.keywordError=void 0;var g=x(),D$=i(),Pb=Qw();UD.keywordError={message:({keyword:b})=>g.str`must pass "${b}" keyword validation`};UD.keyword$DataError={message:({keyword:b,schemaType:w})=>w?g.str`"${b}" keyword must be ${w} ($data)`:g.str`"${b}" keyword is invalid ($data)`};function Tq(b,w=UD.keywordError,$,W){let{it:Q}=b,{gen:G,compositeRule:D,allErrors:X}=Q,Y=LD(b,w,$);if(W!==null&&W!==void 0?W:D||X)OD(G,Y);else qD(Q,g._`[${Y}]`)}UD.reportError=Tq;function Eq(b,w=UD.keywordError,$){let{it:W}=b,{gen:Q,compositeRule:G,allErrors:D}=W,X=LD(b,w,$);if(OD(Q,X),!(G||D))qD(W,Pb.default.vErrors)}UD.reportExtraError=Eq;function _q(b,w){b.assign(Pb.default.errors,w),b.if(g._`${Pb.default.vErrors} !== null`,()=>b.if(w,()=>b.assign(g._`${Pb.default.vErrors}.length`,w),()=>b.assign(Pb.default.vErrors,null)))}UD.resetErrorsCount=_q;function Sq({gen:b,keyword:w,schemaValue:$,data:W,errsCount:Q,it:G}){if(Q===void 0)throw Error("ajv implementation error");let D=b.name("err");b.forRange("i",Q,Pb.default.errors,(X)=>{if(b.const(D,g._`${Pb.default.vErrors}[${X}]`),b.if(g._`${D}.instancePath === undefined`,()=>b.assign(g._`${D}.instancePath`,(0,g.strConcat)(Pb.default.instancePath,G.errorPath))),b.assign(g._`${D}.schemaPath`,g.str`${G.errSchemaPath}/${w}`),G.opts.verbose)b.assign(g._`${D}.schema`,$),b.assign(g._`${D}.data`,W)})}UD.extendErrors=Sq;function OD(b,w){let $=b.const("err",w);b.if(g._`${Pb.default.vErrors} === null`,()=>b.assign(Pb.default.vErrors,g._`[${$}]`),g._`${Pb.default.vErrors}.push(${$})`),b.code(g._`${Pb.default.errors}++`)}function qD(b,w){let{gen:$,validateName:W,schemaEnv:Q}=b;if(Q.$async)$.throw(g._`new ${b.ValidationError}(${w})`);else $.assign(g._`${W}.errors`,w),$.return(!1)}var kw={keyword:new g.Name("keyword"),schemaPath:new g.Name("schemaPath"),params:new g.Name("params"),propertyName:new g.Name("propertyName"),message:new g.Name("message"),schema:new g.Name("schema"),parentSchema:new g.Name("parentSchema")};function LD(b,w,$){let{createErrors:W}=b.it;if(W===!1)return g._`{}`;return Rq(b,w,$)}function Rq(b,w,$={}){let{gen:W,it:Q}=b,G=[vq(Q,$),kq(b,$)];return Cq(b,w,G),W.object(...G)}function vq({errorPath:b},{instancePath:w}){let $=w?g.str`${b}${(0,D$.getErrorPath)(w,D$.Type.Str)}`:b;return[Pb.default.instancePath,(0,g.strConcat)(Pb.default.instancePath,$)]}function kq({keyword:b,it:{errSchemaPath:w}},{schemaPath:$,parentSchema:W}){let Q=W?w:g.str`${w}/${b}`;if($)Q=g.str`${Q}${(0,D$.getErrorPath)($,D$.Type.Str)}`;return[kw.schemaPath,Q]}function Cq(b,{params:w,message:$},W){let{keyword:Q,data:G,schemaValue:D,it:X}=b,{opts:Y,propertyName:H,topSchemaRef:J,schemaPath:z}=X;if(W.push([kw.keyword,Q],[kw.params,typeof w=="function"?w(b):w||g._`{}`]),Y.messages)W.push([kw.message,typeof $=="function"?$(b):$]);if(Y.verbose)W.push([kw.schema,D],[kw.parentSchema,g._`${J}${z}`],[Pb.default.data,G]);if(H)W.push([kw.propertyName,H])}});var MD=j((FD)=>{Object.defineProperty(FD,"__esModule",{value:!0});FD.boolOrEmptySchema=FD.topBoolOrEmptySchema=void 0;var fq=c1(),cq=x(),nq=Qw(),gq={message:"boolean schema is false"};function mq(b){let{gen:w,schema:$,validateName:W}=b;if($===!1)PD(b,!1);else if(typeof $=="object"&&$.$async===!0)w.return(nq.default.data);else w.assign(cq._`${W}.errors`,null),w.return(!0)}FD.topBoolOrEmptySchema=mq;function iq(b,w){let{gen:$,schema:W}=b;if(W===!1)$.var(w,!1),PD(b);else $.var(w,!0)}FD.boolOrEmptySchema=iq;function PD(b,w){let{gen:$,data:W}=b,Q={gen:$,keyword:"false schema",data:W,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:b};(0,fq.reportError)(Q,gq,void 0,w)}});var U6=j((ID)=>{Object.defineProperty(ID,"__esModule",{value:!0});ID.getRules=ID.isJSONType=void 0;var pq=["string","number","integer","boolean","null","object","array"],oq=new Set(pq);function dq(b){return typeof b=="string"&&oq.has(b)}ID.isJSONType=dq;function tq(){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:{}}}ID.getRules=tq});var B6=j((ND)=>{Object.defineProperty(ND,"__esModule",{value:!0});ND.shouldUseRule=ND.shouldUseGroup=ND.schemaHasRulesForType=void 0;function eq({schema:b,self:w},$){let W=w.RULES.types[$];return W&&W!==!0&&jD(b,W)}ND.schemaHasRulesForType=eq;function jD(b,w){return w.rules.some(($)=>VD(b,$))}ND.shouldUseGroup=jD;function VD(b,w){var $;return b[w.keyword]!==void 0||(($=w.definition.implements)===null||$===void 0?void 0:$.some((W)=>b[W]!==void 0))}ND.shouldUseRule=VD});var n1=j((RD)=>{Object.defineProperty(RD,"__esModule",{value:!0});RD.reportTypeError=RD.checkDataTypes=RD.checkDataType=RD.coerceAndCheckDataType=RD.getJSONTypes=RD.getSchemaTypes=RD.DataType=void 0;var bL=U6(),wL=B6(),$L=c1(),C=x(),ED=i(),tw;(function(b){b[b.Correct=0]="Correct",b[b.Wrong=1]="Wrong"})(tw||(RD.DataType=tw={}));function WL(b){let w=_D(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}RD.getSchemaTypes=WL;function _D(b){let w=Array.isArray(b)?b:b?[b]:[];if(w.every(bL.isJSONType))return w;throw Error("type must be JSONType or JSONType[]: "+w.join(","))}RD.getJSONTypes=_D;function QL(b,w){let{gen:$,data:W,opts:Q}=b,G=GL(w,Q.coerceTypes),D=w.length>0&&!(G.length===0&&w.length===1&&(0,wL.schemaHasRulesForType)(b,w[0]));if(D){let X=F6(w,W,Q.strictNumbers,tw.Wrong);$.if(X,()=>{if(G.length)DL(b,w,G);else K6(b)})}return D}RD.coerceAndCheckDataType=QL;var SD=new Set(["string","number","integer","boolean","null"]);function GL(b,w){return w?b.filter(($)=>SD.has($)||w==="array"&&$==="array"):[]}function DL(b,w,$){let{gen:W,data:Q,opts:G}=b,D=W.let("dataType",C._`typeof ${Q}`),X=W.let("coerced",C._`undefined`);if(G.coerceTypes==="array")W.if(C._`${D} == 'object' && Array.isArray(${Q}) && ${Q}.length == 1`,()=>W.assign(Q,C._`${Q}[0]`).assign(D,C._`typeof ${Q}`).if(F6(w,Q,G.strictNumbers),()=>W.assign(X,Q)));W.if(C._`${X} !== undefined`);for(let H of $)if(SD.has(H)||H==="array"&&G.coerceTypes==="array")Y(H);W.else(),K6(b),W.endIf(),W.if(C._`${X} !== undefined`,()=>{W.assign(Q,X),XL(b,X)});function Y(H){switch(H){case"string":W.elseIf(C._`${D} == "number" || ${D} == "boolean"`).assign(X,C._`"" + ${Q}`).elseIf(C._`${Q} === null`).assign(X,C._`""`);return;case"number":W.elseIf(C._`${D} == "boolean" || ${Q} === null
4
4
  || (${D} == "string" && ${Q} && ${Q} == +${Q})`).assign(X,C._`+${Q}`);return;case"integer":W.elseIf(C._`${D} === "boolean" || ${Q} === null
5
5
  || (${D} === "string" && ${Q} && ${Q} == +${Q} && !(${Q} % 1))`).assign(X,C._`+${Q}`);return;case"boolean":W.elseIf(C._`${Q} === "false" || ${Q} === 0 || ${Q} === null`).assign(X,!1).elseIf(C._`${Q} === "true" || ${Q} === 1`).assign(X,!0);return;case"null":W.elseIf(C._`${Q} === "" || ${Q} === 0 || ${Q} === false`),W.assign(X,null);return;case"array":W.elseIf(C._`${D} === "string" || ${D} === "number"
6
- || ${D} === "boolean" || ${Q} === null`).assign(X,C._`[${Q}]`)}}}function XL({gen:b,parentData:w,parentDataProperty:$},W){b.if(C._`${w} !== undefined`,()=>b.assign(C._`${w}[${$}]`,W))}function P4(b,w,$,W=tw.Correct){let Q=W===tw.Correct?C.operators.EQ:C.operators.NEQ,G;switch(b){case"null":return C._`${w} ${Q} null`;case"array":G=C._`Array.isArray(${w})`;break;case"object":G=C._`${w} && typeof ${w} == "object" && !Array.isArray(${w})`;break;case"integer":G=D(C._`!(${w} % 1) && !isNaN(${w})`);break;case"number":G=D();break;default:return C._`typeof ${w} ${Q} ${b}`}return W===tw.Correct?G:(0,C.not)(G);function D(X=C.nil){return(0,C.and)(C._`typeof ${w} == "number"`,X,$?C._`isFinite(${w})`:C.nil)}}RD.checkDataType=P4;function F4(b,w,$,W){if(b.length===1)return P4(b[0],w,$,W);let Q,G=(0,ED.toHash)(b);if(G.array&&G.object){let D=C._`typeof ${w} != "object"`;Q=G.null?D:C._`!${w} || ${D}`,delete G.null,delete G.array,delete G.object}else Q=C.nil;if(G.number)delete G.integer;for(let D in G)Q=(0,C.and)(Q,P4(D,w,$,W));return Q}RD.checkDataTypes=F4;var YL={message:({schema:b})=>`must be ${b}`,params:({schema:b,schemaValue:w})=>typeof b=="string"?C._`{type: ${b}}`:C._`{type: ${w}}`};function K4(b){let w=HL(b);(0,$L.reportError)(w,YL)}RD.reportTypeError=K4;function HL(b){let{gen:w,data:$,schema:W}=b,Q=(0,ED.schemaRefOrVal)(b,W,"type");return{gen:w,keyword:"type",data:$,schema:W.type,schemaCode:Q,schemaValue:Q,parentSchema:W,params:{},it:b}}});var xD=j((CD)=>{Object.defineProperty(CD,"__esModule",{value:!0});CD.assignDefaults=void 0;var rw=x(),UL=i();function BL(b,w){let{properties:$,items:W}=b.schema;if(w==="object"&&$)for(let Q in $)kD(b,Q,$[Q].default);else if(w==="array"&&Array.isArray(W))W.forEach((Q,G)=>kD(b,G,Q.default))}CD.assignDefaults=BL;function kD(b,w,$){let{gen:W,compositeRule:Q,data:G,opts:D}=b;if($===void 0)return;let X=rw._`${G}${(0,rw.getProperty)(w)}`;if(Q){(0,UL.checkStrictMode)(b,`default is ignored for: ${X}`);return}let Y=rw._`${X} === undefined`;if(D.useDefaults==="empty")Y=rw._`${Y} || ${X} === null || ${X} === ""`;W.if(Y,rw._`${X} = ${(0,rw.stringify)($)}`)}});var Cb=j((fD)=>{Object.defineProperty(fD,"__esModule",{value:!0});fD.validateUnion=fD.validateArray=fD.usePattern=fD.callValidateCode=fD.schemaProperties=fD.allSchemaProperties=fD.noPropertyInData=fD.propertyInData=fD.isOwnProperty=fD.hasPropFunc=fD.reportMissingProp=fD.checkMissingProp=fD.checkReportMissingProp=void 0;var a=x(),M4=i(),Vw=Qw(),PL=i();function FL(b,w){let{gen:$,data:W,it:Q}=b;$.if(Z4($,W,w,Q.opts.ownProperties),()=>{b.setParams({missingProperty:a._`${w}`},!0),b.error()})}fD.checkReportMissingProp=FL;function KL({gen:b,data:w,it:{opts:$}},W,Q){return(0,a.or)(...W.map((G)=>(0,a.and)(Z4(b,w,G,$.ownProperties),a._`${Q} = ${G}`)))}fD.checkMissingProp=KL;function ML(b,w){b.setParams({missingProperty:w},!0),b.error()}fD.reportMissingProp=ML;function yD(b){return b.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:a._`Object.prototype.hasOwnProperty`})}fD.hasPropFunc=yD;function I4(b,w,$){return a._`${yD(b)}.call(${w}, ${$})`}fD.isOwnProperty=I4;function IL(b,w,$,W){let Q=a._`${w}${(0,a.getProperty)($)} !== undefined`;return W?a._`${Q} && ${I4(b,w,$)}`:Q}fD.propertyInData=IL;function Z4(b,w,$,W){let Q=a._`${w}${(0,a.getProperty)($)} === undefined`;return W?(0,a.or)(Q,(0,a.not)(I4(b,w,$))):Q}fD.noPropertyInData=Z4;function hD(b){return b?Object.keys(b).filter((w)=>w!=="__proto__"):[]}fD.allSchemaProperties=hD;function ZL(b,w){return hD(w).filter(($)=>!(0,M4.alwaysValidSchema)(b,w[$]))}fD.schemaProperties=ZL;function jL({schemaCode:b,data:w,it:{gen:$,topSchemaRef:W,schemaPath:Q,errorPath:G},it:D},X,Y,H){let J=H?a._`${b}, ${w}, ${W}${Q}`:w,z=[[Vw.default.instancePath,(0,a.strConcat)(Vw.default.instancePath,G)],[Vw.default.parentData,D.parentData],[Vw.default.parentDataProperty,D.parentDataProperty],[Vw.default.rootData,Vw.default.rootData]];if(D.opts.dynamicRef)z.push([Vw.default.dynamicAnchors,Vw.default.dynamicAnchors]);let O=a._`${J}, ${$.object(...z)}`;return Y!==a.nil?a._`${X}.call(${Y}, ${O})`:a._`${X}(${O})`}fD.callValidateCode=jL;var VL=a._`new RegExp`;function NL({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"?VL:(0,PL.useFunc)(b,Q)}(${$}, ${W})`})}fD.usePattern=NL;function TL(b){let{gen:w,data:$,keyword:W,it:Q}=b,G=w.name("valid");if(Q.allErrors){let X=w.let("valid",!0);return D(()=>w.assign(X,!1)),X}return w.var(G,!0),D(()=>w.break()),G;function D(X){let Y=w.const("len",a._`${$}.length`);w.forRange("i",0,Y,(H)=>{b.subschema({keyword:W,dataProp:H,dataPropType:M4.Type.Num},G),w.if((0,a.not)(G),X)})}}fD.validateArray=TL;function EL(b){let{gen:w,schema:$,keyword:W,it:Q}=b;if(!Array.isArray($))throw Error("ajv implementation error");if($.some((Y)=>(0,M4.alwaysValidSchema)(Q,Y))&&!Q.opts.unevaluated)return;let D=w.let("valid",!1),X=w.name("_valid");w.block(()=>$.forEach((Y,H)=>{let J=b.subschema({keyword:W,schemaProp:H,compositeRule:!0},X);if(w.assign(D,a._`${D} || ${X}`),!b.mergeValidEvaluated(J,X))w.if((0,a.not)(D))})),b.result(D,()=>b.reset(),()=>b.error(!0))}fD.validateUnion=EL});var lD=j((mD)=>{Object.defineProperty(mD,"__esModule",{value:!0});mD.validateKeywordUsage=mD.validSchemaType=mD.funcKeywordCode=mD.macroKeywordCode=void 0;var Fb=x(),Cw=Qw(),nL=Cb(),gL=c1();function mL(b,w){let{gen:$,keyword:W,schema:Q,parentSchema:G,it:D}=b,X=w.macro.call(D.self,Q,G,D),Y=gD($,W,X);if(D.opts.validateSchema!==!1)D.self.validateSchema(X,!0);let H=$.name("valid");b.subschema({schema:X,schemaPath:Fb.nil,errSchemaPath:`${D.errSchemaPath}/${W}`,topSchemaRef:Y,compositeRule:!0},H),b.pass(H,()=>b.error(!0))}mD.macroKeywordCode=mL;function iL(b,w){var $;let{gen:W,keyword:Q,schema:G,parentSchema:D,$data:X,it:Y}=b;pL(Y,w);let H=!X&&w.compile?w.compile.call(Y.self,G,D,Y):w.validate,J=gD(W,Q,H),z=W.let("valid");b.block$data(z,O),b.ok(($=w.valid)!==null&&$!==void 0?$:z);function O(){if(w.errors===!1){if(K(),w.modifying)nD(b);I(()=>b.error())}else{let M=w.async?q():B();if(w.modifying)nD(b);I(()=>lL(b,M))}}function q(){let M=W.let("ruleErrs",null);return W.try(()=>K(Fb._`await `),(v)=>W.assign(z,!1).if(Fb._`${v} instanceof ${Y.ValidationError}`,()=>W.assign(M,Fb._`${v}.errors`),()=>W.throw(v))),M}function B(){let M=Fb._`${J}.errors`;return W.assign(M,null),K(Fb.nil),M}function K(M=w.async?Fb._`await `:Fb.nil){let v=Y.opts.passContext?Cw.default.this:Cw.default.self,S=!(("compile"in w)&&!X||w.schema===!1);W.assign(z,Fb._`${M}${(0,nL.callValidateCode)(b,J,v,S)}`,w.modifying)}function I(M){var v;W.if((0,Fb.not)((v=w.valid)!==null&&v!==void 0?v:z),M)}}mD.funcKeywordCode=iL;function nD(b){let{gen:w,data:$,it:W}=b;w.if(W.parentData,()=>w.assign($,Fb._`${W.parentData}[${W.parentDataProperty}]`))}function lL(b,w){let{gen:$}=b;$.if(Fb._`Array.isArray(${w})`,()=>{$.assign(Cw.default.vErrors,Fb._`${Cw.default.vErrors} === null ? ${w} : ${Cw.default.vErrors}.concat(${w})`).assign(Cw.default.errors,Fb._`${Cw.default.vErrors}.length`),(0,gL.extendErrors)(b)},()=>b.error())}function pL({schemaEnv:b},w){if(w.async&&!b.$async)throw Error("async keyword in sync schema")}function gD(b,w,$){if($===void 0)throw Error(`keyword "${w}" failed to compile`);return b.scopeValue("keyword",typeof $=="function"?{ref:$}:{ref:$,code:(0,Fb.stringify)($)})}function oL(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")}mD.validSchemaType=oL;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 D=Q.dependencies;if(D===null||D===void 0?void 0:D.some((X)=>!Object.prototype.hasOwnProperty.call(b,X)))throw Error(`parent schema must have dependencies of ${G}: ${D.join(",")}`);if(Q.validateSchema){if(!Q.validateSchema(b[G])){let Y=`keyword "${G}" value is invalid at path "${W}": `+$.errorsText(Q.validateSchema.errors);if(w.validateSchema==="log")$.logger.error(Y);else throw Error(Y)}}}mD.validateKeywordUsage=dL});var tD=j((oD)=>{Object.defineProperty(oD,"__esModule",{value:!0});oD.extendSubschemaMode=oD.extendSubschemaData=oD.getSubschema=void 0;var db=x(),pD=i();function sL(b,{keyword:w,schemaProp:$,schema:W,schemaPath:Q,errSchemaPath:G,topSchemaRef:D}){if(w!==void 0&&W!==void 0)throw Error('both "keyword" and "schema" passed, only one allowed');if(w!==void 0){let X=b.schema[w];return $===void 0?{schema:X,schemaPath:db._`${b.schemaPath}${(0,db.getProperty)(w)}`,errSchemaPath:`${b.errSchemaPath}/${w}`}:{schema:X[$],schemaPath:db._`${b.schemaPath}${(0,db.getProperty)(w)}${(0,db.getProperty)($)}`,errSchemaPath:`${b.errSchemaPath}/${w}/${(0,pD.escapeFragment)($)}`}}if(W!==void 0){if(Q===void 0||G===void 0||D===void 0)throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:W,schemaPath:Q,topSchemaRef:D,errSchemaPath:G}}throw Error('either "keyword" or "schema" must be passed')}oD.getSubschema=sL;function aL(b,w,{dataProp:$,dataPropType:W,data:Q,dataTypes:G,propertyName:D}){if(Q!==void 0&&$!==void 0)throw Error('both "data" and "dataProp" passed, only one allowed');let{gen:X}=w;if($!==void 0){let{errorPath:H,dataPathArr:J,opts:z}=w,O=X.let("data",db._`${w.data}${(0,db.getProperty)($)}`,!0);Y(O),b.errorPath=db.str`${H}${(0,pD.getErrorPath)($,W,z.jsPropertySyntax)}`,b.parentDataProperty=db._`${$}`,b.dataPathArr=[...J,b.parentDataProperty]}if(Q!==void 0){let H=Q instanceof db.Name?Q:X.let("data",Q,!0);if(Y(H),D!==void 0)b.propertyName=D}if(G)b.dataTypes=G;function Y(H){b.data=H,b.dataLevel=w.dataLevel+1,b.dataTypes=[],w.definedProperties=new Set,b.parentData=w.data,b.dataNames=[...w.dataNames,H]}}oD.extendSubschemaData=aL;function bU(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=$}oD.extendSubschemaMode=bU});var j4=j((dT,rD)=>{rD.exports=function b(w,$){if(w===$)return!0;if(w&&$&&typeof w=="object"&&typeof $=="object"){if(w.constructor!==$.constructor)return!1;var W,Q,G;if(Array.isArray(w)){if(W=w.length,W!=$.length)return!1;for(Q=W;Q--!==0;)if(!b(w[Q],$[Q]))return!1;return!0}if(w.constructor===RegExp)return w.source===$.source&&w.flags===$.flags;if(w.valueOf!==Object.prototype.valueOf)return w.valueOf()===$.valueOf();if(w.toString!==Object.prototype.toString)return w.toString()===$.toString();if(G=Object.keys(w),W=G.length,W!==Object.keys($).length)return!1;for(Q=W;Q--!==0;)if(!Object.prototype.hasOwnProperty.call($,G[Q]))return!1;for(Q=W;Q--!==0;){var D=G[Q];if(!b(w[D],$[D]))return!1}return!0}return w!==w&&$!==$}});var sD=j((tT,eD)=>{var Nw=eD.exports=function(b,w,$){if(typeof w=="function")$=w,w={};$=w.cb||$;var W=typeof $=="function"?$:$.pre||function(){},Q=$.post||function(){};X$(w,W,Q,b,"",b)};Nw.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Nw.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Nw.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Nw.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function X$(b,w,$,W,Q,G,D,X,Y,H){if(W&&typeof W=="object"&&!Array.isArray(W)){w(W,Q,G,D,X,Y,H);for(var J in W){var z=W[J];if(Array.isArray(z)){if(J in Nw.arrayKeywords)for(var O=0;O<z.length;O++)X$(b,w,$,z[O],Q+"/"+J+"/"+O,G,Q,J,W,O)}else if(J in Nw.propsKeywords){if(z&&typeof z=="object")for(var q in z)X$(b,w,$,z[q],Q+"/"+J+"/"+WU(q),G,Q,J,W,q)}else if(J in Nw.keywords||b.allKeys&&!(J in Nw.skipKeywords))X$(b,w,$,z,Q+"/"+J,G,Q,J,W)}$(W,Q,G,D,X,Y,H)}}function WU(b){return b.replace(/~/g,"~0").replace(/\//g,"~1")}});var g1=j(($X)=>{Object.defineProperty($X,"__esModule",{value:!0});$X.getSchemaRefs=$X.resolveUrl=$X.normalizeId=$X._getFullPath=$X.getFullPath=$X.inlineRef=void 0;var QU=i(),GU=j4(),DU=sD(),XU=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function YU(b,w=!0){if(typeof b=="boolean")return!0;if(w===!0)return!V4(b);if(!w)return!1;return aD(b)<=w}$X.inlineRef=YU;var HU=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function V4(b){for(let w in b){if(HU.has(w))return!0;let $=b[w];if(Array.isArray($)&&$.some(V4))return!0;if(typeof $=="object"&&V4($))return!0}return!1}function aD(b){let w=0;for(let $ in b){if($==="$ref")return 1/0;if(w++,XU.has($))continue;if(typeof b[$]=="object")(0,QU.eachItem)(b[$],(W)=>w+=aD(W));if(w===1/0)return 1/0}return w}function bX(b,w="",$){if($!==!1)w=ew(w);let W=b.parse(w);return wX(b,W)}$X.getFullPath=bX;function wX(b,w){return b.serialize(w).split("#")[0]+"#"}$X._getFullPath=wX;var JU=/#\/?$/;function ew(b){return b?b.replace(JU,""):""}$X.normalizeId=ew;function zU(b,w,$){return $=ew($),b.resolve(w,$)}$X.resolveUrl=zU;var AU=/^[a-z_][-a-z0-9._]*$/i;function OU(b,w){if(typeof b=="boolean")return{};let{schemaId:$,uriResolver:W}=this.opts,Q=ew(b[$]||w),G={"":Q},D=bX(W,Q,!1),X={},Y=new Set;return DU(b,{allKeys:!0},(z,O,q,B)=>{if(B===void 0)return;let K=D+O,I=G[B];if(typeof z[$]=="string")I=M.call(this,z[$]);v.call(this,z.$anchor),v.call(this,z.$dynamicAnchor),G[O]=I;function M(S){let h=this.opts.uriResolver.resolve;if(S=ew(I?h(I,S):S),Y.has(S))throw J(S);Y.add(S);let R=this.refs[S];if(typeof R=="string")R=this.refs[R];if(typeof R=="object")H(z,R.schema,S);else if(S!==ew(K))if(S[0]==="#")H(z,X[S],S),X[S]=z;else this.refs[S]=K;return S}function v(S){if(typeof S=="string"){if(!AU.test(S))throw Error(`invalid anchor "${S}"`);M.call(this,`#${S}`)}}}),X;function H(z,O,q){if(O!==void 0&&!GU(z,O))throw J(q)}function J(z){return Error(`reference "${z}" resolves to more than one schema`)}}$X.getSchemaRefs=OU});var l1=j((PX)=>{Object.defineProperty(PX,"__esModule",{value:!0});PX.getData=PX.KeywordCxt=PX.validateFunctionCode=void 0;var YX=MD(),QX=n1(),T4=B4(),Y$=n1(),FU=xD(),i1=lD(),N4=tD(),E=x(),k=Qw(),KU=g1(),Gw=i(),m1=c1();function MU(b){if(zX(b)){if(AX(b),JX(b)){jU(b);return}}HX(b,()=>(0,YX.topBoolOrEmptySchema)(b))}PX.validateFunctionCode=MU;function HX({gen:b,validateName:w,schema:$,schemaEnv:W,opts:Q},G){if(Q.code.es5)b.func(w,E._`${k.default.data}, ${k.default.valCxt}`,W.$async,()=>{b.code(E._`"use strict"; ${GX($,Q)}`),ZU(b,Q),b.code(G)});else b.func(w,E._`${k.default.data}, ${IU(Q)}`,W.$async,()=>b.code(GX($,Q)).code(G))}function IU(b){return E._`{${k.default.instancePath}="", ${k.default.parentData}, ${k.default.parentDataProperty}, ${k.default.rootData}=${k.default.data}${b.dynamicRef?E._`, ${k.default.dynamicAnchors}={}`:E.nil}}={}`}function ZU(b,w){b.if(k.default.valCxt,()=>{if(b.var(k.default.instancePath,E._`${k.default.valCxt}.${k.default.instancePath}`),b.var(k.default.parentData,E._`${k.default.valCxt}.${k.default.parentData}`),b.var(k.default.parentDataProperty,E._`${k.default.valCxt}.${k.default.parentDataProperty}`),b.var(k.default.rootData,E._`${k.default.valCxt}.${k.default.rootData}`),w.dynamicRef)b.var(k.default.dynamicAnchors,E._`${k.default.valCxt}.${k.default.dynamicAnchors}`)},()=>{if(b.var(k.default.instancePath,E._`""`),b.var(k.default.parentData,E._`undefined`),b.var(k.default.parentDataProperty,E._`undefined`),b.var(k.default.rootData,k.default.data),w.dynamicRef)b.var(k.default.dynamicAnchors,E._`{}`)})}function jU(b){let{schema:w,opts:$,gen:W}=b;HX(b,()=>{if($.$comment&&w.$comment)qX(b);if(_U(b),W.let(k.default.vErrors,null),W.let(k.default.errors,0),$.unevaluated)VU(b);OX(b),vU(b)});return}function VU(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 GX(b,w){let $=typeof b=="object"&&b[w.schemaId];return $&&(w.code.source||w.code.process)?E._`/*# sourceURL=${$} */`:E.nil}function NU(b,w){if(zX(b)){if(AX(b),JX(b)){TU(b,w);return}}(0,YX.boolOrEmptySchema)(b,w)}function JX({schema:b,self:w}){if(typeof b=="boolean")return!b;for(let $ in b)if(w.RULES.all[$])return!0;return!1}function zX(b){return typeof b.schema!="boolean"}function TU(b,w){let{schema:$,gen:W,opts:Q}=b;if(Q.$comment&&$.$comment)qX(b);SU(b),RU(b);let G=W.const("_errs",k.default.errors);OX(b,G),W.var(w,E._`${G} === ${k.default.errors}`)}function AX(b){(0,Gw.checkUnknownRules)(b),EU(b)}function OX(b,w){if(b.opts.jtd)return DX(b,[],!1,w);let $=(0,QX.getSchemaTypes)(b.schema),W=(0,QX.coerceAndCheckDataType)(b,$);DX(b,$,!W,w)}function EU(b){let{schema:w,errSchemaPath:$,opts:W,self:Q}=b;if(w.$ref&&W.ignoreKeywordsWithRef&&(0,Gw.schemaHasRulesButRef)(w,Q.RULES))Q.logger.warn(`$ref: keywords ignored in schema at path "${$}"`)}function _U(b){let{schema:w,opts:$}=b;if(w.default!==void 0&&$.useDefaults&&$.strictSchema)(0,Gw.checkStrictMode)(b,"default is ignored in the schema root")}function SU(b){let w=b.schema[b.opts.schemaId];if(w)b.baseId=(0,KU.resolveUrl)(b.opts.uriResolver,b.baseId,w)}function RU(b){if(b.schema.$async&&!b.schemaEnv.$async)throw Error("async schema in sync schema")}function qX({gen:b,schemaEnv:w,schema:$,errSchemaPath:W,opts:Q}){let G=$.$comment;if(Q.$comment===!0)b.code(E._`${k.default.self}.logger.log(${G})`);else if(typeof Q.$comment=="function"){let D=E.str`${W}/$comment`,X=b.scopeValue("root",{ref:w.root});b.code(E._`${k.default.self}.opts.$comment(${G}, ${D}, ${X}.schema)`)}}function vU(b){let{gen:w,schemaEnv:$,validateName:W,ValidationError:Q,opts:G}=b;if($.$async)w.if(E._`${k.default.errors} === 0`,()=>w.return(k.default.data),()=>w.throw(E._`new ${Q}(${k.default.vErrors})`));else{if(w.assign(E._`${W}.errors`,k.default.vErrors),G.unevaluated)kU(b);w.return(E._`${k.default.errors} === 0`)}}function kU({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 DX(b,w,$,W){let{gen:Q,schema:G,data:D,allErrors:X,opts:Y,self:H}=b,{RULES:J}=H;if(G.$ref&&(Y.ignoreKeywordsWithRef||!(0,Gw.schemaHasRulesButRef)(G,J))){Q.block(()=>UX(b,"$ref",J.all.$ref.definition));return}if(!Y.jtd)CU(b,w);Q.block(()=>{for(let O of J.rules)z(O);z(J.post)});function z(O){if(!(0,T4.shouldUseGroup)(G,O))return;if(O.type){if(Q.if((0,Y$.checkDataType)(O.type,D,Y.strictNumbers)),XX(b,O),w.length===1&&w[0]===O.type&&$)Q.else(),(0,Y$.reportTypeError)(b);Q.endIf()}else XX(b,O);if(!X)Q.if(E._`${k.default.errors} === ${W||0}`)}}function XX(b,w){let{gen:$,schema:W,opts:{useDefaults:Q}}=b;if(Q)(0,FU.assignDefaults)(b,w.type);$.block(()=>{for(let G of w.rules)if((0,T4.shouldUseRule)(W,G))UX(b,G.keyword,G.definition,w.type)})}function CU(b,w){if(b.schemaEnv.meta||!b.opts.strictTypes)return;if(uU(b,w),!b.opts.allowUnionTypes)xU(b,w);yU(b,b.dataTypes)}function uU(b,w){if(!w.length)return;if(!b.dataTypes.length){b.dataTypes=w;return}w.forEach(($)=>{if(!LX(b.dataTypes,$))E4(b,`type "${$}" not allowed by context "${b.dataTypes.join(",")}"`)}),fU(b,w)}function xU(b,w){if(w.length>1&&!(w.length===2&&w.includes("null")))E4(b,"use allowUnionTypes to allow union type keyword")}function yU(b,w){let $=b.self.RULES.all;for(let W in $){let Q=$[W];if(typeof Q=="object"&&(0,T4.shouldUseRule)(b.schema,Q)){let{type:G}=Q.definition;if(G.length&&!G.some((D)=>hU(w,D)))E4(b,`missing type "${G.join(",")}" for keyword "${W}"`)}}}function hU(b,w){return b.includes(w)||w==="number"&&b.includes("integer")}function LX(b,w){return b.includes(w)||w==="integer"&&b.includes("number")}function fU(b,w){let $=[];for(let W of b.dataTypes)if(LX(w,W))$.push(W);else if(w.includes("integer")&&W==="number")$.push("integer");b.dataTypes=$}function E4(b,w){let $=b.schemaEnv.baseId+b.errSchemaPath;w+=` at "${$}" (strictTypes)`,(0,Gw.checkStrictMode)(b,w,b.opts.strictTypes)}class _4{constructor(b,w,$){if((0,i1.validateKeywordUsage)(b,w,$),this.gen=b.gen,this.allErrors=b.allErrors,this.keyword=$,this.data=b.data,this.schema=b.schema[$],this.$data=w.$data&&b.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Gw.schemaRefOrVal)(b,this.schema,$,this.$data),this.schemaType=w.schemaType,this.parentSchema=b.schema,this.params={},this.it=b,this.def=w,this.$data)this.schemaCode=b.gen.const("vSchema",BX(this.$data,b));else if(this.schemaCode=this.schemaValue,!(0,i1.validSchemaType)(this.schema,w.schemaType,w.allowUndefined))throw Error(`${$} value must be ${JSON.stringify(w.schemaType)}`);if("code"in w?w.trackErrors:w.errors!==!1)this.errsCount=b.gen.const("_errs",k.default.errors)}result(b,w,$){this.failResult((0,E.not)(b),w,$)}failResult(b,w,$){if(this.gen.if(b),$)$();else this.error();if(w){if(this.gen.else(),w(),this.allErrors)this.gen.endIf()}else if(this.allErrors)this.gen.endIf();else this.gen.else()}pass(b,w){this.failResult((0,E.not)(b),void 0,w)}fail(b){if(b===void 0){if(this.error(),!this.allErrors)this.gen.if(!1);return}if(this.gen.if(b),this.error(),this.allErrors)this.gen.endIf();else this.gen.else()}fail$data(b){if(!this.$data)return this.fail(b);let{schemaCode:w}=this;this.fail(E._`${w} !== undefined && (${(0,E.or)(this.invalid$data(),b)})`)}error(b,w,$){if(w){this.setParams(w),this._error(b,$),this.setParams({});return}this._error(b,$)}_error(b,w){(b?m1.reportExtraError:m1.reportError)(this,this.def.error,w)}$dataError(){(0,m1.reportError)(this,this.def.$dataError||m1.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error('add "trackErrors" to keyword definition');(0,m1.resetErrorsCount)(this.gen,this.errsCount)}ok(b){if(!this.allErrors)this.gen.if(b)}setParams(b,w){if(w)Object.assign(this.params,b);else this.params=b}block$data(b,w,$=E.nil){this.gen.block(()=>{this.check$data(b,$),w()})}check$data(b=E.nil,w=E.nil){if(!this.$data)return;let{gen:$,schemaCode:W,schemaType:Q,def:G}=this;if($.if((0,E.or)(E._`${W} === undefined`,w)),b!==E.nil)$.assign(b,!0);if(Q.length||G.validateSchema){if($.elseIf(this.invalid$data()),this.$dataError(),b!==E.nil)$.assign(b,!1)}$.else()}invalid$data(){let{gen:b,schemaCode:w,schemaType:$,def:W,it:Q}=this;return(0,E.or)(G(),D());function G(){if($.length){if(!(w instanceof E.Name))throw Error("ajv implementation error");let X=Array.isArray($)?$:[$];return E._`${(0,Y$.checkDataTypes)(X,w,Q.opts.strictNumbers,Y$.DataType.Wrong)}`}return E.nil}function D(){if(W.validateSchema){let X=b.scopeValue("validate$data",{ref:W.validateSchema});return E._`!${X}(${w})`}return E.nil}}subschema(b,w){let $=(0,N4.getSubschema)(this.it,b);(0,N4.extendSubschemaData)($,this.it,b),(0,N4.extendSubschemaMode)($,b);let W={...this.it,...$,items:void 0,props:void 0};return NU(W,w),W}mergeEvaluated(b,w){let{it:$,gen:W}=this;if(!$.opts.unevaluated)return;if($.props!==!0&&b.props!==void 0)$.props=Gw.mergeEvaluated.props(W,b.props,$.props,w);if($.items!==!0&&b.items!==void 0)$.items=Gw.mergeEvaluated.items(W,b.items,$.items,w)}mergeValidEvaluated(b,w){let{it:$,gen:W}=this;if($.opts.unevaluated&&($.props!==!0||$.items!==!0))return W.if(w,()=>this.mergeEvaluated(b,E.Name)),!0}}PX.KeywordCxt=_4;function UX(b,w,$,W){let Q=new _4(b,$,w);if("code"in $)$.code(Q,W);else if(Q.$data&&$.validate)(0,i1.funcKeywordCode)(Q,$);else if("macro"in $)(0,i1.macroKeywordCode)(Q,$);else if($.compile||$.validate)(0,i1.funcKeywordCode)(Q,$)}var cU=/^\/(?:[^~]|~0|~1)*$/,nU=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function BX(b,{dataLevel:w,dataNames:$,dataPathArr:W}){let Q,G;if(b==="")return k.default.rootData;if(b[0]==="/"){if(!cU.test(b))throw Error(`Invalid JSON-pointer: ${b}`);Q=b,G=k.default.rootData}else{let H=nU.exec(b);if(!H)throw Error(`Invalid JSON-pointer: ${b}`);let J=+H[1];if(Q=H[2],Q==="#"){if(J>=w)throw Error(Y("property/index",J));return W[w-J]}if(J>w)throw Error(Y("data",J));if(G=$[w-J],!Q)return G}let D=G,X=Q.split("/");for(let H of X)if(H)G=E._`${G}${(0,E.getProperty)((0,Gw.unescapeJsonPointer)(H))}`,D=E._`${D} && ${G}`;return D;function Y(H,J){return`Cannot access ${H} ${J} levels up, current level is ${w}`}}PX.getData=BX});var H$=j((MX)=>{Object.defineProperty(MX,"__esModule",{value:!0});class KX extends Error{constructor(b){super("validation failed");this.errors=b,this.ajv=this.validation=!0}}MX.default=KX});var p1=j((ZX)=>{Object.defineProperty(ZX,"__esModule",{value:!0});var S4=g1();class IX extends Error{constructor(b,w,$,W){super(W||`can't resolve reference ${$} from id ${w}`);this.missingRef=(0,S4.resolveUrl)(b,w,$),this.missingSchema=(0,S4.normalizeId)((0,S4.getFullPath)(b,this.missingRef))}}ZX.default=IX});var z$=j((NX)=>{Object.defineProperty(NX,"__esModule",{value:!0});NX.resolveSchema=NX.getCompilingSchema=NX.resolveRef=NX.compileSchema=NX.SchemaEnv=void 0;var cb=x(),pU=H$(),uw=Qw(),nb=g1(),jX=i(),oU=l1();class o1{constructor(b){var w;this.refs={},this.dynamicAnchors={};let $;if(typeof b.schema=="object")$=b.schema;this.schema=b.schema,this.schemaId=b.schemaId,this.root=b.root||this,this.baseId=(w=b.baseId)!==null&&w!==void 0?w:(0,nb.normalizeId)($===null||$===void 0?void 0:$[b.schemaId||"$id"]),this.schemaPath=b.schemaPath,this.localRefs=b.localRefs,this.meta=b.meta,this.$async=$===null||$===void 0?void 0:$.$async,this.refs={}}}NX.SchemaEnv=o1;function v4(b){let w=VX.call(this,b);if(w)return w;let $=(0,nb.getFullPath)(this.opts.uriResolver,b.root.baseId),{es5:W,lines:Q}=this.opts.code,{ownProperties:G}=this.opts,D=new cb.CodeGen(this.scope,{es5:W,lines:Q,ownProperties:G}),X;if(b.$async)X=D.scopeValue("Error",{ref:pU.default,code:cb._`require("ajv/dist/runtime/validation_error").default`});let Y=D.scopeName("validate");b.validateName=Y;let H={gen:D,allErrors:this.opts.allErrors,data:uw.default.data,parentData:uw.default.parentData,parentDataProperty:uw.default.parentDataProperty,dataNames:[uw.default.data],dataPathArr:[cb.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:D.scopeValue("schema",this.opts.code.source===!0?{ref:b.schema,code:(0,cb.stringify)(b.schema)}:{ref:b.schema}),validateName:Y,ValidationError:X,schema:b.schema,schemaEnv:b,rootId:$,baseId:b.baseId||$,schemaPath:cb.nil,errSchemaPath:b.schemaPath||(this.opts.jtd?"":"#"),errorPath:cb._`""`,opts:this.opts,self:this},J;try{this._compilations.add(b),(0,oU.validateFunctionCode)(H),D.optimize(this.opts.code.optimize);let z=D.toString();if(J=`${D.scopeRefs(uw.default.scope)}return ${z}`,this.opts.code.process)J=this.opts.code.process(J,b);let q=Function(`${uw.default.self}`,`${uw.default.scope}`,J)(this,this.scope.get());if(this.scope.value(Y,{ref:q}),q.errors=null,q.schema=b.schema,q.schemaEnv=b,b.$async)q.$async=!0;if(this.opts.code.source===!0)q.source={validateName:Y,validateCode:z,scopeValues:D._values};if(this.opts.unevaluated){let{props:B,items:K}=H;if(q.evaluated={props:B instanceof cb.Name?void 0:B,items:K instanceof cb.Name?void 0:K,dynamicProps:B instanceof cb.Name,dynamicItems:K instanceof cb.Name},q.source)q.source.evaluated=(0,cb.stringify)(q.evaluated)}return b.validate=q,b}catch(z){if(delete b.validate,delete b.validateName,J)this.logger.error("Error compiling schema, function code:",J);throw z}finally{this._compilations.delete(b)}}NX.compileSchema=v4;function dU(b,w,$){var W;$=(0,nb.resolveUrl)(this.opts.uriResolver,w,$);let Q=b.refs[$];if(Q)return Q;let G=eU.call(this,b,$);if(G===void 0){let D=(W=b.localRefs)===null||W===void 0?void 0:W[$],{schemaId:X}=this.opts;if(D)G=new o1({schema:D,schemaId:X,root:b,baseId:w})}if(G===void 0)return;return b.refs[$]=tU.call(this,G)}NX.resolveRef=dU;function tU(b){if((0,nb.inlineRef)(b.schema,this.opts.inlineRefs))return b.schema;return b.validate?b:v4.call(this,b)}function VX(b){for(let w of this._compilations)if(rU(w,b))return w}NX.getCompilingSchema=VX;function rU(b,w){return b.schema===w.schema&&b.root===w.root&&b.baseId===w.baseId}function eU(b,w){let $;while(typeof($=this.refs[w])=="string")w=$;return $||this.schemas[w]||J$.call(this,b,w)}function J$(b,w){let $=this.opts.uriResolver.parse(w),W=(0,nb._getFullPath)(this.opts.uriResolver,$),Q=(0,nb.getFullPath)(this.opts.uriResolver,b.baseId,void 0);if(Object.keys(b.schema).length>0&&W===Q)return R4.call(this,$,b);let G=(0,nb.normalizeId)(W),D=this.refs[G]||this.schemas[G];if(typeof D=="string"){let X=J$.call(this,b,D);if(typeof(X===null||X===void 0?void 0:X.schema)!=="object")return;return R4.call(this,$,X)}if(typeof(D===null||D===void 0?void 0:D.schema)!=="object")return;if(!D.validate)v4.call(this,D);if(G===(0,nb.normalizeId)(w)){let{schema:X}=D,{schemaId:Y}=this.opts,H=X[Y];if(H)Q=(0,nb.resolveUrl)(this.opts.uriResolver,Q,H);return new o1({schema:X,schemaId:Y,root:b,baseId:Q})}return R4.call(this,$,D)}NX.resolveSchema=J$;var sU=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function R4(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,jX.unescapeFragment)(X)];if(Y===void 0)return;$=Y;let H=typeof $==="object"&&$[this.opts.schemaId];if(!sU.has(X)&&H)w=(0,nb.resolveUrl)(this.opts.uriResolver,w,H)}let G;if(typeof $!="boolean"&&$.$ref&&!(0,jX.schemaHasRulesButRef)($,this.RULES)){let X=(0,nb.resolveUrl)(this.opts.uriResolver,w,$.$ref);G=J$.call(this,W,X)}let{schemaId:D}=this.opts;if(G=G||new o1({schema:$,schemaId:D,root:W,baseId:w}),G.schema!==G.root.schema)return G;return}});var EX=j((wE,W3)=>{W3.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 C4=j(($E,vX)=>{var Q3=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),SX=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 k4(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 G3=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function _X(b){return b.length=0,!0}function D3(b,w,$){if(b.length){let W=k4(b);if(W!=="")w.push(W);else return $.error=!0,!1;b.length=0}return!0}function X3(b){let w=0,$={error:!1,address:"",zone:""},W=[],Q=[],G=!1,D=!1,X=D3;for(let Y=0;Y<b.length;Y++){let H=b[Y];if(H==="["||H==="]")continue;if(H===":"){if(G===!0)D=!0;if(!X(Q,W,$))break;if(++w>7){$.error=!0;break}if(Y>0&&b[Y-1]===":")G=!0;W.push(":");continue}else if(H==="%"){if(!X(Q,W,$))break;X=_X}else{Q.push(H);continue}}if(Q.length)if(X===_X)$.zone=Q.join("");else if(D)W.push(Q.join(""));else W.push(k4(Q));return $.address=W.join(""),$}function RX(b){if(Y3(b,":")<2)return{host:b,isIPV6:!1};let w=X3(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 Y3(b,w){let $=0;for(let W=0;W<b.length;W++)if(b[W]===w)$++;return $}function H3(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 J3(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 z3(b){let w=[];if(b.userinfo!==void 0)w.push(b.userinfo),w.push("@");if(b.host!==void 0){let $=unescape(b.host);if(!SX($)){let W=RX($);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}vX.exports={nonSimpleDomain:G3,recomposeAuthority:z3,normalizeComponentEncoding:J3,removeDotSegments:H3,isIPv4:SX,isUUID:Q3,normalizeIPv6:RX,stringArrayToHexStripped:k4}});var yX=j((WE,xX)=>{var{isUUID:A3}=C4(),O3=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,q3=["http","https","ws","wss","urn","urn:uuid"];function L3(b){return q3.indexOf(b)!==-1}function u4(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 kX(b){if(!b.host)b.error=b.error||"HTTP URIs must have a host.";return b}function CX(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 U3(b){return b.secure=u4(b),b.resourceName=(b.path||"/")+(b.query?"?"+b.query:""),b.path=void 0,b.query=void 0,b}function B3(b){if(b.port===(u4(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 P3(b,w){if(!b.path)return b.error="URN can not be parsed",b;let $=b.path.match(O3);if($){let W=w.scheme||b.scheme||"urn";b.nid=$[1].toLowerCase(),b.nss=$[2];let Q=`${W}:${w.nid||b.nid}`,G=x4(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 F3(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=x4(Q);if(G)b=G.serialize(b,w);let D=b,X=b.nss;return D.path=`${W||w.nid}:${X}`,w.skipEscape=!0,D}function K3(b,w){let $=b;if($.uuid=$.nss,$.nss=void 0,!w.tolerant&&(!$.uuid||!A3($.uuid)))$.error=$.error||"UUID is not valid.";return $}function M3(b){let w=b;return w.nss=(b.uuid||"").toLowerCase(),w}var uX={scheme:"http",domainHost:!0,parse:kX,serialize:CX},I3={scheme:"https",domainHost:uX.domainHost,parse:kX,serialize:CX},A$={scheme:"ws",domainHost:!0,parse:U3,serialize:B3},Z3={scheme:"wss",domainHost:A$.domainHost,parse:A$.parse,serialize:A$.serialize},j3={scheme:"urn",parse:P3,serialize:F3,skipNormalize:!0},V3={scheme:"urn:uuid",parse:K3,serialize:M3,skipNormalize:!0},O$={http:uX,https:I3,ws:A$,wss:Z3,urn:j3,"urn:uuid":V3};Object.setPrototypeOf(O$,null);function x4(b){return b&&(O$[b]||O$[b.toLowerCase()])||void 0}xX.exports={wsIsSecure:u4,SCHEMES:O$,isValidSchemeName:L3,getSchemeHandler:x4}});var cX=j((QE,L$)=>{var{normalizeIPv6:N3,removeDotSegments:d1,recomposeAuthority:T3,normalizeComponentEncoding:q$,isIPv4:E3,nonSimpleDomain:_3}=C4(),{SCHEMES:S3,getSchemeHandler:hX}=yX();function R3(b,w){if(typeof b==="string")b=tb(Dw(b,w),w);else if(typeof b==="object")b=Dw(tb(b,w),w);return b}function v3(b,w,$){let W=$?Object.assign({scheme:"null"},$):{scheme:"null"},Q=fX(Dw(b,W),Dw(w,W),W,!0);return W.skipEscape=!0,tb(Q,W)}function fX(b,w,$,W){let Q={};if(!W)b=Dw(tb(b,$),$),w=Dw(tb(w,$),$);if($=$||{},!$.tolerant&&w.scheme)Q.scheme=w.scheme,Q.userinfo=w.userinfo,Q.host=w.host,Q.port=w.port,Q.path=d1(w.path||""),Q.query=w.query;else{if(w.userinfo!==void 0||w.host!==void 0||w.port!==void 0)Q.userinfo=w.userinfo,Q.host=w.host,Q.port=w.port,Q.path=d1(w.path||""),Q.query=w.query;else{if(!w.path)if(Q.path=b.path,w.query!==void 0)Q.query=w.query;else Q.query=b.query;else{if(w.path[0]==="/")Q.path=d1(w.path);else{if((b.userinfo!==void 0||b.host!==void 0||b.port!==void 0)&&!b.path)Q.path="/"+w.path;else if(!b.path)Q.path=w.path;else Q.path=b.path.slice(0,b.path.lastIndexOf("/")+1)+w.path;Q.path=d1(Q.path)}Q.query=w.query}Q.userinfo=b.userinfo,Q.host=b.host,Q.port=b.port}Q.scheme=b.scheme}return Q.fragment=w.fragment,Q}function k3(b,w,$){if(typeof b==="string")b=unescape(b),b=tb(q$(Dw(b,$),!0),{...$,skipEscape:!0});else if(typeof b==="object")b=tb(q$(b,!0),{...$,skipEscape:!0});if(typeof w==="string")w=unescape(w),w=tb(q$(Dw(w,$),!0),{...$,skipEscape:!0});else if(typeof w==="object")w=tb(q$(w,!0),{...$,skipEscape:!0});return b.toLowerCase()===w.toLowerCase()}function tb(b,w){let $={host:b.host,scheme:b.scheme,userinfo:b.userinfo,port:b.port,path:b.path,query:b.query,nid:b.nid,nss:b.nss,uuid:b.uuid,fragment:b.fragment,reference:b.reference,resourceName:b.resourceName,secure:b.secure,error:""},W=Object.assign({},w),Q=[],G=hX(W.scheme||$.scheme);if(G&&G.serialize)G.serialize($,W);if($.path!==void 0)if(!W.skipEscape){if($.path=escape($.path),$.scheme!==void 0)$.path=$.path.split("%3A").join(":")}else $.path=unescape($.path);if(W.reference!=="suffix"&&$.scheme)Q.push($.scheme,":");let D=T3($);if(D!==void 0){if(W.reference!=="suffix")Q.push("//");if(Q.push(D),$.path&&$.path[0]!=="/")Q.push("/")}if($.path!==void 0){let X=$.path;if(!W.absolutePath&&(!G||!G.absolutePath))X=d1(X);if(D===void 0&&X[0]==="/"&&X[1]==="/")X="/%2F"+X.slice(2);Q.push(X)}if($.query!==void 0)Q.push("?",$.query);if($.fragment!==void 0)Q.push("#",$.fragment);return Q.join("")}var C3=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function Dw(b,w){let $=Object.assign({},w),W={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},Q=!1;if($.reference==="suffix")if($.scheme)b=$.scheme+":"+b;else b="//"+b;let G=b.match(C3);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(E3(W.host)===!1){let Y=N3(W.host);W.host=Y.host.toLowerCase(),Q=Y.isIPV6}else Q=!0;if(W.scheme===void 0&&W.userinfo===void 0&&W.host===void 0&&W.port===void 0&&W.query===void 0&&!W.path)W.reference="same-document";else if(W.scheme===void 0)W.reference="relative";else if(W.fragment===void 0)W.reference="absolute";else W.reference="uri";if($.reference&&$.reference!=="suffix"&&$.reference!==W.reference)W.error=W.error||"URI is not a "+$.reference+" reference.";let D=hX($.scheme||W.scheme);if(!$.unicodeSupport&&(!D||!D.unicodeSupport)){if(W.host&&($.domainHost||D&&D.domainHost)&&Q===!1&&_3(W.host))try{W.host=URL.domainToASCII(W.host.toLowerCase())}catch(X){W.error=W.error||"Host's domain name can not be converted to ASCII: "+X}}if(!D||D&&!D.skipNormalize){if(b.indexOf("%")!==-1){if(W.scheme!==void 0)W.scheme=unescape(W.scheme);if(W.host!==void 0)W.host=unescape(W.host)}if(W.path)W.path=escape(unescape(W.path));if(W.fragment)W.fragment=encodeURI(decodeURIComponent(W.fragment))}if(D&&D.parse)D.parse(W,$)}else W.error=W.error||"URI can not be parsed.";return W}var y4={SCHEMES:S3,normalize:R3,resolve:v3,resolveComponent:fX,equal:k3,serialize:tb,parse:Dw};L$.exports=y4;L$.exports.default=y4;L$.exports.fastUri=y4});var mX=j((gX)=>{Object.defineProperty(gX,"__esModule",{value:!0});var nX=cX();nX.code='require("ajv/dist/runtime/uri").default';gX.default=nX});var eX=j((Xw)=>{Object.defineProperty(Xw,"__esModule",{value:!0});Xw.CodeGen=Xw.Name=Xw.nil=Xw.stringify=Xw.str=Xw._=Xw.KeywordCxt=void 0;var x3=l1();Object.defineProperty(Xw,"KeywordCxt",{enumerable:!0,get:function(){return x3.KeywordCxt}});var sw=x();Object.defineProperty(Xw,"_",{enumerable:!0,get:function(){return sw._}});Object.defineProperty(Xw,"str",{enumerable:!0,get:function(){return sw.str}});Object.defineProperty(Xw,"stringify",{enumerable:!0,get:function(){return sw.stringify}});Object.defineProperty(Xw,"nil",{enumerable:!0,get:function(){return sw.nil}});Object.defineProperty(Xw,"Name",{enumerable:!0,get:function(){return sw.Name}});Object.defineProperty(Xw,"CodeGen",{enumerable:!0,get:function(){return sw.CodeGen}});var y3=H$(),dX=p1(),h3=U4(),t1=z$(),f3=x(),r1=g1(),U$=n1(),f4=i(),iX=EX(),c3=mX(),tX=(b,w)=>new RegExp(b,w);tX.code="new RegExp";var n3=["removeAdditional","useDefaults","coerceTypes"],g3=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),m3={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."},i3={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},lX=200;function l3(b){var w,$,W,Q,G,D,X,Y,H,J,z,O,q,B,K,I,M,v,S,h,R,pb,sb,p$,o$;let J1=b.strict,d$=(w=b.code)===null||w===void 0?void 0:w.optimize,kW=d$===!0||d$===void 0?1:d$||0,CW=(W=($=b.code)===null||$===void 0?void 0:$.regExp)!==null&&W!==void 0?W:tX,mz=(Q=b.uriResolver)!==null&&Q!==void 0?Q:c3.default;return{strictSchema:(D=(G=b.strictSchema)!==null&&G!==void 0?G:J1)!==null&&D!==void 0?D:!0,strictNumbers:(Y=(X=b.strictNumbers)!==null&&X!==void 0?X:J1)!==null&&Y!==void 0?Y:!0,strictTypes:(J=(H=b.strictTypes)!==null&&H!==void 0?H:J1)!==null&&J!==void 0?J:"log",strictTuples:(O=(z=b.strictTuples)!==null&&z!==void 0?z:J1)!==null&&O!==void 0?O:"log",strictRequired:(B=(q=b.strictRequired)!==null&&q!==void 0?q:J1)!==null&&B!==void 0?B:!1,code:b.code?{...b.code,optimize:kW,regExp:CW}:{optimize:kW,regExp:CW},loopRequired:(K=b.loopRequired)!==null&&K!==void 0?K:lX,loopEnum:(I=b.loopEnum)!==null&&I!==void 0?I:lX,meta:(M=b.meta)!==null&&M!==void 0?M:!0,messages:(v=b.messages)!==null&&v!==void 0?v:!0,inlineRefs:(S=b.inlineRefs)!==null&&S!==void 0?S:!0,schemaId:(h=b.schemaId)!==null&&h!==void 0?h:"$id",addUsedSchema:(R=b.addUsedSchema)!==null&&R!==void 0?R:!0,validateSchema:(pb=b.validateSchema)!==null&&pb!==void 0?pb:!0,validateFormats:(sb=b.validateFormats)!==null&&sb!==void 0?sb:!0,unicodeRegExp:(p$=b.unicodeRegExp)!==null&&p$!==void 0?p$:!0,int32range:(o$=b.int32range)!==null&&o$!==void 0?o$:!0,uriResolver:mz}}class B${constructor(b={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,b=this.opts={...b,...l3(b)};let{es5:w,lines:$}=this.opts.code;this.scope=new f3.ValueScope({scope:{},prefixes:g3,es5:w,lines:$}),this.logger=e3(b.logger);let W=b.validateFormats;if(b.validateFormats=!1,this.RULES=(0,h3.getRules)(),pX.call(this,m3,b,"NOT SUPPORTED"),pX.call(this,i3,b,"DEPRECATED","warn"),this._metaOpts=t3.call(this),b.formats)o3.call(this);if(this._addVocabularies(),this._addDefaultMetaSchema(),b.keywords)d3.call(this,b.keywords);if(typeof b.meta=="object")this.addMetaSchema(b.meta);p3.call(this),b.validateFormats=W}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:b,meta:w,schemaId:$}=this.opts,W=iX;if($==="id")W={...iX},W.id=W.$id,delete W.$id;if(w&&b)this.addMetaSchema(W,W[$],!1)}defaultMeta(){let{meta:b,schemaId:w}=this.opts;return this.opts.defaultMeta=typeof b=="object"?b[w]||b:void 0}validate(b,w){let $;if(typeof b=="string"){if($=this.getSchema(b),!$)throw Error(`no schema with key or ref "${b}"`)}else $=this.compile(b);let W=$(w);if(!("$async"in $))this.errors=$.errors;return W}compile(b,w){let $=this._addSchema(b,w);return $.validate||this._compileSchemaEnv($)}compileAsync(b,w){if(typeof this.opts.loadSchema!="function")throw Error("options.loadSchema should be a function");let{loadSchema:$}=this.opts;return W.call(this,b,w);async function W(H,J){await Q.call(this,H.$schema);let z=this._addSchema(H,J);return z.validate||G.call(this,z)}async function Q(H){if(H&&!this.getSchema(H))await W.call(this,{$ref:H},!0)}async function G(H){try{return this._compileSchemaEnv(H)}catch(J){if(!(J instanceof dX.default))throw J;return D.call(this,J),await X.call(this,J.missingSchema),G.call(this,H)}}function D({missingSchema:H,missingRef:J}){if(this.refs[H])throw Error(`AnySchema ${H} is loaded but ${J} cannot be resolved`)}async function X(H){let J=await Y.call(this,H);if(!this.refs[H])await Q.call(this,J.$schema);if(!this.refs[H])this.addSchema(J,H,w)}async function Y(H){let J=this._loading[H];if(J)return J;try{return await(this._loading[H]=$(H))}finally{delete this._loading[H]}}}addSchema(b,w,$,W=this.opts.validateSchema){if(Array.isArray(b)){for(let G of b)this.addSchema(G,void 0,$,W);return this}let Q;if(typeof b==="object"){let{schemaId:G}=this.opts;if(Q=b[G],Q!==void 0&&typeof Q!="string")throw Error(`schema ${G} must be string`)}return w=(0,r1.normalizeId)(w||Q),this._checkUnique(w),this.schemas[w]=this._addSchema(b,$,w,W,!0),this}addMetaSchema(b,w,$=this.opts.validateSchema){return this.addSchema(b,w,!0,$),this}validateSchema(b,w){if(typeof b=="boolean")return!0;let $;if($=b.$schema,$!==void 0&&typeof $!="string")throw Error("$schema must be a string");if($=$||this.opts.defaultMeta||this.defaultMeta(),!$)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let W=this.validate($,b);if(!W&&w){let Q="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(Q);else throw Error(Q)}return W}getSchema(b){let w;while(typeof(w=oX.call(this,b))=="string")b=w;if(w===void 0){let{schemaId:$}=this.opts,W=new t1.SchemaEnv({schema:{},schemaId:$});if(w=t1.resolveSchema.call(this,W,b),!w)return;this.refs[b]=w}return w.validate||this._compileSchemaEnv(w)}removeSchema(b){if(b instanceof RegExp)return this._removeAllSchemas(this.schemas,b),this._removeAllSchemas(this.refs,b),this;switch(typeof b){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let w=oX.call(this,b);if(typeof w=="object")this._cache.delete(w.schema);return delete this.schemas[b],delete this.refs[b],this}case"object":{let w=b;this._cache.delete(w);let $=b[this.opts.schemaId];if($)$=(0,r1.normalizeId)($),delete this.schemas[$],delete this.refs[$];return this}default:throw Error("ajv.removeSchema: invalid parameter")}}addVocabulary(b){for(let w of b)this.addKeyword(w);return this}addKeyword(b,w){let $;if(typeof b=="string"){if($=b,typeof w=="object")this.logger.warn("these parameters are deprecated, see docs for addKeyword"),w.keyword=$}else if(typeof b=="object"&&w===void 0){if(w=b,$=w.keyword,Array.isArray($)&&!$.length)throw Error("addKeywords: keyword must be string or non-empty array")}else throw Error("invalid addKeywords parameters");if(a3.call(this,$,w),!w)return(0,f4.eachItem)($,(Q)=>h4.call(this,Q)),this;wB.call(this,w);let W={...w,type:(0,U$.getJSONTypes)(w.type),schemaType:(0,U$.getJSONTypes)(w.schemaType)};return(0,f4.eachItem)($,W.type.length===0?(Q)=>h4.call(this,Q,W):(Q)=>W.type.forEach((G)=>h4.call(this,Q,W,G))),this}getKeyword(b){let w=this.RULES.all[b];return typeof w=="object"?w.definition:!!w}removeKeyword(b){let{RULES:w}=this;delete w.keywords[b],delete w.all[b];for(let $ of w.rules){let W=$.rules.findIndex((Q)=>Q.keyword===b);if(W>=0)$.rules.splice(W,1)}return this}addFormat(b,w){if(typeof w=="string")w=new RegExp(w);return this.formats[b]=w,this}errorsText(b=this.errors,{separator:w=", ",dataVar:$="data"}={}){if(!b||b.length===0)return"No errors";return b.map((W)=>`${$}${W.instancePath} ${W.message}`).reduce((W,Q)=>W+w+Q)}$dataMetaSchema(b,w){let $=this.RULES.all;b=JSON.parse(JSON.stringify(b));for(let W of w){let Q=W.split("/").slice(1),G=b;for(let D of Q)G=G[D];for(let D in $){let X=$[D];if(typeof X!="object")continue;let{$data:Y}=X.definition,H=G[D];if(Y&&H)G[D]=rX(H)}}return b}_removeAllSchemas(b,w){for(let $ in b){let W=b[$];if(!w||w.test($)){if(typeof W=="string")delete b[$];else if(W&&!W.meta)this._cache.delete(W.schema),delete b[$]}}}_addSchema(b,w,$,W=this.opts.validateSchema,Q=this.opts.addUsedSchema){let G,{schemaId:D}=this.opts;if(typeof b=="object")G=b[D];else if(this.opts.jtd)throw Error("schema must be object");else if(typeof b!="boolean")throw Error("schema must be object or boolean");let X=this._cache.get(b);if(X!==void 0)return X;$=(0,r1.normalizeId)(G||$);let Y=r1.getSchemaRefs.call(this,b,$);if(X=new t1.SchemaEnv({schema:b,schemaId:D,meta:w,baseId:$,localRefs:Y}),this._cache.set(X.schema,X),Q&&!$.startsWith("#")){if($)this._checkUnique($);this.refs[$]=X}if(W)this.validateSchema(b,!0);return X}_checkUnique(b){if(this.schemas[b]||this.refs[b])throw Error(`schema with key or id "${b}" already exists`)}_compileSchemaEnv(b){if(b.meta)this._compileMetaSchema(b);else t1.compileSchema.call(this,b);if(!b.validate)throw Error("ajv implementation error");return b.validate}_compileMetaSchema(b){let w=this.opts;this.opts=this._metaOpts;try{t1.compileSchema.call(this,b)}finally{this.opts=w}}}B$.ValidationError=y3.default;B$.MissingRefError=dX.default;Xw.default=B$;function pX(b,w,$,W="error"){for(let Q in b){let G=Q;if(G in w)this.logger[W](`${$}: option ${Q}. ${b[G]}`)}}function oX(b){return b=(0,r1.normalizeId)(b),this.schemas[b]||this.refs[b]}function p3(){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 o3(){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 t3(){let b={...this.opts};for(let w of n3)delete b[w];return b}var r3={log(){},warn(){},error(){}};function e3(b){if(b===!1)return r3;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 s3=/^[a-z_$][a-z0-9_$:-]*$/i;function a3(b,w){let{RULES:$}=this;if((0,f4.eachItem)(b,(W)=>{if($.keywords[W])throw Error(`Keyword ${W} is already defined`);if(!s3.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 h4(b,w,$){var W;let Q=w===null||w===void 0?void 0:w.post;if($&&Q)throw Error('keyword with "post" flag cannot have "type"');let{RULES:G}=this,D=Q?G.post:G.rules.find(({type:Y})=>Y===$);if(!D)D={type:$,rules:[]},G.rules.push(D);if(G.keywords[b]=!0,!w)return;let X={keyword:b,definition:{...w,type:(0,U$.getJSONTypes)(w.type),schemaType:(0,U$.getJSONTypes)(w.schemaType)}};if(w.before)bB.call(this,D,X,w.before);else D.rules.push(X);G.all[b]=X,(W=w.implements)===null||W===void 0||W.forEach((Y)=>this.addKeyword(Y))}function bB(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 wB(b){let{metaSchema:w}=b;if(w===void 0)return;if(b.$data&&this.opts.$data)w=rX(w);b.validateSchema=this.compile(w,!0)}var $B={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function rX(b){return{anyOf:[b,$B]}}});var aX=j((sX)=>{Object.defineProperty(sX,"__esModule",{value:!0});var GB={keyword:"id",code(){throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};sX.default=GB});var GY=j((WY)=>{Object.defineProperty(WY,"__esModule",{value:!0});WY.callRef=WY.getValidate=void 0;var XB=p1(),bY=Cb(),jb=x(),aw=Qw(),wY=z$(),P$=i(),YB={keyword:"$ref",schemaType:"string",code(b){let{gen:w,schema:$,it:W}=b,{baseId:Q,schemaEnv:G,validateName:D,opts:X,self:Y}=W,{root:H}=G;if(($==="#"||$==="#/")&&Q===H.baseId)return z();let J=wY.resolveRef.call(Y,H,Q,$);if(J===void 0)throw new XB.default(W.opts.uriResolver,Q,$);if(J instanceof wY.SchemaEnv)return O(J);return q(J);function z(){if(G===H)return F$(b,D,G,G.$async);let B=w.scopeValue("root",{ref:H});return F$(b,jb._`${B}.validate`,H,H.$async)}function O(B){let K=$Y(b,B);F$(b,K,B,B.$async)}function q(B){let K=w.scopeValue("schema",X.code.source===!0?{ref:B,code:(0,jb.stringify)(B)}:{ref:B}),I=w.name("valid"),M=b.subschema({schema:B,dataTypes:[],schemaPath:jb.nil,topSchemaRef:K,errSchemaPath:$},I);b.mergeEvaluated(M),b.ok(I)}}};function $Y(b,w){let{gen:$}=b;return w.validate?$.scopeValue("validate",{ref:w.validate}):jb._`${$.scopeValue("wrapper",{ref:w})}.validate`}WY.getValidate=$Y;function F$(b,w,$,W){let{gen:Q,it:G}=b,{allErrors:D,schemaEnv:X,opts:Y}=G,H=Y.passContext?aw.default.this:jb.nil;if(W)J();else z();function J(){if(!X.$async)throw Error("async schema referenced by sync schema");let B=Q.let("valid");Q.try(()=>{if(Q.code(jb._`await ${(0,bY.callValidateCode)(b,w,H)}`),q(w),!D)Q.assign(B,!0)},(K)=>{if(Q.if(jb._`!(${K} instanceof ${G.ValidationError})`,()=>Q.throw(K)),O(K),!D)Q.assign(B,!1)}),b.ok(B)}function z(){b.result((0,bY.callValidateCode)(b,w,H),()=>q(w),()=>O(w))}function O(B){let K=jb._`${B}.errors`;Q.assign(aw.default.vErrors,jb._`${aw.default.vErrors} === null ? ${K} : ${aw.default.vErrors}.concat(${K})`),Q.assign(aw.default.errors,jb._`${aw.default.vErrors}.length`)}function q(B){var K;if(!G.opts.unevaluated)return;let I=(K=$===null||$===void 0?void 0:$.validate)===null||K===void 0?void 0:K.evaluated;if(G.props!==!0)if(I&&!I.dynamicProps){if(I.props!==void 0)G.props=P$.mergeEvaluated.props(Q,I.props,G.props)}else{let M=Q.var("props",jb._`${B}.evaluated.props`);G.props=P$.mergeEvaluated.props(Q,M,G.props,jb.Name)}if(G.items!==!0)if(I&&!I.dynamicItems){if(I.items!==void 0)G.items=P$.mergeEvaluated.items(Q,I.items,G.items)}else{let M=Q.var("items",jb._`${B}.evaluated.items`);G.items=P$.mergeEvaluated.items(Q,M,G.items,jb.Name)}}}WY.callRef=F$;WY.default=YB});var XY=j((DY)=>{Object.defineProperty(DY,"__esModule",{value:!0});var zB=aX(),AB=GY(),OB=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",zB.default,AB.default];DY.default=OB});var HY=j((YY)=>{Object.defineProperty(YY,"__esModule",{value:!0});var K$=x(),Tw=K$.operators,M$={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}},LB={message:({keyword:b,schemaCode:w})=>K$.str`must be ${M$[b].okStr} ${w}`,params:({keyword:b,schemaCode:w})=>K$._`{comparison: ${M$[b].okStr}, limit: ${w}}`},UB={keyword:Object.keys(M$),type:"number",schemaType:"number",$data:!0,error:LB,code(b){let{keyword:w,data:$,schemaCode:W}=b;b.fail$data(K$._`${$} ${M$[w].fail} ${W} || isNaN(${$})`)}};YY.default=UB});var zY=j((JY)=>{Object.defineProperty(JY,"__esModule",{value:!0});var e1=x(),PB={message:({schemaCode:b})=>e1.str`must be multiple of ${b}`,params:({schemaCode:b})=>e1._`{multipleOf: ${b}}`},FB={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:PB,code(b){let{gen:w,data:$,schemaCode:W,it:Q}=b,G=Q.opts.multipleOfPrecision,D=w.let("res"),X=G?e1._`Math.abs(Math.round(${D}) - ${D}) > 1e-${G}`:e1._`${D} !== parseInt(${D})`;b.fail$data(e1._`(${W} === 0 || (${D} = ${$}/${W}, ${X}))`)}};JY.default=FB});var qY=j((OY)=>{Object.defineProperty(OY,"__esModule",{value:!0});function AY(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 $}OY.default=AY;AY.code='require("ajv/dist/runtime/ucs2length").default'});var UY=j((LY)=>{Object.defineProperty(LY,"__esModule",{value:!0});var xw=x(),IB=i(),ZB=qY(),jB={message({keyword:b,schemaCode:w}){let $=b==="maxLength"?"more":"fewer";return xw.str`must NOT have ${$} than ${w} characters`},params:({schemaCode:b})=>xw._`{limit: ${b}}`},VB={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:jB,code(b){let{keyword:w,data:$,schemaCode:W,it:Q}=b,G=w==="maxLength"?xw.operators.GT:xw.operators.LT,D=Q.opts.unicode===!1?xw._`${$}.length`:xw._`${(0,IB.useFunc)(b.gen,ZB.default)}(${$})`;b.fail$data(xw._`${D} ${G} ${W}`)}};LY.default=VB});var PY=j((BY)=>{Object.defineProperty(BY,"__esModule",{value:!0});var TB=Cb(),I$=x(),EB={message:({schemaCode:b})=>I$.str`must match pattern "${b}"`,params:({schemaCode:b})=>I$._`{pattern: ${b}}`},_B={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:EB,code(b){let{data:w,$data:$,schema:W,schemaCode:Q,it:G}=b,D=G.opts.unicodeRegExp?"u":"",X=$?I$._`(new RegExp(${Q}, ${D}))`:(0,TB.usePattern)(b,W);b.fail$data(I$._`!${X}.test(${w})`)}};BY.default=_B});var KY=j((FY)=>{Object.defineProperty(FY,"__esModule",{value:!0});var s1=x(),RB={message({keyword:b,schemaCode:w}){let $=b==="maxProperties"?"more":"fewer";return s1.str`must NOT have ${$} than ${w} properties`},params:({schemaCode:b})=>s1._`{limit: ${b}}`},vB={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:RB,code(b){let{keyword:w,data:$,schemaCode:W}=b,Q=w==="maxProperties"?s1.operators.GT:s1.operators.LT;b.fail$data(s1._`Object.keys(${$}).length ${Q} ${W}`)}};FY.default=vB});var IY=j((MY)=>{Object.defineProperty(MY,"__esModule",{value:!0});var a1=Cb(),b0=x(),CB=i(),uB={message:({params:{missingProperty:b}})=>b0.str`must have required property '${b}'`,params:({params:{missingProperty:b}})=>b0._`{missingProperty: ${b}}`},xB={keyword:"required",type:"object",schemaType:"array",$data:!0,error:uB,code(b){let{gen:w,schema:$,schemaCode:W,data:Q,$data:G,it:D}=b,{opts:X}=D;if(!G&&$.length===0)return;let Y=$.length>=X.loopRequired;if(D.allErrors)H();else J();if(X.strictRequired){let q=b.parentSchema.properties,{definedProperties:B}=b.it;for(let K of $)if((q===null||q===void 0?void 0:q[K])===void 0&&!B.has(K)){let I=D.schemaEnv.baseId+D.errSchemaPath,M=`required property "${K}" is not defined at "${I}" (strictRequired)`;(0,CB.checkStrictMode)(D,M,D.opts.strictRequired)}}function H(){if(Y||G)b.block$data(b0.nil,z);else for(let q of $)(0,a1.checkReportMissingProp)(b,q)}function J(){let q=w.let("missing");if(Y||G){let B=w.let("valid",!0);b.block$data(B,()=>O(q,B)),b.ok(B)}else w.if((0,a1.checkMissingProp)(b,$,q)),(0,a1.reportMissingProp)(b,q),w.else()}function z(){w.forOf("prop",W,(q)=>{b.setParams({missingProperty:q}),w.if((0,a1.noPropertyInData)(w,Q,q,X.ownProperties),()=>b.error())})}function O(q,B){b.setParams({missingProperty:q}),w.forOf(q,W,()=>{w.assign(B,(0,a1.propertyInData)(w,Q,q,X.ownProperties)),w.if((0,b0.not)(B),()=>{b.error(),w.break()})},b0.nil)}}};MY.default=xB});var jY=j((ZY)=>{Object.defineProperty(ZY,"__esModule",{value:!0});var w0=x(),hB={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}}`},fB={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:hB,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}`)}};ZY.default=fB});var Z$=j((NY)=>{Object.defineProperty(NY,"__esModule",{value:!0});var VY=j4();VY.code='require("ajv/dist/runtime/equal").default';NY.default=VY});var EY=j((TY)=>{Object.defineProperty(TY,"__esModule",{value:!0});var c4=n1(),qb=x(),gB=i(),mB=Z$(),iB={message:({params:{i:b,j:w}})=>qb.str`must NOT have duplicate items (items ## ${w} and ${b} are identical)`,params:({params:{i:b,j:w}})=>qb._`{i: ${b}, j: ${w}}`},lB={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:iB,code(b){let{gen:w,data:$,$data:W,schema:Q,parentSchema:G,schemaCode:D,it:X}=b;if(!W&&!Q)return;let Y=w.let("valid"),H=G.items?(0,c4.getSchemaTypes)(G.items):[];b.block$data(Y,J,qb._`${D} === false`),b.ok(Y);function J(){let B=w.let("i",qb._`${$}.length`),K=w.let("j");b.setParams({i:B,j:K}),w.assign(Y,!0),w.if(qb._`${B} > 1`,()=>(z()?O:q)(B,K))}function z(){return H.length>0&&!H.some((B)=>B==="object"||B==="array")}function O(B,K){let I=w.name("item"),M=(0,c4.checkDataTypes)(H,I,X.opts.strictNumbers,c4.DataType.Wrong),v=w.const("indices",qb._`{}`);w.for(qb._`;${B}--;`,()=>{if(w.let(I,qb._`${$}[${B}]`),w.if(M,qb._`continue`),H.length>1)w.if(qb._`typeof ${I} == "string"`,qb._`${I} += "_"`);w.if(qb._`typeof ${v}[${I}] == "number"`,()=>{w.assign(K,qb._`${v}[${I}]`),b.error(),w.assign(Y,!1).break()}).code(qb._`${v}[${I}] = ${B}`)})}function q(B,K){let I=(0,gB.useFunc)(w,mB.default),M=w.name("outer");w.label(M).for(qb._`;${B}--;`,()=>w.for(qb._`${K} = ${B}; ${K}--;`,()=>w.if(qb._`${I}(${$}[${B}], ${$}[${K}])`,()=>{b.error(),w.assign(Y,!1).break(M)})))}}};TY.default=lB});var SY=j((_Y)=>{Object.defineProperty(_Y,"__esModule",{value:!0});var n4=x(),oB=i(),dB=Z$(),tB={message:"must be equal to constant",params:({schemaCode:b})=>n4._`{allowedValue: ${b}}`},rB={keyword:"const",$data:!0,error:tB,code(b){let{gen:w,data:$,$data:W,schemaCode:Q,schema:G}=b;if(W||G&&typeof G=="object")b.fail$data(n4._`!${(0,oB.useFunc)(w,dB.default)}(${$}, ${Q})`);else b.fail(n4._`${G} !== ${$}`)}};_Y.default=rB});var vY=j((RY)=>{Object.defineProperty(RY,"__esModule",{value:!0});var $0=x(),sB=i(),aB=Z$(),bP={message:"must be equal to one of the allowed values",params:({schemaCode:b})=>$0._`{allowedValues: ${b}}`},wP={keyword:"enum",schemaType:"array",$data:!0,error:bP,code(b){let{gen:w,data:$,$data:W,schema:Q,schemaCode:G,it:D}=b;if(!W&&Q.length===0)throw Error("enum must have non-empty array");let X=Q.length>=D.opts.loopEnum,Y,H=()=>Y!==null&&Y!==void 0?Y:Y=(0,sB.useFunc)(w,aB.default),J;if(X||W)J=w.let("valid"),b.block$data(J,z);else{if(!Array.isArray(Q))throw Error("ajv implementation error");let q=w.const("vSchema",G);J=(0,$0.or)(...Q.map((B,K)=>O(q,K)))}b.pass(J);function z(){w.assign(J,!1),w.forOf("v",G,(q)=>w.if($0._`${H()}(${$}, ${q})`,()=>w.assign(J,!0).break()))}function O(q,B){let K=Q[B];return typeof K==="object"&&K!==null?$0._`${H()}(${$}, ${q}[${B}])`:$0._`${$} === ${K}`}}};RY.default=wP});var CY=j((kY)=>{Object.defineProperty(kY,"__esModule",{value:!0});var WP=HY(),QP=zY(),GP=UY(),DP=PY(),XP=KY(),YP=IY(),HP=jY(),JP=EY(),zP=SY(),AP=vY(),OP=[WP.default,QP.default,GP.default,DP.default,XP.default,YP.default,HP.default,JP.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},zP.default,AP.default];kY.default=OP});var m4=j((xY)=>{Object.defineProperty(xY,"__esModule",{value:!0});xY.validateAdditionalItems=void 0;var yw=x(),g4=i(),LP={message:({params:{len:b}})=>yw.str`must NOT have more than ${b} items`,params:({params:{len:b}})=>yw._`{limit: ${b}}`},UP={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:LP,code(b){let{parentSchema:w,it:$}=b,{items:W}=w;if(!Array.isArray(W)){(0,g4.checkStrictMode)($,'"additionalItems" is ignored when "items" is not an array of schemas');return}uY(b,W)}};function uY(b,w){let{gen:$,schema:W,data:Q,keyword:G,it:D}=b;D.items=!0;let X=$.const("len",yw._`${Q}.length`);if(W===!1)b.setParams({len:w.length}),b.pass(yw._`${X} <= ${w.length}`);else if(typeof W=="object"&&!(0,g4.alwaysValidSchema)(D,W)){let H=$.var("valid",yw._`${X} <= ${w.length}`);$.if((0,yw.not)(H),()=>Y(H)),b.ok(H)}function Y(H){$.forRange("i",w.length,X,(J)=>{if(b.subschema({keyword:G,dataProp:J,dataPropType:g4.Type.Num},H),!D.allErrors)$.if((0,yw.not)(H),()=>$.break())})}}xY.validateAdditionalItems=uY;xY.default=UP});var i4=j((cY)=>{Object.defineProperty(cY,"__esModule",{value:!0});cY.validateTuple=void 0;var hY=x(),j$=i(),PP=Cb(),FP={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(b){let{schema:w,it:$}=b;if(Array.isArray(w))return fY(b,"additionalItems",w);if($.items=!0,(0,j$.alwaysValidSchema)($,w))return;b.ok((0,PP.validateArray)(b))}};function fY(b,w,$=b.schema){let{gen:W,parentSchema:Q,data:G,keyword:D,it:X}=b;if(J(Q),X.opts.unevaluated&&$.length&&X.items!==!0)X.items=j$.mergeEvaluated.items(W,$.length,X.items);let Y=W.name("valid"),H=W.const("len",hY._`${G}.length`);$.forEach((z,O)=>{if((0,j$.alwaysValidSchema)(X,z))return;W.if(hY._`${H} > ${O}`,()=>b.subschema({keyword:D,schemaProp:O,dataProp:O},Y)),b.ok(Y)});function J(z){let{opts:O,errSchemaPath:q}=X,B=$.length,K=B===z.minItems&&(B===z.maxItems||z[w]===!1);if(O.strictTuples&&!K){let I=`"${D}" is ${B}-tuple, but minItems or maxItems/${w} are not specified or different at path "${q}"`;(0,j$.checkStrictMode)(X,I,O.strictTuples)}}}cY.validateTuple=fY;cY.default=FP});var mY=j((gY)=>{Object.defineProperty(gY,"__esModule",{value:!0});var MP=i4(),IP={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:(b)=>(0,MP.validateTuple)(b,"items")};gY.default=IP});var pY=j((lY)=>{Object.defineProperty(lY,"__esModule",{value:!0});var iY=x(),jP=i(),VP=Cb(),NP=m4(),TP={message:({params:{len:b}})=>iY.str`must NOT have more than ${b} items`,params:({params:{len:b}})=>iY._`{limit: ${b}}`},EP={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:TP,code(b){let{schema:w,parentSchema:$,it:W}=b,{prefixItems:Q}=$;if(W.items=!0,(0,jP.alwaysValidSchema)(W,w))return;if(Q)(0,NP.validateAdditionalItems)(b,Q);else b.ok((0,VP.validateArray)(b))}};lY.default=EP});var dY=j((oY)=>{Object.defineProperty(oY,"__esModule",{value:!0});var ub=x(),V$=i(),SP={message:({params:{min:b,max:w}})=>w===void 0?ub.str`must contain at least ${b} valid item(s)`:ub.str`must contain at least ${b} and no more than ${w} valid item(s)`,params:({params:{min:b,max:w}})=>w===void 0?ub._`{minContains: ${b}}`:ub._`{minContains: ${b}, maxContains: ${w}}`},RP={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:SP,code(b){let{gen:w,schema:$,parentSchema:W,data:Q,it:G}=b,D,X,{minContains:Y,maxContains:H}=W;if(G.opts.next)D=Y===void 0?1:Y,X=H;else D=1;let J=w.const("len",ub._`${Q}.length`);if(b.setParams({min:D,max:X}),X===void 0&&D===0){(0,V$.checkStrictMode)(G,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(X!==void 0&&D>X){(0,V$.checkStrictMode)(G,'"minContains" > "maxContains" is always invalid'),b.fail();return}if((0,V$.alwaysValidSchema)(G,$)){let K=ub._`${J} >= ${D}`;if(X!==void 0)K=ub._`${K} && ${J} <= ${X}`;b.pass(K);return}G.items=!0;let z=w.name("valid");if(X===void 0&&D===1)q(z,()=>w.if(z,()=>w.break()));else if(D===0){if(w.let(z,!0),X!==void 0)w.if(ub._`${Q}.length > 0`,O)}else w.let(z,!1),O();b.result(z,()=>b.reset());function O(){let K=w.name("_valid"),I=w.let("count",0);q(K,()=>w.if(K,()=>B(I)))}function q(K,I){w.forRange("i",0,J,(M)=>{b.subschema({keyword:"contains",dataProp:M,dataPropType:V$.Type.Num,compositeRule:!0},K),I()})}function B(K){if(w.code(ub._`${K}++`),X===void 0)w.if(ub._`${K} >= ${D}`,()=>w.assign(z,!0).break());else if(w.if(ub._`${K} > ${X}`,()=>w.assign(z,!1).break()),D===1)w.assign(z,!0);else w.if(ub._`${K} >= ${D}`,()=>w.assign(z,!0))}}};oY.default=RP});var bH=j((eY)=>{Object.defineProperty(eY,"__esModule",{value:!0});eY.validateSchemaDeps=eY.validatePropertyDeps=eY.error=void 0;var l4=x(),kP=i(),W0=Cb();eY.error={message:({params:{property:b,depsCount:w,deps:$}})=>{let W=w===1?"property":"properties";return l4.str`must have ${W} ${$} when property ${b} is present`},params:({params:{property:b,depsCount:w,deps:$,missingProperty:W}})=>l4._`{property: ${b},
6
+ || ${D} === "boolean" || ${Q} === null`).assign(X,C._`[${Q}]`)}}}function XL({gen:b,parentData:w,parentDataProperty:$},W){b.if(C._`${w} !== undefined`,()=>b.assign(C._`${w}[${$}]`,W))}function P6(b,w,$,W=tw.Correct){let Q=W===tw.Correct?C.operators.EQ:C.operators.NEQ,G;switch(b){case"null":return C._`${w} ${Q} null`;case"array":G=C._`Array.isArray(${w})`;break;case"object":G=C._`${w} && typeof ${w} == "object" && !Array.isArray(${w})`;break;case"integer":G=D(C._`!(${w} % 1) && !isNaN(${w})`);break;case"number":G=D();break;default:return C._`typeof ${w} ${Q} ${b}`}return W===tw.Correct?G:(0,C.not)(G);function D(X=C.nil){return(0,C.and)(C._`typeof ${w} == "number"`,X,$?C._`isFinite(${w})`:C.nil)}}RD.checkDataType=P6;function F6(b,w,$,W){if(b.length===1)return P6(b[0],w,$,W);let Q,G=(0,ED.toHash)(b);if(G.array&&G.object){let D=C._`typeof ${w} != "object"`;Q=G.null?D:C._`!${w} || ${D}`,delete G.null,delete G.array,delete G.object}else Q=C.nil;if(G.number)delete G.integer;for(let D in G)Q=(0,C.and)(Q,P6(D,w,$,W));return Q}RD.checkDataTypes=F6;var YL={message:({schema:b})=>`must be ${b}`,params:({schema:b,schemaValue:w})=>typeof b=="string"?C._`{type: ${b}}`:C._`{type: ${w}}`};function K6(b){let w=HL(b);(0,$L.reportError)(w,YL)}RD.reportTypeError=K6;function HL(b){let{gen:w,data:$,schema:W}=b,Q=(0,ED.schemaRefOrVal)(b,W,"type");return{gen:w,keyword:"type",data:$,schema:W.type,schemaCode:Q,schemaValue:Q,parentSchema:W,params:{},it:b}}});var xD=j((CD)=>{Object.defineProperty(CD,"__esModule",{value:!0});CD.assignDefaults=void 0;var rw=x(),UL=i();function BL(b,w){let{properties:$,items:W}=b.schema;if(w==="object"&&$)for(let Q in $)kD(b,Q,$[Q].default);else if(w==="array"&&Array.isArray(W))W.forEach((Q,G)=>kD(b,G,Q.default))}CD.assignDefaults=BL;function kD(b,w,$){let{gen:W,compositeRule:Q,data:G,opts:D}=b;if($===void 0)return;let X=rw._`${G}${(0,rw.getProperty)(w)}`;if(Q){(0,UL.checkStrictMode)(b,`default is ignored for: ${X}`);return}let Y=rw._`${X} === undefined`;if(D.useDefaults==="empty")Y=rw._`${Y} || ${X} === null || ${X} === ""`;W.if(Y,rw._`${X} = ${(0,rw.stringify)($)}`)}});var Cb=j((fD)=>{Object.defineProperty(fD,"__esModule",{value:!0});fD.validateUnion=fD.validateArray=fD.usePattern=fD.callValidateCode=fD.schemaProperties=fD.allSchemaProperties=fD.noPropertyInData=fD.propertyInData=fD.isOwnProperty=fD.hasPropFunc=fD.reportMissingProp=fD.checkMissingProp=fD.checkReportMissingProp=void 0;var a=x(),M6=i(),Vw=Qw(),PL=i();function FL(b,w){let{gen:$,data:W,it:Q}=b;$.if(Z6($,W,w,Q.opts.ownProperties),()=>{b.setParams({missingProperty:a._`${w}`},!0),b.error()})}fD.checkReportMissingProp=FL;function KL({gen:b,data:w,it:{opts:$}},W,Q){return(0,a.or)(...W.map((G)=>(0,a.and)(Z6(b,w,G,$.ownProperties),a._`${Q} = ${G}`)))}fD.checkMissingProp=KL;function ML(b,w){b.setParams({missingProperty:w},!0),b.error()}fD.reportMissingProp=ML;function yD(b){return b.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:a._`Object.prototype.hasOwnProperty`})}fD.hasPropFunc=yD;function I6(b,w,$){return a._`${yD(b)}.call(${w}, ${$})`}fD.isOwnProperty=I6;function IL(b,w,$,W){let Q=a._`${w}${(0,a.getProperty)($)} !== undefined`;return W?a._`${Q} && ${I6(b,w,$)}`:Q}fD.propertyInData=IL;function Z6(b,w,$,W){let Q=a._`${w}${(0,a.getProperty)($)} === undefined`;return W?(0,a.or)(Q,(0,a.not)(I6(b,w,$))):Q}fD.noPropertyInData=Z6;function hD(b){return b?Object.keys(b).filter((w)=>w!=="__proto__"):[]}fD.allSchemaProperties=hD;function ZL(b,w){return hD(w).filter(($)=>!(0,M6.alwaysValidSchema)(b,w[$]))}fD.schemaProperties=ZL;function jL({schemaCode:b,data:w,it:{gen:$,topSchemaRef:W,schemaPath:Q,errorPath:G},it:D},X,Y,H){let J=H?a._`${b}, ${w}, ${W}${Q}`:w,z=[[Vw.default.instancePath,(0,a.strConcat)(Vw.default.instancePath,G)],[Vw.default.parentData,D.parentData],[Vw.default.parentDataProperty,D.parentDataProperty],[Vw.default.rootData,Vw.default.rootData]];if(D.opts.dynamicRef)z.push([Vw.default.dynamicAnchors,Vw.default.dynamicAnchors]);let O=a._`${J}, ${$.object(...z)}`;return Y!==a.nil?a._`${X}.call(${Y}, ${O})`:a._`${X}(${O})`}fD.callValidateCode=jL;var VL=a._`new RegExp`;function NL({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"?VL:(0,PL.useFunc)(b,Q)}(${$}, ${W})`})}fD.usePattern=NL;function TL(b){let{gen:w,data:$,keyword:W,it:Q}=b,G=w.name("valid");if(Q.allErrors){let X=w.let("valid",!0);return D(()=>w.assign(X,!1)),X}return w.var(G,!0),D(()=>w.break()),G;function D(X){let Y=w.const("len",a._`${$}.length`);w.forRange("i",0,Y,(H)=>{b.subschema({keyword:W,dataProp:H,dataPropType:M6.Type.Num},G),w.if((0,a.not)(G),X)})}}fD.validateArray=TL;function EL(b){let{gen:w,schema:$,keyword:W,it:Q}=b;if(!Array.isArray($))throw Error("ajv implementation error");if($.some((Y)=>(0,M6.alwaysValidSchema)(Q,Y))&&!Q.opts.unevaluated)return;let D=w.let("valid",!1),X=w.name("_valid");w.block(()=>$.forEach((Y,H)=>{let J=b.subschema({keyword:W,schemaProp:H,compositeRule:!0},X);if(w.assign(D,a._`${D} || ${X}`),!b.mergeValidEvaluated(J,X))w.if((0,a.not)(D))})),b.result(D,()=>b.reset(),()=>b.error(!0))}fD.validateUnion=EL});var lD=j((mD)=>{Object.defineProperty(mD,"__esModule",{value:!0});mD.validateKeywordUsage=mD.validSchemaType=mD.funcKeywordCode=mD.macroKeywordCode=void 0;var Fb=x(),Cw=Qw(),nL=Cb(),gL=c1();function mL(b,w){let{gen:$,keyword:W,schema:Q,parentSchema:G,it:D}=b,X=w.macro.call(D.self,Q,G,D),Y=gD($,W,X);if(D.opts.validateSchema!==!1)D.self.validateSchema(X,!0);let H=$.name("valid");b.subschema({schema:X,schemaPath:Fb.nil,errSchemaPath:`${D.errSchemaPath}/${W}`,topSchemaRef:Y,compositeRule:!0},H),b.pass(H,()=>b.error(!0))}mD.macroKeywordCode=mL;function iL(b,w){var $;let{gen:W,keyword:Q,schema:G,parentSchema:D,$data:X,it:Y}=b;pL(Y,w);let H=!X&&w.compile?w.compile.call(Y.self,G,D,Y):w.validate,J=gD(W,Q,H),z=W.let("valid");b.block$data(z,O),b.ok(($=w.valid)!==null&&$!==void 0?$:z);function O(){if(w.errors===!1){if(K(),w.modifying)nD(b);I(()=>b.error())}else{let M=w.async?q():B();if(w.modifying)nD(b);I(()=>lL(b,M))}}function q(){let M=W.let("ruleErrs",null);return W.try(()=>K(Fb._`await `),(v)=>W.assign(z,!1).if(Fb._`${v} instanceof ${Y.ValidationError}`,()=>W.assign(M,Fb._`${v}.errors`),()=>W.throw(v))),M}function B(){let M=Fb._`${J}.errors`;return W.assign(M,null),K(Fb.nil),M}function K(M=w.async?Fb._`await `:Fb.nil){let v=Y.opts.passContext?Cw.default.this:Cw.default.self,S=!(("compile"in w)&&!X||w.schema===!1);W.assign(z,Fb._`${M}${(0,nL.callValidateCode)(b,J,v,S)}`,w.modifying)}function I(M){var v;W.if((0,Fb.not)((v=w.valid)!==null&&v!==void 0?v:z),M)}}mD.funcKeywordCode=iL;function nD(b){let{gen:w,data:$,it:W}=b;w.if(W.parentData,()=>w.assign($,Fb._`${W.parentData}[${W.parentDataProperty}]`))}function lL(b,w){let{gen:$}=b;$.if(Fb._`Array.isArray(${w})`,()=>{$.assign(Cw.default.vErrors,Fb._`${Cw.default.vErrors} === null ? ${w} : ${Cw.default.vErrors}.concat(${w})`).assign(Cw.default.errors,Fb._`${Cw.default.vErrors}.length`),(0,gL.extendErrors)(b)},()=>b.error())}function pL({schemaEnv:b},w){if(w.async&&!b.$async)throw Error("async keyword in sync schema")}function gD(b,w,$){if($===void 0)throw Error(`keyword "${w}" failed to compile`);return b.scopeValue("keyword",typeof $=="function"?{ref:$}:{ref:$,code:(0,Fb.stringify)($)})}function oL(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")}mD.validSchemaType=oL;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 D=Q.dependencies;if(D===null||D===void 0?void 0:D.some((X)=>!Object.prototype.hasOwnProperty.call(b,X)))throw Error(`parent schema must have dependencies of ${G}: ${D.join(",")}`);if(Q.validateSchema){if(!Q.validateSchema(b[G])){let Y=`keyword "${G}" value is invalid at path "${W}": `+$.errorsText(Q.validateSchema.errors);if(w.validateSchema==="log")$.logger.error(Y);else throw Error(Y)}}}mD.validateKeywordUsage=dL});var tD=j((oD)=>{Object.defineProperty(oD,"__esModule",{value:!0});oD.extendSubschemaMode=oD.extendSubschemaData=oD.getSubschema=void 0;var db=x(),pD=i();function sL(b,{keyword:w,schemaProp:$,schema:W,schemaPath:Q,errSchemaPath:G,topSchemaRef:D}){if(w!==void 0&&W!==void 0)throw Error('both "keyword" and "schema" passed, only one allowed');if(w!==void 0){let X=b.schema[w];return $===void 0?{schema:X,schemaPath:db._`${b.schemaPath}${(0,db.getProperty)(w)}`,errSchemaPath:`${b.errSchemaPath}/${w}`}:{schema:X[$],schemaPath:db._`${b.schemaPath}${(0,db.getProperty)(w)}${(0,db.getProperty)($)}`,errSchemaPath:`${b.errSchemaPath}/${w}/${(0,pD.escapeFragment)($)}`}}if(W!==void 0){if(Q===void 0||G===void 0||D===void 0)throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:W,schemaPath:Q,topSchemaRef:D,errSchemaPath:G}}throw Error('either "keyword" or "schema" must be passed')}oD.getSubschema=sL;function aL(b,w,{dataProp:$,dataPropType:W,data:Q,dataTypes:G,propertyName:D}){if(Q!==void 0&&$!==void 0)throw Error('both "data" and "dataProp" passed, only one allowed');let{gen:X}=w;if($!==void 0){let{errorPath:H,dataPathArr:J,opts:z}=w,O=X.let("data",db._`${w.data}${(0,db.getProperty)($)}`,!0);Y(O),b.errorPath=db.str`${H}${(0,pD.getErrorPath)($,W,z.jsPropertySyntax)}`,b.parentDataProperty=db._`${$}`,b.dataPathArr=[...J,b.parentDataProperty]}if(Q!==void 0){let H=Q instanceof db.Name?Q:X.let("data",Q,!0);if(Y(H),D!==void 0)b.propertyName=D}if(G)b.dataTypes=G;function Y(H){b.data=H,b.dataLevel=w.dataLevel+1,b.dataTypes=[],w.definedProperties=new Set,b.parentData=w.data,b.dataNames=[...w.dataNames,H]}}oD.extendSubschemaData=aL;function bU(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=$}oD.extendSubschemaMode=bU});var j6=j((dT,rD)=>{rD.exports=function b(w,$){if(w===$)return!0;if(w&&$&&typeof w=="object"&&typeof $=="object"){if(w.constructor!==$.constructor)return!1;var W,Q,G;if(Array.isArray(w)){if(W=w.length,W!=$.length)return!1;for(Q=W;Q--!==0;)if(!b(w[Q],$[Q]))return!1;return!0}if(w.constructor===RegExp)return w.source===$.source&&w.flags===$.flags;if(w.valueOf!==Object.prototype.valueOf)return w.valueOf()===$.valueOf();if(w.toString!==Object.prototype.toString)return w.toString()===$.toString();if(G=Object.keys(w),W=G.length,W!==Object.keys($).length)return!1;for(Q=W;Q--!==0;)if(!Object.prototype.hasOwnProperty.call($,G[Q]))return!1;for(Q=W;Q--!==0;){var D=G[Q];if(!b(w[D],$[D]))return!1}return!0}return w!==w&&$!==$}});var sD=j((tT,eD)=>{var Nw=eD.exports=function(b,w,$){if(typeof w=="function")$=w,w={};$=w.cb||$;var W=typeof $=="function"?$:$.pre||function(){},Q=$.post||function(){};X$(w,W,Q,b,"",b)};Nw.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Nw.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Nw.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Nw.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function X$(b,w,$,W,Q,G,D,X,Y,H){if(W&&typeof W=="object"&&!Array.isArray(W)){w(W,Q,G,D,X,Y,H);for(var J in W){var z=W[J];if(Array.isArray(z)){if(J in Nw.arrayKeywords)for(var O=0;O<z.length;O++)X$(b,w,$,z[O],Q+"/"+J+"/"+O,G,Q,J,W,O)}else if(J in Nw.propsKeywords){if(z&&typeof z=="object")for(var q in z)X$(b,w,$,z[q],Q+"/"+J+"/"+WU(q),G,Q,J,W,q)}else if(J in Nw.keywords||b.allKeys&&!(J in Nw.skipKeywords))X$(b,w,$,z,Q+"/"+J,G,Q,J,W)}$(W,Q,G,D,X,Y,H)}}function WU(b){return b.replace(/~/g,"~0").replace(/\//g,"~1")}});var g1=j(($X)=>{Object.defineProperty($X,"__esModule",{value:!0});$X.getSchemaRefs=$X.resolveUrl=$X.normalizeId=$X._getFullPath=$X.getFullPath=$X.inlineRef=void 0;var QU=i(),GU=j6(),DU=sD(),XU=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function YU(b,w=!0){if(typeof b=="boolean")return!0;if(w===!0)return!V6(b);if(!w)return!1;return aD(b)<=w}$X.inlineRef=YU;var HU=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function V6(b){for(let w in b){if(HU.has(w))return!0;let $=b[w];if(Array.isArray($)&&$.some(V6))return!0;if(typeof $=="object"&&V6($))return!0}return!1}function aD(b){let w=0;for(let $ in b){if($==="$ref")return 1/0;if(w++,XU.has($))continue;if(typeof b[$]=="object")(0,QU.eachItem)(b[$],(W)=>w+=aD(W));if(w===1/0)return 1/0}return w}function bX(b,w="",$){if($!==!1)w=ew(w);let W=b.parse(w);return wX(b,W)}$X.getFullPath=bX;function wX(b,w){return b.serialize(w).split("#")[0]+"#"}$X._getFullPath=wX;var JU=/#\/?$/;function ew(b){return b?b.replace(JU,""):""}$X.normalizeId=ew;function zU(b,w,$){return $=ew($),b.resolve(w,$)}$X.resolveUrl=zU;var AU=/^[a-z_][-a-z0-9._]*$/i;function OU(b,w){if(typeof b=="boolean")return{};let{schemaId:$,uriResolver:W}=this.opts,Q=ew(b[$]||w),G={"":Q},D=bX(W,Q,!1),X={},Y=new Set;return DU(b,{allKeys:!0},(z,O,q,B)=>{if(B===void 0)return;let K=D+O,I=G[B];if(typeof z[$]=="string")I=M.call(this,z[$]);v.call(this,z.$anchor),v.call(this,z.$dynamicAnchor),G[O]=I;function M(S){let h=this.opts.uriResolver.resolve;if(S=ew(I?h(I,S):S),Y.has(S))throw J(S);Y.add(S);let R=this.refs[S];if(typeof R=="string")R=this.refs[R];if(typeof R=="object")H(z,R.schema,S);else if(S!==ew(K))if(S[0]==="#")H(z,X[S],S),X[S]=z;else this.refs[S]=K;return S}function v(S){if(typeof S=="string"){if(!AU.test(S))throw Error(`invalid anchor "${S}"`);M.call(this,`#${S}`)}}}),X;function H(z,O,q){if(O!==void 0&&!GU(z,O))throw J(q)}function J(z){return Error(`reference "${z}" resolves to more than one schema`)}}$X.getSchemaRefs=OU});var l1=j((PX)=>{Object.defineProperty(PX,"__esModule",{value:!0});PX.getData=PX.KeywordCxt=PX.validateFunctionCode=void 0;var YX=MD(),QX=n1(),T6=B6(),Y$=n1(),FU=xD(),i1=lD(),N6=tD(),E=x(),k=Qw(),KU=g1(),Gw=i(),m1=c1();function MU(b){if(zX(b)){if(AX(b),JX(b)){jU(b);return}}HX(b,()=>(0,YX.topBoolOrEmptySchema)(b))}PX.validateFunctionCode=MU;function HX({gen:b,validateName:w,schema:$,schemaEnv:W,opts:Q},G){if(Q.code.es5)b.func(w,E._`${k.default.data}, ${k.default.valCxt}`,W.$async,()=>{b.code(E._`"use strict"; ${GX($,Q)}`),ZU(b,Q),b.code(G)});else b.func(w,E._`${k.default.data}, ${IU(Q)}`,W.$async,()=>b.code(GX($,Q)).code(G))}function IU(b){return E._`{${k.default.instancePath}="", ${k.default.parentData}, ${k.default.parentDataProperty}, ${k.default.rootData}=${k.default.data}${b.dynamicRef?E._`, ${k.default.dynamicAnchors}={}`:E.nil}}={}`}function ZU(b,w){b.if(k.default.valCxt,()=>{if(b.var(k.default.instancePath,E._`${k.default.valCxt}.${k.default.instancePath}`),b.var(k.default.parentData,E._`${k.default.valCxt}.${k.default.parentData}`),b.var(k.default.parentDataProperty,E._`${k.default.valCxt}.${k.default.parentDataProperty}`),b.var(k.default.rootData,E._`${k.default.valCxt}.${k.default.rootData}`),w.dynamicRef)b.var(k.default.dynamicAnchors,E._`${k.default.valCxt}.${k.default.dynamicAnchors}`)},()=>{if(b.var(k.default.instancePath,E._`""`),b.var(k.default.parentData,E._`undefined`),b.var(k.default.parentDataProperty,E._`undefined`),b.var(k.default.rootData,k.default.data),w.dynamicRef)b.var(k.default.dynamicAnchors,E._`{}`)})}function jU(b){let{schema:w,opts:$,gen:W}=b;HX(b,()=>{if($.$comment&&w.$comment)qX(b);if(_U(b),W.let(k.default.vErrors,null),W.let(k.default.errors,0),$.unevaluated)VU(b);OX(b),vU(b)});return}function VU(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 GX(b,w){let $=typeof b=="object"&&b[w.schemaId];return $&&(w.code.source||w.code.process)?E._`/*# sourceURL=${$} */`:E.nil}function NU(b,w){if(zX(b)){if(AX(b),JX(b)){TU(b,w);return}}(0,YX.boolOrEmptySchema)(b,w)}function JX({schema:b,self:w}){if(typeof b=="boolean")return!b;for(let $ in b)if(w.RULES.all[$])return!0;return!1}function zX(b){return typeof b.schema!="boolean"}function TU(b,w){let{schema:$,gen:W,opts:Q}=b;if(Q.$comment&&$.$comment)qX(b);SU(b),RU(b);let G=W.const("_errs",k.default.errors);OX(b,G),W.var(w,E._`${G} === ${k.default.errors}`)}function AX(b){(0,Gw.checkUnknownRules)(b),EU(b)}function OX(b,w){if(b.opts.jtd)return DX(b,[],!1,w);let $=(0,QX.getSchemaTypes)(b.schema),W=(0,QX.coerceAndCheckDataType)(b,$);DX(b,$,!W,w)}function EU(b){let{schema:w,errSchemaPath:$,opts:W,self:Q}=b;if(w.$ref&&W.ignoreKeywordsWithRef&&(0,Gw.schemaHasRulesButRef)(w,Q.RULES))Q.logger.warn(`$ref: keywords ignored in schema at path "${$}"`)}function _U(b){let{schema:w,opts:$}=b;if(w.default!==void 0&&$.useDefaults&&$.strictSchema)(0,Gw.checkStrictMode)(b,"default is ignored in the schema root")}function SU(b){let w=b.schema[b.opts.schemaId];if(w)b.baseId=(0,KU.resolveUrl)(b.opts.uriResolver,b.baseId,w)}function RU(b){if(b.schema.$async&&!b.schemaEnv.$async)throw Error("async schema in sync schema")}function qX({gen:b,schemaEnv:w,schema:$,errSchemaPath:W,opts:Q}){let G=$.$comment;if(Q.$comment===!0)b.code(E._`${k.default.self}.logger.log(${G})`);else if(typeof Q.$comment=="function"){let D=E.str`${W}/$comment`,X=b.scopeValue("root",{ref:w.root});b.code(E._`${k.default.self}.opts.$comment(${G}, ${D}, ${X}.schema)`)}}function vU(b){let{gen:w,schemaEnv:$,validateName:W,ValidationError:Q,opts:G}=b;if($.$async)w.if(E._`${k.default.errors} === 0`,()=>w.return(k.default.data),()=>w.throw(E._`new ${Q}(${k.default.vErrors})`));else{if(w.assign(E._`${W}.errors`,k.default.vErrors),G.unevaluated)kU(b);w.return(E._`${k.default.errors} === 0`)}}function kU({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 DX(b,w,$,W){let{gen:Q,schema:G,data:D,allErrors:X,opts:Y,self:H}=b,{RULES:J}=H;if(G.$ref&&(Y.ignoreKeywordsWithRef||!(0,Gw.schemaHasRulesButRef)(G,J))){Q.block(()=>UX(b,"$ref",J.all.$ref.definition));return}if(!Y.jtd)CU(b,w);Q.block(()=>{for(let O of J.rules)z(O);z(J.post)});function z(O){if(!(0,T6.shouldUseGroup)(G,O))return;if(O.type){if(Q.if((0,Y$.checkDataType)(O.type,D,Y.strictNumbers)),XX(b,O),w.length===1&&w[0]===O.type&&$)Q.else(),(0,Y$.reportTypeError)(b);Q.endIf()}else XX(b,O);if(!X)Q.if(E._`${k.default.errors} === ${W||0}`)}}function XX(b,w){let{gen:$,schema:W,opts:{useDefaults:Q}}=b;if(Q)(0,FU.assignDefaults)(b,w.type);$.block(()=>{for(let G of w.rules)if((0,T6.shouldUseRule)(W,G))UX(b,G.keyword,G.definition,w.type)})}function CU(b,w){if(b.schemaEnv.meta||!b.opts.strictTypes)return;if(uU(b,w),!b.opts.allowUnionTypes)xU(b,w);yU(b,b.dataTypes)}function uU(b,w){if(!w.length)return;if(!b.dataTypes.length){b.dataTypes=w;return}w.forEach(($)=>{if(!LX(b.dataTypes,$))E6(b,`type "${$}" not allowed by context "${b.dataTypes.join(",")}"`)}),fU(b,w)}function xU(b,w){if(w.length>1&&!(w.length===2&&w.includes("null")))E6(b,"use allowUnionTypes to allow union type keyword")}function yU(b,w){let $=b.self.RULES.all;for(let W in $){let Q=$[W];if(typeof Q=="object"&&(0,T6.shouldUseRule)(b.schema,Q)){let{type:G}=Q.definition;if(G.length&&!G.some((D)=>hU(w,D)))E6(b,`missing type "${G.join(",")}" for keyword "${W}"`)}}}function hU(b,w){return b.includes(w)||w==="number"&&b.includes("integer")}function LX(b,w){return b.includes(w)||w==="integer"&&b.includes("number")}function fU(b,w){let $=[];for(let W of b.dataTypes)if(LX(w,W))$.push(W);else if(w.includes("integer")&&W==="number")$.push("integer");b.dataTypes=$}function E6(b,w){let $=b.schemaEnv.baseId+b.errSchemaPath;w+=` at "${$}" (strictTypes)`,(0,Gw.checkStrictMode)(b,w,b.opts.strictTypes)}class _6{constructor(b,w,$){if((0,i1.validateKeywordUsage)(b,w,$),this.gen=b.gen,this.allErrors=b.allErrors,this.keyword=$,this.data=b.data,this.schema=b.schema[$],this.$data=w.$data&&b.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Gw.schemaRefOrVal)(b,this.schema,$,this.$data),this.schemaType=w.schemaType,this.parentSchema=b.schema,this.params={},this.it=b,this.def=w,this.$data)this.schemaCode=b.gen.const("vSchema",BX(this.$data,b));else if(this.schemaCode=this.schemaValue,!(0,i1.validSchemaType)(this.schema,w.schemaType,w.allowUndefined))throw Error(`${$} value must be ${JSON.stringify(w.schemaType)}`);if("code"in w?w.trackErrors:w.errors!==!1)this.errsCount=b.gen.const("_errs",k.default.errors)}result(b,w,$){this.failResult((0,E.not)(b),w,$)}failResult(b,w,$){if(this.gen.if(b),$)$();else this.error();if(w){if(this.gen.else(),w(),this.allErrors)this.gen.endIf()}else if(this.allErrors)this.gen.endIf();else this.gen.else()}pass(b,w){this.failResult((0,E.not)(b),void 0,w)}fail(b){if(b===void 0){if(this.error(),!this.allErrors)this.gen.if(!1);return}if(this.gen.if(b),this.error(),this.allErrors)this.gen.endIf();else this.gen.else()}fail$data(b){if(!this.$data)return this.fail(b);let{schemaCode:w}=this;this.fail(E._`${w} !== undefined && (${(0,E.or)(this.invalid$data(),b)})`)}error(b,w,$){if(w){this.setParams(w),this._error(b,$),this.setParams({});return}this._error(b,$)}_error(b,w){(b?m1.reportExtraError:m1.reportError)(this,this.def.error,w)}$dataError(){(0,m1.reportError)(this,this.def.$dataError||m1.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error('add "trackErrors" to keyword definition');(0,m1.resetErrorsCount)(this.gen,this.errsCount)}ok(b){if(!this.allErrors)this.gen.if(b)}setParams(b,w){if(w)Object.assign(this.params,b);else this.params=b}block$data(b,w,$=E.nil){this.gen.block(()=>{this.check$data(b,$),w()})}check$data(b=E.nil,w=E.nil){if(!this.$data)return;let{gen:$,schemaCode:W,schemaType:Q,def:G}=this;if($.if((0,E.or)(E._`${W} === undefined`,w)),b!==E.nil)$.assign(b,!0);if(Q.length||G.validateSchema){if($.elseIf(this.invalid$data()),this.$dataError(),b!==E.nil)$.assign(b,!1)}$.else()}invalid$data(){let{gen:b,schemaCode:w,schemaType:$,def:W,it:Q}=this;return(0,E.or)(G(),D());function G(){if($.length){if(!(w instanceof E.Name))throw Error("ajv implementation error");let X=Array.isArray($)?$:[$];return E._`${(0,Y$.checkDataTypes)(X,w,Q.opts.strictNumbers,Y$.DataType.Wrong)}`}return E.nil}function D(){if(W.validateSchema){let X=b.scopeValue("validate$data",{ref:W.validateSchema});return E._`!${X}(${w})`}return E.nil}}subschema(b,w){let $=(0,N6.getSubschema)(this.it,b);(0,N6.extendSubschemaData)($,this.it,b),(0,N6.extendSubschemaMode)($,b);let W={...this.it,...$,items:void 0,props:void 0};return NU(W,w),W}mergeEvaluated(b,w){let{it:$,gen:W}=this;if(!$.opts.unevaluated)return;if($.props!==!0&&b.props!==void 0)$.props=Gw.mergeEvaluated.props(W,b.props,$.props,w);if($.items!==!0&&b.items!==void 0)$.items=Gw.mergeEvaluated.items(W,b.items,$.items,w)}mergeValidEvaluated(b,w){let{it:$,gen:W}=this;if($.opts.unevaluated&&($.props!==!0||$.items!==!0))return W.if(w,()=>this.mergeEvaluated(b,E.Name)),!0}}PX.KeywordCxt=_6;function UX(b,w,$,W){let Q=new _6(b,$,w);if("code"in $)$.code(Q,W);else if(Q.$data&&$.validate)(0,i1.funcKeywordCode)(Q,$);else if("macro"in $)(0,i1.macroKeywordCode)(Q,$);else if($.compile||$.validate)(0,i1.funcKeywordCode)(Q,$)}var cU=/^\/(?:[^~]|~0|~1)*$/,nU=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function BX(b,{dataLevel:w,dataNames:$,dataPathArr:W}){let Q,G;if(b==="")return k.default.rootData;if(b[0]==="/"){if(!cU.test(b))throw Error(`Invalid JSON-pointer: ${b}`);Q=b,G=k.default.rootData}else{let H=nU.exec(b);if(!H)throw Error(`Invalid JSON-pointer: ${b}`);let J=+H[1];if(Q=H[2],Q==="#"){if(J>=w)throw Error(Y("property/index",J));return W[w-J]}if(J>w)throw Error(Y("data",J));if(G=$[w-J],!Q)return G}let D=G,X=Q.split("/");for(let H of X)if(H)G=E._`${G}${(0,E.getProperty)((0,Gw.unescapeJsonPointer)(H))}`,D=E._`${D} && ${G}`;return D;function Y(H,J){return`Cannot access ${H} ${J} levels up, current level is ${w}`}}PX.getData=BX});var H$=j((MX)=>{Object.defineProperty(MX,"__esModule",{value:!0});class KX extends Error{constructor(b){super("validation failed");this.errors=b,this.ajv=this.validation=!0}}MX.default=KX});var p1=j((ZX)=>{Object.defineProperty(ZX,"__esModule",{value:!0});var S6=g1();class IX extends Error{constructor(b,w,$,W){super(W||`can't resolve reference ${$} from id ${w}`);this.missingRef=(0,S6.resolveUrl)(b,w,$),this.missingSchema=(0,S6.normalizeId)((0,S6.getFullPath)(b,this.missingRef))}}ZX.default=IX});var z$=j((NX)=>{Object.defineProperty(NX,"__esModule",{value:!0});NX.resolveSchema=NX.getCompilingSchema=NX.resolveRef=NX.compileSchema=NX.SchemaEnv=void 0;var cb=x(),pU=H$(),uw=Qw(),nb=g1(),jX=i(),oU=l1();class o1{constructor(b){var w;this.refs={},this.dynamicAnchors={};let $;if(typeof b.schema=="object")$=b.schema;this.schema=b.schema,this.schemaId=b.schemaId,this.root=b.root||this,this.baseId=(w=b.baseId)!==null&&w!==void 0?w:(0,nb.normalizeId)($===null||$===void 0?void 0:$[b.schemaId||"$id"]),this.schemaPath=b.schemaPath,this.localRefs=b.localRefs,this.meta=b.meta,this.$async=$===null||$===void 0?void 0:$.$async,this.refs={}}}NX.SchemaEnv=o1;function v6(b){let w=VX.call(this,b);if(w)return w;let $=(0,nb.getFullPath)(this.opts.uriResolver,b.root.baseId),{es5:W,lines:Q}=this.opts.code,{ownProperties:G}=this.opts,D=new cb.CodeGen(this.scope,{es5:W,lines:Q,ownProperties:G}),X;if(b.$async)X=D.scopeValue("Error",{ref:pU.default,code:cb._`require("ajv/dist/runtime/validation_error").default`});let Y=D.scopeName("validate");b.validateName=Y;let H={gen:D,allErrors:this.opts.allErrors,data:uw.default.data,parentData:uw.default.parentData,parentDataProperty:uw.default.parentDataProperty,dataNames:[uw.default.data],dataPathArr:[cb.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:D.scopeValue("schema",this.opts.code.source===!0?{ref:b.schema,code:(0,cb.stringify)(b.schema)}:{ref:b.schema}),validateName:Y,ValidationError:X,schema:b.schema,schemaEnv:b,rootId:$,baseId:b.baseId||$,schemaPath:cb.nil,errSchemaPath:b.schemaPath||(this.opts.jtd?"":"#"),errorPath:cb._`""`,opts:this.opts,self:this},J;try{this._compilations.add(b),(0,oU.validateFunctionCode)(H),D.optimize(this.opts.code.optimize);let z=D.toString();if(J=`${D.scopeRefs(uw.default.scope)}return ${z}`,this.opts.code.process)J=this.opts.code.process(J,b);let q=Function(`${uw.default.self}`,`${uw.default.scope}`,J)(this,this.scope.get());if(this.scope.value(Y,{ref:q}),q.errors=null,q.schema=b.schema,q.schemaEnv=b,b.$async)q.$async=!0;if(this.opts.code.source===!0)q.source={validateName:Y,validateCode:z,scopeValues:D._values};if(this.opts.unevaluated){let{props:B,items:K}=H;if(q.evaluated={props:B instanceof cb.Name?void 0:B,items:K instanceof cb.Name?void 0:K,dynamicProps:B instanceof cb.Name,dynamicItems:K instanceof cb.Name},q.source)q.source.evaluated=(0,cb.stringify)(q.evaluated)}return b.validate=q,b}catch(z){if(delete b.validate,delete b.validateName,J)this.logger.error("Error compiling schema, function code:",J);throw z}finally{this._compilations.delete(b)}}NX.compileSchema=v6;function dU(b,w,$){var W;$=(0,nb.resolveUrl)(this.opts.uriResolver,w,$);let Q=b.refs[$];if(Q)return Q;let G=eU.call(this,b,$);if(G===void 0){let D=(W=b.localRefs)===null||W===void 0?void 0:W[$],{schemaId:X}=this.opts;if(D)G=new o1({schema:D,schemaId:X,root:b,baseId:w})}if(G===void 0)return;return b.refs[$]=tU.call(this,G)}NX.resolveRef=dU;function tU(b){if((0,nb.inlineRef)(b.schema,this.opts.inlineRefs))return b.schema;return b.validate?b:v6.call(this,b)}function VX(b){for(let w of this._compilations)if(rU(w,b))return w}NX.getCompilingSchema=VX;function rU(b,w){return b.schema===w.schema&&b.root===w.root&&b.baseId===w.baseId}function eU(b,w){let $;while(typeof($=this.refs[w])=="string")w=$;return $||this.schemas[w]||J$.call(this,b,w)}function J$(b,w){let $=this.opts.uriResolver.parse(w),W=(0,nb._getFullPath)(this.opts.uriResolver,$),Q=(0,nb.getFullPath)(this.opts.uriResolver,b.baseId,void 0);if(Object.keys(b.schema).length>0&&W===Q)return R6.call(this,$,b);let G=(0,nb.normalizeId)(W),D=this.refs[G]||this.schemas[G];if(typeof D=="string"){let X=J$.call(this,b,D);if(typeof(X===null||X===void 0?void 0:X.schema)!=="object")return;return R6.call(this,$,X)}if(typeof(D===null||D===void 0?void 0:D.schema)!=="object")return;if(!D.validate)v6.call(this,D);if(G===(0,nb.normalizeId)(w)){let{schema:X}=D,{schemaId:Y}=this.opts,H=X[Y];if(H)Q=(0,nb.resolveUrl)(this.opts.uriResolver,Q,H);return new o1({schema:X,schemaId:Y,root:b,baseId:Q})}return R6.call(this,$,D)}NX.resolveSchema=J$;var sU=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function R6(b,{baseId:w,schema:$,root:W}){var Q;if(((Q=b.fragment)===null||Q===void 0?void 0:Q[0])!=="/")return;for(let X of b.fragment.slice(1).split("/")){if(typeof $==="boolean")return;let Y=$[(0,jX.unescapeFragment)(X)];if(Y===void 0)return;$=Y;let H=typeof $==="object"&&$[this.opts.schemaId];if(!sU.has(X)&&H)w=(0,nb.resolveUrl)(this.opts.uriResolver,w,H)}let G;if(typeof $!="boolean"&&$.$ref&&!(0,jX.schemaHasRulesButRef)($,this.RULES)){let X=(0,nb.resolveUrl)(this.opts.uriResolver,w,$.$ref);G=J$.call(this,W,X)}let{schemaId:D}=this.opts;if(G=G||new o1({schema:$,schemaId:D,root:W,baseId:w}),G.schema!==G.root.schema)return G;return}});var EX=j((wE,W3)=>{W3.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(($E,vX)=>{var Q3=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),SX=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function k6(b){let w="",$=0,W=0;for(W=0;W<b.length;W++){if($=b[W].charCodeAt(0),$===48)continue;if(!($>=48&&$<=57||$>=65&&$<=70||$>=97&&$<=102))return"";w+=b[W];break}for(W+=1;W<b.length;W++){if($=b[W].charCodeAt(0),!($>=48&&$<=57||$>=65&&$<=70||$>=97&&$<=102))return"";w+=b[W]}return w}var G3=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function _X(b){return b.length=0,!0}function D3(b,w,$){if(b.length){let W=k6(b);if(W!=="")w.push(W);else return $.error=!0,!1;b.length=0}return!0}function X3(b){let w=0,$={error:!1,address:"",zone:""},W=[],Q=[],G=!1,D=!1,X=D3;for(let Y=0;Y<b.length;Y++){let H=b[Y];if(H==="["||H==="]")continue;if(H===":"){if(G===!0)D=!0;if(!X(Q,W,$))break;if(++w>7){$.error=!0;break}if(Y>0&&b[Y-1]===":")G=!0;W.push(":");continue}else if(H==="%"){if(!X(Q,W,$))break;X=_X}else{Q.push(H);continue}}if(Q.length)if(X===_X)$.zone=Q.join("");else if(D)W.push(Q.join(""));else W.push(k6(Q));return $.address=W.join(""),$}function RX(b){if(Y3(b,":")<2)return{host:b,isIPV6:!1};let w=X3(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 Y3(b,w){let $=0;for(let W=0;W<b.length;W++)if(b[W]===w)$++;return $}function H3(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 J3(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 z3(b){let w=[];if(b.userinfo!==void 0)w.push(b.userinfo),w.push("@");if(b.host!==void 0){let $=unescape(b.host);if(!SX($)){let W=RX($);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}vX.exports={nonSimpleDomain:G3,recomposeAuthority:z3,normalizeComponentEncoding:J3,removeDotSegments:H3,isIPv4:SX,isUUID:Q3,normalizeIPv6:RX,stringArrayToHexStripped:k6}});var yX=j((WE,xX)=>{var{isUUID:A3}=C6(),O3=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,q3=["http","https","ws","wss","urn","urn:uuid"];function L3(b){return q3.indexOf(b)!==-1}function u6(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 kX(b){if(!b.host)b.error=b.error||"HTTP URIs must have a host.";return b}function CX(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 U3(b){return b.secure=u6(b),b.resourceName=(b.path||"/")+(b.query?"?"+b.query:""),b.path=void 0,b.query=void 0,b}function B3(b){if(b.port===(u6(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 P3(b,w){if(!b.path)return b.error="URN can not be parsed",b;let $=b.path.match(O3);if($){let W=w.scheme||b.scheme||"urn";b.nid=$[1].toLowerCase(),b.nss=$[2];let Q=`${W}:${w.nid||b.nid}`,G=x6(Q);if(b.path=void 0,G)b=G.parse(b,w)}else b.error=b.error||"URN can not be parsed.";return b}function F3(b,w){if(b.nid===void 0)throw Error("URN without nid cannot be serialized");let $=w.scheme||b.scheme||"urn",W=b.nid.toLowerCase(),Q=`${$}:${w.nid||W}`,G=x6(Q);if(G)b=G.serialize(b,w);let D=b,X=b.nss;return D.path=`${W||w.nid}:${X}`,w.skipEscape=!0,D}function K3(b,w){let $=b;if($.uuid=$.nss,$.nss=void 0,!w.tolerant&&(!$.uuid||!A3($.uuid)))$.error=$.error||"UUID is not valid.";return $}function M3(b){let w=b;return w.nss=(b.uuid||"").toLowerCase(),w}var uX={scheme:"http",domainHost:!0,parse:kX,serialize:CX},I3={scheme:"https",domainHost:uX.domainHost,parse:kX,serialize:CX},A$={scheme:"ws",domainHost:!0,parse:U3,serialize:B3},Z3={scheme:"wss",domainHost:A$.domainHost,parse:A$.parse,serialize:A$.serialize},j3={scheme:"urn",parse:P3,serialize:F3,skipNormalize:!0},V3={scheme:"urn:uuid",parse:K3,serialize:M3,skipNormalize:!0},O$={http:uX,https:I3,ws:A$,wss:Z3,urn:j3,"urn:uuid":V3};Object.setPrototypeOf(O$,null);function x6(b){return b&&(O$[b]||O$[b.toLowerCase()])||void 0}xX.exports={wsIsSecure:u6,SCHEMES:O$,isValidSchemeName:L3,getSchemeHandler:x6}});var cX=j((QE,L$)=>{var{normalizeIPv6:N3,removeDotSegments:d1,recomposeAuthority:T3,normalizeComponentEncoding:q$,isIPv4:E3,nonSimpleDomain:_3}=C6(),{SCHEMES:S3,getSchemeHandler:hX}=yX();function R3(b,w){if(typeof b==="string")b=tb(Dw(b,w),w);else if(typeof b==="object")b=Dw(tb(b,w),w);return b}function v3(b,w,$){let W=$?Object.assign({scheme:"null"},$):{scheme:"null"},Q=fX(Dw(b,W),Dw(w,W),W,!0);return W.skipEscape=!0,tb(Q,W)}function fX(b,w,$,W){let Q={};if(!W)b=Dw(tb(b,$),$),w=Dw(tb(w,$),$);if($=$||{},!$.tolerant&&w.scheme)Q.scheme=w.scheme,Q.userinfo=w.userinfo,Q.host=w.host,Q.port=w.port,Q.path=d1(w.path||""),Q.query=w.query;else{if(w.userinfo!==void 0||w.host!==void 0||w.port!==void 0)Q.userinfo=w.userinfo,Q.host=w.host,Q.port=w.port,Q.path=d1(w.path||""),Q.query=w.query;else{if(!w.path)if(Q.path=b.path,w.query!==void 0)Q.query=w.query;else Q.query=b.query;else{if(w.path[0]==="/")Q.path=d1(w.path);else{if((b.userinfo!==void 0||b.host!==void 0||b.port!==void 0)&&!b.path)Q.path="/"+w.path;else if(!b.path)Q.path=w.path;else Q.path=b.path.slice(0,b.path.lastIndexOf("/")+1)+w.path;Q.path=d1(Q.path)}Q.query=w.query}Q.userinfo=b.userinfo,Q.host=b.host,Q.port=b.port}Q.scheme=b.scheme}return Q.fragment=w.fragment,Q}function k3(b,w,$){if(typeof b==="string")b=unescape(b),b=tb(q$(Dw(b,$),!0),{...$,skipEscape:!0});else if(typeof b==="object")b=tb(q$(b,!0),{...$,skipEscape:!0});if(typeof w==="string")w=unescape(w),w=tb(q$(Dw(w,$),!0),{...$,skipEscape:!0});else if(typeof w==="object")w=tb(q$(w,!0),{...$,skipEscape:!0});return b.toLowerCase()===w.toLowerCase()}function tb(b,w){let $={host:b.host,scheme:b.scheme,userinfo:b.userinfo,port:b.port,path:b.path,query:b.query,nid:b.nid,nss:b.nss,uuid:b.uuid,fragment:b.fragment,reference:b.reference,resourceName:b.resourceName,secure:b.secure,error:""},W=Object.assign({},w),Q=[],G=hX(W.scheme||$.scheme);if(G&&G.serialize)G.serialize($,W);if($.path!==void 0)if(!W.skipEscape){if($.path=escape($.path),$.scheme!==void 0)$.path=$.path.split("%3A").join(":")}else $.path=unescape($.path);if(W.reference!=="suffix"&&$.scheme)Q.push($.scheme,":");let D=T3($);if(D!==void 0){if(W.reference!=="suffix")Q.push("//");if(Q.push(D),$.path&&$.path[0]!=="/")Q.push("/")}if($.path!==void 0){let X=$.path;if(!W.absolutePath&&(!G||!G.absolutePath))X=d1(X);if(D===void 0&&X[0]==="/"&&X[1]==="/")X="/%2F"+X.slice(2);Q.push(X)}if($.query!==void 0)Q.push("?",$.query);if($.fragment!==void 0)Q.push("#",$.fragment);return Q.join("")}var C3=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function Dw(b,w){let $=Object.assign({},w),W={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},Q=!1;if($.reference==="suffix")if($.scheme)b=$.scheme+":"+b;else b="//"+b;let G=b.match(C3);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(E3(W.host)===!1){let Y=N3(W.host);W.host=Y.host.toLowerCase(),Q=Y.isIPV6}else Q=!0;if(W.scheme===void 0&&W.userinfo===void 0&&W.host===void 0&&W.port===void 0&&W.query===void 0&&!W.path)W.reference="same-document";else if(W.scheme===void 0)W.reference="relative";else if(W.fragment===void 0)W.reference="absolute";else W.reference="uri";if($.reference&&$.reference!=="suffix"&&$.reference!==W.reference)W.error=W.error||"URI is not a "+$.reference+" reference.";let D=hX($.scheme||W.scheme);if(!$.unicodeSupport&&(!D||!D.unicodeSupport)){if(W.host&&($.domainHost||D&&D.domainHost)&&Q===!1&&_3(W.host))try{W.host=URL.domainToASCII(W.host.toLowerCase())}catch(X){W.error=W.error||"Host's domain name can not be converted to ASCII: "+X}}if(!D||D&&!D.skipNormalize){if(b.indexOf("%")!==-1){if(W.scheme!==void 0)W.scheme=unescape(W.scheme);if(W.host!==void 0)W.host=unescape(W.host)}if(W.path)W.path=escape(unescape(W.path));if(W.fragment)W.fragment=encodeURI(decodeURIComponent(W.fragment))}if(D&&D.parse)D.parse(W,$)}else W.error=W.error||"URI can not be parsed.";return W}var y6={SCHEMES:S3,normalize:R3,resolve:v3,resolveComponent:fX,equal:k3,serialize:tb,parse:Dw};L$.exports=y6;L$.exports.default=y6;L$.exports.fastUri=y6});var mX=j((gX)=>{Object.defineProperty(gX,"__esModule",{value:!0});var nX=cX();nX.code='require("ajv/dist/runtime/uri").default';gX.default=nX});var eX=j((Xw)=>{Object.defineProperty(Xw,"__esModule",{value:!0});Xw.CodeGen=Xw.Name=Xw.nil=Xw.stringify=Xw.str=Xw._=Xw.KeywordCxt=void 0;var x3=l1();Object.defineProperty(Xw,"KeywordCxt",{enumerable:!0,get:function(){return x3.KeywordCxt}});var sw=x();Object.defineProperty(Xw,"_",{enumerable:!0,get:function(){return sw._}});Object.defineProperty(Xw,"str",{enumerable:!0,get:function(){return sw.str}});Object.defineProperty(Xw,"stringify",{enumerable:!0,get:function(){return sw.stringify}});Object.defineProperty(Xw,"nil",{enumerable:!0,get:function(){return sw.nil}});Object.defineProperty(Xw,"Name",{enumerable:!0,get:function(){return sw.Name}});Object.defineProperty(Xw,"CodeGen",{enumerable:!0,get:function(){return sw.CodeGen}});var y3=H$(),dX=p1(),h3=U6(),t1=z$(),f3=x(),r1=g1(),U$=n1(),f6=i(),iX=EX(),c3=mX(),tX=(b,w)=>new RegExp(b,w);tX.code="new RegExp";var n3=["removeAdditional","useDefaults","coerceTypes"],g3=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),m3={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."},i3={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},lX=200;function l3(b){var w,$,W,Q,G,D,X,Y,H,J,z,O,q,B,K,I,M,v,S,h,R,pb,sb,p$,o$;let J1=b.strict,d$=(w=b.code)===null||w===void 0?void 0:w.optimize,kW=d$===!0||d$===void 0?1:d$||0,CW=(W=($=b.code)===null||$===void 0?void 0:$.regExp)!==null&&W!==void 0?W:tX,mz=(Q=b.uriResolver)!==null&&Q!==void 0?Q:c3.default;return{strictSchema:(D=(G=b.strictSchema)!==null&&G!==void 0?G:J1)!==null&&D!==void 0?D:!0,strictNumbers:(Y=(X=b.strictNumbers)!==null&&X!==void 0?X:J1)!==null&&Y!==void 0?Y:!0,strictTypes:(J=(H=b.strictTypes)!==null&&H!==void 0?H:J1)!==null&&J!==void 0?J:"log",strictTuples:(O=(z=b.strictTuples)!==null&&z!==void 0?z:J1)!==null&&O!==void 0?O:"log",strictRequired:(B=(q=b.strictRequired)!==null&&q!==void 0?q:J1)!==null&&B!==void 0?B:!1,code:b.code?{...b.code,optimize:kW,regExp:CW}:{optimize:kW,regExp:CW},loopRequired:(K=b.loopRequired)!==null&&K!==void 0?K:lX,loopEnum:(I=b.loopEnum)!==null&&I!==void 0?I:lX,meta:(M=b.meta)!==null&&M!==void 0?M:!0,messages:(v=b.messages)!==null&&v!==void 0?v:!0,inlineRefs:(S=b.inlineRefs)!==null&&S!==void 0?S:!0,schemaId:(h=b.schemaId)!==null&&h!==void 0?h:"$id",addUsedSchema:(R=b.addUsedSchema)!==null&&R!==void 0?R:!0,validateSchema:(pb=b.validateSchema)!==null&&pb!==void 0?pb:!0,validateFormats:(sb=b.validateFormats)!==null&&sb!==void 0?sb:!0,unicodeRegExp:(p$=b.unicodeRegExp)!==null&&p$!==void 0?p$:!0,int32range:(o$=b.int32range)!==null&&o$!==void 0?o$:!0,uriResolver:mz}}class B${constructor(b={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,b=this.opts={...b,...l3(b)};let{es5:w,lines:$}=this.opts.code;this.scope=new f3.ValueScope({scope:{},prefixes:g3,es5:w,lines:$}),this.logger=e3(b.logger);let W=b.validateFormats;if(b.validateFormats=!1,this.RULES=(0,h3.getRules)(),pX.call(this,m3,b,"NOT SUPPORTED"),pX.call(this,i3,b,"DEPRECATED","warn"),this._metaOpts=t3.call(this),b.formats)o3.call(this);if(this._addVocabularies(),this._addDefaultMetaSchema(),b.keywords)d3.call(this,b.keywords);if(typeof b.meta=="object")this.addMetaSchema(b.meta);p3.call(this),b.validateFormats=W}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:b,meta:w,schemaId:$}=this.opts,W=iX;if($==="id")W={...iX},W.id=W.$id,delete W.$id;if(w&&b)this.addMetaSchema(W,W[$],!1)}defaultMeta(){let{meta:b,schemaId:w}=this.opts;return this.opts.defaultMeta=typeof b=="object"?b[w]||b:void 0}validate(b,w){let $;if(typeof b=="string"){if($=this.getSchema(b),!$)throw Error(`no schema with key or ref "${b}"`)}else $=this.compile(b);let W=$(w);if(!("$async"in $))this.errors=$.errors;return W}compile(b,w){let $=this._addSchema(b,w);return $.validate||this._compileSchemaEnv($)}compileAsync(b,w){if(typeof this.opts.loadSchema!="function")throw Error("options.loadSchema should be a function");let{loadSchema:$}=this.opts;return W.call(this,b,w);async function W(H,J){await Q.call(this,H.$schema);let z=this._addSchema(H,J);return z.validate||G.call(this,z)}async function Q(H){if(H&&!this.getSchema(H))await W.call(this,{$ref:H},!0)}async function G(H){try{return this._compileSchemaEnv(H)}catch(J){if(!(J instanceof dX.default))throw J;return D.call(this,J),await X.call(this,J.missingSchema),G.call(this,H)}}function D({missingSchema:H,missingRef:J}){if(this.refs[H])throw Error(`AnySchema ${H} is loaded but ${J} cannot be resolved`)}async function X(H){let J=await Y.call(this,H);if(!this.refs[H])await Q.call(this,J.$schema);if(!this.refs[H])this.addSchema(J,H,w)}async function Y(H){let J=this._loading[H];if(J)return J;try{return await(this._loading[H]=$(H))}finally{delete this._loading[H]}}}addSchema(b,w,$,W=this.opts.validateSchema){if(Array.isArray(b)){for(let G of b)this.addSchema(G,void 0,$,W);return this}let Q;if(typeof b==="object"){let{schemaId:G}=this.opts;if(Q=b[G],Q!==void 0&&typeof Q!="string")throw Error(`schema ${G} must be string`)}return w=(0,r1.normalizeId)(w||Q),this._checkUnique(w),this.schemas[w]=this._addSchema(b,$,w,W,!0),this}addMetaSchema(b,w,$=this.opts.validateSchema){return this.addSchema(b,w,!0,$),this}validateSchema(b,w){if(typeof b=="boolean")return!0;let $;if($=b.$schema,$!==void 0&&typeof $!="string")throw Error("$schema must be a string");if($=$||this.opts.defaultMeta||this.defaultMeta(),!$)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let W=this.validate($,b);if(!W&&w){let Q="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(Q);else throw Error(Q)}return W}getSchema(b){let w;while(typeof(w=oX.call(this,b))=="string")b=w;if(w===void 0){let{schemaId:$}=this.opts,W=new t1.SchemaEnv({schema:{},schemaId:$});if(w=t1.resolveSchema.call(this,W,b),!w)return;this.refs[b]=w}return w.validate||this._compileSchemaEnv(w)}removeSchema(b){if(b instanceof RegExp)return this._removeAllSchemas(this.schemas,b),this._removeAllSchemas(this.refs,b),this;switch(typeof b){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let w=oX.call(this,b);if(typeof w=="object")this._cache.delete(w.schema);return delete this.schemas[b],delete this.refs[b],this}case"object":{let w=b;this._cache.delete(w);let $=b[this.opts.schemaId];if($)$=(0,r1.normalizeId)($),delete this.schemas[$],delete this.refs[$];return this}default:throw Error("ajv.removeSchema: invalid parameter")}}addVocabulary(b){for(let w of b)this.addKeyword(w);return this}addKeyword(b,w){let $;if(typeof b=="string"){if($=b,typeof w=="object")this.logger.warn("these parameters are deprecated, see docs for addKeyword"),w.keyword=$}else if(typeof b=="object"&&w===void 0){if(w=b,$=w.keyword,Array.isArray($)&&!$.length)throw Error("addKeywords: keyword must be string or non-empty array")}else throw Error("invalid addKeywords parameters");if(a3.call(this,$,w),!w)return(0,f6.eachItem)($,(Q)=>h6.call(this,Q)),this;wB.call(this,w);let W={...w,type:(0,U$.getJSONTypes)(w.type),schemaType:(0,U$.getJSONTypes)(w.schemaType)};return(0,f6.eachItem)($,W.type.length===0?(Q)=>h6.call(this,Q,W):(Q)=>W.type.forEach((G)=>h6.call(this,Q,W,G))),this}getKeyword(b){let w=this.RULES.all[b];return typeof w=="object"?w.definition:!!w}removeKeyword(b){let{RULES:w}=this;delete w.keywords[b],delete w.all[b];for(let $ of w.rules){let W=$.rules.findIndex((Q)=>Q.keyword===b);if(W>=0)$.rules.splice(W,1)}return this}addFormat(b,w){if(typeof w=="string")w=new RegExp(w);return this.formats[b]=w,this}errorsText(b=this.errors,{separator:w=", ",dataVar:$="data"}={}){if(!b||b.length===0)return"No errors";return b.map((W)=>`${$}${W.instancePath} ${W.message}`).reduce((W,Q)=>W+w+Q)}$dataMetaSchema(b,w){let $=this.RULES.all;b=JSON.parse(JSON.stringify(b));for(let W of w){let Q=W.split("/").slice(1),G=b;for(let D of Q)G=G[D];for(let D in $){let X=$[D];if(typeof X!="object")continue;let{$data:Y}=X.definition,H=G[D];if(Y&&H)G[D]=rX(H)}}return b}_removeAllSchemas(b,w){for(let $ in b){let W=b[$];if(!w||w.test($)){if(typeof W=="string")delete b[$];else if(W&&!W.meta)this._cache.delete(W.schema),delete b[$]}}}_addSchema(b,w,$,W=this.opts.validateSchema,Q=this.opts.addUsedSchema){let G,{schemaId:D}=this.opts;if(typeof b=="object")G=b[D];else if(this.opts.jtd)throw Error("schema must be object");else if(typeof b!="boolean")throw Error("schema must be object or boolean");let X=this._cache.get(b);if(X!==void 0)return X;$=(0,r1.normalizeId)(G||$);let Y=r1.getSchemaRefs.call(this,b,$);if(X=new t1.SchemaEnv({schema:b,schemaId:D,meta:w,baseId:$,localRefs:Y}),this._cache.set(X.schema,X),Q&&!$.startsWith("#")){if($)this._checkUnique($);this.refs[$]=X}if(W)this.validateSchema(b,!0);return X}_checkUnique(b){if(this.schemas[b]||this.refs[b])throw Error(`schema with key or id "${b}" already exists`)}_compileSchemaEnv(b){if(b.meta)this._compileMetaSchema(b);else t1.compileSchema.call(this,b);if(!b.validate)throw Error("ajv implementation error");return b.validate}_compileMetaSchema(b){let w=this.opts;this.opts=this._metaOpts;try{t1.compileSchema.call(this,b)}finally{this.opts=w}}}B$.ValidationError=y3.default;B$.MissingRefError=dX.default;Xw.default=B$;function pX(b,w,$,W="error"){for(let Q in b){let G=Q;if(G in w)this.logger[W](`${$}: option ${Q}. ${b[G]}`)}}function oX(b){return b=(0,r1.normalizeId)(b),this.schemas[b]||this.refs[b]}function p3(){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 o3(){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 t3(){let b={...this.opts};for(let w of n3)delete b[w];return b}var r3={log(){},warn(){},error(){}};function e3(b){if(b===!1)return r3;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 s3=/^[a-z_$][a-z0-9_$:-]*$/i;function a3(b,w){let{RULES:$}=this;if((0,f6.eachItem)(b,(W)=>{if($.keywords[W])throw Error(`Keyword ${W} is already defined`);if(!s3.test(W))throw Error(`Keyword ${W} has invalid name`)}),!w)return;if(w.$data&&!(("code"in w)||("validate"in w)))throw Error('$data keyword must have "code" or "validate" function')}function h6(b,w,$){var W;let Q=w===null||w===void 0?void 0:w.post;if($&&Q)throw Error('keyword with "post" flag cannot have "type"');let{RULES:G}=this,D=Q?G.post:G.rules.find(({type:Y})=>Y===$);if(!D)D={type:$,rules:[]},G.rules.push(D);if(G.keywords[b]=!0,!w)return;let X={keyword:b,definition:{...w,type:(0,U$.getJSONTypes)(w.type),schemaType:(0,U$.getJSONTypes)(w.schemaType)}};if(w.before)bB.call(this,D,X,w.before);else D.rules.push(X);G.all[b]=X,(W=w.implements)===null||W===void 0||W.forEach((Y)=>this.addKeyword(Y))}function bB(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 wB(b){let{metaSchema:w}=b;if(w===void 0)return;if(b.$data&&this.opts.$data)w=rX(w);b.validateSchema=this.compile(w,!0)}var $B={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function rX(b){return{anyOf:[b,$B]}}});var aX=j((sX)=>{Object.defineProperty(sX,"__esModule",{value:!0});var GB={keyword:"id",code(){throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};sX.default=GB});var GY=j((WY)=>{Object.defineProperty(WY,"__esModule",{value:!0});WY.callRef=WY.getValidate=void 0;var XB=p1(),bY=Cb(),jb=x(),aw=Qw(),wY=z$(),P$=i(),YB={keyword:"$ref",schemaType:"string",code(b){let{gen:w,schema:$,it:W}=b,{baseId:Q,schemaEnv:G,validateName:D,opts:X,self:Y}=W,{root:H}=G;if(($==="#"||$==="#/")&&Q===H.baseId)return z();let J=wY.resolveRef.call(Y,H,Q,$);if(J===void 0)throw new XB.default(W.opts.uriResolver,Q,$);if(J instanceof wY.SchemaEnv)return O(J);return q(J);function z(){if(G===H)return F$(b,D,G,G.$async);let B=w.scopeValue("root",{ref:H});return F$(b,jb._`${B}.validate`,H,H.$async)}function O(B){let K=$Y(b,B);F$(b,K,B,B.$async)}function q(B){let K=w.scopeValue("schema",X.code.source===!0?{ref:B,code:(0,jb.stringify)(B)}:{ref:B}),I=w.name("valid"),M=b.subschema({schema:B,dataTypes:[],schemaPath:jb.nil,topSchemaRef:K,errSchemaPath:$},I);b.mergeEvaluated(M),b.ok(I)}}};function $Y(b,w){let{gen:$}=b;return w.validate?$.scopeValue("validate",{ref:w.validate}):jb._`${$.scopeValue("wrapper",{ref:w})}.validate`}WY.getValidate=$Y;function F$(b,w,$,W){let{gen:Q,it:G}=b,{allErrors:D,schemaEnv:X,opts:Y}=G,H=Y.passContext?aw.default.this:jb.nil;if(W)J();else z();function J(){if(!X.$async)throw Error("async schema referenced by sync schema");let B=Q.let("valid");Q.try(()=>{if(Q.code(jb._`await ${(0,bY.callValidateCode)(b,w,H)}`),q(w),!D)Q.assign(B,!0)},(K)=>{if(Q.if(jb._`!(${K} instanceof ${G.ValidationError})`,()=>Q.throw(K)),O(K),!D)Q.assign(B,!1)}),b.ok(B)}function z(){b.result((0,bY.callValidateCode)(b,w,H),()=>q(w),()=>O(w))}function O(B){let K=jb._`${B}.errors`;Q.assign(aw.default.vErrors,jb._`${aw.default.vErrors} === null ? ${K} : ${aw.default.vErrors}.concat(${K})`),Q.assign(aw.default.errors,jb._`${aw.default.vErrors}.length`)}function q(B){var K;if(!G.opts.unevaluated)return;let I=(K=$===null||$===void 0?void 0:$.validate)===null||K===void 0?void 0:K.evaluated;if(G.props!==!0)if(I&&!I.dynamicProps){if(I.props!==void 0)G.props=P$.mergeEvaluated.props(Q,I.props,G.props)}else{let M=Q.var("props",jb._`${B}.evaluated.props`);G.props=P$.mergeEvaluated.props(Q,M,G.props,jb.Name)}if(G.items!==!0)if(I&&!I.dynamicItems){if(I.items!==void 0)G.items=P$.mergeEvaluated.items(Q,I.items,G.items)}else{let M=Q.var("items",jb._`${B}.evaluated.items`);G.items=P$.mergeEvaluated.items(Q,M,G.items,jb.Name)}}}WY.callRef=F$;WY.default=YB});var XY=j((DY)=>{Object.defineProperty(DY,"__esModule",{value:!0});var zB=aX(),AB=GY(),OB=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",zB.default,AB.default];DY.default=OB});var HY=j((YY)=>{Object.defineProperty(YY,"__esModule",{value:!0});var K$=x(),Tw=K$.operators,M$={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}},LB={message:({keyword:b,schemaCode:w})=>K$.str`must be ${M$[b].okStr} ${w}`,params:({keyword:b,schemaCode:w})=>K$._`{comparison: ${M$[b].okStr}, limit: ${w}}`},UB={keyword:Object.keys(M$),type:"number",schemaType:"number",$data:!0,error:LB,code(b){let{keyword:w,data:$,schemaCode:W}=b;b.fail$data(K$._`${$} ${M$[w].fail} ${W} || isNaN(${$})`)}};YY.default=UB});var zY=j((JY)=>{Object.defineProperty(JY,"__esModule",{value:!0});var e1=x(),PB={message:({schemaCode:b})=>e1.str`must be multiple of ${b}`,params:({schemaCode:b})=>e1._`{multipleOf: ${b}}`},FB={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:PB,code(b){let{gen:w,data:$,schemaCode:W,it:Q}=b,G=Q.opts.multipleOfPrecision,D=w.let("res"),X=G?e1._`Math.abs(Math.round(${D}) - ${D}) > 1e-${G}`:e1._`${D} !== parseInt(${D})`;b.fail$data(e1._`(${W} === 0 || (${D} = ${$}/${W}, ${X}))`)}};JY.default=FB});var qY=j((OY)=>{Object.defineProperty(OY,"__esModule",{value:!0});function AY(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 $}OY.default=AY;AY.code='require("ajv/dist/runtime/ucs2length").default'});var UY=j((LY)=>{Object.defineProperty(LY,"__esModule",{value:!0});var xw=x(),IB=i(),ZB=qY(),jB={message({keyword:b,schemaCode:w}){let $=b==="maxLength"?"more":"fewer";return xw.str`must NOT have ${$} than ${w} characters`},params:({schemaCode:b})=>xw._`{limit: ${b}}`},VB={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:jB,code(b){let{keyword:w,data:$,schemaCode:W,it:Q}=b,G=w==="maxLength"?xw.operators.GT:xw.operators.LT,D=Q.opts.unicode===!1?xw._`${$}.length`:xw._`${(0,IB.useFunc)(b.gen,ZB.default)}(${$})`;b.fail$data(xw._`${D} ${G} ${W}`)}};LY.default=VB});var PY=j((BY)=>{Object.defineProperty(BY,"__esModule",{value:!0});var TB=Cb(),I$=x(),EB={message:({schemaCode:b})=>I$.str`must match pattern "${b}"`,params:({schemaCode:b})=>I$._`{pattern: ${b}}`},_B={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:EB,code(b){let{data:w,$data:$,schema:W,schemaCode:Q,it:G}=b,D=G.opts.unicodeRegExp?"u":"",X=$?I$._`(new RegExp(${Q}, ${D}))`:(0,TB.usePattern)(b,W);b.fail$data(I$._`!${X}.test(${w})`)}};BY.default=_B});var KY=j((FY)=>{Object.defineProperty(FY,"__esModule",{value:!0});var s1=x(),RB={message({keyword:b,schemaCode:w}){let $=b==="maxProperties"?"more":"fewer";return s1.str`must NOT have ${$} than ${w} properties`},params:({schemaCode:b})=>s1._`{limit: ${b}}`},vB={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:RB,code(b){let{keyword:w,data:$,schemaCode:W}=b,Q=w==="maxProperties"?s1.operators.GT:s1.operators.LT;b.fail$data(s1._`Object.keys(${$}).length ${Q} ${W}`)}};FY.default=vB});var IY=j((MY)=>{Object.defineProperty(MY,"__esModule",{value:!0});var a1=Cb(),b0=x(),CB=i(),uB={message:({params:{missingProperty:b}})=>b0.str`must have required property '${b}'`,params:({params:{missingProperty:b}})=>b0._`{missingProperty: ${b}}`},xB={keyword:"required",type:"object",schemaType:"array",$data:!0,error:uB,code(b){let{gen:w,schema:$,schemaCode:W,data:Q,$data:G,it:D}=b,{opts:X}=D;if(!G&&$.length===0)return;let Y=$.length>=X.loopRequired;if(D.allErrors)H();else J();if(X.strictRequired){let q=b.parentSchema.properties,{definedProperties:B}=b.it;for(let K of $)if((q===null||q===void 0?void 0:q[K])===void 0&&!B.has(K)){let I=D.schemaEnv.baseId+D.errSchemaPath,M=`required property "${K}" is not defined at "${I}" (strictRequired)`;(0,CB.checkStrictMode)(D,M,D.opts.strictRequired)}}function H(){if(Y||G)b.block$data(b0.nil,z);else for(let q of $)(0,a1.checkReportMissingProp)(b,q)}function J(){let q=w.let("missing");if(Y||G){let B=w.let("valid",!0);b.block$data(B,()=>O(q,B)),b.ok(B)}else w.if((0,a1.checkMissingProp)(b,$,q)),(0,a1.reportMissingProp)(b,q),w.else()}function z(){w.forOf("prop",W,(q)=>{b.setParams({missingProperty:q}),w.if((0,a1.noPropertyInData)(w,Q,q,X.ownProperties),()=>b.error())})}function O(q,B){b.setParams({missingProperty:q}),w.forOf(q,W,()=>{w.assign(B,(0,a1.propertyInData)(w,Q,q,X.ownProperties)),w.if((0,b0.not)(B),()=>{b.error(),w.break()})},b0.nil)}}};MY.default=xB});var jY=j((ZY)=>{Object.defineProperty(ZY,"__esModule",{value:!0});var w0=x(),hB={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}}`},fB={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:hB,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}`)}};ZY.default=fB});var Z$=j((NY)=>{Object.defineProperty(NY,"__esModule",{value:!0});var VY=j6();VY.code='require("ajv/dist/runtime/equal").default';NY.default=VY});var EY=j((TY)=>{Object.defineProperty(TY,"__esModule",{value:!0});var c6=n1(),qb=x(),gB=i(),mB=Z$(),iB={message:({params:{i:b,j:w}})=>qb.str`must NOT have duplicate items (items ## ${w} and ${b} are identical)`,params:({params:{i:b,j:w}})=>qb._`{i: ${b}, j: ${w}}`},lB={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:iB,code(b){let{gen:w,data:$,$data:W,schema:Q,parentSchema:G,schemaCode:D,it:X}=b;if(!W&&!Q)return;let Y=w.let("valid"),H=G.items?(0,c6.getSchemaTypes)(G.items):[];b.block$data(Y,J,qb._`${D} === false`),b.ok(Y);function J(){let B=w.let("i",qb._`${$}.length`),K=w.let("j");b.setParams({i:B,j:K}),w.assign(Y,!0),w.if(qb._`${B} > 1`,()=>(z()?O:q)(B,K))}function z(){return H.length>0&&!H.some((B)=>B==="object"||B==="array")}function O(B,K){let I=w.name("item"),M=(0,c6.checkDataTypes)(H,I,X.opts.strictNumbers,c6.DataType.Wrong),v=w.const("indices",qb._`{}`);w.for(qb._`;${B}--;`,()=>{if(w.let(I,qb._`${$}[${B}]`),w.if(M,qb._`continue`),H.length>1)w.if(qb._`typeof ${I} == "string"`,qb._`${I} += "_"`);w.if(qb._`typeof ${v}[${I}] == "number"`,()=>{w.assign(K,qb._`${v}[${I}]`),b.error(),w.assign(Y,!1).break()}).code(qb._`${v}[${I}] = ${B}`)})}function q(B,K){let I=(0,gB.useFunc)(w,mB.default),M=w.name("outer");w.label(M).for(qb._`;${B}--;`,()=>w.for(qb._`${K} = ${B}; ${K}--;`,()=>w.if(qb._`${I}(${$}[${B}], ${$}[${K}])`,()=>{b.error(),w.assign(Y,!1).break(M)})))}}};TY.default=lB});var SY=j((_Y)=>{Object.defineProperty(_Y,"__esModule",{value:!0});var n6=x(),oB=i(),dB=Z$(),tB={message:"must be equal to constant",params:({schemaCode:b})=>n6._`{allowedValue: ${b}}`},rB={keyword:"const",$data:!0,error:tB,code(b){let{gen:w,data:$,$data:W,schemaCode:Q,schema:G}=b;if(W||G&&typeof G=="object")b.fail$data(n6._`!${(0,oB.useFunc)(w,dB.default)}(${$}, ${Q})`);else b.fail(n6._`${G} !== ${$}`)}};_Y.default=rB});var vY=j((RY)=>{Object.defineProperty(RY,"__esModule",{value:!0});var $0=x(),sB=i(),aB=Z$(),bP={message:"must be equal to one of the allowed values",params:({schemaCode:b})=>$0._`{allowedValues: ${b}}`},wP={keyword:"enum",schemaType:"array",$data:!0,error:bP,code(b){let{gen:w,data:$,$data:W,schema:Q,schemaCode:G,it:D}=b;if(!W&&Q.length===0)throw Error("enum must have non-empty array");let X=Q.length>=D.opts.loopEnum,Y,H=()=>Y!==null&&Y!==void 0?Y:Y=(0,sB.useFunc)(w,aB.default),J;if(X||W)J=w.let("valid"),b.block$data(J,z);else{if(!Array.isArray(Q))throw Error("ajv implementation error");let q=w.const("vSchema",G);J=(0,$0.or)(...Q.map((B,K)=>O(q,K)))}b.pass(J);function z(){w.assign(J,!1),w.forOf("v",G,(q)=>w.if($0._`${H()}(${$}, ${q})`,()=>w.assign(J,!0).break()))}function O(q,B){let K=Q[B];return typeof K==="object"&&K!==null?$0._`${H()}(${$}, ${q}[${B}])`:$0._`${$} === ${K}`}}};RY.default=wP});var CY=j((kY)=>{Object.defineProperty(kY,"__esModule",{value:!0});var WP=HY(),QP=zY(),GP=UY(),DP=PY(),XP=KY(),YP=IY(),HP=jY(),JP=EY(),zP=SY(),AP=vY(),OP=[WP.default,QP.default,GP.default,DP.default,XP.default,YP.default,HP.default,JP.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},zP.default,AP.default];kY.default=OP});var m6=j((xY)=>{Object.defineProperty(xY,"__esModule",{value:!0});xY.validateAdditionalItems=void 0;var yw=x(),g6=i(),LP={message:({params:{len:b}})=>yw.str`must NOT have more than ${b} items`,params:({params:{len:b}})=>yw._`{limit: ${b}}`},UP={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:LP,code(b){let{parentSchema:w,it:$}=b,{items:W}=w;if(!Array.isArray(W)){(0,g6.checkStrictMode)($,'"additionalItems" is ignored when "items" is not an array of schemas');return}uY(b,W)}};function uY(b,w){let{gen:$,schema:W,data:Q,keyword:G,it:D}=b;D.items=!0;let X=$.const("len",yw._`${Q}.length`);if(W===!1)b.setParams({len:w.length}),b.pass(yw._`${X} <= ${w.length}`);else if(typeof W=="object"&&!(0,g6.alwaysValidSchema)(D,W)){let H=$.var("valid",yw._`${X} <= ${w.length}`);$.if((0,yw.not)(H),()=>Y(H)),b.ok(H)}function Y(H){$.forRange("i",w.length,X,(J)=>{if(b.subschema({keyword:G,dataProp:J,dataPropType:g6.Type.Num},H),!D.allErrors)$.if((0,yw.not)(H),()=>$.break())})}}xY.validateAdditionalItems=uY;xY.default=UP});var i6=j((cY)=>{Object.defineProperty(cY,"__esModule",{value:!0});cY.validateTuple=void 0;var hY=x(),j$=i(),PP=Cb(),FP={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(b){let{schema:w,it:$}=b;if(Array.isArray(w))return fY(b,"additionalItems",w);if($.items=!0,(0,j$.alwaysValidSchema)($,w))return;b.ok((0,PP.validateArray)(b))}};function fY(b,w,$=b.schema){let{gen:W,parentSchema:Q,data:G,keyword:D,it:X}=b;if(J(Q),X.opts.unevaluated&&$.length&&X.items!==!0)X.items=j$.mergeEvaluated.items(W,$.length,X.items);let Y=W.name("valid"),H=W.const("len",hY._`${G}.length`);$.forEach((z,O)=>{if((0,j$.alwaysValidSchema)(X,z))return;W.if(hY._`${H} > ${O}`,()=>b.subschema({keyword:D,schemaProp:O,dataProp:O},Y)),b.ok(Y)});function J(z){let{opts:O,errSchemaPath:q}=X,B=$.length,K=B===z.minItems&&(B===z.maxItems||z[w]===!1);if(O.strictTuples&&!K){let I=`"${D}" is ${B}-tuple, but minItems or maxItems/${w} are not specified or different at path "${q}"`;(0,j$.checkStrictMode)(X,I,O.strictTuples)}}}cY.validateTuple=fY;cY.default=FP});var mY=j((gY)=>{Object.defineProperty(gY,"__esModule",{value:!0});var MP=i6(),IP={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:(b)=>(0,MP.validateTuple)(b,"items")};gY.default=IP});var pY=j((lY)=>{Object.defineProperty(lY,"__esModule",{value:!0});var iY=x(),jP=i(),VP=Cb(),NP=m6(),TP={message:({params:{len:b}})=>iY.str`must NOT have more than ${b} items`,params:({params:{len:b}})=>iY._`{limit: ${b}}`},EP={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:TP,code(b){let{schema:w,parentSchema:$,it:W}=b,{prefixItems:Q}=$;if(W.items=!0,(0,jP.alwaysValidSchema)(W,w))return;if(Q)(0,NP.validateAdditionalItems)(b,Q);else b.ok((0,VP.validateArray)(b))}};lY.default=EP});var dY=j((oY)=>{Object.defineProperty(oY,"__esModule",{value:!0});var ub=x(),V$=i(),SP={message:({params:{min:b,max:w}})=>w===void 0?ub.str`must contain at least ${b} valid item(s)`:ub.str`must contain at least ${b} and no more than ${w} valid item(s)`,params:({params:{min:b,max:w}})=>w===void 0?ub._`{minContains: ${b}}`:ub._`{minContains: ${b}, maxContains: ${w}}`},RP={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:SP,code(b){let{gen:w,schema:$,parentSchema:W,data:Q,it:G}=b,D,X,{minContains:Y,maxContains:H}=W;if(G.opts.next)D=Y===void 0?1:Y,X=H;else D=1;let J=w.const("len",ub._`${Q}.length`);if(b.setParams({min:D,max:X}),X===void 0&&D===0){(0,V$.checkStrictMode)(G,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(X!==void 0&&D>X){(0,V$.checkStrictMode)(G,'"minContains" > "maxContains" is always invalid'),b.fail();return}if((0,V$.alwaysValidSchema)(G,$)){let K=ub._`${J} >= ${D}`;if(X!==void 0)K=ub._`${K} && ${J} <= ${X}`;b.pass(K);return}G.items=!0;let z=w.name("valid");if(X===void 0&&D===1)q(z,()=>w.if(z,()=>w.break()));else if(D===0){if(w.let(z,!0),X!==void 0)w.if(ub._`${Q}.length > 0`,O)}else w.let(z,!1),O();b.result(z,()=>b.reset());function O(){let K=w.name("_valid"),I=w.let("count",0);q(K,()=>w.if(K,()=>B(I)))}function q(K,I){w.forRange("i",0,J,(M)=>{b.subschema({keyword:"contains",dataProp:M,dataPropType:V$.Type.Num,compositeRule:!0},K),I()})}function B(K){if(w.code(ub._`${K}++`),X===void 0)w.if(ub._`${K} >= ${D}`,()=>w.assign(z,!0).break());else if(w.if(ub._`${K} > ${X}`,()=>w.assign(z,!1).break()),D===1)w.assign(z,!0);else w.if(ub._`${K} >= ${D}`,()=>w.assign(z,!0))}}};oY.default=RP});var bH=j((eY)=>{Object.defineProperty(eY,"__esModule",{value:!0});eY.validateSchemaDeps=eY.validatePropertyDeps=eY.error=void 0;var l6=x(),kP=i(),W0=Cb();eY.error={message:({params:{property:b,depsCount:w,deps:$}})=>{let W=w===1?"property":"properties";return l6.str`must have ${W} ${$} when property ${b} is present`},params:({params:{property:b,depsCount:w,deps:$,missingProperty:W}})=>l6._`{property: ${b},
7
7
  missingProperty: ${W},
8
8
  depsCount: ${w},
9
- deps: ${$}}`};var CP={keyword:"dependencies",type:"object",schemaType:"object",error:eY.error,code(b){let[w,$]=uP(b);tY(b,w),rY(b,$)}};function uP({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 tY(b,w=b.schema){let{gen:$,data:W,it:Q}=b;if(Object.keys(w).length===0)return;let G=$.let("missing");for(let D in w){let X=w[D];if(X.length===0)continue;let Y=(0,W0.propertyInData)($,W,D,Q.opts.ownProperties);if(b.setParams({property:D,depsCount:X.length,deps:X.join(", ")}),Q.allErrors)$.if(Y,()=>{for(let H of X)(0,W0.checkReportMissingProp)(b,H)});else $.if(l4._`${Y} && (${(0,W0.checkMissingProp)(b,X,G)})`),(0,W0.reportMissingProp)(b,G),$.else()}}eY.validatePropertyDeps=tY;function rY(b,w=b.schema){let{gen:$,data:W,keyword:Q,it:G}=b,D=$.name("valid");for(let X in w){if((0,kP.alwaysValidSchema)(G,w[X]))continue;$.if((0,W0.propertyInData)($,W,X,G.opts.ownProperties),()=>{let Y=b.subschema({keyword:Q,schemaProp:X},D);b.mergeValidEvaluated(Y,D)},()=>$.var(D,!0)),b.ok(D)}}eY.validateSchemaDeps=rY;eY.default=CP});var WH=j(($H)=>{Object.defineProperty($H,"__esModule",{value:!0});var wH=x(),hP=i(),fP={message:"property name must be valid",params:({params:b})=>wH._`{propertyName: ${b.propertyName}}`},cP={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:fP,code(b){let{gen:w,schema:$,data:W,it:Q}=b;if((0,hP.alwaysValidSchema)(Q,$))return;let G=w.name("valid");w.forIn("key",W,(D)=>{b.setParams({propertyName:D}),b.subschema({keyword:"propertyNames",data:D,dataTypes:["string"],propertyName:D,compositeRule:!0},G),w.if((0,wH.not)(G),()=>{if(b.error(!0),!Q.allErrors)w.break()})}),b.ok(G)}};$H.default=cP});var p4=j((QH)=>{Object.defineProperty(QH,"__esModule",{value:!0});var N$=Cb(),gb=x(),gP=Qw(),T$=i(),mP={message:"must NOT have additional properties",params:({params:b})=>gb._`{additionalProperty: ${b.additionalProperty}}`},iP={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:mP,code(b){let{gen:w,schema:$,parentSchema:W,data:Q,errsCount:G,it:D}=b;if(!G)throw Error("ajv implementation error");let{allErrors:X,opts:Y}=D;if(D.props=!0,Y.removeAdditional!=="all"&&(0,T$.alwaysValidSchema)(D,$))return;let H=(0,N$.allSchemaProperties)(W.properties),J=(0,N$.allSchemaProperties)(W.patternProperties);z(),b.ok(gb._`${G} === ${gP.default.errors}`);function z(){w.forIn("key",Q,(I)=>{if(!H.length&&!J.length)B(I);else w.if(O(I),()=>B(I))})}function O(I){let M;if(H.length>8){let v=(0,T$.schemaRefOrVal)(D,W.properties,"properties");M=(0,N$.isOwnProperty)(w,v,I)}else if(H.length)M=(0,gb.or)(...H.map((v)=>gb._`${I} === ${v}`));else M=gb.nil;if(J.length)M=(0,gb.or)(M,...J.map((v)=>gb._`${(0,N$.usePattern)(b,v)}.test(${I})`));return(0,gb.not)(M)}function q(I){w.code(gb._`delete ${Q}[${I}]`)}function B(I){if(Y.removeAdditional==="all"||Y.removeAdditional&&$===!1){q(I);return}if($===!1){if(b.setParams({additionalProperty:I}),b.error(),!X)w.break();return}if(typeof $=="object"&&!(0,T$.alwaysValidSchema)(D,$)){let M=w.name("valid");if(Y.removeAdditional==="failing")K(I,M,!1),w.if((0,gb.not)(M),()=>{b.reset(),q(I)});else if(K(I,M),!X)w.if((0,gb.not)(M),()=>w.break())}}function K(I,M,v){let S={keyword:"additionalProperties",dataProp:I,dataPropType:T$.Type.Str};if(v===!1)Object.assign(S,{compositeRule:!0,createErrors:!1,allErrors:!1});b.subschema(S,M)}}};QH.default=iP});var YH=j((XH)=>{Object.defineProperty(XH,"__esModule",{value:!0});var pP=l1(),GH=Cb(),o4=i(),DH=p4(),oP={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)DH.default.code(new pP.KeywordCxt(G,DH.default,"additionalProperties"));let D=(0,GH.allSchemaProperties)($);for(let z of D)G.definedProperties.add(z);if(G.opts.unevaluated&&D.length&&G.props!==!0)G.props=o4.mergeEvaluated.props(w,(0,o4.toHash)(D),G.props);let X=D.filter((z)=>!(0,o4.alwaysValidSchema)(G,$[z]));if(X.length===0)return;let Y=w.name("valid");for(let z of X){if(H(z))J(z);else{if(w.if((0,GH.propertyInData)(w,Q,z,G.opts.ownProperties)),J(z),!G.allErrors)w.else().var(Y,!0);w.endIf()}b.it.definedProperties.add(z),b.ok(Y)}function H(z){return G.opts.useDefaults&&!G.compositeRule&&$[z].default!==void 0}function J(z){b.subschema({keyword:"properties",schemaProp:z,dataProp:z},Y)}}};XH.default=oP});var OH=j((AH)=>{Object.defineProperty(AH,"__esModule",{value:!0});var HH=Cb(),E$=x(),JH=i(),zH=i(),tP={keyword:"patternProperties",type:"object",schemaType:"object",code(b){let{gen:w,schema:$,data:W,parentSchema:Q,it:G}=b,{opts:D}=G,X=(0,HH.allSchemaProperties)($),Y=X.filter((K)=>(0,JH.alwaysValidSchema)(G,$[K]));if(X.length===0||Y.length===X.length&&(!G.opts.unevaluated||G.props===!0))return;let H=D.strictSchema&&!D.allowMatchingProperties&&Q.properties,J=w.name("valid");if(G.props!==!0&&!(G.props instanceof E$.Name))G.props=(0,zH.evaluatedPropsToName)(w,G.props);let{props:z}=G;O();function O(){for(let K of X){if(H)q(K);if(G.allErrors)B(K);else w.var(J,!0),B(K),w.if(J)}}function q(K){for(let I in H)if(new RegExp(K).test(I))(0,JH.checkStrictMode)(G,`property ${I} matches pattern ${K} (use allowMatchingProperties)`)}function B(K){w.forIn("key",W,(I)=>{w.if(E$._`${(0,HH.usePattern)(b,K)}.test(${I})`,()=>{let M=Y.includes(K);if(!M)b.subschema({keyword:"patternProperties",schemaProp:K,dataProp:I,dataPropType:zH.Type.Str},J);if(G.opts.unevaluated&&z!==!0)w.assign(E$._`${z}[${I}]`,!0);else if(!M&&!G.allErrors)w.if((0,E$.not)(J),()=>w.break())})})}}};AH.default=tP});var LH=j((qH)=>{Object.defineProperty(qH,"__esModule",{value:!0});var eP=i(),sP={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(b){let{gen:w,schema:$,it:W}=b;if((0,eP.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"}};qH.default=sP});var BH=j((UH)=>{Object.defineProperty(UH,"__esModule",{value:!0});var bF=Cb(),wF={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:bF.validateUnion,error:{message:"must match a schema in anyOf"}};UH.default=wF});var FH=j((PH)=>{Object.defineProperty(PH,"__esModule",{value:!0});var _$=x(),WF=i(),QF={message:"must match exactly one schema in oneOf",params:({params:b})=>_$._`{passingSchemas: ${b.passing}}`},GF={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:QF,code(b){let{gen:w,schema:$,parentSchema:W,it:Q}=b;if(!Array.isArray($))throw Error("ajv implementation error");if(Q.opts.discriminator&&W.discriminator)return;let G=$,D=w.let("valid",!1),X=w.let("passing",null),Y=w.name("_valid");b.setParams({passing:X}),w.block(H),b.result(D,()=>b.reset(),()=>b.error(!0));function H(){G.forEach((J,z)=>{let O;if((0,WF.alwaysValidSchema)(Q,J))w.var(Y,!0);else O=b.subschema({keyword:"oneOf",schemaProp:z,compositeRule:!0},Y);if(z>0)w.if(_$._`${Y} && ${D}`).assign(D,!1).assign(X,_$._`[${X}, ${z}]`).else();w.if(Y,()=>{if(w.assign(D,!0),w.assign(X,z),O)b.mergeEvaluated(O,_$.Name)})})}}};PH.default=GF});var MH=j((KH)=>{Object.defineProperty(KH,"__esModule",{value:!0});var XF=i(),YF={keyword:"allOf",schemaType:"array",code(b){let{gen:w,schema:$,it:W}=b;if(!Array.isArray($))throw Error("ajv implementation error");let Q=w.name("valid");$.forEach((G,D)=>{if((0,XF.alwaysValidSchema)(W,G))return;let X=b.subschema({keyword:"allOf",schemaProp:D},Q);b.ok(Q),b.mergeEvaluated(X)})}};KH.default=YF});var VH=j((jH)=>{Object.defineProperty(jH,"__esModule",{value:!0});var S$=x(),ZH=i(),JF={message:({params:b})=>S$.str`must match "${b.ifClause}" schema`,params:({params:b})=>S$._`{failingKeyword: ${b.ifClause}}`},zF={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:JF,code(b){let{gen:w,parentSchema:$,it:W}=b;if($.then===void 0&&$.else===void 0)(0,ZH.checkStrictMode)(W,'"if" without "then" and "else" is ignored');let Q=IH(W,"then"),G=IH(W,"else");if(!Q&&!G)return;let D=w.let("valid",!0),X=w.name("_valid");if(Y(),b.reset(),Q&&G){let J=w.let("ifClause");b.setParams({ifClause:J}),w.if(X,H("then",J),H("else",J))}else if(Q)w.if(X,H("then"));else w.if((0,S$.not)(X),H("else"));b.pass(D,()=>b.error(!0));function Y(){let J=b.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},X);b.mergeEvaluated(J)}function H(J,z){return()=>{let O=b.subschema({keyword:J},X);if(w.assign(D,X),b.mergeValidEvaluated(O,D),z)w.assign(z,S$._`${J}`);else b.setParams({ifClause:J})}}}};function IH(b,w){let $=b.schema[w];return $!==void 0&&!(0,ZH.alwaysValidSchema)(b,$)}jH.default=zF});var TH=j((NH)=>{Object.defineProperty(NH,"__esModule",{value:!0});var OF=i(),qF={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:b,parentSchema:w,it:$}){if(w.if===void 0)(0,OF.checkStrictMode)($,`"${b}" without "if" is ignored`)}};NH.default=qF});var _H=j((EH)=>{Object.defineProperty(EH,"__esModule",{value:!0});var UF=m4(),BF=mY(),PF=i4(),FF=pY(),KF=dY(),MF=bH(),IF=WH(),ZF=p4(),jF=YH(),VF=OH(),NF=LH(),TF=BH(),EF=FH(),_F=MH(),SF=VH(),RF=TH();function vF(b=!1){let w=[NF.default,TF.default,EF.default,_F.default,SF.default,RF.default,IF.default,ZF.default,MF.default,jF.default,VF.default];if(b)w.push(BF.default,FF.default);else w.push(UF.default,PF.default);return w.push(KF.default),w}EH.default=vF});var RH=j((SH)=>{Object.defineProperty(SH,"__esModule",{value:!0});var Gb=x(),CF={message:({schemaCode:b})=>Gb.str`must match format "${b}"`,params:({schemaCode:b})=>Gb._`{format: ${b}}`},uF={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:CF,code(b,w){let{gen:$,data:W,$data:Q,schema:G,schemaCode:D,it:X}=b,{opts:Y,errSchemaPath:H,schemaEnv:J,self:z}=X;if(!Y.validateFormats)return;if(Q)O();else q();function O(){let B=$.scopeValue("formats",{ref:z.formats,code:Y.code.formats}),K=$.const("fDef",Gb._`${B}[${D}]`),I=$.let("fType"),M=$.let("format");$.if(Gb._`typeof ${K} == "object" && !(${K} instanceof RegExp)`,()=>$.assign(I,Gb._`${K}.type || "string"`).assign(M,Gb._`${K}.validate`),()=>$.assign(I,Gb._`"string"`).assign(M,K)),b.fail$data((0,Gb.or)(v(),S()));function v(){if(Y.strictSchema===!1)return Gb.nil;return Gb._`${D} && !${M}`}function S(){let h=J.$async?Gb._`(${K}.async ? await ${M}(${W}) : ${M}(${W}))`:Gb._`${M}(${W})`,R=Gb._`(typeof ${M} == "function" ? ${h} : ${M}.test(${W}))`;return Gb._`${M} && ${M} !== true && ${I} === ${w} && !${R}`}}function q(){let B=z.formats[G];if(!B){v();return}if(B===!0)return;let[K,I,M]=S(B);if(K===w)b.pass(h());function v(){if(Y.strictSchema===!1){z.logger.warn(R());return}throw Error(R());function R(){return`unknown format "${G}" ignored in schema at path "${H}"`}}function S(R){let pb=R instanceof RegExp?(0,Gb.regexpCode)(R):Y.code.formats?Gb._`${Y.code.formats}${(0,Gb.getProperty)(G)}`:void 0,sb=$.scopeValue("formats",{key:G,ref:R,code:pb});if(typeof R=="object"&&!(R instanceof RegExp))return[R.type||"string",R.validate,Gb._`${sb}.validate`];return["string",R,sb]}function h(){if(typeof B=="object"&&!(B instanceof RegExp)&&B.async){if(!J.$async)throw Error("async format in sync schema");return Gb._`await ${M}(${W})`}return typeof I=="function"?Gb._`${M}(${W})`:Gb._`${M}.test(${W})`}}}};SH.default=uF});var kH=j((vH)=>{Object.defineProperty(vH,"__esModule",{value:!0});var yF=RH(),hF=[yF.default];vH.default=hF});var xH=j((CH)=>{Object.defineProperty(CH,"__esModule",{value:!0});CH.contentVocabulary=CH.metadataVocabulary=void 0;CH.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];CH.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var fH=j((hH)=>{Object.defineProperty(hH,"__esModule",{value:!0});var nF=XY(),gF=CY(),mF=_H(),iF=kH(),yH=xH(),lF=[nF.default,gF.default,(0,mF.default)(),iF.default,yH.metadataVocabulary,yH.contentVocabulary];hH.default=lF});var mH=j((nH)=>{Object.defineProperty(nH,"__esModule",{value:!0});nH.DiscrError=void 0;var cH;(function(b){b.Tag="tag",b.Mapping="mapping"})(cH||(nH.DiscrError=cH={}))});var pH=j((lH)=>{Object.defineProperty(lH,"__esModule",{value:!0});var b1=x(),d4=mH(),iH=z$(),oF=p1(),dF=i(),tF={message:({params:{discrError:b,tagName:w}})=>b===d4.DiscrError.Tag?`tag "${w}" must be string`:`value of tag "${w}" must be in oneOf`,params:({params:{discrError:b,tag:w,tagName:$}})=>b1._`{error: ${b}, tag: ${$}, tagValue: ${w}}`},rF={keyword:"discriminator",type:"object",schemaType:"object",error:tF,code(b){let{gen:w,data:$,schema:W,parentSchema:Q,it:G}=b,{oneOf:D}=Q;if(!G.opts.discriminator)throw Error("discriminator: requires discriminator option");let X=W.propertyName;if(typeof X!="string")throw Error("discriminator: requires propertyName");if(W.mapping)throw Error("discriminator: mapping is not supported");if(!D)throw Error("discriminator: requires oneOf keyword");let Y=w.let("valid",!1),H=w.const("tag",b1._`${$}${(0,b1.getProperty)(X)}`);w.if(b1._`typeof ${H} == "string"`,()=>J(),()=>b.error(!1,{discrError:d4.DiscrError.Tag,tag:H,tagName:X})),b.ok(Y);function J(){let q=O();w.if(!1);for(let B in q)w.elseIf(b1._`${H} === ${B}`),w.assign(Y,z(q[B]));w.else(),b.error(!1,{discrError:d4.DiscrError.Mapping,tag:H,tagName:X}),w.endIf()}function z(q){let B=w.name("valid"),K=b.subschema({keyword:"oneOf",schemaProp:q},B);return b.mergeEvaluated(K,b1.Name),B}function O(){var q;let B={},K=M(Q),I=!0;for(let h=0;h<D.length;h++){let R=D[h];if((R===null||R===void 0?void 0:R.$ref)&&!(0,dF.schemaHasRulesButRef)(R,G.self.RULES)){let sb=R.$ref;if(R=iH.resolveRef.call(G.self,G.schemaEnv.root,G.baseId,sb),R instanceof iH.SchemaEnv)R=R.schema;if(R===void 0)throw new oF.default(G.opts.uriResolver,G.baseId,sb)}let pb=(q=R===null||R===void 0?void 0:R.properties)===null||q===void 0?void 0:q[X];if(typeof pb!="object")throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${X}"`);I=I&&(K||M(R)),v(pb,h)}if(!I)throw Error(`discriminator: "${X}" must be required`);return B;function M({required:h}){return Array.isArray(h)&&h.includes(X)}function v(h,R){if(h.const)S(h.const,R);else if(h.enum)for(let pb of h.enum)S(pb,R);else throw Error(`discriminator: "properties/${X}" must have "const" or "enum"`)}function S(h,R){if(typeof h!="string"||h in B)throw Error(`discriminator: "${X}" values must be unique strings`);B[h]=R}}}};lH.default=rF});var oH=j((sE,sF)=>{sF.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 r4=j((Vb,t4)=>{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 aF=eX(),bK=fH(),wK=pH(),dH=oH(),$K=["/properties"],R$="http://json-schema.org/draft-07/schema";class Q0 extends aF.default{_addVocabularies(){if(super._addVocabularies(),bK.default.forEach((b)=>this.addVocabulary(b)),this.opts.discriminator)this.addKeyword(wK.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let b=this.opts.$data?this.$dataMetaSchema(dH,$K):dH;this.addMetaSchema(b,R$,!1),this.refs["http://json-schema.org/schema"]=R$}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(R$)?R$:void 0)}}Vb.Ajv=Q0;t4.exports=Vb=Q0;t4.exports.Ajv=Q0;Object.defineProperty(Vb,"__esModule",{value:!0});Vb.default=Q0;var WK=l1();Object.defineProperty(Vb,"KeywordCxt",{enumerable:!0,get:function(){return WK.KeywordCxt}});var w1=x();Object.defineProperty(Vb,"_",{enumerable:!0,get:function(){return w1._}});Object.defineProperty(Vb,"str",{enumerable:!0,get:function(){return w1.str}});Object.defineProperty(Vb,"stringify",{enumerable:!0,get:function(){return w1.stringify}});Object.defineProperty(Vb,"nil",{enumerable:!0,get:function(){return w1.nil}});Object.defineProperty(Vb,"Name",{enumerable:!0,get:function(){return w1.Name}});Object.defineProperty(Vb,"CodeGen",{enumerable:!0,get:function(){return w1.CodeGen}});var QK=H$();Object.defineProperty(Vb,"ValidationError",{enumerable:!0,get:function(){return QK.default}});var GK=p1();Object.defineProperty(Vb,"MissingRefError",{enumerable:!0,get:function(){return GK.default}})});var QJ=j(($J)=>{Object.defineProperty($J,"__esModule",{value:!0});$J.formatNames=$J.fastFormats=$J.fullFormats=void 0;function rb(b,w){return{validate:b,compare:w}}$J.fullFormats={date:rb(sH,bW),time:rb(s4(!0),wW),"date-time":rb(tH(!0),bJ),"iso-time":rb(s4(),aH),"iso-date-time":rb(tH(),wJ),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:OK,"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:KK,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:qK,int32:{type:"number",validate:BK},int64:{type:"number",validate:PK},float:{type:"number",validate:eH},double:{type:"number",validate:eH},password:!0,binary:!0};$J.fastFormats={...$J.fullFormats,date:rb(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,bW),time:rb(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,wW),"date-time":rb(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,bJ),"iso-time":rb(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,aH),"iso-date-time":rb(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,wJ),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};$J.formatNames=Object.keys($J.fullFormats);function YK(b){return b%4===0&&(b%100!==0||b%400===0)}var HK=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,JK=[0,31,28,31,30,31,30,31,31,30,31,30,31];function sH(b){let w=HK.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&&YK($)?29:JK[W])}function bW(b,w){if(!(b&&w))return;if(b>w)return 1;if(b<w)return-1;return 0}var e4=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function s4(b){return function($){let W=e4.exec($);if(!W)return!1;let Q=+W[1],G=+W[2],D=+W[3],X=W[4],Y=W[5]==="-"?-1:1,H=+(W[6]||0),J=+(W[7]||0);if(H>23||J>59||b&&!X)return!1;if(Q<=23&&G<=59&&D<60)return!0;let z=G-J*Y,O=Q-H*Y-(z<0?1:0);return(O===23||O===-1)&&(z===59||z===-1)&&D<61}}function wW(b,w){if(!(b&&w))return;let $=new Date("2020-01-01T"+b).valueOf(),W=new Date("2020-01-01T"+w).valueOf();if(!($&&W))return;return $-W}function aH(b,w){if(!(b&&w))return;let $=e4.exec(b),W=e4.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 a4=/t|\s/i;function tH(b){let w=s4(b);return function(W){let Q=W.split(a4);return Q.length===2&&sH(Q[0])&&w(Q[1])}}function bJ(b,w){if(!(b&&w))return;let $=new Date(b).valueOf(),W=new Date(w).valueOf();if(!($&&W))return;return $-W}function wJ(b,w){if(!(b&&w))return;let[$,W]=b.split(a4),[Q,G]=w.split(a4),D=bW($,Q);if(D===void 0)return;return D||wW(W,G)}var zK=/\/|:/,AK=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function OK(b){return zK.test(b)&&AK.test(b)}var rH=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function qK(b){return rH.lastIndex=0,rH.test(b)}var LK=-2147483648,UK=2147483647;function BK(b){return Number.isInteger(b)&&b<=UK&&b>=LK}function PK(b){return Number.isInteger(b)}function eH(){return!0}var FK=/[^\\]\\Z/;function KK(b){if(FK.test(b))return!1;try{return new RegExp(b),!0}catch(w){return!1}}});var DJ=j((GJ)=>{Object.defineProperty(GJ,"__esModule",{value:!0});GJ.formatLimitDefinition=void 0;var IK=r4(),mb=x(),Ew=mb.operators,v$={formatMaximum:{okStr:"<=",ok:Ew.LTE,fail:Ew.GT},formatMinimum:{okStr:">=",ok:Ew.GTE,fail:Ew.LT},formatExclusiveMaximum:{okStr:"<",ok:Ew.LT,fail:Ew.GTE},formatExclusiveMinimum:{okStr:">",ok:Ew.GT,fail:Ew.LTE}},ZK={message:({keyword:b,schemaCode:w})=>mb.str`should be ${v$[b].okStr} ${w}`,params:({keyword:b,schemaCode:w})=>mb._`{comparison: ${v$[b].okStr}, limit: ${w}}`};GJ.formatLimitDefinition={keyword:Object.keys(v$),type:"string",schemaType:"string",$data:!0,error:ZK,code(b){let{gen:w,data:$,schemaCode:W,keyword:Q,it:G}=b,{opts:D,self:X}=G;if(!D.validateFormats)return;let Y=new IK.KeywordCxt(G,X.RULES.all.format.definition,"format");if(Y.$data)H();else J();function H(){let O=w.scopeValue("formats",{ref:X.formats,code:D.code.formats}),q=w.const("fmt",mb._`${O}[${Y.schemaCode}]`);b.fail$data((0,mb.or)(mb._`typeof ${q} != "object"`,mb._`${q} instanceof RegExp`,mb._`typeof ${q}.compare != "function"`,z(q)))}function J(){let O=Y.schema,q=X.formats[O];if(!q||q===!0)return;if(typeof q!="object"||q instanceof RegExp||typeof q.compare!="function")throw Error(`"${Q}": format "${O}" does not define "compare" function`);let B=w.scopeValue("formats",{key:O,ref:q,code:D.code.formats?mb._`${D.code.formats}${(0,mb.getProperty)(O)}`:void 0});b.fail$data(z(B))}function z(O){return mb._`${O}.compare(${$}, ${W}) ${v$[Q].fail} 0`}},dependencies:["format"]};var jK=(b)=>{return b.addKeyword(GJ.formatLimitDefinition),b};GJ.default=jK});var JJ=j((G0,HJ)=>{Object.defineProperty(G0,"__esModule",{value:!0});var $1=QJ(),NK=DJ(),QW=x(),XJ=new QW.Name("fullFormats"),TK=new QW.Name("fastFormats"),GW=(b,w={keywords:!0})=>{if(Array.isArray(w))return YJ(b,w,$1.fullFormats,XJ),b;let[$,W]=w.mode==="fast"?[$1.fastFormats,TK]:[$1.fullFormats,XJ],Q=w.formats||$1.formatNames;if(YJ(b,Q,$,W),w.keywords)(0,NK.default)(b);return b};GW.get=(b,w="full")=>{let W=(w==="fast"?$1.fastFormats:$1.fullFormats)[b];if(!W)throw Error(`Unknown format "${b}"`);return W};function YJ(b,w,$,W){var Q,G;(Q=(G=b.opts.code).formats)!==null&&Q!==void 0||(G.formats=QW._`require("ajv-formats/dist/formats").${W}`);for(let D of w)b.addFormat(D,$[D])}HJ.exports=G0=GW;Object.defineProperty(G0,"__esModule",{value:!0});G0.default=GW});import{AsyncLocalStorage as $7}from"node:async_hooks";class ob extends Error{statusCode;rawDetails;code;context;constructor(b,w,$,W,Q){super(b);this.statusCode=w;this.rawDetails=$;this.code=W;this.context=Q;this.name="McpApiError"}}function az(b){if(b instanceof ob)return{message:b.message,statusCode:b.statusCode,code:b.code,rawDetails:b.rawDetails,context:b.context};if(b instanceof Error)return{message:b.message};return{message:String(b)}}function b7(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 w7(b){let w=az(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=b7($);if(G.length>0){let D=G.map((Y)=>`\`${Y}\``).join(", "),X=G.every((Y)=>Y.endsWith(":read"))?"the Read-only or Safer agent access preset":"Safer agent access when it covers the task, or Custom permissions";return{title:"API key permission required",description:`The current API key is valid, but this operation requires the missing ${G.length===1?"scope":"scopes"}: ${D}.`,howToFix:`For a local API-key connection, call \`get_account\` to inspect \`apiKeyPermissions\` and open \`apiKeyPermissions.manageUrl\` (or \`companies[].settingsUrl\` → API Keys). If \`get_account\` also requires \`account:read\`, open ${"https://sequenzy.com/dashboard"} directly and use the MCP setup or Settings → API Keys. Create a replacement key with ${X} including ${D}, replace \`SEQUENZY_API_KEY\`, and restart the client. For hosted OAuth MCP, disconnect and reauthorize the Sequenzy connection with a preset or Custom permissions including ${D}. Existing key permissions cannot be edited in place.`,docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q}}if(w.statusCode===403||W.includes("access denied"))return{title:"Access denied",description:"The current API key is valid, but it does not have permission to access the requested company or action.",howToFix:"Use an API key that belongs to the right account, or select a company the key can access before retrying the tool call.",docsUrl:"https://docs.sequenzy.com/authentication",details:Q};if(W.includes("no company available")||W.includes("company not found"))return{title:"Company selection required",description:"The MCP server could not resolve a company for this request.",howToFix:"Call `get_account` to inspect available companies, then call `select_company`, or pass `companyId` explicitly in the next tool call.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(w.statusCode===404||W.includes("not found"))return{title:"Requested resource not found",description:"Sequenzy could not find the requested campaign, template, sequence, company, or subscriber.",howToFix:"List or fetch the resource collection first, then retry the tool with a confirmed ID or email value.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(w.statusCode===409||W.includes("already exists"))return{title:"Resource already exists",description:"Sequenzy rejected this MCP request because it would create a duplicate resource.",howToFix:"List the existing resources first, reuse the matching resource when appropriate, or retry with a unique name or domain.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(w.statusCode===429||W.includes("rate limit"))return{title:"Rate limited",description:"Sequenzy temporarily slowed this MCP request because too many requests were sent too quickly.",howToFix:"Wait briefly before retrying. If the client is looping, reduce retries or add backoff before the next tool call.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(w.code==="NETWORK_ERROR"||W.includes("fetch failed"))return{title:"Network or configuration error",description:"The MCP server could not reach the Sequenzy API from this environment.",howToFix:"Check connectivity and verify `SEQUENZY_API_URL` if you override it in the MCP environment.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(W.includes("unknown tool")||W.includes("unknown resource"))return{title:"Unsupported MCP request",description:"The client asked for a tool or resource name that this Sequenzy MCP server does not expose.",howToFix:"Refresh the client's tool list and call only the names returned by `list_tools` or `list_resources`.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(W.includes("is required")||W.includes("invalid"))return{title:"Invalid MCP input",description:"The tool call was missing a required field or included an invalid value.",howToFix:"Review the tool schema, supply the missing argument, and retry the request with corrected input.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(w.statusCode&&w.statusCode>=500)return{title:"Sequenzy server error",description:"The request reached Sequenzy, but the server could not complete it successfully.",howToFix:"Retry once. If it still fails, keep the details below and consult the docs before escalating.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};return{title:"Tool execution failed",description:"The MCP server could not complete the requested operation.",howToFix:"Review the details below, adjust the tool input or credentials, and retry.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q}}function Ow(b){let w=w7(b);return[`Sequenzy MCP error: ${w.title}`,`Description: ${w.description}`,`How to fix: ${w.howToFix}`,`Docs: ${w.docsUrl}`,`Details: ${w.details}`].join(`
10
- `)}var W7="https://api.sequenzy.com",z1=new $7,yW=!1;function hW(){yW=!0}function z0(){return yW}var fW=null;function qw(){let b=z1.getStore();if(b)return b.selectedCompanyId??null;return fW}function A0(b){let w=z1.getStore();if(w){w.selectedCompanyId=b;return}fW=b}function r$(b,w){return z1.run(b,w)}function cW(){return z1.getStore()?.apiUrl??process.env.SEQUENZY_API_URL??W7}function nW(){return z1.getStore()?.apiKey??process.env.SEQUENZY_API_KEY}function gW(b,w){let $=nW();if(!$)throw new ob("SEQUENZY_API_KEY environment variable is required",401,void 0,"MCP_AUTH_REQUIRED");let W={"Content-Type":b,Authorization:`Bearer ${$}`},Q=w??qw();if(Q)W["x-company-id"]=Q;return W}function mW(){if(nW())return;console.error(Ow(new ob("SEQUENZY_API_KEY environment variable is required",401,void 0,"MCP_AUTH_REQUIRED"))),process.exit(1)}function Nb(b,w){let $=b[w];return typeof $==="string"&&$.trim()!==""?$.trim():void 0}function Q7(b){if(b===void 0)return;if(typeof b==="string")return b.trim()||void 0;return JSON.stringify(b)}function iW(b){if(!b.trim())return{message:"Request failed"};try{let w=JSON.parse(b);if(typeof w==="string")return{message:w};let $=typeof w.error==="object"&&w.error!==null?w.error:void 0,W=Nb(w,"code")??($?Nb($,"code"):void 0),Q=(typeof w.error==="string"?w.error:void 0)??($?Nb($,"message"):void 0)??Nb(w,"message")??Nb(w,"error")??b,G=Nb(w,"howToFix")??Nb(w,"resolution"),D={...Nb(w,"title")?{title:Nb(w,"title")}:{},...Nb(w,"description")?{description:Nb(w,"description")}:{},...G?{howToFix:G}:{},...Nb(w,"docsUrl")?{docsUrl:Nb(w,"docsUrl")}:{}},X=Q7(w.details);if(Object.keys(D).length>0||X)return{message:Q,...W?{code:W}:{},...X?{details:X}:{},...Object.keys(D).length>0?{context:D}:{}};if(typeof w.error==="string")return{message:w.error,...W?{code:W}:{}};if($)return{message:Q,...W?{code:W}:{}};return{message:Q,...W?{code:W}:{}}}catch{return{message:b}}}async function A(b,w,$,W){let Q=gW("application/json",W),G;try{G=await fetch(`${cW()}${w}`,{method:b,headers:Q,body:$?JSON.stringify($):void 0})}catch(D){throw new ob(D instanceof Error?D.message:"Failed to reach Sequenzy API",0,void 0,"NETWORK_ERROR")}if(!G.ok){let D=await G.text(),X=iW(D);throw new ob(X.message,G.status,X.details??D,X.code,X.context)}return G.json()}async function lW(b,w,$,W){let Q=new URL(cW()).origin,G=new URL(b,`${Q}/`);if(G.origin!==Q)throw new ob("The image upload URL did not point to the configured Sequenzy API.",500,void 0,"INVALID_UPLOAD_URL");let D;try{D=await fetch(G,{method:"PUT",headers:gW($,W),body:w})}catch(X){throw new ob(X instanceof Error?X.message:"Failed to upload image bytes",0,void 0,"NETWORK_ERROR")}if(!D.ok){let X=await D.text(),Y=iW(X);throw new ob(Y.message,D.status,Y.details??X,Y.code,Y.context)}}var fM=Object.freeze({status:"aborted"});function U(b,w,$){function W(X,Y){var H;Object.defineProperty(X,"_zod",{value:X._zod??{},enumerable:!1}),(H=X._zod).traits??(H.traits=new Set),X._zod.traits.add(b),w(X,Y);for(let J in D.prototype)if(!(J in X))Object.defineProperty(X,J,{value:D.prototype[J].bind(X)});X._zod.constr=D,X._zod.def=Y}let Q=$?.Parent??Object;class G extends Q{}Object.defineProperty(G,"name",{value:b});function D(X){var Y;let H=$?.Parent?new G:this;W(H,X),(Y=H._zod).deferred??(Y.deferred=[]);for(let J of H._zod.deferred)J();return H}return Object.defineProperty(D,"init",{value:W}),Object.defineProperty(D,Symbol.hasInstance,{value:(X)=>{if($?.Parent&&X instanceof $.Parent)return!0;return X?._zod?.traits?.has(b)}}),Object.defineProperty(D,"name",{value:b}),D}var cM=Symbol("zod_brand");class ab extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class A1 extends Error{constructor(b){super(`Encountered unidirectional transform during encode: ${b}`);this.name="ZodEncodeError"}}var O0={};function Rb(b){if(b)Object.assign(O0,b);return O0}var m={};xW(m,{unwrapMessage:()=>O1,uint8ArrayToHex:()=>_7,uint8ArrayToBase64url:()=>T7,uint8ArrayToBase64:()=>sW,stringifyPrimitive:()=>B0,shallowClone:()=>oW,safeExtend:()=>M7,required:()=>j7,randomString:()=>q7,propertyKeyTypes:()=>w6,promiseAllObject:()=>O7,primitiveTypes:()=>dW,prefixIssues:()=>ww,pick:()=>P7,partial:()=>Z7,optionalKeys:()=>$6,omit:()=>F7,objectClone:()=>J7,numKeys:()=>L7,nullish:()=>q1,normalizeParams:()=>_,mergeDefs:()=>Uw,merge:()=>I7,jsonStringifyReplacer:()=>hw,joinValues:()=>q0,issue:()=>cw,isPlainObject:()=>Bw,isObject:()=>Sw,hexToUint8Array:()=>E7,getSizableOrigin:()=>rW,getParsedType:()=>U7,getLengthableOrigin:()=>U1,getEnumValues:()=>s$,getElementAtPath:()=>A7,floatSafeRemainder:()=>a$,finalizeIssue:()=>yb,extend:()=>K7,escapeRegex:()=>bw,esc:()=>L0,defineLazy:()=>d,createTransparentProxy:()=>B7,cloneDef:()=>z7,clone:()=>xb,cleanRegex:()=>L1,cleanEnum:()=>V7,captureStackTrace:()=>U0,cached:()=>fw,base64urlToUint8Array:()=>N7,base64ToUint8Array:()=>eW,assignProp:()=>Lw,assertNotEqual:()=>D7,assertNever:()=>Y7,assertIs:()=>X7,assertEqual:()=>G7,assert:()=>H7,allowsEval:()=>b6,aborted:()=>Pw,NUMBER_FORMAT_RANGES:()=>W6,Class:()=>aW,BIGINT_FORMAT_RANGES:()=>tW});function G7(b){return b}function D7(b){return b}function X7(b){}function Y7(b){throw Error()}function H7(b){}function s$(b){let w=Object.values(b).filter((W)=>typeof W==="number");return Object.entries(b).filter(([W,Q])=>w.indexOf(+W)===-1).map(([W,Q])=>Q)}function q0(b,w="|"){return b.map(($)=>B0($)).join(w)}function hw(b,w){if(typeof w==="bigint")return w.toString();return w}function fw(b){return{get value(){{let $=b();return Object.defineProperty(this,"value",{value:$}),$}throw Error("cached value already set")}}}function q1(b){return b===null||b===void 0}function L1(b){let w=b.startsWith("^")?1:0,$=b.endsWith("$")?b.length-1:b.length;return b.slice(w,$)}function a$(b,w){let $=(b.toString().split(".")[1]||"").length,W=w.toString(),Q=(W.split(".")[1]||"").length;if(Q===0&&/\d?e-\d?/.test(W)){let Y=W.match(/\d?e-(\d?)/);if(Y?.[1])Q=Number.parseInt(Y[1])}let G=$>Q?$:Q,D=Number.parseInt(b.toFixed(G).replace(".","")),X=Number.parseInt(w.toFixed(G).replace(".",""));return D%X/10**G}var pW=Symbol("evaluating");function d(b,w,$){let W=void 0;Object.defineProperty(b,w,{get(){if(W===pW)return;if(W===void 0)W=pW,W=$();return W},set(Q){Object.defineProperty(b,w,{value:Q})},configurable:!0})}function J7(b){return Object.create(Object.getPrototypeOf(b),Object.getOwnPropertyDescriptors(b))}function Lw(b,w,$){Object.defineProperty(b,w,{value:$,writable:!0,enumerable:!0,configurable:!0})}function Uw(...b){let w={};for(let $ of b){let W=Object.getOwnPropertyDescriptors($);Object.assign(w,W)}return Object.defineProperties({},w)}function z7(b){return Uw(b._zod.def)}function A7(b,w){if(!w)return b;return w.reduce(($,W)=>$?.[W],b)}function O7(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 q7(b=10){let $="";for(let W=0;W<b;W++)$+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return $}function L0(b){return JSON.stringify(b)}var U0="captureStackTrace"in Error?Error.captureStackTrace:(...b)=>{};function Sw(b){return typeof b==="object"&&b!==null&&!Array.isArray(b)}var b6=fw(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(b){return!1}});function Bw(b){if(Sw(b)===!1)return!1;let w=b.constructor;if(w===void 0)return!0;let $=w.prototype;if(Sw($)===!1)return!1;if(Object.prototype.hasOwnProperty.call($,"isPrototypeOf")===!1)return!1;return!0}function oW(b){if(Bw(b))return{...b};if(Array.isArray(b))return[...b];return b}function L7(b){let w=0;for(let $ in b)if(Object.prototype.hasOwnProperty.call(b,$))w++;return w}var U7=(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}`)}},w6=new Set(["string","number","symbol"]),dW=new Set(["string","number","bigint","boolean","symbol","undefined"]);function bw(b){return b.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function xb(b,w,$){let W=new b._zod.constr(w??b._zod.def);if(!w||$?.parent)W._zod.parent=b;return W}function _(b){let w=b;if(!w)return{};if(typeof w==="string")return{error:()=>w};if(w?.message!==void 0){if(w?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");w.error=w.message}if(delete w.message,typeof w.error==="string")return{...w,error:()=>w.error};return w}function B7(b){let w;return new Proxy({},{get($,W,Q){return w??(w=b()),Reflect.get(w,W,Q)},set($,W,Q,G){return w??(w=b()),Reflect.set(w,W,Q,G)},has($,W){return w??(w=b()),Reflect.has(w,W)},deleteProperty($,W){return w??(w=b()),Reflect.deleteProperty(w,W)},ownKeys($){return w??(w=b()),Reflect.ownKeys(w)},getOwnPropertyDescriptor($,W){return w??(w=b()),Reflect.getOwnPropertyDescriptor(w,W)},defineProperty($,W,Q){return w??(w=b()),Reflect.defineProperty(w,W,Q)}})}function B0(b){if(typeof b==="bigint")return b.toString()+"n";if(typeof b==="string")return`"${b}"`;return`${b}`}function $6(b){return Object.keys(b).filter((w)=>{return b[w]._zod.optin==="optional"&&b[w]._zod.optout==="optional"})}var W6={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]},tW={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function P7(b,w){let $=b._zod.def,W=Uw(b._zod.def,{get shape(){let Q={};for(let G in w){if(!(G in $.shape))throw Error(`Unrecognized key: "${G}"`);if(!w[G])continue;Q[G]=$.shape[G]}return Lw(this,"shape",Q),Q},checks:[]});return xb(b,W)}function F7(b,w){let $=b._zod.def,W=Uw(b._zod.def,{get shape(){let Q={...b._zod.def.shape};for(let G in w){if(!(G in $.shape))throw Error(`Unrecognized key: "${G}"`);if(!w[G])continue;delete Q[G]}return Lw(this,"shape",Q),Q},checks:[]});return xb(b,W)}function K7(b,w){if(!Bw(w))throw Error("Invalid input to extend: expected a plain object");let $=b._zod.def.checks;if($&&$.length>0)throw Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");let Q=Uw(b._zod.def,{get shape(){let G={...b._zod.def.shape,...w};return Lw(this,"shape",G),G},checks:[]});return xb(b,Q)}function M7(b,w){if(!Bw(w))throw Error("Invalid input to safeExtend: expected a plain object");let $={...b._zod.def,get shape(){let W={...b._zod.def.shape,...w};return Lw(this,"shape",W),W},checks:b._zod.def.checks};return xb(b,$)}function I7(b,w){let $=Uw(b._zod.def,{get shape(){let W={...b._zod.def.shape,...w._zod.def.shape};return Lw(this,"shape",W),W},get catchall(){return w._zod.def.catchall},checks:[]});return xb(b,$)}function Z7(b,w,$){let W=Uw(w._zod.def,{get shape(){let Q=w._zod.def.shape,G={...Q};if($)for(let D in $){if(!(D in Q))throw Error(`Unrecognized key: "${D}"`);if(!$[D])continue;G[D]=b?new b({type:"optional",innerType:Q[D]}):Q[D]}else for(let D in Q)G[D]=b?new b({type:"optional",innerType:Q[D]}):Q[D];return Lw(this,"shape",G),G},checks:[]});return xb(w,W)}function j7(b,w,$){let W=Uw(w._zod.def,{get shape(){let Q=w._zod.def.shape,G={...Q};if($)for(let D in $){if(!(D in G))throw Error(`Unrecognized key: "${D}"`);if(!$[D])continue;G[D]=new b({type:"nonoptional",innerType:Q[D]})}else for(let D in Q)G[D]=new b({type:"nonoptional",innerType:Q[D]});return Lw(this,"shape",G),G},checks:[]});return xb(w,W)}function Pw(b,w=0){if(b.aborted===!0)return!0;for(let $=w;$<b.issues.length;$++)if(b.issues[$]?.continue!==!0)return!0;return!1}function ww(b,w){return w.map(($)=>{var W;return(W=$).path??(W.path=[]),$.path.unshift(b),$})}function O1(b){return typeof b==="string"?b:b?.message}function yb(b,w,$){let W={...b,path:b.path??[]};if(!b.message){let Q=O1(b.inst?._zod.def?.error?.(b))??O1(w?.error?.(b))??O1($.customError?.(b))??O1($.localeError?.(b))??"Invalid input";W.message=Q}if(delete W.inst,delete W.continue,!w?.reportInput)delete W.input;return W}function rW(b){if(b instanceof Set)return"set";if(b instanceof Map)return"map";if(b instanceof File)return"file";return"unknown"}function U1(b){if(Array.isArray(b))return"array";if(typeof b==="string")return"string";return"unknown"}function cw(...b){let[w,$,W]=b;if(typeof w==="string")return{message:w,code:"custom",input:$,inst:W};return{...w}}function V7(b){return Object.entries(b).filter(([w,$])=>{return Number.isNaN(Number.parseInt(w,10))}).map((w)=>w[1])}function eW(b){let w=atob(b),$=new Uint8Array(w.length);for(let W=0;W<w.length;W++)$[W]=w.charCodeAt(W);return $}function sW(b){let w="";for(let $=0;$<b.length;$++)w+=String.fromCharCode(b[$]);return btoa(w)}function N7(b){let w=b.replace(/-/g,"+").replace(/_/g,"/"),$="=".repeat((4-w.length%4)%4);return eW(w+$)}function T7(b){return sW(b).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function E7(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 _7(b){return Array.from(b).map((w)=>w.toString(16).padStart(2,"0")).join("")}class aW{constructor(...b){}}var bQ=(b,w)=>{b.name="$ZodError",Object.defineProperty(b,"_zod",{value:b._zod,enumerable:!1}),Object.defineProperty(b,"issues",{value:w,enumerable:!1}),b.message=JSON.stringify(w,hw,2),Object.defineProperty(b,"toString",{value:()=>b.message,enumerable:!1})},P0=U("$ZodError",bQ),Q6=U("$ZodError",bQ,{Parent:Error});function wQ(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 $Q(b,w=($)=>$.message){let $={_errors:[]},W=(Q)=>{for(let G of Q.issues)if(G.code==="invalid_union"&&G.errors.length)G.errors.map((D)=>W({issues:D}));else if(G.code==="invalid_key")W({issues:G.issues});else if(G.code==="invalid_element")W({issues:G.issues});else if(G.path.length===0)$._errors.push(w(G));else{let D=$,X=0;while(X<G.path.length){let Y=G.path[X];if(X!==G.path.length-1)D[Y]=D[Y]||{_errors:[]};else D[Y]=D[Y]||{_errors:[]},D[Y]._errors.push(w(G));D=D[Y],X++}}};return W(b),$}var F0=(b)=>(w,$,W,Q)=>{let G=W?Object.assign(W,{async:!1}):{async:!1},D=w._zod.run({value:$,issues:[]},G);if(D instanceof Promise)throw new ab;if(D.issues.length){let X=new(Q?.Err??b)(D.issues.map((Y)=>yb(Y,G,Rb())));throw U0(X,Q?.callee),X}return D.value};var K0=(b)=>async(w,$,W,Q)=>{let G=W?Object.assign(W,{async:!0}):{async:!0},D=w._zod.run({value:$,issues:[]},G);if(D instanceof Promise)D=await D;if(D.issues.length){let X=new(Q?.Err??b)(D.issues.map((Y)=>yb(Y,G,Rb())));throw U0(X,Q?.callee),X}return D.value};var B1=(b)=>(w,$,W)=>{let Q=W?{...W,async:!1}:{async:!1},G=w._zod.run({value:$,issues:[]},Q);if(G instanceof Promise)throw new ab;return G.issues.length?{success:!1,error:new(b??P0)(G.issues.map((D)=>yb(D,Q,Rb())))}:{success:!0,data:G.value}},P1=B1(Q6),F1=(b)=>async(w,$,W)=>{let Q=W?Object.assign(W,{async:!0}):{async:!0},G=w._zod.run({value:$,issues:[]},Q);if(G instanceof Promise)G=await G;return G.issues.length?{success:!1,error:new b(G.issues.map((D)=>yb(D,Q,Rb())))}:{success:!0,data:G.value}},M0=F1(Q6),WQ=(b)=>(w,$,W)=>{let Q=W?Object.assign(W,{direction:"backward"}):{direction:"backward"};return F0(b)(w,$,Q)};var QQ=(b)=>(w,$,W)=>{return F0(b)(w,$,W)};var GQ=(b)=>async(w,$,W)=>{let Q=W?Object.assign(W,{direction:"backward"}):{direction:"backward"};return K0(b)(w,$,Q)};var DQ=(b)=>async(w,$,W)=>{return K0(b)(w,$,W)};var XQ=(b)=>(w,$,W)=>{let Q=W?Object.assign(W,{direction:"backward"}):{direction:"backward"};return B1(b)(w,$,Q)};var YQ=(b)=>(w,$,W)=>{return B1(b)(w,$,W)};var HQ=(b)=>async(w,$,W)=>{let Q=W?Object.assign(W,{direction:"backward"}):{direction:"backward"};return F1(b)(w,$,Q)};var JQ=(b)=>async(w,$,W)=>{return F1(b)(w,$,W)};var zQ=/^[cC][^\s-]{8,}$/,AQ=/^[0-9a-z]+$/,OQ=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,qQ=/^[0-9a-vA-V]{20}$/,LQ=/^[A-Za-z0-9]{27}$/,UQ=/^[a-zA-Z0-9_-]{21}$/,BQ=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var PQ=/^([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})$/,G6=(b)=>{if(!b)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${b}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)};var FQ=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function KQ(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}var MQ=/^(?:(?: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])$/,IQ=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,ZQ=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,jQ=/^(([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])$/,VQ=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,D6=/^[A-Za-z0-9_-]*$/,NQ=/^(?=.{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 TQ=/^\+(?:[0-9]){6,14}[0-9]$/,EQ="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",_Q=new RegExp(`^${EQ}$`);function SQ(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 RQ(b){return new RegExp(`^${SQ(b)}$`)}function vQ(b){let w=SQ({precision:b.precision}),$=["Z"];if(b.local)$.push("");if(b.offset)$.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let W=`${w}(?:${$.join("|")})`;return new RegExp(`^${EQ}T(?:${W})$`)}var kQ=(b)=>{let w=b?`[\\s\\S]{${b?.minimum??0},${b?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${w}$`)};var CQ=/^-?\d+$/,uQ=/^-?\d+(?:\.\d+)?/,xQ=/^(?:true|false)$/i,yQ=/^null$/i;var hQ=/^[^A-Z]*$/,fQ=/^[^a-z]*$/;var Hb=U("$ZodCheck",(b,w)=>{var $;b._zod??(b._zod={}),b._zod.def=w,($=b._zod).onattach??($.onattach=[])}),cQ={number:"number",bigint:"bigint",object:"date"},X6=U("$ZodCheckLessThan",(b,w)=>{Hb.init(b,w);let $=cQ[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})}}),Y6=U("$ZodCheckGreaterThan",(b,w)=>{Hb.init(b,w);let $=cQ[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})}}),nQ=U("$ZodCheckMultipleOf",(b,w)=>{Hb.init(b,w),b._zod.onattach.push(($)=>{var W;(W=$._zod.bag).multipleOf??(W.multipleOf=w.value)}),b._zod.check=($)=>{if(typeof $.value!==typeof w.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof $.value==="bigint"?$.value%w.value===BigInt(0):a$($.value,w.value)===0)return;$.issues.push({origin:typeof $.value,code:"not_multiple_of",divisor:w.value,input:$.value,inst:b,continue:!w.abort})}}),gQ=U("$ZodCheckNumberFormat",(b,w)=>{Hb.init(b,w),w.format=w.format||"float64";let $=w.format?.includes("int"),W=$?"int":"number",[Q,G]=W6[w.format];b._zod.onattach.push((D)=>{let X=D._zod.bag;if(X.format=w.format,X.minimum=Q,X.maximum=G,$)X.pattern=CQ}),b._zod.check=(D)=>{let X=D.value;if($){if(!Number.isInteger(X)){D.issues.push({expected:W,format:w.format,code:"invalid_type",continue:!1,input:X,inst:b});return}if(!Number.isSafeInteger(X)){if(X>0)D.issues.push({input:X,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:b,origin:W,continue:!w.abort});else D.issues.push({input:X,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:b,origin:W,continue:!w.abort});return}}if(X<Q)D.issues.push({origin:"number",input:X,code:"too_small",minimum:Q,inclusive:!0,inst:b,continue:!w.abort});if(X>G)D.issues.push({origin:"number",input:X,code:"too_big",maximum:G,inst:b})}});var mQ=U("$ZodCheckMaxLength",(b,w)=>{var $;Hb.init(b,w),($=b._zod.def).when??($.when=(W)=>{let Q=W.value;return!q1(Q)&&Q.length!==void 0}),b._zod.onattach.push((W)=>{let Q=W._zod.bag.maximum??Number.POSITIVE_INFINITY;if(w.maximum<Q)W._zod.bag.maximum=w.maximum}),b._zod.check=(W)=>{let Q=W.value;if(Q.length<=w.maximum)return;let D=U1(Q);W.issues.push({origin:D,code:"too_big",maximum:w.maximum,inclusive:!0,input:Q,inst:b,continue:!w.abort})}}),iQ=U("$ZodCheckMinLength",(b,w)=>{var $;Hb.init(b,w),($=b._zod.def).when??($.when=(W)=>{let Q=W.value;return!q1(Q)&&Q.length!==void 0}),b._zod.onattach.push((W)=>{let Q=W._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(w.minimum>Q)W._zod.bag.minimum=w.minimum}),b._zod.check=(W)=>{let Q=W.value;if(Q.length>=w.minimum)return;let D=U1(Q);W.issues.push({origin:D,code:"too_small",minimum:w.minimum,inclusive:!0,input:Q,inst:b,continue:!w.abort})}}),lQ=U("$ZodCheckLengthEquals",(b,w)=>{var $;Hb.init(b,w),($=b._zod.def).when??($.when=(W)=>{let Q=W.value;return!q1(Q)&&Q.length!==void 0}),b._zod.onattach.push((W)=>{let Q=W._zod.bag;Q.minimum=w.length,Q.maximum=w.length,Q.length=w.length}),b._zod.check=(W)=>{let Q=W.value,G=Q.length;if(G===w.length)return;let D=U1(Q),X=G>w.length;W.issues.push({origin:D,...X?{code:"too_big",maximum:w.length}:{code:"too_small",minimum:w.length},inclusive:!0,exact:!0,input:W.value,inst:b,continue:!w.abort})}}),K1=U("$ZodCheckStringFormat",(b,w)=>{var $,W;if(Hb.init(b,w),b._zod.onattach.push((Q)=>{let G=Q._zod.bag;if(G.format=w.format,w.pattern)G.patterns??(G.patterns=new Set),G.patterns.add(w.pattern)}),w.pattern)($=b._zod).check??($.check=(Q)=>{if(w.pattern.lastIndex=0,w.pattern.test(Q.value))return;Q.issues.push({origin:"string",code:"invalid_format",format:w.format,input:Q.value,...w.pattern?{pattern:w.pattern.toString()}:{},inst:b,continue:!w.abort})});else(W=b._zod).check??(W.check=()=>{})}),pQ=U("$ZodCheckRegex",(b,w)=>{K1.init(b,w),b._zod.check=($)=>{if(w.pattern.lastIndex=0,w.pattern.test($.value))return;$.issues.push({origin:"string",code:"invalid_format",format:"regex",input:$.value,pattern:w.pattern.toString(),inst:b,continue:!w.abort})}}),oQ=U("$ZodCheckLowerCase",(b,w)=>{w.pattern??(w.pattern=hQ),K1.init(b,w)}),dQ=U("$ZodCheckUpperCase",(b,w)=>{w.pattern??(w.pattern=fQ),K1.init(b,w)}),tQ=U("$ZodCheckIncludes",(b,w)=>{Hb.init(b,w);let $=bw(w.includes),W=new RegExp(typeof w.position==="number"?`^.{${w.position}}${$}`:$);w.pattern=W,b._zod.onattach.push((Q)=>{let G=Q._zod.bag;G.patterns??(G.patterns=new Set),G.patterns.add(W)}),b._zod.check=(Q)=>{if(Q.value.includes(w.includes,w.position))return;Q.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:w.includes,input:Q.value,inst:b,continue:!w.abort})}}),rQ=U("$ZodCheckStartsWith",(b,w)=>{Hb.init(b,w);let $=new RegExp(`^${bw(w.prefix)}.*`);w.pattern??(w.pattern=$),b._zod.onattach.push((W)=>{let Q=W._zod.bag;Q.patterns??(Q.patterns=new Set),Q.patterns.add($)}),b._zod.check=(W)=>{if(W.value.startsWith(w.prefix))return;W.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:w.prefix,input:W.value,inst:b,continue:!w.abort})}}),eQ=U("$ZodCheckEndsWith",(b,w)=>{Hb.init(b,w);let $=new RegExp(`.*${bw(w.suffix)}$`);w.pattern??(w.pattern=$),b._zod.onattach.push((W)=>{let Q=W._zod.bag;Q.patterns??(Q.patterns=new Set),Q.patterns.add($)}),b._zod.check=(W)=>{if(W.value.endsWith(w.suffix))return;W.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:w.suffix,input:W.value,inst:b,continue:!w.abort})}});var sQ=U("$ZodCheckOverwrite",(b,w)=>{Hb.init(b,w),b._zod.check=($)=>{$.value=w.tx($.value)}});class H6{constructor(b=[]){if(this.content=[],this.indent=0,this)this.args=b}indented(b){this.indent+=1,b(this),this.indent-=1}write(b){if(typeof b==="function"){b(this,{execution:"sync"}),b(this,{execution:"async"});return}let $=b.split(`
9
+ deps: ${$}}`};var CP={keyword:"dependencies",type:"object",schemaType:"object",error:eY.error,code(b){let[w,$]=uP(b);tY(b,w),rY(b,$)}};function uP({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 tY(b,w=b.schema){let{gen:$,data:W,it:Q}=b;if(Object.keys(w).length===0)return;let G=$.let("missing");for(let D in w){let X=w[D];if(X.length===0)continue;let Y=(0,W0.propertyInData)($,W,D,Q.opts.ownProperties);if(b.setParams({property:D,depsCount:X.length,deps:X.join(", ")}),Q.allErrors)$.if(Y,()=>{for(let H of X)(0,W0.checkReportMissingProp)(b,H)});else $.if(l6._`${Y} && (${(0,W0.checkMissingProp)(b,X,G)})`),(0,W0.reportMissingProp)(b,G),$.else()}}eY.validatePropertyDeps=tY;function rY(b,w=b.schema){let{gen:$,data:W,keyword:Q,it:G}=b,D=$.name("valid");for(let X in w){if((0,kP.alwaysValidSchema)(G,w[X]))continue;$.if((0,W0.propertyInData)($,W,X,G.opts.ownProperties),()=>{let Y=b.subschema({keyword:Q,schemaProp:X},D);b.mergeValidEvaluated(Y,D)},()=>$.var(D,!0)),b.ok(D)}}eY.validateSchemaDeps=rY;eY.default=CP});var WH=j(($H)=>{Object.defineProperty($H,"__esModule",{value:!0});var wH=x(),hP=i(),fP={message:"property name must be valid",params:({params:b})=>wH._`{propertyName: ${b.propertyName}}`},cP={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:fP,code(b){let{gen:w,schema:$,data:W,it:Q}=b;if((0,hP.alwaysValidSchema)(Q,$))return;let G=w.name("valid");w.forIn("key",W,(D)=>{b.setParams({propertyName:D}),b.subschema({keyword:"propertyNames",data:D,dataTypes:["string"],propertyName:D,compositeRule:!0},G),w.if((0,wH.not)(G),()=>{if(b.error(!0),!Q.allErrors)w.break()})}),b.ok(G)}};$H.default=cP});var p6=j((QH)=>{Object.defineProperty(QH,"__esModule",{value:!0});var N$=Cb(),gb=x(),gP=Qw(),T$=i(),mP={message:"must NOT have additional properties",params:({params:b})=>gb._`{additionalProperty: ${b.additionalProperty}}`},iP={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:mP,code(b){let{gen:w,schema:$,parentSchema:W,data:Q,errsCount:G,it:D}=b;if(!G)throw Error("ajv implementation error");let{allErrors:X,opts:Y}=D;if(D.props=!0,Y.removeAdditional!=="all"&&(0,T$.alwaysValidSchema)(D,$))return;let H=(0,N$.allSchemaProperties)(W.properties),J=(0,N$.allSchemaProperties)(W.patternProperties);z(),b.ok(gb._`${G} === ${gP.default.errors}`);function z(){w.forIn("key",Q,(I)=>{if(!H.length&&!J.length)B(I);else w.if(O(I),()=>B(I))})}function O(I){let M;if(H.length>8){let v=(0,T$.schemaRefOrVal)(D,W.properties,"properties");M=(0,N$.isOwnProperty)(w,v,I)}else if(H.length)M=(0,gb.or)(...H.map((v)=>gb._`${I} === ${v}`));else M=gb.nil;if(J.length)M=(0,gb.or)(M,...J.map((v)=>gb._`${(0,N$.usePattern)(b,v)}.test(${I})`));return(0,gb.not)(M)}function q(I){w.code(gb._`delete ${Q}[${I}]`)}function B(I){if(Y.removeAdditional==="all"||Y.removeAdditional&&$===!1){q(I);return}if($===!1){if(b.setParams({additionalProperty:I}),b.error(),!X)w.break();return}if(typeof $=="object"&&!(0,T$.alwaysValidSchema)(D,$)){let M=w.name("valid");if(Y.removeAdditional==="failing")K(I,M,!1),w.if((0,gb.not)(M),()=>{b.reset(),q(I)});else if(K(I,M),!X)w.if((0,gb.not)(M),()=>w.break())}}function K(I,M,v){let S={keyword:"additionalProperties",dataProp:I,dataPropType:T$.Type.Str};if(v===!1)Object.assign(S,{compositeRule:!0,createErrors:!1,allErrors:!1});b.subschema(S,M)}}};QH.default=iP});var YH=j((XH)=>{Object.defineProperty(XH,"__esModule",{value:!0});var pP=l1(),GH=Cb(),o6=i(),DH=p6(),oP={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)DH.default.code(new pP.KeywordCxt(G,DH.default,"additionalProperties"));let D=(0,GH.allSchemaProperties)($);for(let z of D)G.definedProperties.add(z);if(G.opts.unevaluated&&D.length&&G.props!==!0)G.props=o6.mergeEvaluated.props(w,(0,o6.toHash)(D),G.props);let X=D.filter((z)=>!(0,o6.alwaysValidSchema)(G,$[z]));if(X.length===0)return;let Y=w.name("valid");for(let z of X){if(H(z))J(z);else{if(w.if((0,GH.propertyInData)(w,Q,z,G.opts.ownProperties)),J(z),!G.allErrors)w.else().var(Y,!0);w.endIf()}b.it.definedProperties.add(z),b.ok(Y)}function H(z){return G.opts.useDefaults&&!G.compositeRule&&$[z].default!==void 0}function J(z){b.subschema({keyword:"properties",schemaProp:z,dataProp:z},Y)}}};XH.default=oP});var OH=j((AH)=>{Object.defineProperty(AH,"__esModule",{value:!0});var HH=Cb(),E$=x(),JH=i(),zH=i(),tP={keyword:"patternProperties",type:"object",schemaType:"object",code(b){let{gen:w,schema:$,data:W,parentSchema:Q,it:G}=b,{opts:D}=G,X=(0,HH.allSchemaProperties)($),Y=X.filter((K)=>(0,JH.alwaysValidSchema)(G,$[K]));if(X.length===0||Y.length===X.length&&(!G.opts.unevaluated||G.props===!0))return;let H=D.strictSchema&&!D.allowMatchingProperties&&Q.properties,J=w.name("valid");if(G.props!==!0&&!(G.props instanceof E$.Name))G.props=(0,zH.evaluatedPropsToName)(w,G.props);let{props:z}=G;O();function O(){for(let K of X){if(H)q(K);if(G.allErrors)B(K);else w.var(J,!0),B(K),w.if(J)}}function q(K){for(let I in H)if(new RegExp(K).test(I))(0,JH.checkStrictMode)(G,`property ${I} matches pattern ${K} (use allowMatchingProperties)`)}function B(K){w.forIn("key",W,(I)=>{w.if(E$._`${(0,HH.usePattern)(b,K)}.test(${I})`,()=>{let M=Y.includes(K);if(!M)b.subschema({keyword:"patternProperties",schemaProp:K,dataProp:I,dataPropType:zH.Type.Str},J);if(G.opts.unevaluated&&z!==!0)w.assign(E$._`${z}[${I}]`,!0);else if(!M&&!G.allErrors)w.if((0,E$.not)(J),()=>w.break())})})}}};AH.default=tP});var LH=j((qH)=>{Object.defineProperty(qH,"__esModule",{value:!0});var eP=i(),sP={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(b){let{gen:w,schema:$,it:W}=b;if((0,eP.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"}};qH.default=sP});var BH=j((UH)=>{Object.defineProperty(UH,"__esModule",{value:!0});var bF=Cb(),wF={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:bF.validateUnion,error:{message:"must match a schema in anyOf"}};UH.default=wF});var FH=j((PH)=>{Object.defineProperty(PH,"__esModule",{value:!0});var _$=x(),WF=i(),QF={message:"must match exactly one schema in oneOf",params:({params:b})=>_$._`{passingSchemas: ${b.passing}}`},GF={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:QF,code(b){let{gen:w,schema:$,parentSchema:W,it:Q}=b;if(!Array.isArray($))throw Error("ajv implementation error");if(Q.opts.discriminator&&W.discriminator)return;let G=$,D=w.let("valid",!1),X=w.let("passing",null),Y=w.name("_valid");b.setParams({passing:X}),w.block(H),b.result(D,()=>b.reset(),()=>b.error(!0));function H(){G.forEach((J,z)=>{let O;if((0,WF.alwaysValidSchema)(Q,J))w.var(Y,!0);else O=b.subschema({keyword:"oneOf",schemaProp:z,compositeRule:!0},Y);if(z>0)w.if(_$._`${Y} && ${D}`).assign(D,!1).assign(X,_$._`[${X}, ${z}]`).else();w.if(Y,()=>{if(w.assign(D,!0),w.assign(X,z),O)b.mergeEvaluated(O,_$.Name)})})}}};PH.default=GF});var MH=j((KH)=>{Object.defineProperty(KH,"__esModule",{value:!0});var XF=i(),YF={keyword:"allOf",schemaType:"array",code(b){let{gen:w,schema:$,it:W}=b;if(!Array.isArray($))throw Error("ajv implementation error");let Q=w.name("valid");$.forEach((G,D)=>{if((0,XF.alwaysValidSchema)(W,G))return;let X=b.subschema({keyword:"allOf",schemaProp:D},Q);b.ok(Q),b.mergeEvaluated(X)})}};KH.default=YF});var VH=j((jH)=>{Object.defineProperty(jH,"__esModule",{value:!0});var S$=x(),ZH=i(),JF={message:({params:b})=>S$.str`must match "${b.ifClause}" schema`,params:({params:b})=>S$._`{failingKeyword: ${b.ifClause}}`},zF={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:JF,code(b){let{gen:w,parentSchema:$,it:W}=b;if($.then===void 0&&$.else===void 0)(0,ZH.checkStrictMode)(W,'"if" without "then" and "else" is ignored');let Q=IH(W,"then"),G=IH(W,"else");if(!Q&&!G)return;let D=w.let("valid",!0),X=w.name("_valid");if(Y(),b.reset(),Q&&G){let J=w.let("ifClause");b.setParams({ifClause:J}),w.if(X,H("then",J),H("else",J))}else if(Q)w.if(X,H("then"));else w.if((0,S$.not)(X),H("else"));b.pass(D,()=>b.error(!0));function Y(){let J=b.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},X);b.mergeEvaluated(J)}function H(J,z){return()=>{let O=b.subschema({keyword:J},X);if(w.assign(D,X),b.mergeValidEvaluated(O,D),z)w.assign(z,S$._`${J}`);else b.setParams({ifClause:J})}}}};function IH(b,w){let $=b.schema[w];return $!==void 0&&!(0,ZH.alwaysValidSchema)(b,$)}jH.default=zF});var TH=j((NH)=>{Object.defineProperty(NH,"__esModule",{value:!0});var OF=i(),qF={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:b,parentSchema:w,it:$}){if(w.if===void 0)(0,OF.checkStrictMode)($,`"${b}" without "if" is ignored`)}};NH.default=qF});var _H=j((EH)=>{Object.defineProperty(EH,"__esModule",{value:!0});var UF=m6(),BF=mY(),PF=i6(),FF=pY(),KF=dY(),MF=bH(),IF=WH(),ZF=p6(),jF=YH(),VF=OH(),NF=LH(),TF=BH(),EF=FH(),_F=MH(),SF=VH(),RF=TH();function vF(b=!1){let w=[NF.default,TF.default,EF.default,_F.default,SF.default,RF.default,IF.default,ZF.default,MF.default,jF.default,VF.default];if(b)w.push(BF.default,FF.default);else w.push(UF.default,PF.default);return w.push(KF.default),w}EH.default=vF});var RH=j((SH)=>{Object.defineProperty(SH,"__esModule",{value:!0});var Gb=x(),CF={message:({schemaCode:b})=>Gb.str`must match format "${b}"`,params:({schemaCode:b})=>Gb._`{format: ${b}}`},uF={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:CF,code(b,w){let{gen:$,data:W,$data:Q,schema:G,schemaCode:D,it:X}=b,{opts:Y,errSchemaPath:H,schemaEnv:J,self:z}=X;if(!Y.validateFormats)return;if(Q)O();else q();function O(){let B=$.scopeValue("formats",{ref:z.formats,code:Y.code.formats}),K=$.const("fDef",Gb._`${B}[${D}]`),I=$.let("fType"),M=$.let("format");$.if(Gb._`typeof ${K} == "object" && !(${K} instanceof RegExp)`,()=>$.assign(I,Gb._`${K}.type || "string"`).assign(M,Gb._`${K}.validate`),()=>$.assign(I,Gb._`"string"`).assign(M,K)),b.fail$data((0,Gb.or)(v(),S()));function v(){if(Y.strictSchema===!1)return Gb.nil;return Gb._`${D} && !${M}`}function S(){let h=J.$async?Gb._`(${K}.async ? await ${M}(${W}) : ${M}(${W}))`:Gb._`${M}(${W})`,R=Gb._`(typeof ${M} == "function" ? ${h} : ${M}.test(${W}))`;return Gb._`${M} && ${M} !== true && ${I} === ${w} && !${R}`}}function q(){let B=z.formats[G];if(!B){v();return}if(B===!0)return;let[K,I,M]=S(B);if(K===w)b.pass(h());function v(){if(Y.strictSchema===!1){z.logger.warn(R());return}throw Error(R());function R(){return`unknown format "${G}" ignored in schema at path "${H}"`}}function S(R){let pb=R instanceof RegExp?(0,Gb.regexpCode)(R):Y.code.formats?Gb._`${Y.code.formats}${(0,Gb.getProperty)(G)}`:void 0,sb=$.scopeValue("formats",{key:G,ref:R,code:pb});if(typeof R=="object"&&!(R instanceof RegExp))return[R.type||"string",R.validate,Gb._`${sb}.validate`];return["string",R,sb]}function h(){if(typeof B=="object"&&!(B instanceof RegExp)&&B.async){if(!J.$async)throw Error("async format in sync schema");return Gb._`await ${M}(${W})`}return typeof I=="function"?Gb._`${M}(${W})`:Gb._`${M}.test(${W})`}}}};SH.default=uF});var kH=j((vH)=>{Object.defineProperty(vH,"__esModule",{value:!0});var yF=RH(),hF=[yF.default];vH.default=hF});var xH=j((CH)=>{Object.defineProperty(CH,"__esModule",{value:!0});CH.contentVocabulary=CH.metadataVocabulary=void 0;CH.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];CH.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var fH=j((hH)=>{Object.defineProperty(hH,"__esModule",{value:!0});var nF=XY(),gF=CY(),mF=_H(),iF=kH(),yH=xH(),lF=[nF.default,gF.default,(0,mF.default)(),iF.default,yH.metadataVocabulary,yH.contentVocabulary];hH.default=lF});var mH=j((nH)=>{Object.defineProperty(nH,"__esModule",{value:!0});nH.DiscrError=void 0;var cH;(function(b){b.Tag="tag",b.Mapping="mapping"})(cH||(nH.DiscrError=cH={}))});var pH=j((lH)=>{Object.defineProperty(lH,"__esModule",{value:!0});var b1=x(),d6=mH(),iH=z$(),oF=p1(),dF=i(),tF={message:({params:{discrError:b,tagName:w}})=>b===d6.DiscrError.Tag?`tag "${w}" must be string`:`value of tag "${w}" must be in oneOf`,params:({params:{discrError:b,tag:w,tagName:$}})=>b1._`{error: ${b}, tag: ${$}, tagValue: ${w}}`},rF={keyword:"discriminator",type:"object",schemaType:"object",error:tF,code(b){let{gen:w,data:$,schema:W,parentSchema:Q,it:G}=b,{oneOf:D}=Q;if(!G.opts.discriminator)throw Error("discriminator: requires discriminator option");let X=W.propertyName;if(typeof X!="string")throw Error("discriminator: requires propertyName");if(W.mapping)throw Error("discriminator: mapping is not supported");if(!D)throw Error("discriminator: requires oneOf keyword");let Y=w.let("valid",!1),H=w.const("tag",b1._`${$}${(0,b1.getProperty)(X)}`);w.if(b1._`typeof ${H} == "string"`,()=>J(),()=>b.error(!1,{discrError:d6.DiscrError.Tag,tag:H,tagName:X})),b.ok(Y);function J(){let q=O();w.if(!1);for(let B in q)w.elseIf(b1._`${H} === ${B}`),w.assign(Y,z(q[B]));w.else(),b.error(!1,{discrError:d6.DiscrError.Mapping,tag:H,tagName:X}),w.endIf()}function z(q){let B=w.name("valid"),K=b.subschema({keyword:"oneOf",schemaProp:q},B);return b.mergeEvaluated(K,b1.Name),B}function O(){var q;let B={},K=M(Q),I=!0;for(let h=0;h<D.length;h++){let R=D[h];if((R===null||R===void 0?void 0:R.$ref)&&!(0,dF.schemaHasRulesButRef)(R,G.self.RULES)){let sb=R.$ref;if(R=iH.resolveRef.call(G.self,G.schemaEnv.root,G.baseId,sb),R instanceof iH.SchemaEnv)R=R.schema;if(R===void 0)throw new oF.default(G.opts.uriResolver,G.baseId,sb)}let pb=(q=R===null||R===void 0?void 0:R.properties)===null||q===void 0?void 0:q[X];if(typeof pb!="object")throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${X}"`);I=I&&(K||M(R)),v(pb,h)}if(!I)throw Error(`discriminator: "${X}" must be required`);return B;function M({required:h}){return Array.isArray(h)&&h.includes(X)}function v(h,R){if(h.const)S(h.const,R);else if(h.enum)for(let pb of h.enum)S(pb,R);else throw Error(`discriminator: "properties/${X}" must have "const" or "enum"`)}function S(h,R){if(typeof h!="string"||h in B)throw Error(`discriminator: "${X}" values must be unique strings`);B[h]=R}}}};lH.default=rF});var oH=j((sE,sF)=>{sF.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var r6=j((Vb,t6)=>{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 aF=eX(),bK=fH(),wK=pH(),dH=oH(),$K=["/properties"],R$="http://json-schema.org/draft-07/schema";class Q0 extends aF.default{_addVocabularies(){if(super._addVocabularies(),bK.default.forEach((b)=>this.addVocabulary(b)),this.opts.discriminator)this.addKeyword(wK.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let b=this.opts.$data?this.$dataMetaSchema(dH,$K):dH;this.addMetaSchema(b,R$,!1),this.refs["http://json-schema.org/schema"]=R$}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(R$)?R$:void 0)}}Vb.Ajv=Q0;t6.exports=Vb=Q0;t6.exports.Ajv=Q0;Object.defineProperty(Vb,"__esModule",{value:!0});Vb.default=Q0;var WK=l1();Object.defineProperty(Vb,"KeywordCxt",{enumerable:!0,get:function(){return WK.KeywordCxt}});var w1=x();Object.defineProperty(Vb,"_",{enumerable:!0,get:function(){return w1._}});Object.defineProperty(Vb,"str",{enumerable:!0,get:function(){return w1.str}});Object.defineProperty(Vb,"stringify",{enumerable:!0,get:function(){return w1.stringify}});Object.defineProperty(Vb,"nil",{enumerable:!0,get:function(){return w1.nil}});Object.defineProperty(Vb,"Name",{enumerable:!0,get:function(){return w1.Name}});Object.defineProperty(Vb,"CodeGen",{enumerable:!0,get:function(){return w1.CodeGen}});var QK=H$();Object.defineProperty(Vb,"ValidationError",{enumerable:!0,get:function(){return QK.default}});var GK=p1();Object.defineProperty(Vb,"MissingRefError",{enumerable:!0,get:function(){return GK.default}})});var QJ=j(($J)=>{Object.defineProperty($J,"__esModule",{value:!0});$J.formatNames=$J.fastFormats=$J.fullFormats=void 0;function rb(b,w){return{validate:b,compare:w}}$J.fullFormats={date:rb(sH,bW),time:rb(s6(!0),wW),"date-time":rb(tH(!0),bJ),"iso-time":rb(s6(),aH),"iso-date-time":rb(tH(),wJ),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:OK,"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:KK,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:qK,int32:{type:"number",validate:BK},int64:{type:"number",validate:PK},float:{type:"number",validate:eH},double:{type:"number",validate:eH},password:!0,binary:!0};$J.fastFormats={...$J.fullFormats,date:rb(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,bW),time:rb(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,wW),"date-time":rb(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,bJ),"iso-time":rb(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,aH),"iso-date-time":rb(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,wJ),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};$J.formatNames=Object.keys($J.fullFormats);function YK(b){return b%4===0&&(b%100!==0||b%400===0)}var HK=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,JK=[0,31,28,31,30,31,30,31,31,30,31,30,31];function sH(b){let w=HK.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&&YK($)?29:JK[W])}function bW(b,w){if(!(b&&w))return;if(b>w)return 1;if(b<w)return-1;return 0}var e6=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function s6(b){return function($){let W=e6.exec($);if(!W)return!1;let Q=+W[1],G=+W[2],D=+W[3],X=W[4],Y=W[5]==="-"?-1:1,H=+(W[6]||0),J=+(W[7]||0);if(H>23||J>59||b&&!X)return!1;if(Q<=23&&G<=59&&D<60)return!0;let z=G-J*Y,O=Q-H*Y-(z<0?1:0);return(O===23||O===-1)&&(z===59||z===-1)&&D<61}}function wW(b,w){if(!(b&&w))return;let $=new Date("2020-01-01T"+b).valueOf(),W=new Date("2020-01-01T"+w).valueOf();if(!($&&W))return;return $-W}function aH(b,w){if(!(b&&w))return;let $=e6.exec(b),W=e6.exec(w);if(!($&&W))return;if(b=$[1]+$[2]+$[3],w=W[1]+W[2]+W[3],b>w)return 1;if(b<w)return-1;return 0}var a6=/t|\s/i;function tH(b){let w=s6(b);return function(W){let Q=W.split(a6);return Q.length===2&&sH(Q[0])&&w(Q[1])}}function bJ(b,w){if(!(b&&w))return;let $=new Date(b).valueOf(),W=new Date(w).valueOf();if(!($&&W))return;return $-W}function wJ(b,w){if(!(b&&w))return;let[$,W]=b.split(a6),[Q,G]=w.split(a6),D=bW($,Q);if(D===void 0)return;return D||wW(W,G)}var zK=/\/|:/,AK=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function OK(b){return zK.test(b)&&AK.test(b)}var rH=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function qK(b){return rH.lastIndex=0,rH.test(b)}var LK=-2147483648,UK=2147483647;function BK(b){return Number.isInteger(b)&&b<=UK&&b>=LK}function PK(b){return Number.isInteger(b)}function eH(){return!0}var FK=/[^\\]\\Z/;function KK(b){if(FK.test(b))return!1;try{return new RegExp(b),!0}catch(w){return!1}}});var DJ=j((GJ)=>{Object.defineProperty(GJ,"__esModule",{value:!0});GJ.formatLimitDefinition=void 0;var IK=r6(),mb=x(),Ew=mb.operators,v$={formatMaximum:{okStr:"<=",ok:Ew.LTE,fail:Ew.GT},formatMinimum:{okStr:">=",ok:Ew.GTE,fail:Ew.LT},formatExclusiveMaximum:{okStr:"<",ok:Ew.LT,fail:Ew.GTE},formatExclusiveMinimum:{okStr:">",ok:Ew.GT,fail:Ew.LTE}},ZK={message:({keyword:b,schemaCode:w})=>mb.str`should be ${v$[b].okStr} ${w}`,params:({keyword:b,schemaCode:w})=>mb._`{comparison: ${v$[b].okStr}, limit: ${w}}`};GJ.formatLimitDefinition={keyword:Object.keys(v$),type:"string",schemaType:"string",$data:!0,error:ZK,code(b){let{gen:w,data:$,schemaCode:W,keyword:Q,it:G}=b,{opts:D,self:X}=G;if(!D.validateFormats)return;let Y=new IK.KeywordCxt(G,X.RULES.all.format.definition,"format");if(Y.$data)H();else J();function H(){let O=w.scopeValue("formats",{ref:X.formats,code:D.code.formats}),q=w.const("fmt",mb._`${O}[${Y.schemaCode}]`);b.fail$data((0,mb.or)(mb._`typeof ${q} != "object"`,mb._`${q} instanceof RegExp`,mb._`typeof ${q}.compare != "function"`,z(q)))}function J(){let O=Y.schema,q=X.formats[O];if(!q||q===!0)return;if(typeof q!="object"||q instanceof RegExp||typeof q.compare!="function")throw Error(`"${Q}": format "${O}" does not define "compare" function`);let B=w.scopeValue("formats",{key:O,ref:q,code:D.code.formats?mb._`${D.code.formats}${(0,mb.getProperty)(O)}`:void 0});b.fail$data(z(B))}function z(O){return mb._`${O}.compare(${$}, ${W}) ${v$[Q].fail} 0`}},dependencies:["format"]};var jK=(b)=>{return b.addKeyword(GJ.formatLimitDefinition),b};GJ.default=jK});var JJ=j((G0,HJ)=>{Object.defineProperty(G0,"__esModule",{value:!0});var $1=QJ(),NK=DJ(),QW=x(),XJ=new QW.Name("fullFormats"),TK=new QW.Name("fastFormats"),GW=(b,w={keywords:!0})=>{if(Array.isArray(w))return YJ(b,w,$1.fullFormats,XJ),b;let[$,W]=w.mode==="fast"?[$1.fastFormats,TK]:[$1.fullFormats,XJ],Q=w.formats||$1.formatNames;if(YJ(b,Q,$,W),w.keywords)(0,NK.default)(b);return b};GW.get=(b,w="full")=>{let W=(w==="fast"?$1.fastFormats:$1.fullFormats)[b];if(!W)throw Error(`Unknown format "${b}"`);return W};function YJ(b,w,$,W){var Q,G;(Q=(G=b.opts.code).formats)!==null&&Q!==void 0||(G.formats=QW._`require("ajv-formats/dist/formats").${W}`);for(let D of w)b.addFormat(D,$[D])}HJ.exports=G0=GW;Object.defineProperty(G0,"__esModule",{value:!0});G0.default=GW});import{AsyncLocalStorage as $7}from"node:async_hooks";class ob extends Error{statusCode;rawDetails;code;context;constructor(b,w,$,W,Q){super(b);this.statusCode=w;this.rawDetails=$;this.code=W;this.context=Q;this.name="McpApiError"}}function az(b){if(b instanceof ob)return{message:b.message,statusCode:b.statusCode,code:b.code,rawDetails:b.rawDetails,context:b.context};if(b instanceof Error)return{message:b.message};return{message:String(b)}}function b7(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 w7(b){let w=az(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=b7($);if(G.length>0){let D=G.map((Y)=>`\`${Y}\``).join(", "),X=G.every((Y)=>Y.endsWith(":read"))?"the Read-only or Safer agent access preset":"Safer agent access when it covers the task, or Custom permissions";return{title:"API key permission required",description:`The current API key is valid, but this operation requires the missing ${G.length===1?"scope":"scopes"}: ${D}.`,howToFix:`For a local API-key connection, call \`get_account\` to inspect \`apiKeyPermissions\` and open \`apiKeyPermissions.manageUrl\` (or \`companies[].settingsUrl\` → API Keys). If \`get_account\` also requires \`account:read\`, open ${"https://sequenzy.com/dashboard"} directly and use the MCP setup or Settings → API Keys. Create a replacement key with ${X} including ${D}, replace \`SEQUENZY_API_KEY\`, and restart the client. For hosted OAuth MCP, disconnect and reauthorize the Sequenzy connection with a preset or Custom permissions including ${D}. Existing key permissions cannot be edited in place.`,docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q}}if(w.statusCode===403||W.includes("access denied"))return{title:"Access denied",description:"The current API key is valid, but it does not have permission to access the requested company or action.",howToFix:"Use an API key that belongs to the right account, or select a company the key can access before retrying the tool call.",docsUrl:"https://docs.sequenzy.com/authentication",details:Q};if(W.includes("no company available")||W.includes("company not found"))return{title:"Company selection required",description:"The MCP server could not resolve a company for this request.",howToFix:"Call `get_account` to inspect available companies, then call `select_company`, or pass `companyId` explicitly in the next tool call.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(w.statusCode===404||W.includes("not found"))return{title:"Requested resource not found",description:"Sequenzy could not find the requested campaign, template, sequence, company, or subscriber.",howToFix:"List or fetch the resource collection first, then retry the tool with a confirmed ID or email value.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(w.statusCode===409||W.includes("already exists"))return{title:"Resource already exists",description:"Sequenzy rejected this MCP request because it would create a duplicate resource.",howToFix:"List the existing resources first, reuse the matching resource when appropriate, or retry with a unique name or domain.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(w.statusCode===429||W.includes("rate limit"))return{title:"Rate limited",description:"Sequenzy temporarily slowed this MCP request because too many requests were sent too quickly.",howToFix:"Wait briefly before retrying. If the client is looping, reduce retries or add backoff before the next tool call.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(w.code==="NETWORK_ERROR"||W.includes("fetch failed"))return{title:"Network or configuration error",description:"The MCP server could not reach the Sequenzy API from this environment.",howToFix:"Check connectivity and verify `SEQUENZY_API_URL` if you override it in the MCP environment.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(W.includes("unknown tool")||W.includes("unknown resource"))return{title:"Unsupported MCP request",description:"The client asked for a tool or resource name that this Sequenzy MCP server does not expose.",howToFix:"Refresh the client's tool list and call only the names returned by `list_tools` or `list_resources`.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(W.includes("is required")||W.includes("invalid"))return{title:"Invalid MCP input",description:"The tool call was missing a required field or included an invalid value.",howToFix:"Review the tool schema, supply the missing argument, and retry the request with corrected input.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(w.statusCode&&w.statusCode>=500)return{title:"Sequenzy server error",description:"The request reached Sequenzy, but the server could not complete it successfully.",howToFix:"Retry once. If it still fails, keep the details below and consult the docs before escalating.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};return{title:"Tool execution failed",description:"The MCP server could not complete the requested operation.",howToFix:"Review the details below, adjust the tool input or credentials, and retry.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q}}function Ow(b){let w=w7(b);return[`Sequenzy MCP error: ${w.title}`,`Description: ${w.description}`,`How to fix: ${w.howToFix}`,`Docs: ${w.docsUrl}`,`Details: ${w.details}`].join(`
10
+ `)}var W7="https://api.sequenzy.com",z1=new $7,yW=!1;function hW(){yW=!0}function z0(){return yW}var fW=null;function qw(){let b=z1.getStore();if(b)return b.selectedCompanyId??null;return fW}function A0(b){let w=z1.getStore();if(w){w.selectedCompanyId=b;return}fW=b}function r$(b,w){return z1.run(b,w)}function cW(){return z1.getStore()?.apiUrl??process.env.SEQUENZY_API_URL??W7}function nW(){return z1.getStore()?.apiKey??process.env.SEQUENZY_API_KEY}function gW(b,w){let $=nW();if(!$)throw new ob("SEQUENZY_API_KEY environment variable is required",401,void 0,"MCP_AUTH_REQUIRED");let W={"Content-Type":b,Authorization:`Bearer ${$}`},Q=w??qw();if(Q)W["x-company-id"]=Q;return W}function mW(){if(nW())return;console.error(Ow(new ob("SEQUENZY_API_KEY environment variable is required",401,void 0,"MCP_AUTH_REQUIRED"))),process.exit(1)}function Nb(b,w){let $=b[w];return typeof $==="string"&&$.trim()!==""?$.trim():void 0}function Q7(b){if(b===void 0)return;if(typeof b==="string")return b.trim()||void 0;return JSON.stringify(b)}function iW(b){if(!b.trim())return{message:"Request failed"};try{let w=JSON.parse(b);if(typeof w==="string")return{message:w};let $=typeof w.error==="object"&&w.error!==null?w.error:void 0,W=Nb(w,"code")??($?Nb($,"code"):void 0),Q=(typeof w.error==="string"?w.error:void 0)??($?Nb($,"message"):void 0)??Nb(w,"message")??Nb(w,"error")??b,G=Nb(w,"howToFix")??Nb(w,"resolution"),D={...Nb(w,"title")?{title:Nb(w,"title")}:{},...Nb(w,"description")?{description:Nb(w,"description")}:{},...G?{howToFix:G}:{},...Nb(w,"docsUrl")?{docsUrl:Nb(w,"docsUrl")}:{}},X=Q7(w.details);if(Object.keys(D).length>0||X)return{message:Q,...W?{code:W}:{},...X?{details:X}:{},...Object.keys(D).length>0?{context:D}:{}};if(typeof w.error==="string")return{message:w.error,...W?{code:W}:{}};if($)return{message:Q,...W?{code:W}:{}};return{message:Q,...W?{code:W}:{}}}catch{return{message:b}}}async function A(b,w,$,W){let Q=gW("application/json",W),G;try{G=await fetch(`${cW()}${w}`,{method:b,headers:Q,body:$?JSON.stringify($):void 0})}catch(D){throw new ob(D instanceof Error?D.message:"Failed to reach Sequenzy API",0,void 0,"NETWORK_ERROR")}if(!G.ok){let D=await G.text(),X=iW(D);throw new ob(X.message,G.status,X.details??D,X.code,X.context)}return G.json()}async function lW(b,w,$,W){let Q=new URL(cW()).origin,G=new URL(b,`${Q}/`);if(G.origin!==Q)throw new ob("The image upload URL did not point to the configured Sequenzy API.",500,void 0,"INVALID_UPLOAD_URL");let D;try{D=await fetch(G,{method:"PUT",headers:gW($,W),body:w})}catch(X){throw new ob(X instanceof Error?X.message:"Failed to upload image bytes",0,void 0,"NETWORK_ERROR")}if(!D.ok){let X=await D.text(),Y=iW(X);throw new ob(Y.message,D.status,Y.details??X,Y.code,Y.context)}}var fM=Object.freeze({status:"aborted"});function U(b,w,$){function W(X,Y){var H;Object.defineProperty(X,"_zod",{value:X._zod??{},enumerable:!1}),(H=X._zod).traits??(H.traits=new Set),X._zod.traits.add(b),w(X,Y);for(let J in D.prototype)if(!(J in X))Object.defineProperty(X,J,{value:D.prototype[J].bind(X)});X._zod.constr=D,X._zod.def=Y}let Q=$?.Parent??Object;class G extends Q{}Object.defineProperty(G,"name",{value:b});function D(X){var Y;let H=$?.Parent?new G:this;W(H,X),(Y=H._zod).deferred??(Y.deferred=[]);for(let J of H._zod.deferred)J();return H}return Object.defineProperty(D,"init",{value:W}),Object.defineProperty(D,Symbol.hasInstance,{value:(X)=>{if($?.Parent&&X instanceof $.Parent)return!0;return X?._zod?.traits?.has(b)}}),Object.defineProperty(D,"name",{value:b}),D}var cM=Symbol("zod_brand");class ab extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class A1 extends Error{constructor(b){super(`Encountered unidirectional transform during encode: ${b}`);this.name="ZodEncodeError"}}var O0={};function Rb(b){if(b)Object.assign(O0,b);return O0}var m={};xW(m,{unwrapMessage:()=>O1,uint8ArrayToHex:()=>_7,uint8ArrayToBase64url:()=>T7,uint8ArrayToBase64:()=>sW,stringifyPrimitive:()=>B0,shallowClone:()=>oW,safeExtend:()=>M7,required:()=>j7,randomString:()=>q7,propertyKeyTypes:()=>w4,promiseAllObject:()=>O7,primitiveTypes:()=>dW,prefixIssues:()=>ww,pick:()=>P7,partial:()=>Z7,optionalKeys:()=>$4,omit:()=>F7,objectClone:()=>J7,numKeys:()=>L7,nullish:()=>q1,normalizeParams:()=>_,mergeDefs:()=>Uw,merge:()=>I7,jsonStringifyReplacer:()=>hw,joinValues:()=>q0,issue:()=>cw,isPlainObject:()=>Bw,isObject:()=>Sw,hexToUint8Array:()=>E7,getSizableOrigin:()=>rW,getParsedType:()=>U7,getLengthableOrigin:()=>U1,getEnumValues:()=>s$,getElementAtPath:()=>A7,floatSafeRemainder:()=>a$,finalizeIssue:()=>yb,extend:()=>K7,escapeRegex:()=>bw,esc:()=>L0,defineLazy:()=>d,createTransparentProxy:()=>B7,cloneDef:()=>z7,clone:()=>xb,cleanRegex:()=>L1,cleanEnum:()=>V7,captureStackTrace:()=>U0,cached:()=>fw,base64urlToUint8Array:()=>N7,base64ToUint8Array:()=>eW,assignProp:()=>Lw,assertNotEqual:()=>D7,assertNever:()=>Y7,assertIs:()=>X7,assertEqual:()=>G7,assert:()=>H7,allowsEval:()=>b4,aborted:()=>Pw,NUMBER_FORMAT_RANGES:()=>W4,Class:()=>aW,BIGINT_FORMAT_RANGES:()=>tW});function G7(b){return b}function D7(b){return b}function X7(b){}function Y7(b){throw Error()}function H7(b){}function s$(b){let w=Object.values(b).filter((W)=>typeof W==="number");return Object.entries(b).filter(([W,Q])=>w.indexOf(+W)===-1).map(([W,Q])=>Q)}function q0(b,w="|"){return b.map(($)=>B0($)).join(w)}function hw(b,w){if(typeof w==="bigint")return w.toString();return w}function fw(b){return{get value(){{let $=b();return Object.defineProperty(this,"value",{value:$}),$}throw Error("cached value already set")}}}function q1(b){return b===null||b===void 0}function L1(b){let w=b.startsWith("^")?1:0,$=b.endsWith("$")?b.length-1:b.length;return b.slice(w,$)}function a$(b,w){let $=(b.toString().split(".")[1]||"").length,W=w.toString(),Q=(W.split(".")[1]||"").length;if(Q===0&&/\d?e-\d?/.test(W)){let Y=W.match(/\d?e-(\d?)/);if(Y?.[1])Q=Number.parseInt(Y[1])}let G=$>Q?$:Q,D=Number.parseInt(b.toFixed(G).replace(".","")),X=Number.parseInt(w.toFixed(G).replace(".",""));return D%X/10**G}var pW=Symbol("evaluating");function d(b,w,$){let W=void 0;Object.defineProperty(b,w,{get(){if(W===pW)return;if(W===void 0)W=pW,W=$();return W},set(Q){Object.defineProperty(b,w,{value:Q})},configurable:!0})}function J7(b){return Object.create(Object.getPrototypeOf(b),Object.getOwnPropertyDescriptors(b))}function Lw(b,w,$){Object.defineProperty(b,w,{value:$,writable:!0,enumerable:!0,configurable:!0})}function Uw(...b){let w={};for(let $ of b){let W=Object.getOwnPropertyDescriptors($);Object.assign(w,W)}return Object.defineProperties({},w)}function z7(b){return Uw(b._zod.def)}function A7(b,w){if(!w)return b;return w.reduce(($,W)=>$?.[W],b)}function O7(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 q7(b=10){let $="";for(let W=0;W<b;W++)$+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return $}function L0(b){return JSON.stringify(b)}var U0="captureStackTrace"in Error?Error.captureStackTrace:(...b)=>{};function Sw(b){return typeof b==="object"&&b!==null&&!Array.isArray(b)}var b4=fw(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(b){return!1}});function Bw(b){if(Sw(b)===!1)return!1;let w=b.constructor;if(w===void 0)return!0;let $=w.prototype;if(Sw($)===!1)return!1;if(Object.prototype.hasOwnProperty.call($,"isPrototypeOf")===!1)return!1;return!0}function oW(b){if(Bw(b))return{...b};if(Array.isArray(b))return[...b];return b}function L7(b){let w=0;for(let $ in b)if(Object.prototype.hasOwnProperty.call(b,$))w++;return w}var U7=(b)=>{let w=typeof b;switch(w){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(b)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(b))return"array";if(b===null)return"null";if(b.then&&typeof b.then==="function"&&b.catch&&typeof b.catch==="function")return"promise";if(typeof Map<"u"&&b instanceof Map)return"map";if(typeof Set<"u"&&b instanceof Set)return"set";if(typeof Date<"u"&&b instanceof Date)return"date";if(typeof File<"u"&&b instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${w}`)}},w4=new Set(["string","number","symbol"]),dW=new Set(["string","number","bigint","boolean","symbol","undefined"]);function bw(b){return b.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function xb(b,w,$){let W=new b._zod.constr(w??b._zod.def);if(!w||$?.parent)W._zod.parent=b;return W}function _(b){let w=b;if(!w)return{};if(typeof w==="string")return{error:()=>w};if(w?.message!==void 0){if(w?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");w.error=w.message}if(delete w.message,typeof w.error==="string")return{...w,error:()=>w.error};return w}function B7(b){let w;return new Proxy({},{get($,W,Q){return w??(w=b()),Reflect.get(w,W,Q)},set($,W,Q,G){return w??(w=b()),Reflect.set(w,W,Q,G)},has($,W){return w??(w=b()),Reflect.has(w,W)},deleteProperty($,W){return w??(w=b()),Reflect.deleteProperty(w,W)},ownKeys($){return w??(w=b()),Reflect.ownKeys(w)},getOwnPropertyDescriptor($,W){return w??(w=b()),Reflect.getOwnPropertyDescriptor(w,W)},defineProperty($,W,Q){return w??(w=b()),Reflect.defineProperty(w,W,Q)}})}function B0(b){if(typeof b==="bigint")return b.toString()+"n";if(typeof b==="string")return`"${b}"`;return`${b}`}function $4(b){return Object.keys(b).filter((w)=>{return b[w]._zod.optin==="optional"&&b[w]._zod.optout==="optional"})}var W4={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},tW={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function P7(b,w){let $=b._zod.def,W=Uw(b._zod.def,{get shape(){let Q={};for(let G in w){if(!(G in $.shape))throw Error(`Unrecognized key: "${G}"`);if(!w[G])continue;Q[G]=$.shape[G]}return Lw(this,"shape",Q),Q},checks:[]});return xb(b,W)}function F7(b,w){let $=b._zod.def,W=Uw(b._zod.def,{get shape(){let Q={...b._zod.def.shape};for(let G in w){if(!(G in $.shape))throw Error(`Unrecognized key: "${G}"`);if(!w[G])continue;delete Q[G]}return Lw(this,"shape",Q),Q},checks:[]});return xb(b,W)}function K7(b,w){if(!Bw(w))throw Error("Invalid input to extend: expected a plain object");let $=b._zod.def.checks;if($&&$.length>0)throw Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");let Q=Uw(b._zod.def,{get shape(){let G={...b._zod.def.shape,...w};return Lw(this,"shape",G),G},checks:[]});return xb(b,Q)}function M7(b,w){if(!Bw(w))throw Error("Invalid input to safeExtend: expected a plain object");let $={...b._zod.def,get shape(){let W={...b._zod.def.shape,...w};return Lw(this,"shape",W),W},checks:b._zod.def.checks};return xb(b,$)}function I7(b,w){let $=Uw(b._zod.def,{get shape(){let W={...b._zod.def.shape,...w._zod.def.shape};return Lw(this,"shape",W),W},get catchall(){return w._zod.def.catchall},checks:[]});return xb(b,$)}function Z7(b,w,$){let W=Uw(w._zod.def,{get shape(){let Q=w._zod.def.shape,G={...Q};if($)for(let D in $){if(!(D in Q))throw Error(`Unrecognized key: "${D}"`);if(!$[D])continue;G[D]=b?new b({type:"optional",innerType:Q[D]}):Q[D]}else for(let D in Q)G[D]=b?new b({type:"optional",innerType:Q[D]}):Q[D];return Lw(this,"shape",G),G},checks:[]});return xb(w,W)}function j7(b,w,$){let W=Uw(w._zod.def,{get shape(){let Q=w._zod.def.shape,G={...Q};if($)for(let D in $){if(!(D in G))throw Error(`Unrecognized key: "${D}"`);if(!$[D])continue;G[D]=new b({type:"nonoptional",innerType:Q[D]})}else for(let D in Q)G[D]=new b({type:"nonoptional",innerType:Q[D]});return Lw(this,"shape",G),G},checks:[]});return xb(w,W)}function Pw(b,w=0){if(b.aborted===!0)return!0;for(let $=w;$<b.issues.length;$++)if(b.issues[$]?.continue!==!0)return!0;return!1}function ww(b,w){return w.map(($)=>{var W;return(W=$).path??(W.path=[]),$.path.unshift(b),$})}function O1(b){return typeof b==="string"?b:b?.message}function yb(b,w,$){let W={...b,path:b.path??[]};if(!b.message){let Q=O1(b.inst?._zod.def?.error?.(b))??O1(w?.error?.(b))??O1($.customError?.(b))??O1($.localeError?.(b))??"Invalid input";W.message=Q}if(delete W.inst,delete W.continue,!w?.reportInput)delete W.input;return W}function rW(b){if(b instanceof Set)return"set";if(b instanceof Map)return"map";if(b instanceof File)return"file";return"unknown"}function U1(b){if(Array.isArray(b))return"array";if(typeof b==="string")return"string";return"unknown"}function cw(...b){let[w,$,W]=b;if(typeof w==="string")return{message:w,code:"custom",input:$,inst:W};return{...w}}function V7(b){return Object.entries(b).filter(([w,$])=>{return Number.isNaN(Number.parseInt(w,10))}).map((w)=>w[1])}function eW(b){let w=atob(b),$=new Uint8Array(w.length);for(let W=0;W<w.length;W++)$[W]=w.charCodeAt(W);return $}function sW(b){let w="";for(let $=0;$<b.length;$++)w+=String.fromCharCode(b[$]);return btoa(w)}function N7(b){let w=b.replace(/-/g,"+").replace(/_/g,"/"),$="=".repeat((4-w.length%4)%4);return eW(w+$)}function T7(b){return sW(b).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function E7(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 _7(b){return Array.from(b).map((w)=>w.toString(16).padStart(2,"0")).join("")}class aW{constructor(...b){}}var bQ=(b,w)=>{b.name="$ZodError",Object.defineProperty(b,"_zod",{value:b._zod,enumerable:!1}),Object.defineProperty(b,"issues",{value:w,enumerable:!1}),b.message=JSON.stringify(w,hw,2),Object.defineProperty(b,"toString",{value:()=>b.message,enumerable:!1})},P0=U("$ZodError",bQ),Q4=U("$ZodError",bQ,{Parent:Error});function wQ(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 $Q(b,w=($)=>$.message){let $={_errors:[]},W=(Q)=>{for(let G of Q.issues)if(G.code==="invalid_union"&&G.errors.length)G.errors.map((D)=>W({issues:D}));else if(G.code==="invalid_key")W({issues:G.issues});else if(G.code==="invalid_element")W({issues:G.issues});else if(G.path.length===0)$._errors.push(w(G));else{let D=$,X=0;while(X<G.path.length){let Y=G.path[X];if(X!==G.path.length-1)D[Y]=D[Y]||{_errors:[]};else D[Y]=D[Y]||{_errors:[]},D[Y]._errors.push(w(G));D=D[Y],X++}}};return W(b),$}var F0=(b)=>(w,$,W,Q)=>{let G=W?Object.assign(W,{async:!1}):{async:!1},D=w._zod.run({value:$,issues:[]},G);if(D instanceof Promise)throw new ab;if(D.issues.length){let X=new(Q?.Err??b)(D.issues.map((Y)=>yb(Y,G,Rb())));throw U0(X,Q?.callee),X}return D.value};var K0=(b)=>async(w,$,W,Q)=>{let G=W?Object.assign(W,{async:!0}):{async:!0},D=w._zod.run({value:$,issues:[]},G);if(D instanceof Promise)D=await D;if(D.issues.length){let X=new(Q?.Err??b)(D.issues.map((Y)=>yb(Y,G,Rb())));throw U0(X,Q?.callee),X}return D.value};var B1=(b)=>(w,$,W)=>{let Q=W?{...W,async:!1}:{async:!1},G=w._zod.run({value:$,issues:[]},Q);if(G instanceof Promise)throw new ab;return G.issues.length?{success:!1,error:new(b??P0)(G.issues.map((D)=>yb(D,Q,Rb())))}:{success:!0,data:G.value}},P1=B1(Q4),F1=(b)=>async(w,$,W)=>{let Q=W?Object.assign(W,{async:!0}):{async:!0},G=w._zod.run({value:$,issues:[]},Q);if(G instanceof Promise)G=await G;return G.issues.length?{success:!1,error:new b(G.issues.map((D)=>yb(D,Q,Rb())))}:{success:!0,data:G.value}},M0=F1(Q4),WQ=(b)=>(w,$,W)=>{let Q=W?Object.assign(W,{direction:"backward"}):{direction:"backward"};return F0(b)(w,$,Q)};var QQ=(b)=>(w,$,W)=>{return F0(b)(w,$,W)};var GQ=(b)=>async(w,$,W)=>{let Q=W?Object.assign(W,{direction:"backward"}):{direction:"backward"};return K0(b)(w,$,Q)};var DQ=(b)=>async(w,$,W)=>{return K0(b)(w,$,W)};var XQ=(b)=>(w,$,W)=>{let Q=W?Object.assign(W,{direction:"backward"}):{direction:"backward"};return B1(b)(w,$,Q)};var YQ=(b)=>(w,$,W)=>{return B1(b)(w,$,W)};var HQ=(b)=>async(w,$,W)=>{let Q=W?Object.assign(W,{direction:"backward"}):{direction:"backward"};return F1(b)(w,$,Q)};var JQ=(b)=>async(w,$,W)=>{return F1(b)(w,$,W)};var zQ=/^[cC][^\s-]{8,}$/,AQ=/^[0-9a-z]+$/,OQ=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,qQ=/^[0-9a-vA-V]{20}$/,LQ=/^[A-Za-z0-9]{27}$/,UQ=/^[a-zA-Z0-9_-]{21}$/,BQ=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var PQ=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,G4=(b)=>{if(!b)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${b}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)};var FQ=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function KQ(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}var MQ=/^(?:(?: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])$/,IQ=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,ZQ=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,jQ=/^(([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])$/,VQ=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,D4=/^[A-Za-z0-9_-]*$/,NQ=/^(?=.{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 TQ=/^\+(?:[0-9]){6,14}[0-9]$/,EQ="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",_Q=new RegExp(`^${EQ}$`);function SQ(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 RQ(b){return new RegExp(`^${SQ(b)}$`)}function vQ(b){let w=SQ({precision:b.precision}),$=["Z"];if(b.local)$.push("");if(b.offset)$.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let W=`${w}(?:${$.join("|")})`;return new RegExp(`^${EQ}T(?:${W})$`)}var kQ=(b)=>{let w=b?`[\\s\\S]{${b?.minimum??0},${b?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${w}$`)};var CQ=/^-?\d+$/,uQ=/^-?\d+(?:\.\d+)?/,xQ=/^(?:true|false)$/i,yQ=/^null$/i;var hQ=/^[^A-Z]*$/,fQ=/^[^a-z]*$/;var Hb=U("$ZodCheck",(b,w)=>{var $;b._zod??(b._zod={}),b._zod.def=w,($=b._zod).onattach??($.onattach=[])}),cQ={number:"number",bigint:"bigint",object:"date"},X4=U("$ZodCheckLessThan",(b,w)=>{Hb.init(b,w);let $=cQ[typeof w.value];b._zod.onattach.push((W)=>{let Q=W._zod.bag,G=(w.inclusive?Q.maximum:Q.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(w.value<G)if(w.inclusive)Q.maximum=w.value;else Q.exclusiveMaximum=w.value}),b._zod.check=(W)=>{if(w.inclusive?W.value<=w.value:W.value<w.value)return;W.issues.push({origin:$,code:"too_big",maximum:w.value,input:W.value,inclusive:w.inclusive,inst:b,continue:!w.abort})}}),Y4=U("$ZodCheckGreaterThan",(b,w)=>{Hb.init(b,w);let $=cQ[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})}}),nQ=U("$ZodCheckMultipleOf",(b,w)=>{Hb.init(b,w),b._zod.onattach.push(($)=>{var W;(W=$._zod.bag).multipleOf??(W.multipleOf=w.value)}),b._zod.check=($)=>{if(typeof $.value!==typeof w.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof $.value==="bigint"?$.value%w.value===BigInt(0):a$($.value,w.value)===0)return;$.issues.push({origin:typeof $.value,code:"not_multiple_of",divisor:w.value,input:$.value,inst:b,continue:!w.abort})}}),gQ=U("$ZodCheckNumberFormat",(b,w)=>{Hb.init(b,w),w.format=w.format||"float64";let $=w.format?.includes("int"),W=$?"int":"number",[Q,G]=W4[w.format];b._zod.onattach.push((D)=>{let X=D._zod.bag;if(X.format=w.format,X.minimum=Q,X.maximum=G,$)X.pattern=CQ}),b._zod.check=(D)=>{let X=D.value;if($){if(!Number.isInteger(X)){D.issues.push({expected:W,format:w.format,code:"invalid_type",continue:!1,input:X,inst:b});return}if(!Number.isSafeInteger(X)){if(X>0)D.issues.push({input:X,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:b,origin:W,continue:!w.abort});else D.issues.push({input:X,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:b,origin:W,continue:!w.abort});return}}if(X<Q)D.issues.push({origin:"number",input:X,code:"too_small",minimum:Q,inclusive:!0,inst:b,continue:!w.abort});if(X>G)D.issues.push({origin:"number",input:X,code:"too_big",maximum:G,inst:b})}});var mQ=U("$ZodCheckMaxLength",(b,w)=>{var $;Hb.init(b,w),($=b._zod.def).when??($.when=(W)=>{let Q=W.value;return!q1(Q)&&Q.length!==void 0}),b._zod.onattach.push((W)=>{let Q=W._zod.bag.maximum??Number.POSITIVE_INFINITY;if(w.maximum<Q)W._zod.bag.maximum=w.maximum}),b._zod.check=(W)=>{let Q=W.value;if(Q.length<=w.maximum)return;let D=U1(Q);W.issues.push({origin:D,code:"too_big",maximum:w.maximum,inclusive:!0,input:Q,inst:b,continue:!w.abort})}}),iQ=U("$ZodCheckMinLength",(b,w)=>{var $;Hb.init(b,w),($=b._zod.def).when??($.when=(W)=>{let Q=W.value;return!q1(Q)&&Q.length!==void 0}),b._zod.onattach.push((W)=>{let Q=W._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(w.minimum>Q)W._zod.bag.minimum=w.minimum}),b._zod.check=(W)=>{let Q=W.value;if(Q.length>=w.minimum)return;let D=U1(Q);W.issues.push({origin:D,code:"too_small",minimum:w.minimum,inclusive:!0,input:Q,inst:b,continue:!w.abort})}}),lQ=U("$ZodCheckLengthEquals",(b,w)=>{var $;Hb.init(b,w),($=b._zod.def).when??($.when=(W)=>{let Q=W.value;return!q1(Q)&&Q.length!==void 0}),b._zod.onattach.push((W)=>{let Q=W._zod.bag;Q.minimum=w.length,Q.maximum=w.length,Q.length=w.length}),b._zod.check=(W)=>{let Q=W.value,G=Q.length;if(G===w.length)return;let D=U1(Q),X=G>w.length;W.issues.push({origin:D,...X?{code:"too_big",maximum:w.length}:{code:"too_small",minimum:w.length},inclusive:!0,exact:!0,input:W.value,inst:b,continue:!w.abort})}}),K1=U("$ZodCheckStringFormat",(b,w)=>{var $,W;if(Hb.init(b,w),b._zod.onattach.push((Q)=>{let G=Q._zod.bag;if(G.format=w.format,w.pattern)G.patterns??(G.patterns=new Set),G.patterns.add(w.pattern)}),w.pattern)($=b._zod).check??($.check=(Q)=>{if(w.pattern.lastIndex=0,w.pattern.test(Q.value))return;Q.issues.push({origin:"string",code:"invalid_format",format:w.format,input:Q.value,...w.pattern?{pattern:w.pattern.toString()}:{},inst:b,continue:!w.abort})});else(W=b._zod).check??(W.check=()=>{})}),pQ=U("$ZodCheckRegex",(b,w)=>{K1.init(b,w),b._zod.check=($)=>{if(w.pattern.lastIndex=0,w.pattern.test($.value))return;$.issues.push({origin:"string",code:"invalid_format",format:"regex",input:$.value,pattern:w.pattern.toString(),inst:b,continue:!w.abort})}}),oQ=U("$ZodCheckLowerCase",(b,w)=>{w.pattern??(w.pattern=hQ),K1.init(b,w)}),dQ=U("$ZodCheckUpperCase",(b,w)=>{w.pattern??(w.pattern=fQ),K1.init(b,w)}),tQ=U("$ZodCheckIncludes",(b,w)=>{Hb.init(b,w);let $=bw(w.includes),W=new RegExp(typeof w.position==="number"?`^.{${w.position}}${$}`:$);w.pattern=W,b._zod.onattach.push((Q)=>{let G=Q._zod.bag;G.patterns??(G.patterns=new Set),G.patterns.add(W)}),b._zod.check=(Q)=>{if(Q.value.includes(w.includes,w.position))return;Q.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:w.includes,input:Q.value,inst:b,continue:!w.abort})}}),rQ=U("$ZodCheckStartsWith",(b,w)=>{Hb.init(b,w);let $=new RegExp(`^${bw(w.prefix)}.*`);w.pattern??(w.pattern=$),b._zod.onattach.push((W)=>{let Q=W._zod.bag;Q.patterns??(Q.patterns=new Set),Q.patterns.add($)}),b._zod.check=(W)=>{if(W.value.startsWith(w.prefix))return;W.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:w.prefix,input:W.value,inst:b,continue:!w.abort})}}),eQ=U("$ZodCheckEndsWith",(b,w)=>{Hb.init(b,w);let $=new RegExp(`.*${bw(w.suffix)}$`);w.pattern??(w.pattern=$),b._zod.onattach.push((W)=>{let Q=W._zod.bag;Q.patterns??(Q.patterns=new Set),Q.patterns.add($)}),b._zod.check=(W)=>{if(W.value.endsWith(w.suffix))return;W.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:w.suffix,input:W.value,inst:b,continue:!w.abort})}});var sQ=U("$ZodCheckOverwrite",(b,w)=>{Hb.init(b,w),b._zod.check=($)=>{$.value=w.tx($.value)}});class H4{constructor(b=[]){if(this.content=[],this.indent=0,this)this.args=b}indented(b){this.indent+=1,b(this),this.indent-=1}write(b){if(typeof b==="function"){b(this,{execution:"sync"}),b(this,{execution:"async"});return}let $=b.split(`
11
11
  `).filter((G)=>G),W=Math.min(...$.map((G)=>G.length-G.trimStart().length)),Q=$.map((G)=>G.slice(W)).map((G)=>" ".repeat(this.indent*2)+G);for(let G of Q)this.content.push(G)}compile(){let b=Function,w=this?.args,W=[...(this?.content??[""]).map((Q)=>` ${Q}`)];return new b(...w,W.join(`
12
- `))}}var b9={major:4,minor:1,patch:12};var e=U("$ZodType",(b,w)=>{var $;b??(b={}),b._zod.def=w,b._zod.bag=b._zod.bag||{},b._zod.version=b9;let W=[...b._zod.def.checks??[]];if(b._zod.traits.has("$ZodCheck"))W.unshift(b);for(let Q of W)for(let G of Q._zod.onattach)G(b);if(W.length===0)($=b._zod).deferred??($.deferred=[]),b._zod.deferred?.push(()=>{b._zod.run=b._zod.parse});else{let Q=(D,X,Y)=>{let H=Pw(D),J;for(let z of X){if(z._zod.def.when){if(!z._zod.def.when(D))continue}else if(H)continue;let O=D.issues.length,q=z._zod.check(D);if(q instanceof Promise&&Y?.async===!1)throw new ab;if(J||q instanceof Promise)J=(J??Promise.resolve()).then(async()=>{if(await q,D.issues.length===O)return;if(!H)H=Pw(D,O)});else{if(D.issues.length===O)continue;if(!H)H=Pw(D,O)}}if(J)return J.then(()=>{return D});return D},G=(D,X,Y)=>{if(Pw(D))return D.aborted=!0,D;let H=Q(X,W,Y);if(H instanceof Promise){if(Y.async===!1)throw new ab;return H.then((J)=>b._zod.parse(J,Y))}return b._zod.parse(H,Y)};b._zod.run=(D,X)=>{if(X.skipChecks)return b._zod.parse(D,X);if(X.direction==="backward"){let H=b._zod.parse({value:D.value,issues:[]},{...X,skipChecks:!0});if(H instanceof Promise)return H.then((J)=>{return G(J,D,X)});return G(H,D,X)}let Y=b._zod.parse(D,X);if(Y instanceof Promise){if(X.async===!1)throw new ab;return Y.then((H)=>Q(H,W,X))}return Q(Y,W,X)}}b["~standard"]={validate:(Q)=>{try{let G=P1(b,Q);return G.success?{value:G.data}:{issues:G.error?.issues}}catch(G){return M0(b,Q).then((D)=>D.success?{value:D.data}:{issues:D.error?.issues})}},vendor:"zod",version:1}}),V0=U("$ZodString",(b,w)=>{e.init(b,w),b._zod.pattern=[...b?._zod.bag?.patterns??[]].pop()??kQ(b._zod.bag),b._zod.parse=($,W)=>{if(w.coerce)try{$.value=String($.value)}catch(Q){}if(typeof $.value==="string")return $;return $.issues.push({expected:"string",code:"invalid_type",input:$.value,inst:b}),$}}),s=U("$ZodStringFormat",(b,w)=>{K1.init(b,w),V0.init(b,w)}),H9=U("$ZodGUID",(b,w)=>{w.pattern??(w.pattern=PQ),s.init(b,w)}),J9=U("$ZodUUID",(b,w)=>{if(w.version){let W={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[w.version];if(W===void 0)throw Error(`Invalid UUID version: "${w.version}"`);w.pattern??(w.pattern=G6(W))}else w.pattern??(w.pattern=G6());s.init(b,w)}),z9=U("$ZodEmail",(b,w)=>{w.pattern??(w.pattern=FQ),s.init(b,w)}),A9=U("$ZodURL",(b,w)=>{s.init(b,w),b._zod.check=($)=>{try{let W=$.value.trim(),Q=new URL(W);if(w.hostname){if(w.hostname.lastIndex=0,!w.hostname.test(Q.hostname))$.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:NQ.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})}}}),O9=U("$ZodEmoji",(b,w)=>{w.pattern??(w.pattern=KQ()),s.init(b,w)}),q9=U("$ZodNanoID",(b,w)=>{w.pattern??(w.pattern=UQ),s.init(b,w)}),L9=U("$ZodCUID",(b,w)=>{w.pattern??(w.pattern=zQ),s.init(b,w)}),U9=U("$ZodCUID2",(b,w)=>{w.pattern??(w.pattern=AQ),s.init(b,w)}),B9=U("$ZodULID",(b,w)=>{w.pattern??(w.pattern=OQ),s.init(b,w)}),P9=U("$ZodXID",(b,w)=>{w.pattern??(w.pattern=qQ),s.init(b,w)}),F9=U("$ZodKSUID",(b,w)=>{w.pattern??(w.pattern=LQ),s.init(b,w)}),K9=U("$ZodISODateTime",(b,w)=>{w.pattern??(w.pattern=vQ(w)),s.init(b,w)}),M9=U("$ZodISODate",(b,w)=>{w.pattern??(w.pattern=_Q),s.init(b,w)}),I9=U("$ZodISOTime",(b,w)=>{w.pattern??(w.pattern=RQ(w)),s.init(b,w)}),Z9=U("$ZodISODuration",(b,w)=>{w.pattern??(w.pattern=BQ),s.init(b,w)}),j9=U("$ZodIPv4",(b,w)=>{w.pattern??(w.pattern=MQ),s.init(b,w),b._zod.onattach.push(($)=>{let W=$._zod.bag;W.format="ipv4"})}),V9=U("$ZodIPv6",(b,w)=>{w.pattern??(w.pattern=IQ),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})}}}),N9=U("$ZodCIDRv4",(b,w)=>{w.pattern??(w.pattern=ZQ),s.init(b,w)}),T9=U("$ZodCIDRv6",(b,w)=>{w.pattern??(w.pattern=jQ),s.init(b,w),b._zod.check=($)=>{let W=$.value.split("/");try{if(W.length!==2)throw Error();let[Q,G]=W;if(!G)throw Error();let D=Number(G);if(`${D}`!==G)throw Error();if(D<0||D>128)throw Error();new URL(`http://[${Q}]`)}catch{$.issues.push({code:"invalid_format",format:"cidrv6",input:$.value,inst:b,continue:!w.abort})}}});function E9(b){if(b==="")return!0;if(b.length%4!==0)return!1;try{return atob(b),!0}catch{return!1}}var _9=U("$ZodBase64",(b,w)=>{w.pattern??(w.pattern=VQ),s.init(b,w),b._zod.onattach.push(($)=>{$._zod.bag.contentEncoding="base64"}),b._zod.check=($)=>{if(E9($.value))return;$.issues.push({code:"invalid_format",format:"base64",input:$.value,inst:b,continue:!w.abort})}});function k7(b){if(!D6.test(b))return!1;let w=b.replace(/[-_]/g,(W)=>W==="-"?"+":"/"),$=w.padEnd(Math.ceil(w.length/4)*4,"=");return E9($)}var S9=U("$ZodBase64URL",(b,w)=>{w.pattern??(w.pattern=D6),s.init(b,w),b._zod.onattach.push(($)=>{$._zod.bag.contentEncoding="base64url"}),b._zod.check=($)=>{if(k7($.value))return;$.issues.push({code:"invalid_format",format:"base64url",input:$.value,inst:b,continue:!w.abort})}}),R9=U("$ZodE164",(b,w)=>{w.pattern??(w.pattern=TQ),s.init(b,w)});function C7(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 v9=U("$ZodJWT",(b,w)=>{s.init(b,w),b._zod.check=($)=>{if(C7($.value,w.alg))return;$.issues.push({code:"invalid_format",format:"jwt",input:$.value,inst:b,continue:!w.abort})}});var z6=U("$ZodNumber",(b,w)=>{e.init(b,w),b._zod.pattern=b._zod.bag.pattern??uQ,b._zod.parse=($,W)=>{if(w.coerce)try{$.value=Number($.value)}catch(D){}let Q=$.value;if(typeof Q==="number"&&!Number.isNaN(Q)&&Number.isFinite(Q))return $;let G=typeof Q==="number"?Number.isNaN(Q)?"NaN":!Number.isFinite(Q)?"Infinity":void 0:void 0;return $.issues.push({expected:"number",code:"invalid_type",input:Q,inst:b,...G?{received:G}:{}}),$}}),k9=U("$ZodNumber",(b,w)=>{gQ.init(b,w),z6.init(b,w)}),C9=U("$ZodBoolean",(b,w)=>{e.init(b,w),b._zod.pattern=xQ,b._zod.parse=($,W)=>{if(w.coerce)try{$.value=Boolean($.value)}catch(G){}let Q=$.value;if(typeof Q==="boolean")return $;return $.issues.push({expected:"boolean",code:"invalid_type",input:Q,inst:b}),$}});var u9=U("$ZodNull",(b,w)=>{e.init(b,w),b._zod.pattern=yQ,b._zod.values=new Set([null]),b._zod.parse=($,W)=>{let Q=$.value;if(Q===null)return $;return $.issues.push({expected:"null",code:"invalid_type",input:Q,inst:b}),$}});var x9=U("$ZodUnknown",(b,w)=>{e.init(b,w),b._zod.parse=($)=>$}),y9=U("$ZodNever",(b,w)=>{e.init(b,w),b._zod.parse=($,W)=>{return $.issues.push({expected:"never",code:"invalid_type",input:$.value,inst:b}),$}});function w9(b,w,$){if(b.issues.length)w.issues.push(...ww($,b.issues));w.value[$]=b.value}var h9=U("$ZodArray",(b,w)=>{e.init(b,w),b._zod.parse=($,W)=>{let Q=$.value;if(!Array.isArray(Q))return $.issues.push({expected:"array",code:"invalid_type",input:Q,inst:b}),$;$.value=Array(Q.length);let G=[];for(let D=0;D<Q.length;D++){let X=Q[D],Y=w.element._zod.run({value:X,issues:[]},W);if(Y instanceof Promise)G.push(Y.then((H)=>w9(H,$,D)));else w9(Y,$,D)}if(G.length)return Promise.all(G).then(()=>$);return $}});function j0(b,w,$,W){if(b.issues.length)w.issues.push(...ww($,b.issues));if(b.value===void 0){if($ in W)w.value[$]=void 0}else w.value[$]=b.value}function f9(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 $=$6(b.shape);return{...b,keys:w,keySet:new Set(w),numKeys:w.length,optionalKeys:new Set($)}}function c9(b,w,$,W,Q,G){let D=[],X=Q.keySet,Y=Q.catchall._zod,H=Y.def.type;for(let J of Object.keys(w)){if(X.has(J))continue;if(H==="never"){D.push(J);continue}let z=Y.run({value:w[J],issues:[]},W);if(z instanceof Promise)b.push(z.then((O)=>j0(O,$,J,w)));else j0(z,$,J,w)}if(D.length)$.issues.push({code:"unrecognized_keys",keys:D,input:w,inst:G});if(!b.length)return $;return Promise.all(b).then(()=>{return $})}var u7=U("$ZodObject",(b,w)=>{if(e.init(b,w),!Object.getOwnPropertyDescriptor(w,"shape")?.get){let X=w.shape;Object.defineProperty(w,"shape",{get:()=>{let Y={...X};return Object.defineProperty(w,"shape",{value:Y}),Y}})}let W=fw(()=>f9(w));d(b._zod,"propValues",()=>{let X=w.shape,Y={};for(let H in X){let J=X[H]._zod;if(J.values){Y[H]??(Y[H]=new Set);for(let z of J.values)Y[H].add(z)}}return Y});let Q=Sw,G=w.catchall,D;b._zod.parse=(X,Y)=>{D??(D=W.value);let H=X.value;if(!Q(H))return X.issues.push({expected:"object",code:"invalid_type",input:H,inst:b}),X;X.value={};let J=[],z=D.shape;for(let O of D.keys){let B=z[O]._zod.run({value:H[O],issues:[]},Y);if(B instanceof Promise)J.push(B.then((K)=>j0(K,X,O,H)));else j0(B,X,O,H)}if(!G)return J.length?Promise.all(J).then(()=>X):X;return c9(J,H,X,Y,W.value,b)}}),n9=U("$ZodObjectJIT",(b,w)=>{u7.init(b,w);let $=b._zod.parse,W=fw(()=>f9(w)),Q=(O)=>{let q=new H6(["shape","payload","ctx"]),B=W.value,K=(S)=>{let h=L0(S);return`shape[${h}]._zod.run({ value: input[${h}], issues: [] }, ctx)`};q.write("const input = payload.value;");let I=Object.create(null),M=0;for(let S of B.keys)I[S]=`key_${M++}`;q.write("const newResult = {};");for(let S of B.keys){let h=I[S],R=L0(S);q.write(`const ${h} = ${K(S)};`),q.write(`
12
+ `))}}var b9={major:4,minor:1,patch:12};var e=U("$ZodType",(b,w)=>{var $;b??(b={}),b._zod.def=w,b._zod.bag=b._zod.bag||{},b._zod.version=b9;let W=[...b._zod.def.checks??[]];if(b._zod.traits.has("$ZodCheck"))W.unshift(b);for(let Q of W)for(let G of Q._zod.onattach)G(b);if(W.length===0)($=b._zod).deferred??($.deferred=[]),b._zod.deferred?.push(()=>{b._zod.run=b._zod.parse});else{let Q=(D,X,Y)=>{let H=Pw(D),J;for(let z of X){if(z._zod.def.when){if(!z._zod.def.when(D))continue}else if(H)continue;let O=D.issues.length,q=z._zod.check(D);if(q instanceof Promise&&Y?.async===!1)throw new ab;if(J||q instanceof Promise)J=(J??Promise.resolve()).then(async()=>{if(await q,D.issues.length===O)return;if(!H)H=Pw(D,O)});else{if(D.issues.length===O)continue;if(!H)H=Pw(D,O)}}if(J)return J.then(()=>{return D});return D},G=(D,X,Y)=>{if(Pw(D))return D.aborted=!0,D;let H=Q(X,W,Y);if(H instanceof Promise){if(Y.async===!1)throw new ab;return H.then((J)=>b._zod.parse(J,Y))}return b._zod.parse(H,Y)};b._zod.run=(D,X)=>{if(X.skipChecks)return b._zod.parse(D,X);if(X.direction==="backward"){let H=b._zod.parse({value:D.value,issues:[]},{...X,skipChecks:!0});if(H instanceof Promise)return H.then((J)=>{return G(J,D,X)});return G(H,D,X)}let Y=b._zod.parse(D,X);if(Y instanceof Promise){if(X.async===!1)throw new ab;return Y.then((H)=>Q(H,W,X))}return Q(Y,W,X)}}b["~standard"]={validate:(Q)=>{try{let G=P1(b,Q);return G.success?{value:G.data}:{issues:G.error?.issues}}catch(G){return M0(b,Q).then((D)=>D.success?{value:D.data}:{issues:D.error?.issues})}},vendor:"zod",version:1}}),V0=U("$ZodString",(b,w)=>{e.init(b,w),b._zod.pattern=[...b?._zod.bag?.patterns??[]].pop()??kQ(b._zod.bag),b._zod.parse=($,W)=>{if(w.coerce)try{$.value=String($.value)}catch(Q){}if(typeof $.value==="string")return $;return $.issues.push({expected:"string",code:"invalid_type",input:$.value,inst:b}),$}}),s=U("$ZodStringFormat",(b,w)=>{K1.init(b,w),V0.init(b,w)}),H9=U("$ZodGUID",(b,w)=>{w.pattern??(w.pattern=PQ),s.init(b,w)}),J9=U("$ZodUUID",(b,w)=>{if(w.version){let W={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[w.version];if(W===void 0)throw Error(`Invalid UUID version: "${w.version}"`);w.pattern??(w.pattern=G4(W))}else w.pattern??(w.pattern=G4());s.init(b,w)}),z9=U("$ZodEmail",(b,w)=>{w.pattern??(w.pattern=FQ),s.init(b,w)}),A9=U("$ZodURL",(b,w)=>{s.init(b,w),b._zod.check=($)=>{try{let W=$.value.trim(),Q=new URL(W);if(w.hostname){if(w.hostname.lastIndex=0,!w.hostname.test(Q.hostname))$.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:NQ.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})}}}),O9=U("$ZodEmoji",(b,w)=>{w.pattern??(w.pattern=KQ()),s.init(b,w)}),q9=U("$ZodNanoID",(b,w)=>{w.pattern??(w.pattern=UQ),s.init(b,w)}),L9=U("$ZodCUID",(b,w)=>{w.pattern??(w.pattern=zQ),s.init(b,w)}),U9=U("$ZodCUID2",(b,w)=>{w.pattern??(w.pattern=AQ),s.init(b,w)}),B9=U("$ZodULID",(b,w)=>{w.pattern??(w.pattern=OQ),s.init(b,w)}),P9=U("$ZodXID",(b,w)=>{w.pattern??(w.pattern=qQ),s.init(b,w)}),F9=U("$ZodKSUID",(b,w)=>{w.pattern??(w.pattern=LQ),s.init(b,w)}),K9=U("$ZodISODateTime",(b,w)=>{w.pattern??(w.pattern=vQ(w)),s.init(b,w)}),M9=U("$ZodISODate",(b,w)=>{w.pattern??(w.pattern=_Q),s.init(b,w)}),I9=U("$ZodISOTime",(b,w)=>{w.pattern??(w.pattern=RQ(w)),s.init(b,w)}),Z9=U("$ZodISODuration",(b,w)=>{w.pattern??(w.pattern=BQ),s.init(b,w)}),j9=U("$ZodIPv4",(b,w)=>{w.pattern??(w.pattern=MQ),s.init(b,w),b._zod.onattach.push(($)=>{let W=$._zod.bag;W.format="ipv4"})}),V9=U("$ZodIPv6",(b,w)=>{w.pattern??(w.pattern=IQ),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})}}}),N9=U("$ZodCIDRv4",(b,w)=>{w.pattern??(w.pattern=ZQ),s.init(b,w)}),T9=U("$ZodCIDRv6",(b,w)=>{w.pattern??(w.pattern=jQ),s.init(b,w),b._zod.check=($)=>{let W=$.value.split("/");try{if(W.length!==2)throw Error();let[Q,G]=W;if(!G)throw Error();let D=Number(G);if(`${D}`!==G)throw Error();if(D<0||D>128)throw Error();new URL(`http://[${Q}]`)}catch{$.issues.push({code:"invalid_format",format:"cidrv6",input:$.value,inst:b,continue:!w.abort})}}});function E9(b){if(b==="")return!0;if(b.length%4!==0)return!1;try{return atob(b),!0}catch{return!1}}var _9=U("$ZodBase64",(b,w)=>{w.pattern??(w.pattern=VQ),s.init(b,w),b._zod.onattach.push(($)=>{$._zod.bag.contentEncoding="base64"}),b._zod.check=($)=>{if(E9($.value))return;$.issues.push({code:"invalid_format",format:"base64",input:$.value,inst:b,continue:!w.abort})}});function k7(b){if(!D4.test(b))return!1;let w=b.replace(/[-_]/g,(W)=>W==="-"?"+":"/"),$=w.padEnd(Math.ceil(w.length/4)*4,"=");return E9($)}var S9=U("$ZodBase64URL",(b,w)=>{w.pattern??(w.pattern=D4),s.init(b,w),b._zod.onattach.push(($)=>{$._zod.bag.contentEncoding="base64url"}),b._zod.check=($)=>{if(k7($.value))return;$.issues.push({code:"invalid_format",format:"base64url",input:$.value,inst:b,continue:!w.abort})}}),R9=U("$ZodE164",(b,w)=>{w.pattern??(w.pattern=TQ),s.init(b,w)});function C7(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 v9=U("$ZodJWT",(b,w)=>{s.init(b,w),b._zod.check=($)=>{if(C7($.value,w.alg))return;$.issues.push({code:"invalid_format",format:"jwt",input:$.value,inst:b,continue:!w.abort})}});var z4=U("$ZodNumber",(b,w)=>{e.init(b,w),b._zod.pattern=b._zod.bag.pattern??uQ,b._zod.parse=($,W)=>{if(w.coerce)try{$.value=Number($.value)}catch(D){}let Q=$.value;if(typeof Q==="number"&&!Number.isNaN(Q)&&Number.isFinite(Q))return $;let G=typeof Q==="number"?Number.isNaN(Q)?"NaN":!Number.isFinite(Q)?"Infinity":void 0:void 0;return $.issues.push({expected:"number",code:"invalid_type",input:Q,inst:b,...G?{received:G}:{}}),$}}),k9=U("$ZodNumber",(b,w)=>{gQ.init(b,w),z4.init(b,w)}),C9=U("$ZodBoolean",(b,w)=>{e.init(b,w),b._zod.pattern=xQ,b._zod.parse=($,W)=>{if(w.coerce)try{$.value=Boolean($.value)}catch(G){}let Q=$.value;if(typeof Q==="boolean")return $;return $.issues.push({expected:"boolean",code:"invalid_type",input:Q,inst:b}),$}});var u9=U("$ZodNull",(b,w)=>{e.init(b,w),b._zod.pattern=yQ,b._zod.values=new Set([null]),b._zod.parse=($,W)=>{let Q=$.value;if(Q===null)return $;return $.issues.push({expected:"null",code:"invalid_type",input:Q,inst:b}),$}});var x9=U("$ZodUnknown",(b,w)=>{e.init(b,w),b._zod.parse=($)=>$}),y9=U("$ZodNever",(b,w)=>{e.init(b,w),b._zod.parse=($,W)=>{return $.issues.push({expected:"never",code:"invalid_type",input:$.value,inst:b}),$}});function w9(b,w,$){if(b.issues.length)w.issues.push(...ww($,b.issues));w.value[$]=b.value}var h9=U("$ZodArray",(b,w)=>{e.init(b,w),b._zod.parse=($,W)=>{let Q=$.value;if(!Array.isArray(Q))return $.issues.push({expected:"array",code:"invalid_type",input:Q,inst:b}),$;$.value=Array(Q.length);let G=[];for(let D=0;D<Q.length;D++){let X=Q[D],Y=w.element._zod.run({value:X,issues:[]},W);if(Y instanceof Promise)G.push(Y.then((H)=>w9(H,$,D)));else w9(Y,$,D)}if(G.length)return Promise.all(G).then(()=>$);return $}});function j0(b,w,$,W){if(b.issues.length)w.issues.push(...ww($,b.issues));if(b.value===void 0){if($ in W)w.value[$]=void 0}else w.value[$]=b.value}function f9(b){let w=Object.keys(b.shape);for(let W of w)if(!b.shape?.[W]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${W}": expected a Zod schema`);let $=$4(b.shape);return{...b,keys:w,keySet:new Set(w),numKeys:w.length,optionalKeys:new Set($)}}function c9(b,w,$,W,Q,G){let D=[],X=Q.keySet,Y=Q.catchall._zod,H=Y.def.type;for(let J of Object.keys(w)){if(X.has(J))continue;if(H==="never"){D.push(J);continue}let z=Y.run({value:w[J],issues:[]},W);if(z instanceof Promise)b.push(z.then((O)=>j0(O,$,J,w)));else j0(z,$,J,w)}if(D.length)$.issues.push({code:"unrecognized_keys",keys:D,input:w,inst:G});if(!b.length)return $;return Promise.all(b).then(()=>{return $})}var u7=U("$ZodObject",(b,w)=>{if(e.init(b,w),!Object.getOwnPropertyDescriptor(w,"shape")?.get){let X=w.shape;Object.defineProperty(w,"shape",{get:()=>{let Y={...X};return Object.defineProperty(w,"shape",{value:Y}),Y}})}let W=fw(()=>f9(w));d(b._zod,"propValues",()=>{let X=w.shape,Y={};for(let H in X){let J=X[H]._zod;if(J.values){Y[H]??(Y[H]=new Set);for(let z of J.values)Y[H].add(z)}}return Y});let Q=Sw,G=w.catchall,D;b._zod.parse=(X,Y)=>{D??(D=W.value);let H=X.value;if(!Q(H))return X.issues.push({expected:"object",code:"invalid_type",input:H,inst:b}),X;X.value={};let J=[],z=D.shape;for(let O of D.keys){let B=z[O]._zod.run({value:H[O],issues:[]},Y);if(B instanceof Promise)J.push(B.then((K)=>j0(K,X,O,H)));else j0(B,X,O,H)}if(!G)return J.length?Promise.all(J).then(()=>X):X;return c9(J,H,X,Y,W.value,b)}}),n9=U("$ZodObjectJIT",(b,w)=>{u7.init(b,w);let $=b._zod.parse,W=fw(()=>f9(w)),Q=(O)=>{let q=new H4(["shape","payload","ctx"]),B=W.value,K=(S)=>{let h=L0(S);return`shape[${h}]._zod.run({ value: input[${h}], issues: [] }, ctx)`};q.write("const input = payload.value;");let I=Object.create(null),M=0;for(let S of B.keys)I[S]=`key_${M++}`;q.write("const newResult = {};");for(let S of B.keys){let h=I[S],R=L0(S);q.write(`const ${h} = ${K(S)};`),q.write(`
13
13
  if (${h}.issues.length) {
14
14
  payload.issues = payload.issues.concat(${h}.issues.map(iss => ({
15
15
  ...iss,
@@ -26,7 +26,7 @@ var iz=Object.create;var{getPrototypeOf:lz,defineProperty:t$,getOwnPropertyNames
26
26
  newResult[${R}] = ${h}.value;
27
27
  }
28
28
 
29
- `)}q.write("payload.value = newResult;"),q.write("return payload;");let v=q.compile();return(S,h)=>v(O,S,h)},G,D=Sw,X=!O0.jitless,H=X&&b6.value,J=w.catchall,z;b._zod.parse=(O,q)=>{z??(z=W.value);let B=O.value;if(!D(B))return O.issues.push({expected:"object",code:"invalid_type",input:B,inst:b}),O;if(X&&H&&q?.async===!1&&q.jitless!==!0){if(!G)G=Q(w.shape);if(O=G(O,q),!J)return O;return c9([],B,O,q,z,b)}return $(O,q)}});function $9(b,w,$,W){for(let G of b)if(G.issues.length===0)return w.value=G.value,w;let Q=b.filter((G)=>!Pw(G));if(Q.length===1)return w.value=Q[0].value,Q[0];return w.issues.push({code:"invalid_union",input:w.value,inst:$,errors:b.map((G)=>G.issues.map((D)=>yb(D,W,Rb())))}),w}var A6=U("$ZodUnion",(b,w)=>{e.init(b,w),d(b._zod,"optin",()=>w.options.some((Q)=>Q._zod.optin==="optional")?"optional":void 0),d(b._zod,"optout",()=>w.options.some((Q)=>Q._zod.optout==="optional")?"optional":void 0),d(b._zod,"values",()=>{if(w.options.every((Q)=>Q._zod.values))return new Set(w.options.flatMap((Q)=>Array.from(Q._zod.values)));return}),d(b._zod,"pattern",()=>{if(w.options.every((Q)=>Q._zod.pattern)){let Q=w.options.map((G)=>G._zod.pattern);return new RegExp(`^(${Q.map((G)=>L1(G.source)).join("|")})$`)}return});let $=w.options.length===1,W=w.options[0]._zod.run;b._zod.parse=(Q,G)=>{if($)return W(Q,G);let D=!1,X=[];for(let Y of w.options){let H=Y._zod.run({value:Q.value,issues:[]},G);if(H instanceof Promise)X.push(H),D=!0;else{if(H.issues.length===0)return H;X.push(H)}}if(!D)return $9(X,Q,b,G);return Promise.all(X).then((Y)=>{return $9(Y,Q,b,G)})}}),g9=U("$ZodDiscriminatedUnion",(b,w)=>{A6.init(b,w);let $=b._zod.parse;d(b._zod,"propValues",()=>{let Q={};for(let G of w.options){let D=G._zod.propValues;if(!D||Object.keys(D).length===0)throw Error(`Invalid discriminated union option at index "${w.options.indexOf(G)}"`);for(let[X,Y]of Object.entries(D)){if(!Q[X])Q[X]=new Set;for(let H of Y)Q[X].add(H)}}return Q});let W=fw(()=>{let Q=w.options,G=new Map;for(let D of Q){let X=D._zod.propValues?.[w.discriminator];if(!X||X.size===0)throw Error(`Invalid discriminated union option at index "${w.options.indexOf(D)}"`);for(let Y of X){if(G.has(Y))throw Error(`Duplicate discriminator value "${String(Y)}"`);G.set(Y,D)}}return G});b._zod.parse=(Q,G)=>{let D=Q.value;if(!Sw(D))return Q.issues.push({code:"invalid_type",expected:"object",input:D,inst:b}),Q;let X=W.value.get(D?.[w.discriminator]);if(X)return X._zod.run(Q,G);if(w.unionFallback)return $(Q,G);return Q.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:w.discriminator,input:D,path:[w.discriminator],inst:b}),Q}}),m9=U("$ZodIntersection",(b,w)=>{e.init(b,w),b._zod.parse=($,W)=>{let Q=$.value,G=w.left._zod.run({value:Q,issues:[]},W),D=w.right._zod.run({value:Q,issues:[]},W);if(G instanceof Promise||D instanceof Promise)return Promise.all([G,D]).then(([Y,H])=>{return W9($,Y,H)});return W9($,G,D)}});function J6(b,w){if(b===w)return{valid:!0,data:b};if(b instanceof Date&&w instanceof Date&&+b===+w)return{valid:!0,data:b};if(Bw(b)&&Bw(w)){let $=Object.keys(w),W=Object.keys(b).filter((G)=>$.indexOf(G)!==-1),Q={...b,...w};for(let G of W){let D=J6(b[G],w[G]);if(!D.valid)return{valid:!1,mergeErrorPath:[G,...D.mergeErrorPath]};Q[G]=D.data}return{valid:!0,data:Q}}if(Array.isArray(b)&&Array.isArray(w)){if(b.length!==w.length)return{valid:!1,mergeErrorPath:[]};let $=[];for(let W=0;W<b.length;W++){let Q=b[W],G=w[W],D=J6(Q,G);if(!D.valid)return{valid:!1,mergeErrorPath:[W,...D.mergeErrorPath]};$.push(D.data)}return{valid:!0,data:$}}return{valid:!1,mergeErrorPath:[]}}function W9(b,w,$){if(w.issues.length)b.issues.push(...w.issues);if($.issues.length)b.issues.push(...$.issues);if(Pw(b))return b;let W=J6(w.value,$.value);if(!W.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(W.mergeErrorPath)}`);return b.value=W.data,b}var i9=U("$ZodRecord",(b,w)=>{e.init(b,w),b._zod.parse=($,W)=>{let Q=$.value;if(!Bw(Q))return $.issues.push({expected:"record",code:"invalid_type",input:Q,inst:b}),$;let G=[];if(w.keyType._zod.values){let D=w.keyType._zod.values;$.value={};for(let Y of D)if(typeof Y==="string"||typeof Y==="number"||typeof Y==="symbol"){let H=w.valueType._zod.run({value:Q[Y],issues:[]},W);if(H instanceof Promise)G.push(H.then((J)=>{if(J.issues.length)$.issues.push(...ww(Y,J.issues));$.value[Y]=J.value}));else{if(H.issues.length)$.issues.push(...ww(Y,H.issues));$.value[Y]=H.value}}let X;for(let Y in Q)if(!D.has(Y))X=X??[],X.push(Y);if(X&&X.length>0)$.issues.push({code:"unrecognized_keys",input:Q,inst:b,keys:X})}else{$.value={};for(let D of Reflect.ownKeys(Q)){if(D==="__proto__")continue;let X=w.keyType._zod.run({value:D,issues:[]},W);if(X instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(X.issues.length){$.issues.push({code:"invalid_key",origin:"record",issues:X.issues.map((H)=>yb(H,W,Rb())),input:D,path:[D],inst:b}),$.value[X.value]=X.value;continue}let Y=w.valueType._zod.run({value:Q[D],issues:[]},W);if(Y instanceof Promise)G.push(Y.then((H)=>{if(H.issues.length)$.issues.push(...ww(D,H.issues));$.value[X.value]=H.value}));else{if(Y.issues.length)$.issues.push(...ww(D,Y.issues));$.value[X.value]=Y.value}}}if(G.length)return Promise.all(G).then(()=>$);return $}});var l9=U("$ZodEnum",(b,w)=>{e.init(b,w);let $=s$(w.entries),W=new Set($);b._zod.values=W,b._zod.pattern=new RegExp(`^(${$.filter((Q)=>w6.has(typeof Q)).map((Q)=>typeof Q==="string"?bw(Q):Q.toString()).join("|")})$`),b._zod.parse=(Q,G)=>{let D=Q.value;if(W.has(D))return Q;return Q.issues.push({code:"invalid_value",values:$,input:D,inst:b}),Q}}),p9=U("$ZodLiteral",(b,w)=>{if(e.init(b,w),w.values.length===0)throw Error("Cannot create literal schema with no valid values");b._zod.values=new Set(w.values),b._zod.pattern=new RegExp(`^(${w.values.map(($)=>typeof $==="string"?bw($):$?bw($.toString()):String($)).join("|")})$`),b._zod.parse=($,W)=>{let Q=$.value;if(b._zod.values.has(Q))return $;return $.issues.push({code:"invalid_value",values:w.values,input:Q,inst:b}),$}});var o9=U("$ZodTransform",(b,w)=>{e.init(b,w),b._zod.parse=($,W)=>{if(W.direction==="backward")throw new A1(b.constructor.name);let Q=w.transform($.value,$);if(W.async)return(Q instanceof Promise?Q:Promise.resolve(Q)).then((D)=>{return $.value=D,$});if(Q instanceof Promise)throw new ab;return $.value=Q,$}});function Q9(b,w){if(b.issues.length&&w===void 0)return{issues:[],value:void 0};return b}var d9=U("$ZodOptional",(b,w)=>{e.init(b,w),b._zod.optin="optional",b._zod.optout="optional",d(b._zod,"values",()=>{return w.innerType._zod.values?new Set([...w.innerType._zod.values,void 0]):void 0}),d(b._zod,"pattern",()=>{let $=w.innerType._zod.pattern;return $?new RegExp(`^(${L1($.source)})?$`):void 0}),b._zod.parse=($,W)=>{if(w.innerType._zod.optin==="optional"){let Q=w.innerType._zod.run($,W);if(Q instanceof Promise)return Q.then((G)=>Q9(G,$.value));return Q9(Q,$.value)}if($.value===void 0)return $;return w.innerType._zod.run($,W)}}),t9=U("$ZodNullable",(b,w)=>{e.init(b,w),d(b._zod,"optin",()=>w.innerType._zod.optin),d(b._zod,"optout",()=>w.innerType._zod.optout),d(b._zod,"pattern",()=>{let $=w.innerType._zod.pattern;return $?new RegExp(`^(${L1($.source)}|null)$`):void 0}),d(b._zod,"values",()=>{return w.innerType._zod.values?new Set([...w.innerType._zod.values,null]):void 0}),b._zod.parse=($,W)=>{if($.value===null)return $;return w.innerType._zod.run($,W)}}),r9=U("$ZodDefault",(b,w)=>{e.init(b,w),b._zod.optin="optional",d(b._zod,"values",()=>w.innerType._zod.values),b._zod.parse=($,W)=>{if(W.direction==="backward")return w.innerType._zod.run($,W);if($.value===void 0)return $.value=w.defaultValue,$;let Q=w.innerType._zod.run($,W);if(Q instanceof Promise)return Q.then((G)=>G9(G,w));return G9(Q,w)}});function G9(b,w){if(b.value===void 0)b.value=w.defaultValue;return b}var e9=U("$ZodPrefault",(b,w)=>{e.init(b,w),b._zod.optin="optional",d(b._zod,"values",()=>w.innerType._zod.values),b._zod.parse=($,W)=>{if(W.direction==="backward")return w.innerType._zod.run($,W);if($.value===void 0)$.value=w.defaultValue;return w.innerType._zod.run($,W)}}),s9=U("$ZodNonOptional",(b,w)=>{e.init(b,w),d(b._zod,"values",()=>{let $=w.innerType._zod.values;return $?new Set([...$].filter((W)=>W!==void 0)):void 0}),b._zod.parse=($,W)=>{let Q=w.innerType._zod.run($,W);if(Q instanceof Promise)return Q.then((G)=>D9(G,b));return D9(Q,b)}});function D9(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 a9=U("$ZodCatch",(b,w)=>{e.init(b,w),d(b._zod,"optin",()=>w.innerType._zod.optin),d(b._zod,"optout",()=>w.innerType._zod.optout),d(b._zod,"values",()=>w.innerType._zod.values),b._zod.parse=($,W)=>{if(W.direction==="backward")return w.innerType._zod.run($,W);let Q=w.innerType._zod.run($,W);if(Q instanceof Promise)return Q.then((G)=>{if($.value=G.value,G.issues.length)$.value=w.catchValue({...$,error:{issues:G.issues.map((D)=>yb(D,W,Rb()))},input:$.value}),$.issues=[];return $});if($.value=Q.value,Q.issues.length)$.value=w.catchValue({...$,error:{issues:Q.issues.map((G)=>yb(G,W,Rb()))},input:$.value}),$.issues=[];return $}});var b8=U("$ZodPipe",(b,w)=>{e.init(b,w),d(b._zod,"values",()=>w.in._zod.values),d(b._zod,"optin",()=>w.in._zod.optin),d(b._zod,"optout",()=>w.out._zod.optout),d(b._zod,"propValues",()=>w.in._zod.propValues),b._zod.parse=($,W)=>{if(W.direction==="backward"){let G=w.out._zod.run($,W);if(G instanceof Promise)return G.then((D)=>Z0(D,w.in,W));return Z0(G,w.in,W)}let Q=w.in._zod.run($,W);if(Q instanceof Promise)return Q.then((G)=>Z0(G,w.out,W));return Z0(Q,w.out,W)}});function Z0(b,w,$){if(b.issues.length)return b.aborted=!0,b;return w._zod.run({value:b.value,issues:b.issues},$)}var w8=U("$ZodReadonly",(b,w)=>{e.init(b,w),d(b._zod,"propValues",()=>w.innerType._zod.propValues),d(b._zod,"values",()=>w.innerType._zod.values),d(b._zod,"optin",()=>w.innerType._zod.optin),d(b._zod,"optout",()=>w.innerType._zod.optout),b._zod.parse=($,W)=>{if(W.direction==="backward")return w.innerType._zod.run($,W);let Q=w.innerType._zod.run($,W);if(Q instanceof Promise)return Q.then(X9);return X9(Q)}});function X9(b){return b.value=Object.freeze(b.value),b}var $8=U("$ZodCustom",(b,w)=>{Hb.init(b,w),e.init(b,w),b._zod.parse=($,W)=>{return $},b._zod.check=($)=>{let W=$.value,Q=w.fn(W);if(Q instanceof Promise)return Q.then((G)=>Y9(G,$,W,b));Y9(Q,$,W,b);return}});function Y9(b,w,$,W){if(!b){let Q={code:"custom",input:$,inst:W,path:[...W._zod.def.path??[]],continue:!W._zod.def.abort};if(W._zod.def.params)Q.params=W._zod.def.params;w.issues.push(cw(Q))}}var x7=(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},y7=()=>{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 ${x7(W.input)}`;case"invalid_value":if(W.values.length===1)return`Invalid input: expected ${B0(W.values[0])}`;return`Invalid option: expected one of ${q0(W.values,"|")}`;case"too_big":{let Q=W.inclusive?"<=":"<",G=w(W.origin);if(G)return`Too big: expected ${W.origin??"value"} to have ${Q}${W.maximum.toString()} ${G.unit??"elements"}`;return`Too big: expected ${W.origin??"value"} to be ${Q}${W.maximum.toString()}`}case"too_small":{let Q=W.inclusive?">=":">",G=w(W.origin);if(G)return`Too small: expected ${W.origin} to have ${Q}${W.minimum.toString()} ${G.unit}`;return`Too small: expected ${W.origin} to be ${Q}${W.minimum.toString()}`}case"invalid_format":{let Q=W;if(Q.format==="starts_with")return`Invalid string: must start with "${Q.prefix}"`;if(Q.format==="ends_with")return`Invalid string: must end with "${Q.suffix}"`;if(Q.format==="includes")return`Invalid string: must include "${Q.includes}"`;if(Q.format==="regex")return`Invalid string: must match pattern ${Q.pattern}`;return`Invalid ${$[Q.format]??W.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${W.divisor}`;case"unrecognized_keys":return`Unrecognized key${W.keys.length>1?"s":""}: ${q0(W.keys,", ")}`;case"invalid_key":return`Invalid key in ${W.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${W.origin}`;default:return"Invalid input"}}};function O6(){return{localeError:y7()}}var bI=Symbol("ZodOutput"),wI=Symbol("ZodInput");class W8{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 h7(){return new W8}var M1=h7();function Q8(b,w){return new b({type:"string",..._(w)})}function G8(b,w){return new b({type:"string",format:"email",check:"string_format",abort:!1,..._(w)})}function q6(b,w){return new b({type:"string",format:"guid",check:"string_format",abort:!1,..._(w)})}function D8(b,w){return new b({type:"string",format:"uuid",check:"string_format",abort:!1,..._(w)})}function X8(b,w){return new b({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",..._(w)})}function Y8(b,w){return new b({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",..._(w)})}function H8(b,w){return new b({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",..._(w)})}function J8(b,w){return new b({type:"string",format:"url",check:"string_format",abort:!1,..._(w)})}function z8(b,w){return new b({type:"string",format:"emoji",check:"string_format",abort:!1,..._(w)})}function A8(b,w){return new b({type:"string",format:"nanoid",check:"string_format",abort:!1,..._(w)})}function O8(b,w){return new b({type:"string",format:"cuid",check:"string_format",abort:!1,..._(w)})}function q8(b,w){return new b({type:"string",format:"cuid2",check:"string_format",abort:!1,..._(w)})}function L8(b,w){return new b({type:"string",format:"ulid",check:"string_format",abort:!1,..._(w)})}function U8(b,w){return new b({type:"string",format:"xid",check:"string_format",abort:!1,..._(w)})}function B8(b,w){return new b({type:"string",format:"ksuid",check:"string_format",abort:!1,..._(w)})}function P8(b,w){return new b({type:"string",format:"ipv4",check:"string_format",abort:!1,..._(w)})}function F8(b,w){return new b({type:"string",format:"ipv6",check:"string_format",abort:!1,..._(w)})}function K8(b,w){return new b({type:"string",format:"cidrv4",check:"string_format",abort:!1,..._(w)})}function M8(b,w){return new b({type:"string",format:"cidrv6",check:"string_format",abort:!1,..._(w)})}function I8(b,w){return new b({type:"string",format:"base64",check:"string_format",abort:!1,..._(w)})}function Z8(b,w){return new b({type:"string",format:"base64url",check:"string_format",abort:!1,..._(w)})}function j8(b,w){return new b({type:"string",format:"e164",check:"string_format",abort:!1,..._(w)})}function V8(b,w){return new b({type:"string",format:"jwt",check:"string_format",abort:!1,..._(w)})}function N8(b,w){return new b({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,..._(w)})}function T8(b,w){return new b({type:"string",format:"date",check:"string_format",..._(w)})}function E8(b,w){return new b({type:"string",format:"time",check:"string_format",precision:null,..._(w)})}function _8(b,w){return new b({type:"string",format:"duration",check:"string_format",..._(w)})}function S8(b,w){return new b({type:"number",checks:[],..._(w)})}function R8(b,w){return new b({type:"number",check:"number_format",abort:!1,format:"safeint",..._(w)})}function v8(b,w){return new b({type:"boolean",..._(w)})}function k8(b,w){return new b({type:"null",..._(w)})}function C8(b){return new b({type:"unknown"})}function u8(b,w){return new b({type:"never",..._(w)})}function N0(b,w){return new X6({check:"less_than",..._(w),value:b,inclusive:!1})}function I1(b,w){return new X6({check:"less_than",..._(w),value:b,inclusive:!0})}function T0(b,w){return new Y6({check:"greater_than",..._(w),value:b,inclusive:!1})}function Z1(b,w){return new Y6({check:"greater_than",..._(w),value:b,inclusive:!0})}function E0(b,w){return new nQ({check:"multiple_of",..._(w),value:b})}function _0(b,w){return new mQ({check:"max_length",..._(w),maximum:b})}function nw(b,w){return new iQ({check:"min_length",..._(w),minimum:b})}function S0(b,w){return new lQ({check:"length_equals",..._(w),length:b})}function L6(b,w){return new pQ({check:"string_format",format:"regex",..._(w),pattern:b})}function U6(b){return new oQ({check:"string_format",format:"lowercase",..._(b)})}function B6(b){return new dQ({check:"string_format",format:"uppercase",..._(b)})}function P6(b,w){return new tQ({check:"string_format",format:"includes",..._(w),includes:b})}function F6(b,w){return new rQ({check:"string_format",format:"starts_with",..._(w),prefix:b})}function K6(b,w){return new eQ({check:"string_format",format:"ends_with",..._(w),suffix:b})}function Rw(b){return new sQ({check:"overwrite",tx:b})}function M6(b){return Rw((w)=>w.normalize(b))}function I6(){return Rw((b)=>b.trim())}function Z6(){return Rw((b)=>b.toLowerCase())}function j6(){return Rw((b)=>b.toUpperCase())}function x8(b,w,$){return new b({type:"array",element:w,..._($)})}function y8(b,w,$){let W=_($);return W.abort??(W.abort=!0),new b({type:"custom",check:"custom",fn:w,...W})}function h8(b,w,$){return new b({type:"custom",check:"custom",fn:w,..._($)})}function f8(b){let w=f7(($)=>{return $.addIssue=(W)=>{if(typeof W==="string")$.issues.push(cw(W,$.value,w._zod.def));else{let Q=W;if(Q.fatal)Q.continue=!1;Q.code??(Q.code="custom"),Q.input??(Q.input=$.value),Q.inst??(Q.inst=w),Q.continue??(Q.continue=!w._zod.def.abort),$.issues.push(cw(Q))}},b($.value,$)});return w}function f7(b,w){let $=new Hb({check:"custom",..._(w)});return $._zod.check=b,$}function gw(b){return!!b._zod}function Fw(b,w){if(gw(b))return P1(b,w);return b.safeParse(w)}function R0(b){if(!b)return;let w;if(gw(b))w=b._zod?.def?.shape;else w=b.shape;if(!w)return;if(typeof w==="function")try{return w()}catch{return}return w}function c8(b){if(gw(b)){let G=b._zod?.def;if(G){if(G.value!==void 0)return G.value;if(Array.isArray(G.values)&&G.values.length>0)return G.values[0]}}let $=b._def;if($){if($.value!==void 0)return $.value;if(Array.isArray($.values)&&$.values.length>0)return $.values[0]}let W=b.value;if(W!==void 0)return W;return}var V1={};xW(V1,{time:()=>T6,duration:()=>E6,datetime:()=>V6,date:()=>N6,ZodISOTime:()=>m8,ZodISODuration:()=>i8,ZodISODateTime:()=>n8,ZodISODate:()=>g8});var n8=U("ZodISODateTime",(b,w)=>{K9.init(b,w),bb.init(b,w)});function V6(b){return N8(n8,b)}var g8=U("ZodISODate",(b,w)=>{M9.init(b,w),bb.init(b,w)});function N6(b){return T8(g8,b)}var m8=U("ZodISOTime",(b,w)=>{I9.init(b,w),bb.init(b,w)});function T6(b){return E8(m8,b)}var i8=U("ZodISODuration",(b,w)=>{Z9.init(b,w),bb.init(b,w)});function E6(b){return _8(i8,b)}var l8=(b,w)=>{P0.init(b,w),b.name="ZodError",Object.defineProperties(b,{format:{value:($)=>$Q(b,$)},flatten:{value:($)=>wQ(b,$)},addIssue:{value:($)=>{b.issues.push($),b.message=JSON.stringify(b.issues,hw,2)}},addIssues:{value:($)=>{b.issues.push(...$),b.message=JSON.stringify(b.issues,hw,2)}},isEmpty:{get(){return b.issues.length===0}}})},cI=U("ZodError",l8),Tb=U("ZodError",l8,{Parent:Error});var p8=F0(Tb),o8=K0(Tb),d8=B1(Tb),t8=F1(Tb),r8=WQ(Tb),e8=QQ(Tb),s8=GQ(Tb),a8=DQ(Tb),bG=XQ(Tb),wG=YQ(Tb),$G=HQ(Tb),WG=JQ(Tb);var Qb=U("ZodType",(b,w)=>{return e.init(b,w),b.def=w,b.type=w.type,Object.defineProperty(b,"_def",{value:w}),b.check=(...$)=>{return b.clone(m.mergeDefs(w,{checks:[...w.checks??[],...$.map((W)=>typeof W==="function"?{_zod:{check:W,def:{check:"custom"},onattach:[]}}:W)]}))},b.clone=($,W)=>xb(b,$,W),b.brand=()=>b,b.register=($,W)=>{return $.add(b,W),b},b.parse=($,W)=>p8(b,$,W,{callee:b.parse}),b.safeParse=($,W)=>d8(b,$,W),b.parseAsync=async($,W)=>o8(b,$,W,{callee:b.parseAsync}),b.safeParseAsync=async($,W)=>t8(b,$,W),b.spa=b.safeParseAsync,b.encode=($,W)=>r8(b,$,W),b.decode=($,W)=>e8(b,$,W),b.encodeAsync=async($,W)=>s8(b,$,W),b.decodeAsync=async($,W)=>a8(b,$,W),b.safeEncode=($,W)=>bG(b,$,W),b.safeDecode=($,W)=>wG(b,$,W),b.safeEncodeAsync=async($,W)=>$G(b,$,W),b.safeDecodeAsync=async($,W)=>WG(b,$,W),b.refine=($,W)=>b.check(uA($,W)),b.superRefine=($)=>b.check(xA($)),b.overwrite=($)=>b.check(Rw($)),b.optional=()=>Wb(b),b.nullable=()=>DG(b),b.nullish=()=>Wb(DG(b)),b.nonoptional=($)=>_A(b,$),b.array=()=>f(b),b.or=($)=>r([b,$]),b.and=($)=>k0(b,$),b.transform=($)=>S6(b,zG($)),b.default=($)=>NA(b,$),b.prefault=($)=>EA(b,$),b.catch=($)=>RA(b,$),b.pipe=($)=>S6(b,$),b.readonly=()=>CA(b),b.describe=($)=>{let W=b.clone();return M1.add(W,{description:$}),W},Object.defineProperty(b,"description",{get(){return M1.get(b)?.description},configurable:!0}),b.meta=(...$)=>{if($.length===0)return M1.get(b);let W=b.clone();return M1.add(W,$[0]),W},b.isOptional=()=>b.safeParse(void 0).success,b.isNullable=()=>b.safeParse(null).success,b}),XG=U("_ZodString",(b,w)=>{V0.init(b,w),Qb.init(b,w);let $=b._zod.bag;b.format=$.format??null,b.minLength=$.minimum??null,b.maxLength=$.maximum??null,b.regex=(...W)=>b.check(L6(...W)),b.includes=(...W)=>b.check(P6(...W)),b.startsWith=(...W)=>b.check(F6(...W)),b.endsWith=(...W)=>b.check(K6(...W)),b.min=(...W)=>b.check(nw(...W)),b.max=(...W)=>b.check(_0(...W)),b.length=(...W)=>b.check(S0(...W)),b.nonempty=(...W)=>b.check(nw(1,...W)),b.lowercase=(W)=>b.check(U6(W)),b.uppercase=(W)=>b.check(B6(W)),b.trim=()=>b.check(I6()),b.normalize=(...W)=>b.check(M6(...W)),b.toLowerCase=()=>b.check(Z6()),b.toUpperCase=()=>b.check(j6())}),d7=U("ZodString",(b,w)=>{V0.init(b,w),XG.init(b,w),b.email=($)=>b.check(G8(t7,$)),b.url=($)=>b.check(J8(r7,$)),b.jwt=($)=>b.check(V8(zA,$)),b.emoji=($)=>b.check(z8(e7,$)),b.guid=($)=>b.check(q6(QG,$)),b.uuid=($)=>b.check(D8(v0,$)),b.uuidv4=($)=>b.check(X8(v0,$)),b.uuidv6=($)=>b.check(Y8(v0,$)),b.uuidv7=($)=>b.check(H8(v0,$)),b.nanoid=($)=>b.check(A8(s7,$)),b.guid=($)=>b.check(q6(QG,$)),b.cuid=($)=>b.check(O8(a7,$)),b.cuid2=($)=>b.check(q8(bA,$)),b.ulid=($)=>b.check(L8(wA,$)),b.base64=($)=>b.check(I8(YA,$)),b.base64url=($)=>b.check(Z8(HA,$)),b.xid=($)=>b.check(U8($A,$)),b.ksuid=($)=>b.check(B8(WA,$)),b.ipv4=($)=>b.check(P8(QA,$)),b.ipv6=($)=>b.check(F8(GA,$)),b.cidrv4=($)=>b.check(K8(DA,$)),b.cidrv6=($)=>b.check(M8(XA,$)),b.e164=($)=>b.check(j8(JA,$)),b.datetime=($)=>b.check(V6($)),b.date=($)=>b.check(N6($)),b.time=($)=>b.check(T6($)),b.duration=($)=>b.check(E6($))});function L(b){return Q8(d7,b)}var bb=U("ZodStringFormat",(b,w)=>{s.init(b,w),XG.init(b,w)}),t7=U("ZodEmail",(b,w)=>{z9.init(b,w),bb.init(b,w)});var QG=U("ZodGUID",(b,w)=>{H9.init(b,w),bb.init(b,w)});var v0=U("ZodUUID",(b,w)=>{J9.init(b,w),bb.init(b,w)});var r7=U("ZodURL",(b,w)=>{A9.init(b,w),bb.init(b,w)});var e7=U("ZodEmoji",(b,w)=>{O9.init(b,w),bb.init(b,w)});var s7=U("ZodNanoID",(b,w)=>{q9.init(b,w),bb.init(b,w)});var a7=U("ZodCUID",(b,w)=>{L9.init(b,w),bb.init(b,w)});var bA=U("ZodCUID2",(b,w)=>{U9.init(b,w),bb.init(b,w)});var wA=U("ZodULID",(b,w)=>{B9.init(b,w),bb.init(b,w)});var $A=U("ZodXID",(b,w)=>{P9.init(b,w),bb.init(b,w)});var WA=U("ZodKSUID",(b,w)=>{F9.init(b,w),bb.init(b,w)});var QA=U("ZodIPv4",(b,w)=>{j9.init(b,w),bb.init(b,w)});var GA=U("ZodIPv6",(b,w)=>{V9.init(b,w),bb.init(b,w)});var DA=U("ZodCIDRv4",(b,w)=>{N9.init(b,w),bb.init(b,w)});var XA=U("ZodCIDRv6",(b,w)=>{T9.init(b,w),bb.init(b,w)});var YA=U("ZodBase64",(b,w)=>{_9.init(b,w),bb.init(b,w)});var HA=U("ZodBase64URL",(b,w)=>{S9.init(b,w),bb.init(b,w)});var JA=U("ZodE164",(b,w)=>{R9.init(b,w),bb.init(b,w)});var zA=U("ZodJWT",(b,w)=>{v9.init(b,w),bb.init(b,w)});var YG=U("ZodNumber",(b,w)=>{z6.init(b,w),Qb.init(b,w),b.gt=(W,Q)=>b.check(T0(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(N0(W,Q)),b.lte=(W,Q)=>b.check(I1(W,Q)),b.max=(W,Q)=>b.check(I1(W,Q)),b.int=(W)=>b.check(GG(W)),b.safe=(W)=>b.check(GG(W)),b.positive=(W)=>b.check(T0(0,W)),b.nonnegative=(W)=>b.check(Z1(0,W)),b.negative=(W)=>b.check(N0(0,W)),b.nonpositive=(W)=>b.check(I1(0,W)),b.multipleOf=(W,Q)=>b.check(E0(W,Q)),b.step=(W,Q)=>b.check(E0(W,Q)),b.finite=()=>b;let $=b._zod.bag;b.minValue=Math.max($.minimum??Number.NEGATIVE_INFINITY,$.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,b.maxValue=Math.min($.maximum??Number.POSITIVE_INFINITY,$.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,b.isInt=($.format??"").includes("int")||Number.isSafeInteger($.multipleOf??0.5),b.isFinite=!0,b.format=$.format??null});function p(b){return S8(YG,b)}var AA=U("ZodNumberFormat",(b,w)=>{k9.init(b,w),YG.init(b,w)});function GG(b){return R8(AA,b)}var OA=U("ZodBoolean",(b,w)=>{C9.init(b,w),Qb.init(b,w)});function Yb(b){return v8(OA,b)}var qA=U("ZodNull",(b,w)=>{u9.init(b,w),Qb.init(b,w)});function R6(b){return k8(qA,b)}var LA=U("ZodUnknown",(b,w)=>{x9.init(b,w),Qb.init(b,w)});function wb(){return C8(LA)}var UA=U("ZodNever",(b,w)=>{y9.init(b,w),Qb.init(b,w)});function BA(b){return u8(UA,b)}var PA=U("ZodArray",(b,w)=>{h9.init(b,w),Qb.init(b,w),b.element=w.element,b.min=($,W)=>b.check(nw($,W)),b.nonempty=($)=>b.check(nw(1,$)),b.max=($,W)=>b.check(_0($,W)),b.length=($,W)=>b.check(S0($,W)),b.unwrap=()=>b.element});function f(b,w){return x8(PA,b,w)}var HG=U("ZodObject",(b,w)=>{n9.init(b,w),Qb.init(b,w),m.defineLazy(b,"shape",()=>{return w.shape}),b.keyof=()=>Mb(Object.keys(b._zod.def.shape)),b.catchall=($)=>b.clone({...b._zod.def,catchall:$}),b.passthrough=()=>b.clone({...b._zod.def,catchall:wb()}),b.loose=()=>b.clone({...b._zod.def,catchall:wb()}),b.strict=()=>b.clone({...b._zod.def,catchall:BA()}),b.strip=()=>b.clone({...b._zod.def,catchall:void 0}),b.extend=($)=>{return m.extend(b,$)},b.safeExtend=($)=>{return m.safeExtend(b,$)},b.merge=($)=>m.merge(b,$),b.pick=($)=>m.pick(b,$),b.omit=($)=>m.omit(b,$),b.partial=(...$)=>m.partial(AG,b,$[0]),b.required=(...$)=>m.required(OG,b,$[0])});function V(b,w){let $={type:"object",shape:b??{},...m.normalizeParams(w)};return new HG($)}function Bb(b,w){return new HG({type:"object",shape:b,catchall:wb(),...m.normalizeParams(w)})}var JG=U("ZodUnion",(b,w)=>{A6.init(b,w),Qb.init(b,w),b.options=w.options});function r(b,w){return new JG({type:"union",options:b,...m.normalizeParams(w)})}var FA=U("ZodDiscriminatedUnion",(b,w)=>{JG.init(b,w),g9.init(b,w)});function v6(b,w,$){return new FA({type:"union",options:w,discriminator:b,...m.normalizeParams($)})}var KA=U("ZodIntersection",(b,w)=>{m9.init(b,w),Qb.init(b,w)});function k0(b,w){return new KA({type:"intersection",left:b,right:w})}var MA=U("ZodRecord",(b,w)=>{i9.init(b,w),Qb.init(b,w),b.keyType=w.keyType,b.valueType=w.valueType});function $b(b,w,$){return new MA({type:"record",keyType:b,valueType:w,...m.normalizeParams($)})}var _6=U("ZodEnum",(b,w)=>{l9.init(b,w),Qb.init(b,w),b.enum=w.entries,b.options=Object.values(w.entries);let $=new Set(Object.keys(w.entries));b.extract=(W,Q)=>{let G={};for(let D of W)if($.has(D))G[D]=w.entries[D];else throw Error(`Key ${D} not found in enum`);return new _6({...w,checks:[],...m.normalizeParams(Q),entries:G})},b.exclude=(W,Q)=>{let G={...w.entries};for(let D of W)if($.has(D))delete G[D];else throw Error(`Key ${D} not found in enum`);return new _6({...w,checks:[],...m.normalizeParams(Q),entries:G})}});function Mb(b,w){let $=Array.isArray(b)?Object.fromEntries(b.map((W)=>[W,W])):b;return new _6({type:"enum",entries:$,...m.normalizeParams(w)})}var IA=U("ZodLiteral",(b,w)=>{p9.init(b,w),Qb.init(b,w),b.values=new Set(w.values),Object.defineProperty(b,"value",{get(){if(w.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return w.values[0]}})});function T(b,w){return new IA({type:"literal",values:Array.isArray(b)?b:[b],...m.normalizeParams(w)})}var ZA=U("ZodTransform",(b,w)=>{o9.init(b,w),Qb.init(b,w),b._zod.parse=($,W)=>{if(W.direction==="backward")throw new A1(b.constructor.name);$.addIssue=(G)=>{if(typeof G==="string")$.issues.push(m.issue(G,$.value,w));else{let D=G;if(D.fatal)D.continue=!1;D.code??(D.code="custom"),D.input??(D.input=$.value),D.inst??(D.inst=b),$.issues.push(m.issue(D))}};let Q=w.transform($.value,$);if(Q instanceof Promise)return Q.then((G)=>{return $.value=G,$});return $.value=Q,$}});function zG(b){return new ZA({type:"transform",transform:b})}var AG=U("ZodOptional",(b,w)=>{d9.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType});function Wb(b){return new AG({type:"optional",innerType:b})}var jA=U("ZodNullable",(b,w)=>{t9.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType});function DG(b){return new jA({type:"nullable",innerType:b})}var VA=U("ZodDefault",(b,w)=>{r9.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType,b.removeDefault=b.unwrap});function NA(b,w){return new VA({type:"default",innerType:b,get defaultValue(){return typeof w==="function"?w():m.shallowClone(w)}})}var TA=U("ZodPrefault",(b,w)=>{e9.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType});function EA(b,w){return new TA({type:"prefault",innerType:b,get defaultValue(){return typeof w==="function"?w():m.shallowClone(w)}})}var OG=U("ZodNonOptional",(b,w)=>{s9.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType});function _A(b,w){return new OG({type:"nonoptional",innerType:b,...m.normalizeParams(w)})}var SA=U("ZodCatch",(b,w)=>{a9.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType,b.removeCatch=b.unwrap});function RA(b,w){return new SA({type:"catch",innerType:b,catchValue:typeof w==="function"?w:()=>w})}var vA=U("ZodPipe",(b,w)=>{b8.init(b,w),Qb.init(b,w),b.in=w.in,b.out=w.out});function S6(b,w){return new vA({type:"pipe",in:b,out:w})}var kA=U("ZodReadonly",(b,w)=>{w8.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType});function CA(b){return new kA({type:"readonly",innerType:b})}var qG=U("ZodCustom",(b,w)=>{$8.init(b,w),Qb.init(b,w)});function LG(b,w){return y8(qG,b??(()=>!0),w)}function uA(b,w={}){return h8(qG,b,w)}function xA(b){return f8(b)}function k6(b,w){return S6(zG(b),w)}Rb(O6());var C6="2025-11-25";var UG=[C6,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Kw="io.modelcontextprotocol/related-task",u0="2.0",Jb=LG((b)=>b!==null&&(typeof b==="object"||typeof b==="function")),BG=r([L(),p().int()]),PG=L(),uZ=Bb({ttl:r([p(),R6()]).optional(),pollInterval:p().optional()}),yA=V({ttl:p().optional()}),hA=V({taskId:L()}),u6=Bb({progressToken:BG.optional(),[Kw]:hA.optional()}),Eb=V({_meta:u6.optional()}),N1=Eb.extend({task:yA.optional()}),FG=(b)=>N1.safeParse(b).success,zb=V({method:L(),params:Eb.loose().optional()}),vb=V({_meta:u6.optional()}),kb=V({method:L(),params:vb.loose().optional()}),Ab=Bb({_meta:u6.optional()}),x0=r([L(),p().int()]),KG=V({jsonrpc:T(u0),id:x0,...zb.shape}).strict(),x6=(b)=>KG.safeParse(b).success,MG=V({jsonrpc:T(u0),...kb.shape}).strict(),IG=(b)=>MG.safeParse(b).success,y6=V({jsonrpc:T(u0),id:x0,result:Ab}).strict(),T1=(b)=>y6.safeParse(b).success;var c;(function(b){b[b.ConnectionClosed=-32000]="ConnectionClosed",b[b.RequestTimeout=-32001]="RequestTimeout",b[b.ParseError=-32700]="ParseError",b[b.InvalidRequest=-32600]="InvalidRequest",b[b.MethodNotFound=-32601]="MethodNotFound",b[b.InvalidParams=-32602]="InvalidParams",b[b.InternalError=-32603]="InternalError",b[b.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(c||(c={}));var h6=V({jsonrpc:T(u0),id:x0.optional(),error:V({code:p().int(),message:L(),data:wb().optional()})}).strict();var ZG=(b)=>h6.safeParse(b).success;var jG=r([KG,MG,y6,h6]),xZ=r([y6,h6]),y0=Ab.strict(),fA=vb.extend({requestId:x0.optional(),reason:L().optional()}),h0=kb.extend({method:T("notifications/cancelled"),params:fA}),cA=V({src:L(),mimeType:L().optional(),sizes:f(L()).optional(),theme:Mb(["light","dark"]).optional()}),E1=V({icons:f(cA).optional()}),mw=V({name:L(),title:L().optional()}),VG=mw.extend({...mw.shape,...E1.shape,version:L(),websiteUrl:L().optional(),description:L().optional()}),nA=k0(V({applyDefaults:Yb().optional()}),$b(L(),wb())),gA=k6((b)=>{if(b&&typeof b==="object"&&!Array.isArray(b)){if(Object.keys(b).length===0)return{form:{}}}return b},k0(V({form:nA.optional(),url:Jb.optional()}),$b(L(),wb()).optional())),mA=Bb({list:Jb.optional(),cancel:Jb.optional(),requests:Bb({sampling:Bb({createMessage:Jb.optional()}).optional(),elicitation:Bb({create:Jb.optional()}).optional()}).optional()}),iA=Bb({list:Jb.optional(),cancel:Jb.optional(),requests:Bb({tools:Bb({call:Jb.optional()}).optional()}).optional()}),lA=V({experimental:$b(L(),Jb).optional(),sampling:V({context:Jb.optional(),tools:Jb.optional()}).optional(),elicitation:gA.optional(),roots:V({listChanged:Yb().optional()}).optional(),tasks:mA.optional()}),pA=Eb.extend({protocolVersion:L(),capabilities:lA,clientInfo:VG}),f6=zb.extend({method:T("initialize"),params:pA});var oA=V({experimental:$b(L(),Jb).optional(),logging:Jb.optional(),completions:Jb.optional(),prompts:V({listChanged:Yb().optional()}).optional(),resources:V({subscribe:Yb().optional(),listChanged:Yb().optional()}).optional(),tools:V({listChanged:Yb().optional()}).optional(),tasks:iA.optional()}),dA=Ab.extend({protocolVersion:L(),capabilities:oA,serverInfo:VG,instructions:L().optional()}),c6=kb.extend({method:T("notifications/initialized"),params:vb.optional()});var f0=zb.extend({method:T("ping"),params:Eb.optional()}),tA=V({progress:p(),total:Wb(p()),message:Wb(L())}),rA=V({...vb.shape,...tA.shape,progressToken:BG}),c0=kb.extend({method:T("notifications/progress"),params:rA}),eA=Eb.extend({cursor:PG.optional()}),_1=zb.extend({params:eA.optional()}),S1=Ab.extend({nextCursor:PG.optional()}),sA=Mb(["working","input_required","completed","failed","cancelled"]),R1=V({taskId:L(),status:sA,ttl:r([p(),R6()]),createdAt:L(),lastUpdatedAt:L(),pollInterval:Wb(p()),statusMessage:Wb(L())}),iw=Ab.extend({task:R1}),aA=vb.merge(R1),v1=kb.extend({method:T("notifications/tasks/status"),params:aA}),n0=zb.extend({method:T("tasks/get"),params:Eb.extend({taskId:L()})}),g0=Ab.merge(R1),m0=zb.extend({method:T("tasks/result"),params:Eb.extend({taskId:L()})}),yZ=Ab.loose(),i0=_1.extend({method:T("tasks/list")}),l0=S1.extend({tasks:f(R1)}),p0=zb.extend({method:T("tasks/cancel"),params:Eb.extend({taskId:L()})}),NG=Ab.merge(R1),TG=V({uri:L(),mimeType:Wb(L()),_meta:$b(L(),wb()).optional()}),EG=TG.extend({text:L()}),n6=L().refine((b)=>{try{return atob(b),!0}catch{return!1}},{message:"Invalid Base64 string"}),_G=TG.extend({blob:n6}),k1=Mb(["user","assistant"]),lw=V({audience:f(k1).optional(),priority:p().min(0).max(1).optional(),lastModified:V1.datetime({offset:!0}).optional()}),SG=V({...mw.shape,...E1.shape,uri:L(),description:Wb(L()),mimeType:Wb(L()),annotations:lw.optional(),_meta:Wb(Bb({}))}),b5=V({...mw.shape,...E1.shape,uriTemplate:L(),description:Wb(L()),mimeType:Wb(L()),annotations:lw.optional(),_meta:Wb(Bb({}))}),g6=_1.extend({method:T("resources/list")}),w5=S1.extend({resources:f(SG)}),$5=_1.extend({method:T("resources/templates/list")}),W5=S1.extend({resourceTemplates:f(b5)}),m6=Eb.extend({uri:L()}),Q5=m6,i6=zb.extend({method:T("resources/read"),params:Q5}),G5=Ab.extend({contents:f(r([EG,_G]))}),D5=kb.extend({method:T("notifications/resources/list_changed"),params:vb.optional()}),X5=m6,Y5=zb.extend({method:T("resources/subscribe"),params:X5}),H5=m6,J5=zb.extend({method:T("resources/unsubscribe"),params:H5}),z5=vb.extend({uri:L()}),A5=kb.extend({method:T("notifications/resources/updated"),params:z5}),O5=V({name:L(),description:Wb(L()),required:Wb(Yb())}),q5=V({...mw.shape,...E1.shape,description:Wb(L()),arguments:Wb(f(O5)),_meta:Wb(Bb({}))}),L5=_1.extend({method:T("prompts/list")}),U5=S1.extend({prompts:f(q5)}),B5=Eb.extend({name:L(),arguments:$b(L(),L()).optional()}),P5=zb.extend({method:T("prompts/get"),params:B5}),l6=V({type:T("text"),text:L(),annotations:lw.optional(),_meta:$b(L(),wb()).optional()}),p6=V({type:T("image"),data:n6,mimeType:L(),annotations:lw.optional(),_meta:$b(L(),wb()).optional()}),o6=V({type:T("audio"),data:n6,mimeType:L(),annotations:lw.optional(),_meta:$b(L(),wb()).optional()}),F5=V({type:T("tool_use"),name:L(),id:L(),input:$b(L(),wb()),_meta:$b(L(),wb()).optional()}),K5=V({type:T("resource"),resource:r([EG,_G]),annotations:lw.optional(),_meta:$b(L(),wb()).optional()}),M5=SG.extend({type:T("resource_link")}),d6=r([l6,p6,o6,M5,K5]),I5=V({role:k1,content:d6}),Z5=Ab.extend({description:L().optional(),messages:f(I5)}),j5=kb.extend({method:T("notifications/prompts/list_changed"),params:vb.optional()}),V5=V({title:L().optional(),readOnlyHint:Yb().optional(),destructiveHint:Yb().optional(),idempotentHint:Yb().optional(),openWorldHint:Yb().optional()}),N5=V({taskSupport:Mb(["required","optional","forbidden"]).optional()}),RG=V({...mw.shape,...E1.shape,description:L().optional(),inputSchema:V({type:T("object"),properties:$b(L(),Jb).optional(),required:f(L()).optional()}).catchall(wb()),outputSchema:V({type:T("object"),properties:$b(L(),Jb).optional(),required:f(L()).optional()}).catchall(wb()).optional(),annotations:V5.optional(),execution:N5.optional(),_meta:$b(L(),wb()).optional()}),t6=_1.extend({method:T("tools/list")}),T5=S1.extend({tools:f(RG)}),o0=Ab.extend({content:f(d6).default([]),structuredContent:$b(L(),wb()).optional(),isError:Yb().optional()}),hZ=o0.or(Ab.extend({toolResult:wb()})),E5=N1.extend({name:L(),arguments:$b(L(),wb()).optional()}),C1=zb.extend({method:T("tools/call"),params:E5}),_5=kb.extend({method:T("notifications/tools/list_changed"),params:vb.optional()}),fZ=V({autoRefresh:Yb().default(!0),debounceMs:p().int().nonnegative().default(300)}),u1=Mb(["debug","info","notice","warning","error","critical","alert","emergency"]),S5=Eb.extend({level:u1}),r6=zb.extend({method:T("logging/setLevel"),params:S5}),R5=vb.extend({level:u1,logger:L().optional(),data:wb()}),v5=kb.extend({method:T("notifications/message"),params:R5}),k5=V({name:L().optional()}),C5=V({hints:f(k5).optional(),costPriority:p().min(0).max(1).optional(),speedPriority:p().min(0).max(1).optional(),intelligencePriority:p().min(0).max(1).optional()}),u5=V({mode:Mb(["auto","required","none"]).optional()}),x5=V({type:T("tool_result"),toolUseId:L().describe("The unique identifier for the corresponding tool call."),content:f(d6).default([]),structuredContent:V({}).loose().optional(),isError:Yb().optional(),_meta:$b(L(),wb()).optional()}),y5=v6("type",[l6,p6,o6]),C0=v6("type",[l6,p6,o6,F5,x5]),h5=V({role:k1,content:r([C0,f(C0)]),_meta:$b(L(),wb()).optional()}),f5=N1.extend({messages:f(h5),modelPreferences:C5.optional(),systemPrompt:L().optional(),includeContext:Mb(["none","thisServer","allServers"]).optional(),temperature:p().optional(),maxTokens:p().int(),stopSequences:f(L()).optional(),metadata:Jb.optional(),tools:f(RG).optional(),toolChoice:u5.optional()}),c5=zb.extend({method:T("sampling/createMessage"),params:f5}),e6=Ab.extend({model:L(),stopReason:Wb(Mb(["endTurn","stopSequence","maxTokens"]).or(L())),role:k1,content:y5}),s6=Ab.extend({model:L(),stopReason:Wb(Mb(["endTurn","stopSequence","maxTokens","toolUse"]).or(L())),role:k1,content:r([C0,f(C0)])}),n5=V({type:T("boolean"),title:L().optional(),description:L().optional(),default:Yb().optional()}),g5=V({type:T("string"),title:L().optional(),description:L().optional(),minLength:p().optional(),maxLength:p().optional(),format:Mb(["email","uri","date","date-time"]).optional(),default:L().optional()}),m5=V({type:Mb(["number","integer"]),title:L().optional(),description:L().optional(),minimum:p().optional(),maximum:p().optional(),default:p().optional()}),i5=V({type:T("string"),title:L().optional(),description:L().optional(),enum:f(L()),default:L().optional()}),l5=V({type:T("string"),title:L().optional(),description:L().optional(),oneOf:f(V({const:L(),title:L()})),default:L().optional()}),p5=V({type:T("string"),title:L().optional(),description:L().optional(),enum:f(L()),enumNames:f(L()).optional(),default:L().optional()}),o5=r([i5,l5]),d5=V({type:T("array"),title:L().optional(),description:L().optional(),minItems:p().optional(),maxItems:p().optional(),items:V({type:T("string"),enum:f(L())}),default:f(L()).optional()}),t5=V({type:T("array"),title:L().optional(),description:L().optional(),minItems:p().optional(),maxItems:p().optional(),items:V({anyOf:f(V({const:L(),title:L()}))}),default:f(L()).optional()}),r5=r([d5,t5]),e5=r([p5,o5,r5]),s5=r([e5,n5,g5,m5]),a5=N1.extend({mode:T("form").optional(),message:L(),requestedSchema:V({type:T("object"),properties:$b(L(),s5),required:f(L()).optional()})}),bO=N1.extend({mode:T("url"),message:L(),elicitationId:L(),url:L().url()}),wO=r([a5,bO]),$O=zb.extend({method:T("elicitation/create"),params:wO}),WO=vb.extend({elicitationId:L()}),QO=kb.extend({method:T("notifications/elicitation/complete"),params:WO}),d0=Ab.extend({action:Mb(["accept","decline","cancel"]),content:k6((b)=>b===null?void 0:b,$b(L(),r([L(),p(),Yb(),f(L())])).optional())}),GO=V({type:T("ref/resource"),uri:L()});var DO=V({type:T("ref/prompt"),name:L()}),XO=Eb.extend({ref:r([DO,GO]),argument:V({name:L(),value:L()}),context:V({arguments:$b(L(),L()).optional()}).optional()}),YO=zb.extend({method:T("completion/complete"),params:XO});var HO=Ab.extend({completion:Bb({values:f(L()).max(100),total:Wb(p().int()),hasMore:Wb(Yb())})}),JO=V({uri:L().startsWith("file://"),name:L().optional(),_meta:$b(L(),wb()).optional()}),zO=zb.extend({method:T("roots/list"),params:Eb.optional()}),a6=Ab.extend({roots:f(JO)}),AO=kb.extend({method:T("notifications/roots/list_changed"),params:vb.optional()}),cZ=r([f0,f6,YO,r6,P5,L5,g6,$5,i6,Y5,J5,C1,t6,n0,m0,i0,p0]),nZ=r([h0,c0,c6,AO,v1]),gZ=r([y0,e6,s6,d0,a6,g0,l0,iw]),mZ=r([f0,c5,$O,zO,n0,m0,i0,p0]),iZ=r([h0,c0,v5,A5,D5,_5,j5,v1,QO]),lZ=r([y0,dA,HO,Z5,U5,w5,W5,G5,o0,T5,g0,l0,iw]);class u extends Error{constructor(b,w,$){super(`MCP error ${b}: ${w}`);this.code=b,this.data=$,this.name="McpError"}static fromError(b,w,$){if(b===c.UrlElicitationRequired&&$){let W=$;if(W.elicitations)return new vG(W.elicitations,w)}return new u(b,w,$)}}class vG extends u{constructor(b,w=`URL elicitation${b.length>1?"s":""} required`){super(c.UrlElicitationRequired,w,{elicitations:b})}get elicitations(){return this.data?.elicitations??[]}}function Mw(b){return b==="completed"||b==="failed"||b==="cancelled"}var OO=Symbol("Let zodToJsonSchema decide on which parser to use");var jj=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function b4(b){let $=R0(b)?.method;if(!$)throw Error("Schema is missing a method literal");let W=c8($);if(typeof W!=="string")throw Error("Schema method literal must be a string");return W}function w4(b,w){let $=Fw(b,w);if(!$.success)throw $.error;return $.data}var FO=60000;class $4{constructor(b){if(this._options=b,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(h0,(w)=>{this._oncancel(w)}),this.setNotificationHandler(c0,(w)=>{this._onprogress(w)}),this.setRequestHandler(f0,(w)=>({})),this._taskStore=b?.taskStore,this._taskMessageQueue=b?.taskMessageQueue,this._taskStore)this.setRequestHandler(n0,async(w,$)=>{let W=await this._taskStore.getTask(w.params.taskId,$.sessionId);if(!W)throw new u(c.InvalidParams,"Failed to retrieve task: Task not found");return{...W}}),this.setRequestHandler(m0,async(w,$)=>{let W=async()=>{let Q=w.params.taskId;if(this._taskMessageQueue){let D;while(D=await this._taskMessageQueue.dequeue(Q,$.sessionId)){if(D.type==="response"||D.type==="error"){let X=D.message,Y=X.id,H=this._requestResolvers.get(Y);if(H)if(this._requestResolvers.delete(Y),D.type==="response")H(X);else{let J=X,z=new u(J.error.code,J.error.message,J.error.data);H(z)}else{let J=D.type==="response"?"Response":"Error";this._onerror(Error(`${J} handler missing for request ${Y}`))}continue}await this._transport?.send(D.message,{relatedRequestId:$.requestId})}}let G=await this._taskStore.getTask(Q,$.sessionId);if(!G)throw new u(c.InvalidParams,`Task not found: ${Q}`);if(!Mw(G.status))return await this._waitForTaskUpdate(Q,$.signal),await W();if(Mw(G.status)){let D=await this._taskStore.getTaskResult(Q,$.sessionId);return this._clearTaskQueue(Q),{...D,_meta:{...D._meta,[Kw]:{taskId:Q}}}}return await W()};return await W()}),this.setRequestHandler(i0,async(w,$)=>{try{let{tasks:W,nextCursor:Q}=await this._taskStore.listTasks(w.params?.cursor,$.sessionId);return{tasks:W,nextCursor:Q,_meta:{}}}catch(W){throw new u(c.InvalidParams,`Failed to list tasks: ${W instanceof Error?W.message:String(W)}`)}}),this.setRequestHandler(p0,async(w,$)=>{try{let W=await this._taskStore.getTask(w.params.taskId,$.sessionId);if(!W)throw new u(c.InvalidParams,`Task not found: ${w.params.taskId}`);if(Mw(W.status))throw new u(c.InvalidParams,`Cannot cancel task in terminal status: ${W.status}`);await this._taskStore.updateTaskStatus(w.params.taskId,"cancelled","Client cancelled task execution.",$.sessionId),this._clearTaskQueue(w.params.taskId);let Q=await this._taskStore.getTask(w.params.taskId,$.sessionId);if(!Q)throw new u(c.InvalidParams,`Task not found after cancellation: ${w.params.taskId}`);return{_meta:{},...Q}}catch(W){if(W instanceof u)throw W;throw new u(c.InvalidRequest,`Failed to cancel task: ${W instanceof Error?W.message:String(W)}`)}})}async _oncancel(b){if(!b.params.requestId)return;this._requestHandlerAbortControllers.get(b.params.requestId)?.abort(b.params.reason)}_setupTimeout(b,w,$,W,Q=!1){this._timeoutInfo.set(b,{timeoutId:setTimeout(W,w),startTime:Date.now(),timeout:w,maxTotalTimeout:$,resetTimeoutOnProgress:Q,onTimeout:W})}_resetTimeout(b){let w=this._timeoutInfo.get(b);if(!w)return!1;let $=Date.now()-w.startTime;if(w.maxTotalTimeout&&$>=w.maxTotalTimeout)throw this._timeoutInfo.delete(b),u.fromError(c.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:w.maxTotalTimeout,totalElapsed:$});return clearTimeout(w.timeoutId),w.timeoutId=setTimeout(w.onTimeout,w.timeout),!0}_cleanupTimeout(b){let w=this._timeoutInfo.get(b);if(w)clearTimeout(w.timeoutId),this._timeoutInfo.delete(b)}async connect(b){this._transport=b;let w=this.transport?.onclose;this._transport.onclose=()=>{w?.(),this._onclose()};let $=this.transport?.onerror;this._transport.onerror=(Q)=>{$?.(Q),this._onerror(Q)};let W=this._transport?.onmessage;this._transport.onmessage=(Q,G)=>{if(W?.(Q,G),T1(Q)||ZG(Q))this._onresponse(Q);else if(x6(Q))this._onrequest(Q,G);else if(IG(Q))this._onnotification(Q);else this._onerror(Error(`Unknown message type: ${JSON.stringify(Q)}`))},await this._transport.start()}_onclose(){let b=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();let w=u.fromError(c.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let $ of b.values())$(w)}_onerror(b){this.onerror?.(b)}_onnotification(b){let w=this._notificationHandlers.get(b.method)??this.fallbackNotificationHandler;if(w===void 0)return;Promise.resolve().then(()=>w(b)).catch(($)=>this._onerror(Error(`Uncaught error in notification handler: ${$}`)))}_onrequest(b,w){let $=this._requestHandlers.get(b.method)??this.fallbackRequestHandler,W=this._transport,Q=b.params?._meta?.[Kw]?.taskId;if($===void 0){let H={jsonrpc:"2.0",id:b.id,error:{code:c.MethodNotFound,message:"Method not found"}};if(Q&&this._taskMessageQueue)this._enqueueTaskMessage(Q,{type:"error",message:H,timestamp:Date.now()},W?.sessionId).catch((J)=>this._onerror(Error(`Failed to enqueue error response: ${J}`)));else W?.send(H).catch((J)=>this._onerror(Error(`Failed to send an error response: ${J}`)));return}let G=new AbortController;this._requestHandlerAbortControllers.set(b.id,G);let D=FG(b.params)?b.params.task:void 0,X=this._taskStore?this.requestTaskStore(b,W?.sessionId):void 0,Y={signal:G.signal,sessionId:W?.sessionId,_meta:b.params?._meta,sendNotification:async(H)=>{let J={relatedRequestId:b.id};if(Q)J.relatedTask={taskId:Q};await this.notification(H,J)},sendRequest:async(H,J,z)=>{let O={...z,relatedRequestId:b.id};if(Q&&!O.relatedTask)O.relatedTask={taskId:Q};let q=O.relatedTask?.taskId??Q;if(q&&X)await X.updateTaskStatus(q,"input_required");return await this.request(H,J,O)},authInfo:w?.authInfo,requestId:b.id,requestInfo:w?.requestInfo,taskId:Q,taskStore:X,taskRequestedTtl:D?.ttl,closeSSEStream:w?.closeSSEStream,closeStandaloneSSEStream:w?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(D)this.assertTaskHandlerCapability(b.method)}).then(()=>$(b,Y)).then(async(H)=>{if(G.signal.aborted)return;let J={result:H,jsonrpc:"2.0",id:b.id};if(Q&&this._taskMessageQueue)await this._enqueueTaskMessage(Q,{type:"response",message:J,timestamp:Date.now()},W?.sessionId);else await W?.send(J)},async(H)=>{if(G.signal.aborted)return;let J={jsonrpc:"2.0",id:b.id,error:{code:Number.isSafeInteger(H.code)?H.code:c.InternalError,message:H.message??"Internal error",...H.data!==void 0&&{data:H.data}}};if(Q&&this._taskMessageQueue)await this._enqueueTaskMessage(Q,{type:"error",message:J,timestamp:Date.now()},W?.sessionId);else await W?.send(J)}).catch((H)=>this._onerror(Error(`Failed to send response: ${H}`))).finally(()=>{this._requestHandlerAbortControllers.delete(b.id)})}_onprogress(b){let{progressToken:w,...$}=b.params,W=Number(w),Q=this._progressHandlers.get(W);if(!Q){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(b)}`));return}let G=this._responseHandlers.get(W),D=this._timeoutInfo.get(W);if(D&&G&&D.resetTimeoutOnProgress)try{this._resetTimeout(W)}catch(X){this._responseHandlers.delete(W),this._progressHandlers.delete(W),this._cleanupTimeout(W),G(X);return}Q($)}_onresponse(b){let w=Number(b.id),$=this._requestResolvers.get(w);if($){if(this._requestResolvers.delete(w),T1(b))$(b);else{let G=new u(b.error.code,b.error.message,b.error.data);$(G)}return}let W=this._responseHandlers.get(w);if(W===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(b)}`));return}this._responseHandlers.delete(w),this._cleanupTimeout(w);let Q=!1;if(T1(b)&&b.result&&typeof b.result==="object"){let G=b.result;if(G.task&&typeof G.task==="object"){let D=G.task;if(typeof D.taskId==="string")Q=!0,this._taskProgressTokens.set(D.taskId,w)}}if(!Q)this._progressHandlers.delete(w);if(T1(b))W(b);else{let G=u.fromError(b.error.code,b.error.message,b.error.data);W(G)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(b,w,$){let{task:W}=$??{};if(!W){try{yield{type:"result",result:await this.request(b,w,$)}}catch(G){yield{type:"error",error:G instanceof u?G:new u(c.InternalError,String(G))}}return}let Q;try{let G=await this.request(b,iw,$);if(G.task)Q=G.task.taskId,yield{type:"taskCreated",task:G.task};else throw new u(c.InternalError,"Task creation did not return a task");while(!0){let D=await this.getTask({taskId:Q},$);if(yield{type:"taskStatus",task:D},Mw(D.status)){if(D.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:Q},w,$)};else if(D.status==="failed")yield{type:"error",error:new u(c.InternalError,`Task ${Q} failed`)};else if(D.status==="cancelled")yield{type:"error",error:new u(c.InternalError,`Task ${Q} was cancelled`)};return}if(D.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:Q},w,$)};return}let X=D.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((Y)=>setTimeout(Y,X)),$?.signal?.throwIfAborted()}}catch(G){yield{type:"error",error:G instanceof u?G:new u(c.InternalError,String(G))}}}request(b,w,$){let{relatedRequestId:W,resumptionToken:Q,onresumptiontoken:G,task:D,relatedTask:X}=$??{};return new Promise((Y,H)=>{let J=(M)=>{H(M)};if(!this._transport){J(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(b.method),D)this.assertTaskCapability(b.method)}catch(M){J(M);return}$?.signal?.throwIfAborted();let z=this._requestMessageId++,O={...b,jsonrpc:"2.0",id:z};if($?.onprogress)this._progressHandlers.set(z,$.onprogress),O.params={...b.params,_meta:{...b.params?._meta||{},progressToken:z}};if(D)O.params={...O.params,task:D};if(X)O.params={...O.params,_meta:{...O.params?._meta||{},[Kw]:X}};let q=(M)=>{this._responseHandlers.delete(z),this._progressHandlers.delete(z),this._cleanupTimeout(z),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:z,reason:String(M)}},{relatedRequestId:W,resumptionToken:Q,onresumptiontoken:G}).catch((S)=>this._onerror(Error(`Failed to send cancellation: ${S}`)));let v=M instanceof u?M:new u(c.RequestTimeout,String(M));H(v)};this._responseHandlers.set(z,(M)=>{if($?.signal?.aborted)return;if(M instanceof Error)return H(M);try{let v=Fw(w,M.result);if(!v.success)H(v.error);else Y(v.data)}catch(v){H(v)}}),$?.signal?.addEventListener("abort",()=>{q($?.signal?.reason)});let B=$?.timeout??FO,K=()=>q(u.fromError(c.RequestTimeout,"Request timed out",{timeout:B}));this._setupTimeout(z,B,$?.maxTotalTimeout,K,$?.resetTimeoutOnProgress??!1);let I=X?.taskId;if(I){let M=(v)=>{let S=this._responseHandlers.get(z);if(S)S(v);else this._onerror(Error(`Response handler missing for side-channeled request ${z}`))};this._requestResolvers.set(z,M),this._enqueueTaskMessage(I,{type:"request",message:O,timestamp:Date.now()}).catch((v)=>{this._cleanupTimeout(z),H(v)})}else this._transport.send(O,{relatedRequestId:W,resumptionToken:Q,onresumptiontoken:G}).catch((M)=>{this._cleanupTimeout(z),H(M)})})}async getTask(b,w){return this.request({method:"tasks/get",params:b},g0,w)}async getTaskResult(b,w,$){return this.request({method:"tasks/result",params:b},w,$)}async listTasks(b,w){return this.request({method:"tasks/list",params:b},l0,w)}async cancelTask(b,w){return this.request({method:"tasks/cancel",params:b},NG,w)}async notification(b,w){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(b.method);let $=w?.relatedTask?.taskId;if($){let D={...b,jsonrpc:"2.0",params:{...b.params,_meta:{...b.params?._meta||{},[Kw]:w.relatedTask}}};await this._enqueueTaskMessage($,{type:"notification",message:D,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(b.method)&&!b.params&&!w?.relatedRequestId&&!w?.relatedTask){if(this._pendingDebouncedNotifications.has(b.method))return;this._pendingDebouncedNotifications.add(b.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(b.method),!this._transport)return;let D={...b,jsonrpc:"2.0"};if(w?.relatedTask)D={...D,params:{...D.params,_meta:{...D.params?._meta||{},[Kw]:w.relatedTask}}};this._transport?.send(D,w).catch((X)=>this._onerror(X))});return}let G={...b,jsonrpc:"2.0"};if(w?.relatedTask)G={...G,params:{...G.params,_meta:{...G.params?._meta||{},[Kw]:w.relatedTask}}};await this._transport.send(G,w)}setRequestHandler(b,w){let $=b4(b);this.assertRequestHandlerCapability($),this._requestHandlers.set($,(W,Q)=>{let G=w4(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 $=b4(b);this._notificationHandlers.set($,(W)=>{let Q=w4(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"&&x6(W.message)){let Q=W.message.id,G=this._requestResolvers.get(Q);if(G)G(new u(c.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(Q);else this._onerror(Error(`Resolver missing for request ${Q} during task ${b} cleanup`))}}}async _waitForTaskUpdate(b,w){let $=this._options?.defaultTaskPollInterval??1000;try{let W=await this._taskStore?.getTask(b);if(W?.pollInterval)$=W.pollInterval}catch{}return new Promise((W,Q)=>{if(w.aborted){Q(new u(c.InvalidRequest,"Request cancelled"));return}let G=setTimeout(W,$);w.addEventListener("abort",()=>{clearTimeout(G),Q(new u(c.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(b,w){let $=this._taskStore;if(!$)throw Error("No task store configured");return{createTask:async(W)=>{if(!b)throw Error("No request provided");return await $.createTask(W,b.id,{method:b.method,params:b.params},w)},getTask:async(W)=>{let Q=await $.getTask(W,w);if(!Q)throw new u(c.InvalidParams,"Failed to retrieve task: Task not found");return Q},storeTaskResult:async(W,Q,G)=>{await $.storeTaskResult(W,Q,G,w);let D=await $.getTask(W,w);if(D){let X=v1.parse({method:"notifications/tasks/status",params:D});if(await this.notification(X),Mw(D.status))this._cleanupTaskProgressHandler(W)}},getTaskResult:(W)=>{return $.getTaskResult(W,w)},updateTaskStatus:async(W,Q,G)=>{let D=await $.getTask(W,w);if(!D)throw new u(c.InvalidParams,`Task "${W}" not found - it may have been cleaned up`);if(Mw(D.status))throw new u(c.InvalidParams,`Cannot update task "${W}" from terminal status "${D.status}" to "${Q}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await $.updateTaskStatus(W,Q,G,w);let X=await $.getTask(W,w);if(X){let Y=v1.parse({method:"notifications/tasks/status",params:X});if(await this.notification(Y),Mw(X.status))this._cleanupTaskProgressHandler(W)}},listTasks:(W)=>{return $.listTasks(W,w)}}}}function kG(b){return b!==null&&typeof b==="object"&&!Array.isArray(b)}function CG(b,w){let $={...b};for(let W in w){let Q=W,G=w[Q];if(G===void 0)continue;let D=$[Q];if(kG(D)&&kG(G))$[Q]={...D,...G};else $[Q]=G}return $}var zJ=uW(r4(),1),AJ=uW(JJ(),1);function EK(){let b=new zJ.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return AJ.default(b),b}class DW{constructor(b){this._ajv=b??EK()}getValidator(b){let w="$id"in b&&typeof b.$id==="string"?this._ajv.getSchema(b.$id)??this._ajv.compile(b):this._ajv.compile(b);return($)=>{if(w($))return{valid:!0,data:$,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(w.errors)}}}}class XW{constructor(b){this._server=b}requestStream(b,w,$){return this._server.requestStream(b,w,$)}async getTask(b,w){return this._server.getTask({taskId:b},w)}async getTaskResult(b,w,$){return this._server.getTaskResult({taskId:b},w,$)}async listTasks(b,w){return this._server.listTasks(b?{cursor:b}:void 0,w)}async cancelTask(b,w){return this._server.cancelTask({taskId:b},w)}}function OJ(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 qJ(b,w,$){if(!b)throw Error(`${$} does not support task creation (required for ${w})`);switch(w){case"sampling/createMessage":if(!b.sampling?.createMessage)throw Error(`${$} does not support task creation for sampling/createMessage (required for ${w})`);break;case"elicitation/create":if(!b.elicitation?.create)throw Error(`${$} does not support task creation for elicitation/create (required for ${w})`);break;default:break}}class YW extends $4{constructor(b,w){super(w);if(this._serverInfo=b,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(u1.options.map(($,W)=>[$,W])),this.isMessageIgnored=($,W)=>{let Q=this._loggingLevels.get(W);return Q?this.LOG_LEVEL_SEVERITY.get($)<this.LOG_LEVEL_SEVERITY.get(Q):!1},this._capabilities=w?.capabilities??{},this._instructions=w?.instructions,this._jsonSchemaValidator=w?.jsonSchemaValidator??new DW,this.setRequestHandler(f6,($)=>this._oninitialize($)),this.setNotificationHandler(c6,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(r6,async($,W)=>{let Q=W.sessionId||W.requestInfo?.headers["mcp-session-id"]||void 0,{level:G}=$.params,D=u1.safeParse(G);if(D.success)this._loggingLevels.set(Q,D.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new XW(this)};return this._experimental}registerCapabilities(b){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=CG(this._capabilities,b)}setRequestHandler(b,w){let W=R0(b)?.method;if(!W)throw Error("Schema is missing a method literal");let Q;if(gw(W)){let D=W;Q=D._zod?.def?.value??D.value}else{let D=W;Q=D._def?.value??D.value}if(typeof Q!=="string")throw Error("Schema method literal must be a string");if(Q==="tools/call"){let D=async(X,Y)=>{let H=Fw(C1,X);if(!H.success){let q=H.error instanceof Error?H.error.message:String(H.error);throw new u(c.InvalidParams,`Invalid tools/call request: ${q}`)}let{params:J}=H.data,z=await Promise.resolve(w(X,Y));if(J.task){let q=Fw(iw,z);if(!q.success){let B=q.error instanceof Error?q.error.message:String(q.error);throw new u(c.InvalidParams,`Invalid task creation result: ${B}`)}return q.data}let O=Fw(o0,z);if(!O.success){let q=O.error instanceof Error?O.error.message:String(O.error);throw new u(c.InvalidParams,`Invalid tools/call result: ${q}`)}return O.data};return super.setRequestHandler(b,D)}return super.setRequestHandler(b,w)}assertCapabilityForMethod(b){switch(b){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${b})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${b})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${b})`);break;case"ping":break}}assertNotificationCapability(b){switch(b){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${b})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${b})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${b})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${b})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${b})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(b){if(!this._capabilities)return;switch(b){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${b})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${b})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${b})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${b})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${b})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${b})`);break;case"ping":case"initialize":break}}assertTaskCapability(b){qJ(this._clientCapabilities?.tasks?.requests,b,"Client")}assertTaskHandlerCapability(b){if(!this._capabilities)return;OJ(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:UG.includes(w)?w:C6,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},y0)}async createMessage(b,w){if(b.tools||b.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if(b.messages.length>0){let $=b.messages[b.messages.length-1],W=Array.isArray($.content)?$.content:[$.content],Q=W.some((Y)=>Y.type==="tool_result"),G=b.messages.length>1?b.messages[b.messages.length-2]:void 0,D=G?Array.isArray(G.content)?G.content:[G.content]:[],X=D.some((Y)=>Y.type==="tool_use");if(Q){if(W.some((Y)=>Y.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!X)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(X){let Y=new Set(D.filter((J)=>J.type==="tool_use").map((J)=>J.id)),H=new Set(W.filter((J)=>J.type==="tool_result").map((J)=>J.toolUseId));if(Y.size!==H.size||![...Y].every((J)=>H.has(J)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if(b.tools)return this.request({method:"sampling/createMessage",params:b},s6,w);return this.request({method:"sampling/createMessage",params:b},e6,w)}async elicitInput(b,w){switch(b.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let W=b;return this.request({method:"elicitation/create",params:W},d0,w)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let W=b.mode==="form"?b:{...b,mode:"form"},Q=await this.request({method:"elicitation/create",params:W},d0,w);if(Q.action==="accept"&&Q.content&&W.requestedSchema)try{let D=this._jsonSchemaValidator.getValidator(W.requestedSchema)(Q.content);if(!D.valid)throw new u(c.InvalidParams,`Elicitation response content does not match requested schema: ${D.errorMessage}`)}catch(G){if(G instanceof u)throw G;throw new u(c.InternalError,`Error validating elicitation response: ${G instanceof Error?G.message:String(G)}`)}return Q}}}createElicitationCompletionNotifier(b,w){if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:b}},w)}async listRoots(b,w){return this.request({method:"roots/list",params:b},a6,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 LJ={name:"@sequenzy/mcp",version:"0.0.116",mcpName:"io.github.sequenzy/mcp",description:"Sequenzy MCP server for AI-powered email marketing automation",type:"module",bin:{"sequenzy-mcp":"dist/index.js"},main:"./dist/index.js",exports:{".":"./dist/index.js","./server":"./dist/server.js","./runtime":"./dist/runtime.js","./server.json":"./server.json"},scripts:{dev:"bun --watch src/index.ts",build:"bun build src/index.ts src/server.ts src/runtime.ts --outdir dist --target node --minify",start:"node dist/index.js","type-check":"bunx --bun tsc --noEmit",test:"bun test","test:watch":"bun test --watch",prepublishOnly:"bun run build"},dependencies:{"@modelcontextprotocol/sdk":"^1.0.0"},devDependencies:{"@types/bun":"latest","@types/node":"^22.0.0","bun-types":"latest",typescript:"^7.0.2"},files:["dist","server.json"],keywords:["sequenzy","email","mcp","ai","claude","automation"],license:"MIT",publishConfig:{access:"public"},repository:{type:"git",url:"git+https://github.com/Sequenzy/mcp.git"},homepage:"https://sequenzy.com",bugs:{url:"https://github.com/Sequenzy/mcp/issues"}};var HW=["product-info","domain","tracking","localization","integrations","products","events","tags","labels","goals","sync-rules","api-keys","widgets","team","danger"],UJ={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 SK(b){let $=(b??process.env.SEQUENZY_APP_URL??"https://sequenzy.com").trim().replace(/\/+$/,"");return $.length>0?$:"https://sequenzy.com"}function ib(b){let w=b?.trim();return w?w:void 0}function eb(b){return encodeURIComponent(b)}function Db(b,w){return`${b}${w}`}function Xb(b,w=""){return`/dashboard/company/${eb(b)}${w}`}function BJ(b,w,$){return Db(b,`${Xb(w,"/settings")}?tab=${encodeURIComponent($)}`)}function RK(b,w){let $=HW.map((W)=>[W,w?BJ(b,w,W):""]);return Object.fromEntries($)}function Yw(b={},w){let $=SK(w),W=ib(b.companyId),Q={},G=RK($,W);if(!W)return{appUrl:$,routeTemplates:UJ,settingsTabValues:HW,urls:Q,settingsUrls:G};Q.dashboard=Db($,Xb(W)),Q.campaigns=Db($,Xb(W,"/campaign")),Q.landingPages=Db($,Xb(W,"/landing-pages")),Q.sequences=Db($,Xb(W,"/sequences")),Q.settings=Db($,Xb(W,"/settings")),Q.emails=Db($,Xb(W,"/emails")),Q.subscribers=Db($,Xb(W,"/subscribers")),Q.sentEmails=Db($,Xb(W,"/sent-emails")),Q.segments=Db($,Xb(W,"/segments")),Q.metrics=Db($,Xb(W,"/metrics")),Q.transactional=Db($,Xb(W,"/transactional"));let D=ib(b.campaignId);if(D)Q.campaign=Db($,Xb(W,`/campaign/${eb(D)}`)),Q.campaignPreview=`${Q.campaign}?step=review`;let X=ib(b.landingPageId);if(X)Q.landingPage=Db($,Xb(W,`/landing-pages/${eb(X)}`));let Y=ib(b.sequenceId);if(Y)Q.sequence=Db($,Xb(W,`/sequences/${eb(Y)}`));let H=ib(b.emailId)??ib(b.templateId);if(H)Q.email=Db($,Xb(W,`/emails/${eb(H)}`)),Q.template=Q.email;let J=ib(b.transactionalId);if(J)Q.transactionalEmail=Db($,Xb(W,`/transactional/${eb(J)}`));let z=ib(b.emailSendId);if(z)Q.emailSend=Db($,Xb(W,`/sent-emails/${eb(z)}`));let O=ib(b.domainId);if(O)Q.domain=Db($,Xb(W,`/settings/domain/${eb(O)}`)),Q.domainVerify=`${Q.domain}/verify`;let q=ib(b.status);if(q)Q.campaignList=Db($,Xb(W,`/campaign/list/${eb(q)}`)),Q.sequenceList=Db($,Xb(W,`/sequences/list/${eb(q)}`));let B=ib(b.settingsTab);if(B)Q.settingsTab=BJ($,W,B);return{appUrl:$,routeTemplates:UJ,settingsTabValues:HW,urls:Q,settingsUrls:G}}var PJ=[{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 FJ(b){try{let w;switch(b){case"sequenzy://dashboard":w=await A("GET","/api/v1/metrics?period=7d");break;case"sequenzy://company":{let $=await A("GET","/api/v1/account"),W=qw()??$.currentCompanyId;if(!W)throw Error("No company available. Create or select a company first.");w=await A("GET",`/api/v1/companies/${W}`);break}case"sequenzy://campaigns/recent":w=await A("GET","/api/v1/campaigns?limit=10");break;case"sequenzy://subscribers/recent":w=await A("GET","/api/v1/subscribers?sort=createdAt&limit=20");break;case"sequenzy://subscribers/engaged":w=await A("GET","/api/v1/subscribers?sort=engagement&limit=20");break;case"sequenzy://sequences":w=await A("GET","/api/v1/sequences");break;case"sequenzy://templates":w=await A("GET","/api/v1/templates");break;case"sequenzy://segments":w=await A("GET","/api/v1/segments");break;case"sequenzy://tags":w=await A("GET","/api/v1/tags");break;case"sequenzy://health":w=await A("GET","/api/v1/health/deliverability");break;case"sequenzy://app-routes":w=Yw();break;default:throw Error(`Unknown resource: ${b}`)}return{contents:[{uri:b,mimeType:"application/json",text:JSON.stringify(w,null,2)}]}}catch(w){return{contents:[{uri:b,mimeType:"text/plain",text:Ow(w)}]}}}function y(b){return typeof b==="object"&&b!==null&&!Array.isArray(b)}function P(b,w){let $=b[w];if(typeof $!=="string")return;let W=$.trim();return W.length>0?W:void 0}function Z(b,w,$){let W=P(w,$);if(W===void 0)throw Error(`\`${$}\` is required when calling \`${b}\`.`);return W}var _w='For exact historical Poll/NPS respondents, use field `pollResponse`, operator `is`, and a JSON value shaped like {"v":1,"campaignId":"camp_123","blockId":"poll_1","match":{"kind":"answer","value":"loved"}}. For NPS buckets, use match {"kind":"npsBucket","bucket":"promoters"}; bucket may be `promoters`, `passives`, or `detractors`.',Hw='Sequenzy email blocks. Use this for editor-compatible content, including conditional and repeat blocks. For provider-migrated HTML from another email platform, prefer the `html` field instead; Sequenzy stores it as one raw HTML block to preserve the original design. Use `styles` for per-block background, background opacity, text color, padding, border radius, border width, and border color. Top-level style aliases such as `backgroundColor`, `backgroundOpacity`, `borderColor`, `borderWidth`, and `borderRadius` are also accepted and saved under `styles`. Repeat blocks use { type: \'repeat\', source: \'items\', itemAlias: \'item\', children: [...] }. Any block accepts a `conditions` array so it only renders for matching recipients. To branch on a value passed in transactional `variables` or an automation `event` payload, use { "id": "c1", "field": "variable", "operator": "is", "value": "plan:pro" }; "attribute" uses the same "name:value" form, while "email"/"firstName"/"lastName" use a plain comparison value. Live subscriber fields are "status", "tag", "list", "segment", "event", "emailProvider", "phone", "smsStatus", "added", "stripeProduct", "stripeCurrentProduct", "stripeTrialProduct", "commerceProduct", "emailSent", "emailDelivered", "emailOpened", "emailClicked", "emailBounced", and "emailComplained". They use the same field-specific values and operators as segment filters, for example { "id": "c2", "field": "segment", "operator": "is", "value": "seg_123" }, { "id": "c3", "field": "tag", "operator": "contains", "value": "vip" }, or { "id": "c4", "field": "event", "operator": "at_least", "value": "purchase:3:30d" }. Supported operators across fields are is, is_not, contains, not_contains, gt, gte, lt, lte, less_than, more_than, at_least, less_than_count, is_empty, is_not_empty, is_temporary_bounce, and is_permanent_bounce; each field accepts only its segment-filter operators. Recipients without a stored subscriber match use the OTHERWISE branch or hide a conditionally displayed block. For if/else, use a { type: "conditional-group", conditions: [...], ifBranch: { children: [...] }, elseBranch: { children: [...] } } block. Polls and NPS surveys use a native poll block. For answer buttons use { "type": "poll", "variant": "options", "question": "What did you think?", "options": [{ "label": "Loved it", "value": "loved" }, { "label": "Not for me", "value": "not_for_me" }], "attributeKey": "email_feedback" }. For NPS use { "type": "poll", "variant": "nps", "question": "How likely are you to recommend us?", "options": [], "attributeKey": "nps_score", "npsLowLabel": "Not likely", "npsHighLabel": "Very likely" }. `attributeKey` stores the latest response for segmentation. Optional `appearance` picks the answer style: "soft" (default), "pill", "outline", "filled", "pop" (hard-shadow boxes), "brutal" (square uppercase slabs), "quiz" (A/B/C letter badges), or "minimal" (bare ruled rows). Optional `confirmationMessage` customizes the hosted thank-you page; set `redirectUrl` only when respondents should land on another page. For a new image, call `upload_image_asset` first and insert its returned `imageBlock`. A responsive fixed-height screenshot crop uses { "type": "image", "src": "https://...", "alt": "Product dashboard", "width": 100, "widthType": "percent", "height": 320, "objectFit": "cover", "align": "center" }.',Jw='Replacement Sequenzy email blocks. Use `styles` for per-block background, background opacity, text color, padding, border radius, border width, and border color. Top-level style aliases such as `backgroundColor`, `backgroundOpacity`, `borderColor`, `borderWidth`, and `borderRadius` are also accepted and saved under `styles`. Any block accepts a `conditions` array so it only renders for matching recipients. To branch on a value passed in transactional `variables` or an automation `event` payload, use { "id": "c1", "field": "variable", "operator": "is", "value": "plan:pro" }; "attribute" uses the same "name:value" form, while "email"/"firstName"/"lastName" use a plain comparison value. Live subscriber fields are "status", "tag", "list", "segment", "event", "emailProvider", "phone", "smsStatus", "added", "stripeProduct", "stripeCurrentProduct", "stripeTrialProduct", "commerceProduct", "emailSent", "emailDelivered", "emailOpened", "emailClicked", "emailBounced", and "emailComplained". They use the same field-specific values and operators as segment filters, for example { "id": "c2", "field": "segment", "operator": "is", "value": "seg_123" }, { "id": "c3", "field": "tag", "operator": "contains", "value": "vip" }, or { "id": "c4", "field": "event", "operator": "at_least", "value": "purchase:3:30d" }. Supported operators across fields are is, is_not, contains, not_contains, gt, gte, lt, lte, less_than, more_than, at_least, less_than_count, is_empty, is_not_empty, is_temporary_bounce, and is_permanent_bounce; each field accepts only its segment-filter operators. Recipients without a stored subscriber match use the OTHERWISE branch or hide a conditionally displayed block. For if/else, use a { type: "conditional-group", conditions: [...], ifBranch: { children: [...] }, elseBranch: { children: [...] } } block. Polls and NPS surveys use a native poll block. For answer buttons use { "type": "poll", "variant": "options", "question": "What did you think?", "options": [{ "label": "Loved it", "value": "loved" }, { "label": "Not for me", "value": "not_for_me" }], "attributeKey": "email_feedback" }. For NPS use { "type": "poll", "variant": "nps", "question": "How likely are you to recommend us?", "options": [], "attributeKey": "nps_score", "npsLowLabel": "Not likely", "npsHighLabel": "Very likely" }. `attributeKey` stores the latest response for segmentation. Optional `appearance` picks the answer style: "soft" (default), "pill", "outline", "filled", "pop" (hard-shadow boxes), "brutal" (square uppercase slabs), "quiz" (A/B/C letter badges), or "minimal" (bare ruled rows). Optional `confirmationMessage` customizes the hosted thank-you page; set `redirectUrl` only when respondents should land on another page. For a new image, call `upload_image_asset` first and insert its returned `imageBlock`. A responsive fixed-height screenshot crop uses { "type": "image", "src": "https://...", "alt": "Product dashboard", "width": 100, "widthType": "percent", "height": 320, "objectFit": "cover", "align": "center" }.',W1='Sequenzy email blocks. Provide blocks or html for email steps. For migrated provider HTML, prefer `html`; Sequenzy stores it as one raw HTML block and does not recreate it as native blocks. Use `styles` for per-block background, background opacity, text color, padding, border radius, border width, and border color. Top-level style aliases such as `backgroundColor`, `backgroundOpacity`, `borderColor`, `borderWidth`, and `borderRadius` are also accepted and saved under `styles`. Blocks can include repeat blocks over array variables such as items. Any block accepts a `conditions` array so it only renders for matching recipients. To branch on a value passed in transactional `variables` or an automation `event` payload, use { "id": "c1", "field": "variable", "operator": "is", "value": "plan:pro" }; "attribute" uses the same "name:value" form, while "email"/"firstName"/"lastName" use a plain comparison value. Live subscriber fields are "status", "tag", "list", "segment", "event", "emailProvider", "phone", "smsStatus", "added", "stripeProduct", "stripeCurrentProduct", "stripeTrialProduct", "commerceProduct", "emailSent", "emailDelivered", "emailOpened", "emailClicked", "emailBounced", and "emailComplained". They use the same field-specific values and operators as segment filters, for example { "id": "c2", "field": "segment", "operator": "is", "value": "seg_123" }, { "id": "c3", "field": "tag", "operator": "contains", "value": "vip" }, or { "id": "c4", "field": "event", "operator": "at_least", "value": "purchase:3:30d" }. Supported operators across fields are is, is_not, contains, not_contains, gt, gte, lt, lte, less_than, more_than, at_least, less_than_count, is_empty, is_not_empty, is_temporary_bounce, and is_permanent_bounce; each field accepts only its segment-filter operators. Recipients without a stored subscriber match use the OTHERWISE branch or hide a conditionally displayed block. For if/else, use a { type: "conditional-group", conditions: [...], ifBranch: { children: [...] }, elseBranch: { children: [...] } } block. Polls and NPS surveys use a native poll block. For answer buttons use { "type": "poll", "variant": "options", "question": "What did you think?", "options": [{ "label": "Loved it", "value": "loved" }, { "label": "Not for me", "value": "not_for_me" }], "attributeKey": "email_feedback" }. For NPS use { "type": "poll", "variant": "nps", "question": "How likely are you to recommend us?", "options": [], "attributeKey": "nps_score", "npsLowLabel": "Not likely", "npsHighLabel": "Very likely" }. `attributeKey` stores the latest response for segmentation. Optional `appearance` picks the answer style: "soft" (default), "pill", "outline", "filled", "pop" (hard-shadow boxes), "brutal" (square uppercase slabs), "quiz" (A/B/C letter badges), or "minimal" (bare ruled rows). Optional `confirmationMessage` customizes the hosted thank-you page; set `redirectUrl` only when respondents should land on another page. For a new image, call `upload_image_asset` first and insert its returned `imageBlock`. A responsive fixed-height screenshot crop uses { "type": "image", "src": "https://...", "alt": "Product dashboard", "width": 100, "widthType": "percent", "height": 320, "objectFit": "cover", "align": "center" }.',D0="Complete Sequenzy landing page content JSON. Use this when replacing the page structure. The content must be the editor-compatible landing page schema with version, template, seo, theme, and blocks. Landing pages must include exactly one footer block and at most one form block.",KJ="Optional template key for default content, such as from-scratch, waitlist, lead-magnet, launch, demo-request, webinar, newsletter, product-hunt, pricing-offer, agency-lead-gen, or feature-announcement.",JW=500,zW=500,lb={type:"boolean",description:"If true, include machine-classified bot/scanner opens and clicks. Defaults to false, so metrics and activity are human-only."},k$=["send","delivery","bounce","complaint","open","click","unsubscribe","delivery_delay"],C$={type:"object",description:"Optional send window for every email step in the sequence. When set, email actions that become due outside the window wait until the next allowed local time. Omit days to allow every day.",properties:{enabled:{type:"boolean",description:"Set false to disable the sending window when creating a sequence. For updates, prefer clearSendingWindow."},timezone:{type:"string",description:"IANA timezone for the window, e.g. Europe/Kiev or America/New_York."},startTime:{type:"string",description:"Earliest local send time in 24-hour HH:mm format, e.g. 08:00."},endTime:{type:"string",description:"Latest local send cutoff in 24-hour HH:mm format, e.g. 20:00. Must be later than startTime."},days:{type:"array",description:"Allowed local days. Use full names or short names such as monday, tuesday, mon, tue. Omit for every day.",items:{type:"string"}}},additionalProperties:!1},vK={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:vK,days:{type:"number",description:"Offset days shorthand. Ignored when offset is provided."},hours:{type:"number",description:"Offset hours shorthand. Ignored when offset is provided."},minutes:{type:"number",description:"Offset minutes shorthand. Ignored when offset is provided."},direction:{type:"string",enum:["before","after"],description:"Whether the offset applies before or after the resolved date. Defaults to after."},untilOffsetDirection:{type:"string",enum:["before","after"],description:"Alias for direction."},missingAction:{type:"string",enum:["continue","exit"],description:"What to do if the event field is missing or invalid. Defaults to continue."},untilMissingAction:{type:"string",enum:["continue","exit"],description:"Alias for missingAction."}},additionalProperties:!1},G1={type:"object",description:"Fixed delay before this step. For a dynamic wait-until-date delay, either set mode:'until_date' plus untilDateField here, or use waitUntil.",properties:{days:{type:"number"},hours:{type:"number"},minutes:{type:"number"},mode:{type:"string",enum:["duration","until_date"],description:"Use duration for a fixed wait, or until_date to resolve a date from the trigger event."},untilDateField:{type:"string",description:"For mode:'until_date', dot-path into the trigger event properties."},field:{type:"string",description:"Alias for untilDateField."},untilOffsetDirection:{type:"string",enum:["before","after"],description:"For mode:'until_date', whether days/hours/minutes are before or after the event date. Defaults to after."},direction:{type:"string",enum:["before","after"],description:"Alias for untilOffsetDirection."},untilMissingAction:{type:"string",enum:["continue","exit"],description:"For mode:'until_date', what to do when the field is missing or invalid. Defaults to continue."},missingAction:{type:"string",enum:["continue","exit"],description:"Alias for untilMissingAction."}},additionalProperties:!1},AW={type:"object",description:"Type-aware patch for the existing node. Start from get_sequence.sequence.nodes[].config. For logic_delay, set exactly one of delay ({ days, hours, minutes }), delayMs, or waitUntil; optional label is also accepted. For action_email, use name/label, subject, previewText, html/htmlContent or blocks, isTransactional, and sender/reply identity fields. For action_sms, use text, blocks, imageUrls, label, or ineligibleAction. Other node types accept their editable config keys. Managed IDs, nodeType conversion, and branch path IDs/count are not editable here; use edit_sequence_graph for topology. Webhook header patches are merged, and redacted values from get_sequence must be omitted or replaced with a real new value.",additionalProperties:!0},u$={type:"object",properties:{nodeId:{type:"string",description:"Existing node ID from get_sequence.sequence.nodes[].id."},changes:AW,expectedUpdatedAt:{type:"string",description:"Required optimistic-concurrency value from get_sequence.sequence.nodes[].updatedAt. The update is rejected if that node or its linked email content changed after it was read."}},required:["nodeId","changes","expectedUpdatedAt"],additionalProperties:!1},D1=["gray","red","orange","amber","yellow","lime","green","emerald","teal","cyan","sky","blue","indigo","violet","purple","fuchsia","pink","rose"],X1=["email.sent","email.delivered","email.delivery_delayed","email.bounced","email.complained","email.opened","email.clicked","email.replied","email.unsubscribed","sms.sent","sms.delivered","sms.failed","sms.opted_out","subscriber.invalid","subscriber.updated","subscriber.unsubscribed","subscriber.list_subscribed","subscriber.list_unsubscribed","sequence.finished","sequence.failed","poll.answered"];var kK=new Set(["get_account","get_app_urls","get_company","get_sync_rules","get_shopify_automation_settings","list_websites","check_website","get_integration_guide","get_subscriber","list_subscriber_notes","search_subscribers","list_products","list_tags","list_lists","list_segments","get_segment_count","list_audience_syncs","list_ad_accounts","list_templates","get_template","list_ab_tests","get_ab_test","get_ab_test_stats","list_campaigns","get_campaign","get_email_send","list_forms","get_form_embed","get_recipient_suppression","list_landing_pages","get_landing_page","list_sequences","get_sequence","list_transactional_emails","get_transactional_email","get_stats","get_campaign_stats","get_sequence_stats","list_campaign_events","list_sequence_events","get_subscriber_activity","list_team_members","list_conversations","get_conversation","list_webhooks","list_webhook_deliveries","generate_email","generate_subject_lines","generate_sms","get_sms_settings"]),CK=new Set(["select_company","create_company","update_company","update_sync_rules","update_shopify_automation_settings","create_api_key","add_sending_domain","add_website","verify_sending_domain","add_subscriber","update_subscriber","add_subscriber_note","remove_subscriber","delete_subscriber_note","upsert_products","delete_product","attach_product_file","remove_product_file","upload_image_asset","sync_products","create_tag","update_tag","delete_tag","create_list","update_list","delete_list","add_subscribers_to_list","remove_subscribers_from_list","create_segment","update_segment","delete_segment","create_audience_sync","update_audience_sync","delete_audience_sync","sync_audience_now","create_template","update_template","set_template_localization","sync_template_localizations","delete_template","restart_ab_test","update_ab_test_variant","create_ab_test","add_ab_test_variant","delete_ab_test_variant","delete_ab_test","create_campaign","update_campaign","schedule_campaign","send_test_email","send_test_sms","cancel_campaign","pause_campaign","resume_campaign","delete_campaign","duplicate_campaign","resend_campaign_to_non_openers","create_form","create_landing_page","update_landing_page","delete_landing_page","publish_landing_page","unpublish_landing_page","connect_landing_page_domain","update_landing_page_domain_settings","create_sequence","generate_sequence","update_sequence","update_sequence_node","update_sequence_nodes","edit_sequence_graph","insert_sequence_step","enable_sequence","disable_sequence","pause_sequence_enrollments","resume_sequence_enrollments","enroll_subscribers_in_sequence","cancel_sequence_enrollments","delete_sequence","create_transactional_email","update_transactional_email","send_email","invite_team_member","cancel_team_invitation","reply_to_conversation","update_conversation_status","mark_conversation_read","create_webhook","update_webhook","delete_webhook","test_webhook","replay_webhook_delivery","submit_feedback","remove_recipient_suppression"]),uK=new Set(["send_test_email","send_test_sms","schedule_campaign","resume_campaign","publish_landing_page","connect_landing_page_domain","update_landing_page_domain_settings","add_sending_domain","add_website","verify_sending_domain","enable_sequence","resume_sequence_enrollments","send_email","invite_team_member","reply_to_conversation","create_webhook","update_webhook","test_webhook","replay_webhook_delivery","remove_recipient_suppression"]),xK=new Set(["remove_subscriber","delete_subscriber_note","delete_product","remove_product_file","delete_tag","delete_list","remove_subscribers_from_list","delete_segment","delete_audience_sync","delete_template","restart_ab_test","delete_ab_test_variant","delete_ab_test","cancel_campaign","delete_campaign","delete_landing_page","unpublish_landing_page","disable_sequence","edit_sequence_graph","cancel_sequence_enrollments","delete_sequence","cancel_team_invitation","delete_webhook","remove_recipient_suppression"]);function yK(b){let w=kK.has(b),$=CK.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:xK.has(b),openWorldHint:uK.has(b)}}function MJ(b){return{...b,annotations:{...b.annotations,...yK(b.name)}}}var OW={status:["is","is_not"],phone:["is_not_empty","is_empty"],smsStatus:["is","is_not"],tag:["contains","not_contains","is_empty","is_not_empty"],email:["contains","not_contains"],emailProvider:["is","is_not","is_empty","is_not_empty"],added:["less_than","more_than"],firstName:["contains","not_contains","is_empty","is_not_empty"],lastName:["contains","not_contains","is_empty","is_not_empty"],list:["is","is_not","is_empty","is_not_empty"],emailSent:["is","is_not","at_least","less_than_count"],emailDelivered:["is","is_not","at_least","less_than_count"],emailOpened:["is","is_not","at_least","less_than_count"],emailClicked:["is","is_not","at_least","less_than_count"],emailBounced:["is","is_temporary_bounce","is_permanent_bounce","is_not","at_least","less_than_count"],emailComplained:["is","is_not","at_least","less_than_count"],attribute:["is","is_not","is_empty","is_not_empty","gte","lte","gt","lt","contains","not_contains"],event:["is","is_not","at_least","less_than_count"],pollResponse:["is"],segment:["is","is_not"],stripeProduct:["is","is_not","at_least","less_than_count"],stripeCurrentProduct:["is","is_not","gte","lte","gt","lt"],stripeTrialProduct:["is","is_not","gte","lte","gt","lt"],commerceProduct:["is","is_not","at_least","less_than_count"]},hK=Object.entries(OW).map(([b,w])=>`${b}: ${w.join(", ")}`).join("; "),qW={type:"object",properties:{id:{type:"string",description:"Optional filter ID. Any stable string works; one will be generated if omitted."},field:{type:"string",enum:["status","phone","smsStatus","tag","email","emailProvider","added","firstName","lastName","list","emailSent","emailDelivered","emailOpened","emailClicked","emailBounced","emailComplained","attribute","event","pollResponse","segment","stripeProduct","stripeCurrentProduct","stripeTrialProduct","commerceProduct"],description:`Filter field. Use \`phone\` with is_not_empty/is_empty to check whether a subscriber has a phone number, and \`smsStatus\` (is/is_not one of \`subscribed\`, \`unsubscribed\`, \`not_subscribed\`) for SMS marketing consent. Use \`event\` for custom subscriber events, \`segment\` for saved segment membership, \`stripeProduct\`/\`stripeCurrentProduct\`/\`stripeTrialProduct\` for Stripe product-based segments, and \`commerceProduct\` for products purchased through commerce orders - the value is \`provider:productId\` (provider one of \`shopify\`, \`woocommerce\`, \`api\`; product ids are provider-scoped), optionally with an order-count threshold (\`provider:productId:count\`) for at_least/less_than_count; a bare product id matches the id on any provider. Engagement fields (\`emailSent\`, \`emailDelivered\`, \`emailOpened\`, \`emailClicked\`, \`emailBounced\`, \`emailComplained\`) accept a time range as the value, a specific campaign via \`campaign:<campaign_id>\`, or \`count:timeRange\` (e.g. \`10:30d\`, \`10:all\`) with at_least/less_than_count to segment by number of opens/clicks. ${_w}`},operator:{type:"string",enum:["is","is_not","is_empty","is_not_empty","contains","not_contains","less_than","more_than","is_temporary_bounce","is_permanent_bounce","at_least","less_than_count","gte","lte","gt","lt"],description:`Filter operator. Allowed operators by field: ${hK}.`},value:{type:"string",description:`Filter value. For custom attribute empty checks, use \`attributeName:\` such as \`last_logged_in:\`. Event examples: \`saas.purchase:30d\`, \`saas.purchase:all\`, or \`saas.purchase:5:30d\` for thresholds. Segment values are segment IDs. Stripe product examples: \`prod_123\` for bought/didn't buy/current/trialing, \`prod_123:3\` for payment thresholds, \`prod_123:is_canceled\` for products set to cancel, \`prod_123:cancels_at:2026-05-26\`, \`prod_123:end_at:2026-05-26\`, or \`prod_123:start_at:7 days ago\` for product-scoped dates. Engagement examples: \`7d\`, \`30d\`, \`90d\`, \`180d\`, \`all\` for rolling time windows, \`campaign:<campaign_id>\` to scope to a specific sent campaign (use \`list_campaigns\` to find IDs), or \`count:timeRange\` like \`10:30d\` / \`10:all\` with at_least/less_than_count operators (e.g. emailClicked at_least \`10:all\` = clicked 10 or more times ever). ${_w}`}},required:["field","operator","value"],additionalProperties:!1},LW={type:"object",properties:{kind:{type:"string",enum:["group"]},id:{type:"string",description:"Stable group ID. Any string works; one will be generated if omitted."},joinOperator:{type:"string",enum:["and","or"],description:"How children in this group combine."},children:{type:"array",minItems:1,items:{type:"object",description:'Either a filter leaf (`kind: "filter"`) or another group (`kind: "group"`).'}}},required:["kind","joinOperator","children"],additionalProperties:!0};function x$(b){if(!Array.isArray(b))return b;return b.map((w)=>{if(typeof w!=="object"||w===null)return w;let $=w;if(typeof $.id==="string"&&$.id.trim()!=="")return $;return{...$,id:crypto.randomUUID()}})}function y$(b){if(typeof b!=="object"||b===null)return b;let w=b;if(w.kind==="filter"||"field"in w||"operator"in w||"value"in w){let $=x$([w]);return Array.isArray($)?$[0]:w}if(w.kind!=="group")return b;return{...w,id:typeof w.id==="string"&&w.id.trim()!==""?w.id:crypto.randomUUID(),children:Array.isArray(w.children)?w.children.map(y$):[]}}function fK(b){let w=b.indexOf(":");return w!==-1&&b.substring(0,w).trim().length>0}function cK(b){let w=b.indexOf(":");return w!==-1&&b.substring(w+1).trim().length>0}function IJ(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 nK(b,w){let $=w.split(":");if(b==="at_least"||b==="less_than_count"){if($.length<3)return'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".';let G=$.slice(0,-2).join(":").trim(),D=$.at(-2),X=$.at(-1),Y=D===void 0?Number.NaN:Number.parseInt(D,10);return G&&Number.isInteger(Y)&&Y>0&&X!==void 0&&IJ(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&&IJ(Q)?null:'Event filters must use "eventName:timeRange", like "saas.purchase:30d".'}function gK(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 mK(b){return b.trim().toLowerCase().replace(/[-\s]+/g,"_")}function iK(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 lK(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 pK(b){return["is","is_not","gte","lte","gt","lt"].includes(b)}function oK(b,w,$){if(b==="stripeProduct"){if(w!=="at_least"&&w!=="less_than_count")return null;let X=$.indexOf(":");if(X===-1)return null;let Y=$.substring(0,X).trim(),H=Number.parseInt($.substring(X+1).trim(),10);return Y&&Number.isInteger(H)&&H>=1?null:'Stripe Product threshold filters must use "productId:count" with a count of at least 1.'}if(b!=="stripeCurrentProduct"&&b!=="stripeTrialProduct")return null;let{productId:W,subfilter:Q,rawValue:G}=gK($);if(!W.trim())return"Stripe product filters must include a product ID.";if(!Q)return w==="is"||w==="is_not"?null:'Stripe current/trial date filters must use "productId:dateField:value".';let D=mK(Q);if(iK(D))return w==="is"||w==="is_not"?null:"Stripe cancellation flag filters only support is and is_not operators.";if(!lK(b,D))return`Unsupported Stripe product subfilter "${Q}".`;if(!pK(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 dK=new Set(["shopify","woocommerce","api"]);function tK(b,w){let $=w.trim(),W=$.indexOf(":");if(W!==-1&&dK.has($.substring(0,W).trim()))$=$.substring(W+1).trim();if(!$)return'Purchased Product filters must include a product ID, like "shopify:42".';if(b!=="at_least"&&b!=="less_than_count")return null;let Q=$.lastIndexOf(":");if(Q===-1)return null;let G=$.substring(0,Q).trim(),D=Number.parseInt($.substring(Q+1).trim(),10);return G&&Number.isInteger(D)&&D>=1?null:'Purchased Product threshold filters must use "provider:productId:count" with a count of at least 1.'}function rK(b){let w;try{w=JSON.parse(b)}catch{return`Poll response filters must use valid JSON. ${_w}`}if(!y(w)||w.v!==1||typeof w.campaignId!=="string"||!w.campaignId.trim()||typeof w.blockId!=="string"||!w.blockId.trim()||!y(w.match))return`Poll response filter context is invalid. ${_w}`;let $=w.match;if($.kind==="answer"&&typeof $.value==="string"&&$.value.length>0)return null;if($.kind==="npsBucket"&&($.bucket==="promoters"||$.bucket==="passives"||$.bucket==="detractors"))return null;return`Poll response filter match is invalid. ${_w}`}function h$(b){if(typeof b!=="object"||b===null)return"Segment filters must be objects.";let w=b,$=w.field,W=w.operator,Q=w.value;if(typeof $!=="string"||!($ in OW))return`Unsupported segment filter field "${String($)}".`;if(typeof W!=="string")return`Segment filter "${$}" must include an operator.`;let G=OW[$];if(!G.includes(W))return`Operator "${W}" is not supported for ${$} filters. Use one of: ${G.join(", ")}.`;if(W!=="is_empty"&&W!=="is_not_empty"&&(typeof Q!=="string"||Q.trim().length===0))return`Segment filter "${$}" must include a value.`;if($==="attribute"&&typeof Q==="string"){if(!fK(Q))return'Attribute filters must use "attributeName:value" or "attributeName:" for empty checks.';if(W!=="is_empty"&&W!=="is_not_empty"&&!cK(Q))return'Attribute filters must include a value after "attributeName:".'}if($==="event"&&typeof Q==="string"){let D=nK(W,Q);if(D)return D}if($==="pollResponse"&&typeof Q==="string"){let D=rK(Q);if(D)return D}if(($==="stripeProduct"||$==="stripeCurrentProduct"||$==="stripeTrialProduct")&&typeof Q==="string"){let D=oK($,W,Q);if(D)return D}if($==="commerceProduct"&&typeof Q==="string"){let D=tK(W,Q);if(D)return D}if($==="tag"&&(W==="contains"||W==="not_contains")){if(!(typeof Q==="string"&&Q.split(",").map((X)=>X.trim()).some(Boolean)))return"Tag filters must include at least one tag name."}return null}function f$(b){if(typeof b!=="object"||b===null)return[];let w=b;if(w.kind==="filter"||"field"in w||"operator"in w||"value"in w){let $=h$(w);return $?[$]:[]}if(Array.isArray(w.children))return w.children.flatMap(f$);return[]}function _b(b,w,$){if(w.html!==void 0&&w.blocks!==void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${b}\`, not both.`);if(w.blocks!==void 0&&!Array.isArray(w.blocks))throw Error(`\`blocks\` must be an array when calling \`${b}\`.`);if($?.requireContent&&w.html===void 0&&w.blocks===void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${b}\`.`)}function Y1(b,w){if(w.labels===void 0)return;if(!Array.isArray(w.labels))throw Error(`\`labels\` must be an array when calling \`${b}\`.`);if(w.labels.some(($)=>typeof $!=="string"||$.trim().length===0))throw Error(`\`labels\` must contain only non-empty strings when calling \`${b}\`.`)}function VJ(b){let w=b.filters!==void 0,$=b.root!==void 0;if(w&&$)throw Error("Provide either `filters` or `root` when calling `create_segment`, not both.");if(!w&&!$)throw Error("Provide either `filters` or `root` when calling `create_segment`.");if(w){if(!Array.isArray(b.filters))throw Error("`filters` must be an array when calling `create_segment`.");if(b.filters.length===0)throw Error("`filters` must include at least one filter when calling `create_segment`.")}if($&&(typeof b.root!=="object"||b.root===null))throw Error("`root` must be an object when calling `create_segment`.");let W=w?b.filters.flatMap((Q)=>{let G=h$(Q);return G?[G]:[]}):f$(b.root);if(W.length>0)throw Error(W[0]??"Invalid segment filter in `create_segment`.")}function NJ(b){let w=b.filters!==void 0,$=b.root!==void 0;if(w&&$)throw Error("Provide either `filters` or `root` when calling `update_segment`, not both.");if(b.name===void 0&&b.filterJoinOperator===void 0&&!w&&!$)throw Error("Provide at least one of `name`, `filters`, `root`, or `filterJoinOperator` when calling `update_segment`.");if(w){if(!Array.isArray(b.filters))throw Error("`filters` must be an array when calling `update_segment`.");if(b.filters.length===0)throw Error("`filters` must include at least one filter when calling `update_segment`.")}if($&&(typeof b.root!=="object"||b.root===null))throw Error("`root` must be an object when calling `update_segment`.");let W=w?b.filters.flatMap((Q)=>{let G=h$(Q);return G?[G]:[]}):$?f$(b.root):[];if(W.length>0)throw Error(W[0]??"Invalid segment filter in `update_segment`.")}var UW=["name","description","logoUrl","founderName","primaryColor","brandColors","valueProps","testimonials","toneVoice","companyContext","emailLengthPreference","socialLinks","privacyPolicyUrl","termsUrl","address","language","pricing","fontFamily","emailDirection","fromEmail","fromName","replyTo","replyToName","replyTrackingEnabled","replyTrackingDomainMode","forwardReplies"];function BW(b,w,$){if(w[$]!==void 0&&!y(w[$]))throw Error(`\`${$}\` must be an object when calling \`${b}\`.`)}function ZJ(b,w,$){if(w[$]!==void 0&&!Array.isArray(w[$]))throw Error(`\`${$}\` must be an array when calling \`${b}\`.`)}function TJ(b){let w=new Set(["companyId",...UW]),$=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 UW)if(b[Q]!==void 0)W[Q]=b[Q];if(Object.keys(W).length===0)throw Error(`Provide at least one of ${UW.map((Q)=>`\`${Q}\``).join(", ")} when calling \`update_company\`.`);for(let Q of["name","description","logoUrl","founderName","primaryColor","toneVoice","companyContext","emailLengthPreference","privacyPolicyUrl","termsUrl","address","language","fontFamily","emailDirection","fromEmail","fromName","replyTo","replyToName","replyTrackingDomainMode"])if(b[Q]!==void 0&&typeof b[Q]!=="string")throw Error(`\`${Q}\` must be a string when calling \`update_company\`.`);BW("update_company",b,"brandColors"),BW("update_company",b,"socialLinks"),BW("update_company",b,"pricing"),ZJ("update_company",b,"valueProps"),ZJ("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 EJ=["senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName"];function eK(b){return EJ.some((w)=>b[w]!==void 0)}function sK(b){if(typeof b.nodeType==="string")return b.nodeType==="action_email";return b.type===void 0||b.type==="email"}function c$(b,w,$){for(let W of EJ){let Q=$[W];if(Q!==void 0&&typeof Q!=="string")throw Error(`\`${W}\` must be a string for ${w} when calling \`${b}\`.`)}if($.senderProfileId!==void 0&&$.fromEmail!==void 0)throw Error(`Provide either \`senderProfileId\` or \`fromEmail\` for ${w} when calling \`${b}\`, not both.`);if($.replyProfileId!==void 0&&$.replyTo!==void 0)throw Error(`Provide either \`replyProfileId\` or \`replyTo\` for ${w} when calling \`${b}\`, not both.`);if($.replyToName!==void 0&&$.replyTo===void 0)throw Error(`\`replyToName\` requires \`replyTo\` for ${w} when calling \`${b}\`.`)}function FW(b,w,$){if(eK($)&&!sK($))throw Error(`Sender identity fields are only supported for email steps at ${w} when calling \`${b}\`.`);c$(b,w,$)}function jJ(b,w,$){if(!Array.isArray($))return;$.forEach((W,Q)=>{if(y(W))c$(b,`${w}[${Q}]`,W)})}function PW(b,w,$){if(!Array.isArray($))return;$.forEach((W,Q)=>{if(y(W))FW(b,`${w}[${Q}]`,W)})}function aK(b){if(jJ("update_sequence","emails",b.emails),jJ("update_sequence","steps",b.steps),y(b.insertSteps))PW("update_sequence","insertSteps.steps",b.insertSteps.steps);if(!y(b.branch))return;if(Array.isArray(b.branch.branches))b.branch.branches.forEach(($,W)=>{if(y($))PW("update_sequence",`branch.branches[${W}].steps`,$.steps)});PW("update_sequence","branch.elseSteps",b.branch.elseSteps)}function _J(b){if(b.fromEmail!==void 0&&b.senderProfileId!==void 0)throw Error("Provide either `fromEmail` or `senderProfileId` when calling `update_sequence`, not both.");if(b.replyTo!==void 0&&b.replyProfileId!==void 0)throw Error("Provide either `replyTo` or `replyProfileId` when calling `update_sequence`, not both.");if(b.fromName!==void 0&&b.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `update_sequence`.");if(b.replyToName!==void 0&&b.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `update_sequence`.");if(b.clearEnrollmentFieldPath===!0&&b.enrollmentFieldPath!==void 0)throw Error("Provide either `enrollmentFieldPath` or `clearEnrollmentFieldPath` when calling `update_sequence`, not both.");if(b.clearSendingWindow===!0&&b.sendingWindow!==void 0)throw Error("Provide either `sendingWindow` or `clearSendingWindow` when calling `update_sequence`, not both.");if(b.clearBccEmails===!0&&b.bccEmails!==void 0)throw Error("Provide either `bccEmails` or `clearBccEmails` when calling `update_sequence`, not both.");if(b.branch!==void 0&&b.insertSteps!==void 0)throw Error("Provide either `branch` or `insertSteps` when calling `update_sequence`, not both.");aK(b);let w={...b};if(delete w.clearEnrollmentFieldPath,delete w.clearSendingWindow,delete w.clearBccEmails,b.clearEnrollmentFieldPath===!0)w.enrollmentFieldPath=null;if(b.clearSendingWindow===!0)w.sendingWindow=null;if(b.clearBccEmails===!0)w.bccEmails=null;return w}function SJ(b,w,$){let W=Z(b,w,"nodeId");if(!y(w.changes)||Object.keys(w.changes).length===0)throw Error(`\`changes\` must be a non-empty object for ${$} when calling \`${b}\`.`);let Q=Z(b,w,"expectedUpdatedAt");return{nodeId:W,changes:w.changes,expectedUpdatedAt:Q}}function RJ(b){let w=SJ("update_sequence_node",b,"the node update");return{...b.confirmLiveChange!==void 0&&{confirmLiveChange:b.confirmLiveChange},nodeUpdates:[w]}}function vJ(b){if(!Array.isArray(b.updates)||b.updates.length===0)throw Error("`updates` must be a non-empty array when calling `update_sequence_nodes`.");let w=new Set,$=b.updates.map((W,Q)=>{if(!y(W))throw Error(`\`updates[${Q}]\` must be an object when calling \`update_sequence_nodes\`.`);let G=SJ("update_sequence_nodes",W,`updates[${Q}]`),D=String(G.nodeId);if(w.has(D))throw Error(`\`updates[${Q}]\` targets duplicate nodeId '${D}' when calling \`update_sequence_nodes\`.`);return w.add(D),G});return{...b.confirmLiveChange!==void 0&&{confirmLiveChange:b.confirmLiveChange},nodeUpdates:$}}function kJ(b){let w=Z("edit_sequence_graph",b,"action"),$=Z("edit_sequence_graph",b,"graphRevision");if(!new Set(["move_node","delete_node","duplicate_node","replace_edges"]).has(w))throw Error("`action` must be `move_node`, `delete_node`, `duplicate_node`, or `replace_edges` when calling `edit_sequence_graph`.");let Q=P(b,"nodeId"),G=P(b,"afterNodeId"),D=P(b,"beforeNodeId"),X=b.edges;if(w!=="replace_edges"&&!Q)throw Error(`\`nodeId\` is required for ${w} when calling \`edit_sequence_graph\`.`);if(w==="replace_edges"&&Q)throw Error("`nodeId` is not used with `replace_edges` when calling `edit_sequence_graph`.");let Y=w==="move_node"||w==="duplicate_node";if(Y&&(G?1:0)+(D?1:0)!==1)throw Error(`Provide exactly one of \`afterNodeId\` or \`beforeNodeId\` for ${w} when calling \`edit_sequence_graph\`.`);if(!Y&&(G||D))throw Error(`\`afterNodeId\` and \`beforeNodeId\` are not used with ${w} when calling \`edit_sequence_graph\`.`);if((w==="replace_edges"||w==="delete_node"&&X!==void 0)&&(!Array.isArray(X)||X.length===0))throw Error(`\`edges\` must contain the complete replacement topology for ${w} when calling \`edit_sequence_graph\`.`);if((w==="move_node"||w==="duplicate_node")&&X!==void 0)throw Error(`\`edges\` is not used with ${w} when calling \`edit_sequence_graph\`.`);let H=Array.isArray(X)?X.map((J,z)=>{if(!y(J))throw Error(`\`edges\` item ${z+1} must be an object when calling \`edit_sequence_graph\`.`);let O=Z("edit_sequence_graph",J,"sourceNodeId"),q=Z("edit_sequence_graph",J,"targetNodeId");if(J.condition!==void 0&&J.condition!==null&&!y(J.condition))throw Error(`\`edges\` item ${z+1} \`condition\` must be an object when calling \`edit_sequence_graph\`.`);return{sourceNodeId:O,targetNodeId:q,...y(J.condition)?{condition:J.condition}:{}}}):void 0;return{...b.confirmStructuralChange!==void 0&&{confirmStructuralChange:b.confirmStructuralChange},graphEdit:{action:w,expectedRevision:$,...Q?{nodeId:Q}:{},...G?{afterNodeId:G}:{},...D?{beforeNodeId:D}:{},...H?{edges:H}:{}}}}function CJ(b){let w=b.type==="sms",$;if(w){FW("insert_sequence_step","SMS step",b);let Q=P(b,"text"),G=Array.isArray(b.blocks)&&b.blocks.length>0;if(Q===void 0&&!G)throw Error("Provide `text` (or `blocks`) when inserting an SMS step with `insert_sequence_step`.");$={type:"sms"};for(let D of["text","blocks","imageUrls","label","name","ineligibleAction","delay","delayMs","waitUntil"])if(b[D]!==void 0)$[D]=b[D]}else{_b("insert_sequence_step",b,{requireContent:!0}),c$("insert_sequence_step","email step",b),$={subject:Z("insert_sequence_step",b,"subject")};for(let Q of["name","previewText","html","blocks","delay","delayMs","waitUntil","senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName"])if(b[Q]!==void 0)$[Q]=b[Q]}let W={steps:[$]};if(b.afterNodeId!==void 0)W.afterNodeId=b.afterNodeId;return{...b.confirmStructuralChange!==void 0&&{confirmStructuralChange:b.confirmStructuralChange},insertSteps:W}}function uJ(b){let w=P(b,"subscriberId"),$=b.fieldValues,W=$===void 0?void 0:Array.isArray($)?$:void 0;if($!==void 0&&W===void 0)throw Error("`fieldValues` must be an array when calling `cancel_sequence_enrollments`.");let Q=W?.map((X)=>typeof X==="string"?X.trim():"").filter((X)=>X.length>0)??[];if(W?.some((X)=>typeof X!=="string")||W!==void 0&&Q.length===0)throw Error("`fieldValues` must contain at least one non-empty string when calling `cancel_sequence_enrollments`.");if(w!==void 0===Q.length>0)throw Error("Provide exactly one target when calling `cancel_sequence_enrollments`: `subscriberId` or `fieldValues`.");let G=P(b,"fieldPath"),D=P(b,"reason");return{...w!==void 0&&{subscriberId:w},...G!==void 0&&{fieldPath:G},...Q.length>0&&{fieldValues:Q},...typeof b.dryRun==="boolean"&&{dryRun:b.dryRun},...D!==void 0&&{reason:D}}}function xJ(b){_b("create_campaign",b),Y1("create_campaign",b);let w=P(b,"prompt")!==void 0,$=b.html!==void 0,W=b.blocks!==void 0,Q=b.templateId!==void 0;if(b.prompt!==void 0&&!w)throw Error("`prompt` cannot be empty when calling `create_campaign`.");if(w&&($||W||Q))throw Error("Provide either `prompt`, `html`, `blocks`, or `templateId` when calling `create_campaign`, not multiple content sources.");if(!w&&(b.style!==void 0||b.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_campaign`.");if(!w&&P(b,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_campaign`.")}function yJ(b){_b("create_template",b),Y1("create_template",b);let w=P(b,"prompt")!==void 0,$=[w,b.html!==void 0,b.blocks!==void 0].filter(Boolean).length;if(b.prompt!==void 0&&!w)throw Error("`prompt` cannot be empty when calling `create_template`.");if($!==1)throw Error("Provide exactly one of `prompt`, `html`, or `blocks` when calling `create_template`.");if(!w&&(b.style!==void 0||b.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_template`.");if(!w&&P(b,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_template`.")}function hJ(b){if(P(b,"scheduledAt")===void 0)throw Error("`scheduledAt` is required when calling `schedule_campaign`.");if(b.targetLists!==void 0&&!y(b.targetLists))throw Error("`targetLists` must be an object when calling `schedule_campaign`.");if(b.sendTimeOptimization!==void 0){if(typeof b.sendTimeOptimization!=="boolean")throw Error("`sendTimeOptimization` must be a boolean when calling `schedule_campaign`.")}if(b.spreadOverHours!==void 0){if(typeof b.spreadOverHours!=="number"||!Number.isInteger(b.spreadOverHours)||b.spreadOverHours<1||b.spreadOverHours>72)throw Error("`spreadOverHours` must be an integer between 1 and 72 when calling `schedule_campaign`.")}if(b.recurringInterval!==void 0&&b.recurringInterval!=="weekly"&&b.recurringInterval!=="monthly")throw Error("`recurringInterval` must be 'weekly' or 'monthly' when calling `schedule_campaign`.")}function n$(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 fJ(b){let w=new Set(["companyId","domain","verify"]),$=Object.keys(b).filter((W)=>!w.has(W));if($.length>0)throw Error(`\`update_landing_page_domain_settings\` accepts only \`domain\` and \`verify\`. Unsupported field${$.length===1?"":"s"}: ${$.map((W)=>`\`${W}\``).join(", ")}.`);if(b.domain===void 0&&b.verify!==!0)throw Error("Provide `domain` or `verify: true` when calling `update_landing_page_domain_settings`.");return{...b.domain!==void 0&&{domain:b.domain},...typeof b.verify==="boolean"&&{verify:b.verify}}}function cJ(b){_b("create_transactional_email",b);let w=P(b,"prompt")!==void 0,$=b.html!==void 0,W=b.blocks!==void 0;if(b.prompt!==void 0&&!w)throw Error("`prompt` cannot be empty when calling `create_transactional_email`.");if(w&&($||W))throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`, not multiple content sources.");if(!w&&(b.style!==void 0||b.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_transactional_email`.");if(!w&&!$&&!W)throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`.");if(!w&&P(b,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_transactional_email`.")}var X0={type:"object",description:"Update Subscriber config. firstName, lastName, and customAttributeUpdates values may use trigger-event merge tags such as {{event.plan}}. Number and boolean values must be a literal or one standalone merge tag and are coerced after resolution.",properties:{label:{type:"string"},firstName:{type:["string","null"],description:"First name literal or merge tag; null clears the field."},lastName:{type:["string","null"],description:"Last name literal or merge tag; null clears the field."},status:{type:"string",enum:["active","unsubscribed","bounced"]},customAttributeUpdates:{type:"array",items:{type:"object",properties:{name:{type:"string"},value:{type:["string","number","boolean","null"],description:"Literal scalar, null to delete, or a standalone merge tag such as {{event.plan}}, {{event.amount}}, or {{event.active}}."},valueType:{type:"string",enum:["text","number","boolean"]}},required:["name","value"]}}},additionalProperties:!0},KW={senderProfileId:{type:"string",description:"Sender profile for this step's From identity. Mutually exclusive with fromEmail."},fromEmail:{type:"string",description:"From address for this step. Its domain must be configured and verified. Mutually exclusive with senderProfileId."},fromName:{type:"string",description:"Display name override for this step. Alone it only changes the visible name; with fromEmail it also names a newly created sender profile."},replyProfileId:{type:"string",description:"Reply profile for this step's Reply-To. Mutually exclusive with replyTo."},replyTo:{type:"string",description:"Reply-To address for this step. Mutually exclusive with replyProfileId."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo."}},g$={type:"object",description:"A step to create inside a sequence path. Use type:'delay' for a standalone delay, type:'email' for an email, type:'create_discount' for a discount action, or type:'condition' for a condition gate.",properties:{type:{type:"string",enum:["email","delay","create_discount","discount","update_subscriber","condition","webhook"],description:"Sequence path step type. Omit for email steps; use delay for standalone waits or update_subscriber for action_update_attributes."},nodeType:{type:"string",enum:["logic_delay","action_email","action_create_discount","action_add_tag","action_remove_tag","action_add_to_list","action_remove_from_list","action_update_attributes","logic_wait_for_event","logic_condition","action_webhook"],description:"Advanced sequence path node type. Prefer type unless creating a non-email action."},config:{...X0,description:"Config for advanced nodeType steps. For action_update_attributes, use the documented Update Subscriber fields and trigger-event merge tags; other node types accept their normal config fields.",additionalProperties:!0},subject:{type:"string",description:"Email subject. Required for email steps."},previewText:{type:"string",description:"Email preview text."},blocks:{type:"array",description:W1,items:{type:"object"}},html:{type:"string",description:"HTML content for email steps. Stored as one raw HTML block. Use this for imported provider HTML."},delay:G1,delayMs:{type:"number",description:"Delay in milliseconds. Useful for standalone type:'delay' steps."},waitUntil:Q1,name:{type:"string",description:"Email template name for email steps."},senderProfileId:{type:"string",description:"Sender profile for this email step. Omit to inherit the effective identity of the nearest sequence email. After a branch merge, only fields shared by every incoming path are inherited; conflicting fields use sequence or company defaults."},fromEmail:{type:"string",description:"From address for this email step. Its domain must be verified. Mutually exclusive with senderProfileId."},fromName:{type:"string",description:"Display name override for this email step. With fromEmail, also names a newly created sender profile."},replyProfileId:{type:"string",description:"Reply profile for this email step. Omit to inherit the effective Reply-To of the nearest sequence email. After a branch merge, only fields shared by every incoming path are inherited; conflicting fields use sequence or company defaults."},replyTo:{type:"string",description:"Reply-To address for this email step. Mutually exclusive with replyProfileId."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo."},discount:{type:"object",description:"Discount configuration for create_discount steps. Same shape as create_sequence steps.",additionalProperties:!0},label:{type:"string",description:"Node label for discount or advanced node steps."},provider:{type:"string",enum:["stripe","shopify"],description:"Discount provider. Use stripe to dynamically create a Stripe coupon plus promotion code, or shopify to dynamically create a Shopify Admin discount code."},discountType:{type:"string",enum:["percent","amount"]},percentOff:{type:"number"},amountOff:{type:"number"},currency:{type:"string"},duration:{type:"string",enum:["once","forever","repeating"]},durationInMonths:{type:"number"},appliesToAllPlans:{type:"boolean"},planIds:{type:"array",items:{type:"string"}},codePrefix:{type:"string"},maxRedemptions:{type:"number"},lockToSubscriber:{type:"boolean"},expiresAt:{type:"string"},expiresInHours:{type:"number"}},additionalProperties:!1};function nJ(b){if(!b||typeof b!=="object")return null;let w=b;if(w.success!==!1)return null;if(typeof w.error==="string")return Error(w.error);if(w.error&&typeof w.error==="object"&&typeof w.error.message==="string")return Error(w.error.message);if(typeof w.message==="string")return Error(w.message);return Error("The tool returned an unsuccessful response.")}function MW(b){return b.trim().toLowerCase().replace(/\s+/g,"-")}function 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 mJ(b,w){let $=typeof b.limit==="number"&&Number.isFinite(b.limit)?Math.max(1,Math.trunc(b.limit)):void 0,W=Math.min(100,Math.max(1,$??100)),Q=[],G=1,D=0,X=0,Y=0;while(!0){let J=bM({query:b.query,tags:b.tags,list:b.list,listId:b.listId,listName:b.listName,segmentId:b.segmentId,status:b.status,page:G,pageSize:W}),z=await A("GET",`/api/v1/subscribers?${J.toString()}`,void 0,w);D=z.pagination?.total??z.subscribers.length,X=z.pagination?.totalPages??1,Y+=1,Q.push(...z.subscribers??[]);let O=$!==void 0&&Q.length>=$,q=z.pagination?G>=z.pagination.totalPages:(z.subscribers??[]).length<W;if(O||q)break;G+=1}let H=$!==void 0?Q.slice(0,$):Q;return{success:!0,subscribers:H,pagination:{page:1,limit:W,total:D,totalPages:X,fetchedPages:Y},returned:H.length,truncated:$!==void 0&&D>0&&H.length<D}}function wM(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 $=wM(w);if(!$.email&&!$.externalId)throw Error(`Provide either \`email\` or \`externalId\` when calling \`${b}\`.`);return $}function m$(b,w){let $=new URLSearchParams;if(w?.includeMachineEngagement)$.set("includeMachineEngagement","true");let W=$.toString(),Q=W?`?${W}`:"";if(b.email)return`/api/v1/subscribers/${encodeURIComponent(b.email)}${Q}`;return $.set("externalId",String(b.externalId)),`/api/v1/subscribers/external?${$.toString()}`}function IW(b){if(b.email)return`/api/v1/subscribers/${encodeURIComponent(b.email)}/notes`;let w=new URLSearchParams;return w.set("externalId",String(b.externalId)),`/api/v1/subscribers/external/notes?${w.toString()}`}async function Y0(b,w,$){return A("GET",m$(b,$),void 0,w)}function Ub(b,w,$,W){let Q=P(w,$);if(Q===void 0)return;if(!W.includes(Q))throw Error(`\`${$}\` must be one of ${W.join(", ")} when calling \`${b}\`.`);return Q}function H0(b,w,$,W){let Q=Z(b,w,$);if(!W.includes(Q))throw Error(`\`${$}\` must be one of ${W.join(", ")} when calling \`${b}\`.`);return Q}function zw(b,w,$,W,Q){let G=w[$];if(G===void 0)return;if(typeof G!=="number"||!Number.isInteger(G)||G<W||G>Q)throw Error(`\`${$}\` must be an integer between ${W} and ${Q} when calling \`${b}\`.`);return G}function $M(b,w){let $=[],W=Ub(b,w,"eventType",k$);if(W)$.push(W);if(w.eventTypes!==void 0){if(!Array.isArray(w.eventTypes))throw Error(`\`eventTypes\` must be an array when calling \`${b}\`.`);w.eventTypes.forEach((Q,G)=>{if(typeof Q!=="string")throw Error(`\`eventTypes\` item ${G+1} must be a string when calling \`${b}\`.`);let D=Q.trim();if(!k$.includes(D))throw Error(`\`eventTypes\` item ${G+1} must be one of ${k$.join(", ")} when calling \`${b}\`.`);$.push(D)})}return[...new Set($)]}function ZW(b,w){let $=new URLSearchParams,W=$M(b,w);if(W.length>0)$.set("eventTypes",W.join(","));let Q=Ub(b,w,"period",["1h","24h","7d","30d","90d"]);if(Q)$.set("period",Q);let G=P(w,"start");if(G)$.set("start",G);let D=P(w,"end");if(D)$.set("end",D);let X=zw(b,w,"page",1,1e6);if(X!==void 0)$.set("page",String(X));let Y=zw(b,w,"limit",1,500);if(Y!==void 0)$.set("limit",String(Y));if(w.includeMachineEngagement===!0)$.set("includeMachineEngagement","true");return $}function jW(b,w){if(w.events===void 0)return;if(!Array.isArray(w.events))throw Error(`\`events\` must be an array when calling \`${b}\`.`);let $=w.events.map((W,Q)=>{if(typeof W!=="string"||!X1.includes(W))throw Error(`\`events\` item ${Q+1} must be one of ${X1.join(", ")} when calling \`${b}\`.`);return W});if($.length===0)throw Error(`\`events\` must include at least one event type when calling \`${b}\`.`);return $}function VW(b,w){if(!Array.isArray(w.emails))throw Error(`\`emails\` must be an array when calling \`${b}\`.`);let $=[];if(w.emails.forEach((W,Q)=>{if(typeof W!=="string")throw Error(`\`emails\` item ${Q+1} must be a string when calling \`${b}\`.`);let G=W.trim();if(G.length>0)$.push(G)}),$.length===0)throw Error(`\`emails\` must include at least one email address when calling \`${b}\`.`);if($.length>JW)throw Error(`\`emails\` must include no more than ${JW} email addresses when calling \`${b}\`. Split larger batches into multiple calls.`);return $}function gJ(b,w,$,W){let Q=w[$];if(Q===void 0)return;if(!Array.isArray(Q))throw Error(`\`${$}\` must be an array when calling \`${b}\`.`);let G=[];if(Q.forEach((D,X)=>{if(typeof D!=="string")throw Error(`\`${$}\` item ${X+1} must be a string when calling \`${b}\`.`);let Y=D.trim();if(Y.length>0)G.push(Y)}),G.length===0)throw Error(`\`${$}\` must include at least one ${W} when calling \`${b}\`.`);return G}function iJ(b){let $=gJ("enroll_subscribers_in_sequence",b,"emails","email address"),W=gJ("enroll_subscribers_in_sequence",b,"subscriberIds","subscriber ID"),Q=($?.length??0)+(W?.length??0);if(Q===0)throw Error("Provide `emails` or `subscriberIds` when calling `enroll_subscribers_in_sequence`.");if(Q>zW)throw Error(`\`emails\` and \`subscriberIds\` must include no more than ${zW} total targets when calling \`enroll_subscribers_in_sequence\`. Split larger batches into multiple calls.`);let G=P(b,"targetNodeId");return{...$!==void 0&&{emails:$},...W!==void 0&&{subscriberIds:W},...G!==void 0&&{targetNodeId:G}}}import{readFileSync as WM,statSync as QM}from"node:fs";import{basename as GM}from"node:path";var DM={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 XM(b){let w=b.split(".").pop()?.toLowerCase()??"";return DM[w]??null}var YM=104857600;async function lJ(b,w){if(!z0())throw Error("`filePath` is only supported when the MCP server runs locally on your machine. Host the file somewhere public and pass `url` instead.");let $=XM(b);if(!$)throw Error("Unsupported file type. Use PDF, ePub, ZIP, image, audio, video, or text files.");let W=QM(b).size;if(W>YM)throw Error(`File is too large (${Math.round(W/1048576)}MB). Delivery files must be 100MB or smaller.`);let Q=WM(b),G=await A("POST","/api/v1/products/delivery/upload-url",{filename:GM(b),contentType:$,fileSizeBytes:W},w),D=await fetch(G.uploadUrl,{method:"PUT",headers:{"Content-Type":$},body:Q});if(!D.ok)throw Error(`File upload failed (${D.status})`);return{url:G.publicUrl,fileName:G.fileName,fileSizeBytes:W,mimeType:$}}async function i$(b){let w=P(b,"companyId");if(w)return w;let $=qw();if($)return $;try{return(await A("GET","/api/v1/account")).currentCompanyId??void 0}catch{return}}async function pJ(b,w){let $=await i$(w);if(!$)throw Error(`A company is required when calling \`${b}\`. Call \`get_account\`, then \`select_company\`, or pass \`companyId\` explicitly.`);return $}function H1(b,w){if(!y(b)||!w)return b;return{...b,url:w}}function oJ(b,w){if(!y(b))return b;return{...b,...w.campaign!==void 0&&{url:w.campaign},...w.campaignPreview!==void 0&&{previewUrl:w.campaignPreview}}}function J0(b,w,$){if(!Array.isArray(b)||!w)return b;return b.map((W)=>{if(!y(W))return W;let Q=P(W,"id");if(!Q)return W;let G=Yw({companyId:w,...$==="campaign"&&{campaignId:Q},...$==="landingPage"&&{landingPageId:Q},...$==="sequence"&&{sequenceId:Q},...$==="template"&&{emailId:Q},...$==="transactional"&&{transactionalId:Q}});if($==="campaign")return oJ(W,G.urls);let D=$==="sequence"?G.urls.sequence:$==="landingPage"?G.urls.landingPage:$==="template"?G.urls.email:G.urls.transactionalEmail;return H1(W,D)})}function HM(b){if(!Array.isArray(b))return b;return b.map((w)=>{if(!y(w))return w;let $=P(w,"id");if(!$)return w;let W=Yw({companyId:$});return{...w,url:W.urls.dashboard,settingsUrl:W.urls.settings}})}var NW=new Set(["get_account","select_company","create_company","get_company","update_company","list_campaigns","get_campaign","get_email_send","create_campaign","update_campaign","schedule_campaign","send_test_email","cancel_campaign","pause_campaign","resume_campaign","duplicate_campaign","resend_campaign_to_non_openers","list_landing_pages","get_landing_page","create_landing_page","update_landing_page","publish_landing_page","unpublish_landing_page","delete_landing_page","list_sequences","get_sequence","create_sequence","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 dJ(b,w,$){if(!y($)||!NW.has(b))return $;let W=y($.company)?$.company:void 0,G=P($,"selectedCompanyId")??P($,"currentCompanyId")??P($,"companyId")??(W?P(W,"id"):void 0)??(W?P(W,"companyId"):void 0)??await i$(w);if(!G)return $;let D=y($.campaign)?$.campaign:void 0,X=y($.sequence)?$.sequence:void 0,Y=y($.landingPage)?$.landingPage:void 0,H=y($.template)?$.template:void 0,J=y($.transactional)&&!Array.isArray($.transactional)?$.transactional:void 0,z={companyId:G,campaignId:P(w,"campaignId")??P($,"campaignId")??(D?P(D,"id"):void 0),landingPageId:P(w,"landingPageId")??P($,"landingPageId")??(Y?P(Y,"id"):void 0),sequenceId:P(w,"sequenceId")??P($,"sequenceId")??(X?P(X,"id"):void 0),emailId:P($,"templateId")??(H?P(H,"id"):void 0)??(J?P(J,"emailId"):void 0)??P(w,"templateId"),transactionalId:P(w,"transactionalId")??(J?P(J,"id"):void 0)??P(w,"idOrSlug"),emailSendId:P(w,"emailSendId")??P($,"emailSendId")??(y($.emailSend)?P($.emailSend,"id"):void 0),status:P(w,"status")},O=Yw(z),q=W?Yw({companyId:G}):void 0;return{...$,...Array.isArray($.companies)&&{companies:HM($.companies)},...Array.isArray($.campaigns)&&{campaigns:J0($.campaigns,G,"campaign")},...Array.isArray($.landingPages)&&{landingPages:J0($.landingPages,G,"landingPage")},...Array.isArray($.sequences)&&{sequences:J0($.sequences,G,"sequence")},...Array.isArray($.templates)&&{templates:J0($.templates,G,"template")},...Array.isArray($.transactional)&&{transactional:J0($.transactional,G,"transactional")},...W&&q!==void 0&&{company:{...W,url:q.urls.dashboard,settingsUrl:q.urls.settings}},...D&&O.urls.campaign!==void 0&&{campaign:oJ(D,O.urls)},...X&&O.urls.sequence!==void 0&&{sequence:H1(X,O.urls.sequence)},...Y&&O.urls.landingPage!==void 0&&{landingPage:H1(Y,O.urls.landingPage)},...H&&O.urls.email!==void 0&&{template:H1(H,O.urls.email)},...J&&O.urls.transactionalEmail!==void 0&&{transactional:H1(J,O.urls.transactionalEmail)},...y($.emailSend)&&O.urls.emailSend!==void 0&&{emailSend:H1($.emailSend,O.urls.emailSend)},appUrls:O.urls}}import{readFileSync as JM,statSync as zM}from"node:fs";import{basename as AM,extname as rJ}from"node:path";var EW=5242880,OM=Math.ceil(EW/3)*4,qM=Math.ceil(OM*1.05)+256,eJ={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"},LM=new Set(Object.values(eJ));function TW(b){return b?.split(";")[0]?.trim().toLowerCase()||void 0}function UM(b){return eJ[rJ(b).toLowerCase()]}function BM(b){let w=rJ(b);return(w?b.slice(0,-w.length):b).replace(/[-_]+/g," ").trim()||"Image"}function PM(b){if(b.length>qM)throw Error("Image assets must be 5MB or smaller.")}function FM(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)>EW)throw Error("Image assets must be 5MB or smaller.")}function KM(b){PM(b);let w=b.trim(),$=/^data:([^;,]+);base64,([\s\S]+)$/i.exec(w),W=$?.[2]??w;FM(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:TW($[1])}:{}}}function tJ(b){if(b<=0)throw Error("The image file is empty.");if(b>EW)throw Error("Image assets must be 5MB or smaller.")}function MM(b){let w=UM(b.filename)??TW(b.explicitContentType)??TW(b.dataUrlContentType);if(!w||!LM.has(w))throw Error("Unsupported image type. Use PNG, JPEG, GIF, or WebP.");return w}function IM(b){let w,$,W;if(b.filePath!==void 0){if(!z0())throw Error("`filePath` is only supported when the MCP server runs locally on your machine. For a remote MCP connection, pass `imageBase64` and `filename` instead.");let G=zM(b.filePath).size;tJ(G),w=JM(b.filePath),$=b.filename??AM(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=KM(b.imageBase64);w=G.bytes,W=G.dataUrlContentType,$=b.filename,tJ(w.byteLength)}let Q=MM({filename:$,explicitContentType:b.contentType,dataUrlContentType:W});return{bytes:w,filename:$,contentType:Q,altText:b.altText??BM($)}}async function sJ(b){let w=IM(b),$=w.bytes.byteLength,W=await A("POST","/api/v1/media/upload-url",{filename:w.filename,contentType:w.contentType,fileSizeBytes:$},b.companyId);return await lW(W.uploadUrl,w.bytes,w.contentType,b.companyId),(await A("POST","/api/v1/media/complete-upload",{key:W.key,filename:W.fileName,contentType:w.contentType,fileSizeBytes:$,...b.sourceWidth!==void 0&&{width:b.sourceWidth},...b.sourceHeight!==void 0&&{height:b.sourceHeight},altText:w.altText},b.companyId)).asset}var ZM={type:"boolean",description:"Whether the Sequenzy operation succeeded."},jM={type:"string",description:"Human-readable status, confirmation, or next-step message."},VM={type:"string",description:"Additional context about the result."};function o(b){return{type:"object",description:b,additionalProperties:!0}}function NM(b){return{type:"array",description:b,items:o("One item in the returned collection.")}}function N(b){return{type:"string",description:b}}function Kb(b){return{type:"number",description:b}}function Sb(b){return{type:"boolean",description:b}}function F(b){return o(`The ${b} record returned by Sequenzy.`)}function l(b){return NM(`List of ${b} records returned by Sequenzy.`)}var TM={appUrls:o("Dashboard URLs for relevant Sequenzy resources."),url:N("Primary dashboard URL for this result."),settingsUrl:N("Company settings URL when available.")},EM={success:ZM,message:jM,note:VM,items:{type:"array",description:"Fallback array wrapper used only when a tool returns a bare array.",items:o("One returned item.")},value:o("Fallback object wrapper used only when a tool returns a non-object value.")},_M={get_account:{account:F("account"),companies:l("company"),apiKeyPermissions:o("Current API key preset and scopes, whether common marketing work is discoverable, any missing marketing read scopes, and the API Keys management URL."),currentCompanyId:N("Company ID selected by the authenticated API key, when available."),selectedCompanyId:N("Company ID selected locally for subsequent MCP calls, when available.")},select_company:{companyId:N("Selected company ID."),companyName:N("Selected company name.")},get_app_urls:{dashboard:N("Company dashboard URL."),settings:N("Company settings URL."),campaign:N("Campaign editor URL."),landingPage:N("Landing page editor URL."),sequence:N("Sequence editor URL."),email:N("Email editor URL."),transactionalEmail:N("Transactional email URL."),emailSend:N("Sent email detail URL."),domain:N("Sending domain settings URL."),urls:o("All generated URLs keyed by resource type.")},create_company:{company:F("company"),autoSelected:Sb("Whether the new company was selected for subsequent MCP calls.")},update_company:{company:F("company")},get_company:{company:F("company")},get_sync_rules:{syncRules:{type:"array",description:"Effective sync rules for the company.",items:o("One sync rule.")},isDefault:Sb("Whether the company still uses the platform default rules.")},update_sync_rules:{syncRules:{type:"array",description:"Effective sync rules after the update.",items:o("One sync rule.")},isDefault:Sb("Whether the company now uses the platform default rules.")},get_shopify_automation_settings:{browseAbandonment:o("Effective browse-abandonment settings (defaults applied)."),priceDrop:o("Effective price-drop settings (defaults applied)."),shopDomain:N("Connected Shopify store domain.")},update_shopify_automation_settings:{browseAbandonment:o("Effective browse-abandonment settings after the update."),priceDrop:o("Effective price-drop settings after the update."),shopDomain:N("Connected Shopify store domain.")},create_api_key:{apiKey:o("Created API key metadata: the newly created secret in `key`, plus `scopes` listing the assigned permission scopes (null when the key has full access)."),key:N("Newly created API key if the API response uses the short key field.")},list_websites:{websites:l("sender website")},add_website:{website:F("Sending domain with the SPF, DKIM, MAIL FROM, and inbound DNS records required for setup.")},add_sending_domain:{website:F("Sending domain with the SPF, DKIM, MAIL FROM, and inbound DNS records required for setup.")},check_website:{website:F("sender website"),ready:Sb("Whether the sender website is ready."),status:N("Current processing or verification status.")},verify_sending_domain:{website:F("Sending domain with current aggregate, SPF, DKIM, and MAIL FROM verification details."),verified:Sb("Whether the sending domain passed the fresh verification check."),message:N("Verification result summary.")},get_integration_guide:{guide:F("integration guide"),code:N("Generated integration code or example."),steps:{type:"array",description:"Setup steps for the requested integration.",items:o("One setup step.")}},add_subscriber:{subscriber:F("subscriber")},update_subscriber:{subscriber:F("subscriber")},remove_subscriber:{subscriber:F("subscriber"),hardDeleted:Sb("Whether the subscriber was permanently deleted.")},get_subscriber:{subscriber:F("subscriber")},list_subscriber_notes:{notes:l("subscriber note")},add_subscriber_note:{note:F("subscriber note")},delete_subscriber_note:{id:N("Deleted subscriber note ID."),deleted:Sb("Whether the subscriber note was deleted.")},search_subscribers:{subscribers:l("subscriber"),pagination:o("Pagination metadata."),returned:Kb("Number of subscribers returned."),truncated:Sb("Whether the result was truncated by the requested limit.")},list_products:{products:l("product")},upsert_products:{products:l("product"),created:Kb("Number of products created."),updated:Kb("Number of products updated.")},delete_product:{productId:N("Deleted product ID.")},attach_product_file:{product:F("product"),delivery:F("digital delivery file")},remove_product_file:{product:F("product")},upload_image_asset:{asset:F("hosted image asset"),imageBlock:o("Ready-to-insert Sequenzy image block using the hosted asset URL.")},sync_products:{job:F("product sync job"),jobId:N("Queued product sync job ID.")},list_tags:{tags:l("tag")},create_tag:{tag:F("tag")},update_tag:{tag:F("tag")},delete_tag:{tagId:N("Deleted tag ID.")},list_lists:{lists:l("list")},create_list:{list:F("list")},update_list:{list:F("list")},delete_list:{listId:N("Deleted list ID.")},add_subscribers_to_list:{list:F("list"),added:Kb("Number of subscribers added to the list."),skipped:Kb("Number of subscribers skipped.")},remove_subscribers_from_list:{list:F("list"),removed:Kb("Number of subscribers removed from the list."),skipped:Kb("Number of subscribers skipped.")},list_segments:{segments:l("segment")},create_segment:{segment:F("segment")},update_segment:{segment:F("segment")},delete_segment:{segmentId:N("Deleted segment ID.")},get_segment_count:{count:Kb("Number of subscribers matching the segment."),segmentId:N("Segment ID that was counted.")},list_audience_syncs:{audienceSyncs:l("audience sync")},list_ad_accounts:{adAccounts:l("ad account")},create_audience_sync:{audienceSync:F("audience sync")},update_audience_sync:{audienceSync:F("audience sync")},delete_audience_sync:{audienceSyncId:N("Deleted audience sync ID.")},sync_audience_now:{audienceSync:F("audience sync"),job:F("audience sync job"),jobId:N("Queued audience sync job ID.")},list_templates:{templates:l("email template")},get_template:{template:F("email template")},create_template:{template:F("email template")},update_template:{template:F("email template")},set_template_localization:{templateId:N("Localized template ID."),localization:F("template localization")},sync_template_localizations:{templateId:N("Template ID queued for localization."),queuedLocales:{type:"array",description:"Locale codes queued for AI translation.",items:N("One queued locale code.")},queuedVariantCount:Kb("Number of localized variants queued for translation.")},delete_template:{templateId:N("Deleted template ID.")},list_ab_tests:{abTests:l("A/B test")},get_ab_test:{abTest:F("A/B test")},get_ab_test_stats:{abTest:F("A/B test"),stats:F("A/B test statistics")},restart_ab_test:{abTest:F("A/B test")},update_ab_test_variant:{abTest:F("A/B test"),variant:F("A/B test variant")},create_ab_test:{abTest:F("A/B test")},add_ab_test_variant:{abTest:F("A/B test"),variant:F("A/B test variant")},delete_ab_test_variant:{abTest:F("A/B test"),variantId:N("Deleted A/B test variant ID.")},delete_ab_test:{abTestId:N("Deleted A/B test ID.")},list_campaigns:{campaigns:l("campaign")},get_campaign:{campaign:F("campaign")},get_email_send:{emailSend:F("email send"),events:l("email delivery event")},get_recipient_suppression:{suppression:F("recipient suppression status")},remove_recipient_suppression:{removed:Sb("Whether stale bounce suppression was removed."),removedLocalBounce:Sb("Whether the platform-local bounce block was removed."),removedSesRegions:{type:"array",description:"AWS SES regions where a bounce suppression was removed.",items:N("One AWS SES region.")},remainingSuppression:F("recipient suppression status after cleanup")},create_campaign:{campaign:F("campaign")},update_campaign:{campaign:F("campaign")},schedule_campaign:{campaign:F("campaign"),scheduledAt:N("Scheduled send timestamp.")},send_test_email:{emailSendId:N("Durable test email delivery ID."),recipientEmail:N("Test email recipient.")},send_test_sms:{smsSendId:N("Created test SMS send ID."),toPhone:N("Normalized E.164 destination phone.")},cancel_campaign:{campaign:F("campaign")},pause_campaign:{campaign:F("campaign")},resume_campaign:{campaign:F("campaign")},delete_campaign:{campaignId:N("Deleted campaign ID.")},duplicate_campaign:{campaign:F("duplicated campaign")},resend_campaign_to_non_openers:{campaign:F("non-opener resend draft campaign"),estimatedNonOpenerCount:Kb("Estimated number of subscribers who haven't opened the original campaign.")},list_forms:{forms:l("saved form")},create_form:{form:F("saved form"),embed:o("Public action URL plus JavaScript, native form, and fetch snippets.")},get_form_embed:{form:F("saved form"),embed:o("Public action URL plus JavaScript, native form, and fetch snippets.")},list_landing_pages:{landingPages:l("landing page")},get_landing_page:{landingPage:F("landing page")},create_landing_page:{landingPage:F("landing page")},update_landing_page:{landingPage:F("landing page")},delete_landing_page:{landingPageId:N("Deleted landing page ID.")},publish_landing_page:{landingPage:F("landing page")},unpublish_landing_page:{landingPage:F("landing page")},connect_landing_page_domain:{landingPage:F("landing page"),domain:N("Connected landing page domain.")},update_landing_page_domain_settings:{landingPage:F("landing page"),domain:N("Landing page domain.")},list_sequences:{sequences:l("sequence")},get_sequence:{sequence:F("sequence")},create_sequence:{sequence:F("sequence"),eventTrackingCode:N("Ready-to-adapt code for sending a custom trigger event, including any matching-field property."),eventTracking:o("Custom-event endpoint, payload contract, example payload, documentation URL, and get_integration_guide arguments."),requiredEvents:{type:"array",description:"Event names the application or an integration must send.",items:N("One required event name.")}},update_sequence:{sequence:F("sequence")},update_sequence_node:{sequence:F("sequence")},update_sequence_nodes:{sequence:F("sequence")},edit_sequence_graph:{sequence:F("sequence")},insert_sequence_step:{sequence:F("sequence"),insertedNodeIds:{type:"array",description:"Node IDs created for the inserted step, including any delay node.",items:N("Inserted automation node ID.")},insertedEmailIds:{type:"array",description:"Email template IDs created for the inserted step.",items:N("Inserted email template ID.")},insertedEmailCount:Kb("Number of email steps inserted.")},enable_sequence:{sequence:F("sequence")},disable_sequence:{sequence:F("sequence")},pause_sequence_enrollments:{sequenceId:N("Sequence ID."),enrollmentPaused:Sb("Whether new sequence enrollments are paused.")},resume_sequence_enrollments:{sequenceId:N("Sequence ID."),enrollmentPaused:Sb("Whether new sequence enrollments are paused.")},enroll_subscribers_in_sequence:{sequence:F("sequence"),enrollments:l("sequence enrollment"),enrolled:Kb("Number of subscribers enrolled."),skipped:Kb("Number of subscribers skipped.")},cancel_sequence_enrollments:{sequence:F("sequence"),cancelled:Kb("Number of enrollments cancelled."),skipped:Kb("Number of enrollments skipped.")},delete_sequence:{sequenceId:N("Deleted sequence ID.")},list_transactional_emails:{transactional:l("transactional email")},get_transactional_email:{transactional:F("transactional email")},create_transactional_email:{transactional:F("transactional email")},update_transactional_email:{transactional:F("transactional email")},send_email:{emailSendId:N("Durable transactional delivery ID."),transactional:F("transactional email")},get_stats:{stats:F("account or company statistics")},get_campaign_stats:{campaign:F("campaign"),stats:F("campaign statistics"),clickedLinks:{type:"array",description:"Per-link click breakdown, most clicked first (top 20). Each entry has url, clicks, and percentage (that link's share of every recorded link click). Present only when the campaign has tracked link clicks.",items:o("One clicked link with url/clicks/share.")},polls:{type:"array",description:`Poll and NPS summaries. Each subscriber counts once per campaign poll block using their latest answer to that block; NPS entries include score, average, and promoter/passive/detractor counts. To list the exact historical respondents behind a count, use the summary blockId and the get_campaign_stats campaignId with create_segment. ${_w} A summary's attributeKey identifies the subscriber attribute that stores their current/latest response and may be overwritten by a later poll that reuses the key.`,items:o("One poll or NPS results summary.")}},get_sequence_stats:{sequence:F("sequence"),stats:F("sequence statistics")},list_campaign_events:{events:l("campaign email event"),pagination:o("Pagination metadata.")},list_sequence_events:{events:l("sequence email event"),pagination:o("Pagination metadata.")},get_subscriber_activity:{activity:l("subscriber activity event"),subscribers:l("subscriber"),pagination:o("Pagination metadata.")},list_team_members:{members:l("team member"),invitations:l("team invitation")},invite_team_member:{invitation:F("team invitation")},cancel_team_invitation:{invitationId:N("Cancelled invitation ID.")},list_conversations:{conversations:l("inbox conversation"),pagination:o("Pagination metadata.")},get_conversation:{conversation:F("inbox conversation"),messages:l("conversation message")},reply_to_conversation:{conversation:F("inbox conversation"),message:F("conversation message")},update_conversation_status:{conversation:F("inbox conversation")},mark_conversation_read:{conversation:F("inbox conversation")},list_webhooks:{webhooks:l("outbound webhook")},create_webhook:{webhook:F("outbound webhook")},update_webhook:{webhook:F("outbound webhook")},delete_webhook:{webhookId:N("Deleted outbound webhook ID.")},test_webhook:{webhook:F("outbound webhook"),delivery:F("test webhook delivery")},list_webhook_deliveries:{deliveries:l("webhook delivery")},replay_webhook_delivery:{delivery:F("webhook delivery"),job:F("webhook replay job")},generate_email:{email:F("generated email"),html:N("Generated HTML email body."),blocks:{type:"array",description:"Generated Sequenzy email blocks, wrapped with company branding (logo + footer) unless applyBranding was false.",items:o("One generated email block.")},subject:N("Generated subject line."),previewText:N("Generated inbox preview text.")},generate_sequence:{sequence:F("persisted AI-generated sequence draft"),deprecated:Sb("Always true for this deprecated alias."),deprecationMessage:N("Migration guidance directing callers to create_sequence.")},generate_subject_lines:{subjectLines:{type:"array",description:"Generated subject line variants.",items:N("One generated subject line.")},variants:l("generated subject line variant")},generate_sms:{prompt:N("The prompt the messages were generated for."),messages:{type:"array",description:"Generated SMS message variants with encoding and segment counts.",items:o("One generated SMS message.")}},get_sms_settings:{sms:o("SMS add-on status: enabled, planEligible, creditsBalance, brandPrefix, numbers, readyToSend (paid plan or credits plus an active number).")},submit_feedback:{}};function SM(b){let w=_M[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:{...EM,...w,...NW.has(b)?TM:{}},additionalProperties:!0}}function aJ(b){return{...b,outputSchema:SM(b.name)}}function bz(b){if(y(b))return b;if(Array.isArray(b))return{items:b};return{value:b}}var wz=[{name:"list_ab_tests",description:"List A/B tests and their variants",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Optional sequence ID to filter automation A/B tests."}}}},{name:"get_ab_test",description:"Get A/B test details, variants, and per-locale localization sync status",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"}},required:["abTestId"]}},{name:"get_ab_test_stats",description:"Get A/B test aggregate stats and per-variant stats. Supports period or custom start/end ranges.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"},period:{type:"string",description:"Optional period: 1h, 24h, 7d, 30d, or 90d."},start:{type:"string",description:"Custom range start as ISO 8601. Requires end."},end:{type:"string",description:"Custom range end as ISO 8601. Requires start."},includeMachineEngagement:lb},required:["abTestId"]}},{name:"restart_ab_test",description:"Run another sequence A/B test after a winner is selected. By default the winner becomes the new control; pass sourceVariantId to use another variant as the control email.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID to restart"},sourceVariantId:{type:"string",description:"Optional variant ID to use as the new control email. Defaults to the selected winner."},testType:{type:"string",description:"Optional test type: subject or content."},winnerThreshold:{type:"number",description:"Optional number of subscribers before selecting a winner. Must be from 10 to 1000."},variantCount:{type:"number",description:"Optional total variants including the control. Must be from 2 to 4."}},required:["abTestId"],additionalProperties:!1}},{name:"update_ab_test_variant",description:"Update a draft A/B test variant. Provide at least one of subject, previewText, html, or blocks. Use either html or blocks, not both.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"},variantId:{type:"string",description:"A/B test variant ID"},subject:{type:"string",description:"Variant subject line"},previewText:{type:"string",description:"Variant preview text. Pass an empty string to clear it."},html:{type:"string",description:"Replacement HTML body. Mutually exclusive with blocks."},blocks:{type:"array",description:`${Jw} Mutually exclusive with html.`,items:{type:"object"}}},required:["abTestId","variantId"],additionalProperties:!1}},{name:"create_ab_test",description:"Create a campaign A/B test. Control variant A is created automatically from the campaign's current email; optionally provide extra variants. The campaign must be in draft or rejected status, and each campaign can only have one A/B test.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Draft campaign ID to create the A/B test for."},name:{type:"string",description:"Optional A/B test name."},testPercentage:{type:"number",description:"Percentage of the audience used for the test phase, from 5 to 50. Defaults to 20."},testDurationMinutes:{type:"number",description:"Test phase duration in minutes before the winner is selected, from 15 to 1440. Defaults to 240."},winnerCriteria:{type:"string",enum:["open_rate","click_rate"],description:"Winner selection criteria. Defaults to open_rate."},variants:{type:"array",description:"Optional extra variants to create in addition to control variant A.",items:{type:"object",properties:{subject:{type:"string",description:"Variant subject line."},previewText:{type:"string",description:"Variant preview text."},blocks:{type:"array",description:Jw,items:{type:"object"}}},required:["subject"]}}},required:["campaignId"]}},{name:"add_ab_test_variant",description:"Add a variant to a draft campaign A/B test. Variants cannot be added after the test has started.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"},subject:{type:"string",description:"Variant subject line."},previewText:{type:"string",description:"Variant preview text."},blocks:{type:"array",description:Jw,items:{type:"object"}}},required:["abTestId","subject"]}},{name:"delete_ab_test_variant",description:"Permanently delete a variant from a draft campaign A/B test. This cannot be undone. Variant A is the control and cannot be deleted, and the test must keep at least the minimum number of variants. Variants cannot be removed after the test has started.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"},variantId:{type:"string",description:"A/B test variant ID to delete."}},required:["abTestId","variantId"]}},{name:"delete_ab_test",description:"Permanently delete a campaign A/B test and all of its variants. This cannot be undone. Running tests (testing or winner_selected) cannot be deleted, and the linked campaign must be in draft or rejected status.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID to delete."}},required:["abTestId"]}}];var $z=[{name:"get_account",description:`Get current account information including available companies, the current API key's permission scopes, and the API Keys management URL. Call this after a missing-scope error to inspect access and find the replacement-key settings. IMPORTANT: If you have access to multiple companies, you MUST either:
29
+ `)}q.write("payload.value = newResult;"),q.write("return payload;");let v=q.compile();return(S,h)=>v(O,S,h)},G,D=Sw,X=!O0.jitless,H=X&&b4.value,J=w.catchall,z;b._zod.parse=(O,q)=>{z??(z=W.value);let B=O.value;if(!D(B))return O.issues.push({expected:"object",code:"invalid_type",input:B,inst:b}),O;if(X&&H&&q?.async===!1&&q.jitless!==!0){if(!G)G=Q(w.shape);if(O=G(O,q),!J)return O;return c9([],B,O,q,z,b)}return $(O,q)}});function $9(b,w,$,W){for(let G of b)if(G.issues.length===0)return w.value=G.value,w;let Q=b.filter((G)=>!Pw(G));if(Q.length===1)return w.value=Q[0].value,Q[0];return w.issues.push({code:"invalid_union",input:w.value,inst:$,errors:b.map((G)=>G.issues.map((D)=>yb(D,W,Rb())))}),w}var A4=U("$ZodUnion",(b,w)=>{e.init(b,w),d(b._zod,"optin",()=>w.options.some((Q)=>Q._zod.optin==="optional")?"optional":void 0),d(b._zod,"optout",()=>w.options.some((Q)=>Q._zod.optout==="optional")?"optional":void 0),d(b._zod,"values",()=>{if(w.options.every((Q)=>Q._zod.values))return new Set(w.options.flatMap((Q)=>Array.from(Q._zod.values)));return}),d(b._zod,"pattern",()=>{if(w.options.every((Q)=>Q._zod.pattern)){let Q=w.options.map((G)=>G._zod.pattern);return new RegExp(`^(${Q.map((G)=>L1(G.source)).join("|")})$`)}return});let $=w.options.length===1,W=w.options[0]._zod.run;b._zod.parse=(Q,G)=>{if($)return W(Q,G);let D=!1,X=[];for(let Y of w.options){let H=Y._zod.run({value:Q.value,issues:[]},G);if(H instanceof Promise)X.push(H),D=!0;else{if(H.issues.length===0)return H;X.push(H)}}if(!D)return $9(X,Q,b,G);return Promise.all(X).then((Y)=>{return $9(Y,Q,b,G)})}}),g9=U("$ZodDiscriminatedUnion",(b,w)=>{A4.init(b,w);let $=b._zod.parse;d(b._zod,"propValues",()=>{let Q={};for(let G of w.options){let D=G._zod.propValues;if(!D||Object.keys(D).length===0)throw Error(`Invalid discriminated union option at index "${w.options.indexOf(G)}"`);for(let[X,Y]of Object.entries(D)){if(!Q[X])Q[X]=new Set;for(let H of Y)Q[X].add(H)}}return Q});let W=fw(()=>{let Q=w.options,G=new Map;for(let D of Q){let X=D._zod.propValues?.[w.discriminator];if(!X||X.size===0)throw Error(`Invalid discriminated union option at index "${w.options.indexOf(D)}"`);for(let Y of X){if(G.has(Y))throw Error(`Duplicate discriminator value "${String(Y)}"`);G.set(Y,D)}}return G});b._zod.parse=(Q,G)=>{let D=Q.value;if(!Sw(D))return Q.issues.push({code:"invalid_type",expected:"object",input:D,inst:b}),Q;let X=W.value.get(D?.[w.discriminator]);if(X)return X._zod.run(Q,G);if(w.unionFallback)return $(Q,G);return Q.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:w.discriminator,input:D,path:[w.discriminator],inst:b}),Q}}),m9=U("$ZodIntersection",(b,w)=>{e.init(b,w),b._zod.parse=($,W)=>{let Q=$.value,G=w.left._zod.run({value:Q,issues:[]},W),D=w.right._zod.run({value:Q,issues:[]},W);if(G instanceof Promise||D instanceof Promise)return Promise.all([G,D]).then(([Y,H])=>{return W9($,Y,H)});return W9($,G,D)}});function J4(b,w){if(b===w)return{valid:!0,data:b};if(b instanceof Date&&w instanceof Date&&+b===+w)return{valid:!0,data:b};if(Bw(b)&&Bw(w)){let $=Object.keys(w),W=Object.keys(b).filter((G)=>$.indexOf(G)!==-1),Q={...b,...w};for(let G of W){let D=J4(b[G],w[G]);if(!D.valid)return{valid:!1,mergeErrorPath:[G,...D.mergeErrorPath]};Q[G]=D.data}return{valid:!0,data:Q}}if(Array.isArray(b)&&Array.isArray(w)){if(b.length!==w.length)return{valid:!1,mergeErrorPath:[]};let $=[];for(let W=0;W<b.length;W++){let Q=b[W],G=w[W],D=J4(Q,G);if(!D.valid)return{valid:!1,mergeErrorPath:[W,...D.mergeErrorPath]};$.push(D.data)}return{valid:!0,data:$}}return{valid:!1,mergeErrorPath:[]}}function W9(b,w,$){if(w.issues.length)b.issues.push(...w.issues);if($.issues.length)b.issues.push(...$.issues);if(Pw(b))return b;let W=J4(w.value,$.value);if(!W.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(W.mergeErrorPath)}`);return b.value=W.data,b}var i9=U("$ZodRecord",(b,w)=>{e.init(b,w),b._zod.parse=($,W)=>{let Q=$.value;if(!Bw(Q))return $.issues.push({expected:"record",code:"invalid_type",input:Q,inst:b}),$;let G=[];if(w.keyType._zod.values){let D=w.keyType._zod.values;$.value={};for(let Y of D)if(typeof Y==="string"||typeof Y==="number"||typeof Y==="symbol"){let H=w.valueType._zod.run({value:Q[Y],issues:[]},W);if(H instanceof Promise)G.push(H.then((J)=>{if(J.issues.length)$.issues.push(...ww(Y,J.issues));$.value[Y]=J.value}));else{if(H.issues.length)$.issues.push(...ww(Y,H.issues));$.value[Y]=H.value}}let X;for(let Y in Q)if(!D.has(Y))X=X??[],X.push(Y);if(X&&X.length>0)$.issues.push({code:"unrecognized_keys",input:Q,inst:b,keys:X})}else{$.value={};for(let D of Reflect.ownKeys(Q)){if(D==="__proto__")continue;let X=w.keyType._zod.run({value:D,issues:[]},W);if(X instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(X.issues.length){$.issues.push({code:"invalid_key",origin:"record",issues:X.issues.map((H)=>yb(H,W,Rb())),input:D,path:[D],inst:b}),$.value[X.value]=X.value;continue}let Y=w.valueType._zod.run({value:Q[D],issues:[]},W);if(Y instanceof Promise)G.push(Y.then((H)=>{if(H.issues.length)$.issues.push(...ww(D,H.issues));$.value[X.value]=H.value}));else{if(Y.issues.length)$.issues.push(...ww(D,Y.issues));$.value[X.value]=Y.value}}}if(G.length)return Promise.all(G).then(()=>$);return $}});var l9=U("$ZodEnum",(b,w)=>{e.init(b,w);let $=s$(w.entries),W=new Set($);b._zod.values=W,b._zod.pattern=new RegExp(`^(${$.filter((Q)=>w4.has(typeof Q)).map((Q)=>typeof Q==="string"?bw(Q):Q.toString()).join("|")})$`),b._zod.parse=(Q,G)=>{let D=Q.value;if(W.has(D))return Q;return Q.issues.push({code:"invalid_value",values:$,input:D,inst:b}),Q}}),p9=U("$ZodLiteral",(b,w)=>{if(e.init(b,w),w.values.length===0)throw Error("Cannot create literal schema with no valid values");b._zod.values=new Set(w.values),b._zod.pattern=new RegExp(`^(${w.values.map(($)=>typeof $==="string"?bw($):$?bw($.toString()):String($)).join("|")})$`),b._zod.parse=($,W)=>{let Q=$.value;if(b._zod.values.has(Q))return $;return $.issues.push({code:"invalid_value",values:w.values,input:Q,inst:b}),$}});var o9=U("$ZodTransform",(b,w)=>{e.init(b,w),b._zod.parse=($,W)=>{if(W.direction==="backward")throw new A1(b.constructor.name);let Q=w.transform($.value,$);if(W.async)return(Q instanceof Promise?Q:Promise.resolve(Q)).then((D)=>{return $.value=D,$});if(Q instanceof Promise)throw new ab;return $.value=Q,$}});function Q9(b,w){if(b.issues.length&&w===void 0)return{issues:[],value:void 0};return b}var d9=U("$ZodOptional",(b,w)=>{e.init(b,w),b._zod.optin="optional",b._zod.optout="optional",d(b._zod,"values",()=>{return w.innerType._zod.values?new Set([...w.innerType._zod.values,void 0]):void 0}),d(b._zod,"pattern",()=>{let $=w.innerType._zod.pattern;return $?new RegExp(`^(${L1($.source)})?$`):void 0}),b._zod.parse=($,W)=>{if(w.innerType._zod.optin==="optional"){let Q=w.innerType._zod.run($,W);if(Q instanceof Promise)return Q.then((G)=>Q9(G,$.value));return Q9(Q,$.value)}if($.value===void 0)return $;return w.innerType._zod.run($,W)}}),t9=U("$ZodNullable",(b,w)=>{e.init(b,w),d(b._zod,"optin",()=>w.innerType._zod.optin),d(b._zod,"optout",()=>w.innerType._zod.optout),d(b._zod,"pattern",()=>{let $=w.innerType._zod.pattern;return $?new RegExp(`^(${L1($.source)}|null)$`):void 0}),d(b._zod,"values",()=>{return w.innerType._zod.values?new Set([...w.innerType._zod.values,null]):void 0}),b._zod.parse=($,W)=>{if($.value===null)return $;return w.innerType._zod.run($,W)}}),r9=U("$ZodDefault",(b,w)=>{e.init(b,w),b._zod.optin="optional",d(b._zod,"values",()=>w.innerType._zod.values),b._zod.parse=($,W)=>{if(W.direction==="backward")return w.innerType._zod.run($,W);if($.value===void 0)return $.value=w.defaultValue,$;let Q=w.innerType._zod.run($,W);if(Q instanceof Promise)return Q.then((G)=>G9(G,w));return G9(Q,w)}});function G9(b,w){if(b.value===void 0)b.value=w.defaultValue;return b}var e9=U("$ZodPrefault",(b,w)=>{e.init(b,w),b._zod.optin="optional",d(b._zod,"values",()=>w.innerType._zod.values),b._zod.parse=($,W)=>{if(W.direction==="backward")return w.innerType._zod.run($,W);if($.value===void 0)$.value=w.defaultValue;return w.innerType._zod.run($,W)}}),s9=U("$ZodNonOptional",(b,w)=>{e.init(b,w),d(b._zod,"values",()=>{let $=w.innerType._zod.values;return $?new Set([...$].filter((W)=>W!==void 0)):void 0}),b._zod.parse=($,W)=>{let Q=w.innerType._zod.run($,W);if(Q instanceof Promise)return Q.then((G)=>D9(G,b));return D9(Q,b)}});function D9(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 a9=U("$ZodCatch",(b,w)=>{e.init(b,w),d(b._zod,"optin",()=>w.innerType._zod.optin),d(b._zod,"optout",()=>w.innerType._zod.optout),d(b._zod,"values",()=>w.innerType._zod.values),b._zod.parse=($,W)=>{if(W.direction==="backward")return w.innerType._zod.run($,W);let Q=w.innerType._zod.run($,W);if(Q instanceof Promise)return Q.then((G)=>{if($.value=G.value,G.issues.length)$.value=w.catchValue({...$,error:{issues:G.issues.map((D)=>yb(D,W,Rb()))},input:$.value}),$.issues=[];return $});if($.value=Q.value,Q.issues.length)$.value=w.catchValue({...$,error:{issues:Q.issues.map((G)=>yb(G,W,Rb()))},input:$.value}),$.issues=[];return $}});var b8=U("$ZodPipe",(b,w)=>{e.init(b,w),d(b._zod,"values",()=>w.in._zod.values),d(b._zod,"optin",()=>w.in._zod.optin),d(b._zod,"optout",()=>w.out._zod.optout),d(b._zod,"propValues",()=>w.in._zod.propValues),b._zod.parse=($,W)=>{if(W.direction==="backward"){let G=w.out._zod.run($,W);if(G instanceof Promise)return G.then((D)=>Z0(D,w.in,W));return Z0(G,w.in,W)}let Q=w.in._zod.run($,W);if(Q instanceof Promise)return Q.then((G)=>Z0(G,w.out,W));return Z0(Q,w.out,W)}});function Z0(b,w,$){if(b.issues.length)return b.aborted=!0,b;return w._zod.run({value:b.value,issues:b.issues},$)}var w8=U("$ZodReadonly",(b,w)=>{e.init(b,w),d(b._zod,"propValues",()=>w.innerType._zod.propValues),d(b._zod,"values",()=>w.innerType._zod.values),d(b._zod,"optin",()=>w.innerType._zod.optin),d(b._zod,"optout",()=>w.innerType._zod.optout),b._zod.parse=($,W)=>{if(W.direction==="backward")return w.innerType._zod.run($,W);let Q=w.innerType._zod.run($,W);if(Q instanceof Promise)return Q.then(X9);return X9(Q)}});function X9(b){return b.value=Object.freeze(b.value),b}var $8=U("$ZodCustom",(b,w)=>{Hb.init(b,w),e.init(b,w),b._zod.parse=($,W)=>{return $},b._zod.check=($)=>{let W=$.value,Q=w.fn(W);if(Q instanceof Promise)return Q.then((G)=>Y9(G,$,W,b));Y9(Q,$,W,b);return}});function Y9(b,w,$,W){if(!b){let Q={code:"custom",input:$,inst:W,path:[...W._zod.def.path??[]],continue:!W._zod.def.abort};if(W._zod.def.params)Q.params=W._zod.def.params;w.issues.push(cw(Q))}}var x7=(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},y7=()=>{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 ${x7(W.input)}`;case"invalid_value":if(W.values.length===1)return`Invalid input: expected ${B0(W.values[0])}`;return`Invalid option: expected one of ${q0(W.values,"|")}`;case"too_big":{let Q=W.inclusive?"<=":"<",G=w(W.origin);if(G)return`Too big: expected ${W.origin??"value"} to have ${Q}${W.maximum.toString()} ${G.unit??"elements"}`;return`Too big: expected ${W.origin??"value"} to be ${Q}${W.maximum.toString()}`}case"too_small":{let Q=W.inclusive?">=":">",G=w(W.origin);if(G)return`Too small: expected ${W.origin} to have ${Q}${W.minimum.toString()} ${G.unit}`;return`Too small: expected ${W.origin} to be ${Q}${W.minimum.toString()}`}case"invalid_format":{let Q=W;if(Q.format==="starts_with")return`Invalid string: must start with "${Q.prefix}"`;if(Q.format==="ends_with")return`Invalid string: must end with "${Q.suffix}"`;if(Q.format==="includes")return`Invalid string: must include "${Q.includes}"`;if(Q.format==="regex")return`Invalid string: must match pattern ${Q.pattern}`;return`Invalid ${$[Q.format]??W.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${W.divisor}`;case"unrecognized_keys":return`Unrecognized key${W.keys.length>1?"s":""}: ${q0(W.keys,", ")}`;case"invalid_key":return`Invalid key in ${W.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${W.origin}`;default:return"Invalid input"}}};function O4(){return{localeError:y7()}}var bI=Symbol("ZodOutput"),wI=Symbol("ZodInput");class W8{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 h7(){return new W8}var M1=h7();function Q8(b,w){return new b({type:"string",..._(w)})}function G8(b,w){return new b({type:"string",format:"email",check:"string_format",abort:!1,..._(w)})}function q4(b,w){return new b({type:"string",format:"guid",check:"string_format",abort:!1,..._(w)})}function D8(b,w){return new b({type:"string",format:"uuid",check:"string_format",abort:!1,..._(w)})}function X8(b,w){return new b({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",..._(w)})}function Y8(b,w){return new b({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",..._(w)})}function H8(b,w){return new b({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",..._(w)})}function J8(b,w){return new b({type:"string",format:"url",check:"string_format",abort:!1,..._(w)})}function z8(b,w){return new b({type:"string",format:"emoji",check:"string_format",abort:!1,..._(w)})}function A8(b,w){return new b({type:"string",format:"nanoid",check:"string_format",abort:!1,..._(w)})}function O8(b,w){return new b({type:"string",format:"cuid",check:"string_format",abort:!1,..._(w)})}function q8(b,w){return new b({type:"string",format:"cuid2",check:"string_format",abort:!1,..._(w)})}function L8(b,w){return new b({type:"string",format:"ulid",check:"string_format",abort:!1,..._(w)})}function U8(b,w){return new b({type:"string",format:"xid",check:"string_format",abort:!1,..._(w)})}function B8(b,w){return new b({type:"string",format:"ksuid",check:"string_format",abort:!1,..._(w)})}function P8(b,w){return new b({type:"string",format:"ipv4",check:"string_format",abort:!1,..._(w)})}function F8(b,w){return new b({type:"string",format:"ipv6",check:"string_format",abort:!1,..._(w)})}function K8(b,w){return new b({type:"string",format:"cidrv4",check:"string_format",abort:!1,..._(w)})}function M8(b,w){return new b({type:"string",format:"cidrv6",check:"string_format",abort:!1,..._(w)})}function I8(b,w){return new b({type:"string",format:"base64",check:"string_format",abort:!1,..._(w)})}function Z8(b,w){return new b({type:"string",format:"base64url",check:"string_format",abort:!1,..._(w)})}function j8(b,w){return new b({type:"string",format:"e164",check:"string_format",abort:!1,..._(w)})}function V8(b,w){return new b({type:"string",format:"jwt",check:"string_format",abort:!1,..._(w)})}function N8(b,w){return new b({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,..._(w)})}function T8(b,w){return new b({type:"string",format:"date",check:"string_format",..._(w)})}function E8(b,w){return new b({type:"string",format:"time",check:"string_format",precision:null,..._(w)})}function _8(b,w){return new b({type:"string",format:"duration",check:"string_format",..._(w)})}function S8(b,w){return new b({type:"number",checks:[],..._(w)})}function R8(b,w){return new b({type:"number",check:"number_format",abort:!1,format:"safeint",..._(w)})}function v8(b,w){return new b({type:"boolean",..._(w)})}function k8(b,w){return new b({type:"null",..._(w)})}function C8(b){return new b({type:"unknown"})}function u8(b,w){return new b({type:"never",..._(w)})}function N0(b,w){return new X4({check:"less_than",..._(w),value:b,inclusive:!1})}function I1(b,w){return new X4({check:"less_than",..._(w),value:b,inclusive:!0})}function T0(b,w){return new Y4({check:"greater_than",..._(w),value:b,inclusive:!1})}function Z1(b,w){return new Y4({check:"greater_than",..._(w),value:b,inclusive:!0})}function E0(b,w){return new nQ({check:"multiple_of",..._(w),value:b})}function _0(b,w){return new mQ({check:"max_length",..._(w),maximum:b})}function nw(b,w){return new iQ({check:"min_length",..._(w),minimum:b})}function S0(b,w){return new lQ({check:"length_equals",..._(w),length:b})}function L4(b,w){return new pQ({check:"string_format",format:"regex",..._(w),pattern:b})}function U4(b){return new oQ({check:"string_format",format:"lowercase",..._(b)})}function B4(b){return new dQ({check:"string_format",format:"uppercase",..._(b)})}function P4(b,w){return new tQ({check:"string_format",format:"includes",..._(w),includes:b})}function F4(b,w){return new rQ({check:"string_format",format:"starts_with",..._(w),prefix:b})}function K4(b,w){return new eQ({check:"string_format",format:"ends_with",..._(w),suffix:b})}function Rw(b){return new sQ({check:"overwrite",tx:b})}function M4(b){return Rw((w)=>w.normalize(b))}function I4(){return Rw((b)=>b.trim())}function Z4(){return Rw((b)=>b.toLowerCase())}function j4(){return Rw((b)=>b.toUpperCase())}function x8(b,w,$){return new b({type:"array",element:w,..._($)})}function y8(b,w,$){let W=_($);return W.abort??(W.abort=!0),new b({type:"custom",check:"custom",fn:w,...W})}function h8(b,w,$){return new b({type:"custom",check:"custom",fn:w,..._($)})}function f8(b){let w=f7(($)=>{return $.addIssue=(W)=>{if(typeof W==="string")$.issues.push(cw(W,$.value,w._zod.def));else{let Q=W;if(Q.fatal)Q.continue=!1;Q.code??(Q.code="custom"),Q.input??(Q.input=$.value),Q.inst??(Q.inst=w),Q.continue??(Q.continue=!w._zod.def.abort),$.issues.push(cw(Q))}},b($.value,$)});return w}function f7(b,w){let $=new Hb({check:"custom",..._(w)});return $._zod.check=b,$}function gw(b){return!!b._zod}function Fw(b,w){if(gw(b))return P1(b,w);return b.safeParse(w)}function R0(b){if(!b)return;let w;if(gw(b))w=b._zod?.def?.shape;else w=b.shape;if(!w)return;if(typeof w==="function")try{return w()}catch{return}return w}function c8(b){if(gw(b)){let G=b._zod?.def;if(G){if(G.value!==void 0)return G.value;if(Array.isArray(G.values)&&G.values.length>0)return G.values[0]}}let $=b._def;if($){if($.value!==void 0)return $.value;if(Array.isArray($.values)&&$.values.length>0)return $.values[0]}let W=b.value;if(W!==void 0)return W;return}var V1={};xW(V1,{time:()=>T4,duration:()=>E4,datetime:()=>V4,date:()=>N4,ZodISOTime:()=>m8,ZodISODuration:()=>i8,ZodISODateTime:()=>n8,ZodISODate:()=>g8});var n8=U("ZodISODateTime",(b,w)=>{K9.init(b,w),bb.init(b,w)});function V4(b){return N8(n8,b)}var g8=U("ZodISODate",(b,w)=>{M9.init(b,w),bb.init(b,w)});function N4(b){return T8(g8,b)}var m8=U("ZodISOTime",(b,w)=>{I9.init(b,w),bb.init(b,w)});function T4(b){return E8(m8,b)}var i8=U("ZodISODuration",(b,w)=>{Z9.init(b,w),bb.init(b,w)});function E4(b){return _8(i8,b)}var l8=(b,w)=>{P0.init(b,w),b.name="ZodError",Object.defineProperties(b,{format:{value:($)=>$Q(b,$)},flatten:{value:($)=>wQ(b,$)},addIssue:{value:($)=>{b.issues.push($),b.message=JSON.stringify(b.issues,hw,2)}},addIssues:{value:($)=>{b.issues.push(...$),b.message=JSON.stringify(b.issues,hw,2)}},isEmpty:{get(){return b.issues.length===0}}})},cI=U("ZodError",l8),Tb=U("ZodError",l8,{Parent:Error});var p8=F0(Tb),o8=K0(Tb),d8=B1(Tb),t8=F1(Tb),r8=WQ(Tb),e8=QQ(Tb),s8=GQ(Tb),a8=DQ(Tb),bG=XQ(Tb),wG=YQ(Tb),$G=HQ(Tb),WG=JQ(Tb);var Qb=U("ZodType",(b,w)=>{return e.init(b,w),b.def=w,b.type=w.type,Object.defineProperty(b,"_def",{value:w}),b.check=(...$)=>{return b.clone(m.mergeDefs(w,{checks:[...w.checks??[],...$.map((W)=>typeof W==="function"?{_zod:{check:W,def:{check:"custom"},onattach:[]}}:W)]}))},b.clone=($,W)=>xb(b,$,W),b.brand=()=>b,b.register=($,W)=>{return $.add(b,W),b},b.parse=($,W)=>p8(b,$,W,{callee:b.parse}),b.safeParse=($,W)=>d8(b,$,W),b.parseAsync=async($,W)=>o8(b,$,W,{callee:b.parseAsync}),b.safeParseAsync=async($,W)=>t8(b,$,W),b.spa=b.safeParseAsync,b.encode=($,W)=>r8(b,$,W),b.decode=($,W)=>e8(b,$,W),b.encodeAsync=async($,W)=>s8(b,$,W),b.decodeAsync=async($,W)=>a8(b,$,W),b.safeEncode=($,W)=>bG(b,$,W),b.safeDecode=($,W)=>wG(b,$,W),b.safeEncodeAsync=async($,W)=>$G(b,$,W),b.safeDecodeAsync=async($,W)=>WG(b,$,W),b.refine=($,W)=>b.check(uA($,W)),b.superRefine=($)=>b.check(xA($)),b.overwrite=($)=>b.check(Rw($)),b.optional=()=>Wb(b),b.nullable=()=>DG(b),b.nullish=()=>Wb(DG(b)),b.nonoptional=($)=>_A(b,$),b.array=()=>f(b),b.or=($)=>r([b,$]),b.and=($)=>k0(b,$),b.transform=($)=>S4(b,zG($)),b.default=($)=>NA(b,$),b.prefault=($)=>EA(b,$),b.catch=($)=>RA(b,$),b.pipe=($)=>S4(b,$),b.readonly=()=>CA(b),b.describe=($)=>{let W=b.clone();return M1.add(W,{description:$}),W},Object.defineProperty(b,"description",{get(){return M1.get(b)?.description},configurable:!0}),b.meta=(...$)=>{if($.length===0)return M1.get(b);let W=b.clone();return M1.add(W,$[0]),W},b.isOptional=()=>b.safeParse(void 0).success,b.isNullable=()=>b.safeParse(null).success,b}),XG=U("_ZodString",(b,w)=>{V0.init(b,w),Qb.init(b,w);let $=b._zod.bag;b.format=$.format??null,b.minLength=$.minimum??null,b.maxLength=$.maximum??null,b.regex=(...W)=>b.check(L4(...W)),b.includes=(...W)=>b.check(P4(...W)),b.startsWith=(...W)=>b.check(F4(...W)),b.endsWith=(...W)=>b.check(K4(...W)),b.min=(...W)=>b.check(nw(...W)),b.max=(...W)=>b.check(_0(...W)),b.length=(...W)=>b.check(S0(...W)),b.nonempty=(...W)=>b.check(nw(1,...W)),b.lowercase=(W)=>b.check(U4(W)),b.uppercase=(W)=>b.check(B4(W)),b.trim=()=>b.check(I4()),b.normalize=(...W)=>b.check(M4(...W)),b.toLowerCase=()=>b.check(Z4()),b.toUpperCase=()=>b.check(j4())}),d7=U("ZodString",(b,w)=>{V0.init(b,w),XG.init(b,w),b.email=($)=>b.check(G8(t7,$)),b.url=($)=>b.check(J8(r7,$)),b.jwt=($)=>b.check(V8(zA,$)),b.emoji=($)=>b.check(z8(e7,$)),b.guid=($)=>b.check(q4(QG,$)),b.uuid=($)=>b.check(D8(v0,$)),b.uuidv4=($)=>b.check(X8(v0,$)),b.uuidv6=($)=>b.check(Y8(v0,$)),b.uuidv7=($)=>b.check(H8(v0,$)),b.nanoid=($)=>b.check(A8(s7,$)),b.guid=($)=>b.check(q4(QG,$)),b.cuid=($)=>b.check(O8(a7,$)),b.cuid2=($)=>b.check(q8(bA,$)),b.ulid=($)=>b.check(L8(wA,$)),b.base64=($)=>b.check(I8(YA,$)),b.base64url=($)=>b.check(Z8(HA,$)),b.xid=($)=>b.check(U8($A,$)),b.ksuid=($)=>b.check(B8(WA,$)),b.ipv4=($)=>b.check(P8(QA,$)),b.ipv6=($)=>b.check(F8(GA,$)),b.cidrv4=($)=>b.check(K8(DA,$)),b.cidrv6=($)=>b.check(M8(XA,$)),b.e164=($)=>b.check(j8(JA,$)),b.datetime=($)=>b.check(V4($)),b.date=($)=>b.check(N4($)),b.time=($)=>b.check(T4($)),b.duration=($)=>b.check(E4($))});function L(b){return Q8(d7,b)}var bb=U("ZodStringFormat",(b,w)=>{s.init(b,w),XG.init(b,w)}),t7=U("ZodEmail",(b,w)=>{z9.init(b,w),bb.init(b,w)});var QG=U("ZodGUID",(b,w)=>{H9.init(b,w),bb.init(b,w)});var v0=U("ZodUUID",(b,w)=>{J9.init(b,w),bb.init(b,w)});var r7=U("ZodURL",(b,w)=>{A9.init(b,w),bb.init(b,w)});var e7=U("ZodEmoji",(b,w)=>{O9.init(b,w),bb.init(b,w)});var s7=U("ZodNanoID",(b,w)=>{q9.init(b,w),bb.init(b,w)});var a7=U("ZodCUID",(b,w)=>{L9.init(b,w),bb.init(b,w)});var bA=U("ZodCUID2",(b,w)=>{U9.init(b,w),bb.init(b,w)});var wA=U("ZodULID",(b,w)=>{B9.init(b,w),bb.init(b,w)});var $A=U("ZodXID",(b,w)=>{P9.init(b,w),bb.init(b,w)});var WA=U("ZodKSUID",(b,w)=>{F9.init(b,w),bb.init(b,w)});var QA=U("ZodIPv4",(b,w)=>{j9.init(b,w),bb.init(b,w)});var GA=U("ZodIPv6",(b,w)=>{V9.init(b,w),bb.init(b,w)});var DA=U("ZodCIDRv4",(b,w)=>{N9.init(b,w),bb.init(b,w)});var XA=U("ZodCIDRv6",(b,w)=>{T9.init(b,w),bb.init(b,w)});var YA=U("ZodBase64",(b,w)=>{_9.init(b,w),bb.init(b,w)});var HA=U("ZodBase64URL",(b,w)=>{S9.init(b,w),bb.init(b,w)});var JA=U("ZodE164",(b,w)=>{R9.init(b,w),bb.init(b,w)});var zA=U("ZodJWT",(b,w)=>{v9.init(b,w),bb.init(b,w)});var YG=U("ZodNumber",(b,w)=>{z4.init(b,w),Qb.init(b,w),b.gt=(W,Q)=>b.check(T0(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(N0(W,Q)),b.lte=(W,Q)=>b.check(I1(W,Q)),b.max=(W,Q)=>b.check(I1(W,Q)),b.int=(W)=>b.check(GG(W)),b.safe=(W)=>b.check(GG(W)),b.positive=(W)=>b.check(T0(0,W)),b.nonnegative=(W)=>b.check(Z1(0,W)),b.negative=(W)=>b.check(N0(0,W)),b.nonpositive=(W)=>b.check(I1(0,W)),b.multipleOf=(W,Q)=>b.check(E0(W,Q)),b.step=(W,Q)=>b.check(E0(W,Q)),b.finite=()=>b;let $=b._zod.bag;b.minValue=Math.max($.minimum??Number.NEGATIVE_INFINITY,$.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,b.maxValue=Math.min($.maximum??Number.POSITIVE_INFINITY,$.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,b.isInt=($.format??"").includes("int")||Number.isSafeInteger($.multipleOf??0.5),b.isFinite=!0,b.format=$.format??null});function p(b){return S8(YG,b)}var AA=U("ZodNumberFormat",(b,w)=>{k9.init(b,w),YG.init(b,w)});function GG(b){return R8(AA,b)}var OA=U("ZodBoolean",(b,w)=>{C9.init(b,w),Qb.init(b,w)});function Yb(b){return v8(OA,b)}var qA=U("ZodNull",(b,w)=>{u9.init(b,w),Qb.init(b,w)});function R4(b){return k8(qA,b)}var LA=U("ZodUnknown",(b,w)=>{x9.init(b,w),Qb.init(b,w)});function wb(){return C8(LA)}var UA=U("ZodNever",(b,w)=>{y9.init(b,w),Qb.init(b,w)});function BA(b){return u8(UA,b)}var PA=U("ZodArray",(b,w)=>{h9.init(b,w),Qb.init(b,w),b.element=w.element,b.min=($,W)=>b.check(nw($,W)),b.nonempty=($)=>b.check(nw(1,$)),b.max=($,W)=>b.check(_0($,W)),b.length=($,W)=>b.check(S0($,W)),b.unwrap=()=>b.element});function f(b,w){return x8(PA,b,w)}var HG=U("ZodObject",(b,w)=>{n9.init(b,w),Qb.init(b,w),m.defineLazy(b,"shape",()=>{return w.shape}),b.keyof=()=>Mb(Object.keys(b._zod.def.shape)),b.catchall=($)=>b.clone({...b._zod.def,catchall:$}),b.passthrough=()=>b.clone({...b._zod.def,catchall:wb()}),b.loose=()=>b.clone({...b._zod.def,catchall:wb()}),b.strict=()=>b.clone({...b._zod.def,catchall:BA()}),b.strip=()=>b.clone({...b._zod.def,catchall:void 0}),b.extend=($)=>{return m.extend(b,$)},b.safeExtend=($)=>{return m.safeExtend(b,$)},b.merge=($)=>m.merge(b,$),b.pick=($)=>m.pick(b,$),b.omit=($)=>m.omit(b,$),b.partial=(...$)=>m.partial(AG,b,$[0]),b.required=(...$)=>m.required(OG,b,$[0])});function V(b,w){let $={type:"object",shape:b??{},...m.normalizeParams(w)};return new HG($)}function Bb(b,w){return new HG({type:"object",shape:b,catchall:wb(),...m.normalizeParams(w)})}var JG=U("ZodUnion",(b,w)=>{A4.init(b,w),Qb.init(b,w),b.options=w.options});function r(b,w){return new JG({type:"union",options:b,...m.normalizeParams(w)})}var FA=U("ZodDiscriminatedUnion",(b,w)=>{JG.init(b,w),g9.init(b,w)});function v4(b,w,$){return new FA({type:"union",options:w,discriminator:b,...m.normalizeParams($)})}var KA=U("ZodIntersection",(b,w)=>{m9.init(b,w),Qb.init(b,w)});function k0(b,w){return new KA({type:"intersection",left:b,right:w})}var MA=U("ZodRecord",(b,w)=>{i9.init(b,w),Qb.init(b,w),b.keyType=w.keyType,b.valueType=w.valueType});function $b(b,w,$){return new MA({type:"record",keyType:b,valueType:w,...m.normalizeParams($)})}var _4=U("ZodEnum",(b,w)=>{l9.init(b,w),Qb.init(b,w),b.enum=w.entries,b.options=Object.values(w.entries);let $=new Set(Object.keys(w.entries));b.extract=(W,Q)=>{let G={};for(let D of W)if($.has(D))G[D]=w.entries[D];else throw Error(`Key ${D} not found in enum`);return new _4({...w,checks:[],...m.normalizeParams(Q),entries:G})},b.exclude=(W,Q)=>{let G={...w.entries};for(let D of W)if($.has(D))delete G[D];else throw Error(`Key ${D} not found in enum`);return new _4({...w,checks:[],...m.normalizeParams(Q),entries:G})}});function Mb(b,w){let $=Array.isArray(b)?Object.fromEntries(b.map((W)=>[W,W])):b;return new _4({type:"enum",entries:$,...m.normalizeParams(w)})}var IA=U("ZodLiteral",(b,w)=>{p9.init(b,w),Qb.init(b,w),b.values=new Set(w.values),Object.defineProperty(b,"value",{get(){if(w.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return w.values[0]}})});function T(b,w){return new IA({type:"literal",values:Array.isArray(b)?b:[b],...m.normalizeParams(w)})}var ZA=U("ZodTransform",(b,w)=>{o9.init(b,w),Qb.init(b,w),b._zod.parse=($,W)=>{if(W.direction==="backward")throw new A1(b.constructor.name);$.addIssue=(G)=>{if(typeof G==="string")$.issues.push(m.issue(G,$.value,w));else{let D=G;if(D.fatal)D.continue=!1;D.code??(D.code="custom"),D.input??(D.input=$.value),D.inst??(D.inst=b),$.issues.push(m.issue(D))}};let Q=w.transform($.value,$);if(Q instanceof Promise)return Q.then((G)=>{return $.value=G,$});return $.value=Q,$}});function zG(b){return new ZA({type:"transform",transform:b})}var AG=U("ZodOptional",(b,w)=>{d9.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType});function Wb(b){return new AG({type:"optional",innerType:b})}var jA=U("ZodNullable",(b,w)=>{t9.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType});function DG(b){return new jA({type:"nullable",innerType:b})}var VA=U("ZodDefault",(b,w)=>{r9.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType,b.removeDefault=b.unwrap});function NA(b,w){return new VA({type:"default",innerType:b,get defaultValue(){return typeof w==="function"?w():m.shallowClone(w)}})}var TA=U("ZodPrefault",(b,w)=>{e9.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType});function EA(b,w){return new TA({type:"prefault",innerType:b,get defaultValue(){return typeof w==="function"?w():m.shallowClone(w)}})}var OG=U("ZodNonOptional",(b,w)=>{s9.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType});function _A(b,w){return new OG({type:"nonoptional",innerType:b,...m.normalizeParams(w)})}var SA=U("ZodCatch",(b,w)=>{a9.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType,b.removeCatch=b.unwrap});function RA(b,w){return new SA({type:"catch",innerType:b,catchValue:typeof w==="function"?w:()=>w})}var vA=U("ZodPipe",(b,w)=>{b8.init(b,w),Qb.init(b,w),b.in=w.in,b.out=w.out});function S4(b,w){return new vA({type:"pipe",in:b,out:w})}var kA=U("ZodReadonly",(b,w)=>{w8.init(b,w),Qb.init(b,w),b.unwrap=()=>b._zod.def.innerType});function CA(b){return new kA({type:"readonly",innerType:b})}var qG=U("ZodCustom",(b,w)=>{$8.init(b,w),Qb.init(b,w)});function LG(b,w){return y8(qG,b??(()=>!0),w)}function uA(b,w={}){return h8(qG,b,w)}function xA(b){return f8(b)}function k4(b,w){return S4(zG(b),w)}Rb(O4());var C4="2025-11-25";var UG=[C4,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Kw="io.modelcontextprotocol/related-task",u0="2.0",Jb=LG((b)=>b!==null&&(typeof b==="object"||typeof b==="function")),BG=r([L(),p().int()]),PG=L(),uZ=Bb({ttl:r([p(),R4()]).optional(),pollInterval:p().optional()}),yA=V({ttl:p().optional()}),hA=V({taskId:L()}),u4=Bb({progressToken:BG.optional(),[Kw]:hA.optional()}),Eb=V({_meta:u4.optional()}),N1=Eb.extend({task:yA.optional()}),FG=(b)=>N1.safeParse(b).success,zb=V({method:L(),params:Eb.loose().optional()}),vb=V({_meta:u4.optional()}),kb=V({method:L(),params:vb.loose().optional()}),Ab=Bb({_meta:u4.optional()}),x0=r([L(),p().int()]),KG=V({jsonrpc:T(u0),id:x0,...zb.shape}).strict(),x4=(b)=>KG.safeParse(b).success,MG=V({jsonrpc:T(u0),...kb.shape}).strict(),IG=(b)=>MG.safeParse(b).success,y4=V({jsonrpc:T(u0),id:x0,result:Ab}).strict(),T1=(b)=>y4.safeParse(b).success;var c;(function(b){b[b.ConnectionClosed=-32000]="ConnectionClosed",b[b.RequestTimeout=-32001]="RequestTimeout",b[b.ParseError=-32700]="ParseError",b[b.InvalidRequest=-32600]="InvalidRequest",b[b.MethodNotFound=-32601]="MethodNotFound",b[b.InvalidParams=-32602]="InvalidParams",b[b.InternalError=-32603]="InternalError",b[b.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(c||(c={}));var h4=V({jsonrpc:T(u0),id:x0.optional(),error:V({code:p().int(),message:L(),data:wb().optional()})}).strict();var ZG=(b)=>h4.safeParse(b).success;var jG=r([KG,MG,y4,h4]),xZ=r([y4,h4]),y0=Ab.strict(),fA=vb.extend({requestId:x0.optional(),reason:L().optional()}),h0=kb.extend({method:T("notifications/cancelled"),params:fA}),cA=V({src:L(),mimeType:L().optional(),sizes:f(L()).optional(),theme:Mb(["light","dark"]).optional()}),E1=V({icons:f(cA).optional()}),mw=V({name:L(),title:L().optional()}),VG=mw.extend({...mw.shape,...E1.shape,version:L(),websiteUrl:L().optional(),description:L().optional()}),nA=k0(V({applyDefaults:Yb().optional()}),$b(L(),wb())),gA=k4((b)=>{if(b&&typeof b==="object"&&!Array.isArray(b)){if(Object.keys(b).length===0)return{form:{}}}return b},k0(V({form:nA.optional(),url:Jb.optional()}),$b(L(),wb()).optional())),mA=Bb({list:Jb.optional(),cancel:Jb.optional(),requests:Bb({sampling:Bb({createMessage:Jb.optional()}).optional(),elicitation:Bb({create:Jb.optional()}).optional()}).optional()}),iA=Bb({list:Jb.optional(),cancel:Jb.optional(),requests:Bb({tools:Bb({call:Jb.optional()}).optional()}).optional()}),lA=V({experimental:$b(L(),Jb).optional(),sampling:V({context:Jb.optional(),tools:Jb.optional()}).optional(),elicitation:gA.optional(),roots:V({listChanged:Yb().optional()}).optional(),tasks:mA.optional()}),pA=Eb.extend({protocolVersion:L(),capabilities:lA,clientInfo:VG}),f4=zb.extend({method:T("initialize"),params:pA});var oA=V({experimental:$b(L(),Jb).optional(),logging:Jb.optional(),completions:Jb.optional(),prompts:V({listChanged:Yb().optional()}).optional(),resources:V({subscribe:Yb().optional(),listChanged:Yb().optional()}).optional(),tools:V({listChanged:Yb().optional()}).optional(),tasks:iA.optional()}),dA=Ab.extend({protocolVersion:L(),capabilities:oA,serverInfo:VG,instructions:L().optional()}),c4=kb.extend({method:T("notifications/initialized"),params:vb.optional()});var f0=zb.extend({method:T("ping"),params:Eb.optional()}),tA=V({progress:p(),total:Wb(p()),message:Wb(L())}),rA=V({...vb.shape,...tA.shape,progressToken:BG}),c0=kb.extend({method:T("notifications/progress"),params:rA}),eA=Eb.extend({cursor:PG.optional()}),_1=zb.extend({params:eA.optional()}),S1=Ab.extend({nextCursor:PG.optional()}),sA=Mb(["working","input_required","completed","failed","cancelled"]),R1=V({taskId:L(),status:sA,ttl:r([p(),R4()]),createdAt:L(),lastUpdatedAt:L(),pollInterval:Wb(p()),statusMessage:Wb(L())}),iw=Ab.extend({task:R1}),aA=vb.merge(R1),v1=kb.extend({method:T("notifications/tasks/status"),params:aA}),n0=zb.extend({method:T("tasks/get"),params:Eb.extend({taskId:L()})}),g0=Ab.merge(R1),m0=zb.extend({method:T("tasks/result"),params:Eb.extend({taskId:L()})}),yZ=Ab.loose(),i0=_1.extend({method:T("tasks/list")}),l0=S1.extend({tasks:f(R1)}),p0=zb.extend({method:T("tasks/cancel"),params:Eb.extend({taskId:L()})}),NG=Ab.merge(R1),TG=V({uri:L(),mimeType:Wb(L()),_meta:$b(L(),wb()).optional()}),EG=TG.extend({text:L()}),n4=L().refine((b)=>{try{return atob(b),!0}catch{return!1}},{message:"Invalid Base64 string"}),_G=TG.extend({blob:n4}),k1=Mb(["user","assistant"]),lw=V({audience:f(k1).optional(),priority:p().min(0).max(1).optional(),lastModified:V1.datetime({offset:!0}).optional()}),SG=V({...mw.shape,...E1.shape,uri:L(),description:Wb(L()),mimeType:Wb(L()),annotations:lw.optional(),_meta:Wb(Bb({}))}),b5=V({...mw.shape,...E1.shape,uriTemplate:L(),description:Wb(L()),mimeType:Wb(L()),annotations:lw.optional(),_meta:Wb(Bb({}))}),g4=_1.extend({method:T("resources/list")}),w5=S1.extend({resources:f(SG)}),$5=_1.extend({method:T("resources/templates/list")}),W5=S1.extend({resourceTemplates:f(b5)}),m4=Eb.extend({uri:L()}),Q5=m4,i4=zb.extend({method:T("resources/read"),params:Q5}),G5=Ab.extend({contents:f(r([EG,_G]))}),D5=kb.extend({method:T("notifications/resources/list_changed"),params:vb.optional()}),X5=m4,Y5=zb.extend({method:T("resources/subscribe"),params:X5}),H5=m4,J5=zb.extend({method:T("resources/unsubscribe"),params:H5}),z5=vb.extend({uri:L()}),A5=kb.extend({method:T("notifications/resources/updated"),params:z5}),O5=V({name:L(),description:Wb(L()),required:Wb(Yb())}),q5=V({...mw.shape,...E1.shape,description:Wb(L()),arguments:Wb(f(O5)),_meta:Wb(Bb({}))}),L5=_1.extend({method:T("prompts/list")}),U5=S1.extend({prompts:f(q5)}),B5=Eb.extend({name:L(),arguments:$b(L(),L()).optional()}),P5=zb.extend({method:T("prompts/get"),params:B5}),l4=V({type:T("text"),text:L(),annotations:lw.optional(),_meta:$b(L(),wb()).optional()}),p4=V({type:T("image"),data:n4,mimeType:L(),annotations:lw.optional(),_meta:$b(L(),wb()).optional()}),o4=V({type:T("audio"),data:n4,mimeType:L(),annotations:lw.optional(),_meta:$b(L(),wb()).optional()}),F5=V({type:T("tool_use"),name:L(),id:L(),input:$b(L(),wb()),_meta:$b(L(),wb()).optional()}),K5=V({type:T("resource"),resource:r([EG,_G]),annotations:lw.optional(),_meta:$b(L(),wb()).optional()}),M5=SG.extend({type:T("resource_link")}),d4=r([l4,p4,o4,M5,K5]),I5=V({role:k1,content:d4}),Z5=Ab.extend({description:L().optional(),messages:f(I5)}),j5=kb.extend({method:T("notifications/prompts/list_changed"),params:vb.optional()}),V5=V({title:L().optional(),readOnlyHint:Yb().optional(),destructiveHint:Yb().optional(),idempotentHint:Yb().optional(),openWorldHint:Yb().optional()}),N5=V({taskSupport:Mb(["required","optional","forbidden"]).optional()}),RG=V({...mw.shape,...E1.shape,description:L().optional(),inputSchema:V({type:T("object"),properties:$b(L(),Jb).optional(),required:f(L()).optional()}).catchall(wb()),outputSchema:V({type:T("object"),properties:$b(L(),Jb).optional(),required:f(L()).optional()}).catchall(wb()).optional(),annotations:V5.optional(),execution:N5.optional(),_meta:$b(L(),wb()).optional()}),t4=_1.extend({method:T("tools/list")}),T5=S1.extend({tools:f(RG)}),o0=Ab.extend({content:f(d4).default([]),structuredContent:$b(L(),wb()).optional(),isError:Yb().optional()}),hZ=o0.or(Ab.extend({toolResult:wb()})),E5=N1.extend({name:L(),arguments:$b(L(),wb()).optional()}),C1=zb.extend({method:T("tools/call"),params:E5}),_5=kb.extend({method:T("notifications/tools/list_changed"),params:vb.optional()}),fZ=V({autoRefresh:Yb().default(!0),debounceMs:p().int().nonnegative().default(300)}),u1=Mb(["debug","info","notice","warning","error","critical","alert","emergency"]),S5=Eb.extend({level:u1}),r4=zb.extend({method:T("logging/setLevel"),params:S5}),R5=vb.extend({level:u1,logger:L().optional(),data:wb()}),v5=kb.extend({method:T("notifications/message"),params:R5}),k5=V({name:L().optional()}),C5=V({hints:f(k5).optional(),costPriority:p().min(0).max(1).optional(),speedPriority:p().min(0).max(1).optional(),intelligencePriority:p().min(0).max(1).optional()}),u5=V({mode:Mb(["auto","required","none"]).optional()}),x5=V({type:T("tool_result"),toolUseId:L().describe("The unique identifier for the corresponding tool call."),content:f(d4).default([]),structuredContent:V({}).loose().optional(),isError:Yb().optional(),_meta:$b(L(),wb()).optional()}),y5=v4("type",[l4,p4,o4]),C0=v4("type",[l4,p4,o4,F5,x5]),h5=V({role:k1,content:r([C0,f(C0)]),_meta:$b(L(),wb()).optional()}),f5=N1.extend({messages:f(h5),modelPreferences:C5.optional(),systemPrompt:L().optional(),includeContext:Mb(["none","thisServer","allServers"]).optional(),temperature:p().optional(),maxTokens:p().int(),stopSequences:f(L()).optional(),metadata:Jb.optional(),tools:f(RG).optional(),toolChoice:u5.optional()}),c5=zb.extend({method:T("sampling/createMessage"),params:f5}),e4=Ab.extend({model:L(),stopReason:Wb(Mb(["endTurn","stopSequence","maxTokens"]).or(L())),role:k1,content:y5}),s4=Ab.extend({model:L(),stopReason:Wb(Mb(["endTurn","stopSequence","maxTokens","toolUse"]).or(L())),role:k1,content:r([C0,f(C0)])}),n5=V({type:T("boolean"),title:L().optional(),description:L().optional(),default:Yb().optional()}),g5=V({type:T("string"),title:L().optional(),description:L().optional(),minLength:p().optional(),maxLength:p().optional(),format:Mb(["email","uri","date","date-time"]).optional(),default:L().optional()}),m5=V({type:Mb(["number","integer"]),title:L().optional(),description:L().optional(),minimum:p().optional(),maximum:p().optional(),default:p().optional()}),i5=V({type:T("string"),title:L().optional(),description:L().optional(),enum:f(L()),default:L().optional()}),l5=V({type:T("string"),title:L().optional(),description:L().optional(),oneOf:f(V({const:L(),title:L()})),default:L().optional()}),p5=V({type:T("string"),title:L().optional(),description:L().optional(),enum:f(L()),enumNames:f(L()).optional(),default:L().optional()}),o5=r([i5,l5]),d5=V({type:T("array"),title:L().optional(),description:L().optional(),minItems:p().optional(),maxItems:p().optional(),items:V({type:T("string"),enum:f(L())}),default:f(L()).optional()}),t5=V({type:T("array"),title:L().optional(),description:L().optional(),minItems:p().optional(),maxItems:p().optional(),items:V({anyOf:f(V({const:L(),title:L()}))}),default:f(L()).optional()}),r5=r([d5,t5]),e5=r([p5,o5,r5]),s5=r([e5,n5,g5,m5]),a5=N1.extend({mode:T("form").optional(),message:L(),requestedSchema:V({type:T("object"),properties:$b(L(),s5),required:f(L()).optional()})}),bO=N1.extend({mode:T("url"),message:L(),elicitationId:L(),url:L().url()}),wO=r([a5,bO]),$O=zb.extend({method:T("elicitation/create"),params:wO}),WO=vb.extend({elicitationId:L()}),QO=kb.extend({method:T("notifications/elicitation/complete"),params:WO}),d0=Ab.extend({action:Mb(["accept","decline","cancel"]),content:k4((b)=>b===null?void 0:b,$b(L(),r([L(),p(),Yb(),f(L())])).optional())}),GO=V({type:T("ref/resource"),uri:L()});var DO=V({type:T("ref/prompt"),name:L()}),XO=Eb.extend({ref:r([DO,GO]),argument:V({name:L(),value:L()}),context:V({arguments:$b(L(),L()).optional()}).optional()}),YO=zb.extend({method:T("completion/complete"),params:XO});var HO=Ab.extend({completion:Bb({values:f(L()).max(100),total:Wb(p().int()),hasMore:Wb(Yb())})}),JO=V({uri:L().startsWith("file://"),name:L().optional(),_meta:$b(L(),wb()).optional()}),zO=zb.extend({method:T("roots/list"),params:Eb.optional()}),a4=Ab.extend({roots:f(JO)}),AO=kb.extend({method:T("notifications/roots/list_changed"),params:vb.optional()}),cZ=r([f0,f4,YO,r4,P5,L5,g4,$5,i4,Y5,J5,C1,t4,n0,m0,i0,p0]),nZ=r([h0,c0,c4,AO,v1]),gZ=r([y0,e4,s4,d0,a4,g0,l0,iw]),mZ=r([f0,c5,$O,zO,n0,m0,i0,p0]),iZ=r([h0,c0,v5,A5,D5,_5,j5,v1,QO]),lZ=r([y0,dA,HO,Z5,U5,w5,W5,G5,o0,T5,g0,l0,iw]);class u extends Error{constructor(b,w,$){super(`MCP error ${b}: ${w}`);this.code=b,this.data=$,this.name="McpError"}static fromError(b,w,$){if(b===c.UrlElicitationRequired&&$){let W=$;if(W.elicitations)return new vG(W.elicitations,w)}return new u(b,w,$)}}class vG extends u{constructor(b,w=`URL elicitation${b.length>1?"s":""} required`){super(c.UrlElicitationRequired,w,{elicitations:b})}get elicitations(){return this.data?.elicitations??[]}}function Mw(b){return b==="completed"||b==="failed"||b==="cancelled"}var OO=Symbol("Let zodToJsonSchema decide on which parser to use");var jj=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function b6(b){let $=R0(b)?.method;if(!$)throw Error("Schema is missing a method literal");let W=c8($);if(typeof W!=="string")throw Error("Schema method literal must be a string");return W}function w6(b,w){let $=Fw(b,w);if(!$.success)throw $.error;return $.data}var FO=60000;class $6{constructor(b){if(this._options=b,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(h0,(w)=>{this._oncancel(w)}),this.setNotificationHandler(c0,(w)=>{this._onprogress(w)}),this.setRequestHandler(f0,(w)=>({})),this._taskStore=b?.taskStore,this._taskMessageQueue=b?.taskMessageQueue,this._taskStore)this.setRequestHandler(n0,async(w,$)=>{let W=await this._taskStore.getTask(w.params.taskId,$.sessionId);if(!W)throw new u(c.InvalidParams,"Failed to retrieve task: Task not found");return{...W}}),this.setRequestHandler(m0,async(w,$)=>{let W=async()=>{let Q=w.params.taskId;if(this._taskMessageQueue){let D;while(D=await this._taskMessageQueue.dequeue(Q,$.sessionId)){if(D.type==="response"||D.type==="error"){let X=D.message,Y=X.id,H=this._requestResolvers.get(Y);if(H)if(this._requestResolvers.delete(Y),D.type==="response")H(X);else{let J=X,z=new u(J.error.code,J.error.message,J.error.data);H(z)}else{let J=D.type==="response"?"Response":"Error";this._onerror(Error(`${J} handler missing for request ${Y}`))}continue}await this._transport?.send(D.message,{relatedRequestId:$.requestId})}}let G=await this._taskStore.getTask(Q,$.sessionId);if(!G)throw new u(c.InvalidParams,`Task not found: ${Q}`);if(!Mw(G.status))return await this._waitForTaskUpdate(Q,$.signal),await W();if(Mw(G.status)){let D=await this._taskStore.getTaskResult(Q,$.sessionId);return this._clearTaskQueue(Q),{...D,_meta:{...D._meta,[Kw]:{taskId:Q}}}}return await W()};return await W()}),this.setRequestHandler(i0,async(w,$)=>{try{let{tasks:W,nextCursor:Q}=await this._taskStore.listTasks(w.params?.cursor,$.sessionId);return{tasks:W,nextCursor:Q,_meta:{}}}catch(W){throw new u(c.InvalidParams,`Failed to list tasks: ${W instanceof Error?W.message:String(W)}`)}}),this.setRequestHandler(p0,async(w,$)=>{try{let W=await this._taskStore.getTask(w.params.taskId,$.sessionId);if(!W)throw new u(c.InvalidParams,`Task not found: ${w.params.taskId}`);if(Mw(W.status))throw new u(c.InvalidParams,`Cannot cancel task in terminal status: ${W.status}`);await this._taskStore.updateTaskStatus(w.params.taskId,"cancelled","Client cancelled task execution.",$.sessionId),this._clearTaskQueue(w.params.taskId);let Q=await this._taskStore.getTask(w.params.taskId,$.sessionId);if(!Q)throw new u(c.InvalidParams,`Task not found after cancellation: ${w.params.taskId}`);return{_meta:{},...Q}}catch(W){if(W instanceof u)throw W;throw new u(c.InvalidRequest,`Failed to cancel task: ${W instanceof Error?W.message:String(W)}`)}})}async _oncancel(b){if(!b.params.requestId)return;this._requestHandlerAbortControllers.get(b.params.requestId)?.abort(b.params.reason)}_setupTimeout(b,w,$,W,Q=!1){this._timeoutInfo.set(b,{timeoutId:setTimeout(W,w),startTime:Date.now(),timeout:w,maxTotalTimeout:$,resetTimeoutOnProgress:Q,onTimeout:W})}_resetTimeout(b){let w=this._timeoutInfo.get(b);if(!w)return!1;let $=Date.now()-w.startTime;if(w.maxTotalTimeout&&$>=w.maxTotalTimeout)throw this._timeoutInfo.delete(b),u.fromError(c.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:w.maxTotalTimeout,totalElapsed:$});return clearTimeout(w.timeoutId),w.timeoutId=setTimeout(w.onTimeout,w.timeout),!0}_cleanupTimeout(b){let w=this._timeoutInfo.get(b);if(w)clearTimeout(w.timeoutId),this._timeoutInfo.delete(b)}async connect(b){this._transport=b;let w=this.transport?.onclose;this._transport.onclose=()=>{w?.(),this._onclose()};let $=this.transport?.onerror;this._transport.onerror=(Q)=>{$?.(Q),this._onerror(Q)};let W=this._transport?.onmessage;this._transport.onmessage=(Q,G)=>{if(W?.(Q,G),T1(Q)||ZG(Q))this._onresponse(Q);else if(x4(Q))this._onrequest(Q,G);else if(IG(Q))this._onnotification(Q);else this._onerror(Error(`Unknown message type: ${JSON.stringify(Q)}`))},await this._transport.start()}_onclose(){let b=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();let w=u.fromError(c.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let $ of b.values())$(w)}_onerror(b){this.onerror?.(b)}_onnotification(b){let w=this._notificationHandlers.get(b.method)??this.fallbackNotificationHandler;if(w===void 0)return;Promise.resolve().then(()=>w(b)).catch(($)=>this._onerror(Error(`Uncaught error in notification handler: ${$}`)))}_onrequest(b,w){let $=this._requestHandlers.get(b.method)??this.fallbackRequestHandler,W=this._transport,Q=b.params?._meta?.[Kw]?.taskId;if($===void 0){let H={jsonrpc:"2.0",id:b.id,error:{code:c.MethodNotFound,message:"Method not found"}};if(Q&&this._taskMessageQueue)this._enqueueTaskMessage(Q,{type:"error",message:H,timestamp:Date.now()},W?.sessionId).catch((J)=>this._onerror(Error(`Failed to enqueue error response: ${J}`)));else W?.send(H).catch((J)=>this._onerror(Error(`Failed to send an error response: ${J}`)));return}let G=new AbortController;this._requestHandlerAbortControllers.set(b.id,G);let D=FG(b.params)?b.params.task:void 0,X=this._taskStore?this.requestTaskStore(b,W?.sessionId):void 0,Y={signal:G.signal,sessionId:W?.sessionId,_meta:b.params?._meta,sendNotification:async(H)=>{let J={relatedRequestId:b.id};if(Q)J.relatedTask={taskId:Q};await this.notification(H,J)},sendRequest:async(H,J,z)=>{let O={...z,relatedRequestId:b.id};if(Q&&!O.relatedTask)O.relatedTask={taskId:Q};let q=O.relatedTask?.taskId??Q;if(q&&X)await X.updateTaskStatus(q,"input_required");return await this.request(H,J,O)},authInfo:w?.authInfo,requestId:b.id,requestInfo:w?.requestInfo,taskId:Q,taskStore:X,taskRequestedTtl:D?.ttl,closeSSEStream:w?.closeSSEStream,closeStandaloneSSEStream:w?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(D)this.assertTaskHandlerCapability(b.method)}).then(()=>$(b,Y)).then(async(H)=>{if(G.signal.aborted)return;let J={result:H,jsonrpc:"2.0",id:b.id};if(Q&&this._taskMessageQueue)await this._enqueueTaskMessage(Q,{type:"response",message:J,timestamp:Date.now()},W?.sessionId);else await W?.send(J)},async(H)=>{if(G.signal.aborted)return;let J={jsonrpc:"2.0",id:b.id,error:{code:Number.isSafeInteger(H.code)?H.code:c.InternalError,message:H.message??"Internal error",...H.data!==void 0&&{data:H.data}}};if(Q&&this._taskMessageQueue)await this._enqueueTaskMessage(Q,{type:"error",message:J,timestamp:Date.now()},W?.sessionId);else await W?.send(J)}).catch((H)=>this._onerror(Error(`Failed to send response: ${H}`))).finally(()=>{this._requestHandlerAbortControllers.delete(b.id)})}_onprogress(b){let{progressToken:w,...$}=b.params,W=Number(w),Q=this._progressHandlers.get(W);if(!Q){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(b)}`));return}let G=this._responseHandlers.get(W),D=this._timeoutInfo.get(W);if(D&&G&&D.resetTimeoutOnProgress)try{this._resetTimeout(W)}catch(X){this._responseHandlers.delete(W),this._progressHandlers.delete(W),this._cleanupTimeout(W),G(X);return}Q($)}_onresponse(b){let w=Number(b.id),$=this._requestResolvers.get(w);if($){if(this._requestResolvers.delete(w),T1(b))$(b);else{let G=new u(b.error.code,b.error.message,b.error.data);$(G)}return}let W=this._responseHandlers.get(w);if(W===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(b)}`));return}this._responseHandlers.delete(w),this._cleanupTimeout(w);let Q=!1;if(T1(b)&&b.result&&typeof b.result==="object"){let G=b.result;if(G.task&&typeof G.task==="object"){let D=G.task;if(typeof D.taskId==="string")Q=!0,this._taskProgressTokens.set(D.taskId,w)}}if(!Q)this._progressHandlers.delete(w);if(T1(b))W(b);else{let G=u.fromError(b.error.code,b.error.message,b.error.data);W(G)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(b,w,$){let{task:W}=$??{};if(!W){try{yield{type:"result",result:await this.request(b,w,$)}}catch(G){yield{type:"error",error:G instanceof u?G:new u(c.InternalError,String(G))}}return}let Q;try{let G=await this.request(b,iw,$);if(G.task)Q=G.task.taskId,yield{type:"taskCreated",task:G.task};else throw new u(c.InternalError,"Task creation did not return a task");while(!0){let D=await this.getTask({taskId:Q},$);if(yield{type:"taskStatus",task:D},Mw(D.status)){if(D.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:Q},w,$)};else if(D.status==="failed")yield{type:"error",error:new u(c.InternalError,`Task ${Q} failed`)};else if(D.status==="cancelled")yield{type:"error",error:new u(c.InternalError,`Task ${Q} was cancelled`)};return}if(D.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:Q},w,$)};return}let X=D.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((Y)=>setTimeout(Y,X)),$?.signal?.throwIfAborted()}}catch(G){yield{type:"error",error:G instanceof u?G:new u(c.InternalError,String(G))}}}request(b,w,$){let{relatedRequestId:W,resumptionToken:Q,onresumptiontoken:G,task:D,relatedTask:X}=$??{};return new Promise((Y,H)=>{let J=(M)=>{H(M)};if(!this._transport){J(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(b.method),D)this.assertTaskCapability(b.method)}catch(M){J(M);return}$?.signal?.throwIfAborted();let z=this._requestMessageId++,O={...b,jsonrpc:"2.0",id:z};if($?.onprogress)this._progressHandlers.set(z,$.onprogress),O.params={...b.params,_meta:{...b.params?._meta||{},progressToken:z}};if(D)O.params={...O.params,task:D};if(X)O.params={...O.params,_meta:{...O.params?._meta||{},[Kw]:X}};let q=(M)=>{this._responseHandlers.delete(z),this._progressHandlers.delete(z),this._cleanupTimeout(z),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:z,reason:String(M)}},{relatedRequestId:W,resumptionToken:Q,onresumptiontoken:G}).catch((S)=>this._onerror(Error(`Failed to send cancellation: ${S}`)));let v=M instanceof u?M:new u(c.RequestTimeout,String(M));H(v)};this._responseHandlers.set(z,(M)=>{if($?.signal?.aborted)return;if(M instanceof Error)return H(M);try{let v=Fw(w,M.result);if(!v.success)H(v.error);else Y(v.data)}catch(v){H(v)}}),$?.signal?.addEventListener("abort",()=>{q($?.signal?.reason)});let B=$?.timeout??FO,K=()=>q(u.fromError(c.RequestTimeout,"Request timed out",{timeout:B}));this._setupTimeout(z,B,$?.maxTotalTimeout,K,$?.resetTimeoutOnProgress??!1);let I=X?.taskId;if(I){let M=(v)=>{let S=this._responseHandlers.get(z);if(S)S(v);else this._onerror(Error(`Response handler missing for side-channeled request ${z}`))};this._requestResolvers.set(z,M),this._enqueueTaskMessage(I,{type:"request",message:O,timestamp:Date.now()}).catch((v)=>{this._cleanupTimeout(z),H(v)})}else this._transport.send(O,{relatedRequestId:W,resumptionToken:Q,onresumptiontoken:G}).catch((M)=>{this._cleanupTimeout(z),H(M)})})}async getTask(b,w){return this.request({method:"tasks/get",params:b},g0,w)}async getTaskResult(b,w,$){return this.request({method:"tasks/result",params:b},w,$)}async listTasks(b,w){return this.request({method:"tasks/list",params:b},l0,w)}async cancelTask(b,w){return this.request({method:"tasks/cancel",params:b},NG,w)}async notification(b,w){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(b.method);let $=w?.relatedTask?.taskId;if($){let D={...b,jsonrpc:"2.0",params:{...b.params,_meta:{...b.params?._meta||{},[Kw]:w.relatedTask}}};await this._enqueueTaskMessage($,{type:"notification",message:D,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(b.method)&&!b.params&&!w?.relatedRequestId&&!w?.relatedTask){if(this._pendingDebouncedNotifications.has(b.method))return;this._pendingDebouncedNotifications.add(b.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(b.method),!this._transport)return;let D={...b,jsonrpc:"2.0"};if(w?.relatedTask)D={...D,params:{...D.params,_meta:{...D.params?._meta||{},[Kw]:w.relatedTask}}};this._transport?.send(D,w).catch((X)=>this._onerror(X))});return}let G={...b,jsonrpc:"2.0"};if(w?.relatedTask)G={...G,params:{...G.params,_meta:{...G.params?._meta||{},[Kw]:w.relatedTask}}};await this._transport.send(G,w)}setRequestHandler(b,w){let $=b6(b);this.assertRequestHandlerCapability($),this._requestHandlers.set($,(W,Q)=>{let G=w6(b,W);return Promise.resolve(w(G,Q))})}removeRequestHandler(b){this._requestHandlers.delete(b)}assertCanSetRequestHandler(b){if(this._requestHandlers.has(b))throw Error(`A request handler for ${b} already exists, which would be overridden`)}setNotificationHandler(b,w){let $=b6(b);this._notificationHandlers.set($,(W)=>{let Q=w6(b,W);return Promise.resolve(w(Q))})}removeNotificationHandler(b){this._notificationHandlers.delete(b)}_cleanupTaskProgressHandler(b){let w=this._taskProgressTokens.get(b);if(w!==void 0)this._progressHandlers.delete(w),this._taskProgressTokens.delete(b)}async _enqueueTaskMessage(b,w,$){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let W=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(b,w,$,W)}async _clearTaskQueue(b,w){if(this._taskMessageQueue){let $=await this._taskMessageQueue.dequeueAll(b,w);for(let W of $)if(W.type==="request"&&x4(W.message)){let Q=W.message.id,G=this._requestResolvers.get(Q);if(G)G(new u(c.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(Q);else this._onerror(Error(`Resolver missing for request ${Q} during task ${b} cleanup`))}}}async _waitForTaskUpdate(b,w){let $=this._options?.defaultTaskPollInterval??1000;try{let W=await this._taskStore?.getTask(b);if(W?.pollInterval)$=W.pollInterval}catch{}return new Promise((W,Q)=>{if(w.aborted){Q(new u(c.InvalidRequest,"Request cancelled"));return}let G=setTimeout(W,$);w.addEventListener("abort",()=>{clearTimeout(G),Q(new u(c.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(b,w){let $=this._taskStore;if(!$)throw Error("No task store configured");return{createTask:async(W)=>{if(!b)throw Error("No request provided");return await $.createTask(W,b.id,{method:b.method,params:b.params},w)},getTask:async(W)=>{let Q=await $.getTask(W,w);if(!Q)throw new u(c.InvalidParams,"Failed to retrieve task: Task not found");return Q},storeTaskResult:async(W,Q,G)=>{await $.storeTaskResult(W,Q,G,w);let D=await $.getTask(W,w);if(D){let X=v1.parse({method:"notifications/tasks/status",params:D});if(await this.notification(X),Mw(D.status))this._cleanupTaskProgressHandler(W)}},getTaskResult:(W)=>{return $.getTaskResult(W,w)},updateTaskStatus:async(W,Q,G)=>{let D=await $.getTask(W,w);if(!D)throw new u(c.InvalidParams,`Task "${W}" not found - it may have been cleaned up`);if(Mw(D.status))throw new u(c.InvalidParams,`Cannot update task "${W}" from terminal status "${D.status}" to "${Q}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await $.updateTaskStatus(W,Q,G,w);let X=await $.getTask(W,w);if(X){let Y=v1.parse({method:"notifications/tasks/status",params:X});if(await this.notification(Y),Mw(X.status))this._cleanupTaskProgressHandler(W)}},listTasks:(W)=>{return $.listTasks(W,w)}}}}function kG(b){return b!==null&&typeof b==="object"&&!Array.isArray(b)}function CG(b,w){let $={...b};for(let W in w){let Q=W,G=w[Q];if(G===void 0)continue;let D=$[Q];if(kG(D)&&kG(G))$[Q]={...D,...G};else $[Q]=G}return $}var zJ=uW(r6(),1),AJ=uW(JJ(),1);function EK(){let b=new zJ.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return AJ.default(b),b}class DW{constructor(b){this._ajv=b??EK()}getValidator(b){let w="$id"in b&&typeof b.$id==="string"?this._ajv.getSchema(b.$id)??this._ajv.compile(b):this._ajv.compile(b);return($)=>{if(w($))return{valid:!0,data:$,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(w.errors)}}}}class XW{constructor(b){this._server=b}requestStream(b,w,$){return this._server.requestStream(b,w,$)}async getTask(b,w){return this._server.getTask({taskId:b},w)}async getTaskResult(b,w,$){return this._server.getTaskResult({taskId:b},w,$)}async listTasks(b,w){return this._server.listTasks(b?{cursor:b}:void 0,w)}async cancelTask(b,w){return this._server.cancelTask({taskId:b},w)}}function OJ(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 qJ(b,w,$){if(!b)throw Error(`${$} does not support task creation (required for ${w})`);switch(w){case"sampling/createMessage":if(!b.sampling?.createMessage)throw Error(`${$} does not support task creation for sampling/createMessage (required for ${w})`);break;case"elicitation/create":if(!b.elicitation?.create)throw Error(`${$} does not support task creation for elicitation/create (required for ${w})`);break;default:break}}class YW extends $6{constructor(b,w){super(w);if(this._serverInfo=b,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(u1.options.map(($,W)=>[$,W])),this.isMessageIgnored=($,W)=>{let Q=this._loggingLevels.get(W);return Q?this.LOG_LEVEL_SEVERITY.get($)<this.LOG_LEVEL_SEVERITY.get(Q):!1},this._capabilities=w?.capabilities??{},this._instructions=w?.instructions,this._jsonSchemaValidator=w?.jsonSchemaValidator??new DW,this.setRequestHandler(f4,($)=>this._oninitialize($)),this.setNotificationHandler(c4,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(r4,async($,W)=>{let Q=W.sessionId||W.requestInfo?.headers["mcp-session-id"]||void 0,{level:G}=$.params,D=u1.safeParse(G);if(D.success)this._loggingLevels.set(Q,D.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new XW(this)};return this._experimental}registerCapabilities(b){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=CG(this._capabilities,b)}setRequestHandler(b,w){let W=R0(b)?.method;if(!W)throw Error("Schema is missing a method literal");let Q;if(gw(W)){let D=W;Q=D._zod?.def?.value??D.value}else{let D=W;Q=D._def?.value??D.value}if(typeof Q!=="string")throw Error("Schema method literal must be a string");if(Q==="tools/call"){let D=async(X,Y)=>{let H=Fw(C1,X);if(!H.success){let q=H.error instanceof Error?H.error.message:String(H.error);throw new u(c.InvalidParams,`Invalid tools/call request: ${q}`)}let{params:J}=H.data,z=await Promise.resolve(w(X,Y));if(J.task){let q=Fw(iw,z);if(!q.success){let B=q.error instanceof Error?q.error.message:String(q.error);throw new u(c.InvalidParams,`Invalid task creation result: ${B}`)}return q.data}let O=Fw(o0,z);if(!O.success){let q=O.error instanceof Error?O.error.message:String(O.error);throw new u(c.InvalidParams,`Invalid tools/call result: ${q}`)}return O.data};return super.setRequestHandler(b,D)}return super.setRequestHandler(b,w)}assertCapabilityForMethod(b){switch(b){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${b})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${b})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${b})`);break;case"ping":break}}assertNotificationCapability(b){switch(b){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${b})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${b})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${b})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${b})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${b})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(b){if(!this._capabilities)return;switch(b){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${b})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${b})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${b})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${b})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${b})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${b})`);break;case"ping":case"initialize":break}}assertTaskCapability(b){qJ(this._clientCapabilities?.tasks?.requests,b,"Client")}assertTaskHandlerCapability(b){if(!this._capabilities)return;OJ(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:UG.includes(w)?w:C4,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},y0)}async createMessage(b,w){if(b.tools||b.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if(b.messages.length>0){let $=b.messages[b.messages.length-1],W=Array.isArray($.content)?$.content:[$.content],Q=W.some((Y)=>Y.type==="tool_result"),G=b.messages.length>1?b.messages[b.messages.length-2]:void 0,D=G?Array.isArray(G.content)?G.content:[G.content]:[],X=D.some((Y)=>Y.type==="tool_use");if(Q){if(W.some((Y)=>Y.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!X)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(X){let Y=new Set(D.filter((J)=>J.type==="tool_use").map((J)=>J.id)),H=new Set(W.filter((J)=>J.type==="tool_result").map((J)=>J.toolUseId));if(Y.size!==H.size||![...Y].every((J)=>H.has(J)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if(b.tools)return this.request({method:"sampling/createMessage",params:b},s4,w);return this.request({method:"sampling/createMessage",params:b},e4,w)}async elicitInput(b,w){switch(b.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let W=b;return this.request({method:"elicitation/create",params:W},d0,w)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let W=b.mode==="form"?b:{...b,mode:"form"},Q=await this.request({method:"elicitation/create",params:W},d0,w);if(Q.action==="accept"&&Q.content&&W.requestedSchema)try{let D=this._jsonSchemaValidator.getValidator(W.requestedSchema)(Q.content);if(!D.valid)throw new u(c.InvalidParams,`Elicitation response content does not match requested schema: ${D.errorMessage}`)}catch(G){if(G instanceof u)throw G;throw new u(c.InternalError,`Error validating elicitation response: ${G instanceof Error?G.message:String(G)}`)}return Q}}}createElicitationCompletionNotifier(b,w){if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:b}},w)}async listRoots(b,w){return this.request({method:"roots/list",params:b},a4,w)}async sendLoggingMessage(b,w){if(this._capabilities.logging){if(!this.isMessageIgnored(b.level,w))return this.notification({method:"notifications/message",params:b})}}async sendResourceUpdated(b){return this.notification({method:"notifications/resources/updated",params:b})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}var LJ={name:"@sequenzy/mcp",version:"0.0.117",mcpName:"io.github.sequenzy/mcp",description:"Sequenzy MCP server for AI-powered email marketing automation",type:"module",bin:{"sequenzy-mcp":"dist/index.js"},main:"./dist/index.js",exports:{".":"./dist/index.js","./server":"./dist/server.js","./runtime":"./dist/runtime.js","./server.json":"./server.json"},scripts:{dev:"bun --watch src/index.ts",build:"bun build src/index.ts src/server.ts src/runtime.ts --outdir dist --target node --minify",start:"node dist/index.js","type-check":"bunx --bun tsc --noEmit",test:"bun test","test:watch":"bun test --watch",prepublishOnly:"bun run build"},dependencies:{"@modelcontextprotocol/sdk":"^1.0.0"},devDependencies:{"@types/bun":"latest","@types/node":"^22.0.0","bun-types":"latest",typescript:"^7.0.2"},files:["dist","server.json"],keywords:["sequenzy","email","mcp","ai","claude","automation"],license:"MIT",publishConfig:{access:"public"},repository:{type:"git",url:"git+https://github.com/Sequenzy/mcp.git"},homepage:"https://sequenzy.com",bugs:{url:"https://github.com/Sequenzy/mcp/issues"}};var HW=["product-info","domain","tracking","localization","integrations","products","events","tags","labels","goals","sync-rules","api-keys","widgets","team","danger"],UJ={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 SK(b){let $=(b??process.env.SEQUENZY_APP_URL??"https://sequenzy.com").trim().replace(/\/+$/,"");return $.length>0?$:"https://sequenzy.com"}function ib(b){let w=b?.trim();return w?w:void 0}function eb(b){return encodeURIComponent(b)}function Db(b,w){return`${b}${w}`}function Xb(b,w=""){return`/dashboard/company/${eb(b)}${w}`}function BJ(b,w,$){return Db(b,`${Xb(w,"/settings")}?tab=${encodeURIComponent($)}`)}function RK(b,w){let $=HW.map((W)=>[W,w?BJ(b,w,W):""]);return Object.fromEntries($)}function Yw(b={},w){let $=SK(w),W=ib(b.companyId),Q={},G=RK($,W);if(!W)return{appUrl:$,routeTemplates:UJ,settingsTabValues:HW,urls:Q,settingsUrls:G};Q.dashboard=Db($,Xb(W)),Q.campaigns=Db($,Xb(W,"/campaign")),Q.landingPages=Db($,Xb(W,"/landing-pages")),Q.sequences=Db($,Xb(W,"/sequences")),Q.settings=Db($,Xb(W,"/settings")),Q.emails=Db($,Xb(W,"/emails")),Q.subscribers=Db($,Xb(W,"/subscribers")),Q.sentEmails=Db($,Xb(W,"/sent-emails")),Q.segments=Db($,Xb(W,"/segments")),Q.metrics=Db($,Xb(W,"/metrics")),Q.transactional=Db($,Xb(W,"/transactional"));let D=ib(b.campaignId);if(D)Q.campaign=Db($,Xb(W,`/campaign/${eb(D)}`)),Q.campaignPreview=`${Q.campaign}?step=review`;let X=ib(b.landingPageId);if(X)Q.landingPage=Db($,Xb(W,`/landing-pages/${eb(X)}`));let Y=ib(b.sequenceId);if(Y)Q.sequence=Db($,Xb(W,`/sequences/${eb(Y)}`));let H=ib(b.emailId)??ib(b.templateId);if(H)Q.email=Db($,Xb(W,`/emails/${eb(H)}`)),Q.template=Q.email;let J=ib(b.transactionalId);if(J)Q.transactionalEmail=Db($,Xb(W,`/transactional/${eb(J)}`));let z=ib(b.emailSendId);if(z)Q.emailSend=Db($,Xb(W,`/sent-emails/${eb(z)}`));let O=ib(b.domainId);if(O)Q.domain=Db($,Xb(W,`/settings/domain/${eb(O)}`)),Q.domainVerify=`${Q.domain}/verify`;let q=ib(b.status);if(q)Q.campaignList=Db($,Xb(W,`/campaign/list/${eb(q)}`)),Q.sequenceList=Db($,Xb(W,`/sequences/list/${eb(q)}`));let B=ib(b.settingsTab);if(B)Q.settingsTab=BJ($,W,B);return{appUrl:$,routeTemplates:UJ,settingsTabValues:HW,urls:Q,settingsUrls:G}}var PJ=[{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 FJ(b){try{let w;switch(b){case"sequenzy://dashboard":w=await A("GET","/api/v1/metrics?period=7d");break;case"sequenzy://company":{let $=await A("GET","/api/v1/account"),W=qw()??$.currentCompanyId;if(!W)throw Error("No company available. Create or select a company first.");w=await A("GET",`/api/v1/companies/${W}`);break}case"sequenzy://campaigns/recent":w=await A("GET","/api/v1/campaigns?limit=10");break;case"sequenzy://subscribers/recent":w=await A("GET","/api/v1/subscribers?sort=createdAt&limit=20");break;case"sequenzy://subscribers/engaged":w=await A("GET","/api/v1/subscribers?sort=engagement&limit=20");break;case"sequenzy://sequences":w=await A("GET","/api/v1/sequences");break;case"sequenzy://templates":w=await A("GET","/api/v1/templates");break;case"sequenzy://segments":w=await A("GET","/api/v1/segments");break;case"sequenzy://tags":w=await A("GET","/api/v1/tags");break;case"sequenzy://health":w=await A("GET","/api/v1/health/deliverability");break;case"sequenzy://app-routes":w=Yw();break;default:throw Error(`Unknown resource: ${b}`)}return{contents:[{uri:b,mimeType:"application/json",text:JSON.stringify(w,null,2)}]}}catch(w){return{contents:[{uri:b,mimeType:"text/plain",text:Ow(w)}]}}}function y(b){return typeof b==="object"&&b!==null&&!Array.isArray(b)}function P(b,w){let $=b[w];if(typeof $!=="string")return;let W=$.trim();return W.length>0?W:void 0}function Z(b,w,$){let W=P(w,$);if(W===void 0)throw Error(`\`${$}\` is required when calling \`${b}\`.`);return W}var _w='For exact historical Poll/NPS respondents, use field `pollResponse`, operator `is`, and a JSON value shaped like {"v":1,"campaignId":"camp_123","blockId":"poll_1","match":{"kind":"answer","value":"loved"}}. For NPS buckets, use match {"kind":"npsBucket","bucket":"promoters"}; bucket may be `promoters`, `passives`, or `detractors`.',Hw='Sequenzy email blocks. Use this for editor-compatible content, including conditional and repeat blocks. For provider-migrated HTML from another email platform, prefer the `html` field instead; Sequenzy stores it as one raw HTML block to preserve the original design. Use `styles` for per-block background, background opacity, text color, padding, border radius, border width, and border color. Top-level style aliases such as `backgroundColor`, `backgroundOpacity`, `borderColor`, `borderWidth`, and `borderRadius` are also accepted and saved under `styles`. Repeat blocks use { type: \'repeat\', source: \'items\', itemAlias: \'item\', children: [...] }. Any block accepts a `conditions` array so it only renders for matching recipients. To branch on a value passed in transactional `variables` or an automation `event` payload, use { "id": "c1", "field": "variable", "operator": "is", "value": "plan:pro" }; "attribute" uses the same "name:value" form, while "email"/"firstName"/"lastName" use a plain comparison value. Live subscriber fields are "status", "tag", "list", "segment", "event", "emailProvider", "phone", "smsStatus", "added", "stripeProduct", "stripeCurrentProduct", "stripeTrialProduct", "commerceProduct", "emailSent", "emailDelivered", "emailOpened", "emailClicked", "emailBounced", and "emailComplained". They use the same field-specific values and operators as segment filters, for example { "id": "c2", "field": "segment", "operator": "is", "value": "seg_123" }, { "id": "c3", "field": "tag", "operator": "contains", "value": "vip" }, or { "id": "c4", "field": "event", "operator": "at_least", "value": "purchase:3:30d" }. Supported operators across fields are is, is_not, contains, not_contains, gt, gte, lt, lte, less_than, more_than, at_least, less_than_count, is_empty, is_not_empty, is_temporary_bounce, and is_permanent_bounce; each field accepts only its segment-filter operators. Recipients without a stored subscriber match use the OTHERWISE branch or hide a conditionally displayed block. For if/else, use a { type: "conditional-group", conditions: [...], ifBranch: { children: [...] }, elseBranch: { children: [...] } } block. Polls and NPS surveys use a native poll block. For answer buttons use { "type": "poll", "variant": "options", "question": "What did you think?", "options": [{ "label": "Loved it", "value": "loved" }, { "label": "Not for me", "value": "not_for_me" }], "attributeKey": "email_feedback" }. For NPS use { "type": "poll", "variant": "nps", "question": "How likely are you to recommend us?", "options": [], "attributeKey": "nps_score", "npsLowLabel": "Not likely", "npsHighLabel": "Very likely" }. `attributeKey` stores the latest response for segmentation. Optional `appearance` picks the answer style: "soft" (default), "pill", "outline", "filled", "pop" (hard-shadow boxes), "brutal" (square uppercase slabs), "quiz" (A/B/C letter badges), or "minimal" (bare ruled rows). Optional `confirmationMessage` customizes the hosted thank-you page; set `redirectUrl` only when respondents should land on another page. For a new image, call `upload_image_asset` first and insert its returned `imageBlock`. A responsive fixed-height screenshot crop uses { "type": "image", "src": "https://...", "alt": "Product dashboard", "width": 100, "widthType": "percent", "height": 320, "objectFit": "cover", "align": "center" }.',Jw='Replacement Sequenzy email blocks. Use `styles` for per-block background, background opacity, text color, padding, border radius, border width, and border color. Top-level style aliases such as `backgroundColor`, `backgroundOpacity`, `borderColor`, `borderWidth`, and `borderRadius` are also accepted and saved under `styles`. Any block accepts a `conditions` array so it only renders for matching recipients. To branch on a value passed in transactional `variables` or an automation `event` payload, use { "id": "c1", "field": "variable", "operator": "is", "value": "plan:pro" }; "attribute" uses the same "name:value" form, while "email"/"firstName"/"lastName" use a plain comparison value. Live subscriber fields are "status", "tag", "list", "segment", "event", "emailProvider", "phone", "smsStatus", "added", "stripeProduct", "stripeCurrentProduct", "stripeTrialProduct", "commerceProduct", "emailSent", "emailDelivered", "emailOpened", "emailClicked", "emailBounced", and "emailComplained". They use the same field-specific values and operators as segment filters, for example { "id": "c2", "field": "segment", "operator": "is", "value": "seg_123" }, { "id": "c3", "field": "tag", "operator": "contains", "value": "vip" }, or { "id": "c4", "field": "event", "operator": "at_least", "value": "purchase:3:30d" }. Supported operators across fields are is, is_not, contains, not_contains, gt, gte, lt, lte, less_than, more_than, at_least, less_than_count, is_empty, is_not_empty, is_temporary_bounce, and is_permanent_bounce; each field accepts only its segment-filter operators. Recipients without a stored subscriber match use the OTHERWISE branch or hide a conditionally displayed block. For if/else, use a { type: "conditional-group", conditions: [...], ifBranch: { children: [...] }, elseBranch: { children: [...] } } block. Polls and NPS surveys use a native poll block. For answer buttons use { "type": "poll", "variant": "options", "question": "What did you think?", "options": [{ "label": "Loved it", "value": "loved" }, { "label": "Not for me", "value": "not_for_me" }], "attributeKey": "email_feedback" }. For NPS use { "type": "poll", "variant": "nps", "question": "How likely are you to recommend us?", "options": [], "attributeKey": "nps_score", "npsLowLabel": "Not likely", "npsHighLabel": "Very likely" }. `attributeKey` stores the latest response for segmentation. Optional `appearance` picks the answer style: "soft" (default), "pill", "outline", "filled", "pop" (hard-shadow boxes), "brutal" (square uppercase slabs), "quiz" (A/B/C letter badges), or "minimal" (bare ruled rows). Optional `confirmationMessage` customizes the hosted thank-you page; set `redirectUrl` only when respondents should land on another page. For a new image, call `upload_image_asset` first and insert its returned `imageBlock`. A responsive fixed-height screenshot crop uses { "type": "image", "src": "https://...", "alt": "Product dashboard", "width": 100, "widthType": "percent", "height": 320, "objectFit": "cover", "align": "center" }.',W1='Sequenzy email blocks. Provide blocks or html for email steps. For migrated provider HTML, prefer `html`; Sequenzy stores it as one raw HTML block and does not recreate it as native blocks. Use `styles` for per-block background, background opacity, text color, padding, border radius, border width, and border color. Top-level style aliases such as `backgroundColor`, `backgroundOpacity`, `borderColor`, `borderWidth`, and `borderRadius` are also accepted and saved under `styles`. Blocks can include repeat blocks over array variables such as items. Any block accepts a `conditions` array so it only renders for matching recipients. To branch on a value passed in transactional `variables` or an automation `event` payload, use { "id": "c1", "field": "variable", "operator": "is", "value": "plan:pro" }; "attribute" uses the same "name:value" form, while "email"/"firstName"/"lastName" use a plain comparison value. Live subscriber fields are "status", "tag", "list", "segment", "event", "emailProvider", "phone", "smsStatus", "added", "stripeProduct", "stripeCurrentProduct", "stripeTrialProduct", "commerceProduct", "emailSent", "emailDelivered", "emailOpened", "emailClicked", "emailBounced", and "emailComplained". They use the same field-specific values and operators as segment filters, for example { "id": "c2", "field": "segment", "operator": "is", "value": "seg_123" }, { "id": "c3", "field": "tag", "operator": "contains", "value": "vip" }, or { "id": "c4", "field": "event", "operator": "at_least", "value": "purchase:3:30d" }. Supported operators across fields are is, is_not, contains, not_contains, gt, gte, lt, lte, less_than, more_than, at_least, less_than_count, is_empty, is_not_empty, is_temporary_bounce, and is_permanent_bounce; each field accepts only its segment-filter operators. Recipients without a stored subscriber match use the OTHERWISE branch or hide a conditionally displayed block. For if/else, use a { type: "conditional-group", conditions: [...], ifBranch: { children: [...] }, elseBranch: { children: [...] } } block. Polls and NPS surveys use a native poll block. For answer buttons use { "type": "poll", "variant": "options", "question": "What did you think?", "options": [{ "label": "Loved it", "value": "loved" }, { "label": "Not for me", "value": "not_for_me" }], "attributeKey": "email_feedback" }. For NPS use { "type": "poll", "variant": "nps", "question": "How likely are you to recommend us?", "options": [], "attributeKey": "nps_score", "npsLowLabel": "Not likely", "npsHighLabel": "Very likely" }. `attributeKey` stores the latest response for segmentation. Optional `appearance` picks the answer style: "soft" (default), "pill", "outline", "filled", "pop" (hard-shadow boxes), "brutal" (square uppercase slabs), "quiz" (A/B/C letter badges), or "minimal" (bare ruled rows). Optional `confirmationMessage` customizes the hosted thank-you page; set `redirectUrl` only when respondents should land on another page. For a new image, call `upload_image_asset` first and insert its returned `imageBlock`. A responsive fixed-height screenshot crop uses { "type": "image", "src": "https://...", "alt": "Product dashboard", "width": 100, "widthType": "percent", "height": 320, "objectFit": "cover", "align": "center" }.',D0="Complete Sequenzy landing page content JSON. Use this when replacing the page structure. The content must be the editor-compatible landing page schema with version, template, seo, theme, and blocks. Landing pages must include exactly one footer block and at most one form block.",KJ="Optional template key for default content, such as from-scratch, waitlist, lead-magnet, launch, demo-request, webinar, newsletter, product-hunt, pricing-offer, agency-lead-gen, or feature-announcement.",JW=500,zW=500,lb={type:"boolean",description:"If true, include machine-classified bot/scanner opens and clicks. Defaults to false, so metrics and activity are human-only."},k$=["send","delivery","bounce","complaint","open","click","unsubscribe","delivery_delay"],C$={type:"object",description:"Optional send window for every email step in the sequence. When set, email actions that become due outside the window wait until the next allowed local time. Omit days to allow every day.",properties:{enabled:{type:"boolean",description:"Set false to disable the sending window when creating a sequence. For updates, prefer clearSendingWindow."},timezone:{type:"string",description:"IANA timezone for the window, e.g. Europe/Kiev or America/New_York."},startTime:{type:"string",description:"Earliest local send time in 24-hour HH:mm format, e.g. 08:00."},endTime:{type:"string",description:"Latest local send cutoff in 24-hour HH:mm format, e.g. 20:00. Must be later than startTime."},days:{type:"array",description:"Allowed local days. Use full names or short names such as monday, tuesday, mon, tue. Omit for every day.",items:{type:"string"}}},additionalProperties:!1},vK={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:vK,days:{type:"number",description:"Offset days shorthand. Ignored when offset is provided."},hours:{type:"number",description:"Offset hours shorthand. Ignored when offset is provided."},minutes:{type:"number",description:"Offset minutes shorthand. Ignored when offset is provided."},direction:{type:"string",enum:["before","after"],description:"Whether the offset applies before or after the resolved date. Defaults to after."},untilOffsetDirection:{type:"string",enum:["before","after"],description:"Alias for direction."},missingAction:{type:"string",enum:["continue","exit"],description:"What to do if the event field is missing or invalid. Defaults to continue."},untilMissingAction:{type:"string",enum:["continue","exit"],description:"Alias for missingAction."}},additionalProperties:!1},G1={type:"object",description:"Fixed delay before this step. For a dynamic wait-until-date delay, either set mode:'until_date' plus untilDateField here, or use waitUntil.",properties:{days:{type:"number"},hours:{type:"number"},minutes:{type:"number"},mode:{type:"string",enum:["duration","until_date"],description:"Use duration for a fixed wait, or until_date to resolve a date from the trigger event."},untilDateField:{type:"string",description:"For mode:'until_date', dot-path into the trigger event properties."},field:{type:"string",description:"Alias for untilDateField."},untilOffsetDirection:{type:"string",enum:["before","after"],description:"For mode:'until_date', whether days/hours/minutes are before or after the event date. Defaults to after."},direction:{type:"string",enum:["before","after"],description:"Alias for untilOffsetDirection."},untilMissingAction:{type:"string",enum:["continue","exit"],description:"For mode:'until_date', what to do when the field is missing or invalid. Defaults to continue."},missingAction:{type:"string",enum:["continue","exit"],description:"Alias for untilMissingAction."}},additionalProperties:!1},AW={type:"object",description:"Type-aware patch for the existing node. Start from get_sequence.sequence.nodes[].config. For logic_delay, set exactly one of delay ({ days, hours, minutes }), delayMs, or waitUntil; optional label is also accepted. For action_email, use name/label, subject, previewText, html/htmlContent or blocks, 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. 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. Raw HTML emails do not support this field, and it must not be combined with html/htmlContent."}},additionalProperties:!0},u$={type:"object",properties:{nodeId:{type:"string",description:"Existing node ID from get_sequence.sequence.nodes[].id."},changes:AW,expectedUpdatedAt:{type:"string",description:"Required optimistic-concurrency value from get_sequence.sequence.nodes[].updatedAt. The update is rejected if that node or its linked email content changed after it was read."}},required:["nodeId","changes","expectedUpdatedAt"],additionalProperties:!1},D1=["gray","red","orange","amber","yellow","lime","green","emerald","teal","cyan","sky","blue","indigo","violet","purple","fuchsia","pink","rose"],X1=["email.sent","email.delivered","email.delivery_delayed","email.bounced","email.complained","email.opened","email.clicked","email.replied","email.unsubscribed","sms.sent","sms.delivered","sms.failed","sms.opted_out","subscriber.invalid","subscriber.updated","subscriber.unsubscribed","subscriber.list_subscribed","subscriber.list_unsubscribed","sequence.finished","sequence.failed","poll.answered"];var kK=new Set(["get_account","get_app_urls","get_company","get_sync_rules","get_shopify_automation_settings","list_websites","check_website","get_integration_guide","get_subscriber","list_subscriber_notes","search_subscribers","list_products","list_tags","list_lists","list_segments","get_segment_count","list_audience_syncs","list_ad_accounts","list_templates","get_template","list_ab_tests","get_ab_test","get_ab_test_stats","list_campaigns","get_campaign","get_email_send","list_forms","get_form_embed","get_recipient_suppression","list_landing_pages","get_landing_page","list_sequences","get_sequence","list_transactional_emails","get_transactional_email","get_stats","get_campaign_stats","get_sequence_stats","list_campaign_events","list_sequence_events","get_subscriber_activity","list_team_members","list_conversations","get_conversation","list_webhooks","list_webhook_deliveries","generate_email","generate_subject_lines","generate_sms","get_sms_settings"]),CK=new Set(["select_company","create_company","update_company","update_sync_rules","update_shopify_automation_settings","create_api_key","add_sending_domain","add_website","verify_sending_domain","add_subscriber","update_subscriber","add_subscriber_note","remove_subscriber","delete_subscriber_note","upsert_products","delete_product","attach_product_file","remove_product_file","upload_image_asset","sync_products","create_tag","update_tag","delete_tag","create_list","update_list","delete_list","add_subscribers_to_list","remove_subscribers_from_list","create_segment","update_segment","delete_segment","create_audience_sync","update_audience_sync","delete_audience_sync","sync_audience_now","create_template","update_template","set_template_localization","sync_template_localizations","delete_template","restart_ab_test","update_ab_test_variant","create_ab_test","add_ab_test_variant","delete_ab_test_variant","delete_ab_test","create_campaign","update_campaign","schedule_campaign","send_test_email","send_test_sms","cancel_campaign","pause_campaign","resume_campaign","delete_campaign","duplicate_campaign","resend_campaign_to_non_openers","create_form","create_landing_page","update_landing_page","delete_landing_page","publish_landing_page","unpublish_landing_page","connect_landing_page_domain","update_landing_page_domain_settings","create_sequence","generate_sequence","update_sequence","update_sequence_node","update_sequence_nodes","edit_sequence_graph","insert_sequence_step","enable_sequence","disable_sequence","pause_sequence_enrollments","resume_sequence_enrollments","enroll_subscribers_in_sequence","cancel_sequence_enrollments","delete_sequence","create_transactional_email","update_transactional_email","send_email","invite_team_member","cancel_team_invitation","reply_to_conversation","update_conversation_status","mark_conversation_read","create_webhook","update_webhook","delete_webhook","test_webhook","replay_webhook_delivery","submit_feedback","remove_recipient_suppression"]),uK=new Set(["send_test_email","send_test_sms","schedule_campaign","resume_campaign","publish_landing_page","connect_landing_page_domain","update_landing_page_domain_settings","add_sending_domain","add_website","verify_sending_domain","enable_sequence","resume_sequence_enrollments","send_email","invite_team_member","reply_to_conversation","create_webhook","update_webhook","test_webhook","replay_webhook_delivery","remove_recipient_suppression"]),xK=new Set(["remove_subscriber","delete_subscriber_note","delete_product","remove_product_file","delete_tag","delete_list","remove_subscribers_from_list","delete_segment","delete_audience_sync","delete_template","restart_ab_test","delete_ab_test_variant","delete_ab_test","cancel_campaign","delete_campaign","delete_landing_page","unpublish_landing_page","disable_sequence","edit_sequence_graph","cancel_sequence_enrollments","delete_sequence","cancel_team_invitation","delete_webhook","remove_recipient_suppression"]);function yK(b){let w=kK.has(b),$=CK.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:xK.has(b),openWorldHint:uK.has(b)}}function MJ(b){return{...b,annotations:{...b.annotations,...yK(b.name)}}}var OW={status:["is","is_not"],phone:["is_not_empty","is_empty"],smsStatus:["is","is_not"],tag:["contains","not_contains","is_empty","is_not_empty"],email:["contains","not_contains"],emailProvider:["is","is_not","is_empty","is_not_empty"],added:["less_than","more_than"],firstName:["contains","not_contains","is_empty","is_not_empty"],lastName:["contains","not_contains","is_empty","is_not_empty"],list:["is","is_not","is_empty","is_not_empty"],emailSent:["is","is_not","at_least","less_than_count"],emailDelivered:["is","is_not","at_least","less_than_count"],emailOpened:["is","is_not","at_least","less_than_count"],emailClicked:["is","is_not","at_least","less_than_count"],emailBounced:["is","is_temporary_bounce","is_permanent_bounce","is_not","at_least","less_than_count"],emailComplained:["is","is_not","at_least","less_than_count"],attribute:["is","is_not","is_empty","is_not_empty","gte","lte","gt","lt","contains","not_contains"],event:["is","is_not","at_least","less_than_count"],pollResponse:["is"],segment:["is","is_not"],stripeProduct:["is","is_not","at_least","less_than_count"],stripeCurrentProduct:["is","is_not","gte","lte","gt","lt"],stripeTrialProduct:["is","is_not","gte","lte","gt","lt"],commerceProduct:["is","is_not","at_least","less_than_count"]},hK=Object.entries(OW).map(([b,w])=>`${b}: ${w.join(", ")}`).join("; "),qW={type:"object",properties:{id:{type:"string",description:"Optional filter ID. Any stable string works; one will be generated if omitted."},field:{type:"string",enum:["status","phone","smsStatus","tag","email","emailProvider","added","firstName","lastName","list","emailSent","emailDelivered","emailOpened","emailClicked","emailBounced","emailComplained","attribute","event","pollResponse","segment","stripeProduct","stripeCurrentProduct","stripeTrialProduct","commerceProduct"],description:`Filter field. Use \`phone\` with is_not_empty/is_empty to check whether a subscriber has a phone number, and \`smsStatus\` (is/is_not one of \`subscribed\`, \`unsubscribed\`, \`not_subscribed\`) for SMS marketing consent. Use \`event\` for custom subscriber events, \`segment\` for saved segment membership, \`stripeProduct\`/\`stripeCurrentProduct\`/\`stripeTrialProduct\` for Stripe product-based segments, and \`commerceProduct\` for products purchased through commerce orders - the value is \`provider:productId\` (provider one of \`shopify\`, \`woocommerce\`, \`api\`; product ids are provider-scoped), optionally with an order-count threshold (\`provider:productId:count\`) for at_least/less_than_count; a bare product id matches the id on any provider. Engagement fields (\`emailSent\`, \`emailDelivered\`, \`emailOpened\`, \`emailClicked\`, \`emailBounced\`, \`emailComplained\`) accept a time range as the value, a specific campaign via \`campaign:<campaign_id>\`, or \`count:timeRange\` (e.g. \`10:30d\`, \`10:all\`) with at_least/less_than_count to segment by number of opens/clicks. ${_w}`},operator:{type:"string",enum:["is","is_not","is_empty","is_not_empty","contains","not_contains","less_than","more_than","is_temporary_bounce","is_permanent_bounce","at_least","less_than_count","gte","lte","gt","lt"],description:`Filter operator. Allowed operators by field: ${hK}.`},value:{type:"string",description:`Filter value. For custom attribute empty checks, use \`attributeName:\` such as \`last_logged_in:\`. Event examples: \`saas.purchase:30d\`, \`saas.purchase:all\`, or \`saas.purchase:5:30d\` for thresholds. Segment values are segment IDs. Stripe product examples: \`prod_123\` for bought/didn't buy/current/trialing, \`prod_123:3\` for payment thresholds, \`prod_123:is_canceled\` for products set to cancel, \`prod_123:cancels_at:2026-05-26\`, \`prod_123:end_at:2026-05-26\`, or \`prod_123:start_at:7 days ago\` for product-scoped dates. Engagement examples: \`7d\`, \`30d\`, \`90d\`, \`180d\`, \`all\` for rolling time windows, \`campaign:<campaign_id>\` to scope to a specific sent campaign (use \`list_campaigns\` to find IDs), or \`count:timeRange\` like \`10:30d\` / \`10:all\` with at_least/less_than_count operators (e.g. emailClicked at_least \`10:all\` = clicked 10 or more times ever). ${_w}`}},required:["field","operator","value"],additionalProperties:!1},LW={type:"object",properties:{kind:{type:"string",enum:["group"]},id:{type:"string",description:"Stable group ID. Any string works; one will be generated if omitted."},joinOperator:{type:"string",enum:["and","or"],description:"How children in this group combine."},children:{type:"array",minItems:1,items:{type:"object",description:'Either a filter leaf (`kind: "filter"`) or another group (`kind: "group"`).'}}},required:["kind","joinOperator","children"],additionalProperties:!0};function x$(b){if(!Array.isArray(b))return b;return b.map((w)=>{if(typeof w!=="object"||w===null)return w;let $=w;if(typeof $.id==="string"&&$.id.trim()!=="")return $;return{...$,id:crypto.randomUUID()}})}function y$(b){if(typeof b!=="object"||b===null)return b;let w=b;if(w.kind==="filter"||"field"in w||"operator"in w||"value"in w){let $=x$([w]);return Array.isArray($)?$[0]:w}if(w.kind!=="group")return b;return{...w,id:typeof w.id==="string"&&w.id.trim()!==""?w.id:crypto.randomUUID(),children:Array.isArray(w.children)?w.children.map(y$):[]}}function fK(b){let w=b.indexOf(":");return w!==-1&&b.substring(0,w).trim().length>0}function cK(b){let w=b.indexOf(":");return w!==-1&&b.substring(w+1).trim().length>0}function IJ(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 nK(b,w){let $=w.split(":");if(b==="at_least"||b==="less_than_count"){if($.length<3)return'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".';let G=$.slice(0,-2).join(":").trim(),D=$.at(-2),X=$.at(-1),Y=D===void 0?Number.NaN:Number.parseInt(D,10);return G&&Number.isInteger(Y)&&Y>0&&X!==void 0&&IJ(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&&IJ(Q)?null:'Event filters must use "eventName:timeRange", like "saas.purchase:30d".'}function gK(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 mK(b){return b.trim().toLowerCase().replace(/[-\s]+/g,"_")}function iK(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 lK(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 pK(b){return["is","is_not","gte","lte","gt","lt"].includes(b)}function oK(b,w,$){if(b==="stripeProduct"){if(w!=="at_least"&&w!=="less_than_count")return null;let X=$.indexOf(":");if(X===-1)return null;let Y=$.substring(0,X).trim(),H=Number.parseInt($.substring(X+1).trim(),10);return Y&&Number.isInteger(H)&&H>=1?null:'Stripe Product threshold filters must use "productId:count" with a count of at least 1.'}if(b!=="stripeCurrentProduct"&&b!=="stripeTrialProduct")return null;let{productId:W,subfilter:Q,rawValue:G}=gK($);if(!W.trim())return"Stripe product filters must include a product ID.";if(!Q)return w==="is"||w==="is_not"?null:'Stripe current/trial date filters must use "productId:dateField:value".';let D=mK(Q);if(iK(D))return w==="is"||w==="is_not"?null:"Stripe cancellation flag filters only support is and is_not operators.";if(!lK(b,D))return`Unsupported Stripe product subfilter "${Q}".`;if(!pK(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 dK=new Set(["shopify","woocommerce","api"]);function tK(b,w){let $=w.trim(),W=$.indexOf(":");if(W!==-1&&dK.has($.substring(0,W).trim()))$=$.substring(W+1).trim();if(!$)return'Purchased Product filters must include a product ID, like "shopify:42".';if(b!=="at_least"&&b!=="less_than_count")return null;let Q=$.lastIndexOf(":");if(Q===-1)return null;let G=$.substring(0,Q).trim(),D=Number.parseInt($.substring(Q+1).trim(),10);return G&&Number.isInteger(D)&&D>=1?null:'Purchased Product threshold filters must use "provider:productId:count" with a count of at least 1.'}function rK(b){let w;try{w=JSON.parse(b)}catch{return`Poll response filters must use valid JSON. ${_w}`}if(!y(w)||w.v!==1||typeof w.campaignId!=="string"||!w.campaignId.trim()||typeof w.blockId!=="string"||!w.blockId.trim()||!y(w.match))return`Poll response filter context is invalid. ${_w}`;let $=w.match;if($.kind==="answer"&&typeof $.value==="string"&&$.value.length>0)return null;if($.kind==="npsBucket"&&($.bucket==="promoters"||$.bucket==="passives"||$.bucket==="detractors"))return null;return`Poll response filter match is invalid. ${_w}`}function h$(b){if(typeof b!=="object"||b===null)return"Segment filters must be objects.";let w=b,$=w.field,W=w.operator,Q=w.value;if(typeof $!=="string"||!($ in OW))return`Unsupported segment filter field "${String($)}".`;if(typeof W!=="string")return`Segment filter "${$}" must include an operator.`;let G=OW[$];if(!G.includes(W))return`Operator "${W}" is not supported for ${$} filters. Use one of: ${G.join(", ")}.`;if(W!=="is_empty"&&W!=="is_not_empty"&&(typeof Q!=="string"||Q.trim().length===0))return`Segment filter "${$}" must include a value.`;if($==="attribute"&&typeof Q==="string"){if(!fK(Q))return'Attribute filters must use "attributeName:value" or "attributeName:" for empty checks.';if(W!=="is_empty"&&W!=="is_not_empty"&&!cK(Q))return'Attribute filters must include a value after "attributeName:".'}if($==="event"&&typeof Q==="string"){let D=nK(W,Q);if(D)return D}if($==="pollResponse"&&typeof Q==="string"){let D=rK(Q);if(D)return D}if(($==="stripeProduct"||$==="stripeCurrentProduct"||$==="stripeTrialProduct")&&typeof Q==="string"){let D=oK($,W,Q);if(D)return D}if($==="commerceProduct"&&typeof Q==="string"){let D=tK(W,Q);if(D)return D}if($==="tag"&&(W==="contains"||W==="not_contains")){if(!(typeof Q==="string"&&Q.split(",").map((X)=>X.trim()).some(Boolean)))return"Tag filters must include at least one tag name."}return null}function f$(b){if(typeof b!=="object"||b===null)return[];let w=b;if(w.kind==="filter"||"field"in w||"operator"in w||"value"in w){let $=h$(w);return $?[$]:[]}if(Array.isArray(w.children))return w.children.flatMap(f$);return[]}function _b(b,w,$){if(w.html!==void 0&&w.blocks!==void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${b}\`, not both.`);if(w.blocks!==void 0&&!Array.isArray(w.blocks))throw Error(`\`blocks\` must be an array when calling \`${b}\`.`);if($?.requireContent&&w.html===void 0&&w.blocks===void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${b}\`.`)}function Y1(b,w){if(w.labels===void 0)return;if(!Array.isArray(w.labels))throw Error(`\`labels\` must be an array when calling \`${b}\`.`);if(w.labels.some(($)=>typeof $!=="string"||$.trim().length===0))throw Error(`\`labels\` must contain only non-empty strings when calling \`${b}\`.`)}function VJ(b){let w=b.filters!==void 0,$=b.root!==void 0;if(w&&$)throw Error("Provide either `filters` or `root` when calling `create_segment`, not both.");if(!w&&!$)throw Error("Provide either `filters` or `root` when calling `create_segment`.");if(w){if(!Array.isArray(b.filters))throw Error("`filters` must be an array when calling `create_segment`.");if(b.filters.length===0)throw Error("`filters` must include at least one filter when calling `create_segment`.")}if($&&(typeof b.root!=="object"||b.root===null))throw Error("`root` must be an object when calling `create_segment`.");let W=w?b.filters.flatMap((Q)=>{let G=h$(Q);return G?[G]:[]}):f$(b.root);if(W.length>0)throw Error(W[0]??"Invalid segment filter in `create_segment`.")}function NJ(b){let w=b.filters!==void 0,$=b.root!==void 0;if(w&&$)throw Error("Provide either `filters` or `root` when calling `update_segment`, not both.");if(b.name===void 0&&b.filterJoinOperator===void 0&&!w&&!$)throw Error("Provide at least one of `name`, `filters`, `root`, or `filterJoinOperator` when calling `update_segment`.");if(w){if(!Array.isArray(b.filters))throw Error("`filters` must be an array when calling `update_segment`.");if(b.filters.length===0)throw Error("`filters` must include at least one filter when calling `update_segment`.")}if($&&(typeof b.root!=="object"||b.root===null))throw Error("`root` must be an object when calling `update_segment`.");let W=w?b.filters.flatMap((Q)=>{let G=h$(Q);return G?[G]:[]}):$?f$(b.root):[];if(W.length>0)throw Error(W[0]??"Invalid segment filter in `update_segment`.")}var UW=["name","description","logoUrl","founderName","primaryColor","brandColors","valueProps","testimonials","toneVoice","companyContext","emailLengthPreference","socialLinks","privacyPolicyUrl","termsUrl","address","language","pricing","fontFamily","emailDirection","fromEmail","fromName","replyTo","replyToName","replyTrackingEnabled","replyTrackingDomainMode","forwardReplies"];function BW(b,w,$){if(w[$]!==void 0&&!y(w[$]))throw Error(`\`${$}\` must be an object when calling \`${b}\`.`)}function ZJ(b,w,$){if(w[$]!==void 0&&!Array.isArray(w[$]))throw Error(`\`${$}\` must be an array when calling \`${b}\`.`)}function TJ(b){let w=new Set(["companyId",...UW]),$=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 UW)if(b[Q]!==void 0)W[Q]=b[Q];if(Object.keys(W).length===0)throw Error(`Provide at least one of ${UW.map((Q)=>`\`${Q}\``).join(", ")} when calling \`update_company\`.`);for(let Q of["name","description","logoUrl","founderName","primaryColor","toneVoice","companyContext","emailLengthPreference","privacyPolicyUrl","termsUrl","address","language","fontFamily","emailDirection","fromEmail","fromName","replyTo","replyToName","replyTrackingDomainMode"])if(b[Q]!==void 0&&typeof b[Q]!=="string")throw Error(`\`${Q}\` must be a string when calling \`update_company\`.`);BW("update_company",b,"brandColors"),BW("update_company",b,"socialLinks"),BW("update_company",b,"pricing"),ZJ("update_company",b,"valueProps"),ZJ("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 EJ=["senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName"];function eK(b){return EJ.some((w)=>b[w]!==void 0)}function sK(b){if(typeof b.nodeType==="string")return b.nodeType==="action_email";return b.type===void 0||b.type==="email"}function c$(b,w,$){for(let W of EJ){let Q=$[W];if(Q!==void 0&&typeof Q!=="string")throw Error(`\`${W}\` must be a string for ${w} when calling \`${b}\`.`)}if($.senderProfileId!==void 0&&$.fromEmail!==void 0)throw Error(`Provide either \`senderProfileId\` or \`fromEmail\` for ${w} when calling \`${b}\`, not both.`);if($.replyProfileId!==void 0&&$.replyTo!==void 0)throw Error(`Provide either \`replyProfileId\` or \`replyTo\` for ${w} when calling \`${b}\`, not both.`);if($.replyToName!==void 0&&$.replyTo===void 0)throw Error(`\`replyToName\` requires \`replyTo\` for ${w} when calling \`${b}\`.`)}function FW(b,w,$){if(eK($)&&!sK($))throw Error(`Sender identity fields are only supported for email steps at ${w} when calling \`${b}\`.`);c$(b,w,$)}function jJ(b,w,$){if(!Array.isArray($))return;$.forEach((W,Q)=>{if(y(W))c$(b,`${w}[${Q}]`,W)})}function PW(b,w,$){if(!Array.isArray($))return;$.forEach((W,Q)=>{if(y(W))FW(b,`${w}[${Q}]`,W)})}function aK(b){if(jJ("update_sequence","emails",b.emails),jJ("update_sequence","steps",b.steps),y(b.insertSteps))PW("update_sequence","insertSteps.steps",b.insertSteps.steps);if(!y(b.branch))return;if(Array.isArray(b.branch.branches))b.branch.branches.forEach(($,W)=>{if(y($))PW("update_sequence",`branch.branches[${W}].steps`,$.steps)});PW("update_sequence","branch.elseSteps",b.branch.elseSteps)}function _J(b){if(b.fromEmail!==void 0&&b.senderProfileId!==void 0)throw Error("Provide either `fromEmail` or `senderProfileId` when calling `update_sequence`, not both.");if(b.replyTo!==void 0&&b.replyProfileId!==void 0)throw Error("Provide either `replyTo` or `replyProfileId` when calling `update_sequence`, not both.");if(b.fromName!==void 0&&b.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `update_sequence`.");if(b.replyToName!==void 0&&b.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `update_sequence`.");if(b.clearEnrollmentFieldPath===!0&&b.enrollmentFieldPath!==void 0)throw Error("Provide either `enrollmentFieldPath` or `clearEnrollmentFieldPath` when calling `update_sequence`, not both.");if(b.clearSendingWindow===!0&&b.sendingWindow!==void 0)throw Error("Provide either `sendingWindow` or `clearSendingWindow` when calling `update_sequence`, not both.");if(b.clearBccEmails===!0&&b.bccEmails!==void 0)throw Error("Provide either `bccEmails` or `clearBccEmails` when calling `update_sequence`, not both.");if(b.branch!==void 0&&b.insertSteps!==void 0)throw Error("Provide either `branch` or `insertSteps` when calling `update_sequence`, not both.");aK(b);let w={...b};if(delete w.clearEnrollmentFieldPath,delete w.clearSendingWindow,delete w.clearBccEmails,b.clearEnrollmentFieldPath===!0)w.enrollmentFieldPath=null;if(b.clearSendingWindow===!0)w.sendingWindow=null;if(b.clearBccEmails===!0)w.bccEmails=null;return w}function SJ(b,w,$){let W=Z(b,w,"nodeId");if(!y(w.changes)||Object.keys(w.changes).length===0)throw Error(`\`changes\` must be a non-empty object for ${$} when calling \`${b}\`.`);let Q=Z(b,w,"expectedUpdatedAt");return{nodeId:W,changes:w.changes,expectedUpdatedAt:Q}}function RJ(b){let w=SJ("update_sequence_node",b,"the node update");return{...b.confirmLiveChange!==void 0&&{confirmLiveChange:b.confirmLiveChange},nodeUpdates:[w]}}function vJ(b){if(!Array.isArray(b.updates)||b.updates.length===0)throw Error("`updates` must be a non-empty array when calling `update_sequence_nodes`.");let w=new Set,$=b.updates.map((W,Q)=>{if(!y(W))throw Error(`\`updates[${Q}]\` must be an object when calling \`update_sequence_nodes\`.`);let G=SJ("update_sequence_nodes",W,`updates[${Q}]`),D=String(G.nodeId);if(w.has(D))throw Error(`\`updates[${Q}]\` targets duplicate nodeId '${D}' when calling \`update_sequence_nodes\`.`);return w.add(D),G});return{...b.confirmLiveChange!==void 0&&{confirmLiveChange:b.confirmLiveChange},nodeUpdates:$}}function kJ(b){let w=Z("edit_sequence_graph",b,"action"),$=Z("edit_sequence_graph",b,"graphRevision");if(!new Set(["move_node","delete_node","duplicate_node","replace_edges"]).has(w))throw Error("`action` must be `move_node`, `delete_node`, `duplicate_node`, or `replace_edges` when calling `edit_sequence_graph`.");let Q=P(b,"nodeId"),G=P(b,"afterNodeId"),D=P(b,"beforeNodeId"),X=b.edges;if(w!=="replace_edges"&&!Q)throw Error(`\`nodeId\` is required for ${w} when calling \`edit_sequence_graph\`.`);if(w==="replace_edges"&&Q)throw Error("`nodeId` is not used with `replace_edges` when calling `edit_sequence_graph`.");let Y=w==="move_node"||w==="duplicate_node";if(Y&&(G?1:0)+(D?1:0)!==1)throw Error(`Provide exactly one of \`afterNodeId\` or \`beforeNodeId\` for ${w} when calling \`edit_sequence_graph\`.`);if(!Y&&(G||D))throw Error(`\`afterNodeId\` and \`beforeNodeId\` are not used with ${w} when calling \`edit_sequence_graph\`.`);if((w==="replace_edges"||w==="delete_node"&&X!==void 0)&&(!Array.isArray(X)||X.length===0))throw Error(`\`edges\` must contain the complete replacement topology for ${w} when calling \`edit_sequence_graph\`.`);if((w==="move_node"||w==="duplicate_node")&&X!==void 0)throw Error(`\`edges\` is not used with ${w} when calling \`edit_sequence_graph\`.`);let H=Array.isArray(X)?X.map((J,z)=>{if(!y(J))throw Error(`\`edges\` item ${z+1} must be an object when calling \`edit_sequence_graph\`.`);let O=Z("edit_sequence_graph",J,"sourceNodeId"),q=Z("edit_sequence_graph",J,"targetNodeId");if(J.condition!==void 0&&J.condition!==null&&!y(J.condition))throw Error(`\`edges\` item ${z+1} \`condition\` must be an object when calling \`edit_sequence_graph\`.`);return{sourceNodeId:O,targetNodeId:q,...y(J.condition)?{condition:J.condition}:{}}}):void 0;return{...b.confirmStructuralChange!==void 0&&{confirmStructuralChange:b.confirmStructuralChange},graphEdit:{action:w,expectedRevision:$,...Q?{nodeId:Q}:{},...G?{afterNodeId:G}:{},...D?{beforeNodeId:D}:{},...H?{edges:H}:{}}}}function CJ(b){let w=b.type==="sms",$;if(w){FW("insert_sequence_step","SMS step",b);let Q=P(b,"text"),G=Array.isArray(b.blocks)&&b.blocks.length>0;if(Q===void 0&&!G)throw Error("Provide `text` (or `blocks`) when inserting an SMS step with `insert_sequence_step`.");$={type:"sms"};for(let D of["text","blocks","imageUrls","label","name","ineligibleAction","delay","delayMs","waitUntil"])if(b[D]!==void 0)$[D]=b[D]}else{_b("insert_sequence_step",b,{requireContent:!0}),c$("insert_sequence_step","email step",b),$={subject:Z("insert_sequence_step",b,"subject")};for(let Q of["name","previewText","html","blocks","delay","delayMs","waitUntil","senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName"])if(b[Q]!==void 0)$[Q]=b[Q]}let W={steps:[$]};if(b.afterNodeId!==void 0)W.afterNodeId=b.afterNodeId;return{...b.confirmStructuralChange!==void 0&&{confirmStructuralChange:b.confirmStructuralChange},insertSteps:W}}function uJ(b){let w=P(b,"subscriberId"),$=b.fieldValues,W=$===void 0?void 0:Array.isArray($)?$:void 0;if($!==void 0&&W===void 0)throw Error("`fieldValues` must be an array when calling `cancel_sequence_enrollments`.");let Q=W?.map((X)=>typeof X==="string"?X.trim():"").filter((X)=>X.length>0)??[];if(W?.some((X)=>typeof X!=="string")||W!==void 0&&Q.length===0)throw Error("`fieldValues` must contain at least one non-empty string when calling `cancel_sequence_enrollments`.");if(w!==void 0===Q.length>0)throw Error("Provide exactly one target when calling `cancel_sequence_enrollments`: `subscriberId` or `fieldValues`.");let G=P(b,"fieldPath"),D=P(b,"reason");return{...w!==void 0&&{subscriberId:w},...G!==void 0&&{fieldPath:G},...Q.length>0&&{fieldValues:Q},...typeof b.dryRun==="boolean"&&{dryRun:b.dryRun},...D!==void 0&&{reason:D}}}function xJ(b){_b("create_campaign",b),Y1("create_campaign",b);let w=P(b,"prompt")!==void 0,$=b.html!==void 0,W=b.blocks!==void 0,Q=b.templateId!==void 0;if(b.prompt!==void 0&&!w)throw Error("`prompt` cannot be empty when calling `create_campaign`.");if(w&&($||W||Q))throw Error("Provide either `prompt`, `html`, `blocks`, or `templateId` when calling `create_campaign`, not multiple content sources.");if(!w&&(b.style!==void 0||b.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_campaign`.");if(!w&&P(b,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_campaign`.")}function yJ(b){_b("create_template",b),Y1("create_template",b);let w=P(b,"prompt")!==void 0,$=[w,b.html!==void 0,b.blocks!==void 0].filter(Boolean).length;if(b.prompt!==void 0&&!w)throw Error("`prompt` cannot be empty when calling `create_template`.");if($!==1)throw Error("Provide exactly one of `prompt`, `html`, or `blocks` when calling `create_template`.");if(!w&&(b.style!==void 0||b.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_template`.");if(!w&&P(b,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_template`.")}function hJ(b){if(P(b,"scheduledAt")===void 0)throw Error("`scheduledAt` is required when calling `schedule_campaign`.");if(b.targetLists!==void 0&&!y(b.targetLists))throw Error("`targetLists` must be an object when calling `schedule_campaign`.");if(b.sendTimeOptimization!==void 0){if(typeof b.sendTimeOptimization!=="boolean")throw Error("`sendTimeOptimization` must be a boolean when calling `schedule_campaign`.")}if(b.spreadOverHours!==void 0){if(typeof b.spreadOverHours!=="number"||!Number.isInteger(b.spreadOverHours)||b.spreadOverHours<1||b.spreadOverHours>72)throw Error("`spreadOverHours` must be an integer between 1 and 72 when calling `schedule_campaign`.")}if(b.recurringInterval!==void 0&&b.recurringInterval!=="weekly"&&b.recurringInterval!=="monthly")throw Error("`recurringInterval` must be 'weekly' or 'monthly' when calling `schedule_campaign`.")}function n$(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 fJ(b){let w=new Set(["companyId","domain","verify"]),$=Object.keys(b).filter((W)=>!w.has(W));if($.length>0)throw Error(`\`update_landing_page_domain_settings\` accepts only \`domain\` and \`verify\`. Unsupported field${$.length===1?"":"s"}: ${$.map((W)=>`\`${W}\``).join(", ")}.`);if(b.domain===void 0&&b.verify!==!0)throw Error("Provide `domain` or `verify: true` when calling `update_landing_page_domain_settings`.");return{...b.domain!==void 0&&{domain:b.domain},...typeof b.verify==="boolean"&&{verify:b.verify}}}function cJ(b){_b("create_transactional_email",b);let w=P(b,"prompt")!==void 0,$=b.html!==void 0,W=b.blocks!==void 0;if(b.prompt!==void 0&&!w)throw Error("`prompt` cannot be empty when calling `create_transactional_email`.");if(w&&($||W))throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`, not multiple content sources.");if(!w&&(b.style!==void 0||b.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_transactional_email`.");if(!w&&!$&&!W)throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`.");if(!w&&P(b,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_transactional_email`.")}var X0={type:"object",description:"Update Subscriber config. firstName, lastName, and customAttributeUpdates values may use trigger-event merge tags such as {{event.plan}}. Number and boolean values must be a literal or one standalone merge tag and are coerced after resolution.",properties:{label:{type:"string"},firstName:{type:["string","null"],description:"First name literal or merge tag; null clears the field."},lastName:{type:["string","null"],description:"Last name literal or merge tag; null clears the field."},status:{type:"string",enum:["active","unsubscribed","bounced"]},customAttributeUpdates:{type:"array",items:{type:"object",properties:{name:{type:"string"},value:{type:["string","number","boolean","null"],description:"Literal scalar, null to delete, or a standalone merge tag such as {{event.plan}}, {{event.amount}}, or {{event.active}}."},valueType:{type:"string",enum:["text","number","boolean"]}},required:["name","value"]}}},additionalProperties:!0},KW={senderProfileId:{type:"string",description:"Sender profile for this step's From identity. Mutually exclusive with fromEmail."},fromEmail:{type:"string",description:"From address for this step. Its domain must be configured and verified. Mutually exclusive with senderProfileId."},fromName:{type:"string",description:"Display name override for this step. Alone it only changes the visible name; with fromEmail it also names a newly created sender profile."},replyProfileId:{type:"string",description:"Reply profile for this step's Reply-To. Mutually exclusive with replyTo."},replyTo:{type:"string",description:"Reply-To address for this step. Mutually exclusive with replyProfileId."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo."}},g$={type:"object",description:"A step to create inside a sequence path. Use type:'delay' for a standalone delay, type:'email' for an email, type:'create_discount' for a discount action, or type:'condition' for a condition gate.",properties:{type:{type:"string",enum:["email","delay","create_discount","discount","update_subscriber","condition","webhook"],description:"Sequence path step type. Omit for email steps; use delay for standalone waits or update_subscriber for action_update_attributes."},nodeType:{type:"string",enum:["logic_delay","action_email","action_create_discount","action_add_tag","action_remove_tag","action_add_to_list","action_remove_from_list","action_update_attributes","logic_wait_for_event","logic_condition","action_webhook"],description:"Advanced sequence path node type. Prefer type unless creating a non-email action."},config:{...X0,description:"Config for advanced nodeType steps. For action_update_attributes, use the documented Update Subscriber fields and trigger-event merge tags; other node types accept their normal config fields.",additionalProperties:!0},subject:{type:"string",description:"Email subject. Required for email steps."},previewText:{type:"string",description:"Email preview text."},blocks:{type:"array",description:W1,items:{type:"object"}},html:{type:"string",description:"HTML content for email steps. Stored as one raw HTML block. Use this for imported provider HTML."},delay:G1,delayMs:{type:"number",description:"Delay in milliseconds. Useful for standalone type:'delay' steps."},waitUntil:Q1,name:{type:"string",description:"Email template name for email steps."},senderProfileId:{type:"string",description:"Sender profile for this email step. Omit to inherit the effective identity of the nearest sequence email. After a branch merge, only fields shared by every incoming path are inherited; conflicting fields use sequence or company defaults."},fromEmail:{type:"string",description:"From address for this email step. Its domain must be verified. Mutually exclusive with senderProfileId."},fromName:{type:"string",description:"Display name override for this email step. With fromEmail, also names a newly created sender profile."},replyProfileId:{type:"string",description:"Reply profile for this email step. Omit to inherit the effective Reply-To of the nearest sequence email. After a branch merge, only fields shared by every incoming path are inherited; conflicting fields use sequence or company defaults."},replyTo:{type:"string",description:"Reply-To address for this email step. Mutually exclusive with replyProfileId."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo."},discount:{type:"object",description:"Discount configuration for create_discount steps. Same shape as create_sequence steps.",additionalProperties:!0},label:{type:"string",description:"Node label for discount or advanced node steps."},provider:{type:"string",enum:["stripe","shopify"],description:"Discount provider. Use stripe to dynamically create a Stripe coupon plus promotion code, or shopify to dynamically create a Shopify Admin discount code."},discountType:{type:"string",enum:["percent","amount"]},percentOff:{type:"number"},amountOff:{type:"number"},currency:{type:"string"},duration:{type:"string",enum:["once","forever","repeating"]},durationInMonths:{type:"number"},appliesToAllPlans:{type:"boolean"},planIds:{type:"array",items:{type:"string"}},codePrefix:{type:"string"},maxRedemptions:{type:"number"},lockToSubscriber:{type:"boolean"},expiresAt:{type:"string"},expiresInHours:{type:"number"}},additionalProperties:!1};function nJ(b){if(!b||typeof b!=="object")return null;let w=b;if(w.success!==!1)return null;if(typeof w.error==="string")return Error(w.error);if(w.error&&typeof w.error==="object"&&typeof w.error.message==="string")return Error(w.error.message);if(typeof w.message==="string")return Error(w.message);return Error("The tool returned an unsuccessful response.")}function MW(b){return b.trim().toLowerCase().replace(/\s+/g,"-")}function 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 mJ(b,w){let $=typeof b.limit==="number"&&Number.isFinite(b.limit)?Math.max(1,Math.trunc(b.limit)):void 0,W=Math.min(100,Math.max(1,$??100)),Q=[],G=1,D=0,X=0,Y=0;while(!0){let J=bM({query:b.query,tags:b.tags,list:b.list,listId:b.listId,listName:b.listName,segmentId:b.segmentId,status:b.status,page:G,pageSize:W}),z=await A("GET",`/api/v1/subscribers?${J.toString()}`,void 0,w);D=z.pagination?.total??z.subscribers.length,X=z.pagination?.totalPages??1,Y+=1,Q.push(...z.subscribers??[]);let O=$!==void 0&&Q.length>=$,q=z.pagination?G>=z.pagination.totalPages:(z.subscribers??[]).length<W;if(O||q)break;G+=1}let H=$!==void 0?Q.slice(0,$):Q;return{success:!0,subscribers:H,pagination:{page:1,limit:W,total:D,totalPages:X,fetchedPages:Y},returned:H.length,truncated:$!==void 0&&D>0&&H.length<D}}function wM(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 $=wM(w);if(!$.email&&!$.externalId)throw Error(`Provide either \`email\` or \`externalId\` when calling \`${b}\`.`);return $}function m$(b,w){let $=new URLSearchParams;if(w?.includeMachineEngagement)$.set("includeMachineEngagement","true");let W=$.toString(),Q=W?`?${W}`:"";if(b.email)return`/api/v1/subscribers/${encodeURIComponent(b.email)}${Q}`;return $.set("externalId",String(b.externalId)),`/api/v1/subscribers/external?${$.toString()}`}function IW(b){if(b.email)return`/api/v1/subscribers/${encodeURIComponent(b.email)}/notes`;let w=new URLSearchParams;return w.set("externalId",String(b.externalId)),`/api/v1/subscribers/external/notes?${w.toString()}`}async function Y0(b,w,$){return A("GET",m$(b,$),void 0,w)}function Ub(b,w,$,W){let Q=P(w,$);if(Q===void 0)return;if(!W.includes(Q))throw Error(`\`${$}\` must be one of ${W.join(", ")} when calling \`${b}\`.`);return Q}function H0(b,w,$,W){let Q=Z(b,w,$);if(!W.includes(Q))throw Error(`\`${$}\` must be one of ${W.join(", ")} when calling \`${b}\`.`);return Q}function zw(b,w,$,W,Q){let G=w[$];if(G===void 0)return;if(typeof G!=="number"||!Number.isInteger(G)||G<W||G>Q)throw Error(`\`${$}\` must be an integer between ${W} and ${Q} when calling \`${b}\`.`);return G}function $M(b,w){let $=[],W=Ub(b,w,"eventType",k$);if(W)$.push(W);if(w.eventTypes!==void 0){if(!Array.isArray(w.eventTypes))throw Error(`\`eventTypes\` must be an array when calling \`${b}\`.`);w.eventTypes.forEach((Q,G)=>{if(typeof Q!=="string")throw Error(`\`eventTypes\` item ${G+1} must be a string when calling \`${b}\`.`);let D=Q.trim();if(!k$.includes(D))throw Error(`\`eventTypes\` item ${G+1} must be one of ${k$.join(", ")} when calling \`${b}\`.`);$.push(D)})}return[...new Set($)]}function ZW(b,w){let $=new URLSearchParams,W=$M(b,w);if(W.length>0)$.set("eventTypes",W.join(","));let Q=Ub(b,w,"period",["1h","24h","7d","30d","90d"]);if(Q)$.set("period",Q);let G=P(w,"start");if(G)$.set("start",G);let D=P(w,"end");if(D)$.set("end",D);let X=zw(b,w,"page",1,1e6);if(X!==void 0)$.set("page",String(X));let Y=zw(b,w,"limit",1,500);if(Y!==void 0)$.set("limit",String(Y));if(w.includeMachineEngagement===!0)$.set("includeMachineEngagement","true");return $}function jW(b,w){if(w.events===void 0)return;if(!Array.isArray(w.events))throw Error(`\`events\` must be an array when calling \`${b}\`.`);let $=w.events.map((W,Q)=>{if(typeof W!=="string"||!X1.includes(W))throw Error(`\`events\` item ${Q+1} must be one of ${X1.join(", ")} when calling \`${b}\`.`);return W});if($.length===0)throw Error(`\`events\` must include at least one event type when calling \`${b}\`.`);return $}function VW(b,w){if(!Array.isArray(w.emails))throw Error(`\`emails\` must be an array when calling \`${b}\`.`);let $=[];if(w.emails.forEach((W,Q)=>{if(typeof W!=="string")throw Error(`\`emails\` item ${Q+1} must be a string when calling \`${b}\`.`);let G=W.trim();if(G.length>0)$.push(G)}),$.length===0)throw Error(`\`emails\` must include at least one email address when calling \`${b}\`.`);if($.length>JW)throw Error(`\`emails\` must include no more than ${JW} email addresses when calling \`${b}\`. Split larger batches into multiple calls.`);return $}function gJ(b,w,$,W){let Q=w[$];if(Q===void 0)return;if(!Array.isArray(Q))throw Error(`\`${$}\` must be an array when calling \`${b}\`.`);let G=[];if(Q.forEach((D,X)=>{if(typeof D!=="string")throw Error(`\`${$}\` item ${X+1} must be a string when calling \`${b}\`.`);let Y=D.trim();if(Y.length>0)G.push(Y)}),G.length===0)throw Error(`\`${$}\` must include at least one ${W} when calling \`${b}\`.`);return G}function iJ(b){let $=gJ("enroll_subscribers_in_sequence",b,"emails","email address"),W=gJ("enroll_subscribers_in_sequence",b,"subscriberIds","subscriber ID"),Q=($?.length??0)+(W?.length??0);if(Q===0)throw Error("Provide `emails` or `subscriberIds` when calling `enroll_subscribers_in_sequence`.");if(Q>zW)throw Error(`\`emails\` and \`subscriberIds\` must include no more than ${zW} total targets when calling \`enroll_subscribers_in_sequence\`. Split larger batches into multiple calls.`);let G=P(b,"targetNodeId");return{...$!==void 0&&{emails:$},...W!==void 0&&{subscriberIds:W},...G!==void 0&&{targetNodeId:G}}}import{readFileSync as WM,statSync as QM}from"node:fs";import{basename as GM}from"node:path";var DM={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 XM(b){let w=b.split(".").pop()?.toLowerCase()??"";return DM[w]??null}var YM=104857600;async function lJ(b,w){if(!z0())throw Error("`filePath` is only supported when the MCP server runs locally on your machine. Host the file somewhere public and pass `url` instead.");let $=XM(b);if(!$)throw Error("Unsupported file type. Use PDF, ePub, ZIP, image, audio, video, or text files.");let W=QM(b).size;if(W>YM)throw Error(`File is too large (${Math.round(W/1048576)}MB). Delivery files must be 100MB or smaller.`);let Q=WM(b),G=await A("POST","/api/v1/products/delivery/upload-url",{filename:GM(b),contentType:$,fileSizeBytes:W},w),D=await fetch(G.uploadUrl,{method:"PUT",headers:{"Content-Type":$},body:Q});if(!D.ok)throw Error(`File upload failed (${D.status})`);return{url:G.publicUrl,fileName:G.fileName,fileSizeBytes:W,mimeType:$}}async function i$(b){let w=P(b,"companyId");if(w)return w;let $=qw();if($)return $;try{return(await A("GET","/api/v1/account")).currentCompanyId??void 0}catch{return}}async function pJ(b,w){let $=await i$(w);if(!$)throw Error(`A company is required when calling \`${b}\`. Call \`get_account\`, then \`select_company\`, or pass \`companyId\` explicitly.`);return $}function H1(b,w){if(!y(b)||!w)return b;return{...b,url:w}}function oJ(b,w){if(!y(b))return b;return{...b,...w.campaign!==void 0&&{url:w.campaign},...w.campaignPreview!==void 0&&{previewUrl:w.campaignPreview}}}function J0(b,w,$){if(!Array.isArray(b)||!w)return b;return b.map((W)=>{if(!y(W))return W;let Q=P(W,"id");if(!Q)return W;let G=Yw({companyId:w,...$==="campaign"&&{campaignId:Q},...$==="landingPage"&&{landingPageId:Q},...$==="sequence"&&{sequenceId:Q},...$==="template"&&{emailId:Q},...$==="transactional"&&{transactionalId:Q}});if($==="campaign")return oJ(W,G.urls);let D=$==="sequence"?G.urls.sequence:$==="landingPage"?G.urls.landingPage:$==="template"?G.urls.email:G.urls.transactionalEmail;return H1(W,D)})}function HM(b){if(!Array.isArray(b))return b;return b.map((w)=>{if(!y(w))return w;let $=P(w,"id");if(!$)return w;let W=Yw({companyId:$});return{...w,url:W.urls.dashboard,settingsUrl:W.urls.settings}})}var NW=new Set(["get_account","select_company","create_company","get_company","update_company","list_campaigns","get_campaign","get_email_send","create_campaign","update_campaign","schedule_campaign","send_test_email","cancel_campaign","pause_campaign","resume_campaign","duplicate_campaign","resend_campaign_to_non_openers","list_landing_pages","get_landing_page","create_landing_page","update_landing_page","publish_landing_page","unpublish_landing_page","delete_landing_page","list_sequences","get_sequence","create_sequence","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 dJ(b,w,$){if(!y($)||!NW.has(b))return $;let W=y($.company)?$.company:void 0,G=P($,"selectedCompanyId")??P($,"currentCompanyId")??P($,"companyId")??(W?P(W,"id"):void 0)??(W?P(W,"companyId"):void 0)??await i$(w);if(!G)return $;let D=y($.campaign)?$.campaign:void 0,X=y($.sequence)?$.sequence:void 0,Y=y($.landingPage)?$.landingPage:void 0,H=y($.template)?$.template:void 0,J=y($.transactional)&&!Array.isArray($.transactional)?$.transactional:void 0,z={companyId:G,campaignId:P(w,"campaignId")??P($,"campaignId")??(D?P(D,"id"):void 0),landingPageId:P(w,"landingPageId")??P($,"landingPageId")??(Y?P(Y,"id"):void 0),sequenceId:P(w,"sequenceId")??P($,"sequenceId")??(X?P(X,"id"):void 0),emailId:P($,"templateId")??(H?P(H,"id"):void 0)??(J?P(J,"emailId"):void 0)??P(w,"templateId"),transactionalId:P(w,"transactionalId")??(J?P(J,"id"):void 0)??P(w,"idOrSlug"),emailSendId:P(w,"emailSendId")??P($,"emailSendId")??(y($.emailSend)?P($.emailSend,"id"):void 0),status:P(w,"status")},O=Yw(z),q=W?Yw({companyId:G}):void 0;return{...$,...Array.isArray($.companies)&&{companies:HM($.companies)},...Array.isArray($.campaigns)&&{campaigns:J0($.campaigns,G,"campaign")},...Array.isArray($.landingPages)&&{landingPages:J0($.landingPages,G,"landingPage")},...Array.isArray($.sequences)&&{sequences:J0($.sequences,G,"sequence")},...Array.isArray($.templates)&&{templates:J0($.templates,G,"template")},...Array.isArray($.transactional)&&{transactional:J0($.transactional,G,"transactional")},...W&&q!==void 0&&{company:{...W,url:q.urls.dashboard,settingsUrl:q.urls.settings}},...D&&O.urls.campaign!==void 0&&{campaign:oJ(D,O.urls)},...X&&O.urls.sequence!==void 0&&{sequence:H1(X,O.urls.sequence)},...Y&&O.urls.landingPage!==void 0&&{landingPage:H1(Y,O.urls.landingPage)},...H&&O.urls.email!==void 0&&{template:H1(H,O.urls.email)},...J&&O.urls.transactionalEmail!==void 0&&{transactional:H1(J,O.urls.transactionalEmail)},...y($.emailSend)&&O.urls.emailSend!==void 0&&{emailSend:H1($.emailSend,O.urls.emailSend)},appUrls:O.urls}}import{readFileSync as JM,statSync as zM}from"node:fs";import{basename as AM,extname as rJ}from"node:path";var EW=5242880,OM=Math.ceil(EW/3)*4,qM=Math.ceil(OM*1.05)+256,eJ={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"},LM=new Set(Object.values(eJ));function TW(b){return b?.split(";")[0]?.trim().toLowerCase()||void 0}function UM(b){return eJ[rJ(b).toLowerCase()]}function BM(b){let w=rJ(b);return(w?b.slice(0,-w.length):b).replace(/[-_]+/g," ").trim()||"Image"}function PM(b){if(b.length>qM)throw Error("Image assets must be 5MB or smaller.")}function FM(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)>EW)throw Error("Image assets must be 5MB or smaller.")}function KM(b){PM(b);let w=b.trim(),$=/^data:([^;,]+);base64,([\s\S]+)$/i.exec(w),W=$?.[2]??w;FM(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:TW($[1])}:{}}}function tJ(b){if(b<=0)throw Error("The image file is empty.");if(b>EW)throw Error("Image assets must be 5MB or smaller.")}function MM(b){let w=UM(b.filename)??TW(b.explicitContentType)??TW(b.dataUrlContentType);if(!w||!LM.has(w))throw Error("Unsupported image type. Use PNG, JPEG, GIF, or WebP.");return w}function IM(b){let w,$,W;if(b.filePath!==void 0){if(!z0())throw Error("`filePath` is only supported when the MCP server runs locally on your machine. For a remote MCP connection, pass `imageBase64` and `filename` instead.");let G=zM(b.filePath).size;tJ(G),w=JM(b.filePath),$=b.filename??AM(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=KM(b.imageBase64);w=G.bytes,W=G.dataUrlContentType,$=b.filename,tJ(w.byteLength)}let Q=MM({filename:$,explicitContentType:b.contentType,dataUrlContentType:W});return{bytes:w,filename:$,contentType:Q,altText:b.altText??BM($)}}async function sJ(b){let w=IM(b),$=w.bytes.byteLength,W=await A("POST","/api/v1/media/upload-url",{filename:w.filename,contentType:w.contentType,fileSizeBytes:$},b.companyId);return await lW(W.uploadUrl,w.bytes,w.contentType,b.companyId),(await A("POST","/api/v1/media/complete-upload",{key:W.key,filename:W.fileName,contentType:w.contentType,fileSizeBytes:$,...b.sourceWidth!==void 0&&{width:b.sourceWidth},...b.sourceHeight!==void 0&&{height:b.sourceHeight},altText:w.altText},b.companyId)).asset}var ZM={type:"boolean",description:"Whether the Sequenzy operation succeeded."},jM={type:"string",description:"Human-readable status, confirmation, or next-step message."},VM={type:"string",description:"Additional context about the result."};function o(b){return{type:"object",description:b,additionalProperties:!0}}function NM(b){return{type:"array",description:b,items:o("One item in the returned collection.")}}function N(b){return{type:"string",description:b}}function Kb(b){return{type:"number",description:b}}function Sb(b){return{type:"boolean",description:b}}function F(b){return o(`The ${b} record returned by Sequenzy.`)}function l(b){return NM(`List of ${b} records returned by Sequenzy.`)}var TM={appUrls:o("Dashboard URLs for relevant Sequenzy resources."),url:N("Primary dashboard URL for this result."),settingsUrl:N("Company settings URL when available.")},EM={success:ZM,message:jM,note:VM,items:{type:"array",description:"Fallback array wrapper used only when a tool returns a bare array.",items:o("One returned item.")},value:o("Fallback object wrapper used only when a tool returns a non-object value.")},_M={get_account:{account:F("account"),companies:l("company"),apiKeyPermissions:o("Current API key preset and scopes, whether common marketing work is discoverable, any missing marketing read scopes, and the API Keys management URL."),currentCompanyId:N("Company ID selected by the authenticated API key, when available."),selectedCompanyId:N("Company ID selected locally for subsequent MCP calls, when available.")},select_company:{companyId:N("Selected company ID."),companyName:N("Selected company name.")},get_app_urls:{dashboard:N("Company dashboard URL."),settings:N("Company settings URL."),campaign:N("Campaign editor URL."),landingPage:N("Landing page editor URL."),sequence:N("Sequence editor URL."),email:N("Email editor URL."),transactionalEmail:N("Transactional email URL."),emailSend:N("Sent email detail URL."),domain:N("Sending domain settings URL."),urls:o("All generated URLs keyed by resource type.")},create_company:{company:F("company"),autoSelected:Sb("Whether the new company was selected for subsequent MCP calls.")},update_company:{company:F("company")},get_company:{company:F("company")},get_sync_rules:{syncRules:{type:"array",description:"Effective sync rules for the company.",items:o("One sync rule.")},isDefault:Sb("Whether the company still uses the platform default rules.")},update_sync_rules:{syncRules:{type:"array",description:"Effective sync rules after the update.",items:o("One sync rule.")},isDefault:Sb("Whether the company now uses the platform default rules.")},get_shopify_automation_settings:{browseAbandonment:o("Effective browse-abandonment settings (defaults applied)."),priceDrop:o("Effective price-drop settings (defaults applied)."),shopDomain:N("Connected Shopify store domain.")},update_shopify_automation_settings:{browseAbandonment:o("Effective browse-abandonment settings after the update."),priceDrop:o("Effective price-drop settings after the update."),shopDomain:N("Connected Shopify store domain.")},create_api_key:{apiKey:o("Created API key metadata: the newly created secret in `key`, plus `scopes` listing the assigned permission scopes (null when the key has full access)."),key:N("Newly created API key if the API response uses the short key field.")},list_websites:{websites:l("sender website")},add_website:{website:F("Sending domain with the SPF, DKIM, MAIL FROM, and inbound DNS records required for setup.")},add_sending_domain:{website:F("Sending domain with the SPF, DKIM, MAIL FROM, and inbound DNS records required for setup.")},check_website:{website:F("sender website"),ready:Sb("Whether the sender website is ready."),status:N("Current processing or verification status.")},verify_sending_domain:{website:F("Sending domain with current aggregate, SPF, DKIM, and MAIL FROM verification details."),verified:Sb("Whether the sending domain passed the fresh verification check."),message:N("Verification result summary.")},get_integration_guide:{guide:F("integration guide"),code:N("Generated integration code or example."),steps:{type:"array",description:"Setup steps for the requested integration.",items:o("One setup step.")}},add_subscriber:{subscriber:F("subscriber")},update_subscriber:{subscriber:F("subscriber")},remove_subscriber:{subscriber:F("subscriber"),hardDeleted:Sb("Whether the subscriber was permanently deleted.")},get_subscriber:{subscriber:F("subscriber")},list_subscriber_notes:{notes:l("subscriber note")},add_subscriber_note:{note:F("subscriber note")},delete_subscriber_note:{id:N("Deleted subscriber note ID."),deleted:Sb("Whether the subscriber note was deleted.")},search_subscribers:{subscribers:l("subscriber"),pagination:o("Pagination metadata."),returned:Kb("Number of subscribers returned."),truncated:Sb("Whether the result was truncated by the requested limit.")},list_products:{products:l("product")},upsert_products:{products:l("product"),created:Kb("Number of products created."),updated:Kb("Number of products updated.")},delete_product:{productId:N("Deleted product ID.")},attach_product_file:{product:F("product"),delivery:F("digital delivery file")},remove_product_file:{product:F("product")},upload_image_asset:{asset:F("hosted image asset"),imageBlock:o("Ready-to-insert Sequenzy image block using the hosted asset URL.")},sync_products:{job:F("product sync job"),jobId:N("Queued product sync job ID.")},list_tags:{tags:l("tag")},create_tag:{tag:F("tag")},update_tag:{tag:F("tag")},delete_tag:{tagId:N("Deleted tag ID.")},list_lists:{lists:l("list")},create_list:{list:F("list")},update_list:{list:F("list")},delete_list:{listId:N("Deleted list ID.")},add_subscribers_to_list:{list:F("list"),added:Kb("Number of subscribers added to the list."),skipped:Kb("Number of subscribers skipped.")},remove_subscribers_from_list:{list:F("list"),removed:Kb("Number of subscribers removed from the list."),skipped:Kb("Number of subscribers skipped.")},list_segments:{segments:l("segment")},create_segment:{segment:F("segment")},update_segment:{segment:F("segment")},delete_segment:{segmentId:N("Deleted segment ID.")},get_segment_count:{count:Kb("Number of subscribers matching the segment."),segmentId:N("Segment ID that was counted.")},list_audience_syncs:{audienceSyncs:l("audience sync")},list_ad_accounts:{adAccounts:l("ad account")},create_audience_sync:{audienceSync:F("audience sync")},update_audience_sync:{audienceSync:F("audience sync")},delete_audience_sync:{audienceSyncId:N("Deleted audience sync ID.")},sync_audience_now:{audienceSync:F("audience sync"),job:F("audience sync job"),jobId:N("Queued audience sync job ID.")},list_templates:{templates:l("email template")},get_template:{template:F("email template")},create_template:{template:F("email template")},update_template:{template:F("email template")},set_template_localization:{templateId:N("Localized template ID."),localization:F("template localization")},sync_template_localizations:{templateId:N("Template ID queued for localization."),queuedLocales:{type:"array",description:"Locale codes queued for AI translation.",items:N("One queued locale code.")},queuedVariantCount:Kb("Number of localized variants queued for translation.")},delete_template:{templateId:N("Deleted template ID.")},list_ab_tests:{abTests:l("A/B test")},get_ab_test:{abTest:F("A/B test")},get_ab_test_stats:{abTest:F("A/B test"),stats:F("A/B test statistics")},restart_ab_test:{abTest:F("A/B test")},update_ab_test_variant:{abTest:F("A/B test"),variant:F("A/B test variant")},create_ab_test:{abTest:F("A/B test")},add_ab_test_variant:{abTest:F("A/B test"),variant:F("A/B test variant")},delete_ab_test_variant:{abTest:F("A/B test"),variantId:N("Deleted A/B test variant ID.")},delete_ab_test:{abTestId:N("Deleted A/B test ID.")},list_campaigns:{campaigns:l("campaign")},get_campaign:{campaign:F("campaign")},get_email_send:{emailSend:F("email send"),events:l("email delivery event")},get_recipient_suppression:{suppression:F("recipient suppression status")},remove_recipient_suppression:{removed:Sb("Whether stale bounce suppression was removed."),removedLocalBounce:Sb("Whether the platform-local bounce block was removed."),removedSesRegions:{type:"array",description:"AWS SES regions where a bounce suppression was removed.",items:N("One AWS SES region.")},remainingSuppression:F("recipient suppression status after cleanup")},create_campaign:{campaign:F("campaign")},update_campaign:{campaign:F("campaign")},schedule_campaign:{campaign:F("campaign"),scheduledAt:N("Scheduled send timestamp.")},send_test_email:{emailSendId:N("Durable test email delivery ID."),recipientEmail:N("Test email recipient.")},send_test_sms:{smsSendId:N("Created test SMS send ID."),toPhone:N("Normalized E.164 destination phone.")},cancel_campaign:{campaign:F("campaign")},pause_campaign:{campaign:F("campaign")},resume_campaign:{campaign:F("campaign")},delete_campaign:{campaignId:N("Deleted campaign ID.")},duplicate_campaign:{campaign:F("duplicated campaign")},resend_campaign_to_non_openers:{campaign:F("non-opener resend draft campaign"),estimatedNonOpenerCount:Kb("Estimated number of subscribers who haven't opened the original campaign.")},list_forms:{forms:l("saved form")},create_form:{form:F("saved form"),embed:o("Public action URL plus JavaScript, native form, and fetch snippets.")},get_form_embed:{form:F("saved form"),embed:o("Public action URL plus JavaScript, native form, and fetch snippets.")},list_landing_pages:{landingPages:l("landing page")},get_landing_page:{landingPage:F("landing page")},create_landing_page:{landingPage:F("landing page")},update_landing_page:{landingPage:F("landing page")},delete_landing_page:{landingPageId:N("Deleted landing page ID.")},publish_landing_page:{landingPage:F("landing page")},unpublish_landing_page:{landingPage:F("landing page")},connect_landing_page_domain:{landingPage:F("landing page"),domain:N("Connected landing page domain.")},update_landing_page_domain_settings:{landingPage:F("landing page"),domain:N("Landing page domain.")},list_sequences:{sequences:l("sequence")},get_sequence:{sequence:F("sequence")},create_sequence:{sequence:F("sequence"),eventTrackingCode:N("Ready-to-adapt code for sending a custom trigger event, including any matching-field property."),eventTracking:o("Custom-event endpoint, payload contract, example payload, documentation URL, and get_integration_guide arguments."),requiredEvents:{type:"array",description:"Event names the application or an integration must send.",items:N("One required event name.")}},update_sequence:{sequence:F("sequence")},update_sequence_node:{sequence:F("sequence")},update_sequence_nodes:{sequence:F("sequence")},edit_sequence_graph:{sequence:F("sequence")},insert_sequence_step:{sequence:F("sequence"),insertedNodeIds:{type:"array",description:"Node IDs created for the inserted step, including any delay node.",items:N("Inserted automation node ID.")},insertedEmailIds:{type:"array",description:"Email template IDs created for the inserted step.",items:N("Inserted email template ID.")},insertedEmailCount:Kb("Number of email steps inserted.")},enable_sequence:{sequence:F("sequence")},disable_sequence:{sequence:F("sequence")},pause_sequence_enrollments:{sequenceId:N("Sequence ID."),enrollmentPaused:Sb("Whether new sequence enrollments are paused.")},resume_sequence_enrollments:{sequenceId:N("Sequence ID."),enrollmentPaused:Sb("Whether new sequence enrollments are paused.")},enroll_subscribers_in_sequence:{sequence:F("sequence"),enrollments:l("sequence enrollment"),enrolled:Kb("Number of subscribers enrolled."),skipped:Kb("Number of subscribers skipped.")},cancel_sequence_enrollments:{sequence:F("sequence"),cancelled:Kb("Number of enrollments cancelled."),skipped:Kb("Number of enrollments skipped.")},delete_sequence:{sequenceId:N("Deleted sequence ID.")},list_transactional_emails:{transactional:l("transactional email")},get_transactional_email:{transactional:F("transactional email")},create_transactional_email:{transactional:F("transactional email")},update_transactional_email:{transactional:F("transactional email")},send_email:{emailSendId:N("Durable transactional delivery ID."),transactional:F("transactional email")},get_stats:{stats:F("account or company statistics")},get_campaign_stats:{campaign:F("campaign"),stats:F("campaign statistics"),clickedLinks:{type:"array",description:"Per-link click breakdown, most clicked first (top 20). Each entry has url, clicks, and percentage (that link's share of every recorded link click). Present only when the campaign has tracked link clicks.",items:o("One clicked link with url/clicks/share.")},polls:{type:"array",description:`Poll and NPS summaries. Each subscriber counts once per campaign poll block using their latest answer to that block; NPS entries include score, average, and promoter/passive/detractor counts. To list the exact historical respondents behind a count, use the summary blockId and the get_campaign_stats campaignId with create_segment. ${_w} A summary's attributeKey identifies the subscriber attribute that stores their current/latest response and may be overwritten by a later poll that reuses the key.`,items:o("One poll or NPS results summary.")}},get_sequence_stats:{sequence:F("sequence"),stats:F("sequence statistics")},list_campaign_events:{events:l("campaign email event"),pagination:o("Pagination metadata.")},list_sequence_events:{events:l("sequence email event"),pagination:o("Pagination metadata.")},get_subscriber_activity:{activity:l("subscriber activity event"),subscribers:l("subscriber"),pagination:o("Pagination metadata.")},list_team_members:{members:l("team member"),invitations:l("team invitation")},invite_team_member:{invitation:F("team invitation")},cancel_team_invitation:{invitationId:N("Cancelled invitation ID.")},list_conversations:{conversations:l("inbox conversation"),pagination:o("Pagination metadata.")},get_conversation:{conversation:F("inbox conversation"),messages:l("conversation message")},reply_to_conversation:{conversation:F("inbox conversation"),message:F("conversation message")},update_conversation_status:{conversation:F("inbox conversation")},mark_conversation_read:{conversation:F("inbox conversation")},list_webhooks:{webhooks:l("outbound webhook")},create_webhook:{webhook:F("outbound webhook")},update_webhook:{webhook:F("outbound webhook")},delete_webhook:{webhookId:N("Deleted outbound webhook ID.")},test_webhook:{webhook:F("outbound webhook"),delivery:F("test webhook delivery")},list_webhook_deliveries:{deliveries:l("webhook delivery")},replay_webhook_delivery:{delivery:F("webhook delivery"),job:F("webhook replay job")},generate_email:{email:F("generated email"),html:N("Generated HTML email body."),blocks:{type:"array",description:"Generated Sequenzy email blocks, wrapped with company branding (logo + footer) unless applyBranding was false.",items:o("One generated email block.")},subject:N("Generated subject line."),previewText:N("Generated inbox preview text.")},generate_sequence:{sequence:F("persisted AI-generated sequence draft"),deprecated:Sb("Always true for this deprecated alias."),deprecationMessage:N("Migration guidance directing callers to create_sequence.")},generate_subject_lines:{subjectLines:{type:"array",description:"Generated subject line variants.",items:N("One generated subject line.")},variants:l("generated subject line variant")},generate_sms:{prompt:N("The prompt the messages were generated for."),messages:{type:"array",description:"Generated SMS message variants with encoding and segment counts.",items:o("One generated SMS message.")}},get_sms_settings:{sms:o("SMS add-on status: enabled, planEligible, creditsBalance, brandPrefix, numbers, readyToSend (paid plan or credits plus an active number).")},submit_feedback:{}};function SM(b){let w=_M[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:{...EM,...w,...NW.has(b)?TM:{}},additionalProperties:!0}}function aJ(b){return{...b,outputSchema:SM(b.name)}}function bz(b){if(y(b))return b;if(Array.isArray(b))return{items:b};return{value:b}}var wz=[{name:"list_ab_tests",description:"List A/B tests and their variants",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Optional sequence ID to filter automation A/B tests."}}}},{name:"get_ab_test",description:"Get A/B test details, variants, and per-locale localization sync status",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"}},required:["abTestId"]}},{name:"get_ab_test_stats",description:"Get A/B test aggregate stats and per-variant stats. Supports period or custom start/end ranges.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"},period:{type:"string",description:"Optional period: 1h, 24h, 7d, 30d, or 90d."},start:{type:"string",description:"Custom range start as ISO 8601. Requires end."},end:{type:"string",description:"Custom range end as ISO 8601. Requires start."},includeMachineEngagement:lb},required:["abTestId"]}},{name:"restart_ab_test",description:"Run another sequence A/B test after a winner is selected. By default the winner becomes the new control; pass sourceVariantId to use another variant as the control email.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID to restart"},sourceVariantId:{type:"string",description:"Optional variant ID to use as the new control email. Defaults to the selected winner."},testType:{type:"string",description:"Optional test type: subject or content."},winnerThreshold:{type:"number",description:"Optional number of subscribers before selecting a winner. Must be from 10 to 1000."},variantCount:{type:"number",description:"Optional total variants including the control. Must be from 2 to 4."}},required:["abTestId"],additionalProperties:!1}},{name:"update_ab_test_variant",description:"Update a draft A/B test variant. Provide at least one of subject, previewText, html, or blocks. Use either html or blocks, not both.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"},variantId:{type:"string",description:"A/B test variant ID"},subject:{type:"string",description:"Variant subject line"},previewText:{type:"string",description:"Variant preview text. Pass an empty string to clear it."},html:{type:"string",description:"Replacement HTML body. Mutually exclusive with blocks."},blocks:{type:"array",description:`${Jw} Mutually exclusive with html.`,items:{type:"object"}}},required:["abTestId","variantId"],additionalProperties:!1}},{name:"create_ab_test",description:"Create a campaign A/B test. Control variant A is created automatically from the campaign's current email; optionally provide extra variants. The campaign must be in draft or rejected status, and each campaign can only have one A/B test.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Draft campaign ID to create the A/B test for."},name:{type:"string",description:"Optional A/B test name."},testPercentage:{type:"number",description:"Percentage of the audience used for the test phase, from 5 to 50. Defaults to 20."},testDurationMinutes:{type:"number",description:"Test phase duration in minutes before the winner is selected, from 15 to 1440. Defaults to 240."},winnerCriteria:{type:"string",enum:["open_rate","click_rate"],description:"Winner selection criteria. Defaults to open_rate."},variants:{type:"array",description:"Optional extra variants to create in addition to control variant A.",items:{type:"object",properties:{subject:{type:"string",description:"Variant subject line."},previewText:{type:"string",description:"Variant preview text."},blocks:{type:"array",description:Jw,items:{type:"object"}}},required:["subject"]}}},required:["campaignId"]}},{name:"add_ab_test_variant",description:"Add a variant to a draft campaign A/B test. Variants cannot be added after the test has started.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"},subject:{type:"string",description:"Variant subject line."},previewText:{type:"string",description:"Variant preview text."},blocks:{type:"array",description:Jw,items:{type:"object"}}},required:["abTestId","subject"]}},{name:"delete_ab_test_variant",description:"Permanently delete a variant from a draft campaign A/B test. This cannot be undone. Variant A is the control and cannot be deleted, and the test must keep at least the minimum number of variants. Variants cannot be removed after the test has started.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"},variantId:{type:"string",description:"A/B test variant ID to delete."}},required:["abTestId","variantId"]}},{name:"delete_ab_test",description:"Permanently delete a campaign A/B test and all of its variants. This cannot be undone. Running tests (testing or winner_selected) cannot be deleted, and the linked campaign must be in draft or rejected status.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID to delete."}},required:["abTestId"]}}];var $z=[{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 Wz=[{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 Qz=[{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:lb}}},{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:lb},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:lb},required:["sequenceId"]}},{name:"list_campaign_events",description:"List paginated raw email events for a campaign. Defaults to deliveries; use eventType or eventTypes to include opens, clicks, bounces, complaints, unsubscribes, sends, or delivery delays.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"},eventType:{type:"string",description:"Optional single event type. Supported values: send, delivery, bounce, complaint, open, click, unsubscribe, delivery_delay. Defaults to delivery."},eventTypes:{type:"array",description:"Optional event types to include. Supported values: send, delivery, bounce, complaint, open, click, unsubscribe, delivery_delay. Defaults to delivery.",items:{type:"string"}},period:{type:"string",description:"Optional sliding time window: 1h, 24h, 7d, 30d, or 90d. Ignored when start/end are provided."},start:{type:"string",description:"Optional ISO 8601 start time. Must be used with end; max range is 90 days."},end:{type:"string",description:"Optional ISO 8601 end time. Must be used with start; max range is 90 days."},page:{type:"number",description:"Page number, starting at 1. Defaults to 1."},limit:{type:"number",description:"Events per page. Defaults to 100; maximum 500."},includeMachineEngagement:lb},required:["campaignId"]}},{name:"list_sequence_events",description:"List paginated raw email events for every email step in a sequence. Defaults to deliveries; use eventType or eventTypes to include opens, clicks, bounces, complaints, unsubscribes, sends, or delivery delays.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"},eventType:{type:"string",description:"Optional single event type. Supported values: send, delivery, bounce, complaint, open, click, unsubscribe, delivery_delay. Defaults to delivery."},eventTypes:{type:"array",description:"Optional event types to include. Supported values: send, delivery, bounce, complaint, open, click, unsubscribe, delivery_delay. Defaults to delivery.",items:{type:"string"}},period:{type:"string",description:"Optional sliding time window: 1h, 24h, 7d, 30d, or 90d. Ignored when start/end are provided."},start:{type:"string",description:"Optional ISO 8601 start time. Must be used with end; max range is 90 days."},end:{type:"string",description:"Optional ISO 8601 end time. Must be used with start; max range is 90 days."},page:{type:"number",description:"Page number, starting at 1. Defaults to 1."},limit:{type:"number",description:"Events per page. Defaults to 100; maximum 500."},includeMachineEngagement:lb},required:["sequenceId"]}},{name:"get_subscriber_activity",description:"Get recent activity, email stats, and current sequence enrollments for a subscriber",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},includeMachineEngagement:lb},required:[]}}];var Gz=[{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 Dz=[{name:"list_campaigns",description:"List all campaigns",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list campaigns for. If not provided, uses the currently selected company."},status:{type:"string",description:"Filter by status (draft, scheduled, sent)"},label:{type:"string",description:"Optional label name filter. Only campaigns assigned this label are returned."}}}},{name:"get_campaign",description:"Get campaign details and stats",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"}},required:["campaignId"]}},{name:"get_email_send",description:"Get an email delivery by emailSendId, including queued and test sends, delivery status, provider failure reason, stored HTML, and the ClickHouse event timeline. Queue jobs are internal execution details and are not exposed.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},emailSendId:{type:"string",description:"Durable email delivery ID to inspect."}},required:["emailSendId"]}},{name:"create_campaign",description:"Create a new campaign. Omit all content fields to create an empty draft. For net-new natural-language content use `prompt`; do not author HTML or blocks. `blocks` are finished caller-supplied Sequenzy content and `html` is preserved/imported markup. Defaults to draft; status 'sent' only archives an already-sent campaign.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the campaign in. If not provided, uses the currently selected company."},name:{type:"string",description:"Campaign name"},subject:{type:"string",description:"Email subject line. Optional when `prompt` is provided because the generated subject will be used."},previewText:{type:["string","null"],description:"Email preview text. Optional when `prompt` is provided because the generated preview text will be used."},trackingCode:{type:"string",description:"Optional campaign tracking code for UTM templates. Use only when explicitly requested."},status:{type:"string",description:"Initial status: draft or sent. Defaults to draft. Use sent only for imported/already-sent campaigns; it does not send email or create delivery history."},sentAt:{type:"string",description:"ISO date-time for an imported/already-sent campaign. Only valid when status is sent; defaults to now if omitted."},html:{type:"string",description:"Email HTML content. Mutually exclusive with `blocks`. Use this for imported provider campaigns; Sequenzy stores it as one raw HTML block to preserve the design."},blocks:{type:"array",description:Hw,items:{type:"object"}},prompt:{type:"string",description:"Generate campaign blocks from a prompt. Generated blocks include the company's logo and footer, and the created campaign inherits the company brand font. Mutually exclusive with `html`, `blocks`, and `templateId`."},style:{type:"string",description:"Prompt generation style: minimal, branded, promotional. Only used with `prompt`."},tone:{type:"string",description:"Prompt generation tone: professional, casual, friendly. Only used with `prompt`."},templateId:{type:"string",description:"Use a template instead of html"},segmentId:{type:"string",description:"Target segment ID"},fromEmail:{type:"string",description:"From address for this campaign. Its domain must be configured and verified; a sender profile is created when needed."},fromName:{type:"string",description:"Display name for a newly created sender profile. Requires fromEmail."},senderProfileId:{type:"string",description:"Existing sender profile ID. Mutually exclusive with fromEmail."},replyTo:{type:"string",description:"Reply-To address for this campaign. A reply profile is created when needed."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo."},replyProfileId:{type:"string",description:"Existing reply profile ID. Mutually exclusive with replyTo."},campaignData:{type:"object",description:"Optional campaign-scoped JSON data for repeat blocks and personalization."},computedLists:{type:"array",description:"Optional computed list definitions derived from campaignData at send time.",items:{type:"object"}},labels:{type:"array",description:"Optional label names to assign. Missing labels are created automatically.",items:{type:"string"}}},required:["name"]}},{name:"update_campaign",description:"Update a draft campaign",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"},name:{type:"string",description:"Campaign name"},subject:{type:"string",description:"Email subject line"},trackingCode:{type:"string",description:"Optional campaign tracking code for UTM templates. Use only when explicitly requested. Send an empty string to clear it."},html:{type:"string",description:"Email HTML content. Mutually exclusive with `blocks`. Use this for imported provider campaigns; Sequenzy stores it as one raw HTML block to preserve the design."},blocks:{type:"array",description:Hw,items:{type:"object"}},replyTo:{type:"string",description:"Set reply-to using an existing reply profile email address for this company."},replyProfileId:{type:"string",description:"Set reply-to using a reply profile ID for this company."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo."},fromEmail:{type:"string",description:"Set this campaign's From address. Its domain must be configured and verified."},fromName:{type:"string",description:"Display name for a newly created sender profile. Requires fromEmail."},senderProfileId:{type:"string",description:"Set an existing sender profile. Mutually exclusive with fromEmail."},ccEmails:{type:["array","null"],description:"Addresses CC'd on every recipient's campaign email (max 10). Send an empty array or null to clear them; omit to leave unchanged.",items:{type:"string"},maxItems:10},bccEmails:{type:["array","null"],description:"Addresses BCC'd on every recipient's campaign email (max 10). Send an empty array or null to clear them; omit to leave unchanged.",items:{type:"string"},maxItems:10},campaignData:{type:"object",description:"Set campaign-scoped JSON data for repeat blocks and personalization."},computedLists:{type:"array",description:"Set computed list definitions derived from campaignData at send time.",items:{type:"object"}},labels:{type:"array",description:"Replacement label names. Send an empty array to clear labels. Missing labels are created automatically.",items:{type:"string"}}},required:["campaignId"],additionalProperties:!1}},{name:"schedule_campaign",description:"Schedule a draft or already scheduled campaign. Returns dashboard edit and preview URLs.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"},scheduledAt:{type:"string",description:"Future ISO 8601 timestamp for the send, for example 2026-06-01T14:00:00Z."},targetLists:{type:"object",description:"Optional campaign targeting object. Omit to use saved targeting or all active subscribers. Examples: {type:'all'}, {type:'lists', listIds:['list_123']}, {type:'segment', segmentId:'seg_123'}, {type:'filtered', filters:[...], filterJoinOperator:'and'}, or {type:'rules', include:[{type:'lists', listIds:['list_123']}], exclude:[{type:'segments', segmentIds:['seg_123']}]}. Rules audiences require at least one include rule.",additionalProperties:!0},sendTimeOptimization:{type:"boolean",description:"Whether to use send-time optimization."},spreadOverHours:{type:"number",description:"Spread delivery over an integer number of hours from 1 to 72. When set, spread delivery takes precedence over send-time optimization."},recurringInterval:{type:"string",enum:["weekly","monthly"],description:"Repeat this campaign on a cadence starting at scheduledAt. The campaign becomes a recurring template: each run is duplicated and sent automatically, re-evaluating audience membership every time. Omit for a one-shot send; scheduling again without it stops the recurrence."}},required:["campaignId","scheduledAt"],additionalProperties:!1}},{name:"send_test_email",description:"Queue a campaign test email to a single address. Returns a durable emailSendId; pass it to get_email_send for delivery status and failure details.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to test"},to:{type:"string",description:"Email address to send test to"}},required:["campaignId","to"]}},{name:"cancel_campaign",description:"Cancel a campaign. Stops scheduled and sending campaigns (also works for paused and approval-pending ones). Remaining emails will not be sent and the campaign cannot be restarted - this cannot be undone.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to cancel."}},required:["campaignId"]}},{name:"pause_campaign",description:"Pause a campaign that is currently sending. Only campaigns in sending status can be paused. Use resume_campaign to continue delivery later.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to pause."}},required:["campaignId"]}},{name:"resume_campaign",description:"Resume a paused campaign. Only campaigns in paused status can be resumed. Optionally spread the remaining delivery over a number of hours.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to resume."},spreadOverHours:{type:"number",description:"Spread the remaining delivery over an integer number of hours from 1 to 72."}},required:["campaignId"]}},{name:"delete_campaign",description:"Permanently delete a campaign. This cannot be undone. Sending, scheduled, or paused campaigns must be cancelled with cancel_campaign first.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to delete."}},required:["campaignId"]}},{name:"duplicate_campaign",description:"Duplicate a campaign as a new draft. mode 'campaign' (default) copies the campaign and its email, 'ab_test' also duplicates the campaign's A/B test with all variants, and 'variant' copies a single variant's content as the new campaign email (requires variantId).",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to duplicate."},mode:{type:"string",enum:["campaign","ab_test","variant"],description:"Duplication mode. Defaults to campaign."},variantId:{type:"string",description:"A/B test variant ID whose content becomes the new campaign email. Required when mode is variant."}},required:["campaignId"]}},{name:"resend_campaign_to_non_openers",description:"Create a draft that resends a sent campaign to everyone in the same audience who didn't open it. Copies the campaign email and reuses the original audience with a 'didn't open this campaign' rule added. Only available 6 hours after the campaign finishes sending. The draft must be scheduled or sent separately. Returns the new draft and an estimate of how many subscribers haven't opened the original.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"ID of the sent campaign to resend to non-openers."}},required:["campaignId"]}}];var Xz=[{name:"submit_feedback",description:"Send product feedback about Sequenzy itself to the Sequenzy team. IMPORTANT: call this tool whenever the user wanted to accomplish something and Sequenzy did not expose functionality for it - a missing tool or argument, an unsupported workflow, a confusing behavior, or a bug. Briefly tell the user you reported the gap. This feedback goes straight to the team and shapes what gets built next. Do not use it for questions about the user's own account or data, and never include secrets or API keys. Submitting feedback never changes account data.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},message:{type:"string",description:"The feedback itself. Be specific: what was needed, what was missing or wrong, and what you did instead (workaround, gave up, used the dashboard)."},category:{type:"string",enum:["missing_capability","bug","docs","ux","praise","other"],description:"Feedback category. Use missing_capability when the user wanted something these tools do not support (default: other)."},context:{type:"string",description:"Optional: what the user was trying to accomplish, in their words, plus any relevant tool names or arguments you tried."}},required:["message"]}}];var Yz=[{name:"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 Hz=[{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 Jz=[{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 zz=[{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:KJ},content:{type:"object",description:D0,additionalProperties:!0}},additionalProperties:!1}},{name:"update_landing_page",description:"Edit a landing page's name, slug, or full content. Provide at least one update field.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID."},name:{type:"string",description:"Landing page name."},slug:{type:"string",description:"Landing page URL slug. It will be normalized and made unique within the company."},content:{type:"object",description:D0,additionalProperties:!0}},required:["landingPageId"],additionalProperties:!1}},{name:"delete_landing_page",description:"Delete a landing page",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID."}},required:["landingPageId"],additionalProperties:!1}},{name:"publish_landing_page",description:"Publish a landing page. Optional name, slug, or content updates are saved before publishing.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID."},name:{type:"string",description:"Optional landing page name update."},slug:{type:"string",description:"Optional slug update before publishing."},content:{type:"object",description:D0,additionalProperties:!0}},required:["landingPageId"],additionalProperties:!1}},{name:"unpublish_landing_page",description:"Unpublish a landing page and return it to draft status. Optional name, slug, or content updates are saved first.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID."},name:{type:"string",description:"Optional landing page name update."},slug:{type:"string",description:"Optional slug update before unpublishing."},content:{type:"object",description:D0,additionalProperties:!0}},required:["landingPageId"],additionalProperties:!1}},{name:"connect_landing_page_domain",description:"Connect a custom domain for published landing pages. Returns the DNS target and verification records.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},domain:{type:"string",description:"Custom domain, for example pages.example.com."}},required:["domain"],additionalProperties:!1}},{name:"update_landing_page_domain_settings",description:"Update landing page domain settings. Provide domain to replace the custom domain, verify true to refresh verification, or both.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},domain:{type:"string",description:"Replacement custom domain."},verify:{type:"boolean",description:"Refresh domain verification after any domain update."}},additionalProperties:!1}}];var Az=[{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 Oz=[{name:"list_sequences",description:"List all email sequences (automations)",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list sequences for. If not provided, uses the currently selected company."}}}},{name:"get_sequence",description:"Get sequence details, editable step content, and graph topology. Each sequence.nodes item includes id, nodeType, current config, updatedAt, and updateHints with its editable/managed fields and ready-to-return expectedUpdatedAt token for update_sequence_node/update_sequence_nodes. The response also includes sequence.edges and graphRevision for safe edit_sequence_graph calls, plus sequence.emails with each email step's nodeId, linked emailId, subject, previewText, and blocks.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"],additionalProperties:!1}},{name:"create_sequence",description:"Create and persist a disabled draft email sequence, follow-up series, drip campaign, nurture flow, or automation workflow. For natural-language content, provide goal and emailCount. Use explicit steps for finished caller-supplied content, exact workflows, or migrations. Configure trigger plus its relevant field, such as listId, tagName, segmentId, or eventName. Supports email and SMS steps, delays and date waits, actions that dynamically create a provider discount/code, subscriber updates, event filters, enrollment rules, sending windows, and stop conditions. The saved draft appears in list_sequences. Never call enable_sequence unless the user explicitly asks to activate it.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the sequence in. If not provided, uses the currently selected company."},fromEmail:{type:"string",description:"From address for all emails in this sequence. Its domain must be configured and verified."},fromName:{type:"string",description:"Display name for a newly created sender profile. Requires fromEmail."},senderProfileId:{type:"string",description:"Existing sender profile ID. Mutually exclusive with fromEmail."},replyTo:{type:"string",description:"Reply-To address for all emails in this sequence. A reply profile is created when needed."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo."},replyProfileId:{type:"string",description:"Existing reply profile ID. Mutually exclusive with replyTo."},name:{type:"string",description:"Sequence name (e.g., 'User Onboarding', 'Welcome Series')"},trigger:{type:"string",enum:["contact_added","tag_added","segment_entered","event_received","inactivity","frequency"],description:"Trigger type: 'contact_added' (when added to a list), 'tag_added' (when tag is applied), 'segment_entered' (when a contact newly enters a saved segment), 'event_received' (when custom event fires), 'inactivity' (when subscriber hasn't performed an event for X days), 'frequency' (when subscriber performs event X times in Y days)"},listId:{type:"string",description:"List ID to trigger on (for contact_added trigger). If not provided, triggers on any list."},tagName:{type:"string",description:"Tag name to trigger on (required for tag_added trigger)"},segmentId:{type:"string",description:"Segment ID to trigger on (required for segment_entered trigger). Use list_segments first to choose a saved segment."},eventName:{type:"string",description:"Event name to trigger on (required for event_received, inactivity, and frequency triggers)"},propertyFilters:{type:"array",description:"Optional event property filters for event_received triggers. The sequence only starts when the triggering event's properties match ALL filters. Use a dot-path into the event properties; use [] to match inside arrays. Examples: scope a purchase sequence to one product with { path: 'lineItems[].providerProductId', operator: 'equals', value: 'prod_123' } (ecommerce.order_placed) or { path: 'productIds', operator: 'equals', value: 'prod_123' } (saas.purchase); to match any of several products use { path: 'lineItems[].providerProductId', operator: 'one_of', value: ['prod_123', 'prod_456'] }. Max 10 filters.",items:{type:"object",properties:{path:{type:"string",description:"Dot-path into the event properties, e.g. 'lineItems[].providerProductId' or 'plan'."},operator:{type:"string",enum:["exists","not_exists","equals","not_equals","one_of","contains","greater_than","less_than"],description:"Comparison operator. one_of matches when the property equals any entry of the value array."},value:{type:["string","number","boolean","array"],items:{type:["string","number"]},maxItems:50,description:"Value to compare against. Required for every operator except exists/not_exists. For one_of, pass an array of strings or numbers (max 50 values); all other operators take a single value."}},required:["path","operator"]}},inactiveDays:{type:"number",description:"Number of days of inactivity (required for inactivity trigger, must be >= 1)"},inactivityBaseline:{type:"string",enum:["sequence_created_at","subscriber_created_at"],description:"When to start counting inactivity for subscribers who never had the event. Defaults to sequence_created_at."},minCount:{type:"number",description:"Minimum event count (required for frequency trigger, must be >= 1)"},timeWindowDays:{type:"number",description:"Time window in days for frequency trigger (required for frequency trigger, must be >= 1)"},emailCount:{type:"number",description:"Number of emails in the sequence (default: 5, max: 10)"},durationDays:{type:"number",description:"Total duration in days used to space AI-generated sequence emails. Only applies when using goal-based AI generation."},emailStyle:{type:"string",enum:["visual","plain"],description:"Style for AI-generated emails: 'visual' (designed, with heroes/imagery/rich sections) or 'plain' (personal, text-first notes with a single button). Only applies to goal-based AI generation. Defaults to the company's saved preference when omitted."},goal:{type:"string",description:"What this sequence should accomplish for AI generation. Be specific to the app's actual features and user journey. Avoid generic goals that don't match the app's business model."},enrollmentMode:{type:"string",enum:["unlimited","one_time","matching_field"],description:"Sequence re-entry mode. Use 'matching_field' only for event_received triggers when duplicate active runs should be blocked per event field value."},enrollmentFieldPath:{type:"string",description:"Scalar dot-path event property used by enrollmentMode='matching_field', such as 'order.id' or 'product.providerVariantId'. Array traversal with [] is not supported; use propertyFilters for array matching. Leave omitted for Shopify back-in-stock/replenishment product-variant defaults."},sendingWindow:C$,stopCondition:{type:"object",description:"Optional explicit auto-stop condition. Use { type: 'has_tag', value: 'customer' } to end the sequence when a subscriber gets a tag, { type: 'does_not_have_tag', value: 'trial' } when a tag is removed, { type: 'entered_segment', value: 'segment_123' } when they enter a segment, { type: 'field_changed', value: 'plan' } when a subscriber field changes, { type: 'removed_from_list', value: 'list_123' } when they leave a list, { type: 'event_received', value: 'onboarding.completed' } when an event is tracked, or { type: 'none', value: null } for no auto-stop.",properties:{type:{type:"string",enum:["none","has_tag","does_not_have_tag","added_to_list","removed_from_list","entered_segment","field_changed","event_received"],description:"Stop condition type."},value:{type:["string","null"],description:"Tag name, list ID, segment ID, field path, or event name for the stop condition. Use null or omit for type 'none'."}},required:["type"]},steps:{type:"array",description:"Explicit sequence steps. Omit type for email steps, use type: 'sms' for SMS, type: 'create_discount' for a dynamic discount, or type: 'update_subscriber' with nodeType: 'action_update_attributes' and config to copy trigger-event values such as {{event.plan}} into subscriber data.",items:{type:"object",properties:{type:{type:"string",enum:["email","sms","create_discount","discount","update_subscriber"],description:"Step type. Omit or use 'email' for email content. Use 'sms' to send a text message, 'create_discount' to generate a code, or 'update_subscriber' to copy trigger data into the subscriber."},nodeType:{type:"string",enum:["action_email","action_sms","action_create_discount","action_update_attributes"],description:"Internal step type. Use action_update_attributes with config for Update Subscriber steps."},config:X0,subject:{type:"string",description:"Email subject. Required for email steps."},previewText:{type:"string",description:"Email preview text."},blocks:{type:"array",description:W1,items:{type:"object"}},html:{type:"string",description:"HTML content for email steps. Stored as one raw HTML block. Use this for imported provider HTML."},text:{type:"string",description:"SMS steps only: plain-text message body. Merge tags like {{FIRST_NAME}} work. Do not include opt-out text or a brand prefix - the platform adds those automatically."},imageUrls:{type:"array",items:{type:"string"},description:"SMS steps only: up to 2 publicly reachable image URLs sent as MMS media."},ineligibleAction:{type:"string",enum:["skip","exit"],description:"SMS steps only: what happens when the contact can't receive SMS (no phone, not opted in, unsupported country). Default 'skip' continues the sequence."},delay:G1,delayMs:{type:"number",description:"Delay before this step in milliseconds. Prefer delay for readability; use delayMs when importing provider waits."},waitUntil:Q1,name:{type:"string",description:"Email template name for email steps."},discount:{type:"object",description:"Discount configuration for create_discount steps. Prefer this nested shape for new integrations; legacy top-level discount fields are still accepted.",properties:{label:{type:"string",description:"Builder label for the discount step."},provider:{type:"string",enum:["stripe","shopify"],description:"Discount provider. Use 'stripe' to dynamically create a Stripe coupon plus promotion code, or 'shopify' to dynamically create a Shopify Admin discount code. Defaults to 'stripe' when omitted."},discountType:{type:"string",enum:["percent","amount"],description:"Discount type."},percentOff:{type:"number",description:"Percent discount from 1 to 100. Required when discountType is percent."},amountOff:{type:"number",description:"Fixed amount discount in the smallest currency unit, for example 500 for $5. Required when discountType is amount."},currency:{type:"string",description:"ISO currency for amount discounts. Defaults to usd."},duration:{type:"string",enum:["once","forever","repeating"],description:"Discount duration. Defaults to once."},durationInMonths:{type:"number",description:"Required for repeating discounts."},appliesToAllPlans:{type:"boolean",description:"Whether the discount applies to all plans. Defaults to true."},planIds:{type:"array",description:"Provider product IDs when appliesToAllPlans is false. Stripe uses IDs like prod_abc123; Shopify accepts numeric product IDs or gid://shopify/Product/... IDs.",items:{type:"string"}},codePrefix:{type:"string",description:"Optional prefix for generated dynamic codes. The final code also includes a subscriber/token suffix."},maxRedemptions:{type:"number",description:"Maximum redemptions for each generated code. Use 1 for subscriber-specific codes."},lockToSubscriber:{type:"boolean",description:"Stripe-only. Restrict each generated promotion code to the matched subscriber's Stripe customer."},expiresAt:{type:"string",description:"Optional future expiration date or ISO timestamp."},expiresInHours:{type:"number",description:"Optional relative expiration in hours, resolved when each subscriber's code is created (e.g., 48 for a 48-hour window per subscriber). Takes precedence over expiresAt."},name:{type:"string",description:"Optional display name for each dynamically generated provider discount."}}},label:{type:"string",description:"Legacy top-level discount label. Prefer discount.label."},provider:{type:"string",enum:["stripe","shopify"],description:"Legacy top-level discount provider. Prefer discount.provider. Supports 'stripe' and 'shopify'."},discountType:{type:"string",enum:["percent","amount"],description:"Legacy top-level discount type. Prefer discount.discountType."},percentOff:{type:"number",description:"Percent discount from 1 to 100. Required when discountType is percent."},amountOff:{type:"number",description:"Fixed amount discount in the smallest currency unit, for example 500 for $5. Required when discountType is amount."},currency:{type:"string",description:"ISO currency for amount discounts. Defaults to usd."},duration:{type:"string",enum:["once","forever","repeating"],description:"Discount duration. Defaults to once."},durationInMonths:{type:"number",description:"Required for repeating discounts."},appliesToAllPlans:{type:"boolean",description:"Whether the discount applies to all plans. Defaults to true."},planIds:{type:"array",description:"Provider product IDs when appliesToAllPlans is false. Stripe uses IDs like prod_abc123; Shopify accepts numeric product IDs or gid://shopify/Product/... IDs.",items:{type:"string"}},codePrefix:{type:"string",description:"Optional prefix for generated dynamic codes. The final code also includes a subscriber/token suffix."},maxRedemptions:{type:"number",description:"Maximum redemptions for each generated code. Use 1 for subscriber-specific codes."},lockToSubscriber:{type:"boolean",description:"Legacy top-level Stripe-only flag. Prefer discount.lockToSubscriber."},expiresAt:{type:"string",description:"Optional future expiration date or ISO timestamp."},expiresInHours:{type:"number",description:"Optional relative expiration in hours, resolved when each subscriber's code is created (e.g., 48 for a 48-hour window per subscriber). Takes precedence over expiresAt."}}}}},required:["name","trigger"]}}];var qz=[{name:"update_sequence",description:"Update an existing sequence. To target a specific existing step, use IDs returned by get_sequence. The emails/steps arrays edit email steps, smsSteps edits SMS steps, and subscriberUpdateSteps replaces the config of action_update_attributes steps. To insert new linear steps, use insertSteps with an afterNodeId from get_sequence; omit afterNodeId only to append to an unambiguous linear tail. For active sequences, structural changes such as insertSteps or branch require confirmStructuralChange:true after the user confirms the live-flow impact.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"},name:{type:"string",description:"Sequence name"},fromEmail:{type:"string",description:"Set the From address for all emails in this sequence. Its domain must be configured and verified."},fromName:{type:"string",description:"Display name for a newly created sender profile. Requires fromEmail."},senderProfileId:{type:"string",description:"Set an existing sender profile. Mutually exclusive with fromEmail."},replyTo:{type:"string",description:"Set the Reply-To address for all emails in this sequence."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo."},replyProfileId:{type:"string",description:"Set an existing reply profile. Mutually exclusive with replyTo."},enrollmentPaused:{type:"boolean",description:"Set true to stop new enrollments for an active sequence while current recipients continue. Set false to resume new enrollments. The sequence must already be active."},confirmStructuralChange:{type:"boolean",description:"Set true only after the user explicitly confirms a structural edit to an active sequence. Required for insertSteps or branch when the sequence is active; not needed for content-only email edits."},enrollmentMode:{type:"string",enum:["unlimited","one_time","matching_field"],description:"Updated sequence re-entry mode. 'matching_field' is only valid for event-based sequence triggers."},enrollmentFieldPath:{type:"string",description:"Scalar dot-path event property used by enrollmentMode='matching_field', such as 'order.id' or 'product.providerVariantId'. Array traversal with [] is not supported; use propertyFilters for array matching. Omit to leave unchanged. Use clearEnrollmentFieldPath to clear it."},clearEnrollmentFieldPath:{type:"boolean",description:"Set true to clear enrollmentFieldPath without sending a nullable schema value."},sendingWindow:C$,clearSendingWindow:{type:"boolean",description:"Set true to remove the sequence sending window. Do not provide this together with sendingWindow."},bccEmails:{type:"array",items:{type:"string"},description:"Email addresses that receive a blind copy of every email this sequence sends, such as a customer support inbox (max 10). Omit to leave unchanged. Use clearBccEmails to remove them."},clearBccEmails:{type:"boolean",description:"Set true to remove the sequence BCC addresses. Do not provide this together with bccEmails."},stopCondition:{type:"object",description:"Update the sequence auto-stop condition. Example: { type: 'has_tag', value: 'customer' } ends the sequence when the subscriber has that tag. Use { type: 'entered_segment', value: 'segment_123' } to stop when they enter a segment, { type: 'field_changed', value: 'plan' } to stop when a subscriber field changes, { type: 'removed_from_list', value: 'list_123' } to stop when they leave a list, or { type: 'none', value: null } to clear it.",properties:{type:{type:"string",enum:["none","has_tag","does_not_have_tag","added_to_list","removed_from_list","entered_segment","field_changed","event_received"]},value:{type:["string","null"],description:"Tag name, list ID, segment ID, field path, or event name for the stop condition."}},required:["type"]},branch:{type:"object",description:"Insert an if/else branch into an existing sequence. The branch is inserted after afterNodeId and creates an if path plus an else fallback path. Use get_sequence first to choose afterNodeId. Each branch condition should include steps, and elseSteps is required unless allowEmptyPaths is true. Conditions support tag presence/absence, lists, saved segments, events, clicked links, and field comparisons. Use activityScope for event_received and link_clicked checks.",properties:{afterNodeId:{type:"string",description:"Existing node ID to insert the branch after. Use a nodeId from get_sequence.sequence.nodes or get_sequence.sequence.emails."},label:{type:"string",description:"Optional branch node label."},branches:{type:"array",description:"Conditional branches evaluated in order. An else fallback is created automatically.",items:{type:"object",properties:{id:{type:"string",description:"Optional stable branch ID. Defaults to branch-0, branch-1, etc."},label:{type:"string",description:"Display label, e.g. 'If has customer tag'."},conditionType:{type:"string",enum:["has_tag","does_not_have_tag","in_list","in_segment","event_received","link_clicked","field_equals","field_contains","field_greater_than","field_less_than","has_phone","sms_subscribed"],description:"Condition type for this branch. has_phone (contact has a phone number) and sms_subscribed (contact opted in to SMS marketing) need no extra fields."},tagName:{type:"string",description:"Tag name for has_tag and does_not_have_tag conditions. This can be used instead of tagId."},tagId:{type:"string",description:"Tag ID or tag name for has_tag and does_not_have_tag conditions."},listId:{type:"string",description:"List ID for in_list conditions."},segmentId:{type:"string",description:"Segment ID for in_segment conditions."},segmentName:{type:"string",description:"Optional display name for in_segment conditions."},eventName:{type:"string",description:"Event name for event_received conditions, such as project.invite.accepted."},linkUrl:{type:"string",description:"Optional URL substring for link_clicked conditions. Omit to match any clicked link."},activityScope:{type:"string",enum:["ever","this_sequence","previous_email"],description:"Scope for event_received and link_clicked conditions. Omit to check ever."},fieldName:{type:"string",description:"Subscriber attribute name for field conditions."},fieldValue:{type:"string",description:"Comparison value for field conditions."},steps:{type:"array",description:"Steps to create inside this branch path. Required by default so the branch is not an empty placeholder.",items:g$}},required:["conditionType"]}},elseSteps:{type:"array",description:"Steps to create inside the else fallback path. Required by default so the else arm is usable.",items:g$},allowEmptyPaths:{type:"boolean",description:"Set true only when intentionally creating empty UI placeholders. Normal API/MCP use should omit this and provide branch steps plus elseSteps."}},required:["afterNodeId","branches"]},insertSteps:{type:"object",description:"Insert one or more new linear steps into an existing sequence. Use get_sequence first, then pass afterNodeId to insert after a specific node. If afterNodeId is omitted, the steps are appended only when the sequence has exactly one linear tail. Inserted email steps require subject plus blocks or html.",properties:{afterNodeId:{type:"string",description:"Existing node ID to insert after. Use a nodeId from get_sequence.sequence.nodes or get_sequence.sequence.emails. Omit only to append to an unambiguous linear tail."},steps:{type:"array",description:"New steps to insert. Supports emails, delays, create_discount actions, webhooks, and other supported sequence path node types.",items:g$}},required:["steps"]},emails:{type:"array",description:"Updated existing sequence emails. If you omit emailId/nodeId, items are matched by existing step order. This field does not create new steps; use insertSteps for insertion and include delay on inserted email steps when a timer is needed.",items:{type:"object",properties:{emailId:{type:"string",description:"Optional target linked email template ID for a step. Use the emailId returned in get_sequence.sequence.emails."},nodeId:{type:"string",description:"Optional target action_email node ID for a step. Use the nodeId returned in get_sequence.sequence.emails."},name:{type:"string",description:"Updated step/template name"},subject:{type:"string",description:"Updated email subject"},previewText:{type:"string",description:"Updated preview text"},html:{type:"string",description:"Updated HTML content. Stored as one raw HTML block. Use this to preserve imported provider HTML."},htmlContent:{type:"string",description:"Alias for html. Stored as one raw HTML block. Use this when updating imported provider HTML for a step."},blocks:{type:"array",description:Jw,items:{type:"object"}},...KW}}},steps:{type:"array",description:"Alias for emails. Supports the same fields and matching rules, and only edits existing email steps. Use insertSteps to create new steps.",items:{type:"object",properties:{emailId:{type:"string",description:"Optional target linked email template ID for a step. Use the emailId returned in get_sequence.sequence.emails."},nodeId:{type:"string",description:"Optional target action_email node ID for a step. Use the nodeId returned in get_sequence.sequence.emails."},name:{type:"string",description:"Updated step/template name"},subject:{type:"string",description:"Updated email subject"},previewText:{type:"string",description:"Updated preview text"},html:{type:"string",description:"Updated HTML content. Stored as one raw HTML block. Use this to preserve imported provider HTML."},htmlContent:{type:"string",description:"Alias for html. Stored as one raw HTML block. Use this when updating HTML content for a step."},blocks:{type:"array",description:Jw,items:{type:"object"}},...KW}}},smsSteps:{type:"array",description:"Content updates for existing SMS steps, targeted by nodeId (an action_sms node from get_sequence.sequence.nodes). Content-only edits - use insertSteps to create new SMS steps.",items:{type:"object",properties:{nodeId:{type:"string",description:"Target action_sms node ID. Required."},text:{type:"string",description:"Replacement plain-text message body. Merge tags like {{FIRST_NAME}} work. Provide text or blocks, not both."},blocks:{type:"array",items:{type:"object"},description:"Replacement SMS content blocks (text + image subset)."},imageUrls:{type:"array",items:{type:"string"},description:"Up to 2 publicly reachable MMS image URLs. Only valid together with text."},label:{type:"string",description:"Updated display label for the step."},ineligibleAction:{type:"string",enum:["skip","exit"],description:"Updated behavior when the contact can't receive SMS."}},required:["nodeId"]}},subscriberUpdateSteps:{type:"array",description:"Full config replacements for existing Update Subscriber steps, targeted by action_update_attributes nodeId.",items:{type:"object",properties:{nodeId:{type:"string",description:"Target action_update_attributes node ID."},config:X0},required:["nodeId","config"]}}},required:["sequenceId"]}},{name:"update_sequence_node",description:"Patch one existing sequence node in place. Call get_sequence first, select sequence.nodes[].id, inspect nodeType/config, and pass that node's updatedAt as expectedUpdatedAt. This supports every stored sequence node type, including delays, email/SMS content, actions, conditions, branches without topology changes, webhooks, and trigger settings. Delay example: changes:{ delay:{ days:7 } }. The update is type-aware and preserves fields you omit. It cannot change nodeType, managed linked-resource IDs, or graph topology; use edit_sequence_graph for structural work. On an active sequence, set confirmLiveChange:true only after the user confirms the live behavior change. Existing recipients already waiting keep their scheduled timestamp; the new delay applies when recipients reach the node in the future.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID."},nodeId:u$.properties.nodeId,changes:AW,expectedUpdatedAt:u$.properties.expectedUpdatedAt,confirmLiveChange:{type:"boolean",description:"Set true only after the user explicitly confirms changing a node in an active sequence."}},required:["sequenceId","nodeId","changes","expectedUpdatedAt"],additionalProperties:!1}},{name:"update_sequence_nodes",description:"Atomically patch multiple existing sequence nodes. Call get_sequence first and include each node's id plus its updatedAt as expectedUpdatedAt. Every patch follows update_sequence_node's type-aware rules. Either every node update commits or none do, making this the preferred tool for changes such as replacing all 5-minute delays with 7-day delays. A node may appear only once. It cannot change node types or graph topology. On an active sequence, set confirmLiveChange:true only after the user confirms the live behavior change. Existing recipients already waiting keep their scheduled timestamps.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID."},updates:{type:"array",description:"Non-empty node patches. Each nodeId may appear only once.",items:u$},confirmLiveChange:{type:"boolean",description:"Set true only after the user explicitly confirms changing nodes in an active sequence."}},required:["sequenceId","updates"],additionalProperties:!1}},{name:"edit_sequence_graph",description:"Restructure an existing sequence graph using node IDs, edges, and graphRevision from get_sequence. move_node repositions one non-split step; beforeNodeId can place an A/B test or other step at the shared continuation below a branch. duplicate_node creates an independent copy and deep-copies linked email or A/B test content. delete_node safely splices a linear step; deleting a split node requires the complete replacement edges. replace_edges atomically replaces the complete topology for advanced reconnect or multi-node reorder work. Always call get_sequence immediately before this tool and pass its graphRevision. Active sequences require confirmStructuralChange:true after the user confirms live-flow impact.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID."},action:{type:"string",enum:["move_node","delete_node","duplicate_node","replace_edges"],description:"Graph operation. Use move_node for a single step reorder, duplicate_node for an independent copy, delete_node to remove a step/node, or replace_edges for an atomic reconnect/reorder of the whole topology."},graphRevision:{type:"string",description:"Exact graphRevision returned by the latest get_sequence call. The edit is rejected if the graph changed since then."},nodeId:{type:"string",description:"Existing node to move, duplicate, or delete. Required for those actions and unused by replace_edges."},afterNodeId:{type:"string",description:"For move_node or duplicate_node, insert immediately after this node. The target must have at most one outgoing path. Provide exactly one of afterNodeId or beforeNodeId."},beforeNodeId:{type:"string",description:"For move_node or duplicate_node, insert immediately before this node. All incoming paths converge through the moved/copied node, which is useful for placing a step below a branch. Provide exactly one of beforeNodeId or afterNodeId."},edges:{type:"array",description:"Complete replacement topology from get_sequence.sequence.edges. The returned edge array is already normalized for this input and can be reused directly. Required for replace_edges and when deleting a split node. Preserve each branch edge's condition.branchId. Do not include edges that reference a deleted node.",items:{type:"object",properties:{sourceNodeId:{type:"string"},targetNodeId:{type:"string"},condition:{type:"object",description:"Optional edge routing condition. Preserve condition.branchId on edges leaving logic_branch nodes."}},required:["sourceNodeId","targetNodeId"],additionalProperties:!1}},confirmStructuralChange:{type:"boolean",description:"Set true only after the user explicitly confirms a structural edit to an active sequence."}},required:["sequenceId","action","graphRevision"],additionalProperties:!1}},{name:"insert_sequence_step",description:"Insert one new email or SMS step into an existing sequence. Prefer this over update_sequence.steps/emails when adding a step: it creates the step node (plus an email template for email steps) and, when delay or delayMs is provided, a logic_delay node immediately before it. For SMS steps set type:'sms' and provide 'text' (generate copy with generate_sms; check get_sms_settings first and warn the user if SMS is not enabled). Use get_sequence first, then pass afterNodeId from sequence.nodes or sequence.emails to choose the insertion point. If afterNodeId is omitted, the step is appended only when the sequence has exactly one linear tail. For active sequences, set confirmStructuralChange:true only after the user confirms the live-flow impact.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID."},type:{type:"string",enum:["email","sms"],description:"Step type. Defaults to 'email'. Use 'sms' to insert an SMS step (requires 'text')."},afterNodeId:{type:"string",description:"Existing node ID to insert after. Use a nodeId from get_sequence.sequence.nodes or get_sequence.sequence.emails. Omit only to append to an unambiguous linear tail."},confirmStructuralChange:{type:"boolean",description:"Set true only after the user explicitly confirms a structural edit to an active sequence."},name:{type:"string",description:"Optional email template and step name."},subject:{type:"string",description:"Email subject for the new step. Required for email steps; not used for SMS steps."},previewText:{type:"string",description:"Optional email preview text for the new step."},blocks:{type:"array",description:W1,items:{type:"object"}},html:{type:"string",description:"HTML content for the new step. Stored as one raw HTML block. Use this for imported provider HTML. Provide either html or blocks, not both."},senderProfileId:{type:"string",description:"Email steps only: sender profile for the new step. Omit to inherit the effective identity of the nearest sequence email. After a branch merge, only fields shared by every incoming path are inherited; conflicting fields use sequence or company defaults."},fromEmail:{type:"string",description:"Email steps only: From address for the new step. Its domain must be verified. Mutually exclusive with senderProfileId."},fromName:{type:"string",description:"Email steps only: display name override for the new step. With fromEmail, also names a newly created sender profile."},replyProfileId:{type:"string",description:"Email steps only: reply profile for the new step. Omit to inherit the effective Reply-To of the nearest sequence email. After a branch merge, only fields shared by every incoming path are inherited; conflicting fields use sequence or company defaults. Mutually exclusive with replyTo."},replyTo:{type:"string",description:"Email steps only: Reply-To address for the new step. Mutually exclusive with replyProfileId."},replyToName:{type:"string",description:"Email steps only: display name for a newly created reply profile. Requires replyTo."},text:{type:"string",description:"SMS steps only: plain-text message body. Merge tags like {{FIRST_NAME}} work. Do not include opt-out text or a brand prefix - the platform adds those automatically."},imageUrls:{type:"array",items:{type:"string"},description:"SMS steps only: up to 2 publicly reachable image URLs sent as MMS media."},label:{type:"string",description:"SMS steps only: display label for the step."},ineligibleAction:{type:"string",enum:["skip","exit"],description:"SMS steps only: what happens when the contact can't receive SMS (no phone, not opted in, unsupported country). Default 'skip' continues the sequence."},delay:G1,delayMs:{type:"number",description:"Optional wait in milliseconds before the new step. Prefer delay for readability."},waitUntil:Q1},required:["sequenceId"],additionalProperties:!1}},{name:"enable_sequence",description:"Enable/activate a sequence. IMPORTANT: Only call this when the user EXPLICITLY asks to enable or activate a sequence. Never enable sequences automatically after creation - the user must review the content first.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}},{name:"disable_sequence",description:"Disable/freeze a sequence. This blocks new enrollments and holds current recipients until the sequence is enabled again. To only stop new enrollments while current recipients continue, use pause_sequence_enrollments.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}},{name:"pause_sequence_enrollments",description:"Stop new enrollments for an active sequence while current recipients continue through the sequence. This matches the dashboard 'Stop new enrollments' control and does not freeze current recipients.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}},{name:"resume_sequence_enrollments",description:"Resume new enrollments for an active sequence whose enrollment gate was paused. Use enable_sequence instead for a fully disabled/frozen sequence.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}},{name:"enroll_subscribers_in_sequence",description:"Manually enroll subscribers in a sequence by email address or subscriber ID. Maximum 500 total targets per call across emails and subscriberIds. Only active subscribers are enrolled: unknown emails are returned in `notFound`, while inactive, unavailable, and already actively enrolled subscribers are counted in `skipped`. By default enrollment starts at the first step after the trigger; pass targetNodeId to start at a specific step.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID to enroll subscribers in."},emails:{type:"array",items:{type:"string"},description:"Email addresses of subscribers to enroll. Combined with subscriberIds, maximum 500 total targets per call."},subscriberIds:{type:"array",items:{type:"string"},description:"Subscriber IDs to enroll. Combined with emails, maximum 500 total targets per call."},targetNodeId:{type:"string",description:"Optional node ID to start enrollment at. Use a non-trigger nodeId from get_sequence. Defaults to the first step after the trigger."}},required:["sequenceId"]}},{name:"cancel_sequence_enrollments",description:"Cancel active/waiting enrollments in one sequence. Provide sequenceId and exactly one target: subscriberId for one subscriber, or fieldValues to match stored entry event properties. For fieldValues, fieldPath is optional when the sequence has enrollmentFieldPath configured; otherwise provide a dot path such as order.id.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID whose enrollments should be cancelled."},subscriberId:{type:"string",description:"Subscriber ID to cancel in this sequence. Provide subscriberId or fieldValues, not both."},fieldPath:{type:"string",description:"Dot-path inside the token's stored entry event properties, such as order.id or event.id. Optional when the sequence has enrollmentFieldPath configured."},fieldValues:{type:"array",items:{type:"string"},description:"Entry field values to match. Cancels all active/waiting enrollments in the sequence whose entry field value is in this list. Provide fieldValues or subscriberId, not both."},dryRun:{type:"boolean",description:"When true, returns matching enrollments without cancelling them. Field-value cancellation defaults to dryRun on the API unless explicitly false."},reason:{type:"string",description:"Optional cancellation reason stored on matched enrollment tokens."}},required:["sequenceId"],additionalProperties:!1}},{name:"delete_sequence",description:"Delete a sequence",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}}];var Lz=[{name:"add_subscriber",description:"Add a new subscriber to your list",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to add subscriber to. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address"},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide this with email when creating, or instead of email for an existing subscriber."},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",description:"Initial subscriber status: active, unsubscribed, or bounced. Defaults to active."},optInMode:{type:"string",description:"Consent mode: confirmed creates active immediately when consent is verified, double_opt_in sends a confirmation email before activation, and default obeys company double opt-in settings."}},required:[]}},{name:"update_subscriber",description:"Update an existing subscriber's attributes or tags",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},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."},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 or delete a subscriber",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},hardDelete:{type:"boolean",description:"If true, permanently deletes. If false, just unsubscribes."}},required:[]}},{name:"get_subscriber",description:"Get the full subscriber profile, including tags, notes, list memberships, sequence enrollments, email stats, and recent activity",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},includeMachineEngagement:lb},required:[]}},{name:"list_subscriber_notes",description:"List internal notes for a subscriber. Provide email or externalId to identify the subscriber.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."}},required:[]}},{name:"add_subscriber_note",description:"Add an internal note to a subscriber. Provide email or externalId to identify the subscriber.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},body:{type:"string",description:"Internal note body, up to 5000 characters."}},required:["body"]}},{name:"delete_subscriber_note",description:"Delete one internal subscriber note by note ID.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},noteId:{type:"string",description:"Subscriber note ID to delete."}},required:["noteId"]}},{name:"search_subscribers",description:"Search subscribers by free-text query, tags, list, or segment. If you omit limit, the tool fetches all pages and returns every match.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},query:{type:"string",description:"Search query (email or name)"},tags:{type:"array",items:{type:"string"},description:"Filter by tags"},list:{type:"string",description:"Filter by subscriber list ID or exact list name. Prefer listId when known."},listId:{type:"string",description:"Filter by subscriber list ID."},listName:{type:"string",description:"Filter by exact subscriber list name when the list ID is not known."},segmentId:{type:"string",description:"Filter by segment ID"},status:{type:"string",description:"Filter by subscriber status: active, unsubscribed, or bounced."},limit:{type:"number",description:"Maximum results to return. If omitted, the tool returns all matches across pages."}}}}];var Uz={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."}},Bz=[{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:Uz,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:Uz,required:["email"],additionalProperties:!1}}];var Pz=[{name:"list_tags",description:"List all tags in the account",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list tags for. If not provided, uses the currently selected company."}}}},{name:"create_tag",description:"Create a new tag definition. The name is normalized to lowercase with hyphens (e.g. 'VIP Customer' becomes 'vip-customer'). Color defaults to gray.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},name:{type:"string",description:"Tag name. Normalized to lowercase with hyphens."},color:{type:"string",enum:[...D1],description:"Tag color. Defaults to gray."}},required:["name"]}},{name:"update_tag",description:"Update a tag's color. System tags cannot be updated.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},tagId:{type:"string",description:"Tag ID. Use list_tags to find tag IDs."},color:{type:"string",enum:[...D1],description:"New tag color."}},required:["tagId","color"]}},{name:"delete_tag",description:"Permanently delete a tag and remove it from all subscribers. This cannot be undone. System tags and tags used by sequences cannot be deleted.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},tagId:{type:"string",description:"Tag ID. Use list_tags to find tag IDs."}},required:["tagId"]}},{name:"list_lists",description:"List all subscriber lists",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list lists for. If not provided, uses the currently selected company."}}}},{name:"create_list",description:"Create a new subscriber list",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the list in. If not provided, uses the currently selected company."},name:{type:"string",description:"List name"},description:{type:"string",description:"List description"}},required:["name"]}},{name:"update_list",description:"Update a subscriber list's name, description, or privacy. Only the provided fields are changed.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},listId:{type:"string",description:"Subscriber list ID to update."},name:{type:"string",description:"New list name."},description:{type:["string","null"],description:"New list description. Pass null to clear it."},isPrivate:{type:"boolean",description:"Whether the list is private."}},required:["listId"]}},{name:"delete_list",description:"Permanently delete a subscriber list and remove all of its memberships. Subscribers themselves are kept. This cannot be undone.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},listId:{type:"string",description:"Subscriber list ID to delete."}},required:["listId"]}},{name:"add_subscribers_to_list",description:"Bulk add existing or new subscribers to a subscriber list from an email array. Existing subscribers are added to the list without requiring a per-subscriber update call.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},listId:{type:"string",description:"Subscriber list ID to add subscribers to."},emails:{type:"array",items:{type:"string"},description:"Email addresses to add to the list. Maximum 500 per call."},duplicateStrategy:{type:"string",description:"Duplicate strategy for existing subscribers: skip, merge, or overwrite. Defaults to skip."},enrollInSequences:{type:"boolean",description:"Whether newly created subscribers should enroll in matching sequences. Defaults to false."},optInMode:{type:"string",description:"Consent mode for newly created subscribers: default, confirmed, or double_opt_in. Defaults to default."}},required:["listId","emails"]}},{name:"remove_subscribers_from_list",description:"Remove subscribers from a list by email address. Maximum 500 emails per call. Subscribers stay in the account; only the list membership is removed. Returns the removed count plus a notFound array of emails that did not match a subscriber.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},listId:{type:"string",description:"Subscriber list ID to remove subscribers from."},emails:{type:"array",items:{type:"string"},description:"Email addresses to remove from the list. Maximum 500 per call."}},required:["listId","emails"]}},{name:"list_segments",description:"List all segments",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list segments for. If not provided, uses the currently selected company."}}}},{name:"create_segment",description:'Create a new segment from explicit filter rules. Use `filters` plus `filterJoinOperator` for flat legacy rules, or `root` for nested AND/OR groups such as `{ "kind": "group", "joinOperator": "and", "children": [{ "kind": "filter", "field": "attribute", "operator": "gte", "value": "mrr:50" }, { "kind": "group", "joinOperator": "or", "children": [{ "kind": "filter", "field": "tag", "operator": "contains", "value": "vip" }, { "kind": "filter", "field": "event", "operator": "is_not", "value": "saas.purchase:30d" }] }] }`. Supports `event` and `segment` fields, Stripe product purchase/current/trial/date filters, and campaign-specific engagement filters.',inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the segment in. If not provided, uses the currently selected company."},name:{type:"string",description:"Segment name"},filterJoinOperator:{type:"string",enum:["and","or"],description:'How top-level filters combine. Use `"and"` to require every filter or `"or"` to match any filter.'},filters:{type:"array",items:qW,minItems:1,description:'Array of segment filters. Example custom attribute empty check: [{"id":"filter-1","field":"attribute","operator":"is_empty","value":"last_logged_in:"}]. Example Stripe purchase filter: [{"id":"filter-1","field":"stripeProduct","operator":"is","value":"prod_123"}]. Example threshold filter: [{"id":"filter-1","field":"stripeProduct","operator":"at_least","value":"prod_123:3"}]. Example commerce product purchase filter (value is provider:productId since product ids are provider-scoped): [{"id":"filter-1","field":"commerceProduct","operator":"is","value":"api:prod-starter-kit"}]. Example repeat-buyer filter: [{"id":"filter-1","field":"commerceProduct","operator":"at_least","value":"shopify:42:2"}]. Example trial cancellation filter: [{"id":"filter-1","field":"stripeTrialProduct","operator":"is","value":"prod_123:is_canceled"}]. Example trial end filter: [{"id":"filter-1","field":"stripeTrialProduct","operator":"is","value":"prod_123:end_at:2026-05-26"}]. Example campaign-specific engagement combo: [{"id":"filter-1","field":"emailBounced","operator":"is","value":"campaign:cmp_abc"},{"id":"filter-2","field":"emailBounced","operator":"is_not","value":"campaign:cmp_xyz"}]. Combine them with `filterJoinOperator: "or"` to match any filter.'},root:{...LW,description:"Nested filter root. Mutually exclusive with `filters` and `filterJoinOperator`."}},required:["name"]}},{name:"update_segment",description:"Update a segment's name and/or filter rules. Use the same `filters` plus `filterJoinOperator` or nested `root` shapes as create_segment; providing `filters` or `root` replaces the segment's existing rules.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},segmentId:{type:"string",description:"Segment ID to update."},name:{type:"string",description:"New segment name."},filterJoinOperator:{type:"string",enum:["and","or"],description:'How top-level filters combine. Use `"and"` to require every filter or `"or"` to match any filter.'},filters:{type:"array",items:qW,minItems:1,description:"Replacement segment filters. Same shape and validation rules as create_segment. Mutually exclusive with `root`."},root:{...LW,description:"Replacement nested filter root. Mutually exclusive with `filters` and `filterJoinOperator`."}},required:["segmentId"]}},{name:"delete_segment",description:"Permanently delete a segment. This cannot be undone. Subscribers are not affected.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},segmentId:{type:"string",description:"Segment ID to delete."}},required:["segmentId"]}},{name:"get_segment_count",description:"Get the number of subscribers in a segment",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},segmentId:{type:"string",description:"Segment ID"}},required:["segmentId"]}}];var Fz=[{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 Kz=[{name:"list_templates",description:"List all email templates, including per-locale localization sync status",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"get_template",description:"Get a template's details, content, and all localized variants with sync status",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID"}},required:["templateId"]}},{name:"create_template",description:"Create a new email template. For net-new email content requested in natural language, use `prompt`; do not write HTML or construct blocks yourself. Use `blocks` only for finished caller-supplied Sequenzy content and `html` only for supplied or explicitly requested preserved HTML.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},name:{type:"string",description:"Template name"},subject:{type:"string",description:"Email subject line. Optional with `prompt`."},previewText:{type:["string","null"],description:"Optional preview text override."},html:{type:"string",description:"Email HTML content. Mutually exclusive with `blocks`. Use this for imported provider templates; Sequenzy stores it as one raw HTML block to preserve the design."},blocks:{type:"array",description:Hw,items:{type:"object"}},prompt:{type:"string",description:"Natural-language request for Sequenzy to generate branded native template blocks."},style:{type:"string",description:"Generation style; valid only with `prompt`."},tone:{type:"string",description:"Generation tone; valid only with `prompt`."},labels:{type:"array",description:"Optional label names to assign. Missing labels are created automatically.",items:{type:"string"}}},required:["name"]}},{name:"update_template",description:"Update an existing template. At least one of `name`, `subject`, `html`, `blocks`, or `labels` is required, and only those update fields are accepted.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID"},name:{type:"string",description:"Template name"},subject:{type:"string",description:"Email subject line"},html:{type:"string",description:"Email HTML content. Mutually exclusive with `blocks`. Use this for imported provider templates; Sequenzy stores it as one raw HTML block to preserve the design."},blocks:{type:"array",description:Hw,items:{type:"object"}},labels:{type:"array",description:"Replacement label names. Send an empty array to clear labels. Missing labels are created automatically.",items:{type:"string"}}},required:["templateId"],additionalProperties:!1}},{name:"set_template_localization",description:"Create or replace one caller-supplied localized variant of a template. The locale must be enabled for the company and cannot be its primary locale. Provide exactly one of `html` or `blocks`.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID, transactional email ID, or slug."},locale:{type:"string",description:"Enabled non-primary locale code such as es, fr, or pt-BR."},subject:{type:"string",description:"Localized email subject line."},previewText:{type:["string","null"],description:"Optional localized inbox preview text."},html:{type:"string",description:"Localized email HTML. Mutually exclusive with `blocks`."},blocks:{type:"array",description:Hw,items:{type:"object"}}},required:["templateId","locale","subject"],additionalProperties:!1}},{name:"sync_template_localizations",description:"Queue AI translation for selected template locales. Omit `locales` to sync every enabled non-primary locale. This works even when automatic on-save localization is disabled.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID, transactional email ID, or slug."},locales:{type:"array",description:"Optional enabled non-primary locale codes to sync. Omit to sync all enabled non-primary locales.",items:{type:"string"}}},required:["templateId"],additionalProperties:!1}},{name:"delete_template",description:"Delete a template",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID"}},required:["templateId"]}}];var Mz=[{name:"list_transactional_emails",description:"List transactional email templates, including their API slugs and linked email IDs",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"get_transactional_email",description:"Get a transactional email by ID or slug, including subject, preview text, blocks, variables, and linked dashboard URLs",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},idOrSlug:{type:"string",description:"Transactional email ID or API slug, for example `welcome-email`."}},required:["idOrSlug"]}},{name:"create_transactional_email",description:"Create a saved transactional email template with an API slug. For net-new natural-language content use `prompt`; do not author HTML or blocks. `blocks` are finished caller-supplied Sequenzy content and `html` is preserved/imported markup.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},name:{type:"string",description:"Transactional email name."},slug:{type:"string",description:"Optional API slug used when sending by slug, for example `password-reset`. If omitted, Sequenzy generates one from the name."},subject:{type:"string",description:"Email subject line. Optional when `prompt` is provided because the generated subject will be used."},previewText:{type:["string","null"],description:"Email preview text."},html:{type:"string",description:"Email HTML content. Mutually exclusive with `blocks`. Sequenzy stores it as one raw HTML block."},blocks:{type:"array",description:`${Hw} Mutually exclusive with \`html\`.`,items:{type:"object"}},prompt:{type:"string",description:"Generate transactional email blocks from a prompt. Generated blocks include the company's branding (logo and a footer without an unsubscribe link). Mutually exclusive with `html` and `blocks`."},style:{type:"string",description:"Prompt generation style: minimal, branded, promotional. Only used with `prompt`."},tone:{type:"string",description:"Prompt generation tone: professional, casual, friendly. Only used with `prompt`."},enabled:{type:"boolean",description:"Whether this transactional email can be sent immediately. Prompt-created templates default to false; explicit HTML/blocks retain the compatibility default of true."}},required:["name"],additionalProperties:!1}},{name:"update_transactional_email",description:"Update a transactional email by ID or slug. At least one of `name`, `enabled`, `subject`, `previewText`, `html`, or `blocks` is required. Use `html` or `blocks` to replace the linked email body.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},idOrSlug:{type:"string",description:"Transactional email ID or API slug, for example `welcome-email`."},name:{type:"string",description:"Transactional email name."},enabled:{type:"boolean",description:"Whether this transactional email can be sent."},subject:{type:"string",description:"Email subject line."},previewText:{type:["string","null"],description:"Email preview text."},html:{type:"string",description:"Email HTML content. Mutually exclusive with `blocks`. Sequenzy stores it as one raw HTML block."},blocks:{type:"array",description:`${Jw} Mutually exclusive with \`html\`.`,items:{type:"object"}}},required:["idOrSlug"],additionalProperties:!1}},{name:"send_email",description:"Queue one transactional email using either a saved transactional email API slug (`templateId`) or direct `subject` and `html` content. Returns a durable emailSendId; pass it to get_email_send for delivery status and failure details.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},to:{type:"string",description:"Recipient email address"},subject:{type:"string",description:"Email subject line. Required with `html` when `templateId` is omitted."},html:{type:"string",description:"Direct-send HTML body. Required with `subject` when `templateId` is omitted; the MCP server maps this to the transactional API `body` field."},templateId:{type:"string",description:"Saved transactional email API slug, for example `welcome-email`. The field name is retained for MCP compatibility and is mapped to the transactional API `slug` field."},variables:{type:"object",description:"Variables for template personalization. Nested objects and arrays are supported for repeat blocks, for example { items: [...] }."},subscriberExternalId:{type:"string",description:"Customer-owned subscriber ID for attaching analytics/localization on single-recipient sends. Maximum length: 255 characters."}},required:["to"],additionalProperties:!1}}];var Iz=[{name:"list_webhooks",description:"List outbound webhook endpoints and their subscribed event types.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"create_webhook",description:"Create an outbound webhook endpoint. IMPORTANT: the response includes a signingSecret that is returned only once - show it to the user immediately so they can store it and verify webhook signatures. If events is omitted, a default set of event types is subscribed.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},name:{type:"string",description:"Webhook endpoint name."},url:{type:"string",description:"HTTPS URL that will receive webhook events."},events:{type:"array",items:{type:"string",enum:[...X1]},description:"Event types to subscribe to. If omitted, a default set is used."}},required:["name","url"]}},{name:"update_webhook",description:"Update an outbound webhook endpoint's name, URL, subscribed events, or status (enabled/disabled). Providing events replaces the existing event list.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},webhookId:{type:"string",description:"Webhook endpoint ID."},name:{type:"string",description:"New webhook endpoint name."},url:{type:"string",description:"New HTTPS URL that will receive webhook events."},events:{type:"array",items:{type:"string",enum:[...X1]},description:"Replacement event type subscriptions."},status:{type:"string",enum:["enabled","disabled"],description:"Enable or disable deliveries to this endpoint."}},required:["webhookId"]}},{name:"delete_webhook",description:"Permanently delete an outbound webhook endpoint along with its delivery history. This cannot be undone. To keep the endpoint but stop deliveries, use update_webhook with status disabled instead.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},webhookId:{type:"string",description:"Webhook endpoint ID to delete."}},required:["webhookId"]}},{name:"test_webhook",description:"Send a test event to an outbound webhook endpoint to verify it is reachable and signatures can be validated.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},webhookId:{type:"string",description:"Webhook endpoint ID to test."}},required:["webhookId"]}},{name:"list_webhook_deliveries",description:"List recent delivery attempts for an outbound webhook endpoint, including status and response codes.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},webhookId:{type:"string",description:"Webhook endpoint ID."},limit:{type:"number",description:"Maximum number of deliveries to return, from 1 to 100. Defaults to 20."}},required:["webhookId"]}},{name:"replay_webhook_delivery",description:"Replay a previous webhook delivery, re-sending the same event payload to the endpoint.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},webhookId:{type:"string",description:"Webhook endpoint ID."},deliveryId:{type:"string",description:"Delivery ID to replay. Use list_webhook_deliveries to find delivery IDs."}},required:["webhookId","deliveryId"]}}];var Zz=[...$z,...Lz,...Bz,...Az,...Pz,...Gz,...Kz,...wz,...Dz,...Yz,...zz,...Hz,...Oz,...qz,...Mz,...Qz,...Fz,...Jz,...Iz,...Wz,...Xz];async function jz(b,w){let $;switch(b){case"get_account":{let W=await A("GET","/api/v1/account"),Q=qw();$={...W,selectedCompanyId:Q??W.currentCompanyId};break}case"select_company":{let W=w.companyId,Q=await A("GET","/api/v1/account"),G=Q.companies?.find((D)=>D.id===W);if(!G)throw Error(`Company not found. Available companies: ${Q.companies?.map((D)=>`${D.name} (${D.id})`).join(", ")??"none"}`);A0(W),$={success:!0,message:`Switched to company: ${G.name}`,companyId:G.id,companyName:G.name};break}case"get_app_urls":{let W=await i$(w);$={...Yw({companyId:W,campaignId:P(w,"campaignId"),landingPageId:P(w,"landingPageId"),sequenceId:P(w,"sequenceId"),emailId:P(w,"emailId")??P(w,"templateId"),transactionalId:P(w,"transactionalId"),emailSendId:P(w,"emailSendId"),domainId:P(w,"domainId"),status:P(w,"status"),settingsTab:P(w,"settingsTab")}),...W===void 0&&{note:"No company ID is selected. Call get_account, select_company, or pass companyId to get concrete dashboard URLs."}};break}case"create_company":{let W=await A("POST","/api/v1/companies",{name:w.name,domain:w.domain});if(!W.success)throw Error("Failed to create company");let Q=W.company.id,G=6,D=0,X=W.company.status;while(X==="processing"&&D<G){await new Promise((J)=>setTimeout(J,20000)),D++;let H=await A("GET",`/api/v1/companies/${Q}`);if(H.success)X=H.company.status}A0(Q);let Y=await A("GET",`/api/v1/companies/${Q}`);$={success:!0,company:Y.company,message:X==="processing"?"Company created but still processing. You can continue using it while processing completes.":`Company '${Y.company.name}' created and ready to use.`,autoSelected:!0};break}case"get_company":{let W=w.companyId;$=await A("GET",`/api/v1/companies/${W}`);break}case"update_company":{let W=await pJ("update_company",w),Q=TJ(w);$=await A("PATCH",`/api/v1/companies/${W}`,Q);break}case"get_sync_rules":{let W=w.companyId;$=await A("GET","/api/v1/sync-rules",void 0,W);break}case"update_sync_rules":{let W=w.companyId;if(w.syncRules!==null&&!Array.isArray(w.syncRules))throw Error("`syncRules` must be an array of rules or null when calling `update_sync_rules`.");$=await A("PUT","/api/v1/sync-rules",{syncRules:w.syncRules},W);break}case"get_shopify_automation_settings":{let W=w.companyId;$=await A("GET","/api/v1/shopify/automation-settings",void 0,W);break}case"update_shopify_automation_settings":{let W=w.companyId,Q={};if(w.browseAbandonment!==void 0)Q.browseAbandonment=w.browseAbandonment;if(w.priceDrop!==void 0)Q.priceDrop=w.priceDrop;if(Object.keys(Q).length===0)throw Error("Provide `browseAbandonment` and/or `priceDrop` when calling `update_shopify_automation_settings`.");$=await A("PUT","/api/v1/shopify/automation-settings",Q,W);break}case"create_api_key":{let W=w.companyId,Q={};if(typeof w.name==="string")Q.name=w.name;if(typeof w.preset==="string")Q.preset=w.preset;if(Array.isArray(w.scopes))Q.scopes=w.scopes;$=await A("POST","/api/v1/api-keys",Q,W);break}case"list_websites":{let W=w.companyId;$=await A("GET","/api/v1/websites",void 0,W);break}case"add_sending_domain":case"add_website":{let W=w.companyId;$=await A("POST","/api/v1/websites",{domain:w.domain},W);break}case"check_website":{let W=w.companyId;$=await A("GET",`/api/v1/websites/${encodeURIComponent(String(w.domain))}`,void 0,W);break}case"verify_sending_domain":{let W=w.companyId;$=await A("POST",`/api/v1/websites/${encodeURIComponent(String(w.domain))}/verify`,void 0,W);break}case"get_integration_guide":$=await A("POST","/api/v1/integration-guide",w);break;default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function Vz(b,w){let $;switch(b){case"generate_email":{let W=w.companyId;$=await A("POST","/api/v1/generate/email",w,W);break}case"generate_subject_lines":{let W=w.companyId;$=await A("POST","/api/v1/generate/subjects",w,W);break}case"generate_sms":{let W=w.companyId;$=await A("POST","/api/v1/generate/sms",w,W);break}case"get_sms_settings":{let W=w.companyId;$=await A("GET","/api/v1/sms/settings",void 0,W);break}case"send_test_sms":{let W=w.companyId,Q={to:Z("send_test_sms",w,"to")};for(let G of["text","imageUrls","blocks"])if(w[G]!==void 0)Q[G]=w[G];$=await A("POST","/api/v1/sms/test",Q,W);break}case"submit_feedback":{let W=w.companyId,Q={message:Z("submit_feedback",w,"message"),source:"mcp"};for(let G of["category","context"])if(w[G]!==void 0)Q[G]=w[G];$=await A("POST","/api/v1/feedback",Q,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function Nz(b,w){let $;switch(b){case"list_transactional_emails":{let W=w.companyId;$=await A("GET","/api/v1/transactional",void 0,W);break}case"get_transactional_email":{let W=w.companyId;$=await A("GET",`/api/v1/transactional/${w.idOrSlug}`,void 0,W);break}case"create_transactional_email":{let W=w.companyId,Q=new Set(["companyId","name","slug","subject","previewText","html","blocks","prompt","style","tone","enabled"]),G=Object.keys(w).filter((X)=>!Q.has(X));if(G.length>0)throw Error(`\`create_transactional_email\` accepts only \`name\`, \`slug\`, \`subject\`, \`previewText\`, \`html\`, \`blocks\`, \`prompt\`, \`style\`, \`tone\`, and \`enabled\` fields. Unsupported field${G.length===1?"":"s"}: ${G.map((X)=>`\`${X}\``).join(", ")}.`);cJ(w);let D=Object.fromEntries(Object.entries(w).filter(([X])=>X!=="companyId"));$=await A("POST","/api/v1/transactional",D,W);break}case"update_transactional_email":{let W=w.companyId,Q=new Set(["companyId","idOrSlug","name","enabled","subject","previewText","html","blocks"]),G=Object.keys(w).filter((X)=>!Q.has(X));if(G.length>0)throw Error(`\`update_transactional_email\` accepts only \`name\`, \`enabled\`, \`subject\`, \`previewText\`, \`html\`, and \`blocks\` update fields. Unsupported field${G.length===1?"":"s"}: ${G.map((X)=>`\`${X}\``).join(", ")}.`);if(_b("update_transactional_email",w),w.name===void 0&&w.enabled===void 0&&w.subject===void 0&&w.previewText===void 0&&w.html===void 0&&w.blocks===void 0)throw Error("Provide at least one of `name`, `enabled`, `subject`, `previewText`, `html`, or `blocks` when calling `update_transactional_email`.");let D=Object.fromEntries(Object.entries(w).filter(([X])=>X!=="companyId"&&X!=="idOrSlug"));$=await A("PATCH",`/api/v1/transactional/${w.idOrSlug}`,D,W);break}case"send_email":{let W=w.companyId,Q=Z("send_email",w,"to"),G=w.templateId===void 0?void 0:Z("send_email",w,"templateId"),D=w.subject===void 0?void 0:Z("send_email",w,"subject"),X=w.html===void 0?void 0:Z("send_email",w,"html");if(G!==void 0&&(D!==void 0||X!==void 0))throw Error("`templateId` cannot be combined with `subject` or `html` when calling `send_email`.");if(G===void 0&&(D===void 0||X===void 0))throw Error("Provide either `templateId` or both `subject` and `html` when calling `send_email`.");let Y=Object.fromEntries(Object.entries({to:Q,slug:G,subject:D,body:X,variables:w.variables,subscriberExternalId:w.subscriberExternalId}).filter(([,H])=>H!==void 0));$=await A("POST","/api/v1/transactional/send",Y,W);break}case"get_stats":{let W=w.companyId,Q=w.period??"7d",G=new URLSearchParams({period:String(Q)});if(w.includeMachineEngagement===!0)G.set("includeMachineEngagement","true");$=await A("GET",`/api/v1/metrics?${G.toString()}`,void 0,W);break}case"get_campaign_stats":{let W=w.companyId,Q=new URLSearchParams;if(w.includeMachineEngagement===!0)Q.set("includeMachineEngagement","true");let G=Q.toString();$=await A("GET",`/api/v1/metrics/campaigns/${w.campaignId}${G?`?${G}`:""}`,void 0,W);break}case"get_sequence_stats":{let W=w.companyId,Q=new URLSearchParams;if(w.includeMachineEngagement===!0)Q.set("includeMachineEngagement","true");let G=Q.toString();$=await A("GET",`/api/v1/metrics/sequences/${w.sequenceId}${G?`?${G}`:""}`,void 0,W);break}case"list_campaign_events":{let W=w.companyId,Q=Z("list_campaign_events",w,"campaignId"),D=ZW("list_campaign_events",w).toString();$=await A("GET",`/api/v1/metrics/campaigns/${encodeURIComponent(Q)}/events${D?`?${D}`:""}`,void 0,W);break}case"list_sequence_events":{let W=w.companyId,Q=Z("list_sequence_events",w,"sequenceId"),D=ZW("list_sequence_events",w).toString();$=await A("GET",`/api/v1/metrics/sequences/${encodeURIComponent(Q)}/events${D?`?${D}`:""}`,void 0,W);break}case"get_subscriber_activity":{let W=w.companyId,Q=Aw("get_subscriber_activity",w),G=await Y0(Q,W,{includeMachineEngagement:w.includeMachineEngagement===!0});$={success:G.success,email:G.subscriber.email,emailStats:G.subscriber.emailStats??null,activity:G.subscriber.activity??[],sequenceEnrollments:G.subscriber.sequenceEnrollments??[]};break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function Tz(b,w){let $;switch(b){case"list_tags":{let W=w.companyId;$=await A("GET","/api/v1/tags",void 0,W);break}case"create_tag":{let W=w.companyId,Q=Z("create_tag",w,"name"),G=Ub("create_tag",w,"color",D1);$=await A("POST","/api/v1/tags",{name:Q,...G!==void 0&&{color:G}},W);break}case"update_tag":{let W=w.companyId,Q=Z("update_tag",w,"tagId"),G=H0("update_tag",w,"color",D1);$=await A("PATCH",`/api/v1/tags/${encodeURIComponent(Q)}`,{color:G},W);break}case"delete_tag":{let W=w.companyId,Q=Z("delete_tag",w,"tagId");$=await A("DELETE",`/api/v1/tags/${encodeURIComponent(Q)}`,void 0,W);break}case"list_lists":{let W=w.companyId;$=await A("GET","/api/v1/lists",void 0,W);break}case"create_list":{let W=w.companyId;$=await A("POST","/api/v1/lists",w,W);break}case"update_list":{let W=w.companyId,Q=Z("update_list",w,"listId");if(w.name===void 0&&w.description===void 0&&w.isPrivate===void 0)throw Error("Provide at least one of `name`, `description`, or `isPrivate` when calling `update_list`.");if(w.name!==void 0&&P(w,"name")===void 0)throw Error("`name` cannot be empty when calling `update_list`.");if(w.description!==void 0&&w.description!==null&&typeof w.description!=="string")throw Error("`description` must be a string or null when calling `update_list`.");if(w.isPrivate!==void 0&&typeof w.isPrivate!=="boolean")throw Error("`isPrivate` must be a boolean when calling `update_list`.");$=await A("PATCH",`/api/v1/lists/${encodeURIComponent(Q)}`,{...w.name!==void 0&&{name:P(w,"name")},...w.description!==void 0&&{description:w.description},...w.isPrivate!==void 0&&{isPrivate:w.isPrivate}},W);break}case"delete_list":{let W=w.companyId,Q=Z("delete_list",w,"listId");$=await A("DELETE",`/api/v1/lists/${encodeURIComponent(Q)}`,void 0,W);break}case"add_subscribers_to_list":{let W=w.companyId,Q=Z("add_subscribers_to_list",w,"listId"),G=VW("add_subscribers_to_list",w),D=Ub("add_subscribers_to_list",w,"duplicateStrategy",["skip","merge","overwrite"])??"skip",X=Ub("add_subscribers_to_list",w,"optInMode",["default","confirmed","double_opt_in"])??"default";$=await A("POST",`/api/v1/lists/${encodeURIComponent(Q)}/subscribers`,{emails:G,duplicateStrategy:D,enrollInSequences:w.enrollInSequences===!0,optInMode:X},W);break}case"remove_subscribers_from_list":{let W=w.companyId,Q=Z("remove_subscribers_from_list",w,"listId"),G=VW("remove_subscribers_from_list",w);$=await A("POST",`/api/v1/lists/${encodeURIComponent(Q)}/subscribers/remove`,{emails:G},W);break}case"list_segments":{let W=w.companyId;$=await A("GET","/api/v1/segments",void 0,W);break}case"create_segment":{VJ(w);let W=w.companyId;$=await A("POST","/api/v1/segments",{...w,...w.filters!==void 0?{filters:x$(w.filters)}:{},...w.root!==void 0?{root:y$(w.root)}:{}},W);break}case"update_segment":{NJ(w);let W=w.companyId,Q=Z("update_segment",w,"segmentId"),G=P(w,"name"),D=Ub("update_segment",w,"filterJoinOperator",["and","or"]);$=await A("PATCH",`/api/v1/segments/${encodeURIComponent(Q)}`,{...G!==void 0&&{name:G},...D!==void 0&&{filterJoinOperator:D},...w.filters!==void 0?{filters:x$(w.filters)}:{},...w.root!==void 0?{root:y$(w.root)}:{}},W);break}case"delete_segment":{let W=w.companyId,Q=Z("delete_segment",w,"segmentId");$=await A("DELETE",`/api/v1/segments/${encodeURIComponent(Q)}`,void 0,W);break}case"get_segment_count":{let W=w.companyId;$=await A("GET",`/api/v1/segments/${w.segmentId}/count`,void 0,W);break}case"list_audience_syncs":{let W=w.companyId;$=await A("GET","/api/v1/audience-syncs",void 0,W);break}case"list_ad_accounts":{let W=w.companyId;$=await A("GET","/api/v1/ad-accounts",void 0,W);break}case"create_audience_sync":{let W=w.companyId,Q=P(w,"segmentId"),G=P(w,"predefinedSegmentId");if(Q&&G)throw Error("Provide either `segmentId` or `predefinedSegmentId` when calling `create_audience_sync`, not both.");if(!Q&&!G)throw Error("Provide either `segmentId` or `predefinedSegmentId` when calling `create_audience_sync`.");$=await A("POST","/api/v1/audience-syncs",{segmentId:Q,predefinedSegmentId:G,adAccountId:Z("create_audience_sync",w,"adAccountId"),audienceName:Z("create_audience_sync",w,"audienceName"),...w.frequency!==void 0?{frequency:w.frequency}:{}},W);break}case"update_audience_sync":{let W=w.companyId,Q=Z("update_audience_sync",w,"syncId");$=await A("PATCH",`/api/v1/audience-syncs/${encodeURIComponent(Q)}`,{...w.frequency!==void 0?{frequency:w.frequency}:{},...w.isActive!==void 0?{isActive:w.isActive}:{}},W);break}case"delete_audience_sync":{let W=w.companyId,Q=Z("delete_audience_sync",w,"syncId");$=await A("DELETE",`/api/v1/audience-syncs/${encodeURIComponent(Q)}`,void 0,W);break}case"sync_audience_now":{let W=w.companyId,Q=Z("sync_audience_now",w,"syncId");$=await A("POST",`/api/v1/audience-syncs/${encodeURIComponent(Q)}/sync`,void 0,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function Ez(b,w){let $;switch(b){case"list_templates":{let W=w.companyId,Q=new URLSearchParams,G=P(w,"label");if(G)Q.set("label",G);$=await A("GET",`/api/v1/templates${Q.size>0?`?${Q}`:""}`,void 0,W);break}case"get_template":{let W=w.companyId;$=await A("GET",`/api/v1/templates/${w.templateId}`,void 0,W);break}case"create_template":{let W=w.companyId;yJ(w);let Q=Object.fromEntries(Object.entries(w).filter(([G])=>G!=="companyId"));$=await A("POST","/api/v1/templates",Q,W);break}case"update_template":{let W=w.companyId,Q=new Set(["companyId","templateId","name","subject","html","blocks","labels"]),G=Object.keys(w).filter((D)=>!Q.has(D));if(G.length>0)throw Error(`\`update_template\` accepts only \`name\`, \`subject\`, \`html\`, \`blocks\`, and \`labels\` update fields. Unsupported field${G.length===1?"":"s"}: ${G.map((D)=>`\`${D}\``).join(", ")}.`);if(_b("update_template",w),Y1("update_template",w),w.name===void 0&&w.subject===void 0&&w.html===void 0&&w.blocks===void 0&&w.labels===void 0)throw Error("Provide at least one of `name`, `subject`, `html`, `blocks`, or `labels` when calling `update_template`.");$=await A("PUT",`/api/v1/templates/${w.templateId}`,w,W);break}case"set_template_localization":{let W=w.companyId,Q=Z("set_template_localization",w,"templateId"),G=Z("set_template_localization",w,"locale"),D=Z("set_template_localization",w,"subject"),X=new Set(["companyId","templateId","locale","subject","previewText","html","blocks"]),Y=Object.keys(w).filter((J)=>!X.has(J));if(Y.length>0)throw Error(`\`set_template_localization\` received unsupported field${Y.length===1?"":"s"}: ${Y.map((J)=>`\`${J}\``).join(", ")}.`);_b("set_template_localization",w,{requireContent:!0});let H={subject:D};if(w.previewText!==void 0)H.previewText=w.previewText;if(w.html!==void 0)H.html=w.html;if(w.blocks!==void 0)H.blocks=w.blocks;$=await A("PUT",`/api/v1/templates/${encodeURIComponent(Q)}/localizations/${encodeURIComponent(G)}`,H,W);break}case"sync_template_localizations":{let W=w.companyId,Q=Z("sync_template_localizations",w,"templateId"),G=new Set(["companyId","templateId","locales"]),D=Object.keys(w).filter((Y)=>!G.has(Y));if(D.length>0)throw Error(`\`sync_template_localizations\` received unsupported field${D.length===1?"":"s"}: ${D.map((Y)=>`\`${Y}\``).join(", ")}.`);let X;if(w.locales!==void 0){if(!Array.isArray(w.locales)||w.locales.length===0||w.locales.some((Y)=>typeof Y!=="string"||Y.trim().length===0))throw Error("`locales` must contain at least one non-empty locale string when calling `sync_template_localizations`.");X=w.locales.map((Y)=>Y.trim())}$=await A("POST",`/api/v1/templates/${encodeURIComponent(Q)}/localizations/sync`,X===void 0?{}:{locales:X},W);break}case"delete_template":{let W=w.companyId;$=await A("DELETE",`/api/v1/templates/${w.templateId}`,void 0,W);break}case"list_ab_tests":{let W=w.companyId,Q=new URLSearchParams,G=P(w,"sequenceId");if(G)Q.set("sequenceId",G);$=await A("GET",`/api/v1/ab-tests${Q.size>0?`?${Q}`:""}`,void 0,W);break}case"get_ab_test":{let W=w.companyId;$=await A("GET",`/api/v1/ab-tests/${w.abTestId}`,void 0,W);break}case"get_ab_test_stats":{let W=w.companyId,Q=new URLSearchParams,G=P(w,"period"),D=P(w,"start"),X=P(w,"end");if(G)Q.set("period",G);if(D)Q.set("start",D);if(X)Q.set("end",X);if(w.includeMachineEngagement===!0)Q.set("includeMachineEngagement","true");$=await A("GET",`/api/v1/ab-tests/${w.abTestId}/stats${Q.size>0?`?${Q}`:""}`,void 0,W);break}case"restart_ab_test":{let W=w.companyId,Q=new Set(["companyId","abTestId","sourceVariantId","testType","winnerThreshold","variantCount"]),G=Object.keys(w).filter((H)=>!Q.has(H));if(G.length>0)throw Error(`\`restart_ab_test\` accepts only \`sourceVariantId\`, \`testType\`, \`winnerThreshold\`, and \`variantCount\` option fields. Unsupported field${G.length===1?"":"s"}: ${G.map((H)=>`\`${H}\``).join(", ")}.`);let D=P(w,"testType");if(D!==void 0&&D!=="subject"&&D!=="content")throw Error("`restart_ab_test` testType must be `subject` or `content`.");let X=w.winnerThreshold===void 0?void 0:Number(w.winnerThreshold);if(X!==void 0&&(!Number.isInteger(X)||X<10||X>1000))throw Error("`restart_ab_test` winnerThreshold must be an integer from 10 to 1000.");let Y=w.variantCount===void 0?void 0:Number(w.variantCount);if(Y!==void 0&&(!Number.isInteger(Y)||Y<2||Y>4))throw Error("`restart_ab_test` variantCount must be an integer from 2 to 4.");$=await A("POST",`/api/v1/ab-tests/${w.abTestId}/restart`,{sourceVariantId:P(w,"sourceVariantId"),testType:D,winnerThreshold:X,variantCount:Y},W);break}case"update_ab_test_variant":{let W=w.companyId,Q=new Set(["companyId","abTestId","variantId","subject","previewText","html","blocks"]),G=Object.keys(w).filter((D)=>!Q.has(D));if(G.length>0)throw Error(`\`update_ab_test_variant\` accepts only \`subject\`, \`previewText\`, \`html\`, and \`blocks\` update fields. Unsupported field${G.length===1?"":"s"}: ${G.map((D)=>`\`${D}\``).join(", ")}.`);if(_b("update_ab_test_variant",w),w.subject===void 0&&w.previewText===void 0&&w.html===void 0&&w.blocks===void 0)throw Error("Provide at least one of `subject`, `previewText`, `html`, or `blocks` when calling `update_ab_test_variant`.");$=await A("PATCH",`/api/v1/ab-tests/${w.abTestId}/variants/${w.variantId}`,w,W);break}case"create_ab_test":{let W=w.companyId,Q=Z("create_ab_test",w,"campaignId"),G=P(w,"name"),D=zw("create_ab_test",w,"testPercentage",5,50),X=zw("create_ab_test",w,"testDurationMinutes",15,1440),Y=Ub("create_ab_test",w,"winnerCriteria",["open_rate","click_rate"]);if(w.variants!==void 0){if(!Array.isArray(w.variants))throw Error("`variants` must be an array when calling `create_ab_test`.");w.variants.forEach((H,J)=>{if(!y(H)||typeof H.subject!=="string"||H.subject.trim()==="")throw Error(`\`variants\` item ${J+1} must include a non-empty \`subject\` when calling \`create_ab_test\`.`);if(H.blocks!==void 0&&!Array.isArray(H.blocks))throw Error(`\`variants\` item ${J+1} \`blocks\` must be an array when calling \`create_ab_test\`.`)})}$=await A("POST","/api/v1/ab-tests",{campaignId:Q,...G!==void 0&&{name:G},...D!==void 0&&{testPercentage:D},...X!==void 0&&{testDurationMinutes:X},...Y!==void 0&&{winnerCriteria:Y},...w.variants!==void 0&&{variants:w.variants}},W);break}case"add_ab_test_variant":{let W=w.companyId,Q=Z("add_ab_test_variant",w,"abTestId"),G=Z("add_ab_test_variant",w,"subject"),D=P(w,"previewText");if(w.blocks!==void 0&&!Array.isArray(w.blocks))throw Error("`blocks` must be an array when calling `add_ab_test_variant`.");$=await A("POST",`/api/v1/ab-tests/${encodeURIComponent(Q)}/variants`,{subject:G,...D!==void 0&&{previewText:D},...w.blocks!==void 0&&{blocks:w.blocks}},W);break}case"delete_ab_test_variant":{let W=w.companyId,Q=Z("delete_ab_test_variant",w,"abTestId"),G=Z("delete_ab_test_variant",w,"variantId");$=await A("DELETE",`/api/v1/ab-tests/${encodeURIComponent(Q)}/variants/${encodeURIComponent(G)}`,void 0,W);break}case"delete_ab_test":{let W=w.companyId,Q=Z("delete_ab_test",w,"abTestId");$=await A("DELETE",`/api/v1/ab-tests/${encodeURIComponent(Q)}`,void 0,W);break}case"list_campaigns":{let W=w.companyId,Q=new URLSearchParams;if(w.status)Q.set("status",String(w.status));let G=P(w,"label");if(G)Q.set("label",G);$=await A("GET",`/api/v1/campaigns?${Q}`,void 0,W);break}case"get_campaign":{let W=w.companyId;$=await A("GET",`/api/v1/campaigns/${w.campaignId}`,void 0,W);break}case"get_email_send":{let W=w.companyId;$=await A("GET",`/api/v1/email-sends/${encodeURIComponent(String(w.emailSendId))}`,void 0,W);break}case"create_campaign":{let W=w.companyId;if(xJ(w),w.fromEmail!==void 0&&w.senderProfileId!==void 0)throw Error("Provide either `fromEmail` or `senderProfileId` when calling `create_campaign`, not both.");if(w.replyTo!==void 0&&w.replyProfileId!==void 0)throw Error("Provide either `replyTo` or `replyProfileId` when calling `create_campaign`, not both.");if(w.fromName!==void 0&&w.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `create_campaign`.");if(w.replyToName!==void 0&&w.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `create_campaign`.");let Q=Object.fromEntries(Object.entries(w).filter(([G])=>G!=="companyId"));$=await A("POST","/api/v1/campaigns",Q,W);break}case"update_campaign":{let W=w.companyId,Q=new Set(["companyId","campaignId","name","subject","trackingCode","html","blocks","fromEmail","fromName","senderProfileId","replyTo","replyToName","replyProfileId","ccEmails","bccEmails","campaignData","computedLists","labels"]),G=Object.keys(w).filter((D)=>!Q.has(D));if(G.length>0)throw Error(`\`update_campaign\` accepts only content, sending identity, campaign data, computed list, and label update fields. Unsupported field${G.length===1?"":"s"}: ${G.map((D)=>`\`${D}\``).join(", ")}.`);if(_b("update_campaign",w),Y1("update_campaign",w),w.replyTo!==void 0&&w.replyProfileId!==void 0)throw Error("Provide either `replyTo` or `replyProfileId` when calling `update_campaign`, not both.");if(w.fromEmail!==void 0&&w.senderProfileId!==void 0)throw Error("Provide either `fromEmail` or `senderProfileId` when calling `update_campaign`, not both.");if(w.fromName!==void 0&&w.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `update_campaign`.");if(w.replyToName!==void 0&&w.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `update_campaign`.");if(w.name===void 0&&w.subject===void 0&&w.trackingCode===void 0&&w.html===void 0&&w.blocks===void 0&&w.fromEmail===void 0&&w.senderProfileId===void 0&&w.replyTo===void 0&&w.replyProfileId===void 0&&w.ccEmails===void 0&&w.bccEmails===void 0&&w.campaignData===void 0&&w.computedLists===void 0&&w.labels===void 0)throw Error("Provide at least one campaign content, sending identity, campaign data, computed list, or label field when calling `update_campaign`.");$=await A("PUT",`/api/v1/campaigns/${w.campaignId}`,w,W);break}case"schedule_campaign":{let W=w.companyId,Q=new Set(["companyId","campaignId","scheduledAt","targetLists","sendTimeOptimization","spreadOverHours","recurringInterval"]),G=Object.keys(w).filter((D)=>!Q.has(D));if(G.length>0)throw Error(`\`schedule_campaign\` accepts only \`campaignId\`, \`scheduledAt\`, \`targetLists\`, \`sendTimeOptimization\`, \`spreadOverHours\`, and \`recurringInterval\`. Unsupported field${G.length===1?"":"s"}: ${G.map((D)=>`\`${D}\``).join(", ")}.`);hJ(w),$=await A("POST",`/api/v1/campaigns/${w.campaignId}/schedule`,{scheduledAt:w.scheduledAt,...w.targetLists!==void 0&&{targetLists:w.targetLists},...w.sendTimeOptimization!==void 0&&{sendTimeOptimization:w.sendTimeOptimization},...w.spreadOverHours!==void 0&&{spreadOverHours:w.spreadOverHours},...w.recurringInterval!==void 0&&{recurringInterval:w.recurringInterval}},W);break}case"send_test_email":{let W=w.companyId;$=await A("POST",`/api/v1/campaigns/${w.campaignId}/test`,{to:w.to},W);break}case"cancel_campaign":{let W=w.companyId,Q=Z("cancel_campaign",w,"campaignId");$=await A("POST",`/api/v1/campaigns/${encodeURIComponent(Q)}/cancel`,void 0,W);break}case"pause_campaign":{let W=w.companyId,Q=Z("pause_campaign",w,"campaignId");$=await A("POST",`/api/v1/campaigns/${encodeURIComponent(Q)}/pause`,void 0,W);break}case"resume_campaign":{let W=w.companyId,Q=Z("resume_campaign",w,"campaignId"),G=zw("resume_campaign",w,"spreadOverHours",1,72);$=await A("POST",`/api/v1/campaigns/${encodeURIComponent(Q)}/resume`,{...G!==void 0&&{spreadOverHours:G}},W);break}case"delete_campaign":{let W=w.companyId,Q=Z("delete_campaign",w,"campaignId");$=await A("DELETE",`/api/v1/campaigns/${encodeURIComponent(Q)}`,void 0,W);break}case"duplicate_campaign":{let W=w.companyId,Q=Z("duplicate_campaign",w,"campaignId"),G=Ub("duplicate_campaign",w,"mode",["campaign","ab_test","variant"]),D=P(w,"variantId");if(G==="variant"&&D===void 0)throw Error("`variantId` is required when calling `duplicate_campaign` with mode `variant`.");$=await A("POST",`/api/v1/campaigns/${encodeURIComponent(Q)}/duplicate`,{...G!==void 0&&{mode:G},...D!==void 0&&{variantId:D}},W);break}case"resend_campaign_to_non_openers":{let W=w.companyId,Q=Z("resend_campaign_to_non_openers",w,"campaignId");$=await A("POST",`/api/v1/campaigns/${encodeURIComponent(Q)}/resend-to-non-openers`,void 0,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function _z(b,w){let $;switch(b){case"list_forms":{let W=w.companyId;$=await A("GET","/api/v1/forms",void 0,W);break}case"create_form":{let W=w.companyId,Q=Z("create_form",w,"name"),G=Array.isArray(w.listIds)?w.listIds.filter((Y)=>typeof Y==="string").map((Y)=>Y.trim()).filter(Boolean):[];if(G.length===0)throw Error("`listIds` must contain at least one list ID when calling `create_form`.");let D=Ub("create_form",w,"duplicateStrategy",["skip","merge","overwrite"]),X={name:Q,listIds:G};for(let Y of["tagIds","buttonText","headline","description","successMessage","redirectUrl","showFirstName","showLastName"])if(w[Y]!==void 0)X[Y]=w[Y];if(D!==void 0)X.duplicateStrategy=D;$=await A("POST","/api/v1/forms",X,W);break}case"get_form_embed":{let W=w.companyId,Q=Z("get_form_embed",w,"formId");$=await A("GET",`/api/v1/forms/embed/${encodeURIComponent(Q)}`,void 0,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}function l$(b,w,$,W,Q){let G=b[w];if(G===void 0)return;if(typeof G!=="number"||!Number.isFinite(G)||G<$||G>W||Q&&!Number.isInteger(G))throw Error(`\`${w}\` must be a ${Q?"integer":"number"} between ${$} and ${W} when calling \`upload_image_asset\`.`);return G}async function Sz(b,w){if(b!=="upload_image_asset")return{handled:!1,result:void 0};let $=P(w,"filePath"),W=P(w,"imageBase64");if($===void 0===(W===void 0))throw Error("Provide either `filePath` or `imageBase64` (not both) when calling `upload_image_asset`.");let Q=P(w,"filename");if(W!==void 0&&Q===void 0)throw Error("`filename` is required with `imageBase64` when calling `upload_image_asset`.");let G=l$(w,"sourceWidth",1,20000,!0),D=l$(w,"sourceHeight",1,20000,!0);if(G===void 0!==(D===void 0))throw Error("Provide both `sourceWidth` and `sourceHeight` when calling `upload_image_asset`.");let X=l$(w,"displayWidthPercent",1,100,!1)??100,Y=l$(w,"cropHeight",1,2000,!0),H=P(w,"objectFit");if(H!==void 0&&H!=="cover"&&H!=="contain")throw Error("`objectFit` must be 'cover' or 'contain' when calling `upload_image_asset`.");if(H!==void 0&&Y===void 0)throw Error("`objectFit` can only be used with `cropHeight` when calling `upload_image_asset`.");let J=P(w,"align");if(J!==void 0&&!["left","center","right"].includes(J))throw Error("`align` must be 'left', 'center', or 'right' when calling `upload_image_asset`.");let z=typeof w.altText==="string"?w.altText.trim():void 0;if(z!==void 0&&z.length>500)throw Error("`altText` must be 500 characters or fewer when calling `upload_image_asset`.");let O=await sJ({companyId:P(w,"companyId"),filePath:$,imageBase64:W,filename:Q,contentType:P(w,"contentType"),altText:z,sourceWidth:G,sourceHeight:D}),q={type:"image",src:O.url,alt:O.altText??"",width:X,widthType:"percent",...Y!==void 0&&{height:Y,objectFit:H??"cover"},...J!==void 0&&{align:J}};return{handled:!0,result:{success:!0,asset:O,imageBlock:q,message:"Insert imageBlock into the target email's blocks array with its create or update tool."}}}async function Rz(b,w){let $;switch(b){case"list_landing_pages":{let W=w.companyId;$=await A("GET","/api/v1/landing-pages",void 0,W);break}case"get_landing_page":{let W=w.companyId;$=await A("GET",`/api/v1/landing-pages/${w.landingPageId}`,void 0,W);break}case"create_landing_page":{let W=w.companyId,Q=new Set(["companyId","name","slug","template","content"]),G=Object.keys(w).filter((D)=>!Q.has(D));if(G.length>0)throw Error(`\`create_landing_page\` accepts only \`name\`, \`slug\`, \`template\`, and \`content\` fields. Unsupported field${G.length===1?"":"s"}: ${G.map((D)=>`\`${D}\``).join(", ")}.`);$=await A("POST","/api/v1/landing-pages",{...w.name!==void 0&&{name:w.name},...w.slug!==void 0&&{slug:w.slug},...w.template!==void 0&&{template:w.template},...w.content!==void 0&&{content:w.content}},W);break}case"update_landing_page":{let W=w.companyId,Q=n$("update_landing_page",w,{requireUpdate:!0});$=await A("PUT",`/api/v1/landing-pages/${w.landingPageId}`,Q,W);break}case"publish_landing_page":{let W=w.companyId,Q=n$("publish_landing_page",w,{requireUpdate:!1});$=await A("POST",`/api/v1/landing-pages/${w.landingPageId}/publish`,Q,W);break}case"unpublish_landing_page":{let W=w.companyId,Q=n$("unpublish_landing_page",w,{requireUpdate:!1});$=await A("POST",`/api/v1/landing-pages/${w.landingPageId}/unpublish`,Q,W);break}case"delete_landing_page":{let W=w.companyId;$=await A("DELETE",`/api/v1/landing-pages/${w.landingPageId}`,void 0,W);break}case"connect_landing_page_domain":{let W=w.companyId;$=await A("POST","/api/v1/landing-pages/domain",{domain:w.domain},W);break}case"update_landing_page_domain_settings":{let W=w.companyId,Q=fJ(w);$=await A("PUT","/api/v1/landing-pages/domain",Q,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function vz(b,w){let $;switch(b){case"list_products":{let W=w.companyId,Q=new URLSearchParams;if(typeof w.provider==="string"&&w.provider.trim())Q.set("provider",w.provider.trim());if(typeof w.search==="string"&&w.search.trim())Q.set("search",w.search.trim());let G=Q.size>0?`?${Q.toString()}`:"";$=await A("GET",`/api/v1/products${G}`,void 0,W);break}case"upsert_products":{let W=w.companyId;if(!Array.isArray(w.products)||w.products.length===0)throw Error("`products` must be a non-empty array when calling `upsert_products`.");$=await A("POST","/api/v1/products",{products:w.products},W);break}case"delete_product":{let W=w.companyId,Q=Z("delete_product",w,"productId");$=await A("DELETE",`/api/v1/products/${encodeURIComponent(Q)}`,void 0,W);break}case"attach_product_file":{let W=w.companyId,Q=Z("attach_product_file",w,"productId"),G=P(w,"url"),D=P(w,"filePath");if(G===void 0===(D===void 0))throw Error("Provide either `url` or `filePath` (not both) when calling `attach_product_file`.");let X;if(D!==void 0){let Y=await lJ(D,W);X={url:Y.url,source:"upload",fileName:P(w,"fileName")??Y.fileName,fileSizeBytes:Y.fileSizeBytes,mimeType:Y.mimeType}}else{X={url:G};let Y=P(w,"fileName");if(Y)X.fileName=Y}$=await A("PUT",`/api/v1/products/${encodeURIComponent(Q)}/delivery`,X,W);break}case"remove_product_file":{let W=w.companyId,Q=Z("remove_product_file",w,"productId");$=await A("DELETE",`/api/v1/products/${encodeURIComponent(Q)}/delivery`,void 0,W);break}case"sync_products":{let W=w.companyId;$=await A("POST","/api/v1/products/sync",void 0,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}var kz=80;function RM(b){let w=b.trim().replace(/\s+/g," ");if(w.length<=kz)return w;return`${w.slice(0,kz-3).trimEnd()}...`}async function _W(b,w){let $;switch(b){case"generate_sequence":{let W=Z("generate_sequence",w,"goal"),Q=typeof w.name==="string"&&w.name.trim().length>0?w.name.trim():void 0,D=(await _W("create_sequence",{...w,goal:W,name:Q??RM(W),trigger:"contact_added",durationDays:w.durationDays??14})).result;return{handled:!0,result:typeof D==="object"&&D!==null?{...D,deprecated:!0,deprecationMessage:"generate_sequence is deprecated. Use create_sequence for new integrations."}:D}}case"list_sequences":{let W=w.companyId;$=await A("GET","/api/v1/sequences",void 0,W);break}case"get_sequence":{let W=w.companyId;$=await A("GET",`/api/v1/sequences/${w.sequenceId}`,void 0,W);break}case"create_sequence":{let W=w.companyId;if(w.fromEmail!==void 0&&w.senderProfileId!==void 0)throw Error("Provide either `fromEmail` or `senderProfileId` when calling `create_sequence`, not both.");if(w.replyTo!==void 0&&w.replyProfileId!==void 0)throw Error("Provide either `replyTo` or `replyProfileId` when calling `create_sequence`, not both.");if(w.fromName!==void 0&&w.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `create_sequence`.");if(w.replyToName!==void 0&&w.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `create_sequence`.");let Q=Array.isArray(w.steps)&&w.steps.length>0,G=await A("POST","/api/v1/sequences",w,W);if(!G.success){$=G;break}let D=G.sequence.id;if(Q){let z=await A("GET",`/api/v1/sequences/${D}`,void 0,W);if(z.success)$={...G,success:!0,sequence:z.sequence,message:`Sequence "${z.sequence.name}" created with explicit steps. Review it before enabling.${G.eventTrackingCode?" Add the custom event feed using eventTrackingCode and eventTracking before enabling.":""}`};else $=z;break}let X=7,Y=0,H="pending";while(H!=="complete"&&Y<X){let z=await A("GET",`/api/v1/sequences/${D}`,void 0,W);if(z.success)H=z.sequence.enrichmentStatus;if(Y++,H!=="complete"&&Y<X)await new Promise((O)=>setTimeout(O,20000))}let J=await A("GET",`/api/v1/sequences/${D}`,void 0,W);if(J.success)$={...G,success:!0,sequence:J.sequence,message:J.sequence.enrichmentStatus==="complete"?`Sequence "${J.sequence.name}" created with ${J.sequence.emailCount} AI-generated emails. The sequence is ready to review and enable.${G.eventTrackingCode?" Add the custom event feed using eventTrackingCode and eventTracking before enabling.":""}`:`Sequence "${J.sequence.name}" created. Email enrichment is still in progress (${J.sequence.enrichedCount}/${J.sequence.emailCount} emails generated). You can check status with get_sequence.${G.eventTrackingCode?" Add the custom event feed using eventTrackingCode and eventTracking before enabling.":""}`};else $=J;break}case"update_sequence":{let W=w.companyId,Q=_J(w);$=await A("PUT",`/api/v1/sequences/${w.sequenceId}`,Q,W);break}case"update_sequence_node":{let W=w.companyId,Q=Z("update_sequence_node",w,"sequenceId"),G=RJ(w);$=await A("PUT",`/api/v1/sequences/${Q}`,G,W);break}case"update_sequence_nodes":{let W=w.companyId,Q=Z("update_sequence_nodes",w,"sequenceId"),G=vJ(w);$=await A("PUT",`/api/v1/sequences/${Q}`,G,W);break}case"edit_sequence_graph":{let W=w.companyId,Q=kJ(w);$=await A("PUT",`/api/v1/sequences/${w.sequenceId}`,Q,W);break}case"insert_sequence_step":{let W=w.companyId,Q=CJ(w);$=await A("PUT",`/api/v1/sequences/${w.sequenceId}`,Q,W);break}case"enable_sequence":{let W=w.companyId;$=await A("POST",`/api/v1/sequences/${w.sequenceId}/enable`,void 0,W);break}case"disable_sequence":{let W=w.companyId;$=await A("POST",`/api/v1/sequences/${w.sequenceId}/disable`,void 0,W);break}case"pause_sequence_enrollments":{let W=w.companyId;$=await A("POST",`/api/v1/sequences/${w.sequenceId}/pause-enrollments`,void 0,W);break}case"resume_sequence_enrollments":{let W=w.companyId;$=await A("POST",`/api/v1/sequences/${w.sequenceId}/resume-enrollments`,void 0,W);break}case"enroll_subscribers_in_sequence":{let W=w.companyId,Q=Z("enroll_subscribers_in_sequence",w,"sequenceId"),G=iJ(w);$=await A("POST",`/api/v1/sequences/${encodeURIComponent(Q)}/enroll`,G,W);break}case"cancel_sequence_enrollments":{let W=w.companyId,Q=uJ(w);$=await A("POST",`/api/v1/sequences/${w.sequenceId}/enrollments/cancel`,Q,W);break}case"delete_sequence":{let W=w.companyId;$=await A("DELETE",`/api/v1/sequences/${w.sequenceId}`,void 0,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function Cz(b,w){let $;switch(b){case"add_subscriber":{let W=w.companyId,Q=Aw("add_subscriber",w);$=await A("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,...w.status!==void 0&&{status:w.status},...w.optInMode!==void 0&&{optInMode:w.optInMode}},W);break}case"update_subscriber":{let W=w.companyId,Q=Aw("update_subscriber",w),G=await Y0(Q,W),D=Array.isArray(G.subscriber.tags)?G.subscriber.tags.filter((z)=>typeof z==="string"):[],X=Array.isArray(w.addTags)?w.addTags.filter((z)=>typeof z==="string"&&z.trim()!=="").map(MW):[],Y=new Set(Array.isArray(w.removeTags)?w.removeTags.filter((z)=>typeof z==="string"&&z.trim()!=="").map(MW):[]),H=D.filter((z)=>!Y.has(z));for(let z of X)if(!H.includes(z))H.push(z);let J={};if(Q.email&&Q.externalId)J.externalId=Q.externalId;if(w.firstName!==void 0)J.firstName=w.firstName;if(w.lastName!==void 0)J.lastName=w.lastName;if(y(w.attributes))J.customAttributes={...y(G.subscriber.customAttributes)?G.subscriber.customAttributes:{},...w.attributes};if(w.addTags||w.removeTags)J.tags=H;$=await A("PATCH",m$(Q),J,W);break}case"remove_subscriber":{let W=w.companyId,Q=Aw("remove_subscriber",w),G=m$(Q);if(w.hardDelete===!0)$=await A("DELETE",G,void 0,W);else $=await A("PATCH",G,{status:"unsubscribed"},W);break}case"get_subscriber":{let W=w.companyId,Q=Aw("get_subscriber",w);$=await Y0(Q,W,{includeMachineEngagement:w.includeMachineEngagement===!0});break}case"list_subscriber_notes":{let W=w.companyId,Q=Aw("list_subscriber_notes",w);$=await A("GET",IW(Q),void 0,W);break}case"add_subscriber_note":{let W=w.companyId,Q=Aw("add_subscriber_note",w),G=typeof w.body==="string"?w.body.trim():void 0;if(!G)throw Error("`body` is required when calling `add_subscriber_note`.");if(G.length>5000)throw Error("`body` must be 5000 characters or fewer when calling `add_subscriber_note`.");$=await A("POST",IW(Q),{body:G},W);break}case"delete_subscriber_note":{let W=w.companyId,Q=typeof w.noteId==="string"?w.noteId.trim():"";if(!Q)throw Error("`noteId` is required when calling `delete_subscriber_note`.");$=await A("DELETE",`/api/v1/subscribers/notes/${encodeURIComponent(Q)}`,void 0,W);break}case"search_subscribers":{let W=w.companyId;$=await mJ(w,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function uz(b,w){if(b!=="get_recipient_suppression"&&b!=="remove_recipient_suppression")return{handled:!1,result:void 0};let $=P(w,"companyId"),W=Z(b,w,"email"),Q=P(w,"region"),G=new URLSearchParams;if(Q)G.set("region",Q);let D=`/api/v1/suppressions/${encodeURIComponent(W)}${G.size>0?`?${G}`:""}`;return{handled:!0,result:await A(b==="get_recipient_suppression"?"GET":"DELETE",D,void 0,$)}}async function xz(b,w){let $;switch(b){case"list_team_members":{let W=w.companyId;$=await A("GET","/api/v1/team",void 0,W);break}case"invite_team_member":{let W=w.companyId,Q=Z("invite_team_member",w,"email"),G=H0("invite_team_member",w,"role",["admin","viewer","restricted"]);if(w.canManageBilling!==void 0&&typeof w.canManageBilling!=="boolean")throw Error("`canManageBilling` must be a boolean when calling `invite_team_member`.");$=await A("POST","/api/v1/team/invitations",{email:Q,role:G,...w.canManageBilling!==void 0&&{canManageBilling:w.canManageBilling}},W);break}case"cancel_team_invitation":{let W=w.companyId,Q=Z("cancel_team_invitation",w,"invitationId");$=await A("DELETE",`/api/v1/team/invitations/${encodeURIComponent(Q)}`,void 0,W);break}case"list_conversations":{let W=w.companyId,Q=new URLSearchParams,G=Ub("list_conversations",w,"status",["open","closed","all"]);if(G)Q.set("status",G);let D=P(w,"search");if(D)Q.set("search",D);if(w.unread!==void 0){if(typeof w.unread!=="boolean")throw Error("`unread` must be a boolean when calling `list_conversations`.");if(w.unread)Q.set("unread","true")}if(w.page!==void 0){if(typeof w.page!=="number"||!Number.isInteger(w.page)||w.page<1)throw Error("`page` must be a positive integer when calling `list_conversations`.");Q.set("page",String(w.page))}let X=zw("list_conversations",w,"limit",1,100);if(X!==void 0)Q.set("limit",String(X));$=await A("GET",`/api/v1/conversations${Q.size>0?`?${Q}`:""}`,void 0,W);break}case"get_conversation":{let W=w.companyId,Q=Z("get_conversation",w,"conversationId");$=await A("GET",`/api/v1/conversations/${encodeURIComponent(Q)}`,void 0,W);break}case"reply_to_conversation":{let W=w.companyId,Q=Z("reply_to_conversation",w,"conversationId"),G=Ub("reply_to_conversation",w,"type",["outbound","note"])??"outbound",D=P(w,"subject"),X=P(w,"bodyText"),Y=P(w,"bodyHtml");if(G==="outbound"&&X===void 0&&Y===void 0)throw Error("Provide `bodyText` or `bodyHtml` when calling `reply_to_conversation` with an outbound message.");$=await A("POST",`/api/v1/conversations/${encodeURIComponent(Q)}/messages`,{type:G,...D!==void 0&&{subject:D},...X!==void 0&&{bodyText:X},...Y!==void 0&&{bodyHtml:Y}},W);break}case"update_conversation_status":{let W=w.companyId,Q=Z("update_conversation_status",w,"conversationId"),G=H0("update_conversation_status",w,"status",["open","closed"]);$=await A("POST",`/api/v1/conversations/${encodeURIComponent(Q)}/status`,{status:G},W);break}case"mark_conversation_read":{let W=w.companyId,Q=Z("mark_conversation_read",w,"conversationId");$=await A("POST",`/api/v1/conversations/${encodeURIComponent(Q)}/read`,void 0,W);break}case"list_webhooks":{let W=w.companyId;$=await A("GET","/api/v1/webhooks",void 0,W);break}case"create_webhook":{let W=w.companyId,Q=Z("create_webhook",w,"name"),G=Z("create_webhook",w,"url"),D=jW("create_webhook",w);$=await A("POST","/api/v1/webhooks",{name:Q,url:G,...D!==void 0&&{events:D}},W);break}case"update_webhook":{let W=w.companyId,Q=Z("update_webhook",w,"webhookId"),G=P(w,"name"),D=P(w,"url"),X=jW("update_webhook",w),Y=Ub("update_webhook",w,"status",["enabled","disabled"]);if(G===void 0&&D===void 0&&X===void 0&&Y===void 0)throw Error("Provide at least one of `name`, `url`, `events`, or `status` when calling `update_webhook`.");$=await A("PATCH",`/api/v1/webhooks/${encodeURIComponent(Q)}`,{...G!==void 0&&{name:G},...D!==void 0&&{url:D},...X!==void 0&&{events:X},...Y!==void 0&&{status:Y}},W);break}case"delete_webhook":{let W=w.companyId,Q=Z("delete_webhook",w,"webhookId");$=await A("DELETE",`/api/v1/webhooks/${encodeURIComponent(Q)}`,void 0,W);break}case"test_webhook":{let W=w.companyId,Q=Z("test_webhook",w,"webhookId");$=await A("POST",`/api/v1/webhooks/${encodeURIComponent(Q)}/test`,void 0,W);break}case"list_webhook_deliveries":{let W=w.companyId,Q=Z("list_webhook_deliveries",w,"webhookId"),G=zw("list_webhook_deliveries",w,"limit",1,100),D=new URLSearchParams;if(G!==void 0)D.set("limit",String(G));$=await A("GET",`/api/v1/webhooks/${encodeURIComponent(Q)}/deliveries${D.size>0?`?${D}`:""}`,void 0,W);break}case"replay_webhook_delivery":{let W=w.companyId,Q=Z("replay_webhook_delivery",w,"webhookId"),G=Z("replay_webhook_delivery",w,"deliveryId");$=await A("POST",`/api/v1/webhooks/${encodeURIComponent(Q)}/deliveries/${encodeURIComponent(G)}/replay`,void 0,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}var yz=[jz,Cz,uz,vz,Tz,Ez,_z,Rz,Sz,_W,Nz,xz,Vz];var hz=Zz.map(aJ).map(MJ);async function fz(b,w){try{let $,W=!1;for(let G of yz){let D=await G(b,w);if(D.handled){$=D.result,W=!0;break}}if(!W)throw Error(`Unknown tool: ${b}`);let Q=nJ($);if(Q)throw Q;return $=await dJ(b,w,$),{structuredContent:bz($),content:[{type:"text",text:JSON.stringify($,null,2)}]}}catch($){return{isError:!0,content:[{type:"text",text:Ow($)}]}}}async function cz(b,w,$){let W=w.getRequestContext?.(b)??{};try{return await r$(W,$)}finally{await w.onRequestContextUpdated?.(W,b)}}function SW(b={}){let w=new YW({name:"sequenzy",version:LJ.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(t6,async()=>{return{tools:hz}}),w.setRequestHandler(C1,async($,W)=>{let{name:Q,arguments:G}=$.params;return cz(W,b,()=>fz(Q,G??{}))}),w.setRequestHandler(g6,async()=>{return{resources:PJ}}),w.setRequestHandler(i6,async($,W)=>{let{uri:Q}=$.params;return cz(W,b,()=>FJ(Q))}),w}import gz from"node:process";class RW{append(b){this._buffer=this._buffer?Buffer.concat([this._buffer,b]):b}readMessage(){if(!this._buffer)return null;let b=this._buffer.indexOf(`
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 Wz=[{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 Qz=[{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:lb}}},{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:lb},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:lb},required:["sequenceId"]}},{name:"list_campaign_events",description:"List paginated raw email events for a campaign. Defaults to deliveries; use eventType or eventTypes to include opens, clicks, bounces, complaints, unsubscribes, sends, or delivery delays.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"},eventType:{type:"string",description:"Optional single event type. Supported values: send, delivery, bounce, complaint, open, click, unsubscribe, delivery_delay. Defaults to delivery."},eventTypes:{type:"array",description:"Optional event types to include. Supported values: send, delivery, bounce, complaint, open, click, unsubscribe, delivery_delay. Defaults to delivery.",items:{type:"string"}},period:{type:"string",description:"Optional sliding time window: 1h, 24h, 7d, 30d, or 90d. Ignored when start/end are provided."},start:{type:"string",description:"Optional ISO 8601 start time. Must be used with end; max range is 90 days."},end:{type:"string",description:"Optional ISO 8601 end time. Must be used with start; max range is 90 days."},page:{type:"number",description:"Page number, starting at 1. Defaults to 1."},limit:{type:"number",description:"Events per page. Defaults to 100; maximum 500."},includeMachineEngagement:lb},required:["campaignId"]}},{name:"list_sequence_events",description:"List paginated raw email events for every email step in a sequence. Defaults to deliveries; use eventType or eventTypes to include opens, clicks, bounces, complaints, unsubscribes, sends, or delivery delays.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"},eventType:{type:"string",description:"Optional single event type. Supported values: send, delivery, bounce, complaint, open, click, unsubscribe, delivery_delay. Defaults to delivery."},eventTypes:{type:"array",description:"Optional event types to include. Supported values: send, delivery, bounce, complaint, open, click, unsubscribe, delivery_delay. Defaults to delivery.",items:{type:"string"}},period:{type:"string",description:"Optional sliding time window: 1h, 24h, 7d, 30d, or 90d. Ignored when start/end are provided."},start:{type:"string",description:"Optional ISO 8601 start time. Must be used with end; max range is 90 days."},end:{type:"string",description:"Optional ISO 8601 end time. Must be used with start; max range is 90 days."},page:{type:"number",description:"Page number, starting at 1. Defaults to 1."},limit:{type:"number",description:"Events per page. Defaults to 100; maximum 500."},includeMachineEngagement:lb},required:["sequenceId"]}},{name:"get_subscriber_activity",description:"Get recent activity, email stats, and current sequence enrollments for a subscriber",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},includeMachineEngagement:lb},required:[]}}];var Gz=[{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 Dz=[{name:"list_campaigns",description:"List all campaigns",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list campaigns for. If not provided, uses the currently selected company."},status:{type:"string",description:"Filter by status (draft, scheduled, sent)"},label:{type:"string",description:"Optional label name filter. Only campaigns assigned this label are returned."}}}},{name:"get_campaign",description:"Get campaign details and stats",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"}},required:["campaignId"]}},{name:"get_email_send",description:"Get an email delivery by emailSendId, including queued and test sends, delivery status, provider failure reason, stored HTML, and the ClickHouse event timeline. Queue jobs are internal execution details and are not exposed.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},emailSendId:{type:"string",description:"Durable email delivery ID to inspect."}},required:["emailSendId"]}},{name:"create_campaign",description:"Create a new campaign. Omit all content fields to create an empty draft. For net-new natural-language content use `prompt`; do not author HTML or blocks. `blocks` are finished caller-supplied Sequenzy content and `html` is preserved/imported markup. Defaults to draft; status 'sent' only archives an already-sent campaign.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the campaign in. If not provided, uses the currently selected company."},name:{type:"string",description:"Campaign name"},subject:{type:"string",description:"Email subject line. Optional when `prompt` is provided because the generated subject will be used."},previewText:{type:["string","null"],description:"Email preview text. Optional when `prompt` is provided because the generated preview text will be used."},trackingCode:{type:"string",description:"Optional campaign tracking code for UTM templates. Use only when explicitly requested."},status:{type:"string",description:"Initial status: draft or sent. Defaults to draft. Use sent only for imported/already-sent campaigns; it does not send email or create delivery history."},sentAt:{type:"string",description:"ISO date-time for an imported/already-sent campaign. Only valid when status is sent; defaults to now if omitted."},html:{type:"string",description:"Email HTML content. Mutually exclusive with `blocks`. Use this for imported provider campaigns; Sequenzy stores it as one raw HTML block to preserve the design."},blocks:{type:"array",description:Hw,items:{type:"object"}},prompt:{type:"string",description:"Generate campaign blocks from a prompt. Generated blocks include the company's logo and footer, and the created campaign inherits the company brand font. Mutually exclusive with `html`, `blocks`, and `templateId`."},style:{type:"string",description:"Prompt generation style: minimal, branded, promotional. Only used with `prompt`."},tone:{type:"string",description:"Prompt generation tone: professional, casual, friendly. Only used with `prompt`."},templateId:{type:"string",description:"Use a template instead of html"},segmentId:{type:"string",description:"Target segment ID"},fromEmail:{type:"string",description:"From address for this campaign. Its domain must be configured and verified; a sender profile is created when needed."},fromName:{type:"string",description:"Display name for a newly created sender profile. Requires fromEmail."},senderProfileId:{type:"string",description:"Existing sender profile ID. Mutually exclusive with fromEmail."},replyTo:{type:"string",description:"Reply-To address for this campaign. A reply profile is created when needed."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo."},replyProfileId:{type:"string",description:"Existing reply profile ID. Mutually exclusive with replyTo."},campaignData:{type:"object",description:"Optional campaign-scoped JSON data for repeat blocks and personalization."},computedLists:{type:"array",description:"Optional computed list definitions derived from campaignData at send time.",items:{type:"object"}},labels:{type:"array",description:"Optional label names to assign. Missing labels are created automatically.",items:{type:"string"}}},required:["name"]}},{name:"update_campaign",description:"Update a draft campaign",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"},name:{type:"string",description:"Campaign name"},subject:{type:"string",description:"Email subject line"},trackingCode:{type:"string",description:"Optional campaign tracking code for UTM templates. Use only when explicitly requested. Send an empty string to clear it."},html:{type:"string",description:"Email HTML content. Mutually exclusive with `blocks`. Use this for imported provider campaigns; Sequenzy stores it as one raw HTML block to preserve the design."},blocks:{type:"array",description:Hw,items:{type:"object"}},replyTo:{type:"string",description:"Set reply-to using an existing reply profile email address for this company."},replyProfileId:{type:"string",description:"Set reply-to using a reply profile ID for this company."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo."},fromEmail:{type:"string",description:"Set this campaign's From address. Its domain must be configured and verified."},fromName:{type:"string",description:"Display name for a newly created sender profile. Requires fromEmail."},senderProfileId:{type:"string",description:"Set an existing sender profile. Mutually exclusive with fromEmail."},ccEmails:{type:["array","null"],description:"Addresses CC'd on every recipient's campaign email (max 10). Send an empty array or null to clear them; omit to leave unchanged.",items:{type:"string"},maxItems:10},bccEmails:{type:["array","null"],description:"Addresses BCC'd on every recipient's campaign email (max 10). Send an empty array or null to clear them; omit to leave unchanged.",items:{type:"string"},maxItems:10},campaignData:{type:"object",description:"Set campaign-scoped JSON data for repeat blocks and personalization."},computedLists:{type:"array",description:"Set computed list definitions derived from campaignData at send time.",items:{type:"object"}},labels:{type:"array",description:"Replacement label names. Send an empty array to clear labels. Missing labels are created automatically.",items:{type:"string"}}},required:["campaignId"],additionalProperties:!1}},{name:"schedule_campaign",description:"Schedule a draft or already scheduled campaign. Returns dashboard edit and preview URLs.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"},scheduledAt:{type:"string",description:"Future ISO 8601 timestamp for the send, for example 2026-06-01T14:00:00Z."},targetLists:{type:"object",description:"Optional campaign targeting object. Omit to use saved targeting or all active subscribers. Examples: {type:'all'}, {type:'lists', listIds:['list_123']}, {type:'segment', segmentId:'seg_123'}, {type:'filtered', filters:[...], filterJoinOperator:'and'}, or {type:'rules', include:[{type:'lists', listIds:['list_123']}], exclude:[{type:'segments', segmentIds:['seg_123']}]}. Rules audiences require at least one include rule.",additionalProperties:!0},sendTimeOptimization:{type:"boolean",description:"Whether to use send-time optimization."},spreadOverHours:{type:"number",description:"Spread delivery over an integer number of hours from 1 to 72. When set, spread delivery takes precedence over send-time optimization."},recurringInterval:{type:"string",enum:["weekly","monthly"],description:"Repeat this campaign on a cadence starting at scheduledAt. The campaign becomes a recurring template: each run is duplicated and sent automatically, re-evaluating audience membership every time. Omit for a one-shot send; scheduling again without it stops the recurrence."}},required:["campaignId","scheduledAt"],additionalProperties:!1}},{name:"send_test_email",description:"Queue a campaign test email to a single address. Returns a durable emailSendId; pass it to get_email_send for delivery status and failure details.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to test"},to:{type:"string",description:"Email address to send test to"}},required:["campaignId","to"]}},{name:"cancel_campaign",description:"Cancel a campaign. Stops scheduled and sending campaigns (also works for paused and approval-pending ones). Remaining emails will not be sent and the campaign cannot be restarted - this cannot be undone.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to cancel."}},required:["campaignId"]}},{name:"pause_campaign",description:"Pause a campaign that is currently sending. Only campaigns in sending status can be paused. Use resume_campaign to continue delivery later.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to pause."}},required:["campaignId"]}},{name:"resume_campaign",description:"Resume a paused campaign. Only campaigns in paused status can be resumed. Optionally spread the remaining delivery over a number of hours.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to resume."},spreadOverHours:{type:"number",description:"Spread the remaining delivery over an integer number of hours from 1 to 72."}},required:["campaignId"]}},{name:"delete_campaign",description:"Permanently delete a campaign. This cannot be undone. Sending, scheduled, or paused campaigns must be cancelled with cancel_campaign first.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to delete."}},required:["campaignId"]}},{name:"duplicate_campaign",description:"Duplicate a campaign as a new draft. mode 'campaign' (default) copies the campaign and its email, 'ab_test' also duplicates the campaign's A/B test with all variants, and 'variant' copies a single variant's content as the new campaign email (requires variantId).",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to duplicate."},mode:{type:"string",enum:["campaign","ab_test","variant"],description:"Duplication mode. Defaults to campaign."},variantId:{type:"string",description:"A/B test variant ID whose content becomes the new campaign email. Required when mode is variant."}},required:["campaignId"]}},{name:"resend_campaign_to_non_openers",description:"Create a draft that resends a sent campaign to everyone in the same audience who didn't open it. Copies the campaign email and reuses the original audience with a 'didn't open this campaign' rule added. Only available 6 hours after the campaign finishes sending. The draft must be scheduled or sent separately. Returns the new draft and an estimate of how many subscribers haven't opened the original.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"ID of the sent campaign to resend to non-openers."}},required:["campaignId"]}}];var Xz=[{name:"submit_feedback",description:"Send product feedback about Sequenzy itself to the Sequenzy team. IMPORTANT: call this tool whenever the user wanted to accomplish something and Sequenzy did not expose functionality for it - a missing tool or argument, an unsupported workflow, a confusing behavior, or a bug. Briefly tell the user you reported the gap. This feedback goes straight to the team and shapes what gets built next. Do not use it for questions about the user's own account or data, and never include secrets or API keys. Submitting feedback never changes account data.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},message:{type:"string",description:"The feedback itself. Be specific: what was needed, what was missing or wrong, and what you did instead (workaround, gave up, used the dashboard)."},category:{type:"string",enum:["missing_capability","bug","docs","ux","praise","other"],description:"Feedback category. Use missing_capability when the user wanted something these tools do not support (default: other)."},context:{type:"string",description:"Optional: what the user was trying to accomplish, in their words, plus any relevant tool names or arguments you tried."}},required:["message"]}}];var Yz=[{name:"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 Hz=[{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 Jz=[{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 zz=[{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:KJ},content:{type:"object",description:D0,additionalProperties:!0}},additionalProperties:!1}},{name:"update_landing_page",description:"Edit a landing page's name, slug, or full content. Provide at least one update field.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID."},name:{type:"string",description:"Landing page name."},slug:{type:"string",description:"Landing page URL slug. It will be normalized and made unique within the company."},content:{type:"object",description:D0,additionalProperties:!0}},required:["landingPageId"],additionalProperties:!1}},{name:"delete_landing_page",description:"Delete a landing page",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID."}},required:["landingPageId"],additionalProperties:!1}},{name:"publish_landing_page",description:"Publish a landing page. Optional name, slug, or content updates are saved before publishing.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID."},name:{type:"string",description:"Optional landing page name update."},slug:{type:"string",description:"Optional slug update before publishing."},content:{type:"object",description:D0,additionalProperties:!0}},required:["landingPageId"],additionalProperties:!1}},{name:"unpublish_landing_page",description:"Unpublish a landing page and return it to draft status. Optional name, slug, or content updates are saved first.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID."},name:{type:"string",description:"Optional landing page name update."},slug:{type:"string",description:"Optional slug update before unpublishing."},content:{type:"object",description:D0,additionalProperties:!0}},required:["landingPageId"],additionalProperties:!1}},{name:"connect_landing_page_domain",description:"Connect a custom domain for published landing pages. Returns the DNS target and verification records.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},domain:{type:"string",description:"Custom domain, for example pages.example.com."}},required:["domain"],additionalProperties:!1}},{name:"update_landing_page_domain_settings",description:"Update landing page domain settings. Provide domain to replace the custom domain, verify true to refresh verification, or both.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},domain:{type:"string",description:"Replacement custom domain."},verify:{type:"boolean",description:"Refresh domain verification after any domain update."}},additionalProperties:!1}}];var Az=[{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 Oz=[{name:"list_sequences",description:"List all email sequences (automations)",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list sequences for. If not provided, uses the currently selected company."}}}},{name:"get_sequence",description:"Get sequence details, editable step content, and graph topology. Each sequence.nodes item includes id, nodeType, current config, updatedAt, and updateHints with its editable/managed fields and ready-to-return expectedUpdatedAt token for update_sequence_node/update_sequence_nodes. The response also includes sequence.edges and graphRevision for safe edit_sequence_graph calls, plus sequence.emails with each email step's nodeId, linked emailId, subject, previewText, emailPreset (the per-email Style > Format for native blocks; null for 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')"},trigger:{type:"string",enum:["contact_added","tag_added","segment_entered","event_received","inactivity","frequency"],description:"Trigger type: 'contact_added' (when added to a list), 'tag_added' (when tag is applied), 'segment_entered' (when a contact newly enters a saved segment), 'event_received' (when custom event fires), 'inactivity' (when subscriber hasn't performed an event for X days), 'frequency' (when subscriber performs event X times in Y days)"},listId:{type:"string",description:"List ID to trigger on (for contact_added trigger). If not provided, triggers on any list."},tagName:{type:"string",description:"Tag name to trigger on (required for tag_added trigger)"},segmentId:{type:"string",description:"Segment ID to trigger on (required for segment_entered trigger). Use list_segments first to choose a saved segment."},eventName:{type:"string",description:"Event name to trigger on (required for event_received, inactivity, and frequency triggers)"},propertyFilters:{type:"array",description:"Optional event property filters for event_received triggers. The sequence only starts when the triggering event's properties match ALL filters. Use a dot-path into the event properties; use [] to match inside arrays. Examples: scope a purchase sequence to one product with { path: 'lineItems[].providerProductId', operator: 'equals', value: 'prod_123' } (ecommerce.order_placed) or { path: 'productIds', operator: 'equals', value: 'prod_123' } (saas.purchase); to match any of several products use { path: 'lineItems[].providerProductId', operator: 'one_of', value: ['prod_123', 'prod_456'] }. Max 10 filters.",items:{type:"object",properties:{path:{type:"string",description:"Dot-path into the event properties, e.g. 'lineItems[].providerProductId' or 'plan'."},operator:{type:"string",enum:["exists","not_exists","equals","not_equals","one_of","contains","greater_than","less_than"],description:"Comparison operator. one_of matches when the property equals any entry of the value array."},value:{type:["string","number","boolean","array"],items:{type:["string","number"]},maxItems:50,description:"Value to compare against. Required for every operator except exists/not_exists. For one_of, pass an array of strings or numbers (max 50 values); all other operators take a single value."}},required:["path","operator"]}},inactiveDays:{type:"number",description:"Number of days of inactivity (required for inactivity trigger, must be >= 1)"},inactivityBaseline:{type:"string",enum:["sequence_created_at","subscriber_created_at"],description:"When to start counting inactivity for subscribers who never had the event. Defaults to sequence_created_at."},minCount:{type:"number",description:"Minimum event count (required for frequency trigger, must be >= 1)"},timeWindowDays:{type:"number",description:"Time window in days for frequency trigger (required for frequency trigger, must be >= 1)"},emailCount:{type:"number",description:"Number of emails in the sequence (default: 5, max: 10)"},durationDays:{type:"number",description:"Total duration in days used to space AI-generated sequence emails. Only applies when using goal-based AI generation."},emailStyle:{type:"string",enum:["visual","plain"],description:"Style for AI-generated emails: 'visual' (designed, with heroes/imagery/rich sections) or 'plain' (personal, text-first notes with a single button). Only applies to goal-based AI generation. Defaults to the company's saved preference when omitted."},goal:{type:"string",description:"What this sequence should accomplish for AI generation. Be specific to the app's actual features and user journey. Avoid generic goals that don't match the app's business model."},enrollmentMode:{type:"string",enum:["unlimited","one_time","matching_field"],description:"Sequence re-entry mode. Use 'matching_field' only for event_received triggers when duplicate active runs should be blocked per event field value."},enrollmentFieldPath:{type:"string",description:"Scalar dot-path event property used by enrollmentMode='matching_field', such as 'order.id' or 'product.providerVariantId'. Array traversal with [] is not supported; use propertyFilters for array matching. Leave omitted for Shopify back-in-stock/replenishment product-variant defaults."},sendingWindow:C$,stopCondition:{type:"object",description:"Optional explicit auto-stop condition. Use { type: 'has_tag', value: 'customer' } to end the sequence when a subscriber gets a tag, { type: 'does_not_have_tag', value: 'trial' } when a tag is removed, { type: 'entered_segment', value: 'segment_123' } when they enter a segment, { type: 'field_changed', value: 'plan' } when a subscriber field changes, { type: 'removed_from_list', value: 'list_123' } when they leave a list, { type: 'event_received', value: 'onboarding.completed' } when an event is tracked, or { type: 'none', value: null } for no auto-stop.",properties:{type:{type:"string",enum:["none","has_tag","does_not_have_tag","added_to_list","removed_from_list","entered_segment","field_changed","event_received"],description:"Stop condition type."},value:{type:["string","null"],description:"Tag name, list ID, segment ID, field path, or event name for the stop condition. Use null or omit for type 'none'."}},required:["type"]},steps:{type:"array",description:"Explicit sequence steps. Omit type for email steps, use type: 'sms' for SMS, type: 'create_discount' for a dynamic discount, or type: 'update_subscriber' with nodeType: 'action_update_attributes' and config to copy trigger-event values such as {{event.plan}} into subscriber data.",items:{type:"object",properties:{type:{type:"string",enum:["email","sms","create_discount","discount","update_subscriber"],description:"Step type. Omit or use 'email' for email content. Use 'sms' to send a text message, 'create_discount' to generate a code, or 'update_subscriber' to copy trigger data into the subscriber."},nodeType:{type:"string",enum:["action_email","action_sms","action_create_discount","action_update_attributes"],description:"Internal step type. Use action_update_attributes with config for Update Subscriber steps."},config:X0,subject:{type:"string",description:"Email subject. Required for email steps."},previewText:{type:"string",description:"Email preview text."},blocks:{type:"array",description:W1,items:{type:"object"}},html:{type:"string",description:"HTML content for email steps. Stored as one raw HTML block. Use this for imported provider HTML."},text:{type:"string",description:"SMS steps only: plain-text message body. Merge tags like {{FIRST_NAME}} work. Do not include opt-out text or a brand prefix - the platform adds those automatically."},imageUrls:{type:"array",items:{type:"string"},description:"SMS steps only: up to 2 publicly reachable image URLs sent as MMS media."},ineligibleAction:{type:"string",enum:["skip","exit"],description:"SMS steps only: what happens when the contact can't receive SMS (no phone, not opted in, unsupported country). Default 'skip' continues the sequence."},delay:G1,delayMs:{type:"number",description:"Delay before this step in milliseconds. Prefer delay for readability; use delayMs when importing provider waits."},waitUntil:Q1,name:{type:"string",description:"Email template name for email steps."},discount:{type:"object",description:"Discount configuration for create_discount steps. Prefer this nested shape for new integrations; legacy top-level discount fields are still accepted.",properties:{label:{type:"string",description:"Builder label for the discount step."},provider:{type:"string",enum:["stripe","shopify"],description:"Discount provider. Use 'stripe' to dynamically create a Stripe coupon plus promotion code, or 'shopify' to dynamically create a Shopify Admin discount code. Defaults to 'stripe' when omitted."},discountType:{type:"string",enum:["percent","amount"],description:"Discount type."},percentOff:{type:"number",description:"Percent discount from 1 to 100. Required when discountType is percent."},amountOff:{type:"number",description:"Fixed amount discount in the smallest currency unit, for example 500 for $5. Required when discountType is amount."},currency:{type:"string",description:"ISO currency for amount discounts. Defaults to usd."},duration:{type:"string",enum:["once","forever","repeating"],description:"Discount duration. Defaults to once."},durationInMonths:{type:"number",description:"Required for repeating discounts."},appliesToAllPlans:{type:"boolean",description:"Whether the discount applies to all plans. Defaults to true."},planIds:{type:"array",description:"Provider product IDs when appliesToAllPlans is false. Stripe uses IDs like prod_abc123; Shopify accepts numeric product IDs or gid://shopify/Product/... IDs.",items:{type:"string"}},codePrefix:{type:"string",description:"Optional prefix for generated dynamic codes. The final code also includes a subscriber/token suffix."},maxRedemptions:{type:"number",description:"Maximum redemptions for each generated code. Use 1 for subscriber-specific codes."},lockToSubscriber:{type:"boolean",description:"Stripe-only. Restrict each generated promotion code to the matched subscriber's Stripe customer."},expiresAt:{type:"string",description:"Optional future expiration date or ISO timestamp."},expiresInHours:{type:"number",description:"Optional relative expiration in hours, resolved when each subscriber's code is created (e.g., 48 for a 48-hour window per subscriber). Takes precedence over expiresAt."},name:{type:"string",description:"Optional display name for each dynamically generated provider discount."}}},label:{type:"string",description:"Legacy top-level discount label. Prefer discount.label."},provider:{type:"string",enum:["stripe","shopify"],description:"Legacy top-level discount provider. Prefer discount.provider. Supports 'stripe' and 'shopify'."},discountType:{type:"string",enum:["percent","amount"],description:"Legacy top-level discount type. Prefer discount.discountType."},percentOff:{type:"number",description:"Percent discount from 1 to 100. Required when discountType is percent."},amountOff:{type:"number",description:"Fixed amount discount in the smallest currency unit, for example 500 for $5. Required when discountType is amount."},currency:{type:"string",description:"ISO currency for amount discounts. Defaults to usd."},duration:{type:"string",enum:["once","forever","repeating"],description:"Discount duration. Defaults to once."},durationInMonths:{type:"number",description:"Required for repeating discounts."},appliesToAllPlans:{type:"boolean",description:"Whether the discount applies to all plans. Defaults to true."},planIds:{type:"array",description:"Provider product IDs when appliesToAllPlans is false. Stripe uses IDs like prod_abc123; Shopify accepts numeric product IDs or gid://shopify/Product/... IDs.",items:{type:"string"}},codePrefix:{type:"string",description:"Optional prefix for generated dynamic codes. The final code also includes a subscriber/token suffix."},maxRedemptions:{type:"number",description:"Maximum redemptions for each generated code. Use 1 for subscriber-specific codes."},lockToSubscriber:{type:"boolean",description:"Legacy top-level Stripe-only flag. Prefer discount.lockToSubscriber."},expiresAt:{type:"string",description:"Optional future expiration date or ISO timestamp."},expiresInHours:{type:"number",description:"Optional relative expiration in hours, resolved when each subscriber's code is created (e.g., 48 for a 48-hour window per subscriber). Takes precedence over expiresAt."}}}}},required:["name","trigger"]}}];var qz=[{name:"update_sequence",description:"Update an existing sequence. To target a specific existing step, use IDs returned by get_sequence. The emails/steps arrays edit email steps, smsSteps edits SMS steps, and subscriberUpdateSteps replaces the config of action_update_attributes steps. To insert new linear steps, use insertSteps with an afterNodeId from get_sequence; omit afterNodeId only to append to an unambiguous linear tail. For active sequences, structural changes such as insertSteps or branch require confirmStructuralChange:true after the user confirms the live-flow impact.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"},name:{type:"string",description:"Sequence name"},fromEmail:{type:"string",description:"Set the From address for all emails in this sequence. Its domain must be configured and verified."},fromName:{type:"string",description:"Display name for a newly created sender profile. Requires fromEmail."},senderProfileId:{type:"string",description:"Set an existing sender profile. Mutually exclusive with fromEmail."},replyTo:{type:"string",description:"Set the Reply-To address for all emails in this sequence."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo."},replyProfileId:{type:"string",description:"Set an existing reply profile. Mutually exclusive with replyTo."},enrollmentPaused:{type:"boolean",description:"Set true to stop new enrollments for an active sequence while current recipients continue. Set false to resume new enrollments. The sequence must already be active."},confirmStructuralChange:{type:"boolean",description:"Set true only after the user explicitly confirms a structural edit to an active sequence. Required for insertSteps or branch when the sequence is active; not needed for content-only email edits."},enrollmentMode:{type:"string",enum:["unlimited","one_time","matching_field"],description:"Updated sequence re-entry mode. 'matching_field' is only valid for event-based sequence triggers."},enrollmentFieldPath:{type:"string",description:"Scalar dot-path event property used by enrollmentMode='matching_field', such as 'order.id' or 'product.providerVariantId'. Array traversal with [] is not supported; use propertyFilters for array matching. Omit to leave unchanged. Use clearEnrollmentFieldPath to clear it."},clearEnrollmentFieldPath:{type:"boolean",description:"Set true to clear enrollmentFieldPath without sending a nullable schema value."},sendingWindow:C$,clearSendingWindow:{type:"boolean",description:"Set true to remove the sequence sending window. Do not provide this together with sendingWindow."},bccEmails:{type:"array",items:{type:"string"},description:"Email addresses that receive a blind copy of every email this sequence sends, such as a customer support inbox (max 10). Omit to leave unchanged. Use clearBccEmails to remove them."},clearBccEmails:{type:"boolean",description:"Set true to remove the sequence BCC addresses. Do not provide this together with bccEmails."},stopCondition:{type:"object",description:"Update the sequence auto-stop condition. Example: { type: 'has_tag', value: 'customer' } ends the sequence when the subscriber has that tag. Use { type: 'entered_segment', value: 'segment_123' } to stop when they enter a segment, { type: 'field_changed', value: 'plan' } to stop when a subscriber field changes, { type: 'removed_from_list', value: 'list_123' } to stop when they leave a list, or { type: 'none', value: null } to clear it.",properties:{type:{type:"string",enum:["none","has_tag","does_not_have_tag","added_to_list","removed_from_list","entered_segment","field_changed","event_received"]},value:{type:["string","null"],description:"Tag name, list ID, segment ID, field path, or event name for the stop condition."}},required:["type"]},branch:{type:"object",description:"Insert an if/else branch into an existing sequence. The branch is inserted after afterNodeId and creates an if path plus an else fallback path. Use get_sequence first to choose afterNodeId. Each branch condition should include steps, and elseSteps is required unless allowEmptyPaths is true. Conditions support tag presence/absence, lists, saved segments, events, clicked links, and field comparisons. Use activityScope for event_received and link_clicked checks.",properties:{afterNodeId:{type:"string",description:"Existing node ID to insert the branch after. Use a nodeId from get_sequence.sequence.nodes or get_sequence.sequence.emails."},label:{type:"string",description:"Optional branch node label."},branches:{type:"array",description:"Conditional branches evaluated in order. An else fallback is created automatically.",items:{type:"object",properties:{id:{type:"string",description:"Optional stable branch ID. Defaults to branch-0, branch-1, etc."},label:{type:"string",description:"Display label, e.g. 'If has customer tag'."},conditionType:{type:"string",enum:["has_tag","does_not_have_tag","in_list","in_segment","event_received","link_clicked","field_equals","field_contains","field_greater_than","field_less_than","has_phone","sms_subscribed"],description:"Condition type for this branch. has_phone (contact has a phone number) and sms_subscribed (contact opted in to SMS marketing) need no extra fields."},tagName:{type:"string",description:"Tag name for has_tag and does_not_have_tag conditions. This can be used instead of tagId."},tagId:{type:"string",description:"Tag ID or tag name for has_tag and does_not_have_tag conditions."},listId:{type:"string",description:"List ID for in_list conditions."},segmentId:{type:"string",description:"Segment ID for in_segment conditions."},segmentName:{type:"string",description:"Optional display name for in_segment conditions."},eventName:{type:"string",description:"Event name for event_received conditions, such as project.invite.accepted."},linkUrl:{type:"string",description:"Optional URL substring for link_clicked conditions. Omit to match any clicked link."},activityScope:{type:"string",enum:["ever","this_sequence","previous_email"],description:"Scope for event_received and link_clicked conditions. Omit to check ever."},fieldName:{type:"string",description:"Subscriber attribute name for field conditions."},fieldValue:{type:"string",description:"Comparison value for field conditions."},steps:{type:"array",description:"Steps to create inside this branch path. Required by default so the branch is not an empty placeholder.",items:g$}},required:["conditionType"]}},elseSteps:{type:"array",description:"Steps to create inside the else fallback path. Required by default so the else arm is usable.",items:g$},allowEmptyPaths:{type:"boolean",description:"Set true only when intentionally creating empty UI placeholders. Normal API/MCP use should omit this and provide branch steps plus elseSteps."}},required:["afterNodeId","branches"]},insertSteps:{type:"object",description:"Insert one or more new linear steps into an existing sequence. Use get_sequence first, then pass afterNodeId to insert after a specific node. If afterNodeId is omitted, the steps are appended only when the sequence has exactly one linear tail. Inserted email steps require subject plus blocks or html.",properties:{afterNodeId:{type:"string",description:"Existing node ID to insert after. Use a nodeId from get_sequence.sequence.nodes or get_sequence.sequence.emails. Omit only to append to an unambiguous linear tail."},steps:{type:"array",description:"New steps to insert. Supports emails, delays, create_discount actions, webhooks, and other supported sequence path node types.",items:g$}},required:["steps"]},emails:{type:"array",description:"Updated existing sequence emails. If you omit emailId/nodeId, items are matched by existing step order. This field does not create new steps; use insertSteps for insertion and include delay on inserted email steps when a timer is needed.",items:{type:"object",properties:{emailId:{type:"string",description:"Optional target linked email template ID for a step. Use the emailId returned in get_sequence.sequence.emails."},nodeId:{type:"string",description:"Optional target action_email node ID for a step. Use the nodeId returned in get_sequence.sequence.emails."},name:{type:"string",description:"Updated step/template name"},subject:{type:"string",description:"Updated email subject"},previewText:{type:"string",description:"Updated preview text"},html:{type:"string",description:"Updated HTML content. Stored as one raw HTML block. Use this to preserve imported provider HTML."},htmlContent:{type:"string",description:"Alias for html. Stored as one raw HTML block. Use this when updating imported provider HTML for a step."},emailPreset:{type:"string",enum:["branded","minimal"],description:"Per-email Style > Format for native Sequenzy blocks. Minimal removes the company logo and uses the simple footer; branded restores the branded chrome. Does not change the company default. Not supported for raw HTML emails and must not be combined with html/htmlContent."},blocks:{type:"array",description:Jw,items:{type:"object"}},...KW}}},steps:{type:"array",description:"Alias for emails. Supports the same fields and matching rules, and only edits existing email steps. Use insertSteps to create new steps.",items:{type:"object",properties:{emailId:{type:"string",description:"Optional target linked email template ID for a step. Use the emailId returned in get_sequence.sequence.emails."},nodeId:{type:"string",description:"Optional target action_email node ID for a step. Use the nodeId returned in get_sequence.sequence.emails."},name:{type:"string",description:"Updated step/template name"},subject:{type:"string",description:"Updated email subject"},previewText:{type:"string",description:"Updated preview text"},html:{type:"string",description:"Updated HTML content. Stored as one raw HTML block. Use this to preserve imported provider HTML."},htmlContent:{type:"string",description:"Alias for html. Stored as one raw HTML block. Use this when updating HTML content for a step."},emailPreset:{type:"string",enum:["branded","minimal"],description:"Per-email Style > Format for native Sequenzy blocks. Minimal removes the company logo and uses the simple footer; branded restores the branded chrome. Does not change the company default. Not supported for raw HTML emails and must not be combined with html/htmlContent."},blocks:{type:"array",description:Jw,items:{type:"object"}},...KW}}},smsSteps:{type:"array",description:"Content updates for existing SMS steps, targeted by nodeId (an action_sms node from get_sequence.sequence.nodes). Content-only edits - use insertSteps to create new SMS steps.",items:{type:"object",properties:{nodeId:{type:"string",description:"Target action_sms node ID. Required."},text:{type:"string",description:"Replacement plain-text message body. Merge tags like {{FIRST_NAME}} work. Provide text or blocks, not both."},blocks:{type:"array",items:{type:"object"},description:"Replacement SMS content blocks (text + image subset)."},imageUrls:{type:"array",items:{type:"string"},description:"Up to 2 publicly reachable MMS image URLs. Only valid together with text."},label:{type:"string",description:"Updated display label for the step."},ineligibleAction:{type:"string",enum:["skip","exit"],description:"Updated behavior when the contact can't receive SMS."}},required:["nodeId"]}},subscriberUpdateSteps:{type:"array",description:"Full config replacements for existing Update Subscriber steps, targeted by action_update_attributes nodeId.",items:{type:"object",properties:{nodeId:{type:"string",description:"Target action_update_attributes node ID."},config:X0},required:["nodeId","config"]}}},required:["sequenceId"]}},{name:"update_sequence_node",description:"Patch one existing sequence node in place. Call get_sequence first, select sequence.nodes[].id, inspect nodeType/config, and pass that node's updatedAt as expectedUpdatedAt. This supports every stored sequence node type, including delays, email/SMS content, actions, conditions, branches without topology changes, webhooks, and trigger settings. Delay example: changes:{ delay:{ days:7 } }. 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:u$.properties.nodeId,changes:AW,expectedUpdatedAt:u$.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:u$},confirmLiveChange:{type:"boolean",description:"Set true only after the user explicitly confirms changing nodes in an active sequence."}},required:["sequenceId","updates"],additionalProperties:!1}},{name:"edit_sequence_graph",description:"Restructure an existing sequence graph using node IDs, edges, and graphRevision from get_sequence. move_node repositions one non-split step; beforeNodeId can place an A/B test or other step at the shared continuation below a branch. duplicate_node creates an independent copy and deep-copies linked email or A/B test content. delete_node safely splices a linear step; deleting a split node requires the complete replacement edges. replace_edges atomically replaces the complete topology for advanced reconnect or multi-node reorder work. Always call get_sequence immediately before this tool and pass its graphRevision. Active sequences require confirmStructuralChange:true after the user confirms live-flow impact.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID."},action:{type:"string",enum:["move_node","delete_node","duplicate_node","replace_edges"],description:"Graph operation. Use move_node for a single step reorder, duplicate_node for an independent copy, delete_node to remove a step/node, or replace_edges for an atomic reconnect/reorder of the whole topology."},graphRevision:{type:"string",description:"Exact graphRevision returned by the latest get_sequence call. The edit is rejected if the graph changed since then."},nodeId:{type:"string",description:"Existing node to move, duplicate, or delete. Required for those actions and unused by replace_edges."},afterNodeId:{type:"string",description:"For move_node or duplicate_node, insert immediately after this node. The target must have at most one outgoing path. Provide exactly one of afterNodeId or beforeNodeId."},beforeNodeId:{type:"string",description:"For move_node or duplicate_node, insert immediately before this node. All incoming paths converge through the moved/copied node, which is useful for placing a step below a branch. Provide exactly one of beforeNodeId or afterNodeId."},edges:{type:"array",description:"Complete replacement topology from get_sequence.sequence.edges. The returned edge array is already normalized for this input and can be reused directly. Required for replace_edges and when deleting a split node. Preserve each branch edge's condition.branchId. Do not include edges that reference a deleted node.",items:{type:"object",properties:{sourceNodeId:{type:"string"},targetNodeId:{type:"string"},condition:{type:"object",description:"Optional edge routing condition. Preserve condition.branchId on edges leaving logic_branch nodes."}},required:["sourceNodeId","targetNodeId"],additionalProperties:!1}},confirmStructuralChange:{type:"boolean",description:"Set true only after the user explicitly confirms a structural edit to an active sequence."}},required:["sequenceId","action","graphRevision"],additionalProperties:!1}},{name:"insert_sequence_step",description:"Insert one new email or SMS step into an existing sequence. Prefer this over update_sequence.steps/emails when adding a step: it creates the step node (plus an email template for email steps) and, when delay or delayMs is provided, a logic_delay node immediately before it. For SMS steps set type:'sms' and provide 'text' (generate copy with generate_sms; check get_sms_settings first and warn the user if SMS is not enabled). Use get_sequence first, then pass afterNodeId from sequence.nodes or sequence.emails to choose the insertion point. If afterNodeId is omitted, the step is appended only when the sequence has exactly one linear tail. For active sequences, set confirmStructuralChange:true only after the user confirms the live-flow impact.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID."},type:{type:"string",enum:["email","sms"],description:"Step type. Defaults to 'email'. Use 'sms' to insert an SMS step (requires 'text')."},afterNodeId:{type:"string",description:"Existing node ID to insert after. Use a nodeId from get_sequence.sequence.nodes or get_sequence.sequence.emails. Omit only to append to an unambiguous linear tail."},confirmStructuralChange:{type:"boolean",description:"Set true only after the user explicitly confirms a structural edit to an active sequence."},name:{type:"string",description:"Optional email template and step name."},subject:{type:"string",description:"Email subject for the new step. Required for email steps; not used for SMS steps."},previewText:{type:"string",description:"Optional email preview text for the new step."},blocks:{type:"array",description:W1,items:{type:"object"}},html:{type:"string",description:"HTML content for the new step. Stored as one raw HTML block. Use this for imported provider HTML. Provide either html or blocks, not both."},senderProfileId:{type:"string",description:"Email steps only: sender profile for the new step. Omit to inherit the effective identity of the nearest sequence email. After a branch merge, only fields shared by every incoming path are inherited; conflicting fields use sequence or company defaults."},fromEmail:{type:"string",description:"Email steps only: From address for the new step. Its domain must be verified. Mutually exclusive with senderProfileId."},fromName:{type:"string",description:"Email steps only: display name override for the new step. With fromEmail, also names a newly created sender profile."},replyProfileId:{type:"string",description:"Email steps only: reply profile for the new step. Omit to inherit the effective Reply-To of the nearest sequence email. After a branch merge, only fields shared by every incoming path are inherited; conflicting fields use sequence or company defaults. Mutually exclusive with replyTo."},replyTo:{type:"string",description:"Email steps only: Reply-To address for the new step. Mutually exclusive with replyProfileId."},replyToName:{type:"string",description:"Email steps only: display name for a newly created reply profile. Requires replyTo."},text:{type:"string",description:"SMS steps only: plain-text message body. Merge tags like {{FIRST_NAME}} work. Do not include opt-out text or a brand prefix - the platform adds those automatically."},imageUrls:{type:"array",items:{type:"string"},description:"SMS steps only: up to 2 publicly reachable image URLs sent as MMS media."},label:{type:"string",description:"SMS steps only: display label for the step."},ineligibleAction:{type:"string",enum:["skip","exit"],description:"SMS steps only: what happens when the contact can't receive SMS (no phone, not opted in, unsupported country). Default 'skip' continues the sequence."},delay:G1,delayMs:{type:"number",description:"Optional wait in milliseconds before the new step. Prefer delay for readability."},waitUntil:Q1},required:["sequenceId"],additionalProperties:!1}},{name:"enable_sequence",description:"Enable/activate a sequence. IMPORTANT: Only call this when the user EXPLICITLY asks to enable or activate a sequence. Never enable sequences automatically after creation - the user must review the content first.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}},{name:"disable_sequence",description:"Disable/freeze a sequence. This blocks new enrollments and holds current recipients until the sequence is enabled again. To only stop new enrollments while current recipients continue, use pause_sequence_enrollments.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}},{name:"pause_sequence_enrollments",description:"Stop new enrollments for an active sequence while current recipients continue through the sequence. This matches the dashboard 'Stop new enrollments' control and does not freeze current recipients.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}},{name:"resume_sequence_enrollments",description:"Resume new enrollments for an active sequence whose enrollment gate was paused. Use enable_sequence instead for a fully disabled/frozen sequence.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}},{name:"enroll_subscribers_in_sequence",description:"Manually enroll subscribers in a sequence by email address or subscriber ID. Maximum 500 total targets per call across emails and subscriberIds. Only active subscribers are enrolled: unknown emails are returned in `notFound`, while inactive, unavailable, and already actively enrolled subscribers are counted in `skipped`. By default enrollment starts at the first step after the trigger; pass targetNodeId to start at a specific step.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID to enroll subscribers in."},emails:{type:"array",items:{type:"string"},description:"Email addresses of subscribers to enroll. Combined with subscriberIds, maximum 500 total targets per call."},subscriberIds:{type:"array",items:{type:"string"},description:"Subscriber IDs to enroll. Combined with emails, maximum 500 total targets per call."},targetNodeId:{type:"string",description:"Optional node ID to start enrollment at. Use a non-trigger nodeId from get_sequence. Defaults to the first step after the trigger."}},required:["sequenceId"]}},{name:"cancel_sequence_enrollments",description:"Cancel active/waiting enrollments in one sequence. Provide sequenceId and exactly one target: subscriberId for one subscriber, or fieldValues to match stored entry event properties. For fieldValues, fieldPath is optional when the sequence has enrollmentFieldPath configured; otherwise provide a dot path such as order.id.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID whose enrollments should be cancelled."},subscriberId:{type:"string",description:"Subscriber ID to cancel in this sequence. Provide subscriberId or fieldValues, not both."},fieldPath:{type:"string",description:"Dot-path inside the token's stored entry event properties, such as order.id or event.id. Optional when the sequence has enrollmentFieldPath configured."},fieldValues:{type:"array",items:{type:"string"},description:"Entry field values to match. Cancels all active/waiting enrollments in the sequence whose entry field value is in this list. Provide fieldValues or subscriberId, not both."},dryRun:{type:"boolean",description:"When true, returns matching enrollments without cancelling them. Field-value cancellation defaults to dryRun on the API unless explicitly false."},reason:{type:"string",description:"Optional cancellation reason stored on matched enrollment tokens."}},required:["sequenceId"],additionalProperties:!1}},{name:"delete_sequence",description:"Delete a sequence",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}}];var Lz=[{name:"add_subscriber",description:"Add a new subscriber to your list",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to add subscriber to. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address"},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide this with email when creating, or instead of email for an existing subscriber."},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",description:"Initial subscriber status: active, unsubscribed, or bounced. Defaults to active."},optInMode:{type:"string",description:"Consent mode: confirmed creates active immediately when consent is verified, double_opt_in sends a confirmation email before activation, and default obeys company double opt-in settings."}},required:[]}},{name:"update_subscriber",description:"Update an existing subscriber's attributes or tags",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},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."},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 or delete a subscriber",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},hardDelete:{type:"boolean",description:"If true, permanently deletes. If false, just unsubscribes."}},required:[]}},{name:"get_subscriber",description:"Get the full subscriber profile, including tags, notes, list memberships, sequence enrollments, email stats, and recent activity",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},includeMachineEngagement:lb},required:[]}},{name:"list_subscriber_notes",description:"List internal notes for a subscriber. Provide email or externalId to identify the subscriber.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."}},required:[]}},{name:"add_subscriber_note",description:"Add an internal note to a subscriber. Provide email or externalId to identify the subscriber.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},body:{type:"string",description:"Internal note body, up to 5000 characters."}},required:["body"]}},{name:"delete_subscriber_note",description:"Delete one internal subscriber note by note ID.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},noteId:{type:"string",description:"Subscriber note ID to delete."}},required:["noteId"]}},{name:"search_subscribers",description:"Search subscribers by free-text query, tags, list, or segment. If you omit limit, the tool fetches all pages and returns every match.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},query:{type:"string",description:"Search query (email or name)"},tags:{type:"array",items:{type:"string"},description:"Filter by tags"},list:{type:"string",description:"Filter by subscriber list ID or exact list name. Prefer listId when known."},listId:{type:"string",description:"Filter by subscriber list ID."},listName:{type:"string",description:"Filter by exact subscriber list name when the list ID is not known."},segmentId:{type:"string",description:"Filter by segment ID"},status:{type:"string",description:"Filter by subscriber status: active, unsubscribed, or bounced."},limit:{type:"number",description:"Maximum results to return. If omitted, the tool returns all matches across pages."}}}}];var Uz={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."}},Bz=[{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:Uz,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:Uz,required:["email"],additionalProperties:!1}}];var Pz=[{name:"list_tags",description:"List all tags in the account",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list tags for. If not provided, uses the currently selected company."}}}},{name:"create_tag",description:"Create a new tag definition. The name is normalized to lowercase with hyphens (e.g. 'VIP Customer' becomes 'vip-customer'). Color defaults to gray.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},name:{type:"string",description:"Tag name. Normalized to lowercase with hyphens."},color:{type:"string",enum:[...D1],description:"Tag color. Defaults to gray."}},required:["name"]}},{name:"update_tag",description:"Update a tag's color. System tags cannot be updated.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},tagId:{type:"string",description:"Tag ID. Use list_tags to find tag IDs."},color:{type:"string",enum:[...D1],description:"New tag color."}},required:["tagId","color"]}},{name:"delete_tag",description:"Permanently delete a tag and remove it from all subscribers. This cannot be undone. System tags and tags used by sequences cannot be deleted.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},tagId:{type:"string",description:"Tag ID. Use list_tags to find tag IDs."}},required:["tagId"]}},{name:"list_lists",description:"List all subscriber lists",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list lists for. If not provided, uses the currently selected company."}}}},{name:"create_list",description:"Create a new subscriber list",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the list in. If not provided, uses the currently selected company."},name:{type:"string",description:"List name"},description:{type:"string",description:"List description"}},required:["name"]}},{name:"update_list",description:"Update a subscriber list's name, description, or privacy. Only the provided fields are changed.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},listId:{type:"string",description:"Subscriber list ID to update."},name:{type:"string",description:"New list name."},description:{type:["string","null"],description:"New list description. Pass null to clear it."},isPrivate:{type:"boolean",description:"Whether the list is private."}},required:["listId"]}},{name:"delete_list",description:"Permanently delete a subscriber list and remove all of its memberships. Subscribers themselves are kept. This cannot be undone.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},listId:{type:"string",description:"Subscriber list ID to delete."}},required:["listId"]}},{name:"add_subscribers_to_list",description:"Bulk add existing or new subscribers to a subscriber list from an email array. Existing subscribers are added to the list without requiring a per-subscriber update call.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},listId:{type:"string",description:"Subscriber list ID to add subscribers to."},emails:{type:"array",items:{type:"string"},description:"Email addresses to add to the list. Maximum 500 per call."},duplicateStrategy:{type:"string",description:"Duplicate strategy for existing subscribers: skip, merge, or overwrite. Defaults to skip."},enrollInSequences:{type:"boolean",description:"Whether newly created subscribers should enroll in matching sequences. Defaults to false."},optInMode:{type:"string",description:"Consent mode for newly created subscribers: default, confirmed, or double_opt_in. Defaults to default."}},required:["listId","emails"]}},{name:"remove_subscribers_from_list",description:"Remove subscribers from a list by email address. Maximum 500 emails per call. Subscribers stay in the account; only the list membership is removed. Returns the removed count plus a notFound array of emails that did not match a subscriber.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},listId:{type:"string",description:"Subscriber list ID to remove subscribers from."},emails:{type:"array",items:{type:"string"},description:"Email addresses to remove from the list. Maximum 500 per call."}},required:["listId","emails"]}},{name:"list_segments",description:"List all segments",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list segments for. If not provided, uses the currently selected company."}}}},{name:"create_segment",description:'Create a new segment from explicit filter rules. Use `filters` plus `filterJoinOperator` for flat legacy rules, or `root` for nested AND/OR groups such as `{ "kind": "group", "joinOperator": "and", "children": [{ "kind": "filter", "field": "attribute", "operator": "gte", "value": "mrr:50" }, { "kind": "group", "joinOperator": "or", "children": [{ "kind": "filter", "field": "tag", "operator": "contains", "value": "vip" }, { "kind": "filter", "field": "event", "operator": "is_not", "value": "saas.purchase:30d" }] }] }`. Supports `event` and `segment` fields, Stripe product purchase/current/trial/date filters, and campaign-specific engagement filters.',inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the segment in. If not provided, uses the currently selected company."},name:{type:"string",description:"Segment name"},filterJoinOperator:{type:"string",enum:["and","or"],description:'How top-level filters combine. Use `"and"` to require every filter or `"or"` to match any filter.'},filters:{type:"array",items:qW,minItems:1,description:'Array of segment filters. Example custom attribute empty check: [{"id":"filter-1","field":"attribute","operator":"is_empty","value":"last_logged_in:"}]. Example Stripe purchase filter: [{"id":"filter-1","field":"stripeProduct","operator":"is","value":"prod_123"}]. Example threshold filter: [{"id":"filter-1","field":"stripeProduct","operator":"at_least","value":"prod_123:3"}]. Example commerce product purchase filter (value is provider:productId since product ids are provider-scoped): [{"id":"filter-1","field":"commerceProduct","operator":"is","value":"api:prod-starter-kit"}]. Example repeat-buyer filter: [{"id":"filter-1","field":"commerceProduct","operator":"at_least","value":"shopify:42:2"}]. Example trial cancellation filter: [{"id":"filter-1","field":"stripeTrialProduct","operator":"is","value":"prod_123:is_canceled"}]. Example trial end filter: [{"id":"filter-1","field":"stripeTrialProduct","operator":"is","value":"prod_123:end_at:2026-05-26"}]. Example campaign-specific engagement combo: [{"id":"filter-1","field":"emailBounced","operator":"is","value":"campaign:cmp_abc"},{"id":"filter-2","field":"emailBounced","operator":"is_not","value":"campaign:cmp_xyz"}]. Combine them with `filterJoinOperator: "or"` to match any filter.'},root:{...LW,description:"Nested filter root. Mutually exclusive with `filters` and `filterJoinOperator`."}},required:["name"]}},{name:"update_segment",description:"Update a segment's name and/or filter rules. Use the same `filters` plus `filterJoinOperator` or nested `root` shapes as create_segment; providing `filters` or `root` replaces the segment's existing rules.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},segmentId:{type:"string",description:"Segment ID to update."},name:{type:"string",description:"New segment name."},filterJoinOperator:{type:"string",enum:["and","or"],description:'How top-level filters combine. Use `"and"` to require every filter or `"or"` to match any filter.'},filters:{type:"array",items:qW,minItems:1,description:"Replacement segment filters. Same shape and validation rules as create_segment. Mutually exclusive with `root`."},root:{...LW,description:"Replacement nested filter root. Mutually exclusive with `filters` and `filterJoinOperator`."}},required:["segmentId"]}},{name:"delete_segment",description:"Permanently delete a segment. This cannot be undone. Subscribers are not affected.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},segmentId:{type:"string",description:"Segment ID to delete."}},required:["segmentId"]}},{name:"get_segment_count",description:"Get the number of subscribers in a segment",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},segmentId:{type:"string",description:"Segment ID"}},required:["segmentId"]}}];var Fz=[{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 Kz=[{name:"list_templates",description:"List all email templates, including per-locale localization sync status",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"get_template",description:"Get a template's details, content, and all localized variants with sync status",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID"}},required:["templateId"]}},{name:"create_template",description:"Create a new email template. For net-new email content requested in natural language, use `prompt`; do not write HTML or construct blocks yourself. Use `blocks` only for finished caller-supplied Sequenzy content and `html` only for supplied or explicitly requested preserved HTML.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},name:{type:"string",description:"Template name"},subject:{type:"string",description:"Email subject line. Optional with `prompt`."},previewText:{type:["string","null"],description:"Optional preview text override."},html:{type:"string",description:"Email HTML content. Mutually exclusive with `blocks`. Use this for imported provider templates; Sequenzy stores it as one raw HTML block to preserve the design."},blocks:{type:"array",description:Hw,items:{type:"object"}},prompt:{type:"string",description:"Natural-language request for Sequenzy to generate branded native template blocks."},style:{type:"string",description:"Generation style; valid only with `prompt`."},tone:{type:"string",description:"Generation tone; valid only with `prompt`."},labels:{type:"array",description:"Optional label names to assign. Missing labels are created automatically.",items:{type:"string"}}},required:["name"]}},{name:"update_template",description:"Update an existing template. At least one of `name`, `subject`, `html`, `blocks`, or `labels` is required, and only those update fields are accepted.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID"},name:{type:"string",description:"Template name"},subject:{type:"string",description:"Email subject line"},html:{type:"string",description:"Email HTML content. Mutually exclusive with `blocks`. Use this for imported provider templates; Sequenzy stores it as one raw HTML block to preserve the design."},blocks:{type:"array",description:Hw,items:{type:"object"}},labels:{type:"array",description:"Replacement label names. Send an empty array to clear labels. Missing labels are created automatically.",items:{type:"string"}}},required:["templateId"],additionalProperties:!1}},{name:"set_template_localization",description:"Create or replace one caller-supplied localized variant of a template. The locale must be enabled for the company and cannot be its primary locale. Provide exactly one of `html` or `blocks`.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID, transactional email ID, or slug."},locale:{type:"string",description:"Enabled non-primary locale code such as es, fr, or pt-BR."},subject:{type:"string",description:"Localized email subject line."},previewText:{type:["string","null"],description:"Optional localized inbox preview text."},html:{type:"string",description:"Localized email HTML. Mutually exclusive with `blocks`."},blocks:{type:"array",description:Hw,items:{type:"object"}}},required:["templateId","locale","subject"],additionalProperties:!1}},{name:"sync_template_localizations",description:"Queue AI translation for selected template locales. Omit `locales` to sync every enabled non-primary locale. This works even when automatic on-save localization is disabled.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID, transactional email ID, or slug."},locales:{type:"array",description:"Optional enabled non-primary locale codes to sync. Omit to sync all enabled non-primary locales.",items:{type:"string"}}},required:["templateId"],additionalProperties:!1}},{name:"delete_template",description:"Delete a template",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID"}},required:["templateId"]}}];var Mz=[{name:"list_transactional_emails",description:"List transactional email templates, including their API slugs and linked email IDs",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"get_transactional_email",description:"Get a transactional email by ID or slug, including subject, preview text, blocks, variables, and linked dashboard URLs",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},idOrSlug:{type:"string",description:"Transactional email ID or API slug, for example `welcome-email`."}},required:["idOrSlug"]}},{name:"create_transactional_email",description:"Create a saved transactional email template with an API slug. For net-new natural-language content use `prompt`; do not author HTML or blocks. `blocks` are finished caller-supplied Sequenzy content and `html` is preserved/imported markup.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},name:{type:"string",description:"Transactional email name."},slug:{type:"string",description:"Optional API slug used when sending by slug, for example `password-reset`. If omitted, Sequenzy generates one from the name."},subject:{type:"string",description:"Email subject line. Optional when `prompt` is provided because the generated subject will be used."},previewText:{type:["string","null"],description:"Email preview text."},html:{type:"string",description:"Email HTML content. Mutually exclusive with `blocks`. Sequenzy stores it as one raw HTML block."},blocks:{type:"array",description:`${Hw} Mutually exclusive with \`html\`.`,items:{type:"object"}},prompt:{type:"string",description:"Generate transactional email blocks from a prompt. Generated blocks include the company's branding (logo and a footer without an unsubscribe link). Mutually exclusive with `html` and `blocks`."},style:{type:"string",description:"Prompt generation style: minimal, branded, promotional. Only used with `prompt`."},tone:{type:"string",description:"Prompt generation tone: professional, casual, friendly. Only used with `prompt`."},enabled:{type:"boolean",description:"Whether this transactional email can be sent immediately. Prompt-created templates default to false; explicit HTML/blocks retain the compatibility default of true."}},required:["name"],additionalProperties:!1}},{name:"update_transactional_email",description:"Update a transactional email by ID or slug. At least one of `name`, `enabled`, `subject`, `previewText`, `html`, or `blocks` is required. Use `html` or `blocks` to replace the linked email body.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},idOrSlug:{type:"string",description:"Transactional email ID or API slug, for example `welcome-email`."},name:{type:"string",description:"Transactional email name."},enabled:{type:"boolean",description:"Whether this transactional email can be sent."},subject:{type:"string",description:"Email subject line."},previewText:{type:["string","null"],description:"Email preview text."},html:{type:"string",description:"Email HTML content. Mutually exclusive with `blocks`. Sequenzy stores it as one raw HTML block."},blocks:{type:"array",description:`${Jw} Mutually exclusive with \`html\`.`,items:{type:"object"}}},required:["idOrSlug"],additionalProperties:!1}},{name:"send_email",description:"Queue one transactional email using either a saved transactional email API slug (`templateId`) or direct `subject` and `html` content. Returns a durable emailSendId; pass it to get_email_send for delivery status and failure details.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},to:{type:"string",description:"Recipient email address"},subject:{type:"string",description:"Email subject line. Required with `html` when `templateId` is omitted."},html:{type:"string",description:"Direct-send HTML body. Required with `subject` when `templateId` is omitted; the MCP server maps this to the transactional API `body` field."},templateId:{type:"string",description:"Saved transactional email API slug, for example `welcome-email`. The field name is retained for MCP compatibility and is mapped to the transactional API `slug` field."},variables:{type:"object",description:"Variables for template personalization. Nested objects and arrays are supported for repeat blocks, for example { items: [...] }."},subscriberExternalId:{type:"string",description:"Customer-owned subscriber ID for attaching analytics/localization on single-recipient sends. Maximum length: 255 characters."}},required:["to"],additionalProperties:!1}}];var Iz=[{name:"list_webhooks",description:"List outbound webhook endpoints and their subscribed event types.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"create_webhook",description:"Create an outbound webhook endpoint. IMPORTANT: the response includes a signingSecret that is returned only once - show it to the user immediately so they can store it and verify webhook signatures. If events is omitted, a default set of event types is subscribed.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},name:{type:"string",description:"Webhook endpoint name."},url:{type:"string",description:"HTTPS URL that will receive webhook events."},events:{type:"array",items:{type:"string",enum:[...X1]},description:"Event types to subscribe to. If omitted, a default set is used."}},required:["name","url"]}},{name:"update_webhook",description:"Update an outbound webhook endpoint's name, URL, subscribed events, or status (enabled/disabled). Providing events replaces the existing event list.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},webhookId:{type:"string",description:"Webhook endpoint ID."},name:{type:"string",description:"New webhook endpoint name."},url:{type:"string",description:"New HTTPS URL that will receive webhook events."},events:{type:"array",items:{type:"string",enum:[...X1]},description:"Replacement event type subscriptions."},status:{type:"string",enum:["enabled","disabled"],description:"Enable or disable deliveries to this endpoint."}},required:["webhookId"]}},{name:"delete_webhook",description:"Permanently delete an outbound webhook endpoint along with its delivery history. This cannot be undone. To keep the endpoint but stop deliveries, use update_webhook with status disabled instead.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},webhookId:{type:"string",description:"Webhook endpoint ID to delete."}},required:["webhookId"]}},{name:"test_webhook",description:"Send a test event to an outbound webhook endpoint to verify it is reachable and signatures can be validated.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},webhookId:{type:"string",description:"Webhook endpoint ID to test."}},required:["webhookId"]}},{name:"list_webhook_deliveries",description:"List recent delivery attempts for an outbound webhook endpoint, including status and response codes.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},webhookId:{type:"string",description:"Webhook endpoint ID."},limit:{type:"number",description:"Maximum number of deliveries to return, from 1 to 100. Defaults to 20."}},required:["webhookId"]}},{name:"replay_webhook_delivery",description:"Replay a previous webhook delivery, re-sending the same event payload to the endpoint.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},webhookId:{type:"string",description:"Webhook endpoint ID."},deliveryId:{type:"string",description:"Delivery ID to replay. Use list_webhook_deliveries to find delivery IDs."}},required:["webhookId","deliveryId"]}}];var Zz=[...$z,...Lz,...Bz,...Az,...Pz,...Gz,...Kz,...wz,...Dz,...Yz,...zz,...Hz,...Oz,...qz,...Mz,...Qz,...Fz,...Jz,...Iz,...Wz,...Xz];async function jz(b,w){let $;switch(b){case"get_account":{let W=await A("GET","/api/v1/account"),Q=qw();$={...W,selectedCompanyId:Q??W.currentCompanyId};break}case"select_company":{let W=w.companyId,Q=await A("GET","/api/v1/account"),G=Q.companies?.find((D)=>D.id===W);if(!G)throw Error(`Company not found. Available companies: ${Q.companies?.map((D)=>`${D.name} (${D.id})`).join(", ")??"none"}`);A0(W),$={success:!0,message:`Switched to company: ${G.name}`,companyId:G.id,companyName:G.name};break}case"get_app_urls":{let W=await i$(w);$={...Yw({companyId:W,campaignId:P(w,"campaignId"),landingPageId:P(w,"landingPageId"),sequenceId:P(w,"sequenceId"),emailId:P(w,"emailId")??P(w,"templateId"),transactionalId:P(w,"transactionalId"),emailSendId:P(w,"emailSendId"),domainId:P(w,"domainId"),status:P(w,"status"),settingsTab:P(w,"settingsTab")}),...W===void 0&&{note:"No company ID is selected. Call get_account, select_company, or pass companyId to get concrete dashboard URLs."}};break}case"create_company":{let W=await A("POST","/api/v1/companies",{name:w.name,domain:w.domain});if(!W.success)throw Error("Failed to create company");let Q=W.company.id,G=6,D=0,X=W.company.status;while(X==="processing"&&D<G){await new Promise((J)=>setTimeout(J,20000)),D++;let H=await A("GET",`/api/v1/companies/${Q}`);if(H.success)X=H.company.status}A0(Q);let Y=await A("GET",`/api/v1/companies/${Q}`);$={success:!0,company:Y.company,message:X==="processing"?"Company created but still processing. You can continue using it while processing completes.":`Company '${Y.company.name}' created and ready to use.`,autoSelected:!0};break}case"get_company":{let W=w.companyId;$=await A("GET",`/api/v1/companies/${W}`);break}case"update_company":{let W=await pJ("update_company",w),Q=TJ(w);$=await A("PATCH",`/api/v1/companies/${W}`,Q);break}case"get_sync_rules":{let W=w.companyId;$=await A("GET","/api/v1/sync-rules",void 0,W);break}case"update_sync_rules":{let W=w.companyId;if(w.syncRules!==null&&!Array.isArray(w.syncRules))throw Error("`syncRules` must be an array of rules or null when calling `update_sync_rules`.");$=await A("PUT","/api/v1/sync-rules",{syncRules:w.syncRules},W);break}case"get_shopify_automation_settings":{let W=w.companyId;$=await A("GET","/api/v1/shopify/automation-settings",void 0,W);break}case"update_shopify_automation_settings":{let W=w.companyId,Q={};if(w.browseAbandonment!==void 0)Q.browseAbandonment=w.browseAbandonment;if(w.priceDrop!==void 0)Q.priceDrop=w.priceDrop;if(Object.keys(Q).length===0)throw Error("Provide `browseAbandonment` and/or `priceDrop` when calling `update_shopify_automation_settings`.");$=await A("PUT","/api/v1/shopify/automation-settings",Q,W);break}case"create_api_key":{let W=w.companyId,Q={};if(typeof w.name==="string")Q.name=w.name;if(typeof w.preset==="string")Q.preset=w.preset;if(Array.isArray(w.scopes))Q.scopes=w.scopes;$=await A("POST","/api/v1/api-keys",Q,W);break}case"list_websites":{let W=w.companyId;$=await A("GET","/api/v1/websites",void 0,W);break}case"add_sending_domain":case"add_website":{let W=w.companyId;$=await A("POST","/api/v1/websites",{domain:w.domain},W);break}case"check_website":{let W=w.companyId;$=await A("GET",`/api/v1/websites/${encodeURIComponent(String(w.domain))}`,void 0,W);break}case"verify_sending_domain":{let W=w.companyId;$=await A("POST",`/api/v1/websites/${encodeURIComponent(String(w.domain))}/verify`,void 0,W);break}case"get_integration_guide":$=await A("POST","/api/v1/integration-guide",w);break;default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function Vz(b,w){let $;switch(b){case"generate_email":{let W=w.companyId;$=await A("POST","/api/v1/generate/email",w,W);break}case"generate_subject_lines":{let W=w.companyId;$=await A("POST","/api/v1/generate/subjects",w,W);break}case"generate_sms":{let W=w.companyId;$=await A("POST","/api/v1/generate/sms",w,W);break}case"get_sms_settings":{let W=w.companyId;$=await A("GET","/api/v1/sms/settings",void 0,W);break}case"send_test_sms":{let W=w.companyId,Q={to:Z("send_test_sms",w,"to")};for(let G of["text","imageUrls","blocks"])if(w[G]!==void 0)Q[G]=w[G];$=await A("POST","/api/v1/sms/test",Q,W);break}case"submit_feedback":{let W=w.companyId,Q={message:Z("submit_feedback",w,"message"),source:"mcp"};for(let G of["category","context"])if(w[G]!==void 0)Q[G]=w[G];$=await A("POST","/api/v1/feedback",Q,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function Nz(b,w){let $;switch(b){case"list_transactional_emails":{let W=w.companyId;$=await A("GET","/api/v1/transactional",void 0,W);break}case"get_transactional_email":{let W=w.companyId;$=await A("GET",`/api/v1/transactional/${w.idOrSlug}`,void 0,W);break}case"create_transactional_email":{let W=w.companyId,Q=new Set(["companyId","name","slug","subject","previewText","html","blocks","prompt","style","tone","enabled"]),G=Object.keys(w).filter((X)=>!Q.has(X));if(G.length>0)throw Error(`\`create_transactional_email\` accepts only \`name\`, \`slug\`, \`subject\`, \`previewText\`, \`html\`, \`blocks\`, \`prompt\`, \`style\`, \`tone\`, and \`enabled\` fields. Unsupported field${G.length===1?"":"s"}: ${G.map((X)=>`\`${X}\``).join(", ")}.`);cJ(w);let D=Object.fromEntries(Object.entries(w).filter(([X])=>X!=="companyId"));$=await A("POST","/api/v1/transactional",D,W);break}case"update_transactional_email":{let W=w.companyId,Q=new Set(["companyId","idOrSlug","name","enabled","subject","previewText","html","blocks"]),G=Object.keys(w).filter((X)=>!Q.has(X));if(G.length>0)throw Error(`\`update_transactional_email\` accepts only \`name\`, \`enabled\`, \`subject\`, \`previewText\`, \`html\`, and \`blocks\` update fields. Unsupported field${G.length===1?"":"s"}: ${G.map((X)=>`\`${X}\``).join(", ")}.`);if(_b("update_transactional_email",w),w.name===void 0&&w.enabled===void 0&&w.subject===void 0&&w.previewText===void 0&&w.html===void 0&&w.blocks===void 0)throw Error("Provide at least one of `name`, `enabled`, `subject`, `previewText`, `html`, or `blocks` when calling `update_transactional_email`.");let D=Object.fromEntries(Object.entries(w).filter(([X])=>X!=="companyId"&&X!=="idOrSlug"));$=await A("PATCH",`/api/v1/transactional/${w.idOrSlug}`,D,W);break}case"send_email":{let W=w.companyId,Q=Z("send_email",w,"to"),G=w.templateId===void 0?void 0:Z("send_email",w,"templateId"),D=w.subject===void 0?void 0:Z("send_email",w,"subject"),X=w.html===void 0?void 0:Z("send_email",w,"html");if(G!==void 0&&(D!==void 0||X!==void 0))throw Error("`templateId` cannot be combined with `subject` or `html` when calling `send_email`.");if(G===void 0&&(D===void 0||X===void 0))throw Error("Provide either `templateId` or both `subject` and `html` when calling `send_email`.");let Y=Object.fromEntries(Object.entries({to:Q,slug:G,subject:D,body:X,variables:w.variables,subscriberExternalId:w.subscriberExternalId}).filter(([,H])=>H!==void 0));$=await A("POST","/api/v1/transactional/send",Y,W);break}case"get_stats":{let W=w.companyId,Q=w.period??"7d",G=new URLSearchParams({period:String(Q)});if(w.includeMachineEngagement===!0)G.set("includeMachineEngagement","true");$=await A("GET",`/api/v1/metrics?${G.toString()}`,void 0,W);break}case"get_campaign_stats":{let W=w.companyId,Q=new URLSearchParams;if(w.includeMachineEngagement===!0)Q.set("includeMachineEngagement","true");let G=Q.toString();$=await A("GET",`/api/v1/metrics/campaigns/${w.campaignId}${G?`?${G}`:""}`,void 0,W);break}case"get_sequence_stats":{let W=w.companyId,Q=new URLSearchParams;if(w.includeMachineEngagement===!0)Q.set("includeMachineEngagement","true");let G=Q.toString();$=await A("GET",`/api/v1/metrics/sequences/${w.sequenceId}${G?`?${G}`:""}`,void 0,W);break}case"list_campaign_events":{let W=w.companyId,Q=Z("list_campaign_events",w,"campaignId"),D=ZW("list_campaign_events",w).toString();$=await A("GET",`/api/v1/metrics/campaigns/${encodeURIComponent(Q)}/events${D?`?${D}`:""}`,void 0,W);break}case"list_sequence_events":{let W=w.companyId,Q=Z("list_sequence_events",w,"sequenceId"),D=ZW("list_sequence_events",w).toString();$=await A("GET",`/api/v1/metrics/sequences/${encodeURIComponent(Q)}/events${D?`?${D}`:""}`,void 0,W);break}case"get_subscriber_activity":{let W=w.companyId,Q=Aw("get_subscriber_activity",w),G=await Y0(Q,W,{includeMachineEngagement:w.includeMachineEngagement===!0});$={success:G.success,email:G.subscriber.email,emailStats:G.subscriber.emailStats??null,activity:G.subscriber.activity??[],sequenceEnrollments:G.subscriber.sequenceEnrollments??[]};break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function Tz(b,w){let $;switch(b){case"list_tags":{let W=w.companyId;$=await A("GET","/api/v1/tags",void 0,W);break}case"create_tag":{let W=w.companyId,Q=Z("create_tag",w,"name"),G=Ub("create_tag",w,"color",D1);$=await A("POST","/api/v1/tags",{name:Q,...G!==void 0&&{color:G}},W);break}case"update_tag":{let W=w.companyId,Q=Z("update_tag",w,"tagId"),G=H0("update_tag",w,"color",D1);$=await A("PATCH",`/api/v1/tags/${encodeURIComponent(Q)}`,{color:G},W);break}case"delete_tag":{let W=w.companyId,Q=Z("delete_tag",w,"tagId");$=await A("DELETE",`/api/v1/tags/${encodeURIComponent(Q)}`,void 0,W);break}case"list_lists":{let W=w.companyId;$=await A("GET","/api/v1/lists",void 0,W);break}case"create_list":{let W=w.companyId;$=await A("POST","/api/v1/lists",w,W);break}case"update_list":{let W=w.companyId,Q=Z("update_list",w,"listId");if(w.name===void 0&&w.description===void 0&&w.isPrivate===void 0)throw Error("Provide at least one of `name`, `description`, or `isPrivate` when calling `update_list`.");if(w.name!==void 0&&P(w,"name")===void 0)throw Error("`name` cannot be empty when calling `update_list`.");if(w.description!==void 0&&w.description!==null&&typeof w.description!=="string")throw Error("`description` must be a string or null when calling `update_list`.");if(w.isPrivate!==void 0&&typeof w.isPrivate!=="boolean")throw Error("`isPrivate` must be a boolean when calling `update_list`.");$=await A("PATCH",`/api/v1/lists/${encodeURIComponent(Q)}`,{...w.name!==void 0&&{name:P(w,"name")},...w.description!==void 0&&{description:w.description},...w.isPrivate!==void 0&&{isPrivate:w.isPrivate}},W);break}case"delete_list":{let W=w.companyId,Q=Z("delete_list",w,"listId");$=await A("DELETE",`/api/v1/lists/${encodeURIComponent(Q)}`,void 0,W);break}case"add_subscribers_to_list":{let W=w.companyId,Q=Z("add_subscribers_to_list",w,"listId"),G=VW("add_subscribers_to_list",w),D=Ub("add_subscribers_to_list",w,"duplicateStrategy",["skip","merge","overwrite"])??"skip",X=Ub("add_subscribers_to_list",w,"optInMode",["default","confirmed","double_opt_in"])??"default";$=await A("POST",`/api/v1/lists/${encodeURIComponent(Q)}/subscribers`,{emails:G,duplicateStrategy:D,enrollInSequences:w.enrollInSequences===!0,optInMode:X},W);break}case"remove_subscribers_from_list":{let W=w.companyId,Q=Z("remove_subscribers_from_list",w,"listId"),G=VW("remove_subscribers_from_list",w);$=await A("POST",`/api/v1/lists/${encodeURIComponent(Q)}/subscribers/remove`,{emails:G},W);break}case"list_segments":{let W=w.companyId;$=await A("GET","/api/v1/segments",void 0,W);break}case"create_segment":{VJ(w);let W=w.companyId;$=await A("POST","/api/v1/segments",{...w,...w.filters!==void 0?{filters:x$(w.filters)}:{},...w.root!==void 0?{root:y$(w.root)}:{}},W);break}case"update_segment":{NJ(w);let W=w.companyId,Q=Z("update_segment",w,"segmentId"),G=P(w,"name"),D=Ub("update_segment",w,"filterJoinOperator",["and","or"]);$=await A("PATCH",`/api/v1/segments/${encodeURIComponent(Q)}`,{...G!==void 0&&{name:G},...D!==void 0&&{filterJoinOperator:D},...w.filters!==void 0?{filters:x$(w.filters)}:{},...w.root!==void 0?{root:y$(w.root)}:{}},W);break}case"delete_segment":{let W=w.companyId,Q=Z("delete_segment",w,"segmentId");$=await A("DELETE",`/api/v1/segments/${encodeURIComponent(Q)}`,void 0,W);break}case"get_segment_count":{let W=w.companyId;$=await A("GET",`/api/v1/segments/${w.segmentId}/count`,void 0,W);break}case"list_audience_syncs":{let W=w.companyId;$=await A("GET","/api/v1/audience-syncs",void 0,W);break}case"list_ad_accounts":{let W=w.companyId;$=await A("GET","/api/v1/ad-accounts",void 0,W);break}case"create_audience_sync":{let W=w.companyId,Q=P(w,"segmentId"),G=P(w,"predefinedSegmentId");if(Q&&G)throw Error("Provide either `segmentId` or `predefinedSegmentId` when calling `create_audience_sync`, not both.");if(!Q&&!G)throw Error("Provide either `segmentId` or `predefinedSegmentId` when calling `create_audience_sync`.");$=await A("POST","/api/v1/audience-syncs",{segmentId:Q,predefinedSegmentId:G,adAccountId:Z("create_audience_sync",w,"adAccountId"),audienceName:Z("create_audience_sync",w,"audienceName"),...w.frequency!==void 0?{frequency:w.frequency}:{}},W);break}case"update_audience_sync":{let W=w.companyId,Q=Z("update_audience_sync",w,"syncId");$=await A("PATCH",`/api/v1/audience-syncs/${encodeURIComponent(Q)}`,{...w.frequency!==void 0?{frequency:w.frequency}:{},...w.isActive!==void 0?{isActive:w.isActive}:{}},W);break}case"delete_audience_sync":{let W=w.companyId,Q=Z("delete_audience_sync",w,"syncId");$=await A("DELETE",`/api/v1/audience-syncs/${encodeURIComponent(Q)}`,void 0,W);break}case"sync_audience_now":{let W=w.companyId,Q=Z("sync_audience_now",w,"syncId");$=await A("POST",`/api/v1/audience-syncs/${encodeURIComponent(Q)}/sync`,void 0,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function Ez(b,w){let $;switch(b){case"list_templates":{let W=w.companyId,Q=new URLSearchParams,G=P(w,"label");if(G)Q.set("label",G);$=await A("GET",`/api/v1/templates${Q.size>0?`?${Q}`:""}`,void 0,W);break}case"get_template":{let W=w.companyId;$=await A("GET",`/api/v1/templates/${w.templateId}`,void 0,W);break}case"create_template":{let W=w.companyId;yJ(w);let Q=Object.fromEntries(Object.entries(w).filter(([G])=>G!=="companyId"));$=await A("POST","/api/v1/templates",Q,W);break}case"update_template":{let W=w.companyId,Q=new Set(["companyId","templateId","name","subject","html","blocks","labels"]),G=Object.keys(w).filter((D)=>!Q.has(D));if(G.length>0)throw Error(`\`update_template\` accepts only \`name\`, \`subject\`, \`html\`, \`blocks\`, and \`labels\` update fields. Unsupported field${G.length===1?"":"s"}: ${G.map((D)=>`\`${D}\``).join(", ")}.`);if(_b("update_template",w),Y1("update_template",w),w.name===void 0&&w.subject===void 0&&w.html===void 0&&w.blocks===void 0&&w.labels===void 0)throw Error("Provide at least one of `name`, `subject`, `html`, `blocks`, or `labels` when calling `update_template`.");$=await A("PUT",`/api/v1/templates/${w.templateId}`,w,W);break}case"set_template_localization":{let W=w.companyId,Q=Z("set_template_localization",w,"templateId"),G=Z("set_template_localization",w,"locale"),D=Z("set_template_localization",w,"subject"),X=new Set(["companyId","templateId","locale","subject","previewText","html","blocks"]),Y=Object.keys(w).filter((J)=>!X.has(J));if(Y.length>0)throw Error(`\`set_template_localization\` received unsupported field${Y.length===1?"":"s"}: ${Y.map((J)=>`\`${J}\``).join(", ")}.`);_b("set_template_localization",w,{requireContent:!0});let H={subject:D};if(w.previewText!==void 0)H.previewText=w.previewText;if(w.html!==void 0)H.html=w.html;if(w.blocks!==void 0)H.blocks=w.blocks;$=await A("PUT",`/api/v1/templates/${encodeURIComponent(Q)}/localizations/${encodeURIComponent(G)}`,H,W);break}case"sync_template_localizations":{let W=w.companyId,Q=Z("sync_template_localizations",w,"templateId"),G=new Set(["companyId","templateId","locales"]),D=Object.keys(w).filter((Y)=>!G.has(Y));if(D.length>0)throw Error(`\`sync_template_localizations\` received unsupported field${D.length===1?"":"s"}: ${D.map((Y)=>`\`${Y}\``).join(", ")}.`);let X;if(w.locales!==void 0){if(!Array.isArray(w.locales)||w.locales.length===0||w.locales.some((Y)=>typeof Y!=="string"||Y.trim().length===0))throw Error("`locales` must contain at least one non-empty locale string when calling `sync_template_localizations`.");X=w.locales.map((Y)=>Y.trim())}$=await A("POST",`/api/v1/templates/${encodeURIComponent(Q)}/localizations/sync`,X===void 0?{}:{locales:X},W);break}case"delete_template":{let W=w.companyId;$=await A("DELETE",`/api/v1/templates/${w.templateId}`,void 0,W);break}case"list_ab_tests":{let W=w.companyId,Q=new URLSearchParams,G=P(w,"sequenceId");if(G)Q.set("sequenceId",G);$=await A("GET",`/api/v1/ab-tests${Q.size>0?`?${Q}`:""}`,void 0,W);break}case"get_ab_test":{let W=w.companyId;$=await A("GET",`/api/v1/ab-tests/${w.abTestId}`,void 0,W);break}case"get_ab_test_stats":{let W=w.companyId,Q=new URLSearchParams,G=P(w,"period"),D=P(w,"start"),X=P(w,"end");if(G)Q.set("period",G);if(D)Q.set("start",D);if(X)Q.set("end",X);if(w.includeMachineEngagement===!0)Q.set("includeMachineEngagement","true");$=await A("GET",`/api/v1/ab-tests/${w.abTestId}/stats${Q.size>0?`?${Q}`:""}`,void 0,W);break}case"restart_ab_test":{let W=w.companyId,Q=new Set(["companyId","abTestId","sourceVariantId","testType","winnerThreshold","variantCount"]),G=Object.keys(w).filter((H)=>!Q.has(H));if(G.length>0)throw Error(`\`restart_ab_test\` accepts only \`sourceVariantId\`, \`testType\`, \`winnerThreshold\`, and \`variantCount\` option fields. Unsupported field${G.length===1?"":"s"}: ${G.map((H)=>`\`${H}\``).join(", ")}.`);let D=P(w,"testType");if(D!==void 0&&D!=="subject"&&D!=="content")throw Error("`restart_ab_test` testType must be `subject` or `content`.");let X=w.winnerThreshold===void 0?void 0:Number(w.winnerThreshold);if(X!==void 0&&(!Number.isInteger(X)||X<10||X>1000))throw Error("`restart_ab_test` winnerThreshold must be an integer from 10 to 1000.");let Y=w.variantCount===void 0?void 0:Number(w.variantCount);if(Y!==void 0&&(!Number.isInteger(Y)||Y<2||Y>4))throw Error("`restart_ab_test` variantCount must be an integer from 2 to 4.");$=await A("POST",`/api/v1/ab-tests/${w.abTestId}/restart`,{sourceVariantId:P(w,"sourceVariantId"),testType:D,winnerThreshold:X,variantCount:Y},W);break}case"update_ab_test_variant":{let W=w.companyId,Q=new Set(["companyId","abTestId","variantId","subject","previewText","html","blocks"]),G=Object.keys(w).filter((D)=>!Q.has(D));if(G.length>0)throw Error(`\`update_ab_test_variant\` accepts only \`subject\`, \`previewText\`, \`html\`, and \`blocks\` update fields. Unsupported field${G.length===1?"":"s"}: ${G.map((D)=>`\`${D}\``).join(", ")}.`);if(_b("update_ab_test_variant",w),w.subject===void 0&&w.previewText===void 0&&w.html===void 0&&w.blocks===void 0)throw Error("Provide at least one of `subject`, `previewText`, `html`, or `blocks` when calling `update_ab_test_variant`.");$=await A("PATCH",`/api/v1/ab-tests/${w.abTestId}/variants/${w.variantId}`,w,W);break}case"create_ab_test":{let W=w.companyId,Q=Z("create_ab_test",w,"campaignId"),G=P(w,"name"),D=zw("create_ab_test",w,"testPercentage",5,50),X=zw("create_ab_test",w,"testDurationMinutes",15,1440),Y=Ub("create_ab_test",w,"winnerCriteria",["open_rate","click_rate"]);if(w.variants!==void 0){if(!Array.isArray(w.variants))throw Error("`variants` must be an array when calling `create_ab_test`.");w.variants.forEach((H,J)=>{if(!y(H)||typeof H.subject!=="string"||H.subject.trim()==="")throw Error(`\`variants\` item ${J+1} must include a non-empty \`subject\` when calling \`create_ab_test\`.`);if(H.blocks!==void 0&&!Array.isArray(H.blocks))throw Error(`\`variants\` item ${J+1} \`blocks\` must be an array when calling \`create_ab_test\`.`)})}$=await A("POST","/api/v1/ab-tests",{campaignId:Q,...G!==void 0&&{name:G},...D!==void 0&&{testPercentage:D},...X!==void 0&&{testDurationMinutes:X},...Y!==void 0&&{winnerCriteria:Y},...w.variants!==void 0&&{variants:w.variants}},W);break}case"add_ab_test_variant":{let W=w.companyId,Q=Z("add_ab_test_variant",w,"abTestId"),G=Z("add_ab_test_variant",w,"subject"),D=P(w,"previewText");if(w.blocks!==void 0&&!Array.isArray(w.blocks))throw Error("`blocks` must be an array when calling `add_ab_test_variant`.");$=await A("POST",`/api/v1/ab-tests/${encodeURIComponent(Q)}/variants`,{subject:G,...D!==void 0&&{previewText:D},...w.blocks!==void 0&&{blocks:w.blocks}},W);break}case"delete_ab_test_variant":{let W=w.companyId,Q=Z("delete_ab_test_variant",w,"abTestId"),G=Z("delete_ab_test_variant",w,"variantId");$=await A("DELETE",`/api/v1/ab-tests/${encodeURIComponent(Q)}/variants/${encodeURIComponent(G)}`,void 0,W);break}case"delete_ab_test":{let W=w.companyId,Q=Z("delete_ab_test",w,"abTestId");$=await A("DELETE",`/api/v1/ab-tests/${encodeURIComponent(Q)}`,void 0,W);break}case"list_campaigns":{let W=w.companyId,Q=new URLSearchParams;if(w.status)Q.set("status",String(w.status));let G=P(w,"label");if(G)Q.set("label",G);$=await A("GET",`/api/v1/campaigns?${Q}`,void 0,W);break}case"get_campaign":{let W=w.companyId;$=await A("GET",`/api/v1/campaigns/${w.campaignId}`,void 0,W);break}case"get_email_send":{let W=w.companyId;$=await A("GET",`/api/v1/email-sends/${encodeURIComponent(String(w.emailSendId))}`,void 0,W);break}case"create_campaign":{let W=w.companyId;if(xJ(w),w.fromEmail!==void 0&&w.senderProfileId!==void 0)throw Error("Provide either `fromEmail` or `senderProfileId` when calling `create_campaign`, not both.");if(w.replyTo!==void 0&&w.replyProfileId!==void 0)throw Error("Provide either `replyTo` or `replyProfileId` when calling `create_campaign`, not both.");if(w.fromName!==void 0&&w.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `create_campaign`.");if(w.replyToName!==void 0&&w.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `create_campaign`.");let Q=Object.fromEntries(Object.entries(w).filter(([G])=>G!=="companyId"));$=await A("POST","/api/v1/campaigns",Q,W);break}case"update_campaign":{let W=w.companyId,Q=new Set(["companyId","campaignId","name","subject","trackingCode","html","blocks","fromEmail","fromName","senderProfileId","replyTo","replyToName","replyProfileId","ccEmails","bccEmails","campaignData","computedLists","labels"]),G=Object.keys(w).filter((D)=>!Q.has(D));if(G.length>0)throw Error(`\`update_campaign\` accepts only content, sending identity, campaign data, computed list, and label update fields. Unsupported field${G.length===1?"":"s"}: ${G.map((D)=>`\`${D}\``).join(", ")}.`);if(_b("update_campaign",w),Y1("update_campaign",w),w.replyTo!==void 0&&w.replyProfileId!==void 0)throw Error("Provide either `replyTo` or `replyProfileId` when calling `update_campaign`, not both.");if(w.fromEmail!==void 0&&w.senderProfileId!==void 0)throw Error("Provide either `fromEmail` or `senderProfileId` when calling `update_campaign`, not both.");if(w.fromName!==void 0&&w.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `update_campaign`.");if(w.replyToName!==void 0&&w.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `update_campaign`.");if(w.name===void 0&&w.subject===void 0&&w.trackingCode===void 0&&w.html===void 0&&w.blocks===void 0&&w.fromEmail===void 0&&w.senderProfileId===void 0&&w.replyTo===void 0&&w.replyProfileId===void 0&&w.ccEmails===void 0&&w.bccEmails===void 0&&w.campaignData===void 0&&w.computedLists===void 0&&w.labels===void 0)throw Error("Provide at least one campaign content, sending identity, campaign data, computed list, or label field when calling `update_campaign`.");$=await A("PUT",`/api/v1/campaigns/${w.campaignId}`,w,W);break}case"schedule_campaign":{let W=w.companyId,Q=new Set(["companyId","campaignId","scheduledAt","targetLists","sendTimeOptimization","spreadOverHours","recurringInterval"]),G=Object.keys(w).filter((D)=>!Q.has(D));if(G.length>0)throw Error(`\`schedule_campaign\` accepts only \`campaignId\`, \`scheduledAt\`, \`targetLists\`, \`sendTimeOptimization\`, \`spreadOverHours\`, and \`recurringInterval\`. Unsupported field${G.length===1?"":"s"}: ${G.map((D)=>`\`${D}\``).join(", ")}.`);hJ(w),$=await A("POST",`/api/v1/campaigns/${w.campaignId}/schedule`,{scheduledAt:w.scheduledAt,...w.targetLists!==void 0&&{targetLists:w.targetLists},...w.sendTimeOptimization!==void 0&&{sendTimeOptimization:w.sendTimeOptimization},...w.spreadOverHours!==void 0&&{spreadOverHours:w.spreadOverHours},...w.recurringInterval!==void 0&&{recurringInterval:w.recurringInterval}},W);break}case"send_test_email":{let W=w.companyId;$=await A("POST",`/api/v1/campaigns/${w.campaignId}/test`,{to:w.to},W);break}case"cancel_campaign":{let W=w.companyId,Q=Z("cancel_campaign",w,"campaignId");$=await A("POST",`/api/v1/campaigns/${encodeURIComponent(Q)}/cancel`,void 0,W);break}case"pause_campaign":{let W=w.companyId,Q=Z("pause_campaign",w,"campaignId");$=await A("POST",`/api/v1/campaigns/${encodeURIComponent(Q)}/pause`,void 0,W);break}case"resume_campaign":{let W=w.companyId,Q=Z("resume_campaign",w,"campaignId"),G=zw("resume_campaign",w,"spreadOverHours",1,72);$=await A("POST",`/api/v1/campaigns/${encodeURIComponent(Q)}/resume`,{...G!==void 0&&{spreadOverHours:G}},W);break}case"delete_campaign":{let W=w.companyId,Q=Z("delete_campaign",w,"campaignId");$=await A("DELETE",`/api/v1/campaigns/${encodeURIComponent(Q)}`,void 0,W);break}case"duplicate_campaign":{let W=w.companyId,Q=Z("duplicate_campaign",w,"campaignId"),G=Ub("duplicate_campaign",w,"mode",["campaign","ab_test","variant"]),D=P(w,"variantId");if(G==="variant"&&D===void 0)throw Error("`variantId` is required when calling `duplicate_campaign` with mode `variant`.");$=await A("POST",`/api/v1/campaigns/${encodeURIComponent(Q)}/duplicate`,{...G!==void 0&&{mode:G},...D!==void 0&&{variantId:D}},W);break}case"resend_campaign_to_non_openers":{let W=w.companyId,Q=Z("resend_campaign_to_non_openers",w,"campaignId");$=await A("POST",`/api/v1/campaigns/${encodeURIComponent(Q)}/resend-to-non-openers`,void 0,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function _z(b,w){let $;switch(b){case"list_forms":{let W=w.companyId;$=await A("GET","/api/v1/forms",void 0,W);break}case"create_form":{let W=w.companyId,Q=Z("create_form",w,"name"),G=Array.isArray(w.listIds)?w.listIds.filter((Y)=>typeof Y==="string").map((Y)=>Y.trim()).filter(Boolean):[];if(G.length===0)throw Error("`listIds` must contain at least one list ID when calling `create_form`.");let D=Ub("create_form",w,"duplicateStrategy",["skip","merge","overwrite"]),X={name:Q,listIds:G};for(let Y of["tagIds","buttonText","headline","description","successMessage","redirectUrl","showFirstName","showLastName"])if(w[Y]!==void 0)X[Y]=w[Y];if(D!==void 0)X.duplicateStrategy=D;$=await A("POST","/api/v1/forms",X,W);break}case"get_form_embed":{let W=w.companyId,Q=Z("get_form_embed",w,"formId");$=await A("GET",`/api/v1/forms/embed/${encodeURIComponent(Q)}`,void 0,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}function l$(b,w,$,W,Q){let G=b[w];if(G===void 0)return;if(typeof G!=="number"||!Number.isFinite(G)||G<$||G>W||Q&&!Number.isInteger(G))throw Error(`\`${w}\` must be a ${Q?"integer":"number"} between ${$} and ${W} when calling \`upload_image_asset\`.`);return G}async function Sz(b,w){if(b!=="upload_image_asset")return{handled:!1,result:void 0};let $=P(w,"filePath"),W=P(w,"imageBase64");if($===void 0===(W===void 0))throw Error("Provide either `filePath` or `imageBase64` (not both) when calling `upload_image_asset`.");let Q=P(w,"filename");if(W!==void 0&&Q===void 0)throw Error("`filename` is required with `imageBase64` when calling `upload_image_asset`.");let G=l$(w,"sourceWidth",1,20000,!0),D=l$(w,"sourceHeight",1,20000,!0);if(G===void 0!==(D===void 0))throw Error("Provide both `sourceWidth` and `sourceHeight` when calling `upload_image_asset`.");let X=l$(w,"displayWidthPercent",1,100,!1)??100,Y=l$(w,"cropHeight",1,2000,!0),H=P(w,"objectFit");if(H!==void 0&&H!=="cover"&&H!=="contain")throw Error("`objectFit` must be 'cover' or 'contain' when calling `upload_image_asset`.");if(H!==void 0&&Y===void 0)throw Error("`objectFit` can only be used with `cropHeight` when calling `upload_image_asset`.");let J=P(w,"align");if(J!==void 0&&!["left","center","right"].includes(J))throw Error("`align` must be 'left', 'center', or 'right' when calling `upload_image_asset`.");let z=typeof w.altText==="string"?w.altText.trim():void 0;if(z!==void 0&&z.length>500)throw Error("`altText` must be 500 characters or fewer when calling `upload_image_asset`.");let O=await sJ({companyId:P(w,"companyId"),filePath:$,imageBase64:W,filename:Q,contentType:P(w,"contentType"),altText:z,sourceWidth:G,sourceHeight:D}),q={type:"image",src:O.url,alt:O.altText??"",width:X,widthType:"percent",...Y!==void 0&&{height:Y,objectFit:H??"cover"},...J!==void 0&&{align:J}};return{handled:!0,result:{success:!0,asset:O,imageBlock:q,message:"Insert imageBlock into the target email's blocks array with its create or update tool."}}}async function Rz(b,w){let $;switch(b){case"list_landing_pages":{let W=w.companyId;$=await A("GET","/api/v1/landing-pages",void 0,W);break}case"get_landing_page":{let W=w.companyId;$=await A("GET",`/api/v1/landing-pages/${w.landingPageId}`,void 0,W);break}case"create_landing_page":{let W=w.companyId,Q=new Set(["companyId","name","slug","template","content"]),G=Object.keys(w).filter((D)=>!Q.has(D));if(G.length>0)throw Error(`\`create_landing_page\` accepts only \`name\`, \`slug\`, \`template\`, and \`content\` fields. Unsupported field${G.length===1?"":"s"}: ${G.map((D)=>`\`${D}\``).join(", ")}.`);$=await A("POST","/api/v1/landing-pages",{...w.name!==void 0&&{name:w.name},...w.slug!==void 0&&{slug:w.slug},...w.template!==void 0&&{template:w.template},...w.content!==void 0&&{content:w.content}},W);break}case"update_landing_page":{let W=w.companyId,Q=n$("update_landing_page",w,{requireUpdate:!0});$=await A("PUT",`/api/v1/landing-pages/${w.landingPageId}`,Q,W);break}case"publish_landing_page":{let W=w.companyId,Q=n$("publish_landing_page",w,{requireUpdate:!1});$=await A("POST",`/api/v1/landing-pages/${w.landingPageId}/publish`,Q,W);break}case"unpublish_landing_page":{let W=w.companyId,Q=n$("unpublish_landing_page",w,{requireUpdate:!1});$=await A("POST",`/api/v1/landing-pages/${w.landingPageId}/unpublish`,Q,W);break}case"delete_landing_page":{let W=w.companyId;$=await A("DELETE",`/api/v1/landing-pages/${w.landingPageId}`,void 0,W);break}case"connect_landing_page_domain":{let W=w.companyId;$=await A("POST","/api/v1/landing-pages/domain",{domain:w.domain},W);break}case"update_landing_page_domain_settings":{let W=w.companyId,Q=fJ(w);$=await A("PUT","/api/v1/landing-pages/domain",Q,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function vz(b,w){let $;switch(b){case"list_products":{let W=w.companyId,Q=new URLSearchParams;if(typeof w.provider==="string"&&w.provider.trim())Q.set("provider",w.provider.trim());if(typeof w.search==="string"&&w.search.trim())Q.set("search",w.search.trim());let G=Q.size>0?`?${Q.toString()}`:"";$=await A("GET",`/api/v1/products${G}`,void 0,W);break}case"upsert_products":{let W=w.companyId;if(!Array.isArray(w.products)||w.products.length===0)throw Error("`products` must be a non-empty array when calling `upsert_products`.");$=await A("POST","/api/v1/products",{products:w.products},W);break}case"delete_product":{let W=w.companyId,Q=Z("delete_product",w,"productId");$=await A("DELETE",`/api/v1/products/${encodeURIComponent(Q)}`,void 0,W);break}case"attach_product_file":{let W=w.companyId,Q=Z("attach_product_file",w,"productId"),G=P(w,"url"),D=P(w,"filePath");if(G===void 0===(D===void 0))throw Error("Provide either `url` or `filePath` (not both) when calling `attach_product_file`.");let X;if(D!==void 0){let Y=await lJ(D,W);X={url:Y.url,source:"upload",fileName:P(w,"fileName")??Y.fileName,fileSizeBytes:Y.fileSizeBytes,mimeType:Y.mimeType}}else{X={url:G};let Y=P(w,"fileName");if(Y)X.fileName=Y}$=await A("PUT",`/api/v1/products/${encodeURIComponent(Q)}/delivery`,X,W);break}case"remove_product_file":{let W=w.companyId,Q=Z("remove_product_file",w,"productId");$=await A("DELETE",`/api/v1/products/${encodeURIComponent(Q)}/delivery`,void 0,W);break}case"sync_products":{let W=w.companyId;$=await A("POST","/api/v1/products/sync",void 0,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}var kz=80;function RM(b){let w=b.trim().replace(/\s+/g," ");if(w.length<=kz)return w;return`${w.slice(0,kz-3).trimEnd()}...`}async function _W(b,w){let $;switch(b){case"generate_sequence":{let W=Z("generate_sequence",w,"goal"),Q=typeof w.name==="string"&&w.name.trim().length>0?w.name.trim():void 0,D=(await _W("create_sequence",{...w,goal:W,name:Q??RM(W),trigger:"contact_added",durationDays:w.durationDays??14})).result;return{handled:!0,result:typeof D==="object"&&D!==null?{...D,deprecated:!0,deprecationMessage:"generate_sequence is deprecated. Use create_sequence for new integrations."}:D}}case"list_sequences":{let W=w.companyId;$=await A("GET","/api/v1/sequences",void 0,W);break}case"get_sequence":{let W=w.companyId;$=await A("GET",`/api/v1/sequences/${w.sequenceId}`,void 0,W);break}case"create_sequence":{let W=w.companyId;if(w.fromEmail!==void 0&&w.senderProfileId!==void 0)throw Error("Provide either `fromEmail` or `senderProfileId` when calling `create_sequence`, not both.");if(w.replyTo!==void 0&&w.replyProfileId!==void 0)throw Error("Provide either `replyTo` or `replyProfileId` when calling `create_sequence`, not both.");if(w.fromName!==void 0&&w.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `create_sequence`.");if(w.replyToName!==void 0&&w.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `create_sequence`.");let Q=Array.isArray(w.steps)&&w.steps.length>0,G=await A("POST","/api/v1/sequences",w,W);if(!G.success){$=G;break}let D=G.sequence.id;if(Q){let z=await A("GET",`/api/v1/sequences/${D}`,void 0,W);if(z.success)$={...G,success:!0,sequence:z.sequence,message:`Sequence "${z.sequence.name}" created with explicit steps. Review it before enabling.${G.eventTrackingCode?" Add the custom event feed using eventTrackingCode and eventTracking before enabling.":""}`};else $=z;break}let X=7,Y=0,H="pending";while(H!=="complete"&&Y<X){let z=await A("GET",`/api/v1/sequences/${D}`,void 0,W);if(z.success)H=z.sequence.enrichmentStatus;if(Y++,H!=="complete"&&Y<X)await new Promise((O)=>setTimeout(O,20000))}let J=await A("GET",`/api/v1/sequences/${D}`,void 0,W);if(J.success)$={...G,success:!0,sequence:J.sequence,message:J.sequence.enrichmentStatus==="complete"?`Sequence "${J.sequence.name}" created with ${J.sequence.emailCount} AI-generated emails. The sequence is ready to review and enable.${G.eventTrackingCode?" Add the custom event feed using eventTrackingCode and eventTracking before enabling.":""}`:`Sequence "${J.sequence.name}" created. Email enrichment is still in progress (${J.sequence.enrichedCount}/${J.sequence.emailCount} emails generated). You can check status with get_sequence.${G.eventTrackingCode?" Add the custom event feed using eventTrackingCode and eventTracking before enabling.":""}`};else $=J;break}case"update_sequence":{let W=w.companyId,Q=_J(w);$=await A("PUT",`/api/v1/sequences/${w.sequenceId}`,Q,W);break}case"update_sequence_node":{let W=w.companyId,Q=Z("update_sequence_node",w,"sequenceId"),G=RJ(w);$=await A("PUT",`/api/v1/sequences/${Q}`,G,W);break}case"update_sequence_nodes":{let W=w.companyId,Q=Z("update_sequence_nodes",w,"sequenceId"),G=vJ(w);$=await A("PUT",`/api/v1/sequences/${Q}`,G,W);break}case"edit_sequence_graph":{let W=w.companyId,Q=kJ(w);$=await A("PUT",`/api/v1/sequences/${w.sequenceId}`,Q,W);break}case"insert_sequence_step":{let W=w.companyId,Q=CJ(w);$=await A("PUT",`/api/v1/sequences/${w.sequenceId}`,Q,W);break}case"enable_sequence":{let W=w.companyId;$=await A("POST",`/api/v1/sequences/${w.sequenceId}/enable`,void 0,W);break}case"disable_sequence":{let W=w.companyId;$=await A("POST",`/api/v1/sequences/${w.sequenceId}/disable`,void 0,W);break}case"pause_sequence_enrollments":{let W=w.companyId;$=await A("POST",`/api/v1/sequences/${w.sequenceId}/pause-enrollments`,void 0,W);break}case"resume_sequence_enrollments":{let W=w.companyId;$=await A("POST",`/api/v1/sequences/${w.sequenceId}/resume-enrollments`,void 0,W);break}case"enroll_subscribers_in_sequence":{let W=w.companyId,Q=Z("enroll_subscribers_in_sequence",w,"sequenceId"),G=iJ(w);$=await A("POST",`/api/v1/sequences/${encodeURIComponent(Q)}/enroll`,G,W);break}case"cancel_sequence_enrollments":{let W=w.companyId,Q=uJ(w);$=await A("POST",`/api/v1/sequences/${w.sequenceId}/enrollments/cancel`,Q,W);break}case"delete_sequence":{let W=w.companyId;$=await A("DELETE",`/api/v1/sequences/${w.sequenceId}`,void 0,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function Cz(b,w){let $;switch(b){case"add_subscriber":{let W=w.companyId,Q=Aw("add_subscriber",w);$=await A("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,...w.status!==void 0&&{status:w.status},...w.optInMode!==void 0&&{optInMode:w.optInMode}},W);break}case"update_subscriber":{let W=w.companyId,Q=Aw("update_subscriber",w),G=await Y0(Q,W),D=Array.isArray(G.subscriber.tags)?G.subscriber.tags.filter((z)=>typeof z==="string"):[],X=Array.isArray(w.addTags)?w.addTags.filter((z)=>typeof z==="string"&&z.trim()!=="").map(MW):[],Y=new Set(Array.isArray(w.removeTags)?w.removeTags.filter((z)=>typeof z==="string"&&z.trim()!=="").map(MW):[]),H=D.filter((z)=>!Y.has(z));for(let z of X)if(!H.includes(z))H.push(z);let J={};if(Q.email&&Q.externalId)J.externalId=Q.externalId;if(w.firstName!==void 0)J.firstName=w.firstName;if(w.lastName!==void 0)J.lastName=w.lastName;if(y(w.attributes))J.customAttributes={...y(G.subscriber.customAttributes)?G.subscriber.customAttributes:{},...w.attributes};if(w.addTags||w.removeTags)J.tags=H;$=await A("PATCH",m$(Q),J,W);break}case"remove_subscriber":{let W=w.companyId,Q=Aw("remove_subscriber",w),G=m$(Q);if(w.hardDelete===!0)$=await A("DELETE",G,void 0,W);else $=await A("PATCH",G,{status:"unsubscribed"},W);break}case"get_subscriber":{let W=w.companyId,Q=Aw("get_subscriber",w);$=await Y0(Q,W,{includeMachineEngagement:w.includeMachineEngagement===!0});break}case"list_subscriber_notes":{let W=w.companyId,Q=Aw("list_subscriber_notes",w);$=await A("GET",IW(Q),void 0,W);break}case"add_subscriber_note":{let W=w.companyId,Q=Aw("add_subscriber_note",w),G=typeof w.body==="string"?w.body.trim():void 0;if(!G)throw Error("`body` is required when calling `add_subscriber_note`.");if(G.length>5000)throw Error("`body` must be 5000 characters or fewer when calling `add_subscriber_note`.");$=await A("POST",IW(Q),{body:G},W);break}case"delete_subscriber_note":{let W=w.companyId,Q=typeof w.noteId==="string"?w.noteId.trim():"";if(!Q)throw Error("`noteId` is required when calling `delete_subscriber_note`.");$=await A("DELETE",`/api/v1/subscribers/notes/${encodeURIComponent(Q)}`,void 0,W);break}case"search_subscribers":{let W=w.companyId;$=await mJ(w,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function uz(b,w){if(b!=="get_recipient_suppression"&&b!=="remove_recipient_suppression")return{handled:!1,result:void 0};let $=P(w,"companyId"),W=Z(b,w,"email"),Q=P(w,"region"),G=new URLSearchParams;if(Q)G.set("region",Q);let D=`/api/v1/suppressions/${encodeURIComponent(W)}${G.size>0?`?${G}`:""}`;return{handled:!0,result:await A(b==="get_recipient_suppression"?"GET":"DELETE",D,void 0,$)}}async function xz(b,w){let $;switch(b){case"list_team_members":{let W=w.companyId;$=await A("GET","/api/v1/team",void 0,W);break}case"invite_team_member":{let W=w.companyId,Q=Z("invite_team_member",w,"email"),G=H0("invite_team_member",w,"role",["admin","viewer","restricted"]);if(w.canManageBilling!==void 0&&typeof w.canManageBilling!=="boolean")throw Error("`canManageBilling` must be a boolean when calling `invite_team_member`.");$=await A("POST","/api/v1/team/invitations",{email:Q,role:G,...w.canManageBilling!==void 0&&{canManageBilling:w.canManageBilling}},W);break}case"cancel_team_invitation":{let W=w.companyId,Q=Z("cancel_team_invitation",w,"invitationId");$=await A("DELETE",`/api/v1/team/invitations/${encodeURIComponent(Q)}`,void 0,W);break}case"list_conversations":{let W=w.companyId,Q=new URLSearchParams,G=Ub("list_conversations",w,"status",["open","closed","all"]);if(G)Q.set("status",G);let D=P(w,"search");if(D)Q.set("search",D);if(w.unread!==void 0){if(typeof w.unread!=="boolean")throw Error("`unread` must be a boolean when calling `list_conversations`.");if(w.unread)Q.set("unread","true")}if(w.page!==void 0){if(typeof w.page!=="number"||!Number.isInteger(w.page)||w.page<1)throw Error("`page` must be a positive integer when calling `list_conversations`.");Q.set("page",String(w.page))}let X=zw("list_conversations",w,"limit",1,100);if(X!==void 0)Q.set("limit",String(X));$=await A("GET",`/api/v1/conversations${Q.size>0?`?${Q}`:""}`,void 0,W);break}case"get_conversation":{let W=w.companyId,Q=Z("get_conversation",w,"conversationId");$=await A("GET",`/api/v1/conversations/${encodeURIComponent(Q)}`,void 0,W);break}case"reply_to_conversation":{let W=w.companyId,Q=Z("reply_to_conversation",w,"conversationId"),G=Ub("reply_to_conversation",w,"type",["outbound","note"])??"outbound",D=P(w,"subject"),X=P(w,"bodyText"),Y=P(w,"bodyHtml");if(G==="outbound"&&X===void 0&&Y===void 0)throw Error("Provide `bodyText` or `bodyHtml` when calling `reply_to_conversation` with an outbound message.");$=await A("POST",`/api/v1/conversations/${encodeURIComponent(Q)}/messages`,{type:G,...D!==void 0&&{subject:D},...X!==void 0&&{bodyText:X},...Y!==void 0&&{bodyHtml:Y}},W);break}case"update_conversation_status":{let W=w.companyId,Q=Z("update_conversation_status",w,"conversationId"),G=H0("update_conversation_status",w,"status",["open","closed"]);$=await A("POST",`/api/v1/conversations/${encodeURIComponent(Q)}/status`,{status:G},W);break}case"mark_conversation_read":{let W=w.companyId,Q=Z("mark_conversation_read",w,"conversationId");$=await A("POST",`/api/v1/conversations/${encodeURIComponent(Q)}/read`,void 0,W);break}case"list_webhooks":{let W=w.companyId;$=await A("GET","/api/v1/webhooks",void 0,W);break}case"create_webhook":{let W=w.companyId,Q=Z("create_webhook",w,"name"),G=Z("create_webhook",w,"url"),D=jW("create_webhook",w);$=await A("POST","/api/v1/webhooks",{name:Q,url:G,...D!==void 0&&{events:D}},W);break}case"update_webhook":{let W=w.companyId,Q=Z("update_webhook",w,"webhookId"),G=P(w,"name"),D=P(w,"url"),X=jW("update_webhook",w),Y=Ub("update_webhook",w,"status",["enabled","disabled"]);if(G===void 0&&D===void 0&&X===void 0&&Y===void 0)throw Error("Provide at least one of `name`, `url`, `events`, or `status` when calling `update_webhook`.");$=await A("PATCH",`/api/v1/webhooks/${encodeURIComponent(Q)}`,{...G!==void 0&&{name:G},...D!==void 0&&{url:D},...X!==void 0&&{events:X},...Y!==void 0&&{status:Y}},W);break}case"delete_webhook":{let W=w.companyId,Q=Z("delete_webhook",w,"webhookId");$=await A("DELETE",`/api/v1/webhooks/${encodeURIComponent(Q)}`,void 0,W);break}case"test_webhook":{let W=w.companyId,Q=Z("test_webhook",w,"webhookId");$=await A("POST",`/api/v1/webhooks/${encodeURIComponent(Q)}/test`,void 0,W);break}case"list_webhook_deliveries":{let W=w.companyId,Q=Z("list_webhook_deliveries",w,"webhookId"),G=zw("list_webhook_deliveries",w,"limit",1,100),D=new URLSearchParams;if(G!==void 0)D.set("limit",String(G));$=await A("GET",`/api/v1/webhooks/${encodeURIComponent(Q)}/deliveries${D.size>0?`?${D}`:""}`,void 0,W);break}case"replay_webhook_delivery":{let W=w.companyId,Q=Z("replay_webhook_delivery",w,"webhookId"),G=Z("replay_webhook_delivery",w,"deliveryId");$=await A("POST",`/api/v1/webhooks/${encodeURIComponent(Q)}/deliveries/${encodeURIComponent(G)}/replay`,void 0,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}var yz=[jz,Cz,uz,vz,Tz,Ez,_z,Rz,Sz,_W,Nz,xz,Vz];var hz=Zz.map(aJ).map(MJ);async function fz(b,w){try{let $,W=!1;for(let G of yz){let D=await G(b,w);if(D.handled){$=D.result,W=!0;break}}if(!W)throw Error(`Unknown tool: ${b}`);let Q=nJ($);if(Q)throw Q;return $=await dJ(b,w,$),{structuredContent:bz($),content:[{type:"text",text:JSON.stringify($,null,2)}]}}catch($){return{isError:!0,content:[{type:"text",text:Ow($)}]}}}async function cz(b,w,$){let W=w.getRequestContext?.(b)??{};try{return await r$(W,$)}finally{await w.onRequestContextUpdated?.(W,b)}}function SW(b={}){let w=new YW({name:"sequenzy",version:LJ.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(t4,async()=>{return{tools:hz}}),w.setRequestHandler(C1,async($,W)=>{let{name:Q,arguments:G}=$.params;return cz(W,b,()=>fz(Q,G??{}))}),w.setRequestHandler(g4,async()=>{return{resources:PJ}}),w.setRequestHandler(i4,async($,W)=>{let{uri:Q}=$.params;return cz(W,b,()=>FJ(Q))}),w}import gz from"node:process";class RW{append(b){this._buffer=this._buffer?Buffer.concat([this._buffer,b]):b}readMessage(){if(!this._buffer)return null;let b=this._buffer.indexOf(`
53
53
  `);if(b===-1)return null;let w=this._buffer.toString("utf8",0,b).replace(/\r$/,"");return this._buffer=this._buffer.subarray(b+1),vM(w)}clear(){this._buffer=void 0}}function vM(b){return jG.parse(JSON.parse(b))}function nz(b){return JSON.stringify(b)+`
54
54
  `}class vW{constructor(b=gz.stdin,w=gz.stdout){this._stdin=b,this._stdout=w,this._readBuffer=new RW,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 $=nz(b);if(this._stdout.write($))w();else this._stdout.once("drain",w)})}}async function kM(){mW(),hW();let b=SW(),w=new vW;await b.connect(w),console.error("Sequenzy MCP server running on stdio")}kM().catch((b)=>{console.error(Ow(b)),process.exit(1)});export{r$ as withMcpRequestContext,A0 as setSelectedCompanyId,qw as getSelectedCompanyId,SW as createSequenzyMcpServer,A as apiRequest};