@sequenzy/mcp 0.0.101 → 0.0.102

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 qH=Object.create;var{getPrototypeOf:OH,defineProperty:TQ,getOwnPropertyNames:MH}=Object;var VH=Object.prototype.hasOwnProperty;function ZH(Q){return this[Q]}var NH,wH,BX=(Q,Y,X)=>{var W=Q!=null&&typeof Q==="object";if(W){var G=Y?NH??=new WeakMap:wH??=new WeakMap,$=G.get(Q);if($)return $}X=Q!=null?qH(OH(Q)):{};let z=Y||!Q||!Q.__esModule?TQ(X,"default",{value:Q,enumerable:!0}):X;for(let J of MH(Q))if(!VH.call(z,J))TQ(z,J,{get:ZH.bind(Q,J),enumerable:!0});if(W)G.set(Q,z);return z};var P=(Q,Y)=>()=>(Y||Q((Y={exports:{}}).exports,Y),Y.exports);var PH=(Q)=>Q;function bH(Q,Y){this[Q]=PH.bind(null,Y)}var LX=(Q,Y)=>{for(var X in Y)TQ(Q,X,{get:Y[X],enumerable:!0,configurable:!0,set:bH.bind(Y,X)})};var R4=P((D$)=>{Object.defineProperty(D$,"__esModule",{value:!0});D$.regexpCode=D$.getEsmExportName=D$.getProperty=D$.safeStringify=D$.stringify=D$.strConcat=D$.addCodeArg=D$.str=D$._=D$.nil=D$._Code=D$.Name=D$.IDENTIFIER=D$._CodeOrName=void 0;class y6{}D$._CodeOrName=y6;D$.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class c1 extends y6{constructor(Q){super();if(!D$.IDENTIFIER.test(Q))throw Error("CodeGen: name must be a valid identifier");this.str=Q}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}D$.Name=c1;class _0 extends y6{constructor(Q){super();this._items=typeof Q==="string"?[Q]:Q}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let Q=this._items[0];return Q===""||Q==='""'}get str(){var Q;return(Q=this._str)!==null&&Q!==void 0?Q:this._str=this._items.reduce((Y,X)=>`${Y}${X}`,"")}get names(){var Q;return(Q=this._names)!==null&&Q!==void 0?Q:this._names=this._items.reduce((Y,X)=>{if(X instanceof c1)Y[X.str]=(Y[X.str]||0)+1;return Y},{})}}D$._Code=_0;D$.nil=new _0("");function U$(Q,...Y){let X=[Q[0]],W=0;while(W<Y.length)y9(X,Y[W]),X.push(Q[++W]);return new _0(X)}D$._=U$;var g9=new _0("+");function K$(Q,...Y){let X=[S4(Q[0])],W=0;while(W<Y.length)X.push(g9),y9(X,Y[W]),X.push(g9,S4(Q[++W]));return dU(X),new _0(X)}D$.str=K$;function y9(Q,Y){if(Y instanceof _0)Q.push(...Y._items);else if(Y instanceof c1)Q.push(Y);else Q.push(aU(Y))}D$.addCodeArg=y9;function dU(Q){let Y=1;while(Y<Q.length-1){if(Q[Y]===g9){let X=oU(Q[Y-1],Q[Y+1]);if(X!==void 0){Q.splice(Y-1,3,X);continue}Q[Y++]="+"}Y++}}function oU(Q,Y){if(Y==='""')return Q;if(Q==='""')return Y;if(typeof Q=="string"){if(Y instanceof c1||Q[Q.length-1]!=='"')return;if(typeof Y!="string")return`${Q.slice(0,-1)}${Y}"`;if(Y[0]==='"')return Q.slice(0,-1)+Y.slice(1);return}if(typeof Y=="string"&&Y[0]==='"'&&!(Q instanceof c1))return`"${Q}${Y.slice(1)}`;return}function tU(Q,Y){return Y.emptyStr()?Q:Q.emptyStr()?Y:K$`${Q}${Y}`}D$.strConcat=tU;function aU(Q){return typeof Q=="number"||typeof Q=="boolean"||Q===null?Q:S4(Array.isArray(Q)?Q.join(","):Q)}function sU(Q){return new _0(S4(Q))}D$.stringify=sU;function S4(Q){return JSON.stringify(Q).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}D$.safeStringify=S4;function eU(Q){return typeof Q=="string"&&D$.IDENTIFIER.test(Q)?new _0(`.${Q}`):U$`[${Q}]`}D$.getProperty=eU;function QK(Q){if(typeof Q=="string"&&D$.IDENTIFIER.test(Q))return new _0(`${Q}`);throw Error(`CodeGen: invalid export name: ${Q}, use explicit $id name mapping`)}D$.getEsmExportName=QK;function YK(Q){return new _0(Q.toString())}D$.regexpCode=YK});var l9=P((q$)=>{Object.defineProperty(q$,"__esModule",{value:!0});q$.ValueScope=q$.ValueScopeName=q$.Scope=q$.varKinds=q$.UsedValueState=void 0;var Z0=R4();class L$ extends Error{constructor(Q){super(`CodeGen: "code" for ${Q} not defined`);this.value=Q.value}}var h6;(function(Q){Q[Q.Started=0]="Started",Q[Q.Completed=1]="Completed"})(h6||(q$.UsedValueState=h6={}));q$.varKinds={const:new Z0.Name("const"),let:new Z0.Name("let"),var:new Z0.Name("var")};class h9{constructor({prefixes:Q,parent:Y}={}){this._names={},this._prefixes=Q,this._parent=Y}toName(Q){return Q instanceof Z0.Name?Q:this.name(Q)}name(Q){return new Z0.Name(this._newName(Q))}_newName(Q){let Y=this._names[Q]||this._nameGroup(Q);return`${Q}${Y.index++}`}_nameGroup(Q){var Y,X;if(((X=(Y=this._parent)===null||Y===void 0?void 0:Y._prefixes)===null||X===void 0?void 0:X.has(Q))||this._prefixes&&!this._prefixes.has(Q))throw Error(`CodeGen: prefix "${Q}" is not allowed in this scope`);return this._names[Q]={prefix:Q,index:0}}}q$.Scope=h9;class f9 extends Z0.Name{constructor(Q,Y){super(Y);this.prefix=Q}setValue(Q,{property:Y,itemIndex:X}){this.value=Q,this.scopePath=Z0._`.${new Z0.Name(Y)}[${X}]`}}q$.ValueScopeName=f9;var LK=Z0._`\n`;class F$ extends h9{constructor(Q){super(Q);this._values={},this._scope=Q.scope,this.opts={...Q,_n:Q.lines?LK:Z0.nil}}get(){return this._scope}name(Q){return new f9(Q,this._newName(Q))}value(Q,Y){var X;if(Y.ref===void 0)throw Error("CodeGen: ref must be passed in value");let W=this.toName(Q),{prefix:G}=W,$=(X=Y.key)!==null&&X!==void 0?X:Y.ref,z=this._values[G];if(z){let A=z.get($);if(A)return A}else z=this._values[G]=new Map;z.set($,W);let J=this._scope[G]||(this._scope[G]=[]),H=J.length;return J[H]=Y.ref,W.setValue(Y,{property:G,itemIndex:H}),W}getValue(Q,Y){let X=this._values[Q];if(!X)return;return X.get(Y)}scopeRefs(Q,Y=this._values){return this._reduceValues(Y,(X)=>{if(X.scopePath===void 0)throw Error(`CodeGen: name "${X}" has no value`);return Z0._`${Q}${X.scopePath}`})}scopeCode(Q=this._values,Y,X){return this._reduceValues(Q,(W)=>{if(W.value===void 0)throw Error(`CodeGen: name "${W}" has no value`);return W.value.code},Y,X)}_reduceValues(Q,Y,X={},W){let G=Z0.nil;for(let $ in Q){let z=Q[$];if(!z)continue;let J=X[$]=X[$]||new Map;z.forEach((H)=>{if(J.has(H))return;J.set(H,h6.Started);let A=Y(H);if(A){let U=this.opts.es5?q$.varKinds.var:q$.varKinds.const;G=Z0._`${G}${U} ${H} = ${A};${this.opts._n}`}else if(A=W===null||W===void 0?void 0:W(H))G=Z0._`${G}${A}${this.opts._n}`;else throw new L$(H);J.set(H,h6.Completed)})}return G}}q$.ValueScope=F$});var g=P((N0)=>{Object.defineProperty(N0,"__esModule",{value:!0});N0.or=N0.and=N0.not=N0.CodeGen=N0.operators=N0.varKinds=N0.ValueScopeName=N0.ValueScope=N0.Scope=N0.Name=N0.regexpCode=N0.stringify=N0.getProperty=N0.nil=N0.strConcat=N0.str=N0._=void 0;var f=R4(),g0=l9(),B1=R4();Object.defineProperty(N0,"_",{enumerable:!0,get:function(){return B1._}});Object.defineProperty(N0,"str",{enumerable:!0,get:function(){return B1.str}});Object.defineProperty(N0,"strConcat",{enumerable:!0,get:function(){return B1.strConcat}});Object.defineProperty(N0,"nil",{enumerable:!0,get:function(){return B1.nil}});Object.defineProperty(N0,"getProperty",{enumerable:!0,get:function(){return B1.getProperty}});Object.defineProperty(N0,"stringify",{enumerable:!0,get:function(){return B1.stringify}});Object.defineProperty(N0,"regexpCode",{enumerable:!0,get:function(){return B1.regexpCode}});Object.defineProperty(N0,"Name",{enumerable:!0,get:function(){return B1.Name}});var i6=l9();Object.defineProperty(N0,"Scope",{enumerable:!0,get:function(){return i6.Scope}});Object.defineProperty(N0,"ValueScope",{enumerable:!0,get:function(){return i6.ValueScope}});Object.defineProperty(N0,"ValueScopeName",{enumerable:!0,get:function(){return i6.ValueScopeName}});Object.defineProperty(N0,"varKinds",{enumerable:!0,get:function(){return i6.varKinds}});N0.operators={GT:new f._Code(">"),GTE:new f._Code(">="),LT:new f._Code("<"),LTE:new f._Code("<="),EQ:new f._Code("==="),NEQ:new f._Code("!=="),NOT:new f._Code("!"),OR:new f._Code("||"),AND:new f._Code("&&"),ADD:new f._Code("+")};class L1{optimizeNodes(){return this}optimizeNames(Q,Y){return this}}class M$ extends L1{constructor(Q,Y,X){super();this.varKind=Q,this.name=Y,this.rhs=X}render({es5:Q,_n:Y}){let X=Q?g0.varKinds.var:this.varKind,W=this.rhs===void 0?"":` = ${this.rhs}`;return`${X} ${this.name}${W};`+Y}optimizeNames(Q,Y){if(!Q[this.name.str])return;if(this.rhs)this.rhs=i1(this.rhs,Q,Y);return this}get names(){return this.rhs instanceof f._CodeOrName?this.rhs.names:{}}}class p9 extends L1{constructor(Q,Y,X){super();this.lhs=Q,this.rhs=Y,this.sideEffects=X}render({_n:Q}){return`${this.lhs} = ${this.rhs};`+Q}optimizeNames(Q,Y){if(this.lhs instanceof f.Name&&!Q[this.lhs.str]&&!this.sideEffects)return;return this.rhs=i1(this.rhs,Q,Y),this}get names(){let Q=this.lhs instanceof f.Name?{}:{...this.lhs.names};return p6(Q,this.rhs)}}class V$ extends p9{constructor(Q,Y,X,W){super(Q,X,W);this.op=Y}render({_n:Q}){return`${this.lhs} ${this.op}= ${this.rhs};`+Q}}class Z$ extends L1{constructor(Q){super();this.label=Q,this.names={}}render({_n:Q}){return`${this.label}:`+Q}}class N$ extends L1{constructor(Q){super();this.label=Q,this.names={}}render({_n:Q}){return`break${this.label?` ${this.label}`:""};`+Q}}class w$ extends L1{constructor(Q){super();this.error=Q}render({_n:Q}){return`throw ${this.error};`+Q}get names(){return this.error.names}}class P$ extends L1{constructor(Q){super();this.code=Q}render({_n:Q}){return`${this.code};`+Q}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(Q,Y){return this.code=i1(this.code,Q,Y),this}get names(){return this.code instanceof f._CodeOrName?this.code.names:{}}}class n6 extends L1{constructor(Q=[]){super();this.nodes=Q}render(Q){return this.nodes.reduce((Y,X)=>Y+X.render(Q),"")}optimizeNodes(){let{nodes:Q}=this,Y=Q.length;while(Y--){let X=Q[Y].optimizeNodes();if(Array.isArray(X))Q.splice(Y,1,...X);else if(X)Q[Y]=X;else Q.splice(Y,1)}return Q.length>0?this:void 0}optimizeNames(Q,Y){let{nodes:X}=this,W=X.length;while(W--){let G=X[W];if(G.optimizeNames(Q,Y))continue;MK(Q,G.names),X.splice(W,1)}return X.length>0?this:void 0}get names(){return this.nodes.reduce((Q,Y)=>E1(Q,Y.names),{})}}class F1 extends n6{render(Q){return"{"+Q._n+super.render(Q)+"}"+Q._n}}class b$ extends n6{}class C4 extends F1{}C4.kind="else";class Q1 extends F1{constructor(Q,Y){super(Y);this.condition=Q}render(Q){let Y=`if(${this.condition})`+super.render(Q);if(this.else)Y+="else "+this.else.render(Q);return Y}optimizeNodes(){super.optimizeNodes();let Q=this.condition;if(Q===!0)return this.nodes;let Y=this.else;if(Y){let X=Y.optimizeNodes();Y=this.else=Array.isArray(X)?new C4(X):X}if(Y){if(Q===!1)return Y instanceof Q1?Y:Y.nodes;if(this.nodes.length)return this;return new Q1(S$(Q),Y instanceof Q1?[Y]:Y.nodes)}if(Q===!1||!this.nodes.length)return;return this}optimizeNames(Q,Y){var X;if(this.else=(X=this.else)===null||X===void 0?void 0:X.optimizeNames(Q,Y),!(super.optimizeNames(Q,Y)||this.else))return;return this.condition=i1(this.condition,Q,Y),this}get names(){let Q=super.names;if(p6(Q,this.condition),this.else)E1(Q,this.else.names);return Q}}Q1.kind="if";class p1 extends F1{}p1.kind="for";class j$ extends p1{constructor(Q){super();this.iteration=Q}render(Q){return`for(${this.iteration})`+super.render(Q)}optimizeNames(Q,Y){if(!super.optimizeNames(Q,Y))return;return this.iteration=i1(this.iteration,Q,Y),this}get names(){return E1(super.names,this.iteration.names)}}class I$ extends p1{constructor(Q,Y,X,W){super();this.varKind=Q,this.name=Y,this.from=X,this.to=W}render(Q){let Y=Q.es5?g0.varKinds.var:this.varKind,{name:X,from:W,to:G}=this;return`for(${Y} ${X}=${W}; ${X}<${G}; ${X}++)`+super.render(Q)}get names(){let Q=p6(super.names,this.from);return p6(Q,this.to)}}class m9 extends p1{constructor(Q,Y,X,W){super();this.loop=Q,this.varKind=Y,this.name=X,this.iterable=W}render(Q){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(Q)}optimizeNames(Q,Y){if(!super.optimizeNames(Q,Y))return;return this.iterable=i1(this.iterable,Q,Y),this}get names(){return E1(super.names,this.iterable.names)}}class f6 extends F1{constructor(Q,Y,X){super();this.name=Q,this.args=Y,this.async=X}render(Q){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(Q)}}f6.kind="func";class l6 extends n6{render(Q){return"return "+super.render(Q)}}l6.kind="return";class E$ extends F1{render(Q){let Y="try"+super.render(Q);if(this.catch)Y+=this.catch.render(Q);if(this.finally)Y+=this.finally.render(Q);return Y}optimizeNodes(){var Q,Y;return super.optimizeNodes(),(Q=this.catch)===null||Q===void 0||Q.optimizeNodes(),(Y=this.finally)===null||Y===void 0||Y.optimizeNodes(),this}optimizeNames(Q,Y){var X,W;return super.optimizeNames(Q,Y),(X=this.catch)===null||X===void 0||X.optimizeNames(Q,Y),(W=this.finally)===null||W===void 0||W.optimizeNames(Q,Y),this}get names(){let Q=super.names;if(this.catch)E1(Q,this.catch.names);if(this.finally)E1(Q,this.finally.names);return Q}}class m6 extends F1{constructor(Q){super();this.error=Q}render(Q){return`catch(${this.error})`+super.render(Q)}}m6.kind="catch";class c6 extends F1{render(Q){return"finally"+super.render(Q)}}c6.kind="finally";class T${constructor(Q,Y={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...Y,_n:Y.lines?`
3
- `:""},this._extScope=Q,this._scope=new g0.Scope({parent:Q}),this._nodes=[new b$]}toString(){return this._root.render(this.opts)}name(Q){return this._scope.name(Q)}scopeName(Q){return this._extScope.name(Q)}scopeValue(Q,Y){let X=this._extScope.value(Q,Y);return(this._values[X.prefix]||(this._values[X.prefix]=new Set)).add(X),X}getScopeValue(Q,Y){return this._extScope.getValue(Q,Y)}scopeRefs(Q){return this._extScope.scopeRefs(Q,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(Q,Y,X,W){let G=this._scope.toName(Y);if(X!==void 0&&W)this._constants[G.str]=X;return this._leafNode(new M$(Q,G,X)),G}const(Q,Y,X){return this._def(g0.varKinds.const,Q,Y,X)}let(Q,Y,X){return this._def(g0.varKinds.let,Q,Y,X)}var(Q,Y,X){return this._def(g0.varKinds.var,Q,Y,X)}assign(Q,Y,X){return this._leafNode(new p9(Q,Y,X))}add(Q,Y){return this._leafNode(new V$(Q,N0.operators.ADD,Y))}code(Q){if(typeof Q=="function")Q();else if(Q!==f.nil)this._leafNode(new P$(Q));return this}object(...Q){let Y=["{"];for(let[X,W]of Q){if(Y.length>1)Y.push(",");if(Y.push(X),X!==W||this.opts.es5)Y.push(":"),(0,f.addCodeArg)(Y,W)}return Y.push("}"),new f._Code(Y)}if(Q,Y,X){if(this._blockNode(new Q1(Q)),Y&&X)this.code(Y).else().code(X).endIf();else if(Y)this.code(Y).endIf();else if(X)throw Error('CodeGen: "else" body without "then" body');return this}elseIf(Q){return this._elseNode(new Q1(Q))}else(){return this._elseNode(new C4)}endIf(){return this._endBlockNode(Q1,C4)}_for(Q,Y){if(this._blockNode(Q),Y)this.code(Y).endFor();return this}for(Q,Y){return this._for(new j$(Q),Y)}forRange(Q,Y,X,W,G=this.opts.es5?g0.varKinds.var:g0.varKinds.let){let $=this._scope.toName(Q);return this._for(new I$(G,$,Y,X),()=>W($))}forOf(Q,Y,X,W=g0.varKinds.const){let G=this._scope.toName(Q);if(this.opts.es5){let $=Y instanceof f.Name?Y:this.var("_arr",Y);return this.forRange("_i",0,f._`${$}.length`,(z)=>{this.var(G,f._`${$}[${z}]`),X(G)})}return this._for(new m9("of",W,G,Y),()=>X(G))}forIn(Q,Y,X,W=this.opts.es5?g0.varKinds.var:g0.varKinds.const){if(this.opts.ownProperties)return this.forOf(Q,f._`Object.keys(${Y})`,X);let G=this._scope.toName(Q);return this._for(new m9("in",W,G,Y),()=>X(G))}endFor(){return this._endBlockNode(p1)}label(Q){return this._leafNode(new Z$(Q))}break(Q){return this._leafNode(new N$(Q))}return(Q){let Y=new l6;if(this._blockNode(Y),this.code(Q),Y.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(l6)}try(Q,Y,X){if(!Y&&!X)throw Error('CodeGen: "try" without "catch" and "finally"');let W=new E$;if(this._blockNode(W),this.code(Q),Y){let G=this.name("e");this._currNode=W.catch=new m6(G),Y(G)}if(X)this._currNode=W.finally=new c6,this.code(X);return this._endBlockNode(m6,c6)}throw(Q){return this._leafNode(new w$(Q))}block(Q,Y){if(this._blockStarts.push(this._nodes.length),Q)this.code(Q).endBlock(Y);return this}endBlock(Q){let Y=this._blockStarts.pop();if(Y===void 0)throw Error("CodeGen: not in self-balancing block");let X=this._nodes.length-Y;if(X<0||Q!==void 0&&X!==Q)throw Error(`CodeGen: wrong number of nodes: ${X} vs ${Q} expected`);return this._nodes.length=Y,this}func(Q,Y=f.nil,X,W){if(this._blockNode(new f6(Q,Y,X)),W)this.code(W).endFunc();return this}endFunc(){return this._endBlockNode(f6)}optimize(Q=1){while(Q-- >0)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(Q){return this._currNode.nodes.push(Q),this}_blockNode(Q){this._currNode.nodes.push(Q),this._nodes.push(Q)}_endBlockNode(Q,Y){let X=this._currNode;if(X instanceof Q||Y&&X instanceof Y)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${Y?`${Q.kind}/${Y.kind}`:Q.kind}"`)}_elseNode(Q){let Y=this._currNode;if(!(Y instanceof Q1))throw Error('CodeGen: "else" without "if"');return this._currNode=Y.else=Q,this}get _root(){return this._nodes[0]}get _currNode(){let Q=this._nodes;return Q[Q.length-1]}set _currNode(Q){let Y=this._nodes;Y[Y.length-1]=Q}}N0.CodeGen=T$;function E1(Q,Y){for(let X in Y)Q[X]=(Q[X]||0)+(Y[X]||0);return Q}function p6(Q,Y){return Y instanceof f._CodeOrName?E1(Q,Y.names):Q}function i1(Q,Y,X){if(Q instanceof f.Name)return W(Q);if(!G(Q))return Q;return new f._Code(Q._items.reduce(($,z)=>{if(z instanceof f.Name)z=W(z);if(z instanceof f._Code)$.push(...z._items);else $.push(z);return $},[]));function W($){let z=X[$.str];if(z===void 0||Y[$.str]!==1)return $;return delete Y[$.str],z}function G($){return $ instanceof f._Code&&$._items.some((z)=>z instanceof f.Name&&Y[z.str]===1&&X[z.str]!==void 0)}}function MK(Q,Y){for(let X in Y)Q[X]=(Q[X]||0)-(Y[X]||0)}function S$(Q){return typeof Q=="boolean"||typeof Q=="number"||Q===null?!Q:f._`!${c9(Q)}`}N0.not=S$;var VK=R$(N0.operators.AND);function ZK(...Q){return Q.reduce(VK)}N0.and=ZK;var NK=R$(N0.operators.OR);function wK(...Q){return Q.reduce(NK)}N0.or=wK;function R$(Q){return(Y,X)=>Y===f.nil?X:X===f.nil?Y:f._`${c9(Y)} ${Q} ${c9(X)}`}function c9(Q){return Q instanceof f.Name?Q:f._`(${Q})`}});var c=P((h$)=>{Object.defineProperty(h$,"__esModule",{value:!0});h$.checkStrictMode=h$.getErrorPath=h$.Type=h$.useFunc=h$.setEvaluated=h$.evaluatedPropsToName=h$.mergeEvaluated=h$.eachItem=h$.unescapeJsonPointer=h$.escapeJsonPointer=h$.escapeFragment=h$.unescapeFragment=h$.schemaRefOrVal=h$.schemaHasRulesButRef=h$.schemaHasRules=h$.checkUnknownRules=h$.alwaysValidSchema=h$.toHash=void 0;var r=g(),IK=R4();function EK(Q){let Y={};for(let X of Q)Y[X]=!0;return Y}h$.toHash=EK;function TK(Q,Y){if(typeof Y=="boolean")return Y;if(Object.keys(Y).length===0)return!0;return x$(Q,Y),!_$(Y,Q.self.RULES.all)}h$.alwaysValidSchema=TK;function x$(Q,Y=Q.schema){let{opts:X,self:W}=Q;if(!X.strictSchema)return;if(typeof Y==="boolean")return;let G=W.RULES.keywords;for(let $ in Y)if(!G[$])u$(Q,`unknown keyword: "${$}"`)}h$.checkUnknownRules=x$;function _$(Q,Y){if(typeof Q=="boolean")return!Q;for(let X in Q)if(Y[X])return!0;return!1}h$.schemaHasRules=_$;function SK(Q,Y){if(typeof Q=="boolean")return!Q;for(let X in Q)if(X!=="$ref"&&Y.all[X])return!0;return!1}h$.schemaHasRulesButRef=SK;function RK({topSchemaRef:Q,schemaPath:Y},X,W,G){if(!G){if(typeof X=="number"||typeof X=="boolean")return X;if(typeof X=="string")return r._`${X}`}return r._`${Q}${Y}${(0,r.getProperty)(W)}`}h$.schemaRefOrVal=RK;function CK(Q){return g$(decodeURIComponent(Q))}h$.unescapeFragment=CK;function kK(Q){return encodeURIComponent(n9(Q))}h$.escapeFragment=kK;function n9(Q){if(typeof Q=="number")return`${Q}`;return Q.replace(/~/g,"~0").replace(/\//g,"~1")}h$.escapeJsonPointer=n9;function g$(Q){return Q.replace(/~1/g,"/").replace(/~0/g,"~")}h$.unescapeJsonPointer=g$;function vK(Q,Y){if(Array.isArray(Q))for(let X of Q)Y(X);else Y(Q)}h$.eachItem=vK;function k$({mergeNames:Q,mergeToName:Y,mergeValues:X,resultToName:W}){return(G,$,z,J)=>{let H=z===void 0?$:z instanceof r.Name?($ instanceof r.Name?Q(G,$,z):Y(G,$,z),z):$ instanceof r.Name?(Y(G,z,$),$):X($,z);return J===r.Name&&!(H instanceof r.Name)?W(G,H):H}}h$.mergeEvaluated={props:k$({mergeNames:(Q,Y,X)=>Q.if(r._`${X} !== true && ${Y} !== undefined`,()=>{Q.if(r._`${Y} === true`,()=>Q.assign(X,!0),()=>Q.assign(X,r._`${X} || {}`).code(r._`Object.assign(${X}, ${Y})`))}),mergeToName:(Q,Y,X)=>Q.if(r._`${X} !== true`,()=>{if(Y===!0)Q.assign(X,!0);else Q.assign(X,r._`${X} || {}`),r9(Q,X,Y)}),mergeValues:(Q,Y)=>Q===!0?!0:{...Q,...Y},resultToName:y$}),items:k$({mergeNames:(Q,Y,X)=>Q.if(r._`${X} !== true && ${Y} !== undefined`,()=>Q.assign(X,r._`${Y} === true ? true : ${X} > ${Y} ? ${X} : ${Y}`)),mergeToName:(Q,Y,X)=>Q.if(r._`${X} !== true`,()=>Q.assign(X,Y===!0?!0:r._`${X} > ${Y} ? ${X} : ${Y}`)),mergeValues:(Q,Y)=>Q===!0?!0:Math.max(Q,Y),resultToName:(Q,Y)=>Q.var("items",Y)})};function y$(Q,Y){if(Y===!0)return Q.var("props",!0);let X=Q.var("props",r._`{}`);if(Y!==void 0)r9(Q,X,Y);return X}h$.evaluatedPropsToName=y$;function r9(Q,Y,X){Object.keys(X).forEach((W)=>Q.assign(r._`${Y}${(0,r.getProperty)(W)}`,!0))}h$.setEvaluated=r9;var v$={};function xK(Q,Y){return Q.scopeValue("func",{ref:Y,code:v$[Y.code]||(v$[Y.code]=new IK._Code(Y.code))})}h$.useFunc=xK;var i9;(function(Q){Q[Q.Num=0]="Num",Q[Q.Str=1]="Str"})(i9||(h$.Type=i9={}));function _K(Q,Y,X){if(Q instanceof r.Name){let W=Y===i9.Num;return X?W?r._`"[" + ${Q} + "]"`:r._`"['" + ${Q} + "']"`:W?r._`"/" + ${Q}`:r._`"/" + ${Q}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return X?(0,r.getProperty)(Q).toString():"/"+n9(Q)}h$.getErrorPath=_K;function u$(Q,Y,X=Q.opts.strictSchema){if(!X)return;if(Y=`strict mode: ${Y}`,X===!0)throw Error(Y);Q.self.logger.warn(Y)}h$.checkStrictMode=u$});var Y1=P((l$)=>{Object.defineProperty(l$,"__esModule",{value:!0});var F0=g(),eK={data:new F0.Name("data"),valCxt:new F0.Name("valCxt"),instancePath:new F0.Name("instancePath"),parentData:new F0.Name("parentData"),parentDataProperty:new F0.Name("parentDataProperty"),rootData:new F0.Name("rootData"),dynamicAnchors:new F0.Name("dynamicAnchors"),vErrors:new F0.Name("vErrors"),errors:new F0.Name("errors"),this:new F0.Name("this"),self:new F0.Name("self"),scope:new F0.Name("scope"),json:new F0.Name("json"),jsonPos:new F0.Name("jsonPos"),jsonLen:new F0.Name("jsonLen"),jsonPart:new F0.Name("jsonPart")};l$.default=eK});var k4=P((i$)=>{Object.defineProperty(i$,"__esModule",{value:!0});i$.extendErrors=i$.resetErrorsCount=i$.reportExtraError=i$.reportError=i$.keyword$DataError=i$.keywordError=void 0;var l=g(),d6=c(),O0=Y1();i$.keywordError={message:({keyword:Q})=>l.str`must pass "${Q}" keyword validation`};i$.keyword$DataError={message:({keyword:Q,schemaType:Y})=>Y?l.str`"${Q}" keyword must be ${Y} ($data)`:l.str`"${Q}" keyword is invalid ($data)`};function YD(Q,Y=i$.keywordError,X,W){let{it:G}=Q,{gen:$,compositeRule:z,allErrors:J}=G,H=p$(Q,Y,X);if(W!==null&&W!==void 0?W:z||J)m$($,H);else c$(G,l._`[${H}]`)}i$.reportError=YD;function XD(Q,Y=i$.keywordError,X){let{it:W}=Q,{gen:G,compositeRule:$,allErrors:z}=W,J=p$(Q,Y,X);if(m$(G,J),!($||z))c$(W,O0.default.vErrors)}i$.reportExtraError=XD;function WD(Q,Y){Q.assign(O0.default.errors,Y),Q.if(l._`${O0.default.vErrors} !== null`,()=>Q.if(Y,()=>Q.assign(l._`${O0.default.vErrors}.length`,Y),()=>Q.assign(O0.default.vErrors,null)))}i$.resetErrorsCount=WD;function GD({gen:Q,keyword:Y,schemaValue:X,data:W,errsCount:G,it:$}){if(G===void 0)throw Error("ajv implementation error");let z=Q.name("err");Q.forRange("i",G,O0.default.errors,(J)=>{if(Q.const(z,l._`${O0.default.vErrors}[${J}]`),Q.if(l._`${z}.instancePath === undefined`,()=>Q.assign(l._`${z}.instancePath`,(0,l.strConcat)(O0.default.instancePath,$.errorPath))),Q.assign(l._`${z}.schemaPath`,l.str`${$.errSchemaPath}/${Y}`),$.opts.verbose)Q.assign(l._`${z}.schema`,X),Q.assign(l._`${z}.data`,W)})}i$.extendErrors=GD;function m$(Q,Y){let X=Q.const("err",Y);Q.if(l._`${O0.default.vErrors} === null`,()=>Q.assign(O0.default.vErrors,l._`[${X}]`),l._`${O0.default.vErrors}.push(${X})`),Q.code(l._`${O0.default.errors}++`)}function c$(Q,Y){let{gen:X,validateName:W,schemaEnv:G}=Q;if(G.$async)X.throw(l._`new ${Q.ValidationError}(${Y})`);else X.assign(l._`${W}.errors`,Y),X.return(!1)}var T1={keyword:new l.Name("keyword"),schemaPath:new l.Name("schemaPath"),params:new l.Name("params"),propertyName:new l.Name("propertyName"),message:new l.Name("message"),schema:new l.Name("schema"),parentSchema:new l.Name("parentSchema")};function p$(Q,Y,X){let{createErrors:W}=Q.it;if(W===!1)return l._`{}`;return $D(Q,Y,X)}function $D(Q,Y,X={}){let{gen:W,it:G}=Q,$=[zD(G,X),JD(Q,X)];return HD(Q,Y,$),W.object(...$)}function zD({errorPath:Q},{instancePath:Y}){let X=Y?l.str`${Q}${(0,d6.getErrorPath)(Y,d6.Type.Str)}`:Q;return[O0.default.instancePath,(0,l.strConcat)(O0.default.instancePath,X)]}function JD({keyword:Q,it:{errSchemaPath:Y}},{schemaPath:X,parentSchema:W}){let G=W?Y:l.str`${Y}/${Q}`;if(X)G=l.str`${G}${(0,d6.getErrorPath)(X,d6.Type.Str)}`;return[T1.schemaPath,G]}function HD(Q,{params:Y,message:X},W){let{keyword:G,data:$,schemaValue:z,it:J}=Q,{opts:H,propertyName:A,topSchemaRef:U,schemaPath:K}=J;if(W.push([T1.keyword,G],[T1.params,typeof Y=="function"?Y(Q):Y||l._`{}`]),H.messages)W.push([T1.message,typeof X=="function"?X(Q):X]);if(H.verbose)W.push([T1.schema,z],[T1.parentSchema,l._`${U}${K}`],[O0.default.data,$]);if(A)W.push([T1.propertyName,A])}});var t$=P((d$)=>{Object.defineProperty(d$,"__esModule",{value:!0});d$.boolOrEmptySchema=d$.topBoolOrEmptySchema=void 0;var BD=k4(),LD=g(),FD=Y1(),qD={message:"boolean schema is false"};function OD(Q){let{gen:Y,schema:X,validateName:W}=Q;if(X===!1)r$(Q,!1);else if(typeof X=="object"&&X.$async===!0)Y.return(FD.default.data);else Y.assign(LD._`${W}.errors`,null),Y.return(!0)}d$.topBoolOrEmptySchema=OD;function MD(Q,Y){let{gen:X,schema:W}=Q;if(W===!1)X.var(Y,!1),r$(Q);else X.var(Y,!0)}d$.boolOrEmptySchema=MD;function r$(Q,Y){let{gen:X,data:W}=Q,G={gen:X,keyword:"false schema",data:W,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:Q};(0,BD.reportError)(G,qD,void 0,Y)}});var o9=P((a$)=>{Object.defineProperty(a$,"__esModule",{value:!0});a$.getRules=a$.isJSONType=void 0;var ZD=["string","number","integer","boolean","null","object","array"],ND=new Set(ZD);function wD(Q){return typeof Q=="string"&&ND.has(Q)}a$.isJSONType=wD;function PD(){let Q={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...Q,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},Q.number,Q.string,Q.array,Q.object],post:{rules:[]},all:{},keywords:{}}}a$.getRules=PD});var t9=P((Yz)=>{Object.defineProperty(Yz,"__esModule",{value:!0});Yz.shouldUseRule=Yz.shouldUseGroup=Yz.schemaHasRulesForType=void 0;function jD({schema:Q,self:Y},X){let W=Y.RULES.types[X];return W&&W!==!0&&e$(Q,W)}Yz.schemaHasRulesForType=jD;function e$(Q,Y){return Y.rules.some((X)=>Qz(Q,X))}Yz.shouldUseGroup=e$;function Qz(Q,Y){var X;return Q[Y.keyword]!==void 0||((X=Y.definition.implements)===null||X===void 0?void 0:X.some((W)=>Q[W]!==void 0))}Yz.shouldUseRule=Qz});var v4=P((zz)=>{Object.defineProperty(zz,"__esModule",{value:!0});zz.reportTypeError=zz.checkDataTypes=zz.checkDataType=zz.coerceAndCheckDataType=zz.getJSONTypes=zz.getSchemaTypes=zz.DataType=void 0;var TD=o9(),SD=t9(),RD=k4(),x=g(),Wz=c(),n1;(function(Q){Q[Q.Correct=0]="Correct",Q[Q.Wrong=1]="Wrong"})(n1||(zz.DataType=n1={}));function CD(Q){let Y=Gz(Q.type);if(Y.includes("null")){if(Q.nullable===!1)throw Error("type: null contradicts nullable: false")}else{if(!Y.length&&Q.nullable!==void 0)throw Error('"nullable" cannot be used without "type"');if(Q.nullable===!0)Y.push("null")}return Y}zz.getSchemaTypes=CD;function Gz(Q){let Y=Array.isArray(Q)?Q:Q?[Q]:[];if(Y.every(TD.isJSONType))return Y;throw Error("type must be JSONType or JSONType[]: "+Y.join(","))}zz.getJSONTypes=Gz;function kD(Q,Y){let{gen:X,data:W,opts:G}=Q,$=vD(Y,G.coerceTypes),z=Y.length>0&&!($.length===0&&Y.length===1&&(0,SD.schemaHasRulesForType)(Q,Y[0]));if(z){let J=s9(Y,W,G.strictNumbers,n1.Wrong);X.if(J,()=>{if($.length)xD(Q,Y,$);else e9(Q)})}return z}zz.coerceAndCheckDataType=kD;var $z=new Set(["string","number","integer","boolean","null"]);function vD(Q,Y){return Y?Q.filter((X)=>$z.has(X)||Y==="array"&&X==="array"):[]}function xD(Q,Y,X){let{gen:W,data:G,opts:$}=Q,z=W.let("dataType",x._`typeof ${G}`),J=W.let("coerced",x._`undefined`);if($.coerceTypes==="array")W.if(x._`${z} == 'object' && Array.isArray(${G}) && ${G}.length == 1`,()=>W.assign(G,x._`${G}[0]`).assign(z,x._`typeof ${G}`).if(s9(Y,G,$.strictNumbers),()=>W.assign(J,G)));W.if(x._`${J} !== undefined`);for(let A of X)if($z.has(A)||A==="array"&&$.coerceTypes==="array")H(A);W.else(),e9(Q),W.endIf(),W.if(x._`${J} !== undefined`,()=>{W.assign(G,J),_D(Q,J)});function H(A){switch(A){case"string":W.elseIf(x._`${z} == "number" || ${z} == "boolean"`).assign(J,x._`"" + ${G}`).elseIf(x._`${G} === null`).assign(J,x._`""`);return;case"number":W.elseIf(x._`${z} == "boolean" || ${G} === null
2
+ var wH=Object.create;var{getPrototypeOf:PH,defineProperty:TQ,getOwnPropertyNames:bH}=Object;var jH=Object.prototype.hasOwnProperty;function IH(Q){return this[Q]}var EH,TH,FX=(Q,Y,X)=>{var W=Q!=null&&typeof Q==="object";if(W){var G=Y?EH??=new WeakMap:TH??=new WeakMap,$=G.get(Q);if($)return $}X=Q!=null?wH(PH(Q)):{};let z=Y||!Q||!Q.__esModule?TQ(X,"default",{value:Q,enumerable:!0}):X;for(let J of bH(Q))if(!jH.call(z,J))TQ(z,J,{get:IH.bind(Q,J),enumerable:!0});if(W)G.set(Q,z);return z};var P=(Q,Y)=>()=>(Y||Q((Y={exports:{}}).exports,Y),Y.exports);var SH=(Q)=>Q;function RH(Q,Y){this[Q]=SH.bind(null,Y)}var qX=(Q,Y)=>{for(var X in Y)TQ(Q,X,{get:Y[X],enumerable:!0,configurable:!0,set:RH.bind(Y,X)})};var R4=P((L$)=>{Object.defineProperty(L$,"__esModule",{value:!0});L$.regexpCode=L$.getEsmExportName=L$.getProperty=L$.safeStringify=L$.stringify=L$.strConcat=L$.addCodeArg=L$.str=L$._=L$.nil=L$._Code=L$.Name=L$.IDENTIFIER=L$._CodeOrName=void 0;class y6{}L$._CodeOrName=y6;L$.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class c1 extends y6{constructor(Q){super();if(!L$.IDENTIFIER.test(Q))throw Error("CodeGen: name must be a valid identifier");this.str=Q}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}L$.Name=c1;class _0 extends y6{constructor(Q){super();this._items=typeof Q==="string"?[Q]:Q}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let Q=this._items[0];return Q===""||Q==='""'}get str(){var Q;return(Q=this._str)!==null&&Q!==void 0?Q:this._str=this._items.reduce((Y,X)=>`${Y}${X}`,"")}get names(){var Q;return(Q=this._names)!==null&&Q!==void 0?Q:this._names=this._items.reduce((Y,X)=>{if(X instanceof c1)Y[X.str]=(Y[X.str]||0)+1;return Y},{})}}L$._Code=_0;L$.nil=new _0("");function D$(Q,...Y){let X=[Q[0]],W=0;while(W<Y.length)y9(X,Y[W]),X.push(Q[++W]);return new _0(X)}L$._=D$;var g9=new _0("+");function B$(Q,...Y){let X=[S4(Q[0])],W=0;while(W<Y.length)X.push(g9),y9(X,Y[W]),X.push(g9,S4(Q[++W]));return QK(X),new _0(X)}L$.str=B$;function y9(Q,Y){if(Y instanceof _0)Q.push(...Y._items);else if(Y instanceof c1)Q.push(Y);else Q.push(WK(Y))}L$.addCodeArg=y9;function QK(Q){let Y=1;while(Y<Q.length-1){if(Q[Y]===g9){let X=YK(Q[Y-1],Q[Y+1]);if(X!==void 0){Q.splice(Y-1,3,X);continue}Q[Y++]="+"}Y++}}function YK(Q,Y){if(Y==='""')return Q;if(Q==='""')return Y;if(typeof Q=="string"){if(Y instanceof c1||Q[Q.length-1]!=='"')return;if(typeof Y!="string")return`${Q.slice(0,-1)}${Y}"`;if(Y[0]==='"')return Q.slice(0,-1)+Y.slice(1);return}if(typeof Y=="string"&&Y[0]==='"'&&!(Q instanceof c1))return`"${Q}${Y.slice(1)}`;return}function XK(Q,Y){return Y.emptyStr()?Q:Q.emptyStr()?Y:B$`${Q}${Y}`}L$.strConcat=XK;function WK(Q){return typeof Q=="number"||typeof Q=="boolean"||Q===null?Q:S4(Array.isArray(Q)?Q.join(","):Q)}function GK(Q){return new _0(S4(Q))}L$.stringify=GK;function S4(Q){return JSON.stringify(Q).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}L$.safeStringify=S4;function $K(Q){return typeof Q=="string"&&L$.IDENTIFIER.test(Q)?new _0(`.${Q}`):D$`[${Q}]`}L$.getProperty=$K;function zK(Q){if(typeof Q=="string"&&L$.IDENTIFIER.test(Q))return new _0(`${Q}`);throw Error(`CodeGen: invalid export name: ${Q}, use explicit $id name mapping`)}L$.getEsmExportName=zK;function JK(Q){return new _0(Q.toString())}L$.regexpCode=JK});var l9=P((M$)=>{Object.defineProperty(M$,"__esModule",{value:!0});M$.ValueScope=M$.ValueScopeName=M$.Scope=M$.varKinds=M$.UsedValueState=void 0;var Z0=R4();class q$ extends Error{constructor(Q){super(`CodeGen: "code" for ${Q} not defined`);this.value=Q.value}}var h6;(function(Q){Q[Q.Started=0]="Started",Q[Q.Completed=1]="Completed"})(h6||(M$.UsedValueState=h6={}));M$.varKinds={const:new Z0.Name("const"),let:new Z0.Name("let"),var:new Z0.Name("var")};class h9{constructor({prefixes:Q,parent:Y}={}){this._names={},this._prefixes=Q,this._parent=Y}toName(Q){return Q instanceof Z0.Name?Q:this.name(Q)}name(Q){return new Z0.Name(this._newName(Q))}_newName(Q){let Y=this._names[Q]||this._nameGroup(Q);return`${Q}${Y.index++}`}_nameGroup(Q){var Y,X;if(((X=(Y=this._parent)===null||Y===void 0?void 0:Y._prefixes)===null||X===void 0?void 0:X.has(Q))||this._prefixes&&!this._prefixes.has(Q))throw Error(`CodeGen: prefix "${Q}" is not allowed in this scope`);return this._names[Q]={prefix:Q,index:0}}}M$.Scope=h9;class f9 extends Z0.Name{constructor(Q,Y){super(Y);this.prefix=Q}setValue(Q,{property:Y,itemIndex:X}){this.value=Q,this.scopePath=Z0._`.${new Z0.Name(Y)}[${X}]`}}M$.ValueScopeName=f9;var ZK=Z0._`\n`;class O$ extends h9{constructor(Q){super(Q);this._values={},this._scope=Q.scope,this.opts={...Q,_n:Q.lines?ZK:Z0.nil}}get(){return this._scope}name(Q){return new f9(Q,this._newName(Q))}value(Q,Y){var X;if(Y.ref===void 0)throw Error("CodeGen: ref must be passed in value");let W=this.toName(Q),{prefix:G}=W,$=(X=Y.key)!==null&&X!==void 0?X:Y.ref,z=this._values[G];if(z){let A=z.get($);if(A)return A}else z=this._values[G]=new Map;z.set($,W);let J=this._scope[G]||(this._scope[G]=[]),H=J.length;return J[H]=Y.ref,W.setValue(Y,{property:G,itemIndex:H}),W}getValue(Q,Y){let X=this._values[Q];if(!X)return;return X.get(Y)}scopeRefs(Q,Y=this._values){return this._reduceValues(Y,(X)=>{if(X.scopePath===void 0)throw Error(`CodeGen: name "${X}" has no value`);return Z0._`${Q}${X.scopePath}`})}scopeCode(Q=this._values,Y,X){return this._reduceValues(Q,(W)=>{if(W.value===void 0)throw Error(`CodeGen: name "${W}" has no value`);return W.value.code},Y,X)}_reduceValues(Q,Y,X={},W){let G=Z0.nil;for(let $ in Q){let z=Q[$];if(!z)continue;let J=X[$]=X[$]||new Map;z.forEach((H)=>{if(J.has(H))return;J.set(H,h6.Started);let A=Y(H);if(A){let U=this.opts.es5?M$.varKinds.var:M$.varKinds.const;G=Z0._`${G}${U} ${H} = ${A};${this.opts._n}`}else if(A=W===null||W===void 0?void 0:W(H))G=Z0._`${G}${A}${this.opts._n}`;else throw new q$(H);J.set(H,h6.Completed)})}return G}}M$.ValueScope=O$});var g=P((N0)=>{Object.defineProperty(N0,"__esModule",{value:!0});N0.or=N0.and=N0.not=N0.CodeGen=N0.operators=N0.varKinds=N0.ValueScopeName=N0.ValueScope=N0.Scope=N0.Name=N0.regexpCode=N0.stringify=N0.getProperty=N0.nil=N0.strConcat=N0.str=N0._=void 0;var f=R4(),g0=l9(),B1=R4();Object.defineProperty(N0,"_",{enumerable:!0,get:function(){return B1._}});Object.defineProperty(N0,"str",{enumerable:!0,get:function(){return B1.str}});Object.defineProperty(N0,"strConcat",{enumerable:!0,get:function(){return B1.strConcat}});Object.defineProperty(N0,"nil",{enumerable:!0,get:function(){return B1.nil}});Object.defineProperty(N0,"getProperty",{enumerable:!0,get:function(){return B1.getProperty}});Object.defineProperty(N0,"stringify",{enumerable:!0,get:function(){return B1.stringify}});Object.defineProperty(N0,"regexpCode",{enumerable:!0,get:function(){return B1.regexpCode}});Object.defineProperty(N0,"Name",{enumerable:!0,get:function(){return B1.Name}});var i6=l9();Object.defineProperty(N0,"Scope",{enumerable:!0,get:function(){return i6.Scope}});Object.defineProperty(N0,"ValueScope",{enumerable:!0,get:function(){return i6.ValueScope}});Object.defineProperty(N0,"ValueScopeName",{enumerable:!0,get:function(){return i6.ValueScopeName}});Object.defineProperty(N0,"varKinds",{enumerable:!0,get:function(){return i6.varKinds}});N0.operators={GT:new f._Code(">"),GTE:new f._Code(">="),LT:new f._Code("<"),LTE:new f._Code("<="),EQ:new f._Code("==="),NEQ:new f._Code("!=="),NOT:new f._Code("!"),OR:new f._Code("||"),AND:new f._Code("&&"),ADD:new f._Code("+")};class L1{optimizeNodes(){return this}optimizeNames(Q,Y){return this}}class Z$ extends L1{constructor(Q,Y,X){super();this.varKind=Q,this.name=Y,this.rhs=X}render({es5:Q,_n:Y}){let X=Q?g0.varKinds.var:this.varKind,W=this.rhs===void 0?"":` = ${this.rhs}`;return`${X} ${this.name}${W};`+Y}optimizeNames(Q,Y){if(!Q[this.name.str])return;if(this.rhs)this.rhs=i1(this.rhs,Q,Y);return this}get names(){return this.rhs instanceof f._CodeOrName?this.rhs.names:{}}}class p9 extends L1{constructor(Q,Y,X){super();this.lhs=Q,this.rhs=Y,this.sideEffects=X}render({_n:Q}){return`${this.lhs} = ${this.rhs};`+Q}optimizeNames(Q,Y){if(this.lhs instanceof f.Name&&!Q[this.lhs.str]&&!this.sideEffects)return;return this.rhs=i1(this.rhs,Q,Y),this}get names(){let Q=this.lhs instanceof f.Name?{}:{...this.lhs.names};return p6(Q,this.rhs)}}class N$ extends p9{constructor(Q,Y,X,W){super(Q,X,W);this.op=Y}render({_n:Q}){return`${this.lhs} ${this.op}= ${this.rhs};`+Q}}class w$ extends L1{constructor(Q){super();this.label=Q,this.names={}}render({_n:Q}){return`${this.label}:`+Q}}class P$ extends L1{constructor(Q){super();this.label=Q,this.names={}}render({_n:Q}){return`break${this.label?` ${this.label}`:""};`+Q}}class b$ extends L1{constructor(Q){super();this.error=Q}render({_n:Q}){return`throw ${this.error};`+Q}get names(){return this.error.names}}class j$ extends L1{constructor(Q){super();this.code=Q}render({_n:Q}){return`${this.code};`+Q}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(Q,Y){return this.code=i1(this.code,Q,Y),this}get names(){return this.code instanceof f._CodeOrName?this.code.names:{}}}class n6 extends L1{constructor(Q=[]){super();this.nodes=Q}render(Q){return this.nodes.reduce((Y,X)=>Y+X.render(Q),"")}optimizeNodes(){let{nodes:Q}=this,Y=Q.length;while(Y--){let X=Q[Y].optimizeNodes();if(Array.isArray(X))Q.splice(Y,1,...X);else if(X)Q[Y]=X;else Q.splice(Y,1)}return Q.length>0?this:void 0}optimizeNames(Q,Y){let{nodes:X}=this,W=X.length;while(W--){let G=X[W];if(G.optimizeNames(Q,Y))continue;bK(Q,G.names),X.splice(W,1)}return X.length>0?this:void 0}get names(){return this.nodes.reduce((Q,Y)=>E1(Q,Y.names),{})}}class F1 extends n6{render(Q){return"{"+Q._n+super.render(Q)+"}"+Q._n}}class I$ extends n6{}class C4 extends F1{}C4.kind="else";class Q1 extends F1{constructor(Q,Y){super(Y);this.condition=Q}render(Q){let Y=`if(${this.condition})`+super.render(Q);if(this.else)Y+="else "+this.else.render(Q);return Y}optimizeNodes(){super.optimizeNodes();let Q=this.condition;if(Q===!0)return this.nodes;let Y=this.else;if(Y){let X=Y.optimizeNodes();Y=this.else=Array.isArray(X)?new C4(X):X}if(Y){if(Q===!1)return Y instanceof Q1?Y:Y.nodes;if(this.nodes.length)return this;return new Q1(C$(Q),Y instanceof Q1?[Y]:Y.nodes)}if(Q===!1||!this.nodes.length)return;return this}optimizeNames(Q,Y){var X;if(this.else=(X=this.else)===null||X===void 0?void 0:X.optimizeNames(Q,Y),!(super.optimizeNames(Q,Y)||this.else))return;return this.condition=i1(this.condition,Q,Y),this}get names(){let Q=super.names;if(p6(Q,this.condition),this.else)E1(Q,this.else.names);return Q}}Q1.kind="if";class p1 extends F1{}p1.kind="for";class E$ extends p1{constructor(Q){super();this.iteration=Q}render(Q){return`for(${this.iteration})`+super.render(Q)}optimizeNames(Q,Y){if(!super.optimizeNames(Q,Y))return;return this.iteration=i1(this.iteration,Q,Y),this}get names(){return E1(super.names,this.iteration.names)}}class T$ extends p1{constructor(Q,Y,X,W){super();this.varKind=Q,this.name=Y,this.from=X,this.to=W}render(Q){let Y=Q.es5?g0.varKinds.var:this.varKind,{name:X,from:W,to:G}=this;return`for(${Y} ${X}=${W}; ${X}<${G}; ${X}++)`+super.render(Q)}get names(){let Q=p6(super.names,this.from);return p6(Q,this.to)}}class m9 extends p1{constructor(Q,Y,X,W){super();this.loop=Q,this.varKind=Y,this.name=X,this.iterable=W}render(Q){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(Q)}optimizeNames(Q,Y){if(!super.optimizeNames(Q,Y))return;return this.iterable=i1(this.iterable,Q,Y),this}get names(){return E1(super.names,this.iterable.names)}}class f6 extends F1{constructor(Q,Y,X){super();this.name=Q,this.args=Y,this.async=X}render(Q){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(Q)}}f6.kind="func";class l6 extends n6{render(Q){return"return "+super.render(Q)}}l6.kind="return";class S$ extends F1{render(Q){let Y="try"+super.render(Q);if(this.catch)Y+=this.catch.render(Q);if(this.finally)Y+=this.finally.render(Q);return Y}optimizeNodes(){var Q,Y;return super.optimizeNodes(),(Q=this.catch)===null||Q===void 0||Q.optimizeNodes(),(Y=this.finally)===null||Y===void 0||Y.optimizeNodes(),this}optimizeNames(Q,Y){var X,W;return super.optimizeNames(Q,Y),(X=this.catch)===null||X===void 0||X.optimizeNames(Q,Y),(W=this.finally)===null||W===void 0||W.optimizeNames(Q,Y),this}get names(){let Q=super.names;if(this.catch)E1(Q,this.catch.names);if(this.finally)E1(Q,this.finally.names);return Q}}class m6 extends F1{constructor(Q){super();this.error=Q}render(Q){return`catch(${this.error})`+super.render(Q)}}m6.kind="catch";class c6 extends F1{render(Q){return"finally"+super.render(Q)}}c6.kind="finally";class R${constructor(Q,Y={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...Y,_n:Y.lines?`
3
+ `:""},this._extScope=Q,this._scope=new g0.Scope({parent:Q}),this._nodes=[new I$]}toString(){return this._root.render(this.opts)}name(Q){return this._scope.name(Q)}scopeName(Q){return this._extScope.name(Q)}scopeValue(Q,Y){let X=this._extScope.value(Q,Y);return(this._values[X.prefix]||(this._values[X.prefix]=new Set)).add(X),X}getScopeValue(Q,Y){return this._extScope.getValue(Q,Y)}scopeRefs(Q){return this._extScope.scopeRefs(Q,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(Q,Y,X,W){let G=this._scope.toName(Y);if(X!==void 0&&W)this._constants[G.str]=X;return this._leafNode(new Z$(Q,G,X)),G}const(Q,Y,X){return this._def(g0.varKinds.const,Q,Y,X)}let(Q,Y,X){return this._def(g0.varKinds.let,Q,Y,X)}var(Q,Y,X){return this._def(g0.varKinds.var,Q,Y,X)}assign(Q,Y,X){return this._leafNode(new p9(Q,Y,X))}add(Q,Y){return this._leafNode(new N$(Q,N0.operators.ADD,Y))}code(Q){if(typeof Q=="function")Q();else if(Q!==f.nil)this._leafNode(new j$(Q));return this}object(...Q){let Y=["{"];for(let[X,W]of Q){if(Y.length>1)Y.push(",");if(Y.push(X),X!==W||this.opts.es5)Y.push(":"),(0,f.addCodeArg)(Y,W)}return Y.push("}"),new f._Code(Y)}if(Q,Y,X){if(this._blockNode(new Q1(Q)),Y&&X)this.code(Y).else().code(X).endIf();else if(Y)this.code(Y).endIf();else if(X)throw Error('CodeGen: "else" body without "then" body');return this}elseIf(Q){return this._elseNode(new Q1(Q))}else(){return this._elseNode(new C4)}endIf(){return this._endBlockNode(Q1,C4)}_for(Q,Y){if(this._blockNode(Q),Y)this.code(Y).endFor();return this}for(Q,Y){return this._for(new E$(Q),Y)}forRange(Q,Y,X,W,G=this.opts.es5?g0.varKinds.var:g0.varKinds.let){let $=this._scope.toName(Q);return this._for(new T$(G,$,Y,X),()=>W($))}forOf(Q,Y,X,W=g0.varKinds.const){let G=this._scope.toName(Q);if(this.opts.es5){let $=Y instanceof f.Name?Y:this.var("_arr",Y);return this.forRange("_i",0,f._`${$}.length`,(z)=>{this.var(G,f._`${$}[${z}]`),X(G)})}return this._for(new m9("of",W,G,Y),()=>X(G))}forIn(Q,Y,X,W=this.opts.es5?g0.varKinds.var:g0.varKinds.const){if(this.opts.ownProperties)return this.forOf(Q,f._`Object.keys(${Y})`,X);let G=this._scope.toName(Q);return this._for(new m9("in",W,G,Y),()=>X(G))}endFor(){return this._endBlockNode(p1)}label(Q){return this._leafNode(new w$(Q))}break(Q){return this._leafNode(new P$(Q))}return(Q){let Y=new l6;if(this._blockNode(Y),this.code(Q),Y.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(l6)}try(Q,Y,X){if(!Y&&!X)throw Error('CodeGen: "try" without "catch" and "finally"');let W=new S$;if(this._blockNode(W),this.code(Q),Y){let G=this.name("e");this._currNode=W.catch=new m6(G),Y(G)}if(X)this._currNode=W.finally=new c6,this.code(X);return this._endBlockNode(m6,c6)}throw(Q){return this._leafNode(new b$(Q))}block(Q,Y){if(this._blockStarts.push(this._nodes.length),Q)this.code(Q).endBlock(Y);return this}endBlock(Q){let Y=this._blockStarts.pop();if(Y===void 0)throw Error("CodeGen: not in self-balancing block");let X=this._nodes.length-Y;if(X<0||Q!==void 0&&X!==Q)throw Error(`CodeGen: wrong number of nodes: ${X} vs ${Q} expected`);return this._nodes.length=Y,this}func(Q,Y=f.nil,X,W){if(this._blockNode(new f6(Q,Y,X)),W)this.code(W).endFunc();return this}endFunc(){return this._endBlockNode(f6)}optimize(Q=1){while(Q-- >0)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(Q){return this._currNode.nodes.push(Q),this}_blockNode(Q){this._currNode.nodes.push(Q),this._nodes.push(Q)}_endBlockNode(Q,Y){let X=this._currNode;if(X instanceof Q||Y&&X instanceof Y)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${Y?`${Q.kind}/${Y.kind}`:Q.kind}"`)}_elseNode(Q){let Y=this._currNode;if(!(Y instanceof Q1))throw Error('CodeGen: "else" without "if"');return this._currNode=Y.else=Q,this}get _root(){return this._nodes[0]}get _currNode(){let Q=this._nodes;return Q[Q.length-1]}set _currNode(Q){let Y=this._nodes;Y[Y.length-1]=Q}}N0.CodeGen=R$;function E1(Q,Y){for(let X in Y)Q[X]=(Q[X]||0)+(Y[X]||0);return Q}function p6(Q,Y){return Y instanceof f._CodeOrName?E1(Q,Y.names):Q}function i1(Q,Y,X){if(Q instanceof f.Name)return W(Q);if(!G(Q))return Q;return new f._Code(Q._items.reduce(($,z)=>{if(z instanceof f.Name)z=W(z);if(z instanceof f._Code)$.push(...z._items);else $.push(z);return $},[]));function W($){let z=X[$.str];if(z===void 0||Y[$.str]!==1)return $;return delete Y[$.str],z}function G($){return $ instanceof f._Code&&$._items.some((z)=>z instanceof f.Name&&Y[z.str]===1&&X[z.str]!==void 0)}}function bK(Q,Y){for(let X in Y)Q[X]=(Q[X]||0)-(Y[X]||0)}function C$(Q){return typeof Q=="boolean"||typeof Q=="number"||Q===null?!Q:f._`!${c9(Q)}`}N0.not=C$;var jK=k$(N0.operators.AND);function IK(...Q){return Q.reduce(jK)}N0.and=IK;var EK=k$(N0.operators.OR);function TK(...Q){return Q.reduce(EK)}N0.or=TK;function k$(Q){return(Y,X)=>Y===f.nil?X:X===f.nil?Y:f._`${c9(Y)} ${Q} ${c9(X)}`}function c9(Q){return Q instanceof f.Name?Q:f._`(${Q})`}});var c=P((l$)=>{Object.defineProperty(l$,"__esModule",{value:!0});l$.checkStrictMode=l$.getErrorPath=l$.Type=l$.useFunc=l$.setEvaluated=l$.evaluatedPropsToName=l$.mergeEvaluated=l$.eachItem=l$.unescapeJsonPointer=l$.escapeJsonPointer=l$.escapeFragment=l$.unescapeFragment=l$.schemaRefOrVal=l$.schemaHasRulesButRef=l$.schemaHasRules=l$.checkUnknownRules=l$.alwaysValidSchema=l$.toHash=void 0;var r=g(),kK=R4();function vK(Q){let Y={};for(let X of Q)Y[X]=!0;return Y}l$.toHash=vK;function xK(Q,Y){if(typeof Y=="boolean")return Y;if(Object.keys(Y).length===0)return!0;return g$(Q,Y),!y$(Y,Q.self.RULES.all)}l$.alwaysValidSchema=xK;function g$(Q,Y=Q.schema){let{opts:X,self:W}=Q;if(!X.strictSchema)return;if(typeof Y==="boolean")return;let G=W.RULES.keywords;for(let $ in Y)if(!G[$])f$(Q,`unknown keyword: "${$}"`)}l$.checkUnknownRules=g$;function y$(Q,Y){if(typeof Q=="boolean")return!Q;for(let X in Q)if(Y[X])return!0;return!1}l$.schemaHasRules=y$;function _K(Q,Y){if(typeof Q=="boolean")return!Q;for(let X in Q)if(X!=="$ref"&&Y.all[X])return!0;return!1}l$.schemaHasRulesButRef=_K;function gK({topSchemaRef:Q,schemaPath:Y},X,W,G){if(!G){if(typeof X=="number"||typeof X=="boolean")return X;if(typeof X=="string")return r._`${X}`}return r._`${Q}${Y}${(0,r.getProperty)(W)}`}l$.schemaRefOrVal=gK;function yK(Q){return u$(decodeURIComponent(Q))}l$.unescapeFragment=yK;function uK(Q){return encodeURIComponent(n9(Q))}l$.escapeFragment=uK;function n9(Q){if(typeof Q=="number")return`${Q}`;return Q.replace(/~/g,"~0").replace(/\//g,"~1")}l$.escapeJsonPointer=n9;function u$(Q){return Q.replace(/~1/g,"/").replace(/~0/g,"~")}l$.unescapeJsonPointer=u$;function hK(Q,Y){if(Array.isArray(Q))for(let X of Q)Y(X);else Y(Q)}l$.eachItem=hK;function x$({mergeNames:Q,mergeToName:Y,mergeValues:X,resultToName:W}){return(G,$,z,J)=>{let H=z===void 0?$:z instanceof r.Name?($ instanceof r.Name?Q(G,$,z):Y(G,$,z),z):$ instanceof r.Name?(Y(G,z,$),$):X($,z);return J===r.Name&&!(H instanceof r.Name)?W(G,H):H}}l$.mergeEvaluated={props:x$({mergeNames:(Q,Y,X)=>Q.if(r._`${X} !== true && ${Y} !== undefined`,()=>{Q.if(r._`${Y} === true`,()=>Q.assign(X,!0),()=>Q.assign(X,r._`${X} || {}`).code(r._`Object.assign(${X}, ${Y})`))}),mergeToName:(Q,Y,X)=>Q.if(r._`${X} !== true`,()=>{if(Y===!0)Q.assign(X,!0);else Q.assign(X,r._`${X} || {}`),r9(Q,X,Y)}),mergeValues:(Q,Y)=>Q===!0?!0:{...Q,...Y},resultToName:h$}),items:x$({mergeNames:(Q,Y,X)=>Q.if(r._`${X} !== true && ${Y} !== undefined`,()=>Q.assign(X,r._`${Y} === true ? true : ${X} > ${Y} ? ${X} : ${Y}`)),mergeToName:(Q,Y,X)=>Q.if(r._`${X} !== true`,()=>Q.assign(X,Y===!0?!0:r._`${X} > ${Y} ? ${X} : ${Y}`)),mergeValues:(Q,Y)=>Q===!0?!0:Math.max(Q,Y),resultToName:(Q,Y)=>Q.var("items",Y)})};function h$(Q,Y){if(Y===!0)return Q.var("props",!0);let X=Q.var("props",r._`{}`);if(Y!==void 0)r9(Q,X,Y);return X}l$.evaluatedPropsToName=h$;function r9(Q,Y,X){Object.keys(X).forEach((W)=>Q.assign(r._`${Y}${(0,r.getProperty)(W)}`,!0))}l$.setEvaluated=r9;var _$={};function fK(Q,Y){return Q.scopeValue("func",{ref:Y,code:_$[Y.code]||(_$[Y.code]=new kK._Code(Y.code))})}l$.useFunc=fK;var i9;(function(Q){Q[Q.Num=0]="Num",Q[Q.Str=1]="Str"})(i9||(l$.Type=i9={}));function lK(Q,Y,X){if(Q instanceof r.Name){let W=Y===i9.Num;return X?W?r._`"[" + ${Q} + "]"`:r._`"['" + ${Q} + "']"`:W?r._`"/" + ${Q}`:r._`"/" + ${Q}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return X?(0,r.getProperty)(Q).toString():"/"+n9(Q)}l$.getErrorPath=lK;function f$(Q,Y,X=Q.opts.strictSchema){if(!X)return;if(Y=`strict mode: ${Y}`,X===!0)throw Error(Y);Q.self.logger.warn(Y)}l$.checkStrictMode=f$});var Y1=P((c$)=>{Object.defineProperty(c$,"__esModule",{value:!0});var F0=g(),$D={data:new F0.Name("data"),valCxt:new F0.Name("valCxt"),instancePath:new F0.Name("instancePath"),parentData:new F0.Name("parentData"),parentDataProperty:new F0.Name("parentDataProperty"),rootData:new F0.Name("rootData"),dynamicAnchors:new F0.Name("dynamicAnchors"),vErrors:new F0.Name("vErrors"),errors:new F0.Name("errors"),this:new F0.Name("this"),self:new F0.Name("self"),scope:new F0.Name("scope"),json:new F0.Name("json"),jsonPos:new F0.Name("jsonPos"),jsonLen:new F0.Name("jsonLen"),jsonPart:new F0.Name("jsonPart")};c$.default=$D});var k4=P((r$)=>{Object.defineProperty(r$,"__esModule",{value:!0});r$.extendErrors=r$.resetErrorsCount=r$.reportExtraError=r$.reportError=r$.keyword$DataError=r$.keywordError=void 0;var l=g(),d6=c(),O0=Y1();r$.keywordError={message:({keyword:Q})=>l.str`must pass "${Q}" keyword validation`};r$.keyword$DataError={message:({keyword:Q,schemaType:Y})=>Y?l.str`"${Q}" keyword must be ${Y} ($data)`:l.str`"${Q}" keyword is invalid ($data)`};function JD(Q,Y=r$.keywordError,X,W){let{it:G}=Q,{gen:$,compositeRule:z,allErrors:J}=G,H=n$(Q,Y,X);if(W!==null&&W!==void 0?W:z||J)p$($,H);else i$(G,l._`[${H}]`)}r$.reportError=JD;function HD(Q,Y=r$.keywordError,X){let{it:W}=Q,{gen:G,compositeRule:$,allErrors:z}=W,J=n$(Q,Y,X);if(p$(G,J),!($||z))i$(W,O0.default.vErrors)}r$.reportExtraError=HD;function AD(Q,Y){Q.assign(O0.default.errors,Y),Q.if(l._`${O0.default.vErrors} !== null`,()=>Q.if(Y,()=>Q.assign(l._`${O0.default.vErrors}.length`,Y),()=>Q.assign(O0.default.vErrors,null)))}r$.resetErrorsCount=AD;function UD({gen:Q,keyword:Y,schemaValue:X,data:W,errsCount:G,it:$}){if(G===void 0)throw Error("ajv implementation error");let z=Q.name("err");Q.forRange("i",G,O0.default.errors,(J)=>{if(Q.const(z,l._`${O0.default.vErrors}[${J}]`),Q.if(l._`${z}.instancePath === undefined`,()=>Q.assign(l._`${z}.instancePath`,(0,l.strConcat)(O0.default.instancePath,$.errorPath))),Q.assign(l._`${z}.schemaPath`,l.str`${$.errSchemaPath}/${Y}`),$.opts.verbose)Q.assign(l._`${z}.schema`,X),Q.assign(l._`${z}.data`,W)})}r$.extendErrors=UD;function p$(Q,Y){let X=Q.const("err",Y);Q.if(l._`${O0.default.vErrors} === null`,()=>Q.assign(O0.default.vErrors,l._`[${X}]`),l._`${O0.default.vErrors}.push(${X})`),Q.code(l._`${O0.default.errors}++`)}function i$(Q,Y){let{gen:X,validateName:W,schemaEnv:G}=Q;if(G.$async)X.throw(l._`new ${Q.ValidationError}(${Y})`);else X.assign(l._`${W}.errors`,Y),X.return(!1)}var T1={keyword:new l.Name("keyword"),schemaPath:new l.Name("schemaPath"),params:new l.Name("params"),propertyName:new l.Name("propertyName"),message:new l.Name("message"),schema:new l.Name("schema"),parentSchema:new l.Name("parentSchema")};function n$(Q,Y,X){let{createErrors:W}=Q.it;if(W===!1)return l._`{}`;return KD(Q,Y,X)}function KD(Q,Y,X={}){let{gen:W,it:G}=Q,$=[DD(G,X),BD(Q,X)];return LD(Q,Y,$),W.object(...$)}function DD({errorPath:Q},{instancePath:Y}){let X=Y?l.str`${Q}${(0,d6.getErrorPath)(Y,d6.Type.Str)}`:Q;return[O0.default.instancePath,(0,l.strConcat)(O0.default.instancePath,X)]}function BD({keyword:Q,it:{errSchemaPath:Y}},{schemaPath:X,parentSchema:W}){let G=W?Y:l.str`${Y}/${Q}`;if(X)G=l.str`${G}${(0,d6.getErrorPath)(X,d6.Type.Str)}`;return[T1.schemaPath,G]}function LD(Q,{params:Y,message:X},W){let{keyword:G,data:$,schemaValue:z,it:J}=Q,{opts:H,propertyName:A,topSchemaRef:U,schemaPath:K}=J;if(W.push([T1.keyword,G],[T1.params,typeof Y=="function"?Y(Q):Y||l._`{}`]),H.messages)W.push([T1.message,typeof X=="function"?X(Q):X]);if(H.verbose)W.push([T1.schema,z],[T1.parentSchema,l._`${U}${K}`],[O0.default.data,$]);if(A)W.push([T1.propertyName,A])}});var s$=P((t$)=>{Object.defineProperty(t$,"__esModule",{value:!0});t$.boolOrEmptySchema=t$.topBoolOrEmptySchema=void 0;var VD=k4(),ZD=g(),ND=Y1(),wD={message:"boolean schema is false"};function PD(Q){let{gen:Y,schema:X,validateName:W}=Q;if(X===!1)o$(Q,!1);else if(typeof X=="object"&&X.$async===!0)Y.return(ND.default.data);else Y.assign(ZD._`${W}.errors`,null),Y.return(!0)}t$.topBoolOrEmptySchema=PD;function bD(Q,Y){let{gen:X,schema:W}=Q;if(W===!1)X.var(Y,!1),o$(Q);else X.var(Y,!0)}t$.boolOrEmptySchema=bD;function o$(Q,Y){let{gen:X,data:W}=Q,G={gen:X,keyword:"false schema",data:W,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:Q};(0,VD.reportError)(G,wD,void 0,Y)}});var o9=P((e$)=>{Object.defineProperty(e$,"__esModule",{value:!0});e$.getRules=e$.isJSONType=void 0;var ID=["string","number","integer","boolean","null","object","array"],ED=new Set(ID);function TD(Q){return typeof Q=="string"&&ED.has(Q)}e$.isJSONType=TD;function SD(){let Q={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...Q,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},Q.number,Q.string,Q.array,Q.object],post:{rules:[]},all:{},keywords:{}}}e$.getRules=SD});var t9=P((Wz)=>{Object.defineProperty(Wz,"__esModule",{value:!0});Wz.shouldUseRule=Wz.shouldUseGroup=Wz.schemaHasRulesForType=void 0;function CD({schema:Q,self:Y},X){let W=Y.RULES.types[X];return W&&W!==!0&&Yz(Q,W)}Wz.schemaHasRulesForType=CD;function Yz(Q,Y){return Y.rules.some((X)=>Xz(Q,X))}Wz.shouldUseGroup=Yz;function Xz(Q,Y){var X;return Q[Y.keyword]!==void 0||((X=Y.definition.implements)===null||X===void 0?void 0:X.some((W)=>Q[W]!==void 0))}Wz.shouldUseRule=Xz});var v4=P((Hz)=>{Object.defineProperty(Hz,"__esModule",{value:!0});Hz.reportTypeError=Hz.checkDataTypes=Hz.checkDataType=Hz.coerceAndCheckDataType=Hz.getJSONTypes=Hz.getSchemaTypes=Hz.DataType=void 0;var xD=o9(),_D=t9(),gD=k4(),x=g(),$z=c(),n1;(function(Q){Q[Q.Correct=0]="Correct",Q[Q.Wrong=1]="Wrong"})(n1||(Hz.DataType=n1={}));function yD(Q){let Y=zz(Q.type);if(Y.includes("null")){if(Q.nullable===!1)throw Error("type: null contradicts nullable: false")}else{if(!Y.length&&Q.nullable!==void 0)throw Error('"nullable" cannot be used without "type"');if(Q.nullable===!0)Y.push("null")}return Y}Hz.getSchemaTypes=yD;function zz(Q){let Y=Array.isArray(Q)?Q:Q?[Q]:[];if(Y.every(xD.isJSONType))return Y;throw Error("type must be JSONType or JSONType[]: "+Y.join(","))}Hz.getJSONTypes=zz;function uD(Q,Y){let{gen:X,data:W,opts:G}=Q,$=hD(Y,G.coerceTypes),z=Y.length>0&&!($.length===0&&Y.length===1&&(0,_D.schemaHasRulesForType)(Q,Y[0]));if(z){let J=s9(Y,W,G.strictNumbers,n1.Wrong);X.if(J,()=>{if($.length)fD(Q,Y,$);else e9(Q)})}return z}Hz.coerceAndCheckDataType=uD;var Jz=new Set(["string","number","integer","boolean","null"]);function hD(Q,Y){return Y?Q.filter((X)=>Jz.has(X)||Y==="array"&&X==="array"):[]}function fD(Q,Y,X){let{gen:W,data:G,opts:$}=Q,z=W.let("dataType",x._`typeof ${G}`),J=W.let("coerced",x._`undefined`);if($.coerceTypes==="array")W.if(x._`${z} == 'object' && Array.isArray(${G}) && ${G}.length == 1`,()=>W.assign(G,x._`${G}[0]`).assign(z,x._`typeof ${G}`).if(s9(Y,G,$.strictNumbers),()=>W.assign(J,G)));W.if(x._`${J} !== undefined`);for(let A of X)if(Jz.has(A)||A==="array"&&$.coerceTypes==="array")H(A);W.else(),e9(Q),W.endIf(),W.if(x._`${J} !== undefined`,()=>{W.assign(G,J),lD(Q,J)});function H(A){switch(A){case"string":W.elseIf(x._`${z} == "number" || ${z} == "boolean"`).assign(J,x._`"" + ${G}`).elseIf(x._`${G} === null`).assign(J,x._`""`);return;case"number":W.elseIf(x._`${z} == "boolean" || ${G} === null
4
4
  || (${z} == "string" && ${G} && ${G} == +${G})`).assign(J,x._`+${G}`);return;case"integer":W.elseIf(x._`${z} === "boolean" || ${G} === null
5
5
  || (${z} === "string" && ${G} && ${G} == +${G} && !(${G} % 1))`).assign(J,x._`+${G}`);return;case"boolean":W.elseIf(x._`${G} === "false" || ${G} === 0 || ${G} === null`).assign(J,!1).elseIf(x._`${G} === "true" || ${G} === 1`).assign(J,!0);return;case"null":W.elseIf(x._`${G} === "" || ${G} === 0 || ${G} === false`),W.assign(J,null);return;case"array":W.elseIf(x._`${z} === "string" || ${z} === "number"
6
- || ${z} === "boolean" || ${G} === null`).assign(J,x._`[${G}]`)}}}function _D({gen:Q,parentData:Y,parentDataProperty:X},W){Q.if(x._`${Y} !== undefined`,()=>Q.assign(x._`${Y}[${X}]`,W))}function a9(Q,Y,X,W=n1.Correct){let G=W===n1.Correct?x.operators.EQ:x.operators.NEQ,$;switch(Q){case"null":return x._`${Y} ${G} null`;case"array":$=x._`Array.isArray(${Y})`;break;case"object":$=x._`${Y} && typeof ${Y} == "object" && !Array.isArray(${Y})`;break;case"integer":$=z(x._`!(${Y} % 1) && !isNaN(${Y})`);break;case"number":$=z();break;default:return x._`typeof ${Y} ${G} ${Q}`}return W===n1.Correct?$:(0,x.not)($);function z(J=x.nil){return(0,x.and)(x._`typeof ${Y} == "number"`,J,X?x._`isFinite(${Y})`:x.nil)}}zz.checkDataType=a9;function s9(Q,Y,X,W){if(Q.length===1)return a9(Q[0],Y,X,W);let G,$=(0,Wz.toHash)(Q);if($.array&&$.object){let z=x._`typeof ${Y} != "object"`;G=$.null?z:x._`!${Y} || ${z}`,delete $.null,delete $.array,delete $.object}else G=x.nil;if($.number)delete $.integer;for(let z in $)G=(0,x.and)(G,a9(z,Y,X,W));return G}zz.checkDataTypes=s9;var gD={message:({schema:Q})=>`must be ${Q}`,params:({schema:Q,schemaValue:Y})=>typeof Q=="string"?x._`{type: ${Q}}`:x._`{type: ${Y}}`};function e9(Q){let Y=yD(Q);(0,RD.reportError)(Y,gD)}zz.reportTypeError=e9;function yD(Q){let{gen:Y,data:X,schema:W}=Q,G=(0,Wz.schemaRefOrVal)(Q,W,"type");return{gen:Y,keyword:"type",data:X,schema:W.type,schemaCode:G,schemaValue:G,parentSchema:W,params:{},it:Q}}});var Kz=P((Az)=>{Object.defineProperty(Az,"__esModule",{value:!0});Az.assignDefaults=void 0;var r1=g(),pD=c();function iD(Q,Y){let{properties:X,items:W}=Q.schema;if(Y==="object"&&X)for(let G in X)Hz(Q,G,X[G].default);else if(Y==="array"&&Array.isArray(W))W.forEach((G,$)=>Hz(Q,$,G.default))}Az.assignDefaults=iD;function Hz(Q,Y,X){let{gen:W,compositeRule:G,data:$,opts:z}=Q;if(X===void 0)return;let J=r1._`${$}${(0,r1.getProperty)(Y)}`;if(G){(0,pD.checkStrictMode)(Q,`default is ignored for: ${J}`);return}let H=r1._`${J} === undefined`;if(z.useDefaults==="empty")H=r1._`${H} || ${J} === null || ${J} === ""`;W.if(H,r1._`${J} = ${(0,r1.stringify)(X)}`)}});var C0=P((Lz)=>{Object.defineProperty(Lz,"__esModule",{value:!0});Lz.validateUnion=Lz.validateArray=Lz.usePattern=Lz.callValidateCode=Lz.schemaProperties=Lz.allSchemaProperties=Lz.noPropertyInData=Lz.propertyInData=Lz.isOwnProperty=Lz.hasPropFunc=Lz.reportMissingProp=Lz.checkMissingProp=Lz.checkReportMissingProp=void 0;var a=g(),QY=c(),q1=Y1(),nD=c();function rD(Q,Y){let{gen:X,data:W,it:G}=Q;X.if(XY(X,W,Y,G.opts.ownProperties),()=>{Q.setParams({missingProperty:a._`${Y}`},!0),Q.error()})}Lz.checkReportMissingProp=rD;function dD({gen:Q,data:Y,it:{opts:X}},W,G){return(0,a.or)(...W.map(($)=>(0,a.and)(XY(Q,Y,$,X.ownProperties),a._`${G} = ${$}`)))}Lz.checkMissingProp=dD;function oD(Q,Y){Q.setParams({missingProperty:Y},!0),Q.error()}Lz.reportMissingProp=oD;function Dz(Q){return Q.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:a._`Object.prototype.hasOwnProperty`})}Lz.hasPropFunc=Dz;function YY(Q,Y,X){return a._`${Dz(Q)}.call(${Y}, ${X})`}Lz.isOwnProperty=YY;function tD(Q,Y,X,W){let G=a._`${Y}${(0,a.getProperty)(X)} !== undefined`;return W?a._`${G} && ${YY(Q,Y,X)}`:G}Lz.propertyInData=tD;function XY(Q,Y,X,W){let G=a._`${Y}${(0,a.getProperty)(X)} === undefined`;return W?(0,a.or)(G,(0,a.not)(YY(Q,Y,X))):G}Lz.noPropertyInData=XY;function Bz(Q){return Q?Object.keys(Q).filter((Y)=>Y!=="__proto__"):[]}Lz.allSchemaProperties=Bz;function aD(Q,Y){return Bz(Y).filter((X)=>!(0,QY.alwaysValidSchema)(Q,Y[X]))}Lz.schemaProperties=aD;function sD({schemaCode:Q,data:Y,it:{gen:X,topSchemaRef:W,schemaPath:G,errorPath:$},it:z},J,H,A){let U=A?a._`${Q}, ${Y}, ${W}${G}`:Y,K=[[q1.default.instancePath,(0,a.strConcat)(q1.default.instancePath,$)],[q1.default.parentData,z.parentData],[q1.default.parentDataProperty,z.parentDataProperty],[q1.default.rootData,q1.default.rootData]];if(z.opts.dynamicRef)K.push([q1.default.dynamicAnchors,q1.default.dynamicAnchors]);let D=a._`${U}, ${X.object(...K)}`;return H!==a.nil?a._`${J}.call(${H}, ${D})`:a._`${J}(${D})`}Lz.callValidateCode=sD;var eD=a._`new RegExp`;function QB({gen:Q,it:{opts:Y}},X){let W=Y.unicodeRegExp?"u":"",{regExp:G}=Y.code,$=G(X,W);return Q.scopeValue("pattern",{key:$.toString(),ref:$,code:a._`${G.code==="new RegExp"?eD:(0,nD.useFunc)(Q,G)}(${X}, ${W})`})}Lz.usePattern=QB;function YB(Q){let{gen:Y,data:X,keyword:W,it:G}=Q,$=Y.name("valid");if(G.allErrors){let J=Y.let("valid",!0);return z(()=>Y.assign(J,!1)),J}return Y.var($,!0),z(()=>Y.break()),$;function z(J){let H=Y.const("len",a._`${X}.length`);Y.forRange("i",0,H,(A)=>{Q.subschema({keyword:W,dataProp:A,dataPropType:QY.Type.Num},$),Y.if((0,a.not)($),J)})}}Lz.validateArray=YB;function XB(Q){let{gen:Y,schema:X,keyword:W,it:G}=Q;if(!Array.isArray(X))throw Error("ajv implementation error");if(X.some((H)=>(0,QY.alwaysValidSchema)(G,H))&&!G.opts.unevaluated)return;let z=Y.let("valid",!1),J=Y.name("_valid");Y.block(()=>X.forEach((H,A)=>{let U=Q.subschema({keyword:W,schemaProp:A,compositeRule:!0},J);if(Y.assign(z,a._`${z} || ${J}`),!Q.mergeValidEvaluated(U,J))Y.if((0,a.not)(z))})),Q.result(z,()=>Q.reset(),()=>Q.error(!0))}Lz.validateUnion=XB});var Zz=P((Mz)=>{Object.defineProperty(Mz,"__esModule",{value:!0});Mz.validateKeywordUsage=Mz.validSchemaType=Mz.funcKeywordCode=Mz.macroKeywordCode=void 0;var M0=g(),S1=Y1(),FB=C0(),qB=k4();function OB(Q,Y){let{gen:X,keyword:W,schema:G,parentSchema:$,it:z}=Q,J=Y.macro.call(z.self,G,$,z),H=Oz(X,W,J);if(z.opts.validateSchema!==!1)z.self.validateSchema(J,!0);let A=X.name("valid");Q.subschema({schema:J,schemaPath:M0.nil,errSchemaPath:`${z.errSchemaPath}/${W}`,topSchemaRef:H,compositeRule:!0},A),Q.pass(A,()=>Q.error(!0))}Mz.macroKeywordCode=OB;function MB(Q,Y){var X;let{gen:W,keyword:G,schema:$,parentSchema:z,$data:J,it:H}=Q;ZB(H,Y);let A=!J&&Y.compile?Y.compile.call(H.self,$,z,H):Y.validate,U=Oz(W,G,A),K=W.let("valid");Q.block$data(K,D),Q.ok((X=Y.valid)!==null&&X!==void 0?X:K);function D(){if(Y.errors===!1){if(M(),Y.modifying)qz(Q);N(()=>Q.error())}else{let Z=Y.async?L():O();if(Y.modifying)qz(Q);N(()=>VB(Q,Z))}}function L(){let Z=W.let("ruleErrs",null);return W.try(()=>M(M0._`await `),(k)=>W.assign(K,!1).if(M0._`${k} instanceof ${H.ValidationError}`,()=>W.assign(Z,M0._`${k}.errors`),()=>W.throw(k))),Z}function O(){let Z=M0._`${U}.errors`;return W.assign(Z,null),M(M0.nil),Z}function M(Z=Y.async?M0._`await `:M0.nil){let k=H.opts.passContext?S1.default.this:S1.default.self,S=!(("compile"in Y)&&!J||Y.schema===!1);W.assign(K,M0._`${Z}${(0,FB.callValidateCode)(Q,U,k,S)}`,Y.modifying)}function N(Z){var k;W.if((0,M0.not)((k=Y.valid)!==null&&k!==void 0?k:K),Z)}}Mz.funcKeywordCode=MB;function qz(Q){let{gen:Y,data:X,it:W}=Q;Y.if(W.parentData,()=>Y.assign(X,M0._`${W.parentData}[${W.parentDataProperty}]`))}function VB(Q,Y){let{gen:X}=Q;X.if(M0._`Array.isArray(${Y})`,()=>{X.assign(S1.default.vErrors,M0._`${S1.default.vErrors} === null ? ${Y} : ${S1.default.vErrors}.concat(${Y})`).assign(S1.default.errors,M0._`${S1.default.vErrors}.length`),(0,qB.extendErrors)(Q)},()=>Q.error())}function ZB({schemaEnv:Q},Y){if(Y.async&&!Q.$async)throw Error("async keyword in sync schema")}function Oz(Q,Y,X){if(X===void 0)throw Error(`keyword "${Y}" failed to compile`);return Q.scopeValue("keyword",typeof X=="function"?{ref:X}:{ref:X,code:(0,M0.stringify)(X)})}function NB(Q,Y,X=!1){return!Y.length||Y.some((W)=>W==="array"?Array.isArray(Q):W==="object"?Q&&typeof Q=="object"&&!Array.isArray(Q):typeof Q==W||X&&typeof Q>"u")}Mz.validSchemaType=NB;function wB({schema:Q,opts:Y,self:X,errSchemaPath:W},G,$){if(Array.isArray(G.keyword)?!G.keyword.includes($):G.keyword!==$)throw Error("ajv implementation error");let z=G.dependencies;if(z===null||z===void 0?void 0:z.some((J)=>!Object.prototype.hasOwnProperty.call(Q,J)))throw Error(`parent schema must have dependencies of ${$}: ${z.join(",")}`);if(G.validateSchema){if(!G.validateSchema(Q[$])){let H=`keyword "${$}" value is invalid at path "${W}": `+X.errorsText(G.validateSchema.errors);if(Y.validateSchema==="log")X.logger.error(H);else throw Error(H)}}}Mz.validateKeywordUsage=wB});var bz=P((wz)=>{Object.defineProperty(wz,"__esModule",{value:!0});wz.extendSubschemaMode=wz.extendSubschemaData=wz.getSubschema=void 0;var p0=g(),Nz=c();function IB(Q,{keyword:Y,schemaProp:X,schema:W,schemaPath:G,errSchemaPath:$,topSchemaRef:z}){if(Y!==void 0&&W!==void 0)throw Error('both "keyword" and "schema" passed, only one allowed');if(Y!==void 0){let J=Q.schema[Y];return X===void 0?{schema:J,schemaPath:p0._`${Q.schemaPath}${(0,p0.getProperty)(Y)}`,errSchemaPath:`${Q.errSchemaPath}/${Y}`}:{schema:J[X],schemaPath:p0._`${Q.schemaPath}${(0,p0.getProperty)(Y)}${(0,p0.getProperty)(X)}`,errSchemaPath:`${Q.errSchemaPath}/${Y}/${(0,Nz.escapeFragment)(X)}`}}if(W!==void 0){if(G===void 0||$===void 0||z===void 0)throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:W,schemaPath:G,topSchemaRef:z,errSchemaPath:$}}throw Error('either "keyword" or "schema" must be passed')}wz.getSubschema=IB;function EB(Q,Y,{dataProp:X,dataPropType:W,data:G,dataTypes:$,propertyName:z}){if(G!==void 0&&X!==void 0)throw Error('both "data" and "dataProp" passed, only one allowed');let{gen:J}=Y;if(X!==void 0){let{errorPath:A,dataPathArr:U,opts:K}=Y,D=J.let("data",p0._`${Y.data}${(0,p0.getProperty)(X)}`,!0);H(D),Q.errorPath=p0.str`${A}${(0,Nz.getErrorPath)(X,W,K.jsPropertySyntax)}`,Q.parentDataProperty=p0._`${X}`,Q.dataPathArr=[...U,Q.parentDataProperty]}if(G!==void 0){let A=G instanceof p0.Name?G:J.let("data",G,!0);if(H(A),z!==void 0)Q.propertyName=z}if($)Q.dataTypes=$;function H(A){Q.data=A,Q.dataLevel=Y.dataLevel+1,Q.dataTypes=[],Y.definedProperties=new Set,Q.parentData=Y.data,Q.dataNames=[...Y.dataNames,A]}}wz.extendSubschemaData=EB;function TB(Q,{jtdDiscriminator:Y,jtdMetadata:X,compositeRule:W,createErrors:G,allErrors:$}){if(W!==void 0)Q.compositeRule=W;if(G!==void 0)Q.createErrors=G;if($!==void 0)Q.allErrors=$;Q.jtdDiscriminator=Y,Q.jtdMetadata=X}wz.extendSubschemaMode=TB});var WY=P((II,jz)=>{jz.exports=function Q(Y,X){if(Y===X)return!0;if(Y&&X&&typeof Y=="object"&&typeof X=="object"){if(Y.constructor!==X.constructor)return!1;var W,G,$;if(Array.isArray(Y)){if(W=Y.length,W!=X.length)return!1;for(G=W;G--!==0;)if(!Q(Y[G],X[G]))return!1;return!0}if(Y.constructor===RegExp)return Y.source===X.source&&Y.flags===X.flags;if(Y.valueOf!==Object.prototype.valueOf)return Y.valueOf()===X.valueOf();if(Y.toString!==Object.prototype.toString)return Y.toString()===X.toString();if($=Object.keys(Y),W=$.length,W!==Object.keys(X).length)return!1;for(G=W;G--!==0;)if(!Object.prototype.hasOwnProperty.call(X,$[G]))return!1;for(G=W;G--!==0;){var z=$[G];if(!Q(Y[z],X[z]))return!1}return!0}return Y!==Y&&X!==X}});var Ez=P((EI,Iz)=>{var O1=Iz.exports=function(Q,Y,X){if(typeof Y=="function")X=Y,Y={};X=Y.cb||X;var W=typeof X=="function"?X:X.pre||function(){},G=X.post||function(){};o6(Y,W,G,Q,"",Q)};O1.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};O1.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};O1.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};O1.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 o6(Q,Y,X,W,G,$,z,J,H,A){if(W&&typeof W=="object"&&!Array.isArray(W)){Y(W,G,$,z,J,H,A);for(var U in W){var K=W[U];if(Array.isArray(K)){if(U in O1.arrayKeywords)for(var D=0;D<K.length;D++)o6(Q,Y,X,K[D],G+"/"+U+"/"+D,$,G,U,W,D)}else if(U in O1.propsKeywords){if(K&&typeof K=="object")for(var L in K)o6(Q,Y,X,K[L],G+"/"+U+"/"+CB(L),$,G,U,W,L)}else if(U in O1.keywords||Q.allKeys&&!(U in O1.skipKeywords))o6(Q,Y,X,K,G+"/"+U,$,G,U,W)}X(W,G,$,z,J,H,A)}}function CB(Q){return Q.replace(/~/g,"~0").replace(/\//g,"~1")}});var x4=P((Cz)=>{Object.defineProperty(Cz,"__esModule",{value:!0});Cz.getSchemaRefs=Cz.resolveUrl=Cz.normalizeId=Cz._getFullPath=Cz.getFullPath=Cz.inlineRef=void 0;var kB=c(),vB=WY(),xB=Ez(),_B=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function gB(Q,Y=!0){if(typeof Q=="boolean")return!0;if(Y===!0)return!GY(Q);if(!Y)return!1;return Tz(Q)<=Y}Cz.inlineRef=gB;var yB=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function GY(Q){for(let Y in Q){if(yB.has(Y))return!0;let X=Q[Y];if(Array.isArray(X)&&X.some(GY))return!0;if(typeof X=="object"&&GY(X))return!0}return!1}function Tz(Q){let Y=0;for(let X in Q){if(X==="$ref")return 1/0;if(Y++,_B.has(X))continue;if(typeof Q[X]=="object")(0,kB.eachItem)(Q[X],(W)=>Y+=Tz(W));if(Y===1/0)return 1/0}return Y}function Sz(Q,Y="",X){if(X!==!1)Y=d1(Y);let W=Q.parse(Y);return Rz(Q,W)}Cz.getFullPath=Sz;function Rz(Q,Y){return Q.serialize(Y).split("#")[0]+"#"}Cz._getFullPath=Rz;var uB=/#\/?$/;function d1(Q){return Q?Q.replace(uB,""):""}Cz.normalizeId=d1;function hB(Q,Y,X){return X=d1(X),Q.resolve(Y,X)}Cz.resolveUrl=hB;var fB=/^[a-z_][-a-z0-9._]*$/i;function lB(Q,Y){if(typeof Q=="boolean")return{};let{schemaId:X,uriResolver:W}=this.opts,G=d1(Q[X]||Y),$={"":G},z=Sz(W,G,!1),J={},H=new Set;return xB(Q,{allKeys:!0},(K,D,L,O)=>{if(O===void 0)return;let M=z+D,N=$[O];if(typeof K[X]=="string")N=Z.call(this,K[X]);k.call(this,K.$anchor),k.call(this,K.$dynamicAnchor),$[D]=N;function Z(S){let y=this.opts.uriResolver.resolve;if(S=d1(N?y(N,S):S),H.has(S))throw U(S);H.add(S);let C=this.refs[S];if(typeof C=="string")C=this.refs[C];if(typeof C=="object")A(K,C.schema,S);else if(S!==d1(M))if(S[0]==="#")A(K,J[S],S),J[S]=K;else this.refs[S]=M;return S}function k(S){if(typeof S=="string"){if(!fB.test(S))throw Error(`invalid anchor "${S}"`);Z.call(this,`#${S}`)}}}),J;function A(K,D,L){if(D!==void 0&&!vB(K,D))throw U(L)}function U(K){return Error(`reference "${K}" resolves to more than one schema`)}}Cz.getSchemaRefs=lB});var y4=P((rz)=>{Object.defineProperty(rz,"__esModule",{value:!0});rz.getData=rz.KeywordCxt=rz.validateFunctionCode=void 0;var yz=t$(),vz=v4(),zY=t9(),t6=v4(),rB=Kz(),g4=Zz(),$Y=bz(),I=g(),v=Y1(),dB=x4(),X1=c(),_4=k4();function oB(Q){if(fz(Q)){if(lz(Q),hz(Q)){sB(Q);return}}uz(Q,()=>(0,yz.topBoolOrEmptySchema)(Q))}rz.validateFunctionCode=oB;function uz({gen:Q,validateName:Y,schema:X,schemaEnv:W,opts:G},$){if(G.code.es5)Q.func(Y,I._`${v.default.data}, ${v.default.valCxt}`,W.$async,()=>{Q.code(I._`"use strict"; ${xz(X,G)}`),aB(Q,G),Q.code($)});else Q.func(Y,I._`${v.default.data}, ${tB(G)}`,W.$async,()=>Q.code(xz(X,G)).code($))}function tB(Q){return I._`{${v.default.instancePath}="", ${v.default.parentData}, ${v.default.parentDataProperty}, ${v.default.rootData}=${v.default.data}${Q.dynamicRef?I._`, ${v.default.dynamicAnchors}={}`:I.nil}}={}`}function aB(Q,Y){Q.if(v.default.valCxt,()=>{if(Q.var(v.default.instancePath,I._`${v.default.valCxt}.${v.default.instancePath}`),Q.var(v.default.parentData,I._`${v.default.valCxt}.${v.default.parentData}`),Q.var(v.default.parentDataProperty,I._`${v.default.valCxt}.${v.default.parentDataProperty}`),Q.var(v.default.rootData,I._`${v.default.valCxt}.${v.default.rootData}`),Y.dynamicRef)Q.var(v.default.dynamicAnchors,I._`${v.default.valCxt}.${v.default.dynamicAnchors}`)},()=>{if(Q.var(v.default.instancePath,I._`""`),Q.var(v.default.parentData,I._`undefined`),Q.var(v.default.parentDataProperty,I._`undefined`),Q.var(v.default.rootData,v.default.data),Y.dynamicRef)Q.var(v.default.dynamicAnchors,I._`{}`)})}function sB(Q){let{schema:Y,opts:X,gen:W}=Q;uz(Q,()=>{if(X.$comment&&Y.$comment)cz(Q);if(WL(Q),W.let(v.default.vErrors,null),W.let(v.default.errors,0),X.unevaluated)eB(Q);mz(Q),zL(Q)});return}function eB(Q){let{gen:Y,validateName:X}=Q;Q.evaluated=Y.const("evaluated",I._`${X}.evaluated`),Y.if(I._`${Q.evaluated}.dynamicProps`,()=>Y.assign(I._`${Q.evaluated}.props`,I._`undefined`)),Y.if(I._`${Q.evaluated}.dynamicItems`,()=>Y.assign(I._`${Q.evaluated}.items`,I._`undefined`))}function xz(Q,Y){let X=typeof Q=="object"&&Q[Y.schemaId];return X&&(Y.code.source||Y.code.process)?I._`/*# sourceURL=${X} */`:I.nil}function QL(Q,Y){if(fz(Q)){if(lz(Q),hz(Q)){YL(Q,Y);return}}(0,yz.boolOrEmptySchema)(Q,Y)}function hz({schema:Q,self:Y}){if(typeof Q=="boolean")return!Q;for(let X in Q)if(Y.RULES.all[X])return!0;return!1}function fz(Q){return typeof Q.schema!="boolean"}function YL(Q,Y){let{schema:X,gen:W,opts:G}=Q;if(G.$comment&&X.$comment)cz(Q);GL(Q),$L(Q);let $=W.const("_errs",v.default.errors);mz(Q,$),W.var(Y,I._`${$} === ${v.default.errors}`)}function lz(Q){(0,X1.checkUnknownRules)(Q),XL(Q)}function mz(Q,Y){if(Q.opts.jtd)return _z(Q,[],!1,Y);let X=(0,vz.getSchemaTypes)(Q.schema),W=(0,vz.coerceAndCheckDataType)(Q,X);_z(Q,X,!W,Y)}function XL(Q){let{schema:Y,errSchemaPath:X,opts:W,self:G}=Q;if(Y.$ref&&W.ignoreKeywordsWithRef&&(0,X1.schemaHasRulesButRef)(Y,G.RULES))G.logger.warn(`$ref: keywords ignored in schema at path "${X}"`)}function WL(Q){let{schema:Y,opts:X}=Q;if(Y.default!==void 0&&X.useDefaults&&X.strictSchema)(0,X1.checkStrictMode)(Q,"default is ignored in the schema root")}function GL(Q){let Y=Q.schema[Q.opts.schemaId];if(Y)Q.baseId=(0,dB.resolveUrl)(Q.opts.uriResolver,Q.baseId,Y)}function $L(Q){if(Q.schema.$async&&!Q.schemaEnv.$async)throw Error("async schema in sync schema")}function cz({gen:Q,schemaEnv:Y,schema:X,errSchemaPath:W,opts:G}){let $=X.$comment;if(G.$comment===!0)Q.code(I._`${v.default.self}.logger.log(${$})`);else if(typeof G.$comment=="function"){let z=I.str`${W}/$comment`,J=Q.scopeValue("root",{ref:Y.root});Q.code(I._`${v.default.self}.opts.$comment(${$}, ${z}, ${J}.schema)`)}}function zL(Q){let{gen:Y,schemaEnv:X,validateName:W,ValidationError:G,opts:$}=Q;if(X.$async)Y.if(I._`${v.default.errors} === 0`,()=>Y.return(v.default.data),()=>Y.throw(I._`new ${G}(${v.default.vErrors})`));else{if(Y.assign(I._`${W}.errors`,v.default.vErrors),$.unevaluated)JL(Q);Y.return(I._`${v.default.errors} === 0`)}}function JL({gen:Q,evaluated:Y,props:X,items:W}){if(X instanceof I.Name)Q.assign(I._`${Y}.props`,X);if(W instanceof I.Name)Q.assign(I._`${Y}.items`,W)}function _z(Q,Y,X,W){let{gen:G,schema:$,data:z,allErrors:J,opts:H,self:A}=Q,{RULES:U}=A;if($.$ref&&(H.ignoreKeywordsWithRef||!(0,X1.schemaHasRulesButRef)($,U))){G.block(()=>iz(Q,"$ref",U.all.$ref.definition));return}if(!H.jtd)HL(Q,Y);G.block(()=>{for(let D of U.rules)K(D);K(U.post)});function K(D){if(!(0,zY.shouldUseGroup)($,D))return;if(D.type){if(G.if((0,t6.checkDataType)(D.type,z,H.strictNumbers)),gz(Q,D),Y.length===1&&Y[0]===D.type&&X)G.else(),(0,t6.reportTypeError)(Q);G.endIf()}else gz(Q,D);if(!J)G.if(I._`${v.default.errors} === ${W||0}`)}}function gz(Q,Y){let{gen:X,schema:W,opts:{useDefaults:G}}=Q;if(G)(0,rB.assignDefaults)(Q,Y.type);X.block(()=>{for(let $ of Y.rules)if((0,zY.shouldUseRule)(W,$))iz(Q,$.keyword,$.definition,Y.type)})}function HL(Q,Y){if(Q.schemaEnv.meta||!Q.opts.strictTypes)return;if(AL(Q,Y),!Q.opts.allowUnionTypes)UL(Q,Y);KL(Q,Q.dataTypes)}function AL(Q,Y){if(!Y.length)return;if(!Q.dataTypes.length){Q.dataTypes=Y;return}Y.forEach((X)=>{if(!pz(Q.dataTypes,X))JY(Q,`type "${X}" not allowed by context "${Q.dataTypes.join(",")}"`)}),BL(Q,Y)}function UL(Q,Y){if(Y.length>1&&!(Y.length===2&&Y.includes("null")))JY(Q,"use allowUnionTypes to allow union type keyword")}function KL(Q,Y){let X=Q.self.RULES.all;for(let W in X){let G=X[W];if(typeof G=="object"&&(0,zY.shouldUseRule)(Q.schema,G)){let{type:$}=G.definition;if($.length&&!$.some((z)=>DL(Y,z)))JY(Q,`missing type "${$.join(",")}" for keyword "${W}"`)}}}function DL(Q,Y){return Q.includes(Y)||Y==="number"&&Q.includes("integer")}function pz(Q,Y){return Q.includes(Y)||Y==="integer"&&Q.includes("number")}function BL(Q,Y){let X=[];for(let W of Q.dataTypes)if(pz(Y,W))X.push(W);else if(Y.includes("integer")&&W==="number")X.push("integer");Q.dataTypes=X}function JY(Q,Y){let X=Q.schemaEnv.baseId+Q.errSchemaPath;Y+=` at "${X}" (strictTypes)`,(0,X1.checkStrictMode)(Q,Y,Q.opts.strictTypes)}class HY{constructor(Q,Y,X){if((0,g4.validateKeywordUsage)(Q,Y,X),this.gen=Q.gen,this.allErrors=Q.allErrors,this.keyword=X,this.data=Q.data,this.schema=Q.schema[X],this.$data=Y.$data&&Q.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,X1.schemaRefOrVal)(Q,this.schema,X,this.$data),this.schemaType=Y.schemaType,this.parentSchema=Q.schema,this.params={},this.it=Q,this.def=Y,this.$data)this.schemaCode=Q.gen.const("vSchema",nz(this.$data,Q));else if(this.schemaCode=this.schemaValue,!(0,g4.validSchemaType)(this.schema,Y.schemaType,Y.allowUndefined))throw Error(`${X} value must be ${JSON.stringify(Y.schemaType)}`);if("code"in Y?Y.trackErrors:Y.errors!==!1)this.errsCount=Q.gen.const("_errs",v.default.errors)}result(Q,Y,X){this.failResult((0,I.not)(Q),Y,X)}failResult(Q,Y,X){if(this.gen.if(Q),X)X();else this.error();if(Y){if(this.gen.else(),Y(),this.allErrors)this.gen.endIf()}else if(this.allErrors)this.gen.endIf();else this.gen.else()}pass(Q,Y){this.failResult((0,I.not)(Q),void 0,Y)}fail(Q){if(Q===void 0){if(this.error(),!this.allErrors)this.gen.if(!1);return}if(this.gen.if(Q),this.error(),this.allErrors)this.gen.endIf();else this.gen.else()}fail$data(Q){if(!this.$data)return this.fail(Q);let{schemaCode:Y}=this;this.fail(I._`${Y} !== undefined && (${(0,I.or)(this.invalid$data(),Q)})`)}error(Q,Y,X){if(Y){this.setParams(Y),this._error(Q,X),this.setParams({});return}this._error(Q,X)}_error(Q,Y){(Q?_4.reportExtraError:_4.reportError)(this,this.def.error,Y)}$dataError(){(0,_4.reportError)(this,this.def.$dataError||_4.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error('add "trackErrors" to keyword definition');(0,_4.resetErrorsCount)(this.gen,this.errsCount)}ok(Q){if(!this.allErrors)this.gen.if(Q)}setParams(Q,Y){if(Y)Object.assign(this.params,Q);else this.params=Q}block$data(Q,Y,X=I.nil){this.gen.block(()=>{this.check$data(Q,X),Y()})}check$data(Q=I.nil,Y=I.nil){if(!this.$data)return;let{gen:X,schemaCode:W,schemaType:G,def:$}=this;if(X.if((0,I.or)(I._`${W} === undefined`,Y)),Q!==I.nil)X.assign(Q,!0);if(G.length||$.validateSchema){if(X.elseIf(this.invalid$data()),this.$dataError(),Q!==I.nil)X.assign(Q,!1)}X.else()}invalid$data(){let{gen:Q,schemaCode:Y,schemaType:X,def:W,it:G}=this;return(0,I.or)($(),z());function $(){if(X.length){if(!(Y instanceof I.Name))throw Error("ajv implementation error");let J=Array.isArray(X)?X:[X];return I._`${(0,t6.checkDataTypes)(J,Y,G.opts.strictNumbers,t6.DataType.Wrong)}`}return I.nil}function z(){if(W.validateSchema){let J=Q.scopeValue("validate$data",{ref:W.validateSchema});return I._`!${J}(${Y})`}return I.nil}}subschema(Q,Y){let X=(0,$Y.getSubschema)(this.it,Q);(0,$Y.extendSubschemaData)(X,this.it,Q),(0,$Y.extendSubschemaMode)(X,Q);let W={...this.it,...X,items:void 0,props:void 0};return QL(W,Y),W}mergeEvaluated(Q,Y){let{it:X,gen:W}=this;if(!X.opts.unevaluated)return;if(X.props!==!0&&Q.props!==void 0)X.props=X1.mergeEvaluated.props(W,Q.props,X.props,Y);if(X.items!==!0&&Q.items!==void 0)X.items=X1.mergeEvaluated.items(W,Q.items,X.items,Y)}mergeValidEvaluated(Q,Y){let{it:X,gen:W}=this;if(X.opts.unevaluated&&(X.props!==!0||X.items!==!0))return W.if(Y,()=>this.mergeEvaluated(Q,I.Name)),!0}}rz.KeywordCxt=HY;function iz(Q,Y,X,W){let G=new HY(Q,X,Y);if("code"in X)X.code(G,W);else if(G.$data&&X.validate)(0,g4.funcKeywordCode)(G,X);else if("macro"in X)(0,g4.macroKeywordCode)(G,X);else if(X.compile||X.validate)(0,g4.funcKeywordCode)(G,X)}var LL=/^\/(?:[^~]|~0|~1)*$/,FL=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function nz(Q,{dataLevel:Y,dataNames:X,dataPathArr:W}){let G,$;if(Q==="")return v.default.rootData;if(Q[0]==="/"){if(!LL.test(Q))throw Error(`Invalid JSON-pointer: ${Q}`);G=Q,$=v.default.rootData}else{let A=FL.exec(Q);if(!A)throw Error(`Invalid JSON-pointer: ${Q}`);let U=+A[1];if(G=A[2],G==="#"){if(U>=Y)throw Error(H("property/index",U));return W[Y-U]}if(U>Y)throw Error(H("data",U));if($=X[Y-U],!G)return $}let z=$,J=G.split("/");for(let A of J)if(A)$=I._`${$}${(0,I.getProperty)((0,X1.unescapeJsonPointer)(A))}`,z=I._`${z} && ${$}`;return z;function H(A,U){return`Cannot access ${A} ${U} levels up, current level is ${Y}`}}rz.getData=nz});var a6=P((tz)=>{Object.defineProperty(tz,"__esModule",{value:!0});class oz extends Error{constructor(Q){super("validation failed");this.errors=Q,this.ajv=this.validation=!0}}tz.default=oz});var u4=P((sz)=>{Object.defineProperty(sz,"__esModule",{value:!0});var AY=x4();class az extends Error{constructor(Q,Y,X,W){super(W||`can't resolve reference ${X} from id ${Y}`);this.missingRef=(0,AY.resolveUrl)(Q,Y,X),this.missingSchema=(0,AY.normalizeId)((0,AY.getFullPath)(Q,this.missingRef))}}sz.default=az});var e6=P((YJ)=>{Object.defineProperty(YJ,"__esModule",{value:!0});YJ.resolveSchema=YJ.getCompilingSchema=YJ.resolveRef=YJ.compileSchema=YJ.SchemaEnv=void 0;var y0=g(),ZL=a6(),R1=Y1(),u0=x4(),ez=c(),NL=y4();class h4{constructor(Q){var Y;this.refs={},this.dynamicAnchors={};let X;if(typeof Q.schema=="object")X=Q.schema;this.schema=Q.schema,this.schemaId=Q.schemaId,this.root=Q.root||this,this.baseId=(Y=Q.baseId)!==null&&Y!==void 0?Y:(0,u0.normalizeId)(X===null||X===void 0?void 0:X[Q.schemaId||"$id"]),this.schemaPath=Q.schemaPath,this.localRefs=Q.localRefs,this.meta=Q.meta,this.$async=X===null||X===void 0?void 0:X.$async,this.refs={}}}YJ.SchemaEnv=h4;function KY(Q){let Y=QJ.call(this,Q);if(Y)return Y;let X=(0,u0.getFullPath)(this.opts.uriResolver,Q.root.baseId),{es5:W,lines:G}=this.opts.code,{ownProperties:$}=this.opts,z=new y0.CodeGen(this.scope,{es5:W,lines:G,ownProperties:$}),J;if(Q.$async)J=z.scopeValue("Error",{ref:ZL.default,code:y0._`require("ajv/dist/runtime/validation_error").default`});let H=z.scopeName("validate");Q.validateName=H;let A={gen:z,allErrors:this.opts.allErrors,data:R1.default.data,parentData:R1.default.parentData,parentDataProperty:R1.default.parentDataProperty,dataNames:[R1.default.data],dataPathArr:[y0.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:z.scopeValue("schema",this.opts.code.source===!0?{ref:Q.schema,code:(0,y0.stringify)(Q.schema)}:{ref:Q.schema}),validateName:H,ValidationError:J,schema:Q.schema,schemaEnv:Q,rootId:X,baseId:Q.baseId||X,schemaPath:y0.nil,errSchemaPath:Q.schemaPath||(this.opts.jtd?"":"#"),errorPath:y0._`""`,opts:this.opts,self:this},U;try{this._compilations.add(Q),(0,NL.validateFunctionCode)(A),z.optimize(this.opts.code.optimize);let K=z.toString();if(U=`${z.scopeRefs(R1.default.scope)}return ${K}`,this.opts.code.process)U=this.opts.code.process(U,Q);let L=Function(`${R1.default.self}`,`${R1.default.scope}`,U)(this,this.scope.get());if(this.scope.value(H,{ref:L}),L.errors=null,L.schema=Q.schema,L.schemaEnv=Q,Q.$async)L.$async=!0;if(this.opts.code.source===!0)L.source={validateName:H,validateCode:K,scopeValues:z._values};if(this.opts.unevaluated){let{props:O,items:M}=A;if(L.evaluated={props:O instanceof y0.Name?void 0:O,items:M instanceof y0.Name?void 0:M,dynamicProps:O instanceof y0.Name,dynamicItems:M instanceof y0.Name},L.source)L.source.evaluated=(0,y0.stringify)(L.evaluated)}return Q.validate=L,Q}catch(K){if(delete Q.validate,delete Q.validateName,U)this.logger.error("Error compiling schema, function code:",U);throw K}finally{this._compilations.delete(Q)}}YJ.compileSchema=KY;function wL(Q,Y,X){var W;X=(0,u0.resolveUrl)(this.opts.uriResolver,Y,X);let G=Q.refs[X];if(G)return G;let $=jL.call(this,Q,X);if($===void 0){let z=(W=Q.localRefs)===null||W===void 0?void 0:W[X],{schemaId:J}=this.opts;if(z)$=new h4({schema:z,schemaId:J,root:Q,baseId:Y})}if($===void 0)return;return Q.refs[X]=PL.call(this,$)}YJ.resolveRef=wL;function PL(Q){if((0,u0.inlineRef)(Q.schema,this.opts.inlineRefs))return Q.schema;return Q.validate?Q:KY.call(this,Q)}function QJ(Q){for(let Y of this._compilations)if(bL(Y,Q))return Y}YJ.getCompilingSchema=QJ;function bL(Q,Y){return Q.schema===Y.schema&&Q.root===Y.root&&Q.baseId===Y.baseId}function jL(Q,Y){let X;while(typeof(X=this.refs[Y])=="string")Y=X;return X||this.schemas[Y]||s6.call(this,Q,Y)}function s6(Q,Y){let X=this.opts.uriResolver.parse(Y),W=(0,u0._getFullPath)(this.opts.uriResolver,X),G=(0,u0.getFullPath)(this.opts.uriResolver,Q.baseId,void 0);if(Object.keys(Q.schema).length>0&&W===G)return UY.call(this,X,Q);let $=(0,u0.normalizeId)(W),z=this.refs[$]||this.schemas[$];if(typeof z=="string"){let J=s6.call(this,Q,z);if(typeof(J===null||J===void 0?void 0:J.schema)!=="object")return;return UY.call(this,X,J)}if(typeof(z===null||z===void 0?void 0:z.schema)!=="object")return;if(!z.validate)KY.call(this,z);if($===(0,u0.normalizeId)(Y)){let{schema:J}=z,{schemaId:H}=this.opts,A=J[H];if(A)G=(0,u0.resolveUrl)(this.opts.uriResolver,G,A);return new h4({schema:J,schemaId:H,root:Q,baseId:G})}return UY.call(this,X,z)}YJ.resolveSchema=s6;var IL=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function UY(Q,{baseId:Y,schema:X,root:W}){var G;if(((G=Q.fragment)===null||G===void 0?void 0:G[0])!=="/")return;for(let J of Q.fragment.slice(1).split("/")){if(typeof X==="boolean")return;let H=X[(0,ez.unescapeFragment)(J)];if(H===void 0)return;X=H;let A=typeof X==="object"&&X[this.opts.schemaId];if(!IL.has(J)&&A)Y=(0,u0.resolveUrl)(this.opts.uriResolver,Y,A)}let $;if(typeof X!="boolean"&&X.$ref&&!(0,ez.schemaHasRulesButRef)(X,this.RULES)){let J=(0,u0.resolveUrl)(this.opts.uriResolver,Y,X.$ref);$=s6.call(this,W,J)}let{schemaId:z}=this.opts;if($=$||new h4({schema:X,schemaId:z,root:W,baseId:Y}),$.schema!==$.root.schema)return $;return}});var WJ=P((vI,CL)=>{CL.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 BY=P((xI,JJ)=>{var kL=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),$J=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 DY(Q){let Y="",X=0,W=0;for(W=0;W<Q.length;W++){if(X=Q[W].charCodeAt(0),X===48)continue;if(!(X>=48&&X<=57||X>=65&&X<=70||X>=97&&X<=102))return"";Y+=Q[W];break}for(W+=1;W<Q.length;W++){if(X=Q[W].charCodeAt(0),!(X>=48&&X<=57||X>=65&&X<=70||X>=97&&X<=102))return"";Y+=Q[W]}return Y}var vL=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function GJ(Q){return Q.length=0,!0}function xL(Q,Y,X){if(Q.length){let W=DY(Q);if(W!=="")Y.push(W);else return X.error=!0,!1;Q.length=0}return!0}function _L(Q){let Y=0,X={error:!1,address:"",zone:""},W=[],G=[],$=!1,z=!1,J=xL;for(let H=0;H<Q.length;H++){let A=Q[H];if(A==="["||A==="]")continue;if(A===":"){if($===!0)z=!0;if(!J(G,W,X))break;if(++Y>7){X.error=!0;break}if(H>0&&Q[H-1]===":")$=!0;W.push(":");continue}else if(A==="%"){if(!J(G,W,X))break;J=GJ}else{G.push(A);continue}}if(G.length)if(J===GJ)X.zone=G.join("");else if(z)W.push(G.join(""));else W.push(DY(G));return X.address=W.join(""),X}function zJ(Q){if(gL(Q,":")<2)return{host:Q,isIPV6:!1};let Y=_L(Q);if(!Y.error){let{address:X,address:W}=Y;if(Y.zone)X+="%"+Y.zone,W+="%25"+Y.zone;return{host:X,isIPV6:!0,escapedHost:W}}else return{host:Q,isIPV6:!1}}function gL(Q,Y){let X=0;for(let W=0;W<Q.length;W++)if(Q[W]===Y)X++;return X}function yL(Q){let Y=Q,X=[],W=-1,G=0;while(G=Y.length){if(G===1)if(Y===".")break;else if(Y==="/"){X.push("/");break}else{X.push(Y);break}else if(G===2){if(Y[0]==="."){if(Y[1]===".")break;else if(Y[1]==="/"){Y=Y.slice(2);continue}}else if(Y[0]==="/"){if(Y[1]==="."||Y[1]==="/"){X.push("/");break}}}else if(G===3){if(Y==="/.."){if(X.length!==0)X.pop();X.push("/");break}}if(Y[0]==="."){if(Y[1]==="."){if(Y[2]==="/"){Y=Y.slice(3);continue}}else if(Y[1]==="/"){Y=Y.slice(2);continue}}else if(Y[0]==="/"){if(Y[1]==="."){if(Y[2]==="/"){Y=Y.slice(2);continue}else if(Y[2]==="."){if(Y[3]==="/"){if(Y=Y.slice(3),X.length!==0)X.pop();continue}}}}if((W=Y.indexOf("/",1))===-1){X.push(Y);break}else X.push(Y.slice(0,W)),Y=Y.slice(W)}return X.join("")}function uL(Q,Y){let X=Y!==!0?escape:unescape;if(Q.scheme!==void 0)Q.scheme=X(Q.scheme);if(Q.userinfo!==void 0)Q.userinfo=X(Q.userinfo);if(Q.host!==void 0)Q.host=X(Q.host);if(Q.path!==void 0)Q.path=X(Q.path);if(Q.query!==void 0)Q.query=X(Q.query);if(Q.fragment!==void 0)Q.fragment=X(Q.fragment);return Q}function hL(Q){let Y=[];if(Q.userinfo!==void 0)Y.push(Q.userinfo),Y.push("@");if(Q.host!==void 0){let X=unescape(Q.host);if(!$J(X)){let W=zJ(X);if(W.isIPV6===!0)X=`[${W.escapedHost}]`;else X=Q.host}Y.push(X)}if(typeof Q.port==="number"||typeof Q.port==="string")Y.push(":"),Y.push(String(Q.port));return Y.length?Y.join(""):void 0}JJ.exports={nonSimpleDomain:vL,recomposeAuthority:hL,normalizeComponentEncoding:uL,removeDotSegments:yL,isIPv4:$J,isUUID:kL,normalizeIPv6:zJ,stringArrayToHexStripped:DY}});var DJ=P((_I,KJ)=>{var{isUUID:fL}=BY(),lL=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,mL=["http","https","ws","wss","urn","urn:uuid"];function cL(Q){return mL.indexOf(Q)!==-1}function LY(Q){if(Q.secure===!0)return!0;else if(Q.secure===!1)return!1;else if(Q.scheme)return Q.scheme.length===3&&(Q.scheme[0]==="w"||Q.scheme[0]==="W")&&(Q.scheme[1]==="s"||Q.scheme[1]==="S")&&(Q.scheme[2]==="s"||Q.scheme[2]==="S");else return!1}function HJ(Q){if(!Q.host)Q.error=Q.error||"HTTP URIs must have a host.";return Q}function AJ(Q){let Y=String(Q.scheme).toLowerCase()==="https";if(Q.port===(Y?443:80)||Q.port==="")Q.port=void 0;if(!Q.path)Q.path="/";return Q}function pL(Q){return Q.secure=LY(Q),Q.resourceName=(Q.path||"/")+(Q.query?"?"+Q.query:""),Q.path=void 0,Q.query=void 0,Q}function iL(Q){if(Q.port===(LY(Q)?443:80)||Q.port==="")Q.port=void 0;if(typeof Q.secure==="boolean")Q.scheme=Q.secure?"wss":"ws",Q.secure=void 0;if(Q.resourceName){let[Y,X]=Q.resourceName.split("?");Q.path=Y&&Y!=="/"?Y:void 0,Q.query=X,Q.resourceName=void 0}return Q.fragment=void 0,Q}function nL(Q,Y){if(!Q.path)return Q.error="URN can not be parsed",Q;let X=Q.path.match(lL);if(X){let W=Y.scheme||Q.scheme||"urn";Q.nid=X[1].toLowerCase(),Q.nss=X[2];let G=`${W}:${Y.nid||Q.nid}`,$=FY(G);if(Q.path=void 0,$)Q=$.parse(Q,Y)}else Q.error=Q.error||"URN can not be parsed.";return Q}function rL(Q,Y){if(Q.nid===void 0)throw Error("URN without nid cannot be serialized");let X=Y.scheme||Q.scheme||"urn",W=Q.nid.toLowerCase(),G=`${X}:${Y.nid||W}`,$=FY(G);if($)Q=$.serialize(Q,Y);let z=Q,J=Q.nss;return z.path=`${W||Y.nid}:${J}`,Y.skipEscape=!0,z}function dL(Q,Y){let X=Q;if(X.uuid=X.nss,X.nss=void 0,!Y.tolerant&&(!X.uuid||!fL(X.uuid)))X.error=X.error||"UUID is not valid.";return X}function oL(Q){let Y=Q;return Y.nss=(Q.uuid||"").toLowerCase(),Y}var UJ={scheme:"http",domainHost:!0,parse:HJ,serialize:AJ},tL={scheme:"https",domainHost:UJ.domainHost,parse:HJ,serialize:AJ},QQ={scheme:"ws",domainHost:!0,parse:pL,serialize:iL},aL={scheme:"wss",domainHost:QQ.domainHost,parse:QQ.parse,serialize:QQ.serialize},sL={scheme:"urn",parse:nL,serialize:rL,skipNormalize:!0},eL={scheme:"urn:uuid",parse:dL,serialize:oL,skipNormalize:!0},YQ={http:UJ,https:tL,ws:QQ,wss:aL,urn:sL,"urn:uuid":eL};Object.setPrototypeOf(YQ,null);function FY(Q){return Q&&(YQ[Q]||YQ[Q.toLowerCase()])||void 0}KJ.exports={wsIsSecure:LY,SCHEMES:YQ,isValidSchemeName:cL,getSchemeHandler:FY}});var FJ=P((gI,WQ)=>{var{normalizeIPv6:QF,removeDotSegments:f4,recomposeAuthority:YF,normalizeComponentEncoding:XQ,isIPv4:XF,nonSimpleDomain:WF}=BY(),{SCHEMES:GF,getSchemeHandler:BJ}=DJ();function $F(Q,Y){if(typeof Q==="string")Q=i0(W1(Q,Y),Y);else if(typeof Q==="object")Q=W1(i0(Q,Y),Y);return Q}function zF(Q,Y,X){let W=X?Object.assign({scheme:"null"},X):{scheme:"null"},G=LJ(W1(Q,W),W1(Y,W),W,!0);return W.skipEscape=!0,i0(G,W)}function LJ(Q,Y,X,W){let G={};if(!W)Q=W1(i0(Q,X),X),Y=W1(i0(Y,X),X);if(X=X||{},!X.tolerant&&Y.scheme)G.scheme=Y.scheme,G.userinfo=Y.userinfo,G.host=Y.host,G.port=Y.port,G.path=f4(Y.path||""),G.query=Y.query;else{if(Y.userinfo!==void 0||Y.host!==void 0||Y.port!==void 0)G.userinfo=Y.userinfo,G.host=Y.host,G.port=Y.port,G.path=f4(Y.path||""),G.query=Y.query;else{if(!Y.path)if(G.path=Q.path,Y.query!==void 0)G.query=Y.query;else G.query=Q.query;else{if(Y.path[0]==="/")G.path=f4(Y.path);else{if((Q.userinfo!==void 0||Q.host!==void 0||Q.port!==void 0)&&!Q.path)G.path="/"+Y.path;else if(!Q.path)G.path=Y.path;else G.path=Q.path.slice(0,Q.path.lastIndexOf("/")+1)+Y.path;G.path=f4(G.path)}G.query=Y.query}G.userinfo=Q.userinfo,G.host=Q.host,G.port=Q.port}G.scheme=Q.scheme}return G.fragment=Y.fragment,G}function JF(Q,Y,X){if(typeof Q==="string")Q=unescape(Q),Q=i0(XQ(W1(Q,X),!0),{...X,skipEscape:!0});else if(typeof Q==="object")Q=i0(XQ(Q,!0),{...X,skipEscape:!0});if(typeof Y==="string")Y=unescape(Y),Y=i0(XQ(W1(Y,X),!0),{...X,skipEscape:!0});else if(typeof Y==="object")Y=i0(XQ(Y,!0),{...X,skipEscape:!0});return Q.toLowerCase()===Y.toLowerCase()}function i0(Q,Y){let X={host:Q.host,scheme:Q.scheme,userinfo:Q.userinfo,port:Q.port,path:Q.path,query:Q.query,nid:Q.nid,nss:Q.nss,uuid:Q.uuid,fragment:Q.fragment,reference:Q.reference,resourceName:Q.resourceName,secure:Q.secure,error:""},W=Object.assign({},Y),G=[],$=BJ(W.scheme||X.scheme);if($&&$.serialize)$.serialize(X,W);if(X.path!==void 0)if(!W.skipEscape){if(X.path=escape(X.path),X.scheme!==void 0)X.path=X.path.split("%3A").join(":")}else X.path=unescape(X.path);if(W.reference!=="suffix"&&X.scheme)G.push(X.scheme,":");let z=YF(X);if(z!==void 0){if(W.reference!=="suffix")G.push("//");if(G.push(z),X.path&&X.path[0]!=="/")G.push("/")}if(X.path!==void 0){let J=X.path;if(!W.absolutePath&&(!$||!$.absolutePath))J=f4(J);if(z===void 0&&J[0]==="/"&&J[1]==="/")J="/%2F"+J.slice(2);G.push(J)}if(X.query!==void 0)G.push("?",X.query);if(X.fragment!==void 0)G.push("#",X.fragment);return G.join("")}var HF=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function W1(Q,Y){let X=Object.assign({},Y),W={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},G=!1;if(X.reference==="suffix")if(X.scheme)Q=X.scheme+":"+Q;else Q="//"+Q;let $=Q.match(HF);if($){if(W.scheme=$[1],W.userinfo=$[3],W.host=$[4],W.port=parseInt($[5],10),W.path=$[6]||"",W.query=$[7],W.fragment=$[8],isNaN(W.port))W.port=$[5];if(W.host)if(XF(W.host)===!1){let H=QF(W.host);W.host=H.host.toLowerCase(),G=H.isIPV6}else G=!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(X.reference&&X.reference!=="suffix"&&X.reference!==W.reference)W.error=W.error||"URI is not a "+X.reference+" reference.";let z=BJ(X.scheme||W.scheme);if(!X.unicodeSupport&&(!z||!z.unicodeSupport)){if(W.host&&(X.domainHost||z&&z.domainHost)&&G===!1&&WF(W.host))try{W.host=URL.domainToASCII(W.host.toLowerCase())}catch(J){W.error=W.error||"Host's domain name can not be converted to ASCII: "+J}}if(!z||z&&!z.skipNormalize){if(Q.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(z&&z.parse)z.parse(W,X)}else W.error=W.error||"URI can not be parsed.";return W}var qY={SCHEMES:GF,normalize:$F,resolve:zF,resolveComponent:LJ,equal:JF,serialize:i0,parse:W1};WQ.exports=qY;WQ.exports.default=qY;WQ.exports.fastUri=qY});var MJ=P((OJ)=>{Object.defineProperty(OJ,"__esModule",{value:!0});var qJ=FJ();qJ.code='require("ajv/dist/runtime/uri").default';OJ.default=qJ});var IJ=P((G1)=>{Object.defineProperty(G1,"__esModule",{value:!0});G1.CodeGen=G1.Name=G1.nil=G1.stringify=G1.str=G1._=G1.KeywordCxt=void 0;var UF=y4();Object.defineProperty(G1,"KeywordCxt",{enumerable:!0,get:function(){return UF.KeywordCxt}});var o1=g();Object.defineProperty(G1,"_",{enumerable:!0,get:function(){return o1._}});Object.defineProperty(G1,"str",{enumerable:!0,get:function(){return o1.str}});Object.defineProperty(G1,"stringify",{enumerable:!0,get:function(){return o1.stringify}});Object.defineProperty(G1,"nil",{enumerable:!0,get:function(){return o1.nil}});Object.defineProperty(G1,"Name",{enumerable:!0,get:function(){return o1.Name}});Object.defineProperty(G1,"CodeGen",{enumerable:!0,get:function(){return o1.CodeGen}});var KF=a6(),PJ=u4(),DF=o9(),l4=e6(),BF=g(),m4=x4(),GQ=v4(),MY=c(),VJ=WJ(),LF=MJ(),bJ=(Q,Y)=>new RegExp(Q,Y);bJ.code="new RegExp";var FF=["removeAdditional","useDefaults","coerceTypes"],qF=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),OF={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."},MF={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},ZJ=200;function VF(Q){var Y,X,W,G,$,z,J,H,A,U,K,D,L,O,M,N,Z,k,S,y,C,c0,o0,jQ,IQ;let X4=Q.strict,EQ=(Y=Q.code)===null||Y===void 0?void 0:Y.optimize,KX=EQ===!0||EQ===void 0?1:EQ||0,DX=(W=(X=Q.code)===null||X===void 0?void 0:X.regExp)!==null&&W!==void 0?W:bJ,FH=(G=Q.uriResolver)!==null&&G!==void 0?G:LF.default;return{strictSchema:(z=($=Q.strictSchema)!==null&&$!==void 0?$:X4)!==null&&z!==void 0?z:!0,strictNumbers:(H=(J=Q.strictNumbers)!==null&&J!==void 0?J:X4)!==null&&H!==void 0?H:!0,strictTypes:(U=(A=Q.strictTypes)!==null&&A!==void 0?A:X4)!==null&&U!==void 0?U:"log",strictTuples:(D=(K=Q.strictTuples)!==null&&K!==void 0?K:X4)!==null&&D!==void 0?D:"log",strictRequired:(O=(L=Q.strictRequired)!==null&&L!==void 0?L:X4)!==null&&O!==void 0?O:!1,code:Q.code?{...Q.code,optimize:KX,regExp:DX}:{optimize:KX,regExp:DX},loopRequired:(M=Q.loopRequired)!==null&&M!==void 0?M:ZJ,loopEnum:(N=Q.loopEnum)!==null&&N!==void 0?N:ZJ,meta:(Z=Q.meta)!==null&&Z!==void 0?Z:!0,messages:(k=Q.messages)!==null&&k!==void 0?k:!0,inlineRefs:(S=Q.inlineRefs)!==null&&S!==void 0?S:!0,schemaId:(y=Q.schemaId)!==null&&y!==void 0?y:"$id",addUsedSchema:(C=Q.addUsedSchema)!==null&&C!==void 0?C:!0,validateSchema:(c0=Q.validateSchema)!==null&&c0!==void 0?c0:!0,validateFormats:(o0=Q.validateFormats)!==null&&o0!==void 0?o0:!0,unicodeRegExp:(jQ=Q.unicodeRegExp)!==null&&jQ!==void 0?jQ:!0,int32range:(IQ=Q.int32range)!==null&&IQ!==void 0?IQ:!0,uriResolver:FH}}class $Q{constructor(Q={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,Q=this.opts={...Q,...VF(Q)};let{es5:Y,lines:X}=this.opts.code;this.scope=new BF.ValueScope({scope:{},prefixes:qF,es5:Y,lines:X}),this.logger=jF(Q.logger);let W=Q.validateFormats;if(Q.validateFormats=!1,this.RULES=(0,DF.getRules)(),NJ.call(this,OF,Q,"NOT SUPPORTED"),NJ.call(this,MF,Q,"DEPRECATED","warn"),this._metaOpts=PF.call(this),Q.formats)NF.call(this);if(this._addVocabularies(),this._addDefaultMetaSchema(),Q.keywords)wF.call(this,Q.keywords);if(typeof Q.meta=="object")this.addMetaSchema(Q.meta);ZF.call(this),Q.validateFormats=W}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:Q,meta:Y,schemaId:X}=this.opts,W=VJ;if(X==="id")W={...VJ},W.id=W.$id,delete W.$id;if(Y&&Q)this.addMetaSchema(W,W[X],!1)}defaultMeta(){let{meta:Q,schemaId:Y}=this.opts;return this.opts.defaultMeta=typeof Q=="object"?Q[Y]||Q:void 0}validate(Q,Y){let X;if(typeof Q=="string"){if(X=this.getSchema(Q),!X)throw Error(`no schema with key or ref "${Q}"`)}else X=this.compile(Q);let W=X(Y);if(!("$async"in X))this.errors=X.errors;return W}compile(Q,Y){let X=this._addSchema(Q,Y);return X.validate||this._compileSchemaEnv(X)}compileAsync(Q,Y){if(typeof this.opts.loadSchema!="function")throw Error("options.loadSchema should be a function");let{loadSchema:X}=this.opts;return W.call(this,Q,Y);async function W(A,U){await G.call(this,A.$schema);let K=this._addSchema(A,U);return K.validate||$.call(this,K)}async function G(A){if(A&&!this.getSchema(A))await W.call(this,{$ref:A},!0)}async function $(A){try{return this._compileSchemaEnv(A)}catch(U){if(!(U instanceof PJ.default))throw U;return z.call(this,U),await J.call(this,U.missingSchema),$.call(this,A)}}function z({missingSchema:A,missingRef:U}){if(this.refs[A])throw Error(`AnySchema ${A} is loaded but ${U} cannot be resolved`)}async function J(A){let U=await H.call(this,A);if(!this.refs[A])await G.call(this,U.$schema);if(!this.refs[A])this.addSchema(U,A,Y)}async function H(A){let U=this._loading[A];if(U)return U;try{return await(this._loading[A]=X(A))}finally{delete this._loading[A]}}}addSchema(Q,Y,X,W=this.opts.validateSchema){if(Array.isArray(Q)){for(let $ of Q)this.addSchema($,void 0,X,W);return this}let G;if(typeof Q==="object"){let{schemaId:$}=this.opts;if(G=Q[$],G!==void 0&&typeof G!="string")throw Error(`schema ${$} must be string`)}return Y=(0,m4.normalizeId)(Y||G),this._checkUnique(Y),this.schemas[Y]=this._addSchema(Q,X,Y,W,!0),this}addMetaSchema(Q,Y,X=this.opts.validateSchema){return this.addSchema(Q,Y,!0,X),this}validateSchema(Q,Y){if(typeof Q=="boolean")return!0;let X;if(X=Q.$schema,X!==void 0&&typeof X!="string")throw Error("$schema must be a string");if(X=X||this.opts.defaultMeta||this.defaultMeta(),!X)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let W=this.validate(X,Q);if(!W&&Y){let G="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(G);else throw Error(G)}return W}getSchema(Q){let Y;while(typeof(Y=wJ.call(this,Q))=="string")Q=Y;if(Y===void 0){let{schemaId:X}=this.opts,W=new l4.SchemaEnv({schema:{},schemaId:X});if(Y=l4.resolveSchema.call(this,W,Q),!Y)return;this.refs[Q]=Y}return Y.validate||this._compileSchemaEnv(Y)}removeSchema(Q){if(Q instanceof RegExp)return this._removeAllSchemas(this.schemas,Q),this._removeAllSchemas(this.refs,Q),this;switch(typeof Q){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let Y=wJ.call(this,Q);if(typeof Y=="object")this._cache.delete(Y.schema);return delete this.schemas[Q],delete this.refs[Q],this}case"object":{let Y=Q;this._cache.delete(Y);let X=Q[this.opts.schemaId];if(X)X=(0,m4.normalizeId)(X),delete this.schemas[X],delete this.refs[X];return this}default:throw Error("ajv.removeSchema: invalid parameter")}}addVocabulary(Q){for(let Y of Q)this.addKeyword(Y);return this}addKeyword(Q,Y){let X;if(typeof Q=="string"){if(X=Q,typeof Y=="object")this.logger.warn("these parameters are deprecated, see docs for addKeyword"),Y.keyword=X}else if(typeof Q=="object"&&Y===void 0){if(Y=Q,X=Y.keyword,Array.isArray(X)&&!X.length)throw Error("addKeywords: keyword must be string or non-empty array")}else throw Error("invalid addKeywords parameters");if(EF.call(this,X,Y),!Y)return(0,MY.eachItem)(X,(G)=>OY.call(this,G)),this;SF.call(this,Y);let W={...Y,type:(0,GQ.getJSONTypes)(Y.type),schemaType:(0,GQ.getJSONTypes)(Y.schemaType)};return(0,MY.eachItem)(X,W.type.length===0?(G)=>OY.call(this,G,W):(G)=>W.type.forEach(($)=>OY.call(this,G,W,$))),this}getKeyword(Q){let Y=this.RULES.all[Q];return typeof Y=="object"?Y.definition:!!Y}removeKeyword(Q){let{RULES:Y}=this;delete Y.keywords[Q],delete Y.all[Q];for(let X of Y.rules){let W=X.rules.findIndex((G)=>G.keyword===Q);if(W>=0)X.rules.splice(W,1)}return this}addFormat(Q,Y){if(typeof Y=="string")Y=new RegExp(Y);return this.formats[Q]=Y,this}errorsText(Q=this.errors,{separator:Y=", ",dataVar:X="data"}={}){if(!Q||Q.length===0)return"No errors";return Q.map((W)=>`${X}${W.instancePath} ${W.message}`).reduce((W,G)=>W+Y+G)}$dataMetaSchema(Q,Y){let X=this.RULES.all;Q=JSON.parse(JSON.stringify(Q));for(let W of Y){let G=W.split("/").slice(1),$=Q;for(let z of G)$=$[z];for(let z in X){let J=X[z];if(typeof J!="object")continue;let{$data:H}=J.definition,A=$[z];if(H&&A)$[z]=jJ(A)}}return Q}_removeAllSchemas(Q,Y){for(let X in Q){let W=Q[X];if(!Y||Y.test(X)){if(typeof W=="string")delete Q[X];else if(W&&!W.meta)this._cache.delete(W.schema),delete Q[X]}}}_addSchema(Q,Y,X,W=this.opts.validateSchema,G=this.opts.addUsedSchema){let $,{schemaId:z}=this.opts;if(typeof Q=="object")$=Q[z];else if(this.opts.jtd)throw Error("schema must be object");else if(typeof Q!="boolean")throw Error("schema must be object or boolean");let J=this._cache.get(Q);if(J!==void 0)return J;X=(0,m4.normalizeId)($||X);let H=m4.getSchemaRefs.call(this,Q,X);if(J=new l4.SchemaEnv({schema:Q,schemaId:z,meta:Y,baseId:X,localRefs:H}),this._cache.set(J.schema,J),G&&!X.startsWith("#")){if(X)this._checkUnique(X);this.refs[X]=J}if(W)this.validateSchema(Q,!0);return J}_checkUnique(Q){if(this.schemas[Q]||this.refs[Q])throw Error(`schema with key or id "${Q}" already exists`)}_compileSchemaEnv(Q){if(Q.meta)this._compileMetaSchema(Q);else l4.compileSchema.call(this,Q);if(!Q.validate)throw Error("ajv implementation error");return Q.validate}_compileMetaSchema(Q){let Y=this.opts;this.opts=this._metaOpts;try{l4.compileSchema.call(this,Q)}finally{this.opts=Y}}}$Q.ValidationError=KF.default;$Q.MissingRefError=PJ.default;G1.default=$Q;function NJ(Q,Y,X,W="error"){for(let G in Q){let $=G;if($ in Y)this.logger[W](`${X}: option ${G}. ${Q[$]}`)}}function wJ(Q){return Q=(0,m4.normalizeId)(Q),this.schemas[Q]||this.refs[Q]}function ZF(){let Q=this.opts.schemas;if(!Q)return;if(Array.isArray(Q))this.addSchema(Q);else for(let Y in Q)this.addSchema(Q[Y],Y)}function NF(){for(let Q in this.opts.formats){let Y=this.opts.formats[Q];if(Y)this.addFormat(Q,Y)}}function wF(Q){if(Array.isArray(Q)){this.addVocabulary(Q);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let Y in Q){let X=Q[Y];if(!X.keyword)X.keyword=Y;this.addKeyword(X)}}function PF(){let Q={...this.opts};for(let Y of FF)delete Q[Y];return Q}var bF={log(){},warn(){},error(){}};function jF(Q){if(Q===!1)return bF;if(Q===void 0)return console;if(Q.log&&Q.warn&&Q.error)return Q;throw Error("logger must implement log, warn and error methods")}var IF=/^[a-z_$][a-z0-9_$:-]*$/i;function EF(Q,Y){let{RULES:X}=this;if((0,MY.eachItem)(Q,(W)=>{if(X.keywords[W])throw Error(`Keyword ${W} is already defined`);if(!IF.test(W))throw Error(`Keyword ${W} has invalid name`)}),!Y)return;if(Y.$data&&!(("code"in Y)||("validate"in Y)))throw Error('$data keyword must have "code" or "validate" function')}function OY(Q,Y,X){var W;let G=Y===null||Y===void 0?void 0:Y.post;if(X&&G)throw Error('keyword with "post" flag cannot have "type"');let{RULES:$}=this,z=G?$.post:$.rules.find(({type:H})=>H===X);if(!z)z={type:X,rules:[]},$.rules.push(z);if($.keywords[Q]=!0,!Y)return;let J={keyword:Q,definition:{...Y,type:(0,GQ.getJSONTypes)(Y.type),schemaType:(0,GQ.getJSONTypes)(Y.schemaType)}};if(Y.before)TF.call(this,z,J,Y.before);else z.rules.push(J);$.all[Q]=J,(W=Y.implements)===null||W===void 0||W.forEach((H)=>this.addKeyword(H))}function TF(Q,Y,X){let W=Q.rules.findIndex((G)=>G.keyword===X);if(W>=0)Q.rules.splice(W,0,Y);else Q.rules.push(Y),this.logger.warn(`rule ${X} is not defined`)}function SF(Q){let{metaSchema:Y}=Q;if(Y===void 0)return;if(Q.$data&&this.opts.$data)Y=jJ(Y);Q.validateSchema=this.compile(Y,!0)}var RF={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function jJ(Q){return{anyOf:[Q,RF]}}});var TJ=P((EJ)=>{Object.defineProperty(EJ,"__esModule",{value:!0});var vF={keyword:"id",code(){throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};EJ.default=vF});var xJ=P((kJ)=>{Object.defineProperty(kJ,"__esModule",{value:!0});kJ.callRef=kJ.getValidate=void 0;var _F=u4(),SJ=C0(),w0=g(),t1=Y1(),RJ=e6(),zQ=c(),gF={keyword:"$ref",schemaType:"string",code(Q){let{gen:Y,schema:X,it:W}=Q,{baseId:G,schemaEnv:$,validateName:z,opts:J,self:H}=W,{root:A}=$;if((X==="#"||X==="#/")&&G===A.baseId)return K();let U=RJ.resolveRef.call(H,A,G,X);if(U===void 0)throw new _F.default(W.opts.uriResolver,G,X);if(U instanceof RJ.SchemaEnv)return D(U);return L(U);function K(){if($===A)return JQ(Q,z,$,$.$async);let O=Y.scopeValue("root",{ref:A});return JQ(Q,w0._`${O}.validate`,A,A.$async)}function D(O){let M=CJ(Q,O);JQ(Q,M,O,O.$async)}function L(O){let M=Y.scopeValue("schema",J.code.source===!0?{ref:O,code:(0,w0.stringify)(O)}:{ref:O}),N=Y.name("valid"),Z=Q.subschema({schema:O,dataTypes:[],schemaPath:w0.nil,topSchemaRef:M,errSchemaPath:X},N);Q.mergeEvaluated(Z),Q.ok(N)}}};function CJ(Q,Y){let{gen:X}=Q;return Y.validate?X.scopeValue("validate",{ref:Y.validate}):w0._`${X.scopeValue("wrapper",{ref:Y})}.validate`}kJ.getValidate=CJ;function JQ(Q,Y,X,W){let{gen:G,it:$}=Q,{allErrors:z,schemaEnv:J,opts:H}=$,A=H.passContext?t1.default.this:w0.nil;if(W)U();else K();function U(){if(!J.$async)throw Error("async schema referenced by sync schema");let O=G.let("valid");G.try(()=>{if(G.code(w0._`await ${(0,SJ.callValidateCode)(Q,Y,A)}`),L(Y),!z)G.assign(O,!0)},(M)=>{if(G.if(w0._`!(${M} instanceof ${$.ValidationError})`,()=>G.throw(M)),D(M),!z)G.assign(O,!1)}),Q.ok(O)}function K(){Q.result((0,SJ.callValidateCode)(Q,Y,A),()=>L(Y),()=>D(Y))}function D(O){let M=w0._`${O}.errors`;G.assign(t1.default.vErrors,w0._`${t1.default.vErrors} === null ? ${M} : ${t1.default.vErrors}.concat(${M})`),G.assign(t1.default.errors,w0._`${t1.default.vErrors}.length`)}function L(O){var M;if(!$.opts.unevaluated)return;let N=(M=X===null||X===void 0?void 0:X.validate)===null||M===void 0?void 0:M.evaluated;if($.props!==!0)if(N&&!N.dynamicProps){if(N.props!==void 0)$.props=zQ.mergeEvaluated.props(G,N.props,$.props)}else{let Z=G.var("props",w0._`${O}.evaluated.props`);$.props=zQ.mergeEvaluated.props(G,Z,$.props,w0.Name)}if($.items!==!0)if(N&&!N.dynamicItems){if(N.items!==void 0)$.items=zQ.mergeEvaluated.items(G,N.items,$.items)}else{let Z=G.var("items",w0._`${O}.evaluated.items`);$.items=zQ.mergeEvaluated.items(G,Z,$.items,w0.Name)}}}kJ.callRef=JQ;kJ.default=gF});var gJ=P((_J)=>{Object.defineProperty(_J,"__esModule",{value:!0});var hF=TJ(),fF=xJ(),lF=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",hF.default,fF.default];_J.default=lF});var uJ=P((yJ)=>{Object.defineProperty(yJ,"__esModule",{value:!0});var HQ=g(),M1=HQ.operators,AQ={maximum:{okStr:"<=",ok:M1.LTE,fail:M1.GT},minimum:{okStr:">=",ok:M1.GTE,fail:M1.LT},exclusiveMaximum:{okStr:"<",ok:M1.LT,fail:M1.GTE},exclusiveMinimum:{okStr:">",ok:M1.GT,fail:M1.LTE}},cF={message:({keyword:Q,schemaCode:Y})=>HQ.str`must be ${AQ[Q].okStr} ${Y}`,params:({keyword:Q,schemaCode:Y})=>HQ._`{comparison: ${AQ[Q].okStr}, limit: ${Y}}`},pF={keyword:Object.keys(AQ),type:"number",schemaType:"number",$data:!0,error:cF,code(Q){let{keyword:Y,data:X,schemaCode:W}=Q;Q.fail$data(HQ._`${X} ${AQ[Y].fail} ${W} || isNaN(${X})`)}};yJ.default=pF});var fJ=P((hJ)=>{Object.defineProperty(hJ,"__esModule",{value:!0});var c4=g(),nF={message:({schemaCode:Q})=>c4.str`must be multiple of ${Q}`,params:({schemaCode:Q})=>c4._`{multipleOf: ${Q}}`},rF={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:nF,code(Q){let{gen:Y,data:X,schemaCode:W,it:G}=Q,$=G.opts.multipleOfPrecision,z=Y.let("res"),J=$?c4._`Math.abs(Math.round(${z}) - ${z}) > 1e-${$}`:c4._`${z} !== parseInt(${z})`;Q.fail$data(c4._`(${W} === 0 || (${z} = ${X}/${W}, ${J}))`)}};hJ.default=rF});var cJ=P((mJ)=>{Object.defineProperty(mJ,"__esModule",{value:!0});function lJ(Q){let Y=Q.length,X=0,W=0,G;while(W<Y)if(X++,G=Q.charCodeAt(W++),G>=55296&&G<=56319&&W<Y){if(G=Q.charCodeAt(W),(G&64512)===56320)W++}return X}mJ.default=lJ;lJ.code='require("ajv/dist/runtime/ucs2length").default'});var iJ=P((pJ)=>{Object.defineProperty(pJ,"__esModule",{value:!0});var C1=g(),tF=c(),aF=cJ(),sF={message({keyword:Q,schemaCode:Y}){let X=Q==="maxLength"?"more":"fewer";return C1.str`must NOT have ${X} than ${Y} characters`},params:({schemaCode:Q})=>C1._`{limit: ${Q}}`},eF={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:sF,code(Q){let{keyword:Y,data:X,schemaCode:W,it:G}=Q,$=Y==="maxLength"?C1.operators.GT:C1.operators.LT,z=G.opts.unicode===!1?C1._`${X}.length`:C1._`${(0,tF.useFunc)(Q.gen,aF.default)}(${X})`;Q.fail$data(C1._`${z} ${$} ${W}`)}};pJ.default=eF});var rJ=P((nJ)=>{Object.defineProperty(nJ,"__esModule",{value:!0});var Yq=C0(),UQ=g(),Xq={message:({schemaCode:Q})=>UQ.str`must match pattern "${Q}"`,params:({schemaCode:Q})=>UQ._`{pattern: ${Q}}`},Wq={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:Xq,code(Q){let{data:Y,$data:X,schema:W,schemaCode:G,it:$}=Q,z=$.opts.unicodeRegExp?"u":"",J=X?UQ._`(new RegExp(${G}, ${z}))`:(0,Yq.usePattern)(Q,W);Q.fail$data(UQ._`!${J}.test(${Y})`)}};nJ.default=Wq});var oJ=P((dJ)=>{Object.defineProperty(dJ,"__esModule",{value:!0});var p4=g(),$q={message({keyword:Q,schemaCode:Y}){let X=Q==="maxProperties"?"more":"fewer";return p4.str`must NOT have ${X} than ${Y} properties`},params:({schemaCode:Q})=>p4._`{limit: ${Q}}`},zq={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:$q,code(Q){let{keyword:Y,data:X,schemaCode:W}=Q,G=Y==="maxProperties"?p4.operators.GT:p4.operators.LT;Q.fail$data(p4._`Object.keys(${X}).length ${G} ${W}`)}};dJ.default=zq});var aJ=P((tJ)=>{Object.defineProperty(tJ,"__esModule",{value:!0});var i4=C0(),n4=g(),Hq=c(),Aq={message:({params:{missingProperty:Q}})=>n4.str`must have required property '${Q}'`,params:({params:{missingProperty:Q}})=>n4._`{missingProperty: ${Q}}`},Uq={keyword:"required",type:"object",schemaType:"array",$data:!0,error:Aq,code(Q){let{gen:Y,schema:X,schemaCode:W,data:G,$data:$,it:z}=Q,{opts:J}=z;if(!$&&X.length===0)return;let H=X.length>=J.loopRequired;if(z.allErrors)A();else U();if(J.strictRequired){let L=Q.parentSchema.properties,{definedProperties:O}=Q.it;for(let M of X)if((L===null||L===void 0?void 0:L[M])===void 0&&!O.has(M)){let N=z.schemaEnv.baseId+z.errSchemaPath,Z=`required property "${M}" is not defined at "${N}" (strictRequired)`;(0,Hq.checkStrictMode)(z,Z,z.opts.strictRequired)}}function A(){if(H||$)Q.block$data(n4.nil,K);else for(let L of X)(0,i4.checkReportMissingProp)(Q,L)}function U(){let L=Y.let("missing");if(H||$){let O=Y.let("valid",!0);Q.block$data(O,()=>D(L,O)),Q.ok(O)}else Y.if((0,i4.checkMissingProp)(Q,X,L)),(0,i4.reportMissingProp)(Q,L),Y.else()}function K(){Y.forOf("prop",W,(L)=>{Q.setParams({missingProperty:L}),Y.if((0,i4.noPropertyInData)(Y,G,L,J.ownProperties),()=>Q.error())})}function D(L,O){Q.setParams({missingProperty:L}),Y.forOf(L,W,()=>{Y.assign(O,(0,i4.propertyInData)(Y,G,L,J.ownProperties)),Y.if((0,n4.not)(O),()=>{Q.error(),Y.break()})},n4.nil)}}};tJ.default=Uq});var eJ=P((sJ)=>{Object.defineProperty(sJ,"__esModule",{value:!0});var r4=g(),Dq={message({keyword:Q,schemaCode:Y}){let X=Q==="maxItems"?"more":"fewer";return r4.str`must NOT have ${X} than ${Y} items`},params:({schemaCode:Q})=>r4._`{limit: ${Q}}`},Bq={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:Dq,code(Q){let{keyword:Y,data:X,schemaCode:W}=Q,G=Y==="maxItems"?r4.operators.GT:r4.operators.LT;Q.fail$data(r4._`${X}.length ${G} ${W}`)}};sJ.default=Bq});var KQ=P((Y7)=>{Object.defineProperty(Y7,"__esModule",{value:!0});var Q7=WY();Q7.code='require("ajv/dist/runtime/equal").default';Y7.default=Q7});var W7=P((X7)=>{Object.defineProperty(X7,"__esModule",{value:!0});var VY=v4(),L0=g(),qq=c(),Oq=KQ(),Mq={message:({params:{i:Q,j:Y}})=>L0.str`must NOT have duplicate items (items ## ${Y} and ${Q} are identical)`,params:({params:{i:Q,j:Y}})=>L0._`{i: ${Q}, j: ${Y}}`},Vq={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:Mq,code(Q){let{gen:Y,data:X,$data:W,schema:G,parentSchema:$,schemaCode:z,it:J}=Q;if(!W&&!G)return;let H=Y.let("valid"),A=$.items?(0,VY.getSchemaTypes)($.items):[];Q.block$data(H,U,L0._`${z} === false`),Q.ok(H);function U(){let O=Y.let("i",L0._`${X}.length`),M=Y.let("j");Q.setParams({i:O,j:M}),Y.assign(H,!0),Y.if(L0._`${O} > 1`,()=>(K()?D:L)(O,M))}function K(){return A.length>0&&!A.some((O)=>O==="object"||O==="array")}function D(O,M){let N=Y.name("item"),Z=(0,VY.checkDataTypes)(A,N,J.opts.strictNumbers,VY.DataType.Wrong),k=Y.const("indices",L0._`{}`);Y.for(L0._`;${O}--;`,()=>{if(Y.let(N,L0._`${X}[${O}]`),Y.if(Z,L0._`continue`),A.length>1)Y.if(L0._`typeof ${N} == "string"`,L0._`${N} += "_"`);Y.if(L0._`typeof ${k}[${N}] == "number"`,()=>{Y.assign(M,L0._`${k}[${N}]`),Q.error(),Y.assign(H,!1).break()}).code(L0._`${k}[${N}] = ${O}`)})}function L(O,M){let N=(0,qq.useFunc)(Y,Oq.default),Z=Y.name("outer");Y.label(Z).for(L0._`;${O}--;`,()=>Y.for(L0._`${M} = ${O}; ${M}--;`,()=>Y.if(L0._`${N}(${X}[${O}], ${X}[${M}])`,()=>{Q.error(),Y.assign(H,!1).break(Z)})))}}};X7.default=Vq});var $7=P((G7)=>{Object.defineProperty(G7,"__esModule",{value:!0});var ZY=g(),Nq=c(),wq=KQ(),Pq={message:"must be equal to constant",params:({schemaCode:Q})=>ZY._`{allowedValue: ${Q}}`},bq={keyword:"const",$data:!0,error:Pq,code(Q){let{gen:Y,data:X,$data:W,schemaCode:G,schema:$}=Q;if(W||$&&typeof $=="object")Q.fail$data(ZY._`!${(0,Nq.useFunc)(Y,wq.default)}(${X}, ${G})`);else Q.fail(ZY._`${$} !== ${X}`)}};G7.default=bq});var J7=P((z7)=>{Object.defineProperty(z7,"__esModule",{value:!0});var d4=g(),Iq=c(),Eq=KQ(),Tq={message:"must be equal to one of the allowed values",params:({schemaCode:Q})=>d4._`{allowedValues: ${Q}}`},Sq={keyword:"enum",schemaType:"array",$data:!0,error:Tq,code(Q){let{gen:Y,data:X,$data:W,schema:G,schemaCode:$,it:z}=Q;if(!W&&G.length===0)throw Error("enum must have non-empty array");let J=G.length>=z.opts.loopEnum,H,A=()=>H!==null&&H!==void 0?H:H=(0,Iq.useFunc)(Y,Eq.default),U;if(J||W)U=Y.let("valid"),Q.block$data(U,K);else{if(!Array.isArray(G))throw Error("ajv implementation error");let L=Y.const("vSchema",$);U=(0,d4.or)(...G.map((O,M)=>D(L,M)))}Q.pass(U);function K(){Y.assign(U,!1),Y.forOf("v",$,(L)=>Y.if(d4._`${A()}(${X}, ${L})`,()=>Y.assign(U,!0).break()))}function D(L,O){let M=G[O];return typeof M==="object"&&M!==null?d4._`${A()}(${X}, ${L}[${O}])`:d4._`${X} === ${M}`}}};z7.default=Sq});var A7=P((H7)=>{Object.defineProperty(H7,"__esModule",{value:!0});var Cq=uJ(),kq=fJ(),vq=iJ(),xq=rJ(),_q=oJ(),gq=aJ(),yq=eJ(),uq=W7(),hq=$7(),fq=J7(),lq=[Cq.default,kq.default,vq.default,xq.default,_q.default,gq.default,yq.default,uq.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},hq.default,fq.default];H7.default=lq});var wY=P((K7)=>{Object.defineProperty(K7,"__esModule",{value:!0});K7.validateAdditionalItems=void 0;var k1=g(),NY=c(),cq={message:({params:{len:Q}})=>k1.str`must NOT have more than ${Q} items`,params:({params:{len:Q}})=>k1._`{limit: ${Q}}`},pq={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:cq,code(Q){let{parentSchema:Y,it:X}=Q,{items:W}=Y;if(!Array.isArray(W)){(0,NY.checkStrictMode)(X,'"additionalItems" is ignored when "items" is not an array of schemas');return}U7(Q,W)}};function U7(Q,Y){let{gen:X,schema:W,data:G,keyword:$,it:z}=Q;z.items=!0;let J=X.const("len",k1._`${G}.length`);if(W===!1)Q.setParams({len:Y.length}),Q.pass(k1._`${J} <= ${Y.length}`);else if(typeof W=="object"&&!(0,NY.alwaysValidSchema)(z,W)){let A=X.var("valid",k1._`${J} <= ${Y.length}`);X.if((0,k1.not)(A),()=>H(A)),Q.ok(A)}function H(A){X.forRange("i",Y.length,J,(U)=>{if(Q.subschema({keyword:$,dataProp:U,dataPropType:NY.Type.Num},A),!z.allErrors)X.if((0,k1.not)(A),()=>X.break())})}}K7.validateAdditionalItems=U7;K7.default=pq});var PY=P((F7)=>{Object.defineProperty(F7,"__esModule",{value:!0});F7.validateTuple=void 0;var B7=g(),DQ=c(),nq=C0(),rq={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(Q){let{schema:Y,it:X}=Q;if(Array.isArray(Y))return L7(Q,"additionalItems",Y);if(X.items=!0,(0,DQ.alwaysValidSchema)(X,Y))return;Q.ok((0,nq.validateArray)(Q))}};function L7(Q,Y,X=Q.schema){let{gen:W,parentSchema:G,data:$,keyword:z,it:J}=Q;if(U(G),J.opts.unevaluated&&X.length&&J.items!==!0)J.items=DQ.mergeEvaluated.items(W,X.length,J.items);let H=W.name("valid"),A=W.const("len",B7._`${$}.length`);X.forEach((K,D)=>{if((0,DQ.alwaysValidSchema)(J,K))return;W.if(B7._`${A} > ${D}`,()=>Q.subschema({keyword:z,schemaProp:D,dataProp:D},H)),Q.ok(H)});function U(K){let{opts:D,errSchemaPath:L}=J,O=X.length,M=O===K.minItems&&(O===K.maxItems||K[Y]===!1);if(D.strictTuples&&!M){let N=`"${z}" is ${O}-tuple, but minItems or maxItems/${Y} are not specified or different at path "${L}"`;(0,DQ.checkStrictMode)(J,N,D.strictTuples)}}}F7.validateTuple=L7;F7.default=rq});var M7=P((O7)=>{Object.defineProperty(O7,"__esModule",{value:!0});var oq=PY(),tq={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:(Q)=>(0,oq.validateTuple)(Q,"items")};O7.default=tq});var N7=P((Z7)=>{Object.defineProperty(Z7,"__esModule",{value:!0});var V7=g(),sq=c(),eq=C0(),QO=wY(),YO={message:({params:{len:Q}})=>V7.str`must NOT have more than ${Q} items`,params:({params:{len:Q}})=>V7._`{limit: ${Q}}`},XO={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:YO,code(Q){let{schema:Y,parentSchema:X,it:W}=Q,{prefixItems:G}=X;if(W.items=!0,(0,sq.alwaysValidSchema)(W,Y))return;if(G)(0,QO.validateAdditionalItems)(Q,G);else Q.ok((0,eq.validateArray)(Q))}};Z7.default=XO});var P7=P((w7)=>{Object.defineProperty(w7,"__esModule",{value:!0});var k0=g(),BQ=c(),GO={message:({params:{min:Q,max:Y}})=>Y===void 0?k0.str`must contain at least ${Q} valid item(s)`:k0.str`must contain at least ${Q} and no more than ${Y} valid item(s)`,params:({params:{min:Q,max:Y}})=>Y===void 0?k0._`{minContains: ${Q}}`:k0._`{minContains: ${Q}, maxContains: ${Y}}`},$O={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:GO,code(Q){let{gen:Y,schema:X,parentSchema:W,data:G,it:$}=Q,z,J,{minContains:H,maxContains:A}=W;if($.opts.next)z=H===void 0?1:H,J=A;else z=1;let U=Y.const("len",k0._`${G}.length`);if(Q.setParams({min:z,max:J}),J===void 0&&z===0){(0,BQ.checkStrictMode)($,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(J!==void 0&&z>J){(0,BQ.checkStrictMode)($,'"minContains" > "maxContains" is always invalid'),Q.fail();return}if((0,BQ.alwaysValidSchema)($,X)){let M=k0._`${U} >= ${z}`;if(J!==void 0)M=k0._`${M} && ${U} <= ${J}`;Q.pass(M);return}$.items=!0;let K=Y.name("valid");if(J===void 0&&z===1)L(K,()=>Y.if(K,()=>Y.break()));else if(z===0){if(Y.let(K,!0),J!==void 0)Y.if(k0._`${G}.length > 0`,D)}else Y.let(K,!1),D();Q.result(K,()=>Q.reset());function D(){let M=Y.name("_valid"),N=Y.let("count",0);L(M,()=>Y.if(M,()=>O(N)))}function L(M,N){Y.forRange("i",0,U,(Z)=>{Q.subschema({keyword:"contains",dataProp:Z,dataPropType:BQ.Type.Num,compositeRule:!0},M),N()})}function O(M){if(Y.code(k0._`${M}++`),J===void 0)Y.if(k0._`${M} >= ${z}`,()=>Y.assign(K,!0).break());else if(Y.if(k0._`${M} > ${J}`,()=>Y.assign(K,!1).break()),z===1)Y.assign(K,!0);else Y.if(k0._`${M} >= ${z}`,()=>Y.assign(K,!0))}}};w7.default=$O});var S7=P((I7)=>{Object.defineProperty(I7,"__esModule",{value:!0});I7.validateSchemaDeps=I7.validatePropertyDeps=I7.error=void 0;var bY=g(),JO=c(),o4=C0();I7.error={message:({params:{property:Q,depsCount:Y,deps:X}})=>{let W=Y===1?"property":"properties";return bY.str`must have ${W} ${X} when property ${Q} is present`},params:({params:{property:Q,depsCount:Y,deps:X,missingProperty:W}})=>bY._`{property: ${Q},
6
+ || ${z} === "boolean" || ${G} === null`).assign(J,x._`[${G}]`)}}}function lD({gen:Q,parentData:Y,parentDataProperty:X},W){Q.if(x._`${Y} !== undefined`,()=>Q.assign(x._`${Y}[${X}]`,W))}function a9(Q,Y,X,W=n1.Correct){let G=W===n1.Correct?x.operators.EQ:x.operators.NEQ,$;switch(Q){case"null":return x._`${Y} ${G} null`;case"array":$=x._`Array.isArray(${Y})`;break;case"object":$=x._`${Y} && typeof ${Y} == "object" && !Array.isArray(${Y})`;break;case"integer":$=z(x._`!(${Y} % 1) && !isNaN(${Y})`);break;case"number":$=z();break;default:return x._`typeof ${Y} ${G} ${Q}`}return W===n1.Correct?$:(0,x.not)($);function z(J=x.nil){return(0,x.and)(x._`typeof ${Y} == "number"`,J,X?x._`isFinite(${Y})`:x.nil)}}Hz.checkDataType=a9;function s9(Q,Y,X,W){if(Q.length===1)return a9(Q[0],Y,X,W);let G,$=(0,$z.toHash)(Q);if($.array&&$.object){let z=x._`typeof ${Y} != "object"`;G=$.null?z:x._`!${Y} || ${z}`,delete $.null,delete $.array,delete $.object}else G=x.nil;if($.number)delete $.integer;for(let z in $)G=(0,x.and)(G,a9(z,Y,X,W));return G}Hz.checkDataTypes=s9;var mD={message:({schema:Q})=>`must be ${Q}`,params:({schema:Q,schemaValue:Y})=>typeof Q=="string"?x._`{type: ${Q}}`:x._`{type: ${Y}}`};function e9(Q){let Y=cD(Q);(0,gD.reportError)(Y,mD)}Hz.reportTypeError=e9;function cD(Q){let{gen:Y,data:X,schema:W}=Q,G=(0,$z.schemaRefOrVal)(Q,W,"type");return{gen:Y,keyword:"type",data:X,schema:W.type,schemaCode:G,schemaValue:G,parentSchema:W,params:{},it:Q}}});var Bz=P((Kz)=>{Object.defineProperty(Kz,"__esModule",{value:!0});Kz.assignDefaults=void 0;var r1=g(),tD=c();function aD(Q,Y){let{properties:X,items:W}=Q.schema;if(Y==="object"&&X)for(let G in X)Uz(Q,G,X[G].default);else if(Y==="array"&&Array.isArray(W))W.forEach((G,$)=>Uz(Q,$,G.default))}Kz.assignDefaults=aD;function Uz(Q,Y,X){let{gen:W,compositeRule:G,data:$,opts:z}=Q;if(X===void 0)return;let J=r1._`${$}${(0,r1.getProperty)(Y)}`;if(G){(0,tD.checkStrictMode)(Q,`default is ignored for: ${J}`);return}let H=r1._`${J} === undefined`;if(z.useDefaults==="empty")H=r1._`${H} || ${J} === null || ${J} === ""`;W.if(H,r1._`${J} = ${(0,r1.stringify)(X)}`)}});var C0=P((qz)=>{Object.defineProperty(qz,"__esModule",{value:!0});qz.validateUnion=qz.validateArray=qz.usePattern=qz.callValidateCode=qz.schemaProperties=qz.allSchemaProperties=qz.noPropertyInData=qz.propertyInData=qz.isOwnProperty=qz.hasPropFunc=qz.reportMissingProp=qz.checkMissingProp=qz.checkReportMissingProp=void 0;var a=g(),QY=c(),q1=Y1(),sD=c();function eD(Q,Y){let{gen:X,data:W,it:G}=Q;X.if(XY(X,W,Y,G.opts.ownProperties),()=>{Q.setParams({missingProperty:a._`${Y}`},!0),Q.error()})}qz.checkReportMissingProp=eD;function QB({gen:Q,data:Y,it:{opts:X}},W,G){return(0,a.or)(...W.map(($)=>(0,a.and)(XY(Q,Y,$,X.ownProperties),a._`${G} = ${$}`)))}qz.checkMissingProp=QB;function YB(Q,Y){Q.setParams({missingProperty:Y},!0),Q.error()}qz.reportMissingProp=YB;function Lz(Q){return Q.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:a._`Object.prototype.hasOwnProperty`})}qz.hasPropFunc=Lz;function YY(Q,Y,X){return a._`${Lz(Q)}.call(${Y}, ${X})`}qz.isOwnProperty=YY;function XB(Q,Y,X,W){let G=a._`${Y}${(0,a.getProperty)(X)} !== undefined`;return W?a._`${G} && ${YY(Q,Y,X)}`:G}qz.propertyInData=XB;function XY(Q,Y,X,W){let G=a._`${Y}${(0,a.getProperty)(X)} === undefined`;return W?(0,a.or)(G,(0,a.not)(YY(Q,Y,X))):G}qz.noPropertyInData=XY;function Fz(Q){return Q?Object.keys(Q).filter((Y)=>Y!=="__proto__"):[]}qz.allSchemaProperties=Fz;function WB(Q,Y){return Fz(Y).filter((X)=>!(0,QY.alwaysValidSchema)(Q,Y[X]))}qz.schemaProperties=WB;function GB({schemaCode:Q,data:Y,it:{gen:X,topSchemaRef:W,schemaPath:G,errorPath:$},it:z},J,H,A){let U=A?a._`${Q}, ${Y}, ${W}${G}`:Y,K=[[q1.default.instancePath,(0,a.strConcat)(q1.default.instancePath,$)],[q1.default.parentData,z.parentData],[q1.default.parentDataProperty,z.parentDataProperty],[q1.default.rootData,q1.default.rootData]];if(z.opts.dynamicRef)K.push([q1.default.dynamicAnchors,q1.default.dynamicAnchors]);let D=a._`${U}, ${X.object(...K)}`;return H!==a.nil?a._`${J}.call(${H}, ${D})`:a._`${J}(${D})`}qz.callValidateCode=GB;var $B=a._`new RegExp`;function zB({gen:Q,it:{opts:Y}},X){let W=Y.unicodeRegExp?"u":"",{regExp:G}=Y.code,$=G(X,W);return Q.scopeValue("pattern",{key:$.toString(),ref:$,code:a._`${G.code==="new RegExp"?$B:(0,sD.useFunc)(Q,G)}(${X}, ${W})`})}qz.usePattern=zB;function JB(Q){let{gen:Y,data:X,keyword:W,it:G}=Q,$=Y.name("valid");if(G.allErrors){let J=Y.let("valid",!0);return z(()=>Y.assign(J,!1)),J}return Y.var($,!0),z(()=>Y.break()),$;function z(J){let H=Y.const("len",a._`${X}.length`);Y.forRange("i",0,H,(A)=>{Q.subschema({keyword:W,dataProp:A,dataPropType:QY.Type.Num},$),Y.if((0,a.not)($),J)})}}qz.validateArray=JB;function HB(Q){let{gen:Y,schema:X,keyword:W,it:G}=Q;if(!Array.isArray(X))throw Error("ajv implementation error");if(X.some((H)=>(0,QY.alwaysValidSchema)(G,H))&&!G.opts.unevaluated)return;let z=Y.let("valid",!1),J=Y.name("_valid");Y.block(()=>X.forEach((H,A)=>{let U=Q.subschema({keyword:W,schemaProp:A,compositeRule:!0},J);if(Y.assign(z,a._`${z} || ${J}`),!Q.mergeValidEvaluated(U,J))Y.if((0,a.not)(z))})),Q.result(z,()=>Q.reset(),()=>Q.error(!0))}qz.validateUnion=HB});var wz=P((Zz)=>{Object.defineProperty(Zz,"__esModule",{value:!0});Zz.validateKeywordUsage=Zz.validSchemaType=Zz.funcKeywordCode=Zz.macroKeywordCode=void 0;var M0=g(),S1=Y1(),NB=C0(),wB=k4();function PB(Q,Y){let{gen:X,keyword:W,schema:G,parentSchema:$,it:z}=Q,J=Y.macro.call(z.self,G,$,z),H=Vz(X,W,J);if(z.opts.validateSchema!==!1)z.self.validateSchema(J,!0);let A=X.name("valid");Q.subschema({schema:J,schemaPath:M0.nil,errSchemaPath:`${z.errSchemaPath}/${W}`,topSchemaRef:H,compositeRule:!0},A),Q.pass(A,()=>Q.error(!0))}Zz.macroKeywordCode=PB;function bB(Q,Y){var X;let{gen:W,keyword:G,schema:$,parentSchema:z,$data:J,it:H}=Q;IB(H,Y);let A=!J&&Y.compile?Y.compile.call(H.self,$,z,H):Y.validate,U=Vz(W,G,A),K=W.let("valid");Q.block$data(K,D),Q.ok((X=Y.valid)!==null&&X!==void 0?X:K);function D(){if(Y.errors===!1){if(M(),Y.modifying)Mz(Q);N(()=>Q.error())}else{let Z=Y.async?L():O();if(Y.modifying)Mz(Q);N(()=>jB(Q,Z))}}function L(){let Z=W.let("ruleErrs",null);return W.try(()=>M(M0._`await `),(k)=>W.assign(K,!1).if(M0._`${k} instanceof ${H.ValidationError}`,()=>W.assign(Z,M0._`${k}.errors`),()=>W.throw(k))),Z}function O(){let Z=M0._`${U}.errors`;return W.assign(Z,null),M(M0.nil),Z}function M(Z=Y.async?M0._`await `:M0.nil){let k=H.opts.passContext?S1.default.this:S1.default.self,S=!(("compile"in Y)&&!J||Y.schema===!1);W.assign(K,M0._`${Z}${(0,NB.callValidateCode)(Q,U,k,S)}`,Y.modifying)}function N(Z){var k;W.if((0,M0.not)((k=Y.valid)!==null&&k!==void 0?k:K),Z)}}Zz.funcKeywordCode=bB;function Mz(Q){let{gen:Y,data:X,it:W}=Q;Y.if(W.parentData,()=>Y.assign(X,M0._`${W.parentData}[${W.parentDataProperty}]`))}function jB(Q,Y){let{gen:X}=Q;X.if(M0._`Array.isArray(${Y})`,()=>{X.assign(S1.default.vErrors,M0._`${S1.default.vErrors} === null ? ${Y} : ${S1.default.vErrors}.concat(${Y})`).assign(S1.default.errors,M0._`${S1.default.vErrors}.length`),(0,wB.extendErrors)(Q)},()=>Q.error())}function IB({schemaEnv:Q},Y){if(Y.async&&!Q.$async)throw Error("async keyword in sync schema")}function Vz(Q,Y,X){if(X===void 0)throw Error(`keyword "${Y}" failed to compile`);return Q.scopeValue("keyword",typeof X=="function"?{ref:X}:{ref:X,code:(0,M0.stringify)(X)})}function EB(Q,Y,X=!1){return!Y.length||Y.some((W)=>W==="array"?Array.isArray(Q):W==="object"?Q&&typeof Q=="object"&&!Array.isArray(Q):typeof Q==W||X&&typeof Q>"u")}Zz.validSchemaType=EB;function TB({schema:Q,opts:Y,self:X,errSchemaPath:W},G,$){if(Array.isArray(G.keyword)?!G.keyword.includes($):G.keyword!==$)throw Error("ajv implementation error");let z=G.dependencies;if(z===null||z===void 0?void 0:z.some((J)=>!Object.prototype.hasOwnProperty.call(Q,J)))throw Error(`parent schema must have dependencies of ${$}: ${z.join(",")}`);if(G.validateSchema){if(!G.validateSchema(Q[$])){let H=`keyword "${$}" value is invalid at path "${W}": `+X.errorsText(G.validateSchema.errors);if(Y.validateSchema==="log")X.logger.error(H);else throw Error(H)}}}Zz.validateKeywordUsage=TB});var Iz=P((bz)=>{Object.defineProperty(bz,"__esModule",{value:!0});bz.extendSubschemaMode=bz.extendSubschemaData=bz.getSubschema=void 0;var p0=g(),Pz=c();function kB(Q,{keyword:Y,schemaProp:X,schema:W,schemaPath:G,errSchemaPath:$,topSchemaRef:z}){if(Y!==void 0&&W!==void 0)throw Error('both "keyword" and "schema" passed, only one allowed');if(Y!==void 0){let J=Q.schema[Y];return X===void 0?{schema:J,schemaPath:p0._`${Q.schemaPath}${(0,p0.getProperty)(Y)}`,errSchemaPath:`${Q.errSchemaPath}/${Y}`}:{schema:J[X],schemaPath:p0._`${Q.schemaPath}${(0,p0.getProperty)(Y)}${(0,p0.getProperty)(X)}`,errSchemaPath:`${Q.errSchemaPath}/${Y}/${(0,Pz.escapeFragment)(X)}`}}if(W!==void 0){if(G===void 0||$===void 0||z===void 0)throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:W,schemaPath:G,topSchemaRef:z,errSchemaPath:$}}throw Error('either "keyword" or "schema" must be passed')}bz.getSubschema=kB;function vB(Q,Y,{dataProp:X,dataPropType:W,data:G,dataTypes:$,propertyName:z}){if(G!==void 0&&X!==void 0)throw Error('both "data" and "dataProp" passed, only one allowed');let{gen:J}=Y;if(X!==void 0){let{errorPath:A,dataPathArr:U,opts:K}=Y,D=J.let("data",p0._`${Y.data}${(0,p0.getProperty)(X)}`,!0);H(D),Q.errorPath=p0.str`${A}${(0,Pz.getErrorPath)(X,W,K.jsPropertySyntax)}`,Q.parentDataProperty=p0._`${X}`,Q.dataPathArr=[...U,Q.parentDataProperty]}if(G!==void 0){let A=G instanceof p0.Name?G:J.let("data",G,!0);if(H(A),z!==void 0)Q.propertyName=z}if($)Q.dataTypes=$;function H(A){Q.data=A,Q.dataLevel=Y.dataLevel+1,Q.dataTypes=[],Y.definedProperties=new Set,Q.parentData=Y.data,Q.dataNames=[...Y.dataNames,A]}}bz.extendSubschemaData=vB;function xB(Q,{jtdDiscriminator:Y,jtdMetadata:X,compositeRule:W,createErrors:G,allErrors:$}){if(W!==void 0)Q.compositeRule=W;if(G!==void 0)Q.createErrors=G;if($!==void 0)Q.allErrors=$;Q.jtdDiscriminator=Y,Q.jtdMetadata=X}bz.extendSubschemaMode=xB});var WY=P((_I,Ez)=>{Ez.exports=function Q(Y,X){if(Y===X)return!0;if(Y&&X&&typeof Y=="object"&&typeof X=="object"){if(Y.constructor!==X.constructor)return!1;var W,G,$;if(Array.isArray(Y)){if(W=Y.length,W!=X.length)return!1;for(G=W;G--!==0;)if(!Q(Y[G],X[G]))return!1;return!0}if(Y.constructor===RegExp)return Y.source===X.source&&Y.flags===X.flags;if(Y.valueOf!==Object.prototype.valueOf)return Y.valueOf()===X.valueOf();if(Y.toString!==Object.prototype.toString)return Y.toString()===X.toString();if($=Object.keys(Y),W=$.length,W!==Object.keys(X).length)return!1;for(G=W;G--!==0;)if(!Object.prototype.hasOwnProperty.call(X,$[G]))return!1;for(G=W;G--!==0;){var z=$[G];if(!Q(Y[z],X[z]))return!1}return!0}return Y!==Y&&X!==X}});var Sz=P((gI,Tz)=>{var O1=Tz.exports=function(Q,Y,X){if(typeof Y=="function")X=Y,Y={};X=Y.cb||X;var W=typeof X=="function"?X:X.pre||function(){},G=X.post||function(){};o6(Y,W,G,Q,"",Q)};O1.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};O1.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};O1.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};O1.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 o6(Q,Y,X,W,G,$,z,J,H,A){if(W&&typeof W=="object"&&!Array.isArray(W)){Y(W,G,$,z,J,H,A);for(var U in W){var K=W[U];if(Array.isArray(K)){if(U in O1.arrayKeywords)for(var D=0;D<K.length;D++)o6(Q,Y,X,K[D],G+"/"+U+"/"+D,$,G,U,W,D)}else if(U in O1.propsKeywords){if(K&&typeof K=="object")for(var L in K)o6(Q,Y,X,K[L],G+"/"+U+"/"+yB(L),$,G,U,W,L)}else if(U in O1.keywords||Q.allKeys&&!(U in O1.skipKeywords))o6(Q,Y,X,K,G+"/"+U,$,G,U,W)}X(W,G,$,z,J,H,A)}}function yB(Q){return Q.replace(/~/g,"~0").replace(/\//g,"~1")}});var x4=P((vz)=>{Object.defineProperty(vz,"__esModule",{value:!0});vz.getSchemaRefs=vz.resolveUrl=vz.normalizeId=vz._getFullPath=vz.getFullPath=vz.inlineRef=void 0;var uB=c(),hB=WY(),fB=Sz(),lB=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function mB(Q,Y=!0){if(typeof Q=="boolean")return!0;if(Y===!0)return!GY(Q);if(!Y)return!1;return Rz(Q)<=Y}vz.inlineRef=mB;var cB=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function GY(Q){for(let Y in Q){if(cB.has(Y))return!0;let X=Q[Y];if(Array.isArray(X)&&X.some(GY))return!0;if(typeof X=="object"&&GY(X))return!0}return!1}function Rz(Q){let Y=0;for(let X in Q){if(X==="$ref")return 1/0;if(Y++,lB.has(X))continue;if(typeof Q[X]=="object")(0,uB.eachItem)(Q[X],(W)=>Y+=Rz(W));if(Y===1/0)return 1/0}return Y}function Cz(Q,Y="",X){if(X!==!1)Y=d1(Y);let W=Q.parse(Y);return kz(Q,W)}vz.getFullPath=Cz;function kz(Q,Y){return Q.serialize(Y).split("#")[0]+"#"}vz._getFullPath=kz;var pB=/#\/?$/;function d1(Q){return Q?Q.replace(pB,""):""}vz.normalizeId=d1;function iB(Q,Y,X){return X=d1(X),Q.resolve(Y,X)}vz.resolveUrl=iB;var nB=/^[a-z_][-a-z0-9._]*$/i;function rB(Q,Y){if(typeof Q=="boolean")return{};let{schemaId:X,uriResolver:W}=this.opts,G=d1(Q[X]||Y),$={"":G},z=Cz(W,G,!1),J={},H=new Set;return fB(Q,{allKeys:!0},(K,D,L,O)=>{if(O===void 0)return;let M=z+D,N=$[O];if(typeof K[X]=="string")N=Z.call(this,K[X]);k.call(this,K.$anchor),k.call(this,K.$dynamicAnchor),$[D]=N;function Z(S){let y=this.opts.uriResolver.resolve;if(S=d1(N?y(N,S):S),H.has(S))throw U(S);H.add(S);let C=this.refs[S];if(typeof C=="string")C=this.refs[C];if(typeof C=="object")A(K,C.schema,S);else if(S!==d1(M))if(S[0]==="#")A(K,J[S],S),J[S]=K;else this.refs[S]=M;return S}function k(S){if(typeof S=="string"){if(!nB.test(S))throw Error(`invalid anchor "${S}"`);Z.call(this,`#${S}`)}}}),J;function A(K,D,L){if(D!==void 0&&!hB(K,D))throw U(L)}function U(K){return Error(`reference "${K}" resolves to more than one schema`)}}vz.getSchemaRefs=rB});var y4=P((oz)=>{Object.defineProperty(oz,"__esModule",{value:!0});oz.getData=oz.KeywordCxt=oz.validateFunctionCode=void 0;var hz=s$(),_z=v4(),zY=t9(),t6=v4(),eB=Bz(),g4=wz(),$Y=Iz(),I=g(),v=Y1(),QL=x4(),X1=c(),_4=k4();function YL(Q){if(mz(Q)){if(cz(Q),lz(Q)){GL(Q);return}}fz(Q,()=>(0,hz.topBoolOrEmptySchema)(Q))}oz.validateFunctionCode=YL;function fz({gen:Q,validateName:Y,schema:X,schemaEnv:W,opts:G},$){if(G.code.es5)Q.func(Y,I._`${v.default.data}, ${v.default.valCxt}`,W.$async,()=>{Q.code(I._`"use strict"; ${gz(X,G)}`),WL(Q,G),Q.code($)});else Q.func(Y,I._`${v.default.data}, ${XL(G)}`,W.$async,()=>Q.code(gz(X,G)).code($))}function XL(Q){return I._`{${v.default.instancePath}="", ${v.default.parentData}, ${v.default.parentDataProperty}, ${v.default.rootData}=${v.default.data}${Q.dynamicRef?I._`, ${v.default.dynamicAnchors}={}`:I.nil}}={}`}function WL(Q,Y){Q.if(v.default.valCxt,()=>{if(Q.var(v.default.instancePath,I._`${v.default.valCxt}.${v.default.instancePath}`),Q.var(v.default.parentData,I._`${v.default.valCxt}.${v.default.parentData}`),Q.var(v.default.parentDataProperty,I._`${v.default.valCxt}.${v.default.parentDataProperty}`),Q.var(v.default.rootData,I._`${v.default.valCxt}.${v.default.rootData}`),Y.dynamicRef)Q.var(v.default.dynamicAnchors,I._`${v.default.valCxt}.${v.default.dynamicAnchors}`)},()=>{if(Q.var(v.default.instancePath,I._`""`),Q.var(v.default.parentData,I._`undefined`),Q.var(v.default.parentDataProperty,I._`undefined`),Q.var(v.default.rootData,v.default.data),Y.dynamicRef)Q.var(v.default.dynamicAnchors,I._`{}`)})}function GL(Q){let{schema:Y,opts:X,gen:W}=Q;fz(Q,()=>{if(X.$comment&&Y.$comment)iz(Q);if(AL(Q),W.let(v.default.vErrors,null),W.let(v.default.errors,0),X.unevaluated)$L(Q);pz(Q),DL(Q)});return}function $L(Q){let{gen:Y,validateName:X}=Q;Q.evaluated=Y.const("evaluated",I._`${X}.evaluated`),Y.if(I._`${Q.evaluated}.dynamicProps`,()=>Y.assign(I._`${Q.evaluated}.props`,I._`undefined`)),Y.if(I._`${Q.evaluated}.dynamicItems`,()=>Y.assign(I._`${Q.evaluated}.items`,I._`undefined`))}function gz(Q,Y){let X=typeof Q=="object"&&Q[Y.schemaId];return X&&(Y.code.source||Y.code.process)?I._`/*# sourceURL=${X} */`:I.nil}function zL(Q,Y){if(mz(Q)){if(cz(Q),lz(Q)){JL(Q,Y);return}}(0,hz.boolOrEmptySchema)(Q,Y)}function lz({schema:Q,self:Y}){if(typeof Q=="boolean")return!Q;for(let X in Q)if(Y.RULES.all[X])return!0;return!1}function mz(Q){return typeof Q.schema!="boolean"}function JL(Q,Y){let{schema:X,gen:W,opts:G}=Q;if(G.$comment&&X.$comment)iz(Q);UL(Q),KL(Q);let $=W.const("_errs",v.default.errors);pz(Q,$),W.var(Y,I._`${$} === ${v.default.errors}`)}function cz(Q){(0,X1.checkUnknownRules)(Q),HL(Q)}function pz(Q,Y){if(Q.opts.jtd)return yz(Q,[],!1,Y);let X=(0,_z.getSchemaTypes)(Q.schema),W=(0,_z.coerceAndCheckDataType)(Q,X);yz(Q,X,!W,Y)}function HL(Q){let{schema:Y,errSchemaPath:X,opts:W,self:G}=Q;if(Y.$ref&&W.ignoreKeywordsWithRef&&(0,X1.schemaHasRulesButRef)(Y,G.RULES))G.logger.warn(`$ref: keywords ignored in schema at path "${X}"`)}function AL(Q){let{schema:Y,opts:X}=Q;if(Y.default!==void 0&&X.useDefaults&&X.strictSchema)(0,X1.checkStrictMode)(Q,"default is ignored in the schema root")}function UL(Q){let Y=Q.schema[Q.opts.schemaId];if(Y)Q.baseId=(0,QL.resolveUrl)(Q.opts.uriResolver,Q.baseId,Y)}function KL(Q){if(Q.schema.$async&&!Q.schemaEnv.$async)throw Error("async schema in sync schema")}function iz({gen:Q,schemaEnv:Y,schema:X,errSchemaPath:W,opts:G}){let $=X.$comment;if(G.$comment===!0)Q.code(I._`${v.default.self}.logger.log(${$})`);else if(typeof G.$comment=="function"){let z=I.str`${W}/$comment`,J=Q.scopeValue("root",{ref:Y.root});Q.code(I._`${v.default.self}.opts.$comment(${$}, ${z}, ${J}.schema)`)}}function DL(Q){let{gen:Y,schemaEnv:X,validateName:W,ValidationError:G,opts:$}=Q;if(X.$async)Y.if(I._`${v.default.errors} === 0`,()=>Y.return(v.default.data),()=>Y.throw(I._`new ${G}(${v.default.vErrors})`));else{if(Y.assign(I._`${W}.errors`,v.default.vErrors),$.unevaluated)BL(Q);Y.return(I._`${v.default.errors} === 0`)}}function BL({gen:Q,evaluated:Y,props:X,items:W}){if(X instanceof I.Name)Q.assign(I._`${Y}.props`,X);if(W instanceof I.Name)Q.assign(I._`${Y}.items`,W)}function yz(Q,Y,X,W){let{gen:G,schema:$,data:z,allErrors:J,opts:H,self:A}=Q,{RULES:U}=A;if($.$ref&&(H.ignoreKeywordsWithRef||!(0,X1.schemaHasRulesButRef)($,U))){G.block(()=>rz(Q,"$ref",U.all.$ref.definition));return}if(!H.jtd)LL(Q,Y);G.block(()=>{for(let D of U.rules)K(D);K(U.post)});function K(D){if(!(0,zY.shouldUseGroup)($,D))return;if(D.type){if(G.if((0,t6.checkDataType)(D.type,z,H.strictNumbers)),uz(Q,D),Y.length===1&&Y[0]===D.type&&X)G.else(),(0,t6.reportTypeError)(Q);G.endIf()}else uz(Q,D);if(!J)G.if(I._`${v.default.errors} === ${W||0}`)}}function uz(Q,Y){let{gen:X,schema:W,opts:{useDefaults:G}}=Q;if(G)(0,eB.assignDefaults)(Q,Y.type);X.block(()=>{for(let $ of Y.rules)if((0,zY.shouldUseRule)(W,$))rz(Q,$.keyword,$.definition,Y.type)})}function LL(Q,Y){if(Q.schemaEnv.meta||!Q.opts.strictTypes)return;if(FL(Q,Y),!Q.opts.allowUnionTypes)qL(Q,Y);OL(Q,Q.dataTypes)}function FL(Q,Y){if(!Y.length)return;if(!Q.dataTypes.length){Q.dataTypes=Y;return}Y.forEach((X)=>{if(!nz(Q.dataTypes,X))JY(Q,`type "${X}" not allowed by context "${Q.dataTypes.join(",")}"`)}),VL(Q,Y)}function qL(Q,Y){if(Y.length>1&&!(Y.length===2&&Y.includes("null")))JY(Q,"use allowUnionTypes to allow union type keyword")}function OL(Q,Y){let X=Q.self.RULES.all;for(let W in X){let G=X[W];if(typeof G=="object"&&(0,zY.shouldUseRule)(Q.schema,G)){let{type:$}=G.definition;if($.length&&!$.some((z)=>ML(Y,z)))JY(Q,`missing type "${$.join(",")}" for keyword "${W}"`)}}}function ML(Q,Y){return Q.includes(Y)||Y==="number"&&Q.includes("integer")}function nz(Q,Y){return Q.includes(Y)||Y==="integer"&&Q.includes("number")}function VL(Q,Y){let X=[];for(let W of Q.dataTypes)if(nz(Y,W))X.push(W);else if(Y.includes("integer")&&W==="number")X.push("integer");Q.dataTypes=X}function JY(Q,Y){let X=Q.schemaEnv.baseId+Q.errSchemaPath;Y+=` at "${X}" (strictTypes)`,(0,X1.checkStrictMode)(Q,Y,Q.opts.strictTypes)}class HY{constructor(Q,Y,X){if((0,g4.validateKeywordUsage)(Q,Y,X),this.gen=Q.gen,this.allErrors=Q.allErrors,this.keyword=X,this.data=Q.data,this.schema=Q.schema[X],this.$data=Y.$data&&Q.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,X1.schemaRefOrVal)(Q,this.schema,X,this.$data),this.schemaType=Y.schemaType,this.parentSchema=Q.schema,this.params={},this.it=Q,this.def=Y,this.$data)this.schemaCode=Q.gen.const("vSchema",dz(this.$data,Q));else if(this.schemaCode=this.schemaValue,!(0,g4.validSchemaType)(this.schema,Y.schemaType,Y.allowUndefined))throw Error(`${X} value must be ${JSON.stringify(Y.schemaType)}`);if("code"in Y?Y.trackErrors:Y.errors!==!1)this.errsCount=Q.gen.const("_errs",v.default.errors)}result(Q,Y,X){this.failResult((0,I.not)(Q),Y,X)}failResult(Q,Y,X){if(this.gen.if(Q),X)X();else this.error();if(Y){if(this.gen.else(),Y(),this.allErrors)this.gen.endIf()}else if(this.allErrors)this.gen.endIf();else this.gen.else()}pass(Q,Y){this.failResult((0,I.not)(Q),void 0,Y)}fail(Q){if(Q===void 0){if(this.error(),!this.allErrors)this.gen.if(!1);return}if(this.gen.if(Q),this.error(),this.allErrors)this.gen.endIf();else this.gen.else()}fail$data(Q){if(!this.$data)return this.fail(Q);let{schemaCode:Y}=this;this.fail(I._`${Y} !== undefined && (${(0,I.or)(this.invalid$data(),Q)})`)}error(Q,Y,X){if(Y){this.setParams(Y),this._error(Q,X),this.setParams({});return}this._error(Q,X)}_error(Q,Y){(Q?_4.reportExtraError:_4.reportError)(this,this.def.error,Y)}$dataError(){(0,_4.reportError)(this,this.def.$dataError||_4.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error('add "trackErrors" to keyword definition');(0,_4.resetErrorsCount)(this.gen,this.errsCount)}ok(Q){if(!this.allErrors)this.gen.if(Q)}setParams(Q,Y){if(Y)Object.assign(this.params,Q);else this.params=Q}block$data(Q,Y,X=I.nil){this.gen.block(()=>{this.check$data(Q,X),Y()})}check$data(Q=I.nil,Y=I.nil){if(!this.$data)return;let{gen:X,schemaCode:W,schemaType:G,def:$}=this;if(X.if((0,I.or)(I._`${W} === undefined`,Y)),Q!==I.nil)X.assign(Q,!0);if(G.length||$.validateSchema){if(X.elseIf(this.invalid$data()),this.$dataError(),Q!==I.nil)X.assign(Q,!1)}X.else()}invalid$data(){let{gen:Q,schemaCode:Y,schemaType:X,def:W,it:G}=this;return(0,I.or)($(),z());function $(){if(X.length){if(!(Y instanceof I.Name))throw Error("ajv implementation error");let J=Array.isArray(X)?X:[X];return I._`${(0,t6.checkDataTypes)(J,Y,G.opts.strictNumbers,t6.DataType.Wrong)}`}return I.nil}function z(){if(W.validateSchema){let J=Q.scopeValue("validate$data",{ref:W.validateSchema});return I._`!${J}(${Y})`}return I.nil}}subschema(Q,Y){let X=(0,$Y.getSubschema)(this.it,Q);(0,$Y.extendSubschemaData)(X,this.it,Q),(0,$Y.extendSubschemaMode)(X,Q);let W={...this.it,...X,items:void 0,props:void 0};return zL(W,Y),W}mergeEvaluated(Q,Y){let{it:X,gen:W}=this;if(!X.opts.unevaluated)return;if(X.props!==!0&&Q.props!==void 0)X.props=X1.mergeEvaluated.props(W,Q.props,X.props,Y);if(X.items!==!0&&Q.items!==void 0)X.items=X1.mergeEvaluated.items(W,Q.items,X.items,Y)}mergeValidEvaluated(Q,Y){let{it:X,gen:W}=this;if(X.opts.unevaluated&&(X.props!==!0||X.items!==!0))return W.if(Y,()=>this.mergeEvaluated(Q,I.Name)),!0}}oz.KeywordCxt=HY;function rz(Q,Y,X,W){let G=new HY(Q,X,Y);if("code"in X)X.code(G,W);else if(G.$data&&X.validate)(0,g4.funcKeywordCode)(G,X);else if("macro"in X)(0,g4.macroKeywordCode)(G,X);else if(X.compile||X.validate)(0,g4.funcKeywordCode)(G,X)}var ZL=/^\/(?:[^~]|~0|~1)*$/,NL=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function dz(Q,{dataLevel:Y,dataNames:X,dataPathArr:W}){let G,$;if(Q==="")return v.default.rootData;if(Q[0]==="/"){if(!ZL.test(Q))throw Error(`Invalid JSON-pointer: ${Q}`);G=Q,$=v.default.rootData}else{let A=NL.exec(Q);if(!A)throw Error(`Invalid JSON-pointer: ${Q}`);let U=+A[1];if(G=A[2],G==="#"){if(U>=Y)throw Error(H("property/index",U));return W[Y-U]}if(U>Y)throw Error(H("data",U));if($=X[Y-U],!G)return $}let z=$,J=G.split("/");for(let A of J)if(A)$=I._`${$}${(0,I.getProperty)((0,X1.unescapeJsonPointer)(A))}`,z=I._`${z} && ${$}`;return z;function H(A,U){return`Cannot access ${A} ${U} levels up, current level is ${Y}`}}oz.getData=dz});var a6=P((sz)=>{Object.defineProperty(sz,"__esModule",{value:!0});class az extends Error{constructor(Q){super("validation failed");this.errors=Q,this.ajv=this.validation=!0}}sz.default=az});var u4=P((QJ)=>{Object.defineProperty(QJ,"__esModule",{value:!0});var AY=x4();class ez extends Error{constructor(Q,Y,X,W){super(W||`can't resolve reference ${X} from id ${Y}`);this.missingRef=(0,AY.resolveUrl)(Q,Y,X),this.missingSchema=(0,AY.normalizeId)((0,AY.getFullPath)(Q,this.missingRef))}}QJ.default=ez});var e6=P((WJ)=>{Object.defineProperty(WJ,"__esModule",{value:!0});WJ.resolveSchema=WJ.getCompilingSchema=WJ.resolveRef=WJ.compileSchema=WJ.SchemaEnv=void 0;var y0=g(),IL=a6(),R1=Y1(),u0=x4(),YJ=c(),EL=y4();class h4{constructor(Q){var Y;this.refs={},this.dynamicAnchors={};let X;if(typeof Q.schema=="object")X=Q.schema;this.schema=Q.schema,this.schemaId=Q.schemaId,this.root=Q.root||this,this.baseId=(Y=Q.baseId)!==null&&Y!==void 0?Y:(0,u0.normalizeId)(X===null||X===void 0?void 0:X[Q.schemaId||"$id"]),this.schemaPath=Q.schemaPath,this.localRefs=Q.localRefs,this.meta=Q.meta,this.$async=X===null||X===void 0?void 0:X.$async,this.refs={}}}WJ.SchemaEnv=h4;function KY(Q){let Y=XJ.call(this,Q);if(Y)return Y;let X=(0,u0.getFullPath)(this.opts.uriResolver,Q.root.baseId),{es5:W,lines:G}=this.opts.code,{ownProperties:$}=this.opts,z=new y0.CodeGen(this.scope,{es5:W,lines:G,ownProperties:$}),J;if(Q.$async)J=z.scopeValue("Error",{ref:IL.default,code:y0._`require("ajv/dist/runtime/validation_error").default`});let H=z.scopeName("validate");Q.validateName=H;let A={gen:z,allErrors:this.opts.allErrors,data:R1.default.data,parentData:R1.default.parentData,parentDataProperty:R1.default.parentDataProperty,dataNames:[R1.default.data],dataPathArr:[y0.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:z.scopeValue("schema",this.opts.code.source===!0?{ref:Q.schema,code:(0,y0.stringify)(Q.schema)}:{ref:Q.schema}),validateName:H,ValidationError:J,schema:Q.schema,schemaEnv:Q,rootId:X,baseId:Q.baseId||X,schemaPath:y0.nil,errSchemaPath:Q.schemaPath||(this.opts.jtd?"":"#"),errorPath:y0._`""`,opts:this.opts,self:this},U;try{this._compilations.add(Q),(0,EL.validateFunctionCode)(A),z.optimize(this.opts.code.optimize);let K=z.toString();if(U=`${z.scopeRefs(R1.default.scope)}return ${K}`,this.opts.code.process)U=this.opts.code.process(U,Q);let L=Function(`${R1.default.self}`,`${R1.default.scope}`,U)(this,this.scope.get());if(this.scope.value(H,{ref:L}),L.errors=null,L.schema=Q.schema,L.schemaEnv=Q,Q.$async)L.$async=!0;if(this.opts.code.source===!0)L.source={validateName:H,validateCode:K,scopeValues:z._values};if(this.opts.unevaluated){let{props:O,items:M}=A;if(L.evaluated={props:O instanceof y0.Name?void 0:O,items:M instanceof y0.Name?void 0:M,dynamicProps:O instanceof y0.Name,dynamicItems:M instanceof y0.Name},L.source)L.source.evaluated=(0,y0.stringify)(L.evaluated)}return Q.validate=L,Q}catch(K){if(delete Q.validate,delete Q.validateName,U)this.logger.error("Error compiling schema, function code:",U);throw K}finally{this._compilations.delete(Q)}}WJ.compileSchema=KY;function TL(Q,Y,X){var W;X=(0,u0.resolveUrl)(this.opts.uriResolver,Y,X);let G=Q.refs[X];if(G)return G;let $=CL.call(this,Q,X);if($===void 0){let z=(W=Q.localRefs)===null||W===void 0?void 0:W[X],{schemaId:J}=this.opts;if(z)$=new h4({schema:z,schemaId:J,root:Q,baseId:Y})}if($===void 0)return;return Q.refs[X]=SL.call(this,$)}WJ.resolveRef=TL;function SL(Q){if((0,u0.inlineRef)(Q.schema,this.opts.inlineRefs))return Q.schema;return Q.validate?Q:KY.call(this,Q)}function XJ(Q){for(let Y of this._compilations)if(RL(Y,Q))return Y}WJ.getCompilingSchema=XJ;function RL(Q,Y){return Q.schema===Y.schema&&Q.root===Y.root&&Q.baseId===Y.baseId}function CL(Q,Y){let X;while(typeof(X=this.refs[Y])=="string")Y=X;return X||this.schemas[Y]||s6.call(this,Q,Y)}function s6(Q,Y){let X=this.opts.uriResolver.parse(Y),W=(0,u0._getFullPath)(this.opts.uriResolver,X),G=(0,u0.getFullPath)(this.opts.uriResolver,Q.baseId,void 0);if(Object.keys(Q.schema).length>0&&W===G)return UY.call(this,X,Q);let $=(0,u0.normalizeId)(W),z=this.refs[$]||this.schemas[$];if(typeof z=="string"){let J=s6.call(this,Q,z);if(typeof(J===null||J===void 0?void 0:J.schema)!=="object")return;return UY.call(this,X,J)}if(typeof(z===null||z===void 0?void 0:z.schema)!=="object")return;if(!z.validate)KY.call(this,z);if($===(0,u0.normalizeId)(Y)){let{schema:J}=z,{schemaId:H}=this.opts,A=J[H];if(A)G=(0,u0.resolveUrl)(this.opts.uriResolver,G,A);return new h4({schema:J,schemaId:H,root:Q,baseId:G})}return UY.call(this,X,z)}WJ.resolveSchema=s6;var kL=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function UY(Q,{baseId:Y,schema:X,root:W}){var G;if(((G=Q.fragment)===null||G===void 0?void 0:G[0])!=="/")return;for(let J of Q.fragment.slice(1).split("/")){if(typeof X==="boolean")return;let H=X[(0,YJ.unescapeFragment)(J)];if(H===void 0)return;X=H;let A=typeof X==="object"&&X[this.opts.schemaId];if(!kL.has(J)&&A)Y=(0,u0.resolveUrl)(this.opts.uriResolver,Y,A)}let $;if(typeof X!="boolean"&&X.$ref&&!(0,YJ.schemaHasRulesButRef)(X,this.RULES)){let J=(0,u0.resolveUrl)(this.opts.uriResolver,Y,X.$ref);$=s6.call(this,W,J)}let{schemaId:z}=this.opts;if($=$||new h4({schema:X,schemaId:z,root:W,baseId:Y}),$.schema!==$.root.schema)return $;return}});var $J=P((mI,yL)=>{yL.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 BY=P((cI,AJ)=>{var uL=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),JJ=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 DY(Q){let Y="",X=0,W=0;for(W=0;W<Q.length;W++){if(X=Q[W].charCodeAt(0),X===48)continue;if(!(X>=48&&X<=57||X>=65&&X<=70||X>=97&&X<=102))return"";Y+=Q[W];break}for(W+=1;W<Q.length;W++){if(X=Q[W].charCodeAt(0),!(X>=48&&X<=57||X>=65&&X<=70||X>=97&&X<=102))return"";Y+=Q[W]}return Y}var hL=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function zJ(Q){return Q.length=0,!0}function fL(Q,Y,X){if(Q.length){let W=DY(Q);if(W!=="")Y.push(W);else return X.error=!0,!1;Q.length=0}return!0}function lL(Q){let Y=0,X={error:!1,address:"",zone:""},W=[],G=[],$=!1,z=!1,J=fL;for(let H=0;H<Q.length;H++){let A=Q[H];if(A==="["||A==="]")continue;if(A===":"){if($===!0)z=!0;if(!J(G,W,X))break;if(++Y>7){X.error=!0;break}if(H>0&&Q[H-1]===":")$=!0;W.push(":");continue}else if(A==="%"){if(!J(G,W,X))break;J=zJ}else{G.push(A);continue}}if(G.length)if(J===zJ)X.zone=G.join("");else if(z)W.push(G.join(""));else W.push(DY(G));return X.address=W.join(""),X}function HJ(Q){if(mL(Q,":")<2)return{host:Q,isIPV6:!1};let Y=lL(Q);if(!Y.error){let{address:X,address:W}=Y;if(Y.zone)X+="%"+Y.zone,W+="%25"+Y.zone;return{host:X,isIPV6:!0,escapedHost:W}}else return{host:Q,isIPV6:!1}}function mL(Q,Y){let X=0;for(let W=0;W<Q.length;W++)if(Q[W]===Y)X++;return X}function cL(Q){let Y=Q,X=[],W=-1,G=0;while(G=Y.length){if(G===1)if(Y===".")break;else if(Y==="/"){X.push("/");break}else{X.push(Y);break}else if(G===2){if(Y[0]==="."){if(Y[1]===".")break;else if(Y[1]==="/"){Y=Y.slice(2);continue}}else if(Y[0]==="/"){if(Y[1]==="."||Y[1]==="/"){X.push("/");break}}}else if(G===3){if(Y==="/.."){if(X.length!==0)X.pop();X.push("/");break}}if(Y[0]==="."){if(Y[1]==="."){if(Y[2]==="/"){Y=Y.slice(3);continue}}else if(Y[1]==="/"){Y=Y.slice(2);continue}}else if(Y[0]==="/"){if(Y[1]==="."){if(Y[2]==="/"){Y=Y.slice(2);continue}else if(Y[2]==="."){if(Y[3]==="/"){if(Y=Y.slice(3),X.length!==0)X.pop();continue}}}}if((W=Y.indexOf("/",1))===-1){X.push(Y);break}else X.push(Y.slice(0,W)),Y=Y.slice(W)}return X.join("")}function pL(Q,Y){let X=Y!==!0?escape:unescape;if(Q.scheme!==void 0)Q.scheme=X(Q.scheme);if(Q.userinfo!==void 0)Q.userinfo=X(Q.userinfo);if(Q.host!==void 0)Q.host=X(Q.host);if(Q.path!==void 0)Q.path=X(Q.path);if(Q.query!==void 0)Q.query=X(Q.query);if(Q.fragment!==void 0)Q.fragment=X(Q.fragment);return Q}function iL(Q){let Y=[];if(Q.userinfo!==void 0)Y.push(Q.userinfo),Y.push("@");if(Q.host!==void 0){let X=unescape(Q.host);if(!JJ(X)){let W=HJ(X);if(W.isIPV6===!0)X=`[${W.escapedHost}]`;else X=Q.host}Y.push(X)}if(typeof Q.port==="number"||typeof Q.port==="string")Y.push(":"),Y.push(String(Q.port));return Y.length?Y.join(""):void 0}AJ.exports={nonSimpleDomain:hL,recomposeAuthority:iL,normalizeComponentEncoding:pL,removeDotSegments:cL,isIPv4:JJ,isUUID:uL,normalizeIPv6:HJ,stringArrayToHexStripped:DY}});var LJ=P((pI,BJ)=>{var{isUUID:nL}=BY(),rL=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,dL=["http","https","ws","wss","urn","urn:uuid"];function oL(Q){return dL.indexOf(Q)!==-1}function LY(Q){if(Q.secure===!0)return!0;else if(Q.secure===!1)return!1;else if(Q.scheme)return Q.scheme.length===3&&(Q.scheme[0]==="w"||Q.scheme[0]==="W")&&(Q.scheme[1]==="s"||Q.scheme[1]==="S")&&(Q.scheme[2]==="s"||Q.scheme[2]==="S");else return!1}function UJ(Q){if(!Q.host)Q.error=Q.error||"HTTP URIs must have a host.";return Q}function KJ(Q){let Y=String(Q.scheme).toLowerCase()==="https";if(Q.port===(Y?443:80)||Q.port==="")Q.port=void 0;if(!Q.path)Q.path="/";return Q}function tL(Q){return Q.secure=LY(Q),Q.resourceName=(Q.path||"/")+(Q.query?"?"+Q.query:""),Q.path=void 0,Q.query=void 0,Q}function aL(Q){if(Q.port===(LY(Q)?443:80)||Q.port==="")Q.port=void 0;if(typeof Q.secure==="boolean")Q.scheme=Q.secure?"wss":"ws",Q.secure=void 0;if(Q.resourceName){let[Y,X]=Q.resourceName.split("?");Q.path=Y&&Y!=="/"?Y:void 0,Q.query=X,Q.resourceName=void 0}return Q.fragment=void 0,Q}function sL(Q,Y){if(!Q.path)return Q.error="URN can not be parsed",Q;let X=Q.path.match(rL);if(X){let W=Y.scheme||Q.scheme||"urn";Q.nid=X[1].toLowerCase(),Q.nss=X[2];let G=`${W}:${Y.nid||Q.nid}`,$=FY(G);if(Q.path=void 0,$)Q=$.parse(Q,Y)}else Q.error=Q.error||"URN can not be parsed.";return Q}function eL(Q,Y){if(Q.nid===void 0)throw Error("URN without nid cannot be serialized");let X=Y.scheme||Q.scheme||"urn",W=Q.nid.toLowerCase(),G=`${X}:${Y.nid||W}`,$=FY(G);if($)Q=$.serialize(Q,Y);let z=Q,J=Q.nss;return z.path=`${W||Y.nid}:${J}`,Y.skipEscape=!0,z}function QF(Q,Y){let X=Q;if(X.uuid=X.nss,X.nss=void 0,!Y.tolerant&&(!X.uuid||!nL(X.uuid)))X.error=X.error||"UUID is not valid.";return X}function YF(Q){let Y=Q;return Y.nss=(Q.uuid||"").toLowerCase(),Y}var DJ={scheme:"http",domainHost:!0,parse:UJ,serialize:KJ},XF={scheme:"https",domainHost:DJ.domainHost,parse:UJ,serialize:KJ},QQ={scheme:"ws",domainHost:!0,parse:tL,serialize:aL},WF={scheme:"wss",domainHost:QQ.domainHost,parse:QQ.parse,serialize:QQ.serialize},GF={scheme:"urn",parse:sL,serialize:eL,skipNormalize:!0},$F={scheme:"urn:uuid",parse:QF,serialize:YF,skipNormalize:!0},YQ={http:DJ,https:XF,ws:QQ,wss:WF,urn:GF,"urn:uuid":$F};Object.setPrototypeOf(YQ,null);function FY(Q){return Q&&(YQ[Q]||YQ[Q.toLowerCase()])||void 0}BJ.exports={wsIsSecure:LY,SCHEMES:YQ,isValidSchemeName:oL,getSchemeHandler:FY}});var OJ=P((iI,WQ)=>{var{normalizeIPv6:zF,removeDotSegments:f4,recomposeAuthority:JF,normalizeComponentEncoding:XQ,isIPv4:HF,nonSimpleDomain:AF}=BY(),{SCHEMES:UF,getSchemeHandler:FJ}=LJ();function KF(Q,Y){if(typeof Q==="string")Q=i0(W1(Q,Y),Y);else if(typeof Q==="object")Q=W1(i0(Q,Y),Y);return Q}function DF(Q,Y,X){let W=X?Object.assign({scheme:"null"},X):{scheme:"null"},G=qJ(W1(Q,W),W1(Y,W),W,!0);return W.skipEscape=!0,i0(G,W)}function qJ(Q,Y,X,W){let G={};if(!W)Q=W1(i0(Q,X),X),Y=W1(i0(Y,X),X);if(X=X||{},!X.tolerant&&Y.scheme)G.scheme=Y.scheme,G.userinfo=Y.userinfo,G.host=Y.host,G.port=Y.port,G.path=f4(Y.path||""),G.query=Y.query;else{if(Y.userinfo!==void 0||Y.host!==void 0||Y.port!==void 0)G.userinfo=Y.userinfo,G.host=Y.host,G.port=Y.port,G.path=f4(Y.path||""),G.query=Y.query;else{if(!Y.path)if(G.path=Q.path,Y.query!==void 0)G.query=Y.query;else G.query=Q.query;else{if(Y.path[0]==="/")G.path=f4(Y.path);else{if((Q.userinfo!==void 0||Q.host!==void 0||Q.port!==void 0)&&!Q.path)G.path="/"+Y.path;else if(!Q.path)G.path=Y.path;else G.path=Q.path.slice(0,Q.path.lastIndexOf("/")+1)+Y.path;G.path=f4(G.path)}G.query=Y.query}G.userinfo=Q.userinfo,G.host=Q.host,G.port=Q.port}G.scheme=Q.scheme}return G.fragment=Y.fragment,G}function BF(Q,Y,X){if(typeof Q==="string")Q=unescape(Q),Q=i0(XQ(W1(Q,X),!0),{...X,skipEscape:!0});else if(typeof Q==="object")Q=i0(XQ(Q,!0),{...X,skipEscape:!0});if(typeof Y==="string")Y=unescape(Y),Y=i0(XQ(W1(Y,X),!0),{...X,skipEscape:!0});else if(typeof Y==="object")Y=i0(XQ(Y,!0),{...X,skipEscape:!0});return Q.toLowerCase()===Y.toLowerCase()}function i0(Q,Y){let X={host:Q.host,scheme:Q.scheme,userinfo:Q.userinfo,port:Q.port,path:Q.path,query:Q.query,nid:Q.nid,nss:Q.nss,uuid:Q.uuid,fragment:Q.fragment,reference:Q.reference,resourceName:Q.resourceName,secure:Q.secure,error:""},W=Object.assign({},Y),G=[],$=FJ(W.scheme||X.scheme);if($&&$.serialize)$.serialize(X,W);if(X.path!==void 0)if(!W.skipEscape){if(X.path=escape(X.path),X.scheme!==void 0)X.path=X.path.split("%3A").join(":")}else X.path=unescape(X.path);if(W.reference!=="suffix"&&X.scheme)G.push(X.scheme,":");let z=JF(X);if(z!==void 0){if(W.reference!=="suffix")G.push("//");if(G.push(z),X.path&&X.path[0]!=="/")G.push("/")}if(X.path!==void 0){let J=X.path;if(!W.absolutePath&&(!$||!$.absolutePath))J=f4(J);if(z===void 0&&J[0]==="/"&&J[1]==="/")J="/%2F"+J.slice(2);G.push(J)}if(X.query!==void 0)G.push("?",X.query);if(X.fragment!==void 0)G.push("#",X.fragment);return G.join("")}var LF=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function W1(Q,Y){let X=Object.assign({},Y),W={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},G=!1;if(X.reference==="suffix")if(X.scheme)Q=X.scheme+":"+Q;else Q="//"+Q;let $=Q.match(LF);if($){if(W.scheme=$[1],W.userinfo=$[3],W.host=$[4],W.port=parseInt($[5],10),W.path=$[6]||"",W.query=$[7],W.fragment=$[8],isNaN(W.port))W.port=$[5];if(W.host)if(HF(W.host)===!1){let H=zF(W.host);W.host=H.host.toLowerCase(),G=H.isIPV6}else G=!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(X.reference&&X.reference!=="suffix"&&X.reference!==W.reference)W.error=W.error||"URI is not a "+X.reference+" reference.";let z=FJ(X.scheme||W.scheme);if(!X.unicodeSupport&&(!z||!z.unicodeSupport)){if(W.host&&(X.domainHost||z&&z.domainHost)&&G===!1&&AF(W.host))try{W.host=URL.domainToASCII(W.host.toLowerCase())}catch(J){W.error=W.error||"Host's domain name can not be converted to ASCII: "+J}}if(!z||z&&!z.skipNormalize){if(Q.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(z&&z.parse)z.parse(W,X)}else W.error=W.error||"URI can not be parsed.";return W}var qY={SCHEMES:UF,normalize:KF,resolve:DF,resolveComponent:qJ,equal:BF,serialize:i0,parse:W1};WQ.exports=qY;WQ.exports.default=qY;WQ.exports.fastUri=qY});var ZJ=P((VJ)=>{Object.defineProperty(VJ,"__esModule",{value:!0});var MJ=OJ();MJ.code='require("ajv/dist/runtime/uri").default';VJ.default=MJ});var TJ=P((G1)=>{Object.defineProperty(G1,"__esModule",{value:!0});G1.CodeGen=G1.Name=G1.nil=G1.stringify=G1.str=G1._=G1.KeywordCxt=void 0;var qF=y4();Object.defineProperty(G1,"KeywordCxt",{enumerable:!0,get:function(){return qF.KeywordCxt}});var o1=g();Object.defineProperty(G1,"_",{enumerable:!0,get:function(){return o1._}});Object.defineProperty(G1,"str",{enumerable:!0,get:function(){return o1.str}});Object.defineProperty(G1,"stringify",{enumerable:!0,get:function(){return o1.stringify}});Object.defineProperty(G1,"nil",{enumerable:!0,get:function(){return o1.nil}});Object.defineProperty(G1,"Name",{enumerable:!0,get:function(){return o1.Name}});Object.defineProperty(G1,"CodeGen",{enumerable:!0,get:function(){return o1.CodeGen}});var OF=a6(),jJ=u4(),MF=o9(),l4=e6(),VF=g(),m4=x4(),GQ=v4(),MY=c(),NJ=$J(),ZF=ZJ(),IJ=(Q,Y)=>new RegExp(Q,Y);IJ.code="new RegExp";var NF=["removeAdditional","useDefaults","coerceTypes"],wF=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),PF={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."},bF={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},wJ=200;function jF(Q){var Y,X,W,G,$,z,J,H,A,U,K,D,L,O,M,N,Z,k,S,y,C,c0,o0,jQ,IQ;let X4=Q.strict,EQ=(Y=Q.code)===null||Y===void 0?void 0:Y.optimize,BX=EQ===!0||EQ===void 0?1:EQ||0,LX=(W=(X=Q.code)===null||X===void 0?void 0:X.regExp)!==null&&W!==void 0?W:IJ,NH=(G=Q.uriResolver)!==null&&G!==void 0?G:ZF.default;return{strictSchema:(z=($=Q.strictSchema)!==null&&$!==void 0?$:X4)!==null&&z!==void 0?z:!0,strictNumbers:(H=(J=Q.strictNumbers)!==null&&J!==void 0?J:X4)!==null&&H!==void 0?H:!0,strictTypes:(U=(A=Q.strictTypes)!==null&&A!==void 0?A:X4)!==null&&U!==void 0?U:"log",strictTuples:(D=(K=Q.strictTuples)!==null&&K!==void 0?K:X4)!==null&&D!==void 0?D:"log",strictRequired:(O=(L=Q.strictRequired)!==null&&L!==void 0?L:X4)!==null&&O!==void 0?O:!1,code:Q.code?{...Q.code,optimize:BX,regExp:LX}:{optimize:BX,regExp:LX},loopRequired:(M=Q.loopRequired)!==null&&M!==void 0?M:wJ,loopEnum:(N=Q.loopEnum)!==null&&N!==void 0?N:wJ,meta:(Z=Q.meta)!==null&&Z!==void 0?Z:!0,messages:(k=Q.messages)!==null&&k!==void 0?k:!0,inlineRefs:(S=Q.inlineRefs)!==null&&S!==void 0?S:!0,schemaId:(y=Q.schemaId)!==null&&y!==void 0?y:"$id",addUsedSchema:(C=Q.addUsedSchema)!==null&&C!==void 0?C:!0,validateSchema:(c0=Q.validateSchema)!==null&&c0!==void 0?c0:!0,validateFormats:(o0=Q.validateFormats)!==null&&o0!==void 0?o0:!0,unicodeRegExp:(jQ=Q.unicodeRegExp)!==null&&jQ!==void 0?jQ:!0,int32range:(IQ=Q.int32range)!==null&&IQ!==void 0?IQ:!0,uriResolver:NH}}class $Q{constructor(Q={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,Q=this.opts={...Q,...jF(Q)};let{es5:Y,lines:X}=this.opts.code;this.scope=new VF.ValueScope({scope:{},prefixes:wF,es5:Y,lines:X}),this.logger=CF(Q.logger);let W=Q.validateFormats;if(Q.validateFormats=!1,this.RULES=(0,MF.getRules)(),PJ.call(this,PF,Q,"NOT SUPPORTED"),PJ.call(this,bF,Q,"DEPRECATED","warn"),this._metaOpts=SF.call(this),Q.formats)EF.call(this);if(this._addVocabularies(),this._addDefaultMetaSchema(),Q.keywords)TF.call(this,Q.keywords);if(typeof Q.meta=="object")this.addMetaSchema(Q.meta);IF.call(this),Q.validateFormats=W}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:Q,meta:Y,schemaId:X}=this.opts,W=NJ;if(X==="id")W={...NJ},W.id=W.$id,delete W.$id;if(Y&&Q)this.addMetaSchema(W,W[X],!1)}defaultMeta(){let{meta:Q,schemaId:Y}=this.opts;return this.opts.defaultMeta=typeof Q=="object"?Q[Y]||Q:void 0}validate(Q,Y){let X;if(typeof Q=="string"){if(X=this.getSchema(Q),!X)throw Error(`no schema with key or ref "${Q}"`)}else X=this.compile(Q);let W=X(Y);if(!("$async"in X))this.errors=X.errors;return W}compile(Q,Y){let X=this._addSchema(Q,Y);return X.validate||this._compileSchemaEnv(X)}compileAsync(Q,Y){if(typeof this.opts.loadSchema!="function")throw Error("options.loadSchema should be a function");let{loadSchema:X}=this.opts;return W.call(this,Q,Y);async function W(A,U){await G.call(this,A.$schema);let K=this._addSchema(A,U);return K.validate||$.call(this,K)}async function G(A){if(A&&!this.getSchema(A))await W.call(this,{$ref:A},!0)}async function $(A){try{return this._compileSchemaEnv(A)}catch(U){if(!(U instanceof jJ.default))throw U;return z.call(this,U),await J.call(this,U.missingSchema),$.call(this,A)}}function z({missingSchema:A,missingRef:U}){if(this.refs[A])throw Error(`AnySchema ${A} is loaded but ${U} cannot be resolved`)}async function J(A){let U=await H.call(this,A);if(!this.refs[A])await G.call(this,U.$schema);if(!this.refs[A])this.addSchema(U,A,Y)}async function H(A){let U=this._loading[A];if(U)return U;try{return await(this._loading[A]=X(A))}finally{delete this._loading[A]}}}addSchema(Q,Y,X,W=this.opts.validateSchema){if(Array.isArray(Q)){for(let $ of Q)this.addSchema($,void 0,X,W);return this}let G;if(typeof Q==="object"){let{schemaId:$}=this.opts;if(G=Q[$],G!==void 0&&typeof G!="string")throw Error(`schema ${$} must be string`)}return Y=(0,m4.normalizeId)(Y||G),this._checkUnique(Y),this.schemas[Y]=this._addSchema(Q,X,Y,W,!0),this}addMetaSchema(Q,Y,X=this.opts.validateSchema){return this.addSchema(Q,Y,!0,X),this}validateSchema(Q,Y){if(typeof Q=="boolean")return!0;let X;if(X=Q.$schema,X!==void 0&&typeof X!="string")throw Error("$schema must be a string");if(X=X||this.opts.defaultMeta||this.defaultMeta(),!X)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let W=this.validate(X,Q);if(!W&&Y){let G="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(G);else throw Error(G)}return W}getSchema(Q){let Y;while(typeof(Y=bJ.call(this,Q))=="string")Q=Y;if(Y===void 0){let{schemaId:X}=this.opts,W=new l4.SchemaEnv({schema:{},schemaId:X});if(Y=l4.resolveSchema.call(this,W,Q),!Y)return;this.refs[Q]=Y}return Y.validate||this._compileSchemaEnv(Y)}removeSchema(Q){if(Q instanceof RegExp)return this._removeAllSchemas(this.schemas,Q),this._removeAllSchemas(this.refs,Q),this;switch(typeof Q){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let Y=bJ.call(this,Q);if(typeof Y=="object")this._cache.delete(Y.schema);return delete this.schemas[Q],delete this.refs[Q],this}case"object":{let Y=Q;this._cache.delete(Y);let X=Q[this.opts.schemaId];if(X)X=(0,m4.normalizeId)(X),delete this.schemas[X],delete this.refs[X];return this}default:throw Error("ajv.removeSchema: invalid parameter")}}addVocabulary(Q){for(let Y of Q)this.addKeyword(Y);return this}addKeyword(Q,Y){let X;if(typeof Q=="string"){if(X=Q,typeof Y=="object")this.logger.warn("these parameters are deprecated, see docs for addKeyword"),Y.keyword=X}else if(typeof Q=="object"&&Y===void 0){if(Y=Q,X=Y.keyword,Array.isArray(X)&&!X.length)throw Error("addKeywords: keyword must be string or non-empty array")}else throw Error("invalid addKeywords parameters");if(vF.call(this,X,Y),!Y)return(0,MY.eachItem)(X,(G)=>OY.call(this,G)),this;_F.call(this,Y);let W={...Y,type:(0,GQ.getJSONTypes)(Y.type),schemaType:(0,GQ.getJSONTypes)(Y.schemaType)};return(0,MY.eachItem)(X,W.type.length===0?(G)=>OY.call(this,G,W):(G)=>W.type.forEach(($)=>OY.call(this,G,W,$))),this}getKeyword(Q){let Y=this.RULES.all[Q];return typeof Y=="object"?Y.definition:!!Y}removeKeyword(Q){let{RULES:Y}=this;delete Y.keywords[Q],delete Y.all[Q];for(let X of Y.rules){let W=X.rules.findIndex((G)=>G.keyword===Q);if(W>=0)X.rules.splice(W,1)}return this}addFormat(Q,Y){if(typeof Y=="string")Y=new RegExp(Y);return this.formats[Q]=Y,this}errorsText(Q=this.errors,{separator:Y=", ",dataVar:X="data"}={}){if(!Q||Q.length===0)return"No errors";return Q.map((W)=>`${X}${W.instancePath} ${W.message}`).reduce((W,G)=>W+Y+G)}$dataMetaSchema(Q,Y){let X=this.RULES.all;Q=JSON.parse(JSON.stringify(Q));for(let W of Y){let G=W.split("/").slice(1),$=Q;for(let z of G)$=$[z];for(let z in X){let J=X[z];if(typeof J!="object")continue;let{$data:H}=J.definition,A=$[z];if(H&&A)$[z]=EJ(A)}}return Q}_removeAllSchemas(Q,Y){for(let X in Q){let W=Q[X];if(!Y||Y.test(X)){if(typeof W=="string")delete Q[X];else if(W&&!W.meta)this._cache.delete(W.schema),delete Q[X]}}}_addSchema(Q,Y,X,W=this.opts.validateSchema,G=this.opts.addUsedSchema){let $,{schemaId:z}=this.opts;if(typeof Q=="object")$=Q[z];else if(this.opts.jtd)throw Error("schema must be object");else if(typeof Q!="boolean")throw Error("schema must be object or boolean");let J=this._cache.get(Q);if(J!==void 0)return J;X=(0,m4.normalizeId)($||X);let H=m4.getSchemaRefs.call(this,Q,X);if(J=new l4.SchemaEnv({schema:Q,schemaId:z,meta:Y,baseId:X,localRefs:H}),this._cache.set(J.schema,J),G&&!X.startsWith("#")){if(X)this._checkUnique(X);this.refs[X]=J}if(W)this.validateSchema(Q,!0);return J}_checkUnique(Q){if(this.schemas[Q]||this.refs[Q])throw Error(`schema with key or id "${Q}" already exists`)}_compileSchemaEnv(Q){if(Q.meta)this._compileMetaSchema(Q);else l4.compileSchema.call(this,Q);if(!Q.validate)throw Error("ajv implementation error");return Q.validate}_compileMetaSchema(Q){let Y=this.opts;this.opts=this._metaOpts;try{l4.compileSchema.call(this,Q)}finally{this.opts=Y}}}$Q.ValidationError=OF.default;$Q.MissingRefError=jJ.default;G1.default=$Q;function PJ(Q,Y,X,W="error"){for(let G in Q){let $=G;if($ in Y)this.logger[W](`${X}: option ${G}. ${Q[$]}`)}}function bJ(Q){return Q=(0,m4.normalizeId)(Q),this.schemas[Q]||this.refs[Q]}function IF(){let Q=this.opts.schemas;if(!Q)return;if(Array.isArray(Q))this.addSchema(Q);else for(let Y in Q)this.addSchema(Q[Y],Y)}function EF(){for(let Q in this.opts.formats){let Y=this.opts.formats[Q];if(Y)this.addFormat(Q,Y)}}function TF(Q){if(Array.isArray(Q)){this.addVocabulary(Q);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let Y in Q){let X=Q[Y];if(!X.keyword)X.keyword=Y;this.addKeyword(X)}}function SF(){let Q={...this.opts};for(let Y of NF)delete Q[Y];return Q}var RF={log(){},warn(){},error(){}};function CF(Q){if(Q===!1)return RF;if(Q===void 0)return console;if(Q.log&&Q.warn&&Q.error)return Q;throw Error("logger must implement log, warn and error methods")}var kF=/^[a-z_$][a-z0-9_$:-]*$/i;function vF(Q,Y){let{RULES:X}=this;if((0,MY.eachItem)(Q,(W)=>{if(X.keywords[W])throw Error(`Keyword ${W} is already defined`);if(!kF.test(W))throw Error(`Keyword ${W} has invalid name`)}),!Y)return;if(Y.$data&&!(("code"in Y)||("validate"in Y)))throw Error('$data keyword must have "code" or "validate" function')}function OY(Q,Y,X){var W;let G=Y===null||Y===void 0?void 0:Y.post;if(X&&G)throw Error('keyword with "post" flag cannot have "type"');let{RULES:$}=this,z=G?$.post:$.rules.find(({type:H})=>H===X);if(!z)z={type:X,rules:[]},$.rules.push(z);if($.keywords[Q]=!0,!Y)return;let J={keyword:Q,definition:{...Y,type:(0,GQ.getJSONTypes)(Y.type),schemaType:(0,GQ.getJSONTypes)(Y.schemaType)}};if(Y.before)xF.call(this,z,J,Y.before);else z.rules.push(J);$.all[Q]=J,(W=Y.implements)===null||W===void 0||W.forEach((H)=>this.addKeyword(H))}function xF(Q,Y,X){let W=Q.rules.findIndex((G)=>G.keyword===X);if(W>=0)Q.rules.splice(W,0,Y);else Q.rules.push(Y),this.logger.warn(`rule ${X} is not defined`)}function _F(Q){let{metaSchema:Y}=Q;if(Y===void 0)return;if(Q.$data&&this.opts.$data)Y=EJ(Y);Q.validateSchema=this.compile(Y,!0)}var gF={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function EJ(Q){return{anyOf:[Q,gF]}}});var RJ=P((SJ)=>{Object.defineProperty(SJ,"__esModule",{value:!0});var hF={keyword:"id",code(){throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};SJ.default=hF});var gJ=P((xJ)=>{Object.defineProperty(xJ,"__esModule",{value:!0});xJ.callRef=xJ.getValidate=void 0;var lF=u4(),CJ=C0(),w0=g(),t1=Y1(),kJ=e6(),zQ=c(),mF={keyword:"$ref",schemaType:"string",code(Q){let{gen:Y,schema:X,it:W}=Q,{baseId:G,schemaEnv:$,validateName:z,opts:J,self:H}=W,{root:A}=$;if((X==="#"||X==="#/")&&G===A.baseId)return K();let U=kJ.resolveRef.call(H,A,G,X);if(U===void 0)throw new lF.default(W.opts.uriResolver,G,X);if(U instanceof kJ.SchemaEnv)return D(U);return L(U);function K(){if($===A)return JQ(Q,z,$,$.$async);let O=Y.scopeValue("root",{ref:A});return JQ(Q,w0._`${O}.validate`,A,A.$async)}function D(O){let M=vJ(Q,O);JQ(Q,M,O,O.$async)}function L(O){let M=Y.scopeValue("schema",J.code.source===!0?{ref:O,code:(0,w0.stringify)(O)}:{ref:O}),N=Y.name("valid"),Z=Q.subschema({schema:O,dataTypes:[],schemaPath:w0.nil,topSchemaRef:M,errSchemaPath:X},N);Q.mergeEvaluated(Z),Q.ok(N)}}};function vJ(Q,Y){let{gen:X}=Q;return Y.validate?X.scopeValue("validate",{ref:Y.validate}):w0._`${X.scopeValue("wrapper",{ref:Y})}.validate`}xJ.getValidate=vJ;function JQ(Q,Y,X,W){let{gen:G,it:$}=Q,{allErrors:z,schemaEnv:J,opts:H}=$,A=H.passContext?t1.default.this:w0.nil;if(W)U();else K();function U(){if(!J.$async)throw Error("async schema referenced by sync schema");let O=G.let("valid");G.try(()=>{if(G.code(w0._`await ${(0,CJ.callValidateCode)(Q,Y,A)}`),L(Y),!z)G.assign(O,!0)},(M)=>{if(G.if(w0._`!(${M} instanceof ${$.ValidationError})`,()=>G.throw(M)),D(M),!z)G.assign(O,!1)}),Q.ok(O)}function K(){Q.result((0,CJ.callValidateCode)(Q,Y,A),()=>L(Y),()=>D(Y))}function D(O){let M=w0._`${O}.errors`;G.assign(t1.default.vErrors,w0._`${t1.default.vErrors} === null ? ${M} : ${t1.default.vErrors}.concat(${M})`),G.assign(t1.default.errors,w0._`${t1.default.vErrors}.length`)}function L(O){var M;if(!$.opts.unevaluated)return;let N=(M=X===null||X===void 0?void 0:X.validate)===null||M===void 0?void 0:M.evaluated;if($.props!==!0)if(N&&!N.dynamicProps){if(N.props!==void 0)$.props=zQ.mergeEvaluated.props(G,N.props,$.props)}else{let Z=G.var("props",w0._`${O}.evaluated.props`);$.props=zQ.mergeEvaluated.props(G,Z,$.props,w0.Name)}if($.items!==!0)if(N&&!N.dynamicItems){if(N.items!==void 0)$.items=zQ.mergeEvaluated.items(G,N.items,$.items)}else{let Z=G.var("items",w0._`${O}.evaluated.items`);$.items=zQ.mergeEvaluated.items(G,Z,$.items,w0.Name)}}}xJ.callRef=JQ;xJ.default=mF});var uJ=P((yJ)=>{Object.defineProperty(yJ,"__esModule",{value:!0});var iF=RJ(),nF=gJ(),rF=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",iF.default,nF.default];yJ.default=rF});var fJ=P((hJ)=>{Object.defineProperty(hJ,"__esModule",{value:!0});var HQ=g(),M1=HQ.operators,AQ={maximum:{okStr:"<=",ok:M1.LTE,fail:M1.GT},minimum:{okStr:">=",ok:M1.GTE,fail:M1.LT},exclusiveMaximum:{okStr:"<",ok:M1.LT,fail:M1.GTE},exclusiveMinimum:{okStr:">",ok:M1.GT,fail:M1.LTE}},oF={message:({keyword:Q,schemaCode:Y})=>HQ.str`must be ${AQ[Q].okStr} ${Y}`,params:({keyword:Q,schemaCode:Y})=>HQ._`{comparison: ${AQ[Q].okStr}, limit: ${Y}}`},tF={keyword:Object.keys(AQ),type:"number",schemaType:"number",$data:!0,error:oF,code(Q){let{keyword:Y,data:X,schemaCode:W}=Q;Q.fail$data(HQ._`${X} ${AQ[Y].fail} ${W} || isNaN(${X})`)}};hJ.default=tF});var mJ=P((lJ)=>{Object.defineProperty(lJ,"__esModule",{value:!0});var c4=g(),sF={message:({schemaCode:Q})=>c4.str`must be multiple of ${Q}`,params:({schemaCode:Q})=>c4._`{multipleOf: ${Q}}`},eF={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:sF,code(Q){let{gen:Y,data:X,schemaCode:W,it:G}=Q,$=G.opts.multipleOfPrecision,z=Y.let("res"),J=$?c4._`Math.abs(Math.round(${z}) - ${z}) > 1e-${$}`:c4._`${z} !== parseInt(${z})`;Q.fail$data(c4._`(${W} === 0 || (${z} = ${X}/${W}, ${J}))`)}};lJ.default=eF});var iJ=P((pJ)=>{Object.defineProperty(pJ,"__esModule",{value:!0});function cJ(Q){let Y=Q.length,X=0,W=0,G;while(W<Y)if(X++,G=Q.charCodeAt(W++),G>=55296&&G<=56319&&W<Y){if(G=Q.charCodeAt(W),(G&64512)===56320)W++}return X}pJ.default=cJ;cJ.code='require("ajv/dist/runtime/ucs2length").default'});var rJ=P((nJ)=>{Object.defineProperty(nJ,"__esModule",{value:!0});var C1=g(),Xq=c(),Wq=iJ(),Gq={message({keyword:Q,schemaCode:Y}){let X=Q==="maxLength"?"more":"fewer";return C1.str`must NOT have ${X} than ${Y} characters`},params:({schemaCode:Q})=>C1._`{limit: ${Q}}`},$q={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:Gq,code(Q){let{keyword:Y,data:X,schemaCode:W,it:G}=Q,$=Y==="maxLength"?C1.operators.GT:C1.operators.LT,z=G.opts.unicode===!1?C1._`${X}.length`:C1._`${(0,Xq.useFunc)(Q.gen,Wq.default)}(${X})`;Q.fail$data(C1._`${z} ${$} ${W}`)}};nJ.default=$q});var oJ=P((dJ)=>{Object.defineProperty(dJ,"__esModule",{value:!0});var Jq=C0(),UQ=g(),Hq={message:({schemaCode:Q})=>UQ.str`must match pattern "${Q}"`,params:({schemaCode:Q})=>UQ._`{pattern: ${Q}}`},Aq={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:Hq,code(Q){let{data:Y,$data:X,schema:W,schemaCode:G,it:$}=Q,z=$.opts.unicodeRegExp?"u":"",J=X?UQ._`(new RegExp(${G}, ${z}))`:(0,Jq.usePattern)(Q,W);Q.fail$data(UQ._`!${J}.test(${Y})`)}};dJ.default=Aq});var aJ=P((tJ)=>{Object.defineProperty(tJ,"__esModule",{value:!0});var p4=g(),Kq={message({keyword:Q,schemaCode:Y}){let X=Q==="maxProperties"?"more":"fewer";return p4.str`must NOT have ${X} than ${Y} properties`},params:({schemaCode:Q})=>p4._`{limit: ${Q}}`},Dq={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:Kq,code(Q){let{keyword:Y,data:X,schemaCode:W}=Q,G=Y==="maxProperties"?p4.operators.GT:p4.operators.LT;Q.fail$data(p4._`Object.keys(${X}).length ${G} ${W}`)}};tJ.default=Dq});var eJ=P((sJ)=>{Object.defineProperty(sJ,"__esModule",{value:!0});var i4=C0(),n4=g(),Lq=c(),Fq={message:({params:{missingProperty:Q}})=>n4.str`must have required property '${Q}'`,params:({params:{missingProperty:Q}})=>n4._`{missingProperty: ${Q}}`},qq={keyword:"required",type:"object",schemaType:"array",$data:!0,error:Fq,code(Q){let{gen:Y,schema:X,schemaCode:W,data:G,$data:$,it:z}=Q,{opts:J}=z;if(!$&&X.length===0)return;let H=X.length>=J.loopRequired;if(z.allErrors)A();else U();if(J.strictRequired){let L=Q.parentSchema.properties,{definedProperties:O}=Q.it;for(let M of X)if((L===null||L===void 0?void 0:L[M])===void 0&&!O.has(M)){let N=z.schemaEnv.baseId+z.errSchemaPath,Z=`required property "${M}" is not defined at "${N}" (strictRequired)`;(0,Lq.checkStrictMode)(z,Z,z.opts.strictRequired)}}function A(){if(H||$)Q.block$data(n4.nil,K);else for(let L of X)(0,i4.checkReportMissingProp)(Q,L)}function U(){let L=Y.let("missing");if(H||$){let O=Y.let("valid",!0);Q.block$data(O,()=>D(L,O)),Q.ok(O)}else Y.if((0,i4.checkMissingProp)(Q,X,L)),(0,i4.reportMissingProp)(Q,L),Y.else()}function K(){Y.forOf("prop",W,(L)=>{Q.setParams({missingProperty:L}),Y.if((0,i4.noPropertyInData)(Y,G,L,J.ownProperties),()=>Q.error())})}function D(L,O){Q.setParams({missingProperty:L}),Y.forOf(L,W,()=>{Y.assign(O,(0,i4.propertyInData)(Y,G,L,J.ownProperties)),Y.if((0,n4.not)(O),()=>{Q.error(),Y.break()})},n4.nil)}}};sJ.default=qq});var Y7=P((Q7)=>{Object.defineProperty(Q7,"__esModule",{value:!0});var r4=g(),Mq={message({keyword:Q,schemaCode:Y}){let X=Q==="maxItems"?"more":"fewer";return r4.str`must NOT have ${X} than ${Y} items`},params:({schemaCode:Q})=>r4._`{limit: ${Q}}`},Vq={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:Mq,code(Q){let{keyword:Y,data:X,schemaCode:W}=Q,G=Y==="maxItems"?r4.operators.GT:r4.operators.LT;Q.fail$data(r4._`${X}.length ${G} ${W}`)}};Q7.default=Vq});var KQ=P((W7)=>{Object.defineProperty(W7,"__esModule",{value:!0});var X7=WY();X7.code='require("ajv/dist/runtime/equal").default';W7.default=X7});var $7=P((G7)=>{Object.defineProperty(G7,"__esModule",{value:!0});var VY=v4(),L0=g(),wq=c(),Pq=KQ(),bq={message:({params:{i:Q,j:Y}})=>L0.str`must NOT have duplicate items (items ## ${Y} and ${Q} are identical)`,params:({params:{i:Q,j:Y}})=>L0._`{i: ${Q}, j: ${Y}}`},jq={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:bq,code(Q){let{gen:Y,data:X,$data:W,schema:G,parentSchema:$,schemaCode:z,it:J}=Q;if(!W&&!G)return;let H=Y.let("valid"),A=$.items?(0,VY.getSchemaTypes)($.items):[];Q.block$data(H,U,L0._`${z} === false`),Q.ok(H);function U(){let O=Y.let("i",L0._`${X}.length`),M=Y.let("j");Q.setParams({i:O,j:M}),Y.assign(H,!0),Y.if(L0._`${O} > 1`,()=>(K()?D:L)(O,M))}function K(){return A.length>0&&!A.some((O)=>O==="object"||O==="array")}function D(O,M){let N=Y.name("item"),Z=(0,VY.checkDataTypes)(A,N,J.opts.strictNumbers,VY.DataType.Wrong),k=Y.const("indices",L0._`{}`);Y.for(L0._`;${O}--;`,()=>{if(Y.let(N,L0._`${X}[${O}]`),Y.if(Z,L0._`continue`),A.length>1)Y.if(L0._`typeof ${N} == "string"`,L0._`${N} += "_"`);Y.if(L0._`typeof ${k}[${N}] == "number"`,()=>{Y.assign(M,L0._`${k}[${N}]`),Q.error(),Y.assign(H,!1).break()}).code(L0._`${k}[${N}] = ${O}`)})}function L(O,M){let N=(0,wq.useFunc)(Y,Pq.default),Z=Y.name("outer");Y.label(Z).for(L0._`;${O}--;`,()=>Y.for(L0._`${M} = ${O}; ${M}--;`,()=>Y.if(L0._`${N}(${X}[${O}], ${X}[${M}])`,()=>{Q.error(),Y.assign(H,!1).break(Z)})))}}};G7.default=jq});var J7=P((z7)=>{Object.defineProperty(z7,"__esModule",{value:!0});var ZY=g(),Eq=c(),Tq=KQ(),Sq={message:"must be equal to constant",params:({schemaCode:Q})=>ZY._`{allowedValue: ${Q}}`},Rq={keyword:"const",$data:!0,error:Sq,code(Q){let{gen:Y,data:X,$data:W,schemaCode:G,schema:$}=Q;if(W||$&&typeof $=="object")Q.fail$data(ZY._`!${(0,Eq.useFunc)(Y,Tq.default)}(${X}, ${G})`);else Q.fail(ZY._`${$} !== ${X}`)}};z7.default=Rq});var A7=P((H7)=>{Object.defineProperty(H7,"__esModule",{value:!0});var d4=g(),kq=c(),vq=KQ(),xq={message:"must be equal to one of the allowed values",params:({schemaCode:Q})=>d4._`{allowedValues: ${Q}}`},_q={keyword:"enum",schemaType:"array",$data:!0,error:xq,code(Q){let{gen:Y,data:X,$data:W,schema:G,schemaCode:$,it:z}=Q;if(!W&&G.length===0)throw Error("enum must have non-empty array");let J=G.length>=z.opts.loopEnum,H,A=()=>H!==null&&H!==void 0?H:H=(0,kq.useFunc)(Y,vq.default),U;if(J||W)U=Y.let("valid"),Q.block$data(U,K);else{if(!Array.isArray(G))throw Error("ajv implementation error");let L=Y.const("vSchema",$);U=(0,d4.or)(...G.map((O,M)=>D(L,M)))}Q.pass(U);function K(){Y.assign(U,!1),Y.forOf("v",$,(L)=>Y.if(d4._`${A()}(${X}, ${L})`,()=>Y.assign(U,!0).break()))}function D(L,O){let M=G[O];return typeof M==="object"&&M!==null?d4._`${A()}(${X}, ${L}[${O}])`:d4._`${X} === ${M}`}}};H7.default=_q});var K7=P((U7)=>{Object.defineProperty(U7,"__esModule",{value:!0});var yq=fJ(),uq=mJ(),hq=rJ(),fq=oJ(),lq=aJ(),mq=eJ(),cq=Y7(),pq=$7(),iq=J7(),nq=A7(),rq=[yq.default,uq.default,hq.default,fq.default,lq.default,mq.default,cq.default,pq.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},iq.default,nq.default];U7.default=rq});var wY=P((B7)=>{Object.defineProperty(B7,"__esModule",{value:!0});B7.validateAdditionalItems=void 0;var k1=g(),NY=c(),oq={message:({params:{len:Q}})=>k1.str`must NOT have more than ${Q} items`,params:({params:{len:Q}})=>k1._`{limit: ${Q}}`},tq={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:oq,code(Q){let{parentSchema:Y,it:X}=Q,{items:W}=Y;if(!Array.isArray(W)){(0,NY.checkStrictMode)(X,'"additionalItems" is ignored when "items" is not an array of schemas');return}D7(Q,W)}};function D7(Q,Y){let{gen:X,schema:W,data:G,keyword:$,it:z}=Q;z.items=!0;let J=X.const("len",k1._`${G}.length`);if(W===!1)Q.setParams({len:Y.length}),Q.pass(k1._`${J} <= ${Y.length}`);else if(typeof W=="object"&&!(0,NY.alwaysValidSchema)(z,W)){let A=X.var("valid",k1._`${J} <= ${Y.length}`);X.if((0,k1.not)(A),()=>H(A)),Q.ok(A)}function H(A){X.forRange("i",Y.length,J,(U)=>{if(Q.subschema({keyword:$,dataProp:U,dataPropType:NY.Type.Num},A),!z.allErrors)X.if((0,k1.not)(A),()=>X.break())})}}B7.validateAdditionalItems=D7;B7.default=tq});var PY=P((O7)=>{Object.defineProperty(O7,"__esModule",{value:!0});O7.validateTuple=void 0;var F7=g(),DQ=c(),sq=C0(),eq={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(Q){let{schema:Y,it:X}=Q;if(Array.isArray(Y))return q7(Q,"additionalItems",Y);if(X.items=!0,(0,DQ.alwaysValidSchema)(X,Y))return;Q.ok((0,sq.validateArray)(Q))}};function q7(Q,Y,X=Q.schema){let{gen:W,parentSchema:G,data:$,keyword:z,it:J}=Q;if(U(G),J.opts.unevaluated&&X.length&&J.items!==!0)J.items=DQ.mergeEvaluated.items(W,X.length,J.items);let H=W.name("valid"),A=W.const("len",F7._`${$}.length`);X.forEach((K,D)=>{if((0,DQ.alwaysValidSchema)(J,K))return;W.if(F7._`${A} > ${D}`,()=>Q.subschema({keyword:z,schemaProp:D,dataProp:D},H)),Q.ok(H)});function U(K){let{opts:D,errSchemaPath:L}=J,O=X.length,M=O===K.minItems&&(O===K.maxItems||K[Y]===!1);if(D.strictTuples&&!M){let N=`"${z}" is ${O}-tuple, but minItems or maxItems/${Y} are not specified or different at path "${L}"`;(0,DQ.checkStrictMode)(J,N,D.strictTuples)}}}O7.validateTuple=q7;O7.default=eq});var Z7=P((V7)=>{Object.defineProperty(V7,"__esModule",{value:!0});var YO=PY(),XO={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:(Q)=>(0,YO.validateTuple)(Q,"items")};V7.default=XO});var P7=P((w7)=>{Object.defineProperty(w7,"__esModule",{value:!0});var N7=g(),GO=c(),$O=C0(),zO=wY(),JO={message:({params:{len:Q}})=>N7.str`must NOT have more than ${Q} items`,params:({params:{len:Q}})=>N7._`{limit: ${Q}}`},HO={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:JO,code(Q){let{schema:Y,parentSchema:X,it:W}=Q,{prefixItems:G}=X;if(W.items=!0,(0,GO.alwaysValidSchema)(W,Y))return;if(G)(0,zO.validateAdditionalItems)(Q,G);else Q.ok((0,$O.validateArray)(Q))}};w7.default=HO});var j7=P((b7)=>{Object.defineProperty(b7,"__esModule",{value:!0});var k0=g(),BQ=c(),UO={message:({params:{min:Q,max:Y}})=>Y===void 0?k0.str`must contain at least ${Q} valid item(s)`:k0.str`must contain at least ${Q} and no more than ${Y} valid item(s)`,params:({params:{min:Q,max:Y}})=>Y===void 0?k0._`{minContains: ${Q}}`:k0._`{minContains: ${Q}, maxContains: ${Y}}`},KO={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:UO,code(Q){let{gen:Y,schema:X,parentSchema:W,data:G,it:$}=Q,z,J,{minContains:H,maxContains:A}=W;if($.opts.next)z=H===void 0?1:H,J=A;else z=1;let U=Y.const("len",k0._`${G}.length`);if(Q.setParams({min:z,max:J}),J===void 0&&z===0){(0,BQ.checkStrictMode)($,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(J!==void 0&&z>J){(0,BQ.checkStrictMode)($,'"minContains" > "maxContains" is always invalid'),Q.fail();return}if((0,BQ.alwaysValidSchema)($,X)){let M=k0._`${U} >= ${z}`;if(J!==void 0)M=k0._`${M} && ${U} <= ${J}`;Q.pass(M);return}$.items=!0;let K=Y.name("valid");if(J===void 0&&z===1)L(K,()=>Y.if(K,()=>Y.break()));else if(z===0){if(Y.let(K,!0),J!==void 0)Y.if(k0._`${G}.length > 0`,D)}else Y.let(K,!1),D();Q.result(K,()=>Q.reset());function D(){let M=Y.name("_valid"),N=Y.let("count",0);L(M,()=>Y.if(M,()=>O(N)))}function L(M,N){Y.forRange("i",0,U,(Z)=>{Q.subschema({keyword:"contains",dataProp:Z,dataPropType:BQ.Type.Num,compositeRule:!0},M),N()})}function O(M){if(Y.code(k0._`${M}++`),J===void 0)Y.if(k0._`${M} >= ${z}`,()=>Y.assign(K,!0).break());else if(Y.if(k0._`${M} > ${J}`,()=>Y.assign(K,!1).break()),z===1)Y.assign(K,!0);else Y.if(k0._`${M} >= ${z}`,()=>Y.assign(K,!0))}}};b7.default=KO});var C7=P((T7)=>{Object.defineProperty(T7,"__esModule",{value:!0});T7.validateSchemaDeps=T7.validatePropertyDeps=T7.error=void 0;var bY=g(),BO=c(),o4=C0();T7.error={message:({params:{property:Q,depsCount:Y,deps:X}})=>{let W=Y===1?"property":"properties";return bY.str`must have ${W} ${X} when property ${Q} is present`},params:({params:{property:Q,depsCount:Y,deps:X,missingProperty:W}})=>bY._`{property: ${Q},
7
7
  missingProperty: ${W},
8
8
  depsCount: ${Y},
9
- deps: ${X}}`};var HO={keyword:"dependencies",type:"object",schemaType:"object",error:I7.error,code(Q){let[Y,X]=AO(Q);b7(Q,Y),j7(Q,X)}};function AO({schema:Q}){let Y={},X={};for(let W in Q){if(W==="__proto__")continue;let G=Array.isArray(Q[W])?Y:X;G[W]=Q[W]}return[Y,X]}function b7(Q,Y=Q.schema){let{gen:X,data:W,it:G}=Q;if(Object.keys(Y).length===0)return;let $=X.let("missing");for(let z in Y){let J=Y[z];if(J.length===0)continue;let H=(0,o4.propertyInData)(X,W,z,G.opts.ownProperties);if(Q.setParams({property:z,depsCount:J.length,deps:J.join(", ")}),G.allErrors)X.if(H,()=>{for(let A of J)(0,o4.checkReportMissingProp)(Q,A)});else X.if(bY._`${H} && (${(0,o4.checkMissingProp)(Q,J,$)})`),(0,o4.reportMissingProp)(Q,$),X.else()}}I7.validatePropertyDeps=b7;function j7(Q,Y=Q.schema){let{gen:X,data:W,keyword:G,it:$}=Q,z=X.name("valid");for(let J in Y){if((0,JO.alwaysValidSchema)($,Y[J]))continue;X.if((0,o4.propertyInData)(X,W,J,$.opts.ownProperties),()=>{let H=Q.subschema({keyword:G,schemaProp:J},z);Q.mergeValidEvaluated(H,z)},()=>X.var(z,!0)),Q.ok(z)}}I7.validateSchemaDeps=j7;I7.default=HO});var k7=P((C7)=>{Object.defineProperty(C7,"__esModule",{value:!0});var R7=g(),DO=c(),BO={message:"property name must be valid",params:({params:Q})=>R7._`{propertyName: ${Q.propertyName}}`},LO={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:BO,code(Q){let{gen:Y,schema:X,data:W,it:G}=Q;if((0,DO.alwaysValidSchema)(G,X))return;let $=Y.name("valid");Y.forIn("key",W,(z)=>{Q.setParams({propertyName:z}),Q.subschema({keyword:"propertyNames",data:z,dataTypes:["string"],propertyName:z,compositeRule:!0},$),Y.if((0,R7.not)($),()=>{if(Q.error(!0),!G.allErrors)Y.break()})}),Q.ok($)}};C7.default=LO});var jY=P((v7)=>{Object.defineProperty(v7,"__esModule",{value:!0});var LQ=C0(),h0=g(),qO=Y1(),FQ=c(),OO={message:"must NOT have additional properties",params:({params:Q})=>h0._`{additionalProperty: ${Q.additionalProperty}}`},MO={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:OO,code(Q){let{gen:Y,schema:X,parentSchema:W,data:G,errsCount:$,it:z}=Q;if(!$)throw Error("ajv implementation error");let{allErrors:J,opts:H}=z;if(z.props=!0,H.removeAdditional!=="all"&&(0,FQ.alwaysValidSchema)(z,X))return;let A=(0,LQ.allSchemaProperties)(W.properties),U=(0,LQ.allSchemaProperties)(W.patternProperties);K(),Q.ok(h0._`${$} === ${qO.default.errors}`);function K(){Y.forIn("key",G,(N)=>{if(!A.length&&!U.length)O(N);else Y.if(D(N),()=>O(N))})}function D(N){let Z;if(A.length>8){let k=(0,FQ.schemaRefOrVal)(z,W.properties,"properties");Z=(0,LQ.isOwnProperty)(Y,k,N)}else if(A.length)Z=(0,h0.or)(...A.map((k)=>h0._`${N} === ${k}`));else Z=h0.nil;if(U.length)Z=(0,h0.or)(Z,...U.map((k)=>h0._`${(0,LQ.usePattern)(Q,k)}.test(${N})`));return(0,h0.not)(Z)}function L(N){Y.code(h0._`delete ${G}[${N}]`)}function O(N){if(H.removeAdditional==="all"||H.removeAdditional&&X===!1){L(N);return}if(X===!1){if(Q.setParams({additionalProperty:N}),Q.error(),!J)Y.break();return}if(typeof X=="object"&&!(0,FQ.alwaysValidSchema)(z,X)){let Z=Y.name("valid");if(H.removeAdditional==="failing")M(N,Z,!1),Y.if((0,h0.not)(Z),()=>{Q.reset(),L(N)});else if(M(N,Z),!J)Y.if((0,h0.not)(Z),()=>Y.break())}}function M(N,Z,k){let S={keyword:"additionalProperties",dataProp:N,dataPropType:FQ.Type.Str};if(k===!1)Object.assign(S,{compositeRule:!0,createErrors:!1,allErrors:!1});Q.subschema(S,Z)}}};v7.default=MO});var y7=P((g7)=>{Object.defineProperty(g7,"__esModule",{value:!0});var ZO=y4(),x7=C0(),IY=c(),_7=jY(),NO={keyword:"properties",type:"object",schemaType:"object",code(Q){let{gen:Y,schema:X,parentSchema:W,data:G,it:$}=Q;if($.opts.removeAdditional==="all"&&W.additionalProperties===void 0)_7.default.code(new ZO.KeywordCxt($,_7.default,"additionalProperties"));let z=(0,x7.allSchemaProperties)(X);for(let K of z)$.definedProperties.add(K);if($.opts.unevaluated&&z.length&&$.props!==!0)$.props=IY.mergeEvaluated.props(Y,(0,IY.toHash)(z),$.props);let J=z.filter((K)=>!(0,IY.alwaysValidSchema)($,X[K]));if(J.length===0)return;let H=Y.name("valid");for(let K of J){if(A(K))U(K);else{if(Y.if((0,x7.propertyInData)(Y,G,K,$.opts.ownProperties)),U(K),!$.allErrors)Y.else().var(H,!0);Y.endIf()}Q.it.definedProperties.add(K),Q.ok(H)}function A(K){return $.opts.useDefaults&&!$.compositeRule&&X[K].default!==void 0}function U(K){Q.subschema({keyword:"properties",schemaProp:K,dataProp:K},H)}}};g7.default=NO});var m7=P((l7)=>{Object.defineProperty(l7,"__esModule",{value:!0});var u7=C0(),qQ=g(),h7=c(),f7=c(),PO={keyword:"patternProperties",type:"object",schemaType:"object",code(Q){let{gen:Y,schema:X,data:W,parentSchema:G,it:$}=Q,{opts:z}=$,J=(0,u7.allSchemaProperties)(X),H=J.filter((M)=>(0,h7.alwaysValidSchema)($,X[M]));if(J.length===0||H.length===J.length&&(!$.opts.unevaluated||$.props===!0))return;let A=z.strictSchema&&!z.allowMatchingProperties&&G.properties,U=Y.name("valid");if($.props!==!0&&!($.props instanceof qQ.Name))$.props=(0,f7.evaluatedPropsToName)(Y,$.props);let{props:K}=$;D();function D(){for(let M of J){if(A)L(M);if($.allErrors)O(M);else Y.var(U,!0),O(M),Y.if(U)}}function L(M){for(let N in A)if(new RegExp(M).test(N))(0,h7.checkStrictMode)($,`property ${N} matches pattern ${M} (use allowMatchingProperties)`)}function O(M){Y.forIn("key",W,(N)=>{Y.if(qQ._`${(0,u7.usePattern)(Q,M)}.test(${N})`,()=>{let Z=H.includes(M);if(!Z)Q.subschema({keyword:"patternProperties",schemaProp:M,dataProp:N,dataPropType:f7.Type.Str},U);if($.opts.unevaluated&&K!==!0)Y.assign(qQ._`${K}[${N}]`,!0);else if(!Z&&!$.allErrors)Y.if((0,qQ.not)(U),()=>Y.break())})})}}};l7.default=PO});var p7=P((c7)=>{Object.defineProperty(c7,"__esModule",{value:!0});var jO=c(),IO={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(Q){let{gen:Y,schema:X,it:W}=Q;if((0,jO.alwaysValidSchema)(W,X)){Q.fail();return}let G=Y.name("valid");Q.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},G),Q.failResult(G,()=>Q.reset(),()=>Q.error())},error:{message:"must NOT be valid"}};c7.default=IO});var n7=P((i7)=>{Object.defineProperty(i7,"__esModule",{value:!0});var TO=C0(),SO={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:TO.validateUnion,error:{message:"must match a schema in anyOf"}};i7.default=SO});var d7=P((r7)=>{Object.defineProperty(r7,"__esModule",{value:!0});var OQ=g(),CO=c(),kO={message:"must match exactly one schema in oneOf",params:({params:Q})=>OQ._`{passingSchemas: ${Q.passing}}`},vO={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:kO,code(Q){let{gen:Y,schema:X,parentSchema:W,it:G}=Q;if(!Array.isArray(X))throw Error("ajv implementation error");if(G.opts.discriminator&&W.discriminator)return;let $=X,z=Y.let("valid",!1),J=Y.let("passing",null),H=Y.name("_valid");Q.setParams({passing:J}),Y.block(A),Q.result(z,()=>Q.reset(),()=>Q.error(!0));function A(){$.forEach((U,K)=>{let D;if((0,CO.alwaysValidSchema)(G,U))Y.var(H,!0);else D=Q.subschema({keyword:"oneOf",schemaProp:K,compositeRule:!0},H);if(K>0)Y.if(OQ._`${H} && ${z}`).assign(z,!1).assign(J,OQ._`[${J}, ${K}]`).else();Y.if(H,()=>{if(Y.assign(z,!0),Y.assign(J,K),D)Q.mergeEvaluated(D,OQ.Name)})})}}};r7.default=vO});var t7=P((o7)=>{Object.defineProperty(o7,"__esModule",{value:!0});var _O=c(),gO={keyword:"allOf",schemaType:"array",code(Q){let{gen:Y,schema:X,it:W}=Q;if(!Array.isArray(X))throw Error("ajv implementation error");let G=Y.name("valid");X.forEach(($,z)=>{if((0,_O.alwaysValidSchema)(W,$))return;let J=Q.subschema({keyword:"allOf",schemaProp:z},G);Q.ok(G),Q.mergeEvaluated(J)})}};o7.default=gO});var Q5=P((e7)=>{Object.defineProperty(e7,"__esModule",{value:!0});var MQ=g(),s7=c(),uO={message:({params:Q})=>MQ.str`must match "${Q.ifClause}" schema`,params:({params:Q})=>MQ._`{failingKeyword: ${Q.ifClause}}`},hO={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:uO,code(Q){let{gen:Y,parentSchema:X,it:W}=Q;if(X.then===void 0&&X.else===void 0)(0,s7.checkStrictMode)(W,'"if" without "then" and "else" is ignored');let G=a7(W,"then"),$=a7(W,"else");if(!G&&!$)return;let z=Y.let("valid",!0),J=Y.name("_valid");if(H(),Q.reset(),G&&$){let U=Y.let("ifClause");Q.setParams({ifClause:U}),Y.if(J,A("then",U),A("else",U))}else if(G)Y.if(J,A("then"));else Y.if((0,MQ.not)(J),A("else"));Q.pass(z,()=>Q.error(!0));function H(){let U=Q.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},J);Q.mergeEvaluated(U)}function A(U,K){return()=>{let D=Q.subschema({keyword:U},J);if(Y.assign(z,J),Q.mergeValidEvaluated(D,z),K)Y.assign(K,MQ._`${U}`);else Q.setParams({ifClause:U})}}}};function a7(Q,Y){let X=Q.schema[Y];return X!==void 0&&!(0,s7.alwaysValidSchema)(Q,X)}e7.default=hO});var X5=P((Y5)=>{Object.defineProperty(Y5,"__esModule",{value:!0});var lO=c(),mO={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:Q,parentSchema:Y,it:X}){if(Y.if===void 0)(0,lO.checkStrictMode)(X,`"${Q}" without "if" is ignored`)}};Y5.default=mO});var G5=P((W5)=>{Object.defineProperty(W5,"__esModule",{value:!0});var pO=wY(),iO=M7(),nO=PY(),rO=N7(),dO=P7(),oO=S7(),tO=k7(),aO=jY(),sO=y7(),eO=m7(),QM=p7(),YM=n7(),XM=d7(),WM=t7(),GM=Q5(),$M=X5();function zM(Q=!1){let Y=[QM.default,YM.default,XM.default,WM.default,GM.default,$M.default,tO.default,aO.default,oO.default,sO.default,eO.default];if(Q)Y.push(iO.default,rO.default);else Y.push(pO.default,nO.default);return Y.push(dO.default),Y}W5.default=zM});var z5=P(($5)=>{Object.defineProperty($5,"__esModule",{value:!0});var G0=g(),HM={message:({schemaCode:Q})=>G0.str`must match format "${Q}"`,params:({schemaCode:Q})=>G0._`{format: ${Q}}`},AM={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:HM,code(Q,Y){let{gen:X,data:W,$data:G,schema:$,schemaCode:z,it:J}=Q,{opts:H,errSchemaPath:A,schemaEnv:U,self:K}=J;if(!H.validateFormats)return;if(G)D();else L();function D(){let O=X.scopeValue("formats",{ref:K.formats,code:H.code.formats}),M=X.const("fDef",G0._`${O}[${z}]`),N=X.let("fType"),Z=X.let("format");X.if(G0._`typeof ${M} == "object" && !(${M} instanceof RegExp)`,()=>X.assign(N,G0._`${M}.type || "string"`).assign(Z,G0._`${M}.validate`),()=>X.assign(N,G0._`"string"`).assign(Z,M)),Q.fail$data((0,G0.or)(k(),S()));function k(){if(H.strictSchema===!1)return G0.nil;return G0._`${z} && !${Z}`}function S(){let y=U.$async?G0._`(${M}.async ? await ${Z}(${W}) : ${Z}(${W}))`:G0._`${Z}(${W})`,C=G0._`(typeof ${Z} == "function" ? ${y} : ${Z}.test(${W}))`;return G0._`${Z} && ${Z} !== true && ${N} === ${Y} && !${C}`}}function L(){let O=K.formats[$];if(!O){k();return}if(O===!0)return;let[M,N,Z]=S(O);if(M===Y)Q.pass(y());function k(){if(H.strictSchema===!1){K.logger.warn(C());return}throw Error(C());function C(){return`unknown format "${$}" ignored in schema at path "${A}"`}}function S(C){let c0=C instanceof RegExp?(0,G0.regexpCode)(C):H.code.formats?G0._`${H.code.formats}${(0,G0.getProperty)($)}`:void 0,o0=X.scopeValue("formats",{key:$,ref:C,code:c0});if(typeof C=="object"&&!(C instanceof RegExp))return[C.type||"string",C.validate,G0._`${o0}.validate`];return["string",C,o0]}function y(){if(typeof O=="object"&&!(O instanceof RegExp)&&O.async){if(!U.$async)throw Error("async format in sync schema");return G0._`await ${Z}(${W})`}return typeof N=="function"?G0._`${Z}(${W})`:G0._`${Z}.test(${W})`}}}};$5.default=AM});var H5=P((J5)=>{Object.defineProperty(J5,"__esModule",{value:!0});var KM=z5(),DM=[KM.default];J5.default=DM});var K5=P((A5)=>{Object.defineProperty(A5,"__esModule",{value:!0});A5.contentVocabulary=A5.metadataVocabulary=void 0;A5.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];A5.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var L5=P((B5)=>{Object.defineProperty(B5,"__esModule",{value:!0});var FM=gJ(),qM=A7(),OM=G5(),MM=H5(),D5=K5(),VM=[FM.default,qM.default,(0,OM.default)(),MM.default,D5.metadataVocabulary,D5.contentVocabulary];B5.default=VM});var M5=P((q5)=>{Object.defineProperty(q5,"__esModule",{value:!0});q5.DiscrError=void 0;var F5;(function(Q){Q.Tag="tag",Q.Mapping="mapping"})(F5||(q5.DiscrError=F5={}))});var N5=P((Z5)=>{Object.defineProperty(Z5,"__esModule",{value:!0});var a1=g(),EY=M5(),V5=e6(),NM=u4(),wM=c(),PM={message:({params:{discrError:Q,tagName:Y}})=>Q===EY.DiscrError.Tag?`tag "${Y}" must be string`:`value of tag "${Y}" must be in oneOf`,params:({params:{discrError:Q,tag:Y,tagName:X}})=>a1._`{error: ${Q}, tag: ${X}, tagValue: ${Y}}`},bM={keyword:"discriminator",type:"object",schemaType:"object",error:PM,code(Q){let{gen:Y,data:X,schema:W,parentSchema:G,it:$}=Q,{oneOf:z}=G;if(!$.opts.discriminator)throw Error("discriminator: requires discriminator option");let J=W.propertyName;if(typeof J!="string")throw Error("discriminator: requires propertyName");if(W.mapping)throw Error("discriminator: mapping is not supported");if(!z)throw Error("discriminator: requires oneOf keyword");let H=Y.let("valid",!1),A=Y.const("tag",a1._`${X}${(0,a1.getProperty)(J)}`);Y.if(a1._`typeof ${A} == "string"`,()=>U(),()=>Q.error(!1,{discrError:EY.DiscrError.Tag,tag:A,tagName:J})),Q.ok(H);function U(){let L=D();Y.if(!1);for(let O in L)Y.elseIf(a1._`${A} === ${O}`),Y.assign(H,K(L[O]));Y.else(),Q.error(!1,{discrError:EY.DiscrError.Mapping,tag:A,tagName:J}),Y.endIf()}function K(L){let O=Y.name("valid"),M=Q.subschema({keyword:"oneOf",schemaProp:L},O);return Q.mergeEvaluated(M,a1.Name),O}function D(){var L;let O={},M=Z(G),N=!0;for(let y=0;y<z.length;y++){let C=z[y];if((C===null||C===void 0?void 0:C.$ref)&&!(0,wM.schemaHasRulesButRef)(C,$.self.RULES)){let o0=C.$ref;if(C=V5.resolveRef.call($.self,$.schemaEnv.root,$.baseId,o0),C instanceof V5.SchemaEnv)C=C.schema;if(C===void 0)throw new NM.default($.opts.uriResolver,$.baseId,o0)}let c0=(L=C===null||C===void 0?void 0:C.properties)===null||L===void 0?void 0:L[J];if(typeof c0!="object")throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${J}"`);N=N&&(M||Z(C)),k(c0,y)}if(!N)throw Error(`discriminator: "${J}" must be required`);return O;function Z({required:y}){return Array.isArray(y)&&y.includes(J)}function k(y,C){if(y.const)S(y.const,C);else if(y.enum)for(let c0 of y.enum)S(c0,C);else throw Error(`discriminator: "properties/${J}" must have "const" or "enum"`)}function S(y,C){if(typeof y!="string"||y in O)throw Error(`discriminator: "${J}" values must be unique strings`);O[y]=C}}}};Z5.default=bM});var w5=P((RE,IM)=>{IM.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 SY=P((P0,TY)=>{Object.defineProperty(P0,"__esModule",{value:!0});P0.MissingRefError=P0.ValidationError=P0.CodeGen=P0.Name=P0.nil=P0.stringify=P0.str=P0._=P0.KeywordCxt=P0.Ajv=void 0;var EM=IJ(),TM=L5(),SM=N5(),P5=w5(),RM=["/properties"],VQ="http://json-schema.org/draft-07/schema";class t4 extends EM.default{_addVocabularies(){if(super._addVocabularies(),TM.default.forEach((Q)=>this.addVocabulary(Q)),this.opts.discriminator)this.addKeyword(SM.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let Q=this.opts.$data?this.$dataMetaSchema(P5,RM):P5;this.addMetaSchema(Q,VQ,!1),this.refs["http://json-schema.org/schema"]=VQ}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(VQ)?VQ:void 0)}}P0.Ajv=t4;TY.exports=P0=t4;TY.exports.Ajv=t4;Object.defineProperty(P0,"__esModule",{value:!0});P0.default=t4;var CM=y4();Object.defineProperty(P0,"KeywordCxt",{enumerable:!0,get:function(){return CM.KeywordCxt}});var s1=g();Object.defineProperty(P0,"_",{enumerable:!0,get:function(){return s1._}});Object.defineProperty(P0,"str",{enumerable:!0,get:function(){return s1.str}});Object.defineProperty(P0,"stringify",{enumerable:!0,get:function(){return s1.stringify}});Object.defineProperty(P0,"nil",{enumerable:!0,get:function(){return s1.nil}});Object.defineProperty(P0,"Name",{enumerable:!0,get:function(){return s1.Name}});Object.defineProperty(P0,"CodeGen",{enumerable:!0,get:function(){return s1.CodeGen}});var kM=a6();Object.defineProperty(P0,"ValidationError",{enumerable:!0,get:function(){return kM.default}});var vM=u4();Object.defineProperty(P0,"MissingRefError",{enumerable:!0,get:function(){return vM.default}})});var v5=P((C5)=>{Object.defineProperty(C5,"__esModule",{value:!0});C5.formatNames=C5.fastFormats=C5.fullFormats=void 0;function n0(Q,Y){return{validate:Q,compare:Y}}C5.fullFormats={date:n0(E5,vY),time:n0(CY(!0),xY),"date-time":n0(b5(!0),S5),"iso-time":n0(CY(),T5),"iso-date-time":n0(b5(),R5),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:lM,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:dM,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:mM,int32:{type:"number",validate:iM},int64:{type:"number",validate:nM},float:{type:"number",validate:I5},double:{type:"number",validate:I5},password:!0,binary:!0};C5.fastFormats={...C5.fullFormats,date:n0(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,vY),time:n0(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,xY),"date-time":n0(/^\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,S5),"iso-time":n0(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,T5),"iso-date-time":n0(/^\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,R5),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};C5.formatNames=Object.keys(C5.fullFormats);function gM(Q){return Q%4===0&&(Q%100!==0||Q%400===0)}var yM=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,uM=[0,31,28,31,30,31,30,31,31,30,31,30,31];function E5(Q){let Y=yM.exec(Q);if(!Y)return!1;let X=+Y[1],W=+Y[2],G=+Y[3];return W>=1&&W<=12&&G>=1&&G<=(W===2&&gM(X)?29:uM[W])}function vY(Q,Y){if(!(Q&&Y))return;if(Q>Y)return 1;if(Q<Y)return-1;return 0}var RY=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function CY(Q){return function(X){let W=RY.exec(X);if(!W)return!1;let G=+W[1],$=+W[2],z=+W[3],J=W[4],H=W[5]==="-"?-1:1,A=+(W[6]||0),U=+(W[7]||0);if(A>23||U>59||Q&&!J)return!1;if(G<=23&&$<=59&&z<60)return!0;let K=$-U*H,D=G-A*H-(K<0?1:0);return(D===23||D===-1)&&(K===59||K===-1)&&z<61}}function xY(Q,Y){if(!(Q&&Y))return;let X=new Date("2020-01-01T"+Q).valueOf(),W=new Date("2020-01-01T"+Y).valueOf();if(!(X&&W))return;return X-W}function T5(Q,Y){if(!(Q&&Y))return;let X=RY.exec(Q),W=RY.exec(Y);if(!(X&&W))return;if(Q=X[1]+X[2]+X[3],Y=W[1]+W[2]+W[3],Q>Y)return 1;if(Q<Y)return-1;return 0}var kY=/t|\s/i;function b5(Q){let Y=CY(Q);return function(W){let G=W.split(kY);return G.length===2&&E5(G[0])&&Y(G[1])}}function S5(Q,Y){if(!(Q&&Y))return;let X=new Date(Q).valueOf(),W=new Date(Y).valueOf();if(!(X&&W))return;return X-W}function R5(Q,Y){if(!(Q&&Y))return;let[X,W]=Q.split(kY),[G,$]=Y.split(kY),z=vY(X,G);if(z===void 0)return;return z||xY(W,$)}var hM=/\/|:/,fM=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function lM(Q){return hM.test(Q)&&fM.test(Q)}var j5=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function mM(Q){return j5.lastIndex=0,j5.test(Q)}var cM=-2147483648,pM=2147483647;function iM(Q){return Number.isInteger(Q)&&Q<=pM&&Q>=cM}function nM(Q){return Number.isInteger(Q)}function I5(){return!0}var rM=/[^\\]\\Z/;function dM(Q){if(rM.test(Q))return!1;try{return new RegExp(Q),!0}catch(Y){return!1}}});var _5=P((x5)=>{Object.defineProperty(x5,"__esModule",{value:!0});x5.formatLimitDefinition=void 0;var tM=SY(),f0=g(),V1=f0.operators,ZQ={formatMaximum:{okStr:"<=",ok:V1.LTE,fail:V1.GT},formatMinimum:{okStr:">=",ok:V1.GTE,fail:V1.LT},formatExclusiveMaximum:{okStr:"<",ok:V1.LT,fail:V1.GTE},formatExclusiveMinimum:{okStr:">",ok:V1.GT,fail:V1.LTE}},aM={message:({keyword:Q,schemaCode:Y})=>f0.str`should be ${ZQ[Q].okStr} ${Y}`,params:({keyword:Q,schemaCode:Y})=>f0._`{comparison: ${ZQ[Q].okStr}, limit: ${Y}}`};x5.formatLimitDefinition={keyword:Object.keys(ZQ),type:"string",schemaType:"string",$data:!0,error:aM,code(Q){let{gen:Y,data:X,schemaCode:W,keyword:G,it:$}=Q,{opts:z,self:J}=$;if(!z.validateFormats)return;let H=new tM.KeywordCxt($,J.RULES.all.format.definition,"format");if(H.$data)A();else U();function A(){let D=Y.scopeValue("formats",{ref:J.formats,code:z.code.formats}),L=Y.const("fmt",f0._`${D}[${H.schemaCode}]`);Q.fail$data((0,f0.or)(f0._`typeof ${L} != "object"`,f0._`${L} instanceof RegExp`,f0._`typeof ${L}.compare != "function"`,K(L)))}function U(){let D=H.schema,L=J.formats[D];if(!L||L===!0)return;if(typeof L!="object"||L instanceof RegExp||typeof L.compare!="function")throw Error(`"${G}": format "${D}" does not define "compare" function`);let O=Y.scopeValue("formats",{key:D,ref:L,code:z.code.formats?f0._`${z.code.formats}${(0,f0.getProperty)(D)}`:void 0});Q.fail$data(K(O))}function K(D){return f0._`${D}.compare(${X}, ${W}) ${ZQ[G].fail} 0`}},dependencies:["format"]};var sM=(Q)=>{return Q.addKeyword(x5.formatLimitDefinition),Q};x5.default=sM});var h5=P((a4,u5)=>{Object.defineProperty(a4,"__esModule",{value:!0});var e1=v5(),QV=_5(),yY=g(),g5=new yY.Name("fullFormats"),YV=new yY.Name("fastFormats"),uY=(Q,Y={keywords:!0})=>{if(Array.isArray(Y))return y5(Q,Y,e1.fullFormats,g5),Q;let[X,W]=Y.mode==="fast"?[e1.fastFormats,YV]:[e1.fullFormats,g5],G=Y.formats||e1.formatNames;if(y5(Q,G,X,W),Y.keywords)(0,QV.default)(Q);return Q};uY.get=(Q,Y="full")=>{let W=(Y==="fast"?e1.fastFormats:e1.fullFormats)[Q];if(!W)throw Error(`Unknown format "${Q}"`);return W};function y5(Q,Y,X,W){var G,$;(G=($=Q.opts.code).formats)!==null&&G!==void 0||($.formats=yY._`require("ajv-formats/dist/formats").${W}`);for(let z of Y)Q.addFormat(z,X[z])}u5.exports=a4=uY;Object.defineProperty(a4,"__esModule",{value:!0});a4.default=uY});import{AsyncLocalStorage as TH}from"node:async_hooks";class P1 extends Error{statusCode;rawDetails;code;context;constructor(Q,Y,X,W,G){super(Q);this.statusCode=Y;this.rawDetails=X;this.code=W;this.context=G;this.name="McpApiError"}}function jH(Q){if(Q instanceof P1)return{message:Q.message,statusCode:Q.statusCode,code:Q.code,rawDetails:Q.rawDetails,context:Q.context};if(Q instanceof Error)return{message:Q.message};return{message:String(Q)}}function IH(Q){let Y=Q.match(/api key is missing required scopes?:\s*(.+)$/i);if(!Y?.[1])return[];return Y[1].match(/[a-z_]+:[a-z_]+/gi)??[]}function EH(Q){let Y=jH(Q),X=Y.message.trim()||"Unknown error",W=X.toLowerCase(),G=Y.rawDetails?.trim()||X;if(Y.context?.title||Y.context?.description||Y.context?.howToFix||Y.context?.docsUrl)return{title:Y.context.title??(Y.statusCode===409?"Request conflict":"API request failed"),description:Y.context.description??X,howToFix:Y.context.howToFix??"Review the details below, adjust the tool input, and retry.",docsUrl:Y.context.docsUrl??"https://docs.sequenzy.com/concepts/mcp",details:G};if(Y.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:G};if(Y.statusCode===401||Y.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:G};let $=IH(X);if($.length>0){let z=$.map((H)=>`\`${H}\``).join(", "),J=$.every((H)=>H.endsWith(":read"))?"the Read-only or Safer agent access preset":"Safer agent access when it covers the task, or Custom permissions";return{title:"API key permission required",description:`The current API key is valid, but this operation requires the missing ${$.length===1?"scope":"scopes"}: ${z}.`,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 ${J} including ${z}, 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 ${z}. Existing key permissions cannot be edited in place.`,docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:G}}if(Y.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:G};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:G};if(Y.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:G};if(Y.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:G};if(Y.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:G};if(Y.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:G};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:G};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:G};if(Y.statusCode&&Y.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:G};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:G}}function $1(Q){let Y=EH(Q);return[`Sequenzy MCP error: ${Y.title}`,`Description: ${Y.description}`,`How to fix: ${Y.howToFix}`,`Docs: ${Y.docsUrl}`,`Details: ${Y.details}`].join(`
10
- `)}var SH="https://api.sequenzy.com",W4=new TH,FX=!1;function qX(){FX=!0}function OX(){return FX}var MX=null;function b1(){let Q=W4.getStore();if(Q)return Q.selectedCompanyId??null;return MX}function Q6(Q){let Y=W4.getStore();if(Y){Y.selectedCompanyId=Q;return}MX=Q}function SQ(Q,Y){return W4.run(Q,Y)}function RH(){return W4.getStore()?.apiUrl??process.env.SEQUENZY_API_URL??SH}function VX(){return W4.getStore()?.apiKey??process.env.SEQUENZY_API_KEY}function ZX(){if(VX())return;console.error($1(new P1("SEQUENZY_API_KEY environment variable is required",401,void 0,"MCP_AUTH_REQUIRED"))),process.exit(1)}function j0(Q,Y){let X=Q[Y];return typeof X==="string"&&X.trim()!==""?X.trim():void 0}function CH(Q){if(Q===void 0)return;if(typeof Q==="string")return Q.trim()||void 0;return JSON.stringify(Q)}function kH(Q){if(!Q.trim())return{message:"Request failed"};try{let Y=JSON.parse(Q);if(typeof Y==="string")return{message:Y};let X=typeof Y.error==="object"&&Y.error!==null?Y.error:void 0,W=j0(Y,"code")??(X?j0(X,"code"):void 0),G=(typeof Y.error==="string"?Y.error:void 0)??(X?j0(X,"message"):void 0)??j0(Y,"message")??j0(Y,"error")??Q,$=j0(Y,"howToFix")??j0(Y,"resolution"),z={...j0(Y,"title")?{title:j0(Y,"title")}:{},...j0(Y,"description")?{description:j0(Y,"description")}:{},...$?{howToFix:$}:{},...j0(Y,"docsUrl")?{docsUrl:j0(Y,"docsUrl")}:{}},J=CH(Y.details);if(Object.keys(z).length>0||J)return{message:G,...W?{code:W}:{},...J?{details:J}:{},...Object.keys(z).length>0?{context:z}:{}};if(typeof Y.error==="string")return{message:Y.error,...W?{code:W}:{}};if(X)return{message:G,...W?{code:W}:{}};return{message:G,...W?{code:W}:{}}}catch{return{message:Q}}}async function B(Q,Y,X,W){let G=VX();if(!G)throw new P1("SEQUENZY_API_KEY environment variable is required",401,void 0,"MCP_AUTH_REQUIRED");let $={"Content-Type":"application/json",Authorization:`Bearer ${G}`},z=W??b1();if(z)$["x-company-id"]=z;let J;try{J=await fetch(`${RH()}${Y}`,{method:Q,headers:$,body:X?JSON.stringify(X):void 0})}catch(H){throw new P1(H instanceof Error?H.message:"Failed to reach Sequenzy API",0,void 0,"NETWORK_ERROR")}if(!J.ok){let H=await J.text(),A=kH(H);throw new P1(A.message,J.status,A.details??H,A.code,A.context)}return J.json()}var OZ=Object.freeze({status:"aborted"});function q(Q,Y,X){function W(J,H){var A;Object.defineProperty(J,"_zod",{value:J._zod??{},enumerable:!1}),(A=J._zod).traits??(A.traits=new Set),J._zod.traits.add(Q),Y(J,H);for(let U in z.prototype)if(!(U in J))Object.defineProperty(J,U,{value:z.prototype[U].bind(J)});J._zod.constr=z,J._zod.def=H}let G=X?.Parent??Object;class $ extends G{}Object.defineProperty($,"name",{value:Q});function z(J){var H;let A=X?.Parent?new $:this;W(A,J),(H=A._zod).deferred??(H.deferred=[]);for(let U of A._zod.deferred)U();return A}return Object.defineProperty(z,"init",{value:W}),Object.defineProperty(z,Symbol.hasInstance,{value:(J)=>{if(X?.Parent&&J instanceof X.Parent)return!0;return J?._zod?.traits?.has(Q)}}),Object.defineProperty(z,"name",{value:Q}),z}var MZ=Symbol("zod_brand");class t0 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class G4 extends Error{constructor(Q){super(`Encountered unidirectional transform during encode: ${Q}`);this.name="ZodEncodeError"}}var Y6={};function T0(Q){if(Q)Object.assign(Y6,Q);return Y6}var m={};LX(m,{unwrapMessage:()=>$4,uint8ArrayToHex:()=>WA,uint8ArrayToBase64url:()=>YA,uint8ArrayToBase64:()=>EX,stringifyPrimitive:()=>$6,shallowClone:()=>wX,safeExtend:()=>oH,required:()=>sH,randomString:()=>mH,propertyKeyTypes:()=>xQ,promiseAllObject:()=>lH,primitiveTypes:()=>PX,prefixIssues:()=>s0,pick:()=>nH,partial:()=>aH,optionalKeys:()=>_Q,omit:()=>rH,objectClone:()=>uH,numKeys:()=>cH,nullish:()=>z4,normalizeParams:()=>T,mergeDefs:()=>J1,merge:()=>tH,jsonStringifyReplacer:()=>_1,joinValues:()=>X6,issue:()=>y1,isPlainObject:()=>H1,isObject:()=>j1,hexToUint8Array:()=>XA,getSizableOrigin:()=>jX,getParsedType:()=>pH,getLengthableOrigin:()=>H4,getEnumValues:()=>CQ,getElementAtPath:()=>fH,floatSafeRemainder:()=>kQ,finalizeIssue:()=>x0,extend:()=>dH,escapeRegex:()=>a0,esc:()=>W6,defineLazy:()=>n,createTransparentProxy:()=>iH,cloneDef:()=>hH,clone:()=>v0,cleanRegex:()=>J4,cleanEnum:()=>eH,captureStackTrace:()=>G6,cached:()=>g1,base64urlToUint8Array:()=>QA,base64ToUint8Array:()=>IX,assignProp:()=>z1,assertNotEqual:()=>xH,assertNever:()=>gH,assertIs:()=>_H,assertEqual:()=>vH,assert:()=>yH,allowsEval:()=>vQ,aborted:()=>A1,NUMBER_FORMAT_RANGES:()=>gQ,Class:()=>TX,BIGINT_FORMAT_RANGES:()=>bX});function vH(Q){return Q}function xH(Q){return Q}function _H(Q){}function gH(Q){throw Error()}function yH(Q){}function CQ(Q){let Y=Object.values(Q).filter((W)=>typeof W==="number");return Object.entries(Q).filter(([W,G])=>Y.indexOf(+W)===-1).map(([W,G])=>G)}function X6(Q,Y="|"){return Q.map((X)=>$6(X)).join(Y)}function _1(Q,Y){if(typeof Y==="bigint")return Y.toString();return Y}function g1(Q){return{get value(){{let X=Q();return Object.defineProperty(this,"value",{value:X}),X}throw Error("cached value already set")}}}function z4(Q){return Q===null||Q===void 0}function J4(Q){let Y=Q.startsWith("^")?1:0,X=Q.endsWith("$")?Q.length-1:Q.length;return Q.slice(Y,X)}function kQ(Q,Y){let X=(Q.toString().split(".")[1]||"").length,W=Y.toString(),G=(W.split(".")[1]||"").length;if(G===0&&/\d?e-\d?/.test(W)){let H=W.match(/\d?e-(\d?)/);if(H?.[1])G=Number.parseInt(H[1])}let $=X>G?X:G,z=Number.parseInt(Q.toFixed($).replace(".","")),J=Number.parseInt(Y.toFixed($).replace(".",""));return z%J/10**$}var NX=Symbol("evaluating");function n(Q,Y,X){let W=void 0;Object.defineProperty(Q,Y,{get(){if(W===NX)return;if(W===void 0)W=NX,W=X();return W},set(G){Object.defineProperty(Q,Y,{value:G})},configurable:!0})}function uH(Q){return Object.create(Object.getPrototypeOf(Q),Object.getOwnPropertyDescriptors(Q))}function z1(Q,Y,X){Object.defineProperty(Q,Y,{value:X,writable:!0,enumerable:!0,configurable:!0})}function J1(...Q){let Y={};for(let X of Q){let W=Object.getOwnPropertyDescriptors(X);Object.assign(Y,W)}return Object.defineProperties({},Y)}function hH(Q){return J1(Q._zod.def)}function fH(Q,Y){if(!Y)return Q;return Y.reduce((X,W)=>X?.[W],Q)}function lH(Q){let Y=Object.keys(Q),X=Y.map((W)=>Q[W]);return Promise.all(X).then((W)=>{let G={};for(let $=0;$<Y.length;$++)G[Y[$]]=W[$];return G})}function mH(Q=10){let X="";for(let W=0;W<Q;W++)X+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return X}function W6(Q){return JSON.stringify(Q)}var G6="captureStackTrace"in Error?Error.captureStackTrace:(...Q)=>{};function j1(Q){return typeof Q==="object"&&Q!==null&&!Array.isArray(Q)}var vQ=g1(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(Q){return!1}});function H1(Q){if(j1(Q)===!1)return!1;let Y=Q.constructor;if(Y===void 0)return!0;let X=Y.prototype;if(j1(X)===!1)return!1;if(Object.prototype.hasOwnProperty.call(X,"isPrototypeOf")===!1)return!1;return!0}function wX(Q){if(H1(Q))return{...Q};if(Array.isArray(Q))return[...Q];return Q}function cH(Q){let Y=0;for(let X in Q)if(Object.prototype.hasOwnProperty.call(Q,X))Y++;return Y}var pH=(Q)=>{let Y=typeof Q;switch(Y){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(Q)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(Q))return"array";if(Q===null)return"null";if(Q.then&&typeof Q.then==="function"&&Q.catch&&typeof Q.catch==="function")return"promise";if(typeof Map<"u"&&Q instanceof Map)return"map";if(typeof Set<"u"&&Q instanceof Set)return"set";if(typeof Date<"u"&&Q instanceof Date)return"date";if(typeof File<"u"&&Q instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${Y}`)}},xQ=new Set(["string","number","symbol"]),PX=new Set(["string","number","bigint","boolean","symbol","undefined"]);function a0(Q){return Q.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function v0(Q,Y,X){let W=new Q._zod.constr(Y??Q._zod.def);if(!Y||X?.parent)W._zod.parent=Q;return W}function T(Q){let Y=Q;if(!Y)return{};if(typeof Y==="string")return{error:()=>Y};if(Y?.message!==void 0){if(Y?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");Y.error=Y.message}if(delete Y.message,typeof Y.error==="string")return{...Y,error:()=>Y.error};return Y}function iH(Q){let Y;return new Proxy({},{get(X,W,G){return Y??(Y=Q()),Reflect.get(Y,W,G)},set(X,W,G,$){return Y??(Y=Q()),Reflect.set(Y,W,G,$)},has(X,W){return Y??(Y=Q()),Reflect.has(Y,W)},deleteProperty(X,W){return Y??(Y=Q()),Reflect.deleteProperty(Y,W)},ownKeys(X){return Y??(Y=Q()),Reflect.ownKeys(Y)},getOwnPropertyDescriptor(X,W){return Y??(Y=Q()),Reflect.getOwnPropertyDescriptor(Y,W)},defineProperty(X,W,G){return Y??(Y=Q()),Reflect.defineProperty(Y,W,G)}})}function $6(Q){if(typeof Q==="bigint")return Q.toString()+"n";if(typeof Q==="string")return`"${Q}"`;return`${Q}`}function _Q(Q){return Object.keys(Q).filter((Y)=>{return Q[Y]._zod.optin==="optional"&&Q[Y]._zod.optout==="optional"})}var gQ={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]},bX={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function nH(Q,Y){let X=Q._zod.def,W=J1(Q._zod.def,{get shape(){let G={};for(let $ in Y){if(!($ in X.shape))throw Error(`Unrecognized key: "${$}"`);if(!Y[$])continue;G[$]=X.shape[$]}return z1(this,"shape",G),G},checks:[]});return v0(Q,W)}function rH(Q,Y){let X=Q._zod.def,W=J1(Q._zod.def,{get shape(){let G={...Q._zod.def.shape};for(let $ in Y){if(!($ in X.shape))throw Error(`Unrecognized key: "${$}"`);if(!Y[$])continue;delete G[$]}return z1(this,"shape",G),G},checks:[]});return v0(Q,W)}function dH(Q,Y){if(!H1(Y))throw Error("Invalid input to extend: expected a plain object");let X=Q._zod.def.checks;if(X&&X.length>0)throw Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");let G=J1(Q._zod.def,{get shape(){let $={...Q._zod.def.shape,...Y};return z1(this,"shape",$),$},checks:[]});return v0(Q,G)}function oH(Q,Y){if(!H1(Y))throw Error("Invalid input to safeExtend: expected a plain object");let X={...Q._zod.def,get shape(){let W={...Q._zod.def.shape,...Y};return z1(this,"shape",W),W},checks:Q._zod.def.checks};return v0(Q,X)}function tH(Q,Y){let X=J1(Q._zod.def,{get shape(){let W={...Q._zod.def.shape,...Y._zod.def.shape};return z1(this,"shape",W),W},get catchall(){return Y._zod.def.catchall},checks:[]});return v0(Q,X)}function aH(Q,Y,X){let W=J1(Y._zod.def,{get shape(){let G=Y._zod.def.shape,$={...G};if(X)for(let z in X){if(!(z in G))throw Error(`Unrecognized key: "${z}"`);if(!X[z])continue;$[z]=Q?new Q({type:"optional",innerType:G[z]}):G[z]}else for(let z in G)$[z]=Q?new Q({type:"optional",innerType:G[z]}):G[z];return z1(this,"shape",$),$},checks:[]});return v0(Y,W)}function sH(Q,Y,X){let W=J1(Y._zod.def,{get shape(){let G=Y._zod.def.shape,$={...G};if(X)for(let z in X){if(!(z in $))throw Error(`Unrecognized key: "${z}"`);if(!X[z])continue;$[z]=new Q({type:"nonoptional",innerType:G[z]})}else for(let z in G)$[z]=new Q({type:"nonoptional",innerType:G[z]});return z1(this,"shape",$),$},checks:[]});return v0(Y,W)}function A1(Q,Y=0){if(Q.aborted===!0)return!0;for(let X=Y;X<Q.issues.length;X++)if(Q.issues[X]?.continue!==!0)return!0;return!1}function s0(Q,Y){return Y.map((X)=>{var W;return(W=X).path??(W.path=[]),X.path.unshift(Q),X})}function $4(Q){return typeof Q==="string"?Q:Q?.message}function x0(Q,Y,X){let W={...Q,path:Q.path??[]};if(!Q.message){let G=$4(Q.inst?._zod.def?.error?.(Q))??$4(Y?.error?.(Q))??$4(X.customError?.(Q))??$4(X.localeError?.(Q))??"Invalid input";W.message=G}if(delete W.inst,delete W.continue,!Y?.reportInput)delete W.input;return W}function jX(Q){if(Q instanceof Set)return"set";if(Q instanceof Map)return"map";if(Q instanceof File)return"file";return"unknown"}function H4(Q){if(Array.isArray(Q))return"array";if(typeof Q==="string")return"string";return"unknown"}function y1(...Q){let[Y,X,W]=Q;if(typeof Y==="string")return{message:Y,code:"custom",input:X,inst:W};return{...Y}}function eH(Q){return Object.entries(Q).filter(([Y,X])=>{return Number.isNaN(Number.parseInt(Y,10))}).map((Y)=>Y[1])}function IX(Q){let Y=atob(Q),X=new Uint8Array(Y.length);for(let W=0;W<Y.length;W++)X[W]=Y.charCodeAt(W);return X}function EX(Q){let Y="";for(let X=0;X<Q.length;X++)Y+=String.fromCharCode(Q[X]);return btoa(Y)}function QA(Q){let Y=Q.replace(/-/g,"+").replace(/_/g,"/"),X="=".repeat((4-Y.length%4)%4);return IX(Y+X)}function YA(Q){return EX(Q).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function XA(Q){let Y=Q.replace(/^0x/,"");if(Y.length%2!==0)throw Error("Invalid hex string length");let X=new Uint8Array(Y.length/2);for(let W=0;W<Y.length;W+=2)X[W/2]=Number.parseInt(Y.slice(W,W+2),16);return X}function WA(Q){return Array.from(Q).map((Y)=>Y.toString(16).padStart(2,"0")).join("")}class TX{constructor(...Q){}}var SX=(Q,Y)=>{Q.name="$ZodError",Object.defineProperty(Q,"_zod",{value:Q._zod,enumerable:!1}),Object.defineProperty(Q,"issues",{value:Y,enumerable:!1}),Q.message=JSON.stringify(Y,_1,2),Object.defineProperty(Q,"toString",{value:()=>Q.message,enumerable:!1})},z6=q("$ZodError",SX),yQ=q("$ZodError",SX,{Parent:Error});function RX(Q,Y=(X)=>X.message){let X={},W=[];for(let G of Q.issues)if(G.path.length>0)X[G.path[0]]=X[G.path[0]]||[],X[G.path[0]].push(Y(G));else W.push(Y(G));return{formErrors:W,fieldErrors:X}}function CX(Q,Y=(X)=>X.message){let X={_errors:[]},W=(G)=>{for(let $ of G.issues)if($.code==="invalid_union"&&$.errors.length)$.errors.map((z)=>W({issues:z}));else if($.code==="invalid_key")W({issues:$.issues});else if($.code==="invalid_element")W({issues:$.issues});else if($.path.length===0)X._errors.push(Y($));else{let z=X,J=0;while(J<$.path.length){let H=$.path[J];if(J!==$.path.length-1)z[H]=z[H]||{_errors:[]};else z[H]=z[H]||{_errors:[]},z[H]._errors.push(Y($));z=z[H],J++}}};return W(Q),X}var J6=(Q)=>(Y,X,W,G)=>{let $=W?Object.assign(W,{async:!1}):{async:!1},z=Y._zod.run({value:X,issues:[]},$);if(z instanceof Promise)throw new t0;if(z.issues.length){let J=new(G?.Err??Q)(z.issues.map((H)=>x0(H,$,T0())));throw G6(J,G?.callee),J}return z.value};var H6=(Q)=>async(Y,X,W,G)=>{let $=W?Object.assign(W,{async:!0}):{async:!0},z=Y._zod.run({value:X,issues:[]},$);if(z instanceof Promise)z=await z;if(z.issues.length){let J=new(G?.Err??Q)(z.issues.map((H)=>x0(H,$,T0())));throw G6(J,G?.callee),J}return z.value};var A4=(Q)=>(Y,X,W)=>{let G=W?{...W,async:!1}:{async:!1},$=Y._zod.run({value:X,issues:[]},G);if($ instanceof Promise)throw new t0;return $.issues.length?{success:!1,error:new(Q??z6)($.issues.map((z)=>x0(z,G,T0())))}:{success:!0,data:$.value}},U4=A4(yQ),K4=(Q)=>async(Y,X,W)=>{let G=W?Object.assign(W,{async:!0}):{async:!0},$=Y._zod.run({value:X,issues:[]},G);if($ instanceof Promise)$=await $;return $.issues.length?{success:!1,error:new Q($.issues.map((z)=>x0(z,G,T0())))}:{success:!0,data:$.value}},A6=K4(yQ),kX=(Q)=>(Y,X,W)=>{let G=W?Object.assign(W,{direction:"backward"}):{direction:"backward"};return J6(Q)(Y,X,G)};var vX=(Q)=>(Y,X,W)=>{return J6(Q)(Y,X,W)};var xX=(Q)=>async(Y,X,W)=>{let G=W?Object.assign(W,{direction:"backward"}):{direction:"backward"};return H6(Q)(Y,X,G)};var _X=(Q)=>async(Y,X,W)=>{return H6(Q)(Y,X,W)};var gX=(Q)=>(Y,X,W)=>{let G=W?Object.assign(W,{direction:"backward"}):{direction:"backward"};return A4(Q)(Y,X,G)};var yX=(Q)=>(Y,X,W)=>{return A4(Q)(Y,X,W)};var uX=(Q)=>async(Y,X,W)=>{let G=W?Object.assign(W,{direction:"backward"}):{direction:"backward"};return K4(Q)(Y,X,G)};var hX=(Q)=>async(Y,X,W)=>{return K4(Q)(Y,X,W)};var fX=/^[cC][^\s-]{8,}$/,lX=/^[0-9a-z]+$/,mX=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,cX=/^[0-9a-vA-V]{20}$/,pX=/^[A-Za-z0-9]{27}$/,iX=/^[a-zA-Z0-9_-]{21}$/,nX=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var rX=/^([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})$/,uQ=(Q)=>{if(!Q)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}-${Q}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)};var dX=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function oX(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}var tX=/^(?:(?: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])$/,aX=/^(([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}|:))$/,sX=/^((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])$/,eX=/^(([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])$/,Q8=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,hQ=/^[A-Za-z0-9_-]*$/,Y8=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/;var X8=/^\+(?:[0-9]){6,14}[0-9]$/,W8="(?:(?:\\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])))",G8=new RegExp(`^${W8}$`);function $8(Q){return typeof Q.precision==="number"?Q.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":Q.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{${Q.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function z8(Q){return new RegExp(`^${$8(Q)}$`)}function J8(Q){let Y=$8({precision:Q.precision}),X=["Z"];if(Q.local)X.push("");if(Q.offset)X.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let W=`${Y}(?:${X.join("|")})`;return new RegExp(`^${W8}T(?:${W})$`)}var H8=(Q)=>{let Y=Q?`[\\s\\S]{${Q?.minimum??0},${Q?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${Y}$`)};var A8=/^-?\d+$/,U8=/^-?\d+(?:\.\d+)?/,K8=/^(?:true|false)$/i,D8=/^null$/i;var B8=/^[^A-Z]*$/,L8=/^[^a-z]*$/;var A0=q("$ZodCheck",(Q,Y)=>{var X;Q._zod??(Q._zod={}),Q._zod.def=Y,(X=Q._zod).onattach??(X.onattach=[])}),F8={number:"number",bigint:"bigint",object:"date"},fQ=q("$ZodCheckLessThan",(Q,Y)=>{A0.init(Q,Y);let X=F8[typeof Y.value];Q._zod.onattach.push((W)=>{let G=W._zod.bag,$=(Y.inclusive?G.maximum:G.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(Y.value<$)if(Y.inclusive)G.maximum=Y.value;else G.exclusiveMaximum=Y.value}),Q._zod.check=(W)=>{if(Y.inclusive?W.value<=Y.value:W.value<Y.value)return;W.issues.push({origin:X,code:"too_big",maximum:Y.value,input:W.value,inclusive:Y.inclusive,inst:Q,continue:!Y.abort})}}),lQ=q("$ZodCheckGreaterThan",(Q,Y)=>{A0.init(Q,Y);let X=F8[typeof Y.value];Q._zod.onattach.push((W)=>{let G=W._zod.bag,$=(Y.inclusive?G.minimum:G.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(Y.value>$)if(Y.inclusive)G.minimum=Y.value;else G.exclusiveMinimum=Y.value}),Q._zod.check=(W)=>{if(Y.inclusive?W.value>=Y.value:W.value>Y.value)return;W.issues.push({origin:X,code:"too_small",minimum:Y.value,input:W.value,inclusive:Y.inclusive,inst:Q,continue:!Y.abort})}}),q8=q("$ZodCheckMultipleOf",(Q,Y)=>{A0.init(Q,Y),Q._zod.onattach.push((X)=>{var W;(W=X._zod.bag).multipleOf??(W.multipleOf=Y.value)}),Q._zod.check=(X)=>{if(typeof X.value!==typeof Y.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof X.value==="bigint"?X.value%Y.value===BigInt(0):kQ(X.value,Y.value)===0)return;X.issues.push({origin:typeof X.value,code:"not_multiple_of",divisor:Y.value,input:X.value,inst:Q,continue:!Y.abort})}}),O8=q("$ZodCheckNumberFormat",(Q,Y)=>{A0.init(Q,Y),Y.format=Y.format||"float64";let X=Y.format?.includes("int"),W=X?"int":"number",[G,$]=gQ[Y.format];Q._zod.onattach.push((z)=>{let J=z._zod.bag;if(J.format=Y.format,J.minimum=G,J.maximum=$,X)J.pattern=A8}),Q._zod.check=(z)=>{let J=z.value;if(X){if(!Number.isInteger(J)){z.issues.push({expected:W,format:Y.format,code:"invalid_type",continue:!1,input:J,inst:Q});return}if(!Number.isSafeInteger(J)){if(J>0)z.issues.push({input:J,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:Q,origin:W,continue:!Y.abort});else z.issues.push({input:J,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:Q,origin:W,continue:!Y.abort});return}}if(J<G)z.issues.push({origin:"number",input:J,code:"too_small",minimum:G,inclusive:!0,inst:Q,continue:!Y.abort});if(J>$)z.issues.push({origin:"number",input:J,code:"too_big",maximum:$,inst:Q})}});var M8=q("$ZodCheckMaxLength",(Q,Y)=>{var X;A0.init(Q,Y),(X=Q._zod.def).when??(X.when=(W)=>{let G=W.value;return!z4(G)&&G.length!==void 0}),Q._zod.onattach.push((W)=>{let G=W._zod.bag.maximum??Number.POSITIVE_INFINITY;if(Y.maximum<G)W._zod.bag.maximum=Y.maximum}),Q._zod.check=(W)=>{let G=W.value;if(G.length<=Y.maximum)return;let z=H4(G);W.issues.push({origin:z,code:"too_big",maximum:Y.maximum,inclusive:!0,input:G,inst:Q,continue:!Y.abort})}}),V8=q("$ZodCheckMinLength",(Q,Y)=>{var X;A0.init(Q,Y),(X=Q._zod.def).when??(X.when=(W)=>{let G=W.value;return!z4(G)&&G.length!==void 0}),Q._zod.onattach.push((W)=>{let G=W._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(Y.minimum>G)W._zod.bag.minimum=Y.minimum}),Q._zod.check=(W)=>{let G=W.value;if(G.length>=Y.minimum)return;let z=H4(G);W.issues.push({origin:z,code:"too_small",minimum:Y.minimum,inclusive:!0,input:G,inst:Q,continue:!Y.abort})}}),Z8=q("$ZodCheckLengthEquals",(Q,Y)=>{var X;A0.init(Q,Y),(X=Q._zod.def).when??(X.when=(W)=>{let G=W.value;return!z4(G)&&G.length!==void 0}),Q._zod.onattach.push((W)=>{let G=W._zod.bag;G.minimum=Y.length,G.maximum=Y.length,G.length=Y.length}),Q._zod.check=(W)=>{let G=W.value,$=G.length;if($===Y.length)return;let z=H4(G),J=$>Y.length;W.issues.push({origin:z,...J?{code:"too_big",maximum:Y.length}:{code:"too_small",minimum:Y.length},inclusive:!0,exact:!0,input:W.value,inst:Q,continue:!Y.abort})}}),D4=q("$ZodCheckStringFormat",(Q,Y)=>{var X,W;if(A0.init(Q,Y),Q._zod.onattach.push((G)=>{let $=G._zod.bag;if($.format=Y.format,Y.pattern)$.patterns??($.patterns=new Set),$.patterns.add(Y.pattern)}),Y.pattern)(X=Q._zod).check??(X.check=(G)=>{if(Y.pattern.lastIndex=0,Y.pattern.test(G.value))return;G.issues.push({origin:"string",code:"invalid_format",format:Y.format,input:G.value,...Y.pattern?{pattern:Y.pattern.toString()}:{},inst:Q,continue:!Y.abort})});else(W=Q._zod).check??(W.check=()=>{})}),N8=q("$ZodCheckRegex",(Q,Y)=>{D4.init(Q,Y),Q._zod.check=(X)=>{if(Y.pattern.lastIndex=0,Y.pattern.test(X.value))return;X.issues.push({origin:"string",code:"invalid_format",format:"regex",input:X.value,pattern:Y.pattern.toString(),inst:Q,continue:!Y.abort})}}),w8=q("$ZodCheckLowerCase",(Q,Y)=>{Y.pattern??(Y.pattern=B8),D4.init(Q,Y)}),P8=q("$ZodCheckUpperCase",(Q,Y)=>{Y.pattern??(Y.pattern=L8),D4.init(Q,Y)}),b8=q("$ZodCheckIncludes",(Q,Y)=>{A0.init(Q,Y);let X=a0(Y.includes),W=new RegExp(typeof Y.position==="number"?`^.{${Y.position}}${X}`:X);Y.pattern=W,Q._zod.onattach.push((G)=>{let $=G._zod.bag;$.patterns??($.patterns=new Set),$.patterns.add(W)}),Q._zod.check=(G)=>{if(G.value.includes(Y.includes,Y.position))return;G.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:Y.includes,input:G.value,inst:Q,continue:!Y.abort})}}),j8=q("$ZodCheckStartsWith",(Q,Y)=>{A0.init(Q,Y);let X=new RegExp(`^${a0(Y.prefix)}.*`);Y.pattern??(Y.pattern=X),Q._zod.onattach.push((W)=>{let G=W._zod.bag;G.patterns??(G.patterns=new Set),G.patterns.add(X)}),Q._zod.check=(W)=>{if(W.value.startsWith(Y.prefix))return;W.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:Y.prefix,input:W.value,inst:Q,continue:!Y.abort})}}),I8=q("$ZodCheckEndsWith",(Q,Y)=>{A0.init(Q,Y);let X=new RegExp(`.*${a0(Y.suffix)}$`);Y.pattern??(Y.pattern=X),Q._zod.onattach.push((W)=>{let G=W._zod.bag;G.patterns??(G.patterns=new Set),G.patterns.add(X)}),Q._zod.check=(W)=>{if(W.value.endsWith(Y.suffix))return;W.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:Y.suffix,input:W.value,inst:Q,continue:!Y.abort})}});var E8=q("$ZodCheckOverwrite",(Q,Y)=>{A0.init(Q,Y),Q._zod.check=(X)=>{X.value=Y.tx(X.value)}});class mQ{constructor(Q=[]){if(this.content=[],this.indent=0,this)this.args=Q}indented(Q){this.indent+=1,Q(this),this.indent-=1}write(Q){if(typeof Q==="function"){Q(this,{execution:"sync"}),Q(this,{execution:"async"});return}let X=Q.split(`
9
+ deps: ${X}}`};var LO={keyword:"dependencies",type:"object",schemaType:"object",error:T7.error,code(Q){let[Y,X]=FO(Q);I7(Q,Y),E7(Q,X)}};function FO({schema:Q}){let Y={},X={};for(let W in Q){if(W==="__proto__")continue;let G=Array.isArray(Q[W])?Y:X;G[W]=Q[W]}return[Y,X]}function I7(Q,Y=Q.schema){let{gen:X,data:W,it:G}=Q;if(Object.keys(Y).length===0)return;let $=X.let("missing");for(let z in Y){let J=Y[z];if(J.length===0)continue;let H=(0,o4.propertyInData)(X,W,z,G.opts.ownProperties);if(Q.setParams({property:z,depsCount:J.length,deps:J.join(", ")}),G.allErrors)X.if(H,()=>{for(let A of J)(0,o4.checkReportMissingProp)(Q,A)});else X.if(bY._`${H} && (${(0,o4.checkMissingProp)(Q,J,$)})`),(0,o4.reportMissingProp)(Q,$),X.else()}}T7.validatePropertyDeps=I7;function E7(Q,Y=Q.schema){let{gen:X,data:W,keyword:G,it:$}=Q,z=X.name("valid");for(let J in Y){if((0,BO.alwaysValidSchema)($,Y[J]))continue;X.if((0,o4.propertyInData)(X,W,J,$.opts.ownProperties),()=>{let H=Q.subschema({keyword:G,schemaProp:J},z);Q.mergeValidEvaluated(H,z)},()=>X.var(z,!0)),Q.ok(z)}}T7.validateSchemaDeps=E7;T7.default=LO});var x7=P((v7)=>{Object.defineProperty(v7,"__esModule",{value:!0});var k7=g(),MO=c(),VO={message:"property name must be valid",params:({params:Q})=>k7._`{propertyName: ${Q.propertyName}}`},ZO={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:VO,code(Q){let{gen:Y,schema:X,data:W,it:G}=Q;if((0,MO.alwaysValidSchema)(G,X))return;let $=Y.name("valid");Y.forIn("key",W,(z)=>{Q.setParams({propertyName:z}),Q.subschema({keyword:"propertyNames",data:z,dataTypes:["string"],propertyName:z,compositeRule:!0},$),Y.if((0,k7.not)($),()=>{if(Q.error(!0),!G.allErrors)Y.break()})}),Q.ok($)}};v7.default=ZO});var jY=P((_7)=>{Object.defineProperty(_7,"__esModule",{value:!0});var LQ=C0(),h0=g(),wO=Y1(),FQ=c(),PO={message:"must NOT have additional properties",params:({params:Q})=>h0._`{additionalProperty: ${Q.additionalProperty}}`},bO={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:PO,code(Q){let{gen:Y,schema:X,parentSchema:W,data:G,errsCount:$,it:z}=Q;if(!$)throw Error("ajv implementation error");let{allErrors:J,opts:H}=z;if(z.props=!0,H.removeAdditional!=="all"&&(0,FQ.alwaysValidSchema)(z,X))return;let A=(0,LQ.allSchemaProperties)(W.properties),U=(0,LQ.allSchemaProperties)(W.patternProperties);K(),Q.ok(h0._`${$} === ${wO.default.errors}`);function K(){Y.forIn("key",G,(N)=>{if(!A.length&&!U.length)O(N);else Y.if(D(N),()=>O(N))})}function D(N){let Z;if(A.length>8){let k=(0,FQ.schemaRefOrVal)(z,W.properties,"properties");Z=(0,LQ.isOwnProperty)(Y,k,N)}else if(A.length)Z=(0,h0.or)(...A.map((k)=>h0._`${N} === ${k}`));else Z=h0.nil;if(U.length)Z=(0,h0.or)(Z,...U.map((k)=>h0._`${(0,LQ.usePattern)(Q,k)}.test(${N})`));return(0,h0.not)(Z)}function L(N){Y.code(h0._`delete ${G}[${N}]`)}function O(N){if(H.removeAdditional==="all"||H.removeAdditional&&X===!1){L(N);return}if(X===!1){if(Q.setParams({additionalProperty:N}),Q.error(),!J)Y.break();return}if(typeof X=="object"&&!(0,FQ.alwaysValidSchema)(z,X)){let Z=Y.name("valid");if(H.removeAdditional==="failing")M(N,Z,!1),Y.if((0,h0.not)(Z),()=>{Q.reset(),L(N)});else if(M(N,Z),!J)Y.if((0,h0.not)(Z),()=>Y.break())}}function M(N,Z,k){let S={keyword:"additionalProperties",dataProp:N,dataPropType:FQ.Type.Str};if(k===!1)Object.assign(S,{compositeRule:!0,createErrors:!1,allErrors:!1});Q.subschema(S,Z)}}};_7.default=bO});var h7=P((u7)=>{Object.defineProperty(u7,"__esModule",{value:!0});var IO=y4(),g7=C0(),IY=c(),y7=jY(),EO={keyword:"properties",type:"object",schemaType:"object",code(Q){let{gen:Y,schema:X,parentSchema:W,data:G,it:$}=Q;if($.opts.removeAdditional==="all"&&W.additionalProperties===void 0)y7.default.code(new IO.KeywordCxt($,y7.default,"additionalProperties"));let z=(0,g7.allSchemaProperties)(X);for(let K of z)$.definedProperties.add(K);if($.opts.unevaluated&&z.length&&$.props!==!0)$.props=IY.mergeEvaluated.props(Y,(0,IY.toHash)(z),$.props);let J=z.filter((K)=>!(0,IY.alwaysValidSchema)($,X[K]));if(J.length===0)return;let H=Y.name("valid");for(let K of J){if(A(K))U(K);else{if(Y.if((0,g7.propertyInData)(Y,G,K,$.opts.ownProperties)),U(K),!$.allErrors)Y.else().var(H,!0);Y.endIf()}Q.it.definedProperties.add(K),Q.ok(H)}function A(K){return $.opts.useDefaults&&!$.compositeRule&&X[K].default!==void 0}function U(K){Q.subschema({keyword:"properties",schemaProp:K,dataProp:K},H)}}};u7.default=EO});var p7=P((c7)=>{Object.defineProperty(c7,"__esModule",{value:!0});var f7=C0(),qQ=g(),l7=c(),m7=c(),SO={keyword:"patternProperties",type:"object",schemaType:"object",code(Q){let{gen:Y,schema:X,data:W,parentSchema:G,it:$}=Q,{opts:z}=$,J=(0,f7.allSchemaProperties)(X),H=J.filter((M)=>(0,l7.alwaysValidSchema)($,X[M]));if(J.length===0||H.length===J.length&&(!$.opts.unevaluated||$.props===!0))return;let A=z.strictSchema&&!z.allowMatchingProperties&&G.properties,U=Y.name("valid");if($.props!==!0&&!($.props instanceof qQ.Name))$.props=(0,m7.evaluatedPropsToName)(Y,$.props);let{props:K}=$;D();function D(){for(let M of J){if(A)L(M);if($.allErrors)O(M);else Y.var(U,!0),O(M),Y.if(U)}}function L(M){for(let N in A)if(new RegExp(M).test(N))(0,l7.checkStrictMode)($,`property ${N} matches pattern ${M} (use allowMatchingProperties)`)}function O(M){Y.forIn("key",W,(N)=>{Y.if(qQ._`${(0,f7.usePattern)(Q,M)}.test(${N})`,()=>{let Z=H.includes(M);if(!Z)Q.subschema({keyword:"patternProperties",schemaProp:M,dataProp:N,dataPropType:m7.Type.Str},U);if($.opts.unevaluated&&K!==!0)Y.assign(qQ._`${K}[${N}]`,!0);else if(!Z&&!$.allErrors)Y.if((0,qQ.not)(U),()=>Y.break())})})}}};c7.default=SO});var n7=P((i7)=>{Object.defineProperty(i7,"__esModule",{value:!0});var CO=c(),kO={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(Q){let{gen:Y,schema:X,it:W}=Q;if((0,CO.alwaysValidSchema)(W,X)){Q.fail();return}let G=Y.name("valid");Q.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},G),Q.failResult(G,()=>Q.reset(),()=>Q.error())},error:{message:"must NOT be valid"}};i7.default=kO});var d7=P((r7)=>{Object.defineProperty(r7,"__esModule",{value:!0});var xO=C0(),_O={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:xO.validateUnion,error:{message:"must match a schema in anyOf"}};r7.default=_O});var t7=P((o7)=>{Object.defineProperty(o7,"__esModule",{value:!0});var OQ=g(),yO=c(),uO={message:"must match exactly one schema in oneOf",params:({params:Q})=>OQ._`{passingSchemas: ${Q.passing}}`},hO={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:uO,code(Q){let{gen:Y,schema:X,parentSchema:W,it:G}=Q;if(!Array.isArray(X))throw Error("ajv implementation error");if(G.opts.discriminator&&W.discriminator)return;let $=X,z=Y.let("valid",!1),J=Y.let("passing",null),H=Y.name("_valid");Q.setParams({passing:J}),Y.block(A),Q.result(z,()=>Q.reset(),()=>Q.error(!0));function A(){$.forEach((U,K)=>{let D;if((0,yO.alwaysValidSchema)(G,U))Y.var(H,!0);else D=Q.subschema({keyword:"oneOf",schemaProp:K,compositeRule:!0},H);if(K>0)Y.if(OQ._`${H} && ${z}`).assign(z,!1).assign(J,OQ._`[${J}, ${K}]`).else();Y.if(H,()=>{if(Y.assign(z,!0),Y.assign(J,K),D)Q.mergeEvaluated(D,OQ.Name)})})}}};o7.default=hO});var s7=P((a7)=>{Object.defineProperty(a7,"__esModule",{value:!0});var lO=c(),mO={keyword:"allOf",schemaType:"array",code(Q){let{gen:Y,schema:X,it:W}=Q;if(!Array.isArray(X))throw Error("ajv implementation error");let G=Y.name("valid");X.forEach(($,z)=>{if((0,lO.alwaysValidSchema)(W,$))return;let J=Q.subschema({keyword:"allOf",schemaProp:z},G);Q.ok(G),Q.mergeEvaluated(J)})}};a7.default=mO});var X5=P((Y5)=>{Object.defineProperty(Y5,"__esModule",{value:!0});var MQ=g(),Q5=c(),pO={message:({params:Q})=>MQ.str`must match "${Q.ifClause}" schema`,params:({params:Q})=>MQ._`{failingKeyword: ${Q.ifClause}}`},iO={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:pO,code(Q){let{gen:Y,parentSchema:X,it:W}=Q;if(X.then===void 0&&X.else===void 0)(0,Q5.checkStrictMode)(W,'"if" without "then" and "else" is ignored');let G=e7(W,"then"),$=e7(W,"else");if(!G&&!$)return;let z=Y.let("valid",!0),J=Y.name("_valid");if(H(),Q.reset(),G&&$){let U=Y.let("ifClause");Q.setParams({ifClause:U}),Y.if(J,A("then",U),A("else",U))}else if(G)Y.if(J,A("then"));else Y.if((0,MQ.not)(J),A("else"));Q.pass(z,()=>Q.error(!0));function H(){let U=Q.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},J);Q.mergeEvaluated(U)}function A(U,K){return()=>{let D=Q.subschema({keyword:U},J);if(Y.assign(z,J),Q.mergeValidEvaluated(D,z),K)Y.assign(K,MQ._`${U}`);else Q.setParams({ifClause:U})}}}};function e7(Q,Y){let X=Q.schema[Y];return X!==void 0&&!(0,Q5.alwaysValidSchema)(Q,X)}Y5.default=iO});var G5=P((W5)=>{Object.defineProperty(W5,"__esModule",{value:!0});var rO=c(),dO={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:Q,parentSchema:Y,it:X}){if(Y.if===void 0)(0,rO.checkStrictMode)(X,`"${Q}" without "if" is ignored`)}};W5.default=dO});var z5=P(($5)=>{Object.defineProperty($5,"__esModule",{value:!0});var tO=wY(),aO=Z7(),sO=PY(),eO=P7(),QM=j7(),YM=C7(),XM=x7(),WM=jY(),GM=h7(),$M=p7(),zM=n7(),JM=d7(),HM=t7(),AM=s7(),UM=X5(),KM=G5();function DM(Q=!1){let Y=[zM.default,JM.default,HM.default,AM.default,UM.default,KM.default,XM.default,WM.default,YM.default,GM.default,$M.default];if(Q)Y.push(aO.default,eO.default);else Y.push(tO.default,sO.default);return Y.push(QM.default),Y}$5.default=DM});var H5=P((J5)=>{Object.defineProperty(J5,"__esModule",{value:!0});var $0=g(),LM={message:({schemaCode:Q})=>$0.str`must match format "${Q}"`,params:({schemaCode:Q})=>$0._`{format: ${Q}}`},FM={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:LM,code(Q,Y){let{gen:X,data:W,$data:G,schema:$,schemaCode:z,it:J}=Q,{opts:H,errSchemaPath:A,schemaEnv:U,self:K}=J;if(!H.validateFormats)return;if(G)D();else L();function D(){let O=X.scopeValue("formats",{ref:K.formats,code:H.code.formats}),M=X.const("fDef",$0._`${O}[${z}]`),N=X.let("fType"),Z=X.let("format");X.if($0._`typeof ${M} == "object" && !(${M} instanceof RegExp)`,()=>X.assign(N,$0._`${M}.type || "string"`).assign(Z,$0._`${M}.validate`),()=>X.assign(N,$0._`"string"`).assign(Z,M)),Q.fail$data((0,$0.or)(k(),S()));function k(){if(H.strictSchema===!1)return $0.nil;return $0._`${z} && !${Z}`}function S(){let y=U.$async?$0._`(${M}.async ? await ${Z}(${W}) : ${Z}(${W}))`:$0._`${Z}(${W})`,C=$0._`(typeof ${Z} == "function" ? ${y} : ${Z}.test(${W}))`;return $0._`${Z} && ${Z} !== true && ${N} === ${Y} && !${C}`}}function L(){let O=K.formats[$];if(!O){k();return}if(O===!0)return;let[M,N,Z]=S(O);if(M===Y)Q.pass(y());function k(){if(H.strictSchema===!1){K.logger.warn(C());return}throw Error(C());function C(){return`unknown format "${$}" ignored in schema at path "${A}"`}}function S(C){let c0=C instanceof RegExp?(0,$0.regexpCode)(C):H.code.formats?$0._`${H.code.formats}${(0,$0.getProperty)($)}`:void 0,o0=X.scopeValue("formats",{key:$,ref:C,code:c0});if(typeof C=="object"&&!(C instanceof RegExp))return[C.type||"string",C.validate,$0._`${o0}.validate`];return["string",C,o0]}function y(){if(typeof O=="object"&&!(O instanceof RegExp)&&O.async){if(!U.$async)throw Error("async format in sync schema");return $0._`await ${Z}(${W})`}return typeof N=="function"?$0._`${Z}(${W})`:$0._`${Z}.test(${W})`}}}};J5.default=FM});var U5=P((A5)=>{Object.defineProperty(A5,"__esModule",{value:!0});var OM=H5(),MM=[OM.default];A5.default=MM});var B5=P((K5)=>{Object.defineProperty(K5,"__esModule",{value:!0});K5.contentVocabulary=K5.metadataVocabulary=void 0;K5.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];K5.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var q5=P((F5)=>{Object.defineProperty(F5,"__esModule",{value:!0});var NM=uJ(),wM=K7(),PM=z5(),bM=U5(),L5=B5(),jM=[NM.default,wM.default,(0,PM.default)(),bM.default,L5.metadataVocabulary,L5.contentVocabulary];F5.default=jM});var Z5=P((M5)=>{Object.defineProperty(M5,"__esModule",{value:!0});M5.DiscrError=void 0;var O5;(function(Q){Q.Tag="tag",Q.Mapping="mapping"})(O5||(M5.DiscrError=O5={}))});var P5=P((w5)=>{Object.defineProperty(w5,"__esModule",{value:!0});var a1=g(),EY=Z5(),N5=e6(),EM=u4(),TM=c(),SM={message:({params:{discrError:Q,tagName:Y}})=>Q===EY.DiscrError.Tag?`tag "${Y}" must be string`:`value of tag "${Y}" must be in oneOf`,params:({params:{discrError:Q,tag:Y,tagName:X}})=>a1._`{error: ${Q}, tag: ${X}, tagValue: ${Y}}`},RM={keyword:"discriminator",type:"object",schemaType:"object",error:SM,code(Q){let{gen:Y,data:X,schema:W,parentSchema:G,it:$}=Q,{oneOf:z}=G;if(!$.opts.discriminator)throw Error("discriminator: requires discriminator option");let J=W.propertyName;if(typeof J!="string")throw Error("discriminator: requires propertyName");if(W.mapping)throw Error("discriminator: mapping is not supported");if(!z)throw Error("discriminator: requires oneOf keyword");let H=Y.let("valid",!1),A=Y.const("tag",a1._`${X}${(0,a1.getProperty)(J)}`);Y.if(a1._`typeof ${A} == "string"`,()=>U(),()=>Q.error(!1,{discrError:EY.DiscrError.Tag,tag:A,tagName:J})),Q.ok(H);function U(){let L=D();Y.if(!1);for(let O in L)Y.elseIf(a1._`${A} === ${O}`),Y.assign(H,K(L[O]));Y.else(),Q.error(!1,{discrError:EY.DiscrError.Mapping,tag:A,tagName:J}),Y.endIf()}function K(L){let O=Y.name("valid"),M=Q.subschema({keyword:"oneOf",schemaProp:L},O);return Q.mergeEvaluated(M,a1.Name),O}function D(){var L;let O={},M=Z(G),N=!0;for(let y=0;y<z.length;y++){let C=z[y];if((C===null||C===void 0?void 0:C.$ref)&&!(0,TM.schemaHasRulesButRef)(C,$.self.RULES)){let o0=C.$ref;if(C=N5.resolveRef.call($.self,$.schemaEnv.root,$.baseId,o0),C instanceof N5.SchemaEnv)C=C.schema;if(C===void 0)throw new EM.default($.opts.uriResolver,$.baseId,o0)}let c0=(L=C===null||C===void 0?void 0:C.properties)===null||L===void 0?void 0:L[J];if(typeof c0!="object")throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${J}"`);N=N&&(M||Z(C)),k(c0,y)}if(!N)throw Error(`discriminator: "${J}" must be required`);return O;function Z({required:y}){return Array.isArray(y)&&y.includes(J)}function k(y,C){if(y.const)S(y.const,C);else if(y.enum)for(let c0 of y.enum)S(c0,C);else throw Error(`discriminator: "properties/${J}" must have "const" or "enum"`)}function S(y,C){if(typeof y!="string"||y in O)throw Error(`discriminator: "${J}" values must be unique strings`);O[y]=C}}}};w5.default=RM});var b5=P((hE,kM)=>{kM.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 SY=P((P0,TY)=>{Object.defineProperty(P0,"__esModule",{value:!0});P0.MissingRefError=P0.ValidationError=P0.CodeGen=P0.Name=P0.nil=P0.stringify=P0.str=P0._=P0.KeywordCxt=P0.Ajv=void 0;var vM=TJ(),xM=q5(),_M=P5(),j5=b5(),gM=["/properties"],VQ="http://json-schema.org/draft-07/schema";class t4 extends vM.default{_addVocabularies(){if(super._addVocabularies(),xM.default.forEach((Q)=>this.addVocabulary(Q)),this.opts.discriminator)this.addKeyword(_M.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let Q=this.opts.$data?this.$dataMetaSchema(j5,gM):j5;this.addMetaSchema(Q,VQ,!1),this.refs["http://json-schema.org/schema"]=VQ}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(VQ)?VQ:void 0)}}P0.Ajv=t4;TY.exports=P0=t4;TY.exports.Ajv=t4;Object.defineProperty(P0,"__esModule",{value:!0});P0.default=t4;var yM=y4();Object.defineProperty(P0,"KeywordCxt",{enumerable:!0,get:function(){return yM.KeywordCxt}});var s1=g();Object.defineProperty(P0,"_",{enumerable:!0,get:function(){return s1._}});Object.defineProperty(P0,"str",{enumerable:!0,get:function(){return s1.str}});Object.defineProperty(P0,"stringify",{enumerable:!0,get:function(){return s1.stringify}});Object.defineProperty(P0,"nil",{enumerable:!0,get:function(){return s1.nil}});Object.defineProperty(P0,"Name",{enumerable:!0,get:function(){return s1.Name}});Object.defineProperty(P0,"CodeGen",{enumerable:!0,get:function(){return s1.CodeGen}});var uM=a6();Object.defineProperty(P0,"ValidationError",{enumerable:!0,get:function(){return uM.default}});var hM=u4();Object.defineProperty(P0,"MissingRefError",{enumerable:!0,get:function(){return hM.default}})});var _5=P((v5)=>{Object.defineProperty(v5,"__esModule",{value:!0});v5.formatNames=v5.fastFormats=v5.fullFormats=void 0;function n0(Q,Y){return{validate:Q,compare:Y}}v5.fullFormats={date:n0(S5,vY),time:n0(CY(!0),xY),"date-time":n0(I5(!0),C5),"iso-time":n0(CY(),R5),"iso-date-time":n0(I5(),k5),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:rM,"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:QV,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:dM,int32:{type:"number",validate:aM},int64:{type:"number",validate:sM},float:{type:"number",validate:T5},double:{type:"number",validate:T5},password:!0,binary:!0};v5.fastFormats={...v5.fullFormats,date:n0(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,vY),time:n0(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,xY),"date-time":n0(/^\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,C5),"iso-time":n0(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,R5),"iso-date-time":n0(/^\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,k5),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};v5.formatNames=Object.keys(v5.fullFormats);function mM(Q){return Q%4===0&&(Q%100!==0||Q%400===0)}var cM=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,pM=[0,31,28,31,30,31,30,31,31,30,31,30,31];function S5(Q){let Y=cM.exec(Q);if(!Y)return!1;let X=+Y[1],W=+Y[2],G=+Y[3];return W>=1&&W<=12&&G>=1&&G<=(W===2&&mM(X)?29:pM[W])}function vY(Q,Y){if(!(Q&&Y))return;if(Q>Y)return 1;if(Q<Y)return-1;return 0}var RY=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function CY(Q){return function(X){let W=RY.exec(X);if(!W)return!1;let G=+W[1],$=+W[2],z=+W[3],J=W[4],H=W[5]==="-"?-1:1,A=+(W[6]||0),U=+(W[7]||0);if(A>23||U>59||Q&&!J)return!1;if(G<=23&&$<=59&&z<60)return!0;let K=$-U*H,D=G-A*H-(K<0?1:0);return(D===23||D===-1)&&(K===59||K===-1)&&z<61}}function xY(Q,Y){if(!(Q&&Y))return;let X=new Date("2020-01-01T"+Q).valueOf(),W=new Date("2020-01-01T"+Y).valueOf();if(!(X&&W))return;return X-W}function R5(Q,Y){if(!(Q&&Y))return;let X=RY.exec(Q),W=RY.exec(Y);if(!(X&&W))return;if(Q=X[1]+X[2]+X[3],Y=W[1]+W[2]+W[3],Q>Y)return 1;if(Q<Y)return-1;return 0}var kY=/t|\s/i;function I5(Q){let Y=CY(Q);return function(W){let G=W.split(kY);return G.length===2&&S5(G[0])&&Y(G[1])}}function C5(Q,Y){if(!(Q&&Y))return;let X=new Date(Q).valueOf(),W=new Date(Y).valueOf();if(!(X&&W))return;return X-W}function k5(Q,Y){if(!(Q&&Y))return;let[X,W]=Q.split(kY),[G,$]=Y.split(kY),z=vY(X,G);if(z===void 0)return;return z||xY(W,$)}var iM=/\/|:/,nM=/^(?:[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 rM(Q){return iM.test(Q)&&nM.test(Q)}var E5=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function dM(Q){return E5.lastIndex=0,E5.test(Q)}var oM=-2147483648,tM=2147483647;function aM(Q){return Number.isInteger(Q)&&Q<=tM&&Q>=oM}function sM(Q){return Number.isInteger(Q)}function T5(){return!0}var eM=/[^\\]\\Z/;function QV(Q){if(eM.test(Q))return!1;try{return new RegExp(Q),!0}catch(Y){return!1}}});var y5=P((g5)=>{Object.defineProperty(g5,"__esModule",{value:!0});g5.formatLimitDefinition=void 0;var XV=SY(),f0=g(),V1=f0.operators,ZQ={formatMaximum:{okStr:"<=",ok:V1.LTE,fail:V1.GT},formatMinimum:{okStr:">=",ok:V1.GTE,fail:V1.LT},formatExclusiveMaximum:{okStr:"<",ok:V1.LT,fail:V1.GTE},formatExclusiveMinimum:{okStr:">",ok:V1.GT,fail:V1.LTE}},WV={message:({keyword:Q,schemaCode:Y})=>f0.str`should be ${ZQ[Q].okStr} ${Y}`,params:({keyword:Q,schemaCode:Y})=>f0._`{comparison: ${ZQ[Q].okStr}, limit: ${Y}}`};g5.formatLimitDefinition={keyword:Object.keys(ZQ),type:"string",schemaType:"string",$data:!0,error:WV,code(Q){let{gen:Y,data:X,schemaCode:W,keyword:G,it:$}=Q,{opts:z,self:J}=$;if(!z.validateFormats)return;let H=new XV.KeywordCxt($,J.RULES.all.format.definition,"format");if(H.$data)A();else U();function A(){let D=Y.scopeValue("formats",{ref:J.formats,code:z.code.formats}),L=Y.const("fmt",f0._`${D}[${H.schemaCode}]`);Q.fail$data((0,f0.or)(f0._`typeof ${L} != "object"`,f0._`${L} instanceof RegExp`,f0._`typeof ${L}.compare != "function"`,K(L)))}function U(){let D=H.schema,L=J.formats[D];if(!L||L===!0)return;if(typeof L!="object"||L instanceof RegExp||typeof L.compare!="function")throw Error(`"${G}": format "${D}" does not define "compare" function`);let O=Y.scopeValue("formats",{key:D,ref:L,code:z.code.formats?f0._`${z.code.formats}${(0,f0.getProperty)(D)}`:void 0});Q.fail$data(K(O))}function K(D){return f0._`${D}.compare(${X}, ${W}) ${ZQ[G].fail} 0`}},dependencies:["format"]};var GV=(Q)=>{return Q.addKeyword(g5.formatLimitDefinition),Q};g5.default=GV});var l5=P((a4,f5)=>{Object.defineProperty(a4,"__esModule",{value:!0});var e1=_5(),zV=y5(),yY=g(),u5=new yY.Name("fullFormats"),JV=new yY.Name("fastFormats"),uY=(Q,Y={keywords:!0})=>{if(Array.isArray(Y))return h5(Q,Y,e1.fullFormats,u5),Q;let[X,W]=Y.mode==="fast"?[e1.fastFormats,JV]:[e1.fullFormats,u5],G=Y.formats||e1.formatNames;if(h5(Q,G,X,W),Y.keywords)(0,zV.default)(Q);return Q};uY.get=(Q,Y="full")=>{let W=(Y==="fast"?e1.fastFormats:e1.fullFormats)[Q];if(!W)throw Error(`Unknown format "${Q}"`);return W};function h5(Q,Y,X,W){var G,$;(G=($=Q.opts.code).formats)!==null&&G!==void 0||($.formats=yY._`require("ajv-formats/dist/formats").${W}`);for(let z of Y)Q.addFormat(z,X[z])}f5.exports=a4=uY;Object.defineProperty(a4,"__esModule",{value:!0});a4.default=uY});import{AsyncLocalStorage as xH}from"node:async_hooks";class P1 extends Error{statusCode;rawDetails;code;context;constructor(Q,Y,X,W,G){super(Q);this.statusCode=Y;this.rawDetails=X;this.code=W;this.context=G;this.name="McpApiError"}}function CH(Q){if(Q instanceof P1)return{message:Q.message,statusCode:Q.statusCode,code:Q.code,rawDetails:Q.rawDetails,context:Q.context};if(Q instanceof Error)return{message:Q.message};return{message:String(Q)}}function kH(Q){let Y=Q.match(/api key is missing required scopes?:\s*(.+)$/i);if(!Y?.[1])return[];return Y[1].match(/[a-z_]+:[a-z_]+/gi)??[]}function vH(Q){let Y=CH(Q),X=Y.message.trim()||"Unknown error",W=X.toLowerCase(),G=Y.rawDetails?.trim()||X;if(Y.context?.title||Y.context?.description||Y.context?.howToFix||Y.context?.docsUrl)return{title:Y.context.title??(Y.statusCode===409?"Request conflict":"API request failed"),description:Y.context.description??X,howToFix:Y.context.howToFix??"Review the details below, adjust the tool input, and retry.",docsUrl:Y.context.docsUrl??"https://docs.sequenzy.com/concepts/mcp",details:G};if(Y.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:G};if(Y.statusCode===401||Y.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:G};let $=kH(X);if($.length>0){let z=$.map((H)=>`\`${H}\``).join(", "),J=$.every((H)=>H.endsWith(":read"))?"the Read-only or Safer agent access preset":"Safer agent access when it covers the task, or Custom permissions";return{title:"API key permission required",description:`The current API key is valid, but this operation requires the missing ${$.length===1?"scope":"scopes"}: ${z}.`,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 ${J} including ${z}, 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 ${z}. Existing key permissions cannot be edited in place.`,docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:G}}if(Y.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:G};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:G};if(Y.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:G};if(Y.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:G};if(Y.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:G};if(Y.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:G};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:G};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:G};if(Y.statusCode&&Y.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:G};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:G}}function $1(Q){let Y=vH(Q);return[`Sequenzy MCP error: ${Y.title}`,`Description: ${Y.description}`,`How to fix: ${Y.howToFix}`,`Docs: ${Y.docsUrl}`,`Details: ${Y.details}`].join(`
10
+ `)}var _H="https://api.sequenzy.com",W4=new xH,OX=!1;function MX(){OX=!0}function VX(){return OX}var ZX=null;function b1(){let Q=W4.getStore();if(Q)return Q.selectedCompanyId??null;return ZX}function Q6(Q){let Y=W4.getStore();if(Y){Y.selectedCompanyId=Q;return}ZX=Q}function SQ(Q,Y){return W4.run(Q,Y)}function gH(){return W4.getStore()?.apiUrl??process.env.SEQUENZY_API_URL??_H}function NX(){return W4.getStore()?.apiKey??process.env.SEQUENZY_API_KEY}function wX(){if(NX())return;console.error($1(new P1("SEQUENZY_API_KEY environment variable is required",401,void 0,"MCP_AUTH_REQUIRED"))),process.exit(1)}function j0(Q,Y){let X=Q[Y];return typeof X==="string"&&X.trim()!==""?X.trim():void 0}function yH(Q){if(Q===void 0)return;if(typeof Q==="string")return Q.trim()||void 0;return JSON.stringify(Q)}function uH(Q){if(!Q.trim())return{message:"Request failed"};try{let Y=JSON.parse(Q);if(typeof Y==="string")return{message:Y};let X=typeof Y.error==="object"&&Y.error!==null?Y.error:void 0,W=j0(Y,"code")??(X?j0(X,"code"):void 0),G=(typeof Y.error==="string"?Y.error:void 0)??(X?j0(X,"message"):void 0)??j0(Y,"message")??j0(Y,"error")??Q,$=j0(Y,"howToFix")??j0(Y,"resolution"),z={...j0(Y,"title")?{title:j0(Y,"title")}:{},...j0(Y,"description")?{description:j0(Y,"description")}:{},...$?{howToFix:$}:{},...j0(Y,"docsUrl")?{docsUrl:j0(Y,"docsUrl")}:{}},J=yH(Y.details);if(Object.keys(z).length>0||J)return{message:G,...W?{code:W}:{},...J?{details:J}:{},...Object.keys(z).length>0?{context:z}:{}};if(typeof Y.error==="string")return{message:Y.error,...W?{code:W}:{}};if(X)return{message:G,...W?{code:W}:{}};return{message:G,...W?{code:W}:{}}}catch{return{message:Q}}}async function B(Q,Y,X,W){let G=NX();if(!G)throw new P1("SEQUENZY_API_KEY environment variable is required",401,void 0,"MCP_AUTH_REQUIRED");let $={"Content-Type":"application/json",Authorization:`Bearer ${G}`},z=W??b1();if(z)$["x-company-id"]=z;let J;try{J=await fetch(`${gH()}${Y}`,{method:Q,headers:$,body:X?JSON.stringify(X):void 0})}catch(H){throw new P1(H instanceof Error?H.message:"Failed to reach Sequenzy API",0,void 0,"NETWORK_ERROR")}if(!J.ok){let H=await J.text(),A=uH(H);throw new P1(A.message,J.status,A.details??H,A.code,A.context)}return J.json()}var IZ=Object.freeze({status:"aborted"});function q(Q,Y,X){function W(J,H){var A;Object.defineProperty(J,"_zod",{value:J._zod??{},enumerable:!1}),(A=J._zod).traits??(A.traits=new Set),J._zod.traits.add(Q),Y(J,H);for(let U in z.prototype)if(!(U in J))Object.defineProperty(J,U,{value:z.prototype[U].bind(J)});J._zod.constr=z,J._zod.def=H}let G=X?.Parent??Object;class $ extends G{}Object.defineProperty($,"name",{value:Q});function z(J){var H;let A=X?.Parent?new $:this;W(A,J),(H=A._zod).deferred??(H.deferred=[]);for(let U of A._zod.deferred)U();return A}return Object.defineProperty(z,"init",{value:W}),Object.defineProperty(z,Symbol.hasInstance,{value:(J)=>{if(X?.Parent&&J instanceof X.Parent)return!0;return J?._zod?.traits?.has(Q)}}),Object.defineProperty(z,"name",{value:Q}),z}var EZ=Symbol("zod_brand");class t0 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class G4 extends Error{constructor(Q){super(`Encountered unidirectional transform during encode: ${Q}`);this.name="ZodEncodeError"}}var Y6={};function T0(Q){if(Q)Object.assign(Y6,Q);return Y6}var m={};qX(m,{unwrapMessage:()=>$4,uint8ArrayToHex:()=>AA,uint8ArrayToBase64url:()=>JA,uint8ArrayToBase64:()=>SX,stringifyPrimitive:()=>$6,shallowClone:()=>bX,safeExtend:()=>YA,required:()=>GA,randomString:()=>dH,propertyKeyTypes:()=>xQ,promiseAllObject:()=>rH,primitiveTypes:()=>jX,prefixIssues:()=>s0,pick:()=>sH,partial:()=>WA,optionalKeys:()=>_Q,omit:()=>eH,objectClone:()=>pH,numKeys:()=>oH,nullish:()=>z4,normalizeParams:()=>T,mergeDefs:()=>J1,merge:()=>XA,jsonStringifyReplacer:()=>_1,joinValues:()=>X6,issue:()=>y1,isPlainObject:()=>H1,isObject:()=>j1,hexToUint8Array:()=>HA,getSizableOrigin:()=>EX,getParsedType:()=>tH,getLengthableOrigin:()=>H4,getEnumValues:()=>CQ,getElementAtPath:()=>nH,floatSafeRemainder:()=>kQ,finalizeIssue:()=>x0,extend:()=>QA,escapeRegex:()=>a0,esc:()=>W6,defineLazy:()=>n,createTransparentProxy:()=>aH,cloneDef:()=>iH,clone:()=>v0,cleanRegex:()=>J4,cleanEnum:()=>$A,captureStackTrace:()=>G6,cached:()=>g1,base64urlToUint8Array:()=>zA,base64ToUint8Array:()=>TX,assignProp:()=>z1,assertNotEqual:()=>fH,assertNever:()=>mH,assertIs:()=>lH,assertEqual:()=>hH,assert:()=>cH,allowsEval:()=>vQ,aborted:()=>A1,NUMBER_FORMAT_RANGES:()=>gQ,Class:()=>RX,BIGINT_FORMAT_RANGES:()=>IX});function hH(Q){return Q}function fH(Q){return Q}function lH(Q){}function mH(Q){throw Error()}function cH(Q){}function CQ(Q){let Y=Object.values(Q).filter((W)=>typeof W==="number");return Object.entries(Q).filter(([W,G])=>Y.indexOf(+W)===-1).map(([W,G])=>G)}function X6(Q,Y="|"){return Q.map((X)=>$6(X)).join(Y)}function _1(Q,Y){if(typeof Y==="bigint")return Y.toString();return Y}function g1(Q){return{get value(){{let X=Q();return Object.defineProperty(this,"value",{value:X}),X}throw Error("cached value already set")}}}function z4(Q){return Q===null||Q===void 0}function J4(Q){let Y=Q.startsWith("^")?1:0,X=Q.endsWith("$")?Q.length-1:Q.length;return Q.slice(Y,X)}function kQ(Q,Y){let X=(Q.toString().split(".")[1]||"").length,W=Y.toString(),G=(W.split(".")[1]||"").length;if(G===0&&/\d?e-\d?/.test(W)){let H=W.match(/\d?e-(\d?)/);if(H?.[1])G=Number.parseInt(H[1])}let $=X>G?X:G,z=Number.parseInt(Q.toFixed($).replace(".","")),J=Number.parseInt(Y.toFixed($).replace(".",""));return z%J/10**$}var PX=Symbol("evaluating");function n(Q,Y,X){let W=void 0;Object.defineProperty(Q,Y,{get(){if(W===PX)return;if(W===void 0)W=PX,W=X();return W},set(G){Object.defineProperty(Q,Y,{value:G})},configurable:!0})}function pH(Q){return Object.create(Object.getPrototypeOf(Q),Object.getOwnPropertyDescriptors(Q))}function z1(Q,Y,X){Object.defineProperty(Q,Y,{value:X,writable:!0,enumerable:!0,configurable:!0})}function J1(...Q){let Y={};for(let X of Q){let W=Object.getOwnPropertyDescriptors(X);Object.assign(Y,W)}return Object.defineProperties({},Y)}function iH(Q){return J1(Q._zod.def)}function nH(Q,Y){if(!Y)return Q;return Y.reduce((X,W)=>X?.[W],Q)}function rH(Q){let Y=Object.keys(Q),X=Y.map((W)=>Q[W]);return Promise.all(X).then((W)=>{let G={};for(let $=0;$<Y.length;$++)G[Y[$]]=W[$];return G})}function dH(Q=10){let X="";for(let W=0;W<Q;W++)X+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return X}function W6(Q){return JSON.stringify(Q)}var G6="captureStackTrace"in Error?Error.captureStackTrace:(...Q)=>{};function j1(Q){return typeof Q==="object"&&Q!==null&&!Array.isArray(Q)}var vQ=g1(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(Q){return!1}});function H1(Q){if(j1(Q)===!1)return!1;let Y=Q.constructor;if(Y===void 0)return!0;let X=Y.prototype;if(j1(X)===!1)return!1;if(Object.prototype.hasOwnProperty.call(X,"isPrototypeOf")===!1)return!1;return!0}function bX(Q){if(H1(Q))return{...Q};if(Array.isArray(Q))return[...Q];return Q}function oH(Q){let Y=0;for(let X in Q)if(Object.prototype.hasOwnProperty.call(Q,X))Y++;return Y}var tH=(Q)=>{let Y=typeof Q;switch(Y){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(Q)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(Q))return"array";if(Q===null)return"null";if(Q.then&&typeof Q.then==="function"&&Q.catch&&typeof Q.catch==="function")return"promise";if(typeof Map<"u"&&Q instanceof Map)return"map";if(typeof Set<"u"&&Q instanceof Set)return"set";if(typeof Date<"u"&&Q instanceof Date)return"date";if(typeof File<"u"&&Q instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${Y}`)}},xQ=new Set(["string","number","symbol"]),jX=new Set(["string","number","bigint","boolean","symbol","undefined"]);function a0(Q){return Q.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function v0(Q,Y,X){let W=new Q._zod.constr(Y??Q._zod.def);if(!Y||X?.parent)W._zod.parent=Q;return W}function T(Q){let Y=Q;if(!Y)return{};if(typeof Y==="string")return{error:()=>Y};if(Y?.message!==void 0){if(Y?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");Y.error=Y.message}if(delete Y.message,typeof Y.error==="string")return{...Y,error:()=>Y.error};return Y}function aH(Q){let Y;return new Proxy({},{get(X,W,G){return Y??(Y=Q()),Reflect.get(Y,W,G)},set(X,W,G,$){return Y??(Y=Q()),Reflect.set(Y,W,G,$)},has(X,W){return Y??(Y=Q()),Reflect.has(Y,W)},deleteProperty(X,W){return Y??(Y=Q()),Reflect.deleteProperty(Y,W)},ownKeys(X){return Y??(Y=Q()),Reflect.ownKeys(Y)},getOwnPropertyDescriptor(X,W){return Y??(Y=Q()),Reflect.getOwnPropertyDescriptor(Y,W)},defineProperty(X,W,G){return Y??(Y=Q()),Reflect.defineProperty(Y,W,G)}})}function $6(Q){if(typeof Q==="bigint")return Q.toString()+"n";if(typeof Q==="string")return`"${Q}"`;return`${Q}`}function _Q(Q){return Object.keys(Q).filter((Y)=>{return Q[Y]._zod.optin==="optional"&&Q[Y]._zod.optout==="optional"})}var gQ={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]},IX={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function sH(Q,Y){let X=Q._zod.def,W=J1(Q._zod.def,{get shape(){let G={};for(let $ in Y){if(!($ in X.shape))throw Error(`Unrecognized key: "${$}"`);if(!Y[$])continue;G[$]=X.shape[$]}return z1(this,"shape",G),G},checks:[]});return v0(Q,W)}function eH(Q,Y){let X=Q._zod.def,W=J1(Q._zod.def,{get shape(){let G={...Q._zod.def.shape};for(let $ in Y){if(!($ in X.shape))throw Error(`Unrecognized key: "${$}"`);if(!Y[$])continue;delete G[$]}return z1(this,"shape",G),G},checks:[]});return v0(Q,W)}function QA(Q,Y){if(!H1(Y))throw Error("Invalid input to extend: expected a plain object");let X=Q._zod.def.checks;if(X&&X.length>0)throw Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");let G=J1(Q._zod.def,{get shape(){let $={...Q._zod.def.shape,...Y};return z1(this,"shape",$),$},checks:[]});return v0(Q,G)}function YA(Q,Y){if(!H1(Y))throw Error("Invalid input to safeExtend: expected a plain object");let X={...Q._zod.def,get shape(){let W={...Q._zod.def.shape,...Y};return z1(this,"shape",W),W},checks:Q._zod.def.checks};return v0(Q,X)}function XA(Q,Y){let X=J1(Q._zod.def,{get shape(){let W={...Q._zod.def.shape,...Y._zod.def.shape};return z1(this,"shape",W),W},get catchall(){return Y._zod.def.catchall},checks:[]});return v0(Q,X)}function WA(Q,Y,X){let W=J1(Y._zod.def,{get shape(){let G=Y._zod.def.shape,$={...G};if(X)for(let z in X){if(!(z in G))throw Error(`Unrecognized key: "${z}"`);if(!X[z])continue;$[z]=Q?new Q({type:"optional",innerType:G[z]}):G[z]}else for(let z in G)$[z]=Q?new Q({type:"optional",innerType:G[z]}):G[z];return z1(this,"shape",$),$},checks:[]});return v0(Y,W)}function GA(Q,Y,X){let W=J1(Y._zod.def,{get shape(){let G=Y._zod.def.shape,$={...G};if(X)for(let z in X){if(!(z in $))throw Error(`Unrecognized key: "${z}"`);if(!X[z])continue;$[z]=new Q({type:"nonoptional",innerType:G[z]})}else for(let z in G)$[z]=new Q({type:"nonoptional",innerType:G[z]});return z1(this,"shape",$),$},checks:[]});return v0(Y,W)}function A1(Q,Y=0){if(Q.aborted===!0)return!0;for(let X=Y;X<Q.issues.length;X++)if(Q.issues[X]?.continue!==!0)return!0;return!1}function s0(Q,Y){return Y.map((X)=>{var W;return(W=X).path??(W.path=[]),X.path.unshift(Q),X})}function $4(Q){return typeof Q==="string"?Q:Q?.message}function x0(Q,Y,X){let W={...Q,path:Q.path??[]};if(!Q.message){let G=$4(Q.inst?._zod.def?.error?.(Q))??$4(Y?.error?.(Q))??$4(X.customError?.(Q))??$4(X.localeError?.(Q))??"Invalid input";W.message=G}if(delete W.inst,delete W.continue,!Y?.reportInput)delete W.input;return W}function EX(Q){if(Q instanceof Set)return"set";if(Q instanceof Map)return"map";if(Q instanceof File)return"file";return"unknown"}function H4(Q){if(Array.isArray(Q))return"array";if(typeof Q==="string")return"string";return"unknown"}function y1(...Q){let[Y,X,W]=Q;if(typeof Y==="string")return{message:Y,code:"custom",input:X,inst:W};return{...Y}}function $A(Q){return Object.entries(Q).filter(([Y,X])=>{return Number.isNaN(Number.parseInt(Y,10))}).map((Y)=>Y[1])}function TX(Q){let Y=atob(Q),X=new Uint8Array(Y.length);for(let W=0;W<Y.length;W++)X[W]=Y.charCodeAt(W);return X}function SX(Q){let Y="";for(let X=0;X<Q.length;X++)Y+=String.fromCharCode(Q[X]);return btoa(Y)}function zA(Q){let Y=Q.replace(/-/g,"+").replace(/_/g,"/"),X="=".repeat((4-Y.length%4)%4);return TX(Y+X)}function JA(Q){return SX(Q).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function HA(Q){let Y=Q.replace(/^0x/,"");if(Y.length%2!==0)throw Error("Invalid hex string length");let X=new Uint8Array(Y.length/2);for(let W=0;W<Y.length;W+=2)X[W/2]=Number.parseInt(Y.slice(W,W+2),16);return X}function AA(Q){return Array.from(Q).map((Y)=>Y.toString(16).padStart(2,"0")).join("")}class RX{constructor(...Q){}}var CX=(Q,Y)=>{Q.name="$ZodError",Object.defineProperty(Q,"_zod",{value:Q._zod,enumerable:!1}),Object.defineProperty(Q,"issues",{value:Y,enumerable:!1}),Q.message=JSON.stringify(Y,_1,2),Object.defineProperty(Q,"toString",{value:()=>Q.message,enumerable:!1})},z6=q("$ZodError",CX),yQ=q("$ZodError",CX,{Parent:Error});function kX(Q,Y=(X)=>X.message){let X={},W=[];for(let G of Q.issues)if(G.path.length>0)X[G.path[0]]=X[G.path[0]]||[],X[G.path[0]].push(Y(G));else W.push(Y(G));return{formErrors:W,fieldErrors:X}}function vX(Q,Y=(X)=>X.message){let X={_errors:[]},W=(G)=>{for(let $ of G.issues)if($.code==="invalid_union"&&$.errors.length)$.errors.map((z)=>W({issues:z}));else if($.code==="invalid_key")W({issues:$.issues});else if($.code==="invalid_element")W({issues:$.issues});else if($.path.length===0)X._errors.push(Y($));else{let z=X,J=0;while(J<$.path.length){let H=$.path[J];if(J!==$.path.length-1)z[H]=z[H]||{_errors:[]};else z[H]=z[H]||{_errors:[]},z[H]._errors.push(Y($));z=z[H],J++}}};return W(Q),X}var J6=(Q)=>(Y,X,W,G)=>{let $=W?Object.assign(W,{async:!1}):{async:!1},z=Y._zod.run({value:X,issues:[]},$);if(z instanceof Promise)throw new t0;if(z.issues.length){let J=new(G?.Err??Q)(z.issues.map((H)=>x0(H,$,T0())));throw G6(J,G?.callee),J}return z.value};var H6=(Q)=>async(Y,X,W,G)=>{let $=W?Object.assign(W,{async:!0}):{async:!0},z=Y._zod.run({value:X,issues:[]},$);if(z instanceof Promise)z=await z;if(z.issues.length){let J=new(G?.Err??Q)(z.issues.map((H)=>x0(H,$,T0())));throw G6(J,G?.callee),J}return z.value};var A4=(Q)=>(Y,X,W)=>{let G=W?{...W,async:!1}:{async:!1},$=Y._zod.run({value:X,issues:[]},G);if($ instanceof Promise)throw new t0;return $.issues.length?{success:!1,error:new(Q??z6)($.issues.map((z)=>x0(z,G,T0())))}:{success:!0,data:$.value}},U4=A4(yQ),K4=(Q)=>async(Y,X,W)=>{let G=W?Object.assign(W,{async:!0}):{async:!0},$=Y._zod.run({value:X,issues:[]},G);if($ instanceof Promise)$=await $;return $.issues.length?{success:!1,error:new Q($.issues.map((z)=>x0(z,G,T0())))}:{success:!0,data:$.value}},A6=K4(yQ),xX=(Q)=>(Y,X,W)=>{let G=W?Object.assign(W,{direction:"backward"}):{direction:"backward"};return J6(Q)(Y,X,G)};var _X=(Q)=>(Y,X,W)=>{return J6(Q)(Y,X,W)};var gX=(Q)=>async(Y,X,W)=>{let G=W?Object.assign(W,{direction:"backward"}):{direction:"backward"};return H6(Q)(Y,X,G)};var yX=(Q)=>async(Y,X,W)=>{return H6(Q)(Y,X,W)};var uX=(Q)=>(Y,X,W)=>{let G=W?Object.assign(W,{direction:"backward"}):{direction:"backward"};return A4(Q)(Y,X,G)};var hX=(Q)=>(Y,X,W)=>{return A4(Q)(Y,X,W)};var fX=(Q)=>async(Y,X,W)=>{let G=W?Object.assign(W,{direction:"backward"}):{direction:"backward"};return K4(Q)(Y,X,G)};var lX=(Q)=>async(Y,X,W)=>{return K4(Q)(Y,X,W)};var mX=/^[cC][^\s-]{8,}$/,cX=/^[0-9a-z]+$/,pX=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,iX=/^[0-9a-vA-V]{20}$/,nX=/^[A-Za-z0-9]{27}$/,rX=/^[a-zA-Z0-9_-]{21}$/,dX=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var oX=/^([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})$/,uQ=(Q)=>{if(!Q)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}-${Q}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)};var tX=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function aX(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}var sX=/^(?:(?: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])$/,eX=/^(([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}|:))$/,Q8=/^((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])$/,Y8=/^(([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])$/,X8=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,hQ=/^[A-Za-z0-9_-]*$/,W8=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/;var G8=/^\+(?:[0-9]){6,14}[0-9]$/,$8="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",z8=new RegExp(`^${$8}$`);function J8(Q){return typeof Q.precision==="number"?Q.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":Q.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{${Q.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function H8(Q){return new RegExp(`^${J8(Q)}$`)}function A8(Q){let Y=J8({precision:Q.precision}),X=["Z"];if(Q.local)X.push("");if(Q.offset)X.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let W=`${Y}(?:${X.join("|")})`;return new RegExp(`^${$8}T(?:${W})$`)}var U8=(Q)=>{let Y=Q?`[\\s\\S]{${Q?.minimum??0},${Q?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${Y}$`)};var K8=/^-?\d+$/,D8=/^-?\d+(?:\.\d+)?/,B8=/^(?:true|false)$/i,L8=/^null$/i;var F8=/^[^A-Z]*$/,q8=/^[^a-z]*$/;var A0=q("$ZodCheck",(Q,Y)=>{var X;Q._zod??(Q._zod={}),Q._zod.def=Y,(X=Q._zod).onattach??(X.onattach=[])}),O8={number:"number",bigint:"bigint",object:"date"},fQ=q("$ZodCheckLessThan",(Q,Y)=>{A0.init(Q,Y);let X=O8[typeof Y.value];Q._zod.onattach.push((W)=>{let G=W._zod.bag,$=(Y.inclusive?G.maximum:G.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(Y.value<$)if(Y.inclusive)G.maximum=Y.value;else G.exclusiveMaximum=Y.value}),Q._zod.check=(W)=>{if(Y.inclusive?W.value<=Y.value:W.value<Y.value)return;W.issues.push({origin:X,code:"too_big",maximum:Y.value,input:W.value,inclusive:Y.inclusive,inst:Q,continue:!Y.abort})}}),lQ=q("$ZodCheckGreaterThan",(Q,Y)=>{A0.init(Q,Y);let X=O8[typeof Y.value];Q._zod.onattach.push((W)=>{let G=W._zod.bag,$=(Y.inclusive?G.minimum:G.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(Y.value>$)if(Y.inclusive)G.minimum=Y.value;else G.exclusiveMinimum=Y.value}),Q._zod.check=(W)=>{if(Y.inclusive?W.value>=Y.value:W.value>Y.value)return;W.issues.push({origin:X,code:"too_small",minimum:Y.value,input:W.value,inclusive:Y.inclusive,inst:Q,continue:!Y.abort})}}),M8=q("$ZodCheckMultipleOf",(Q,Y)=>{A0.init(Q,Y),Q._zod.onattach.push((X)=>{var W;(W=X._zod.bag).multipleOf??(W.multipleOf=Y.value)}),Q._zod.check=(X)=>{if(typeof X.value!==typeof Y.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof X.value==="bigint"?X.value%Y.value===BigInt(0):kQ(X.value,Y.value)===0)return;X.issues.push({origin:typeof X.value,code:"not_multiple_of",divisor:Y.value,input:X.value,inst:Q,continue:!Y.abort})}}),V8=q("$ZodCheckNumberFormat",(Q,Y)=>{A0.init(Q,Y),Y.format=Y.format||"float64";let X=Y.format?.includes("int"),W=X?"int":"number",[G,$]=gQ[Y.format];Q._zod.onattach.push((z)=>{let J=z._zod.bag;if(J.format=Y.format,J.minimum=G,J.maximum=$,X)J.pattern=K8}),Q._zod.check=(z)=>{let J=z.value;if(X){if(!Number.isInteger(J)){z.issues.push({expected:W,format:Y.format,code:"invalid_type",continue:!1,input:J,inst:Q});return}if(!Number.isSafeInteger(J)){if(J>0)z.issues.push({input:J,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:Q,origin:W,continue:!Y.abort});else z.issues.push({input:J,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:Q,origin:W,continue:!Y.abort});return}}if(J<G)z.issues.push({origin:"number",input:J,code:"too_small",minimum:G,inclusive:!0,inst:Q,continue:!Y.abort});if(J>$)z.issues.push({origin:"number",input:J,code:"too_big",maximum:$,inst:Q})}});var Z8=q("$ZodCheckMaxLength",(Q,Y)=>{var X;A0.init(Q,Y),(X=Q._zod.def).when??(X.when=(W)=>{let G=W.value;return!z4(G)&&G.length!==void 0}),Q._zod.onattach.push((W)=>{let G=W._zod.bag.maximum??Number.POSITIVE_INFINITY;if(Y.maximum<G)W._zod.bag.maximum=Y.maximum}),Q._zod.check=(W)=>{let G=W.value;if(G.length<=Y.maximum)return;let z=H4(G);W.issues.push({origin:z,code:"too_big",maximum:Y.maximum,inclusive:!0,input:G,inst:Q,continue:!Y.abort})}}),N8=q("$ZodCheckMinLength",(Q,Y)=>{var X;A0.init(Q,Y),(X=Q._zod.def).when??(X.when=(W)=>{let G=W.value;return!z4(G)&&G.length!==void 0}),Q._zod.onattach.push((W)=>{let G=W._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(Y.minimum>G)W._zod.bag.minimum=Y.minimum}),Q._zod.check=(W)=>{let G=W.value;if(G.length>=Y.minimum)return;let z=H4(G);W.issues.push({origin:z,code:"too_small",minimum:Y.minimum,inclusive:!0,input:G,inst:Q,continue:!Y.abort})}}),w8=q("$ZodCheckLengthEquals",(Q,Y)=>{var X;A0.init(Q,Y),(X=Q._zod.def).when??(X.when=(W)=>{let G=W.value;return!z4(G)&&G.length!==void 0}),Q._zod.onattach.push((W)=>{let G=W._zod.bag;G.minimum=Y.length,G.maximum=Y.length,G.length=Y.length}),Q._zod.check=(W)=>{let G=W.value,$=G.length;if($===Y.length)return;let z=H4(G),J=$>Y.length;W.issues.push({origin:z,...J?{code:"too_big",maximum:Y.length}:{code:"too_small",minimum:Y.length},inclusive:!0,exact:!0,input:W.value,inst:Q,continue:!Y.abort})}}),D4=q("$ZodCheckStringFormat",(Q,Y)=>{var X,W;if(A0.init(Q,Y),Q._zod.onattach.push((G)=>{let $=G._zod.bag;if($.format=Y.format,Y.pattern)$.patterns??($.patterns=new Set),$.patterns.add(Y.pattern)}),Y.pattern)(X=Q._zod).check??(X.check=(G)=>{if(Y.pattern.lastIndex=0,Y.pattern.test(G.value))return;G.issues.push({origin:"string",code:"invalid_format",format:Y.format,input:G.value,...Y.pattern?{pattern:Y.pattern.toString()}:{},inst:Q,continue:!Y.abort})});else(W=Q._zod).check??(W.check=()=>{})}),P8=q("$ZodCheckRegex",(Q,Y)=>{D4.init(Q,Y),Q._zod.check=(X)=>{if(Y.pattern.lastIndex=0,Y.pattern.test(X.value))return;X.issues.push({origin:"string",code:"invalid_format",format:"regex",input:X.value,pattern:Y.pattern.toString(),inst:Q,continue:!Y.abort})}}),b8=q("$ZodCheckLowerCase",(Q,Y)=>{Y.pattern??(Y.pattern=F8),D4.init(Q,Y)}),j8=q("$ZodCheckUpperCase",(Q,Y)=>{Y.pattern??(Y.pattern=q8),D4.init(Q,Y)}),I8=q("$ZodCheckIncludes",(Q,Y)=>{A0.init(Q,Y);let X=a0(Y.includes),W=new RegExp(typeof Y.position==="number"?`^.{${Y.position}}${X}`:X);Y.pattern=W,Q._zod.onattach.push((G)=>{let $=G._zod.bag;$.patterns??($.patterns=new Set),$.patterns.add(W)}),Q._zod.check=(G)=>{if(G.value.includes(Y.includes,Y.position))return;G.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:Y.includes,input:G.value,inst:Q,continue:!Y.abort})}}),E8=q("$ZodCheckStartsWith",(Q,Y)=>{A0.init(Q,Y);let X=new RegExp(`^${a0(Y.prefix)}.*`);Y.pattern??(Y.pattern=X),Q._zod.onattach.push((W)=>{let G=W._zod.bag;G.patterns??(G.patterns=new Set),G.patterns.add(X)}),Q._zod.check=(W)=>{if(W.value.startsWith(Y.prefix))return;W.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:Y.prefix,input:W.value,inst:Q,continue:!Y.abort})}}),T8=q("$ZodCheckEndsWith",(Q,Y)=>{A0.init(Q,Y);let X=new RegExp(`.*${a0(Y.suffix)}$`);Y.pattern??(Y.pattern=X),Q._zod.onattach.push((W)=>{let G=W._zod.bag;G.patterns??(G.patterns=new Set),G.patterns.add(X)}),Q._zod.check=(W)=>{if(W.value.endsWith(Y.suffix))return;W.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:Y.suffix,input:W.value,inst:Q,continue:!Y.abort})}});var S8=q("$ZodCheckOverwrite",(Q,Y)=>{A0.init(Q,Y),Q._zod.check=(X)=>{X.value=Y.tx(X.value)}});class mQ{constructor(Q=[]){if(this.content=[],this.indent=0,this)this.args=Q}indented(Q){this.indent+=1,Q(this),this.indent-=1}write(Q){if(typeof Q==="function"){Q(this,{execution:"sync"}),Q(this,{execution:"async"});return}let X=Q.split(`
11
11
  `).filter(($)=>$),W=Math.min(...X.map(($)=>$.length-$.trimStart().length)),G=X.map(($)=>$.slice(W)).map(($)=>" ".repeat(this.indent*2)+$);for(let $ of G)this.content.push($)}compile(){let Q=Function,Y=this?.args,W=[...(this?.content??[""]).map((G)=>` ${G}`)];return new Q(...Y,W.join(`
12
- `))}}var S8={major:4,minor:1,patch:12};var o=q("$ZodType",(Q,Y)=>{var X;Q??(Q={}),Q._zod.def=Y,Q._zod.bag=Q._zod.bag||{},Q._zod.version=S8;let W=[...Q._zod.def.checks??[]];if(Q._zod.traits.has("$ZodCheck"))W.unshift(Q);for(let G of W)for(let $ of G._zod.onattach)$(Q);if(W.length===0)(X=Q._zod).deferred??(X.deferred=[]),Q._zod.deferred?.push(()=>{Q._zod.run=Q._zod.parse});else{let G=(z,J,H)=>{let A=A1(z),U;for(let K of J){if(K._zod.def.when){if(!K._zod.def.when(z))continue}else if(A)continue;let D=z.issues.length,L=K._zod.check(z);if(L instanceof Promise&&H?.async===!1)throw new t0;if(U||L instanceof Promise)U=(U??Promise.resolve()).then(async()=>{if(await L,z.issues.length===D)return;if(!A)A=A1(z,D)});else{if(z.issues.length===D)continue;if(!A)A=A1(z,D)}}if(U)return U.then(()=>{return z});return z},$=(z,J,H)=>{if(A1(z))return z.aborted=!0,z;let A=G(J,W,H);if(A instanceof Promise){if(H.async===!1)throw new t0;return A.then((U)=>Q._zod.parse(U,H))}return Q._zod.parse(A,H)};Q._zod.run=(z,J)=>{if(J.skipChecks)return Q._zod.parse(z,J);if(J.direction==="backward"){let A=Q._zod.parse({value:z.value,issues:[]},{...J,skipChecks:!0});if(A instanceof Promise)return A.then((U)=>{return $(U,z,J)});return $(A,z,J)}let H=Q._zod.parse(z,J);if(H instanceof Promise){if(J.async===!1)throw new t0;return H.then((A)=>G(A,W,J))}return G(H,W,J)}}Q["~standard"]={validate:(G)=>{try{let $=U4(Q,G);return $.success?{value:$.data}:{issues:$.error?.issues}}catch($){return A6(Q,G).then((z)=>z.success?{value:z.data}:{issues:z.error?.issues})}},vendor:"zod",version:1}}),B6=q("$ZodString",(Q,Y)=>{o.init(Q,Y),Q._zod.pattern=[...Q?._zod.bag?.patterns??[]].pop()??H8(Q._zod.bag),Q._zod.parse=(X,W)=>{if(Y.coerce)try{X.value=String(X.value)}catch(G){}if(typeof X.value==="string")return X;return X.issues.push({expected:"string",code:"invalid_type",input:X.value,inst:Q}),X}}),t=q("$ZodStringFormat",(Q,Y)=>{D4.init(Q,Y),B6.init(Q,Y)}),u8=q("$ZodGUID",(Q,Y)=>{Y.pattern??(Y.pattern=rX),t.init(Q,Y)}),h8=q("$ZodUUID",(Q,Y)=>{if(Y.version){let W={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[Y.version];if(W===void 0)throw Error(`Invalid UUID version: "${Y.version}"`);Y.pattern??(Y.pattern=uQ(W))}else Y.pattern??(Y.pattern=uQ());t.init(Q,Y)}),f8=q("$ZodEmail",(Q,Y)=>{Y.pattern??(Y.pattern=dX),t.init(Q,Y)}),l8=q("$ZodURL",(Q,Y)=>{t.init(Q,Y),Q._zod.check=(X)=>{try{let W=X.value.trim(),G=new URL(W);if(Y.hostname){if(Y.hostname.lastIndex=0,!Y.hostname.test(G.hostname))X.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:Y8.source,input:X.value,inst:Q,continue:!Y.abort})}if(Y.protocol){if(Y.protocol.lastIndex=0,!Y.protocol.test(G.protocol.endsWith(":")?G.protocol.slice(0,-1):G.protocol))X.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:Y.protocol.source,input:X.value,inst:Q,continue:!Y.abort})}if(Y.normalize)X.value=G.href;else X.value=W;return}catch(W){X.issues.push({code:"invalid_format",format:"url",input:X.value,inst:Q,continue:!Y.abort})}}}),m8=q("$ZodEmoji",(Q,Y)=>{Y.pattern??(Y.pattern=oX()),t.init(Q,Y)}),c8=q("$ZodNanoID",(Q,Y)=>{Y.pattern??(Y.pattern=iX),t.init(Q,Y)}),p8=q("$ZodCUID",(Q,Y)=>{Y.pattern??(Y.pattern=fX),t.init(Q,Y)}),i8=q("$ZodCUID2",(Q,Y)=>{Y.pattern??(Y.pattern=lX),t.init(Q,Y)}),n8=q("$ZodULID",(Q,Y)=>{Y.pattern??(Y.pattern=mX),t.init(Q,Y)}),r8=q("$ZodXID",(Q,Y)=>{Y.pattern??(Y.pattern=cX),t.init(Q,Y)}),d8=q("$ZodKSUID",(Q,Y)=>{Y.pattern??(Y.pattern=pX),t.init(Q,Y)}),o8=q("$ZodISODateTime",(Q,Y)=>{Y.pattern??(Y.pattern=J8(Y)),t.init(Q,Y)}),t8=q("$ZodISODate",(Q,Y)=>{Y.pattern??(Y.pattern=G8),t.init(Q,Y)}),a8=q("$ZodISOTime",(Q,Y)=>{Y.pattern??(Y.pattern=z8(Y)),t.init(Q,Y)}),s8=q("$ZodISODuration",(Q,Y)=>{Y.pattern??(Y.pattern=nX),t.init(Q,Y)}),e8=q("$ZodIPv4",(Q,Y)=>{Y.pattern??(Y.pattern=tX),t.init(Q,Y),Q._zod.onattach.push((X)=>{let W=X._zod.bag;W.format="ipv4"})}),QW=q("$ZodIPv6",(Q,Y)=>{Y.pattern??(Y.pattern=aX),t.init(Q,Y),Q._zod.onattach.push((X)=>{let W=X._zod.bag;W.format="ipv6"}),Q._zod.check=(X)=>{try{new URL(`http://[${X.value}]`)}catch{X.issues.push({code:"invalid_format",format:"ipv6",input:X.value,inst:Q,continue:!Y.abort})}}}),YW=q("$ZodCIDRv4",(Q,Y)=>{Y.pattern??(Y.pattern=sX),t.init(Q,Y)}),XW=q("$ZodCIDRv6",(Q,Y)=>{Y.pattern??(Y.pattern=eX),t.init(Q,Y),Q._zod.check=(X)=>{let W=X.value.split("/");try{if(W.length!==2)throw Error();let[G,$]=W;if(!$)throw Error();let z=Number($);if(`${z}`!==$)throw Error();if(z<0||z>128)throw Error();new URL(`http://[${G}]`)}catch{X.issues.push({code:"invalid_format",format:"cidrv6",input:X.value,inst:Q,continue:!Y.abort})}}});function WW(Q){if(Q==="")return!0;if(Q.length%4!==0)return!1;try{return atob(Q),!0}catch{return!1}}var GW=q("$ZodBase64",(Q,Y)=>{Y.pattern??(Y.pattern=Q8),t.init(Q,Y),Q._zod.onattach.push((X)=>{X._zod.bag.contentEncoding="base64"}),Q._zod.check=(X)=>{if(WW(X.value))return;X.issues.push({code:"invalid_format",format:"base64",input:X.value,inst:Q,continue:!Y.abort})}});function JA(Q){if(!hQ.test(Q))return!1;let Y=Q.replace(/[-_]/g,(W)=>W==="-"?"+":"/"),X=Y.padEnd(Math.ceil(Y.length/4)*4,"=");return WW(X)}var $W=q("$ZodBase64URL",(Q,Y)=>{Y.pattern??(Y.pattern=hQ),t.init(Q,Y),Q._zod.onattach.push((X)=>{X._zod.bag.contentEncoding="base64url"}),Q._zod.check=(X)=>{if(JA(X.value))return;X.issues.push({code:"invalid_format",format:"base64url",input:X.value,inst:Q,continue:!Y.abort})}}),zW=q("$ZodE164",(Q,Y)=>{Y.pattern??(Y.pattern=X8),t.init(Q,Y)});function HA(Q,Y=null){try{let X=Q.split(".");if(X.length!==3)return!1;let[W]=X;if(!W)return!1;let G=JSON.parse(atob(W));if("typ"in G&&G?.typ!=="JWT")return!1;if(!G.alg)return!1;if(Y&&(!("alg"in G)||G.alg!==Y))return!1;return!0}catch{return!1}}var JW=q("$ZodJWT",(Q,Y)=>{t.init(Q,Y),Q._zod.check=(X)=>{if(HA(X.value,Y.alg))return;X.issues.push({code:"invalid_format",format:"jwt",input:X.value,inst:Q,continue:!Y.abort})}});var pQ=q("$ZodNumber",(Q,Y)=>{o.init(Q,Y),Q._zod.pattern=Q._zod.bag.pattern??U8,Q._zod.parse=(X,W)=>{if(Y.coerce)try{X.value=Number(X.value)}catch(z){}let G=X.value;if(typeof G==="number"&&!Number.isNaN(G)&&Number.isFinite(G))return X;let $=typeof G==="number"?Number.isNaN(G)?"NaN":!Number.isFinite(G)?"Infinity":void 0:void 0;return X.issues.push({expected:"number",code:"invalid_type",input:G,inst:Q,...$?{received:$}:{}}),X}}),HW=q("$ZodNumber",(Q,Y)=>{O8.init(Q,Y),pQ.init(Q,Y)}),AW=q("$ZodBoolean",(Q,Y)=>{o.init(Q,Y),Q._zod.pattern=K8,Q._zod.parse=(X,W)=>{if(Y.coerce)try{X.value=Boolean(X.value)}catch($){}let G=X.value;if(typeof G==="boolean")return X;return X.issues.push({expected:"boolean",code:"invalid_type",input:G,inst:Q}),X}});var UW=q("$ZodNull",(Q,Y)=>{o.init(Q,Y),Q._zod.pattern=D8,Q._zod.values=new Set([null]),Q._zod.parse=(X,W)=>{let G=X.value;if(G===null)return X;return X.issues.push({expected:"null",code:"invalid_type",input:G,inst:Q}),X}});var KW=q("$ZodUnknown",(Q,Y)=>{o.init(Q,Y),Q._zod.parse=(X)=>X}),DW=q("$ZodNever",(Q,Y)=>{o.init(Q,Y),Q._zod.parse=(X,W)=>{return X.issues.push({expected:"never",code:"invalid_type",input:X.value,inst:Q}),X}});function R8(Q,Y,X){if(Q.issues.length)Y.issues.push(...s0(X,Q.issues));Y.value[X]=Q.value}var BW=q("$ZodArray",(Q,Y)=>{o.init(Q,Y),Q._zod.parse=(X,W)=>{let G=X.value;if(!Array.isArray(G))return X.issues.push({expected:"array",code:"invalid_type",input:G,inst:Q}),X;X.value=Array(G.length);let $=[];for(let z=0;z<G.length;z++){let J=G[z],H=Y.element._zod.run({value:J,issues:[]},W);if(H instanceof Promise)$.push(H.then((A)=>R8(A,X,z)));else R8(H,X,z)}if($.length)return Promise.all($).then(()=>X);return X}});function D6(Q,Y,X,W){if(Q.issues.length)Y.issues.push(...s0(X,Q.issues));if(Q.value===void 0){if(X in W)Y.value[X]=void 0}else Y.value[X]=Q.value}function LW(Q){let Y=Object.keys(Q.shape);for(let W of Y)if(!Q.shape?.[W]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${W}": expected a Zod schema`);let X=_Q(Q.shape);return{...Q,keys:Y,keySet:new Set(Y),numKeys:Y.length,optionalKeys:new Set(X)}}function FW(Q,Y,X,W,G,$){let z=[],J=G.keySet,H=G.catchall._zod,A=H.def.type;for(let U of Object.keys(Y)){if(J.has(U))continue;if(A==="never"){z.push(U);continue}let K=H.run({value:Y[U],issues:[]},W);if(K instanceof Promise)Q.push(K.then((D)=>D6(D,X,U,Y)));else D6(K,X,U,Y)}if(z.length)X.issues.push({code:"unrecognized_keys",keys:z,input:Y,inst:$});if(!Q.length)return X;return Promise.all(Q).then(()=>{return X})}var AA=q("$ZodObject",(Q,Y)=>{if(o.init(Q,Y),!Object.getOwnPropertyDescriptor(Y,"shape")?.get){let J=Y.shape;Object.defineProperty(Y,"shape",{get:()=>{let H={...J};return Object.defineProperty(Y,"shape",{value:H}),H}})}let W=g1(()=>LW(Y));n(Q._zod,"propValues",()=>{let J=Y.shape,H={};for(let A in J){let U=J[A]._zod;if(U.values){H[A]??(H[A]=new Set);for(let K of U.values)H[A].add(K)}}return H});let G=j1,$=Y.catchall,z;Q._zod.parse=(J,H)=>{z??(z=W.value);let A=J.value;if(!G(A))return J.issues.push({expected:"object",code:"invalid_type",input:A,inst:Q}),J;J.value={};let U=[],K=z.shape;for(let D of z.keys){let O=K[D]._zod.run({value:A[D],issues:[]},H);if(O instanceof Promise)U.push(O.then((M)=>D6(M,J,D,A)));else D6(O,J,D,A)}if(!$)return U.length?Promise.all(U).then(()=>J):J;return FW(U,A,J,H,W.value,Q)}}),qW=q("$ZodObjectJIT",(Q,Y)=>{AA.init(Q,Y);let X=Q._zod.parse,W=g1(()=>LW(Y)),G=(D)=>{let L=new mQ(["shape","payload","ctx"]),O=W.value,M=(S)=>{let y=W6(S);return`shape[${y}]._zod.run({ value: input[${y}], issues: [] }, ctx)`};L.write("const input = payload.value;");let N=Object.create(null),Z=0;for(let S of O.keys)N[S]=`key_${Z++}`;L.write("const newResult = {};");for(let S of O.keys){let y=N[S],C=W6(S);L.write(`const ${y} = ${M(S)};`),L.write(`
12
+ `))}}var C8={major:4,minor:1,patch:12};var o=q("$ZodType",(Q,Y)=>{var X;Q??(Q={}),Q._zod.def=Y,Q._zod.bag=Q._zod.bag||{},Q._zod.version=C8;let W=[...Q._zod.def.checks??[]];if(Q._zod.traits.has("$ZodCheck"))W.unshift(Q);for(let G of W)for(let $ of G._zod.onattach)$(Q);if(W.length===0)(X=Q._zod).deferred??(X.deferred=[]),Q._zod.deferred?.push(()=>{Q._zod.run=Q._zod.parse});else{let G=(z,J,H)=>{let A=A1(z),U;for(let K of J){if(K._zod.def.when){if(!K._zod.def.when(z))continue}else if(A)continue;let D=z.issues.length,L=K._zod.check(z);if(L instanceof Promise&&H?.async===!1)throw new t0;if(U||L instanceof Promise)U=(U??Promise.resolve()).then(async()=>{if(await L,z.issues.length===D)return;if(!A)A=A1(z,D)});else{if(z.issues.length===D)continue;if(!A)A=A1(z,D)}}if(U)return U.then(()=>{return z});return z},$=(z,J,H)=>{if(A1(z))return z.aborted=!0,z;let A=G(J,W,H);if(A instanceof Promise){if(H.async===!1)throw new t0;return A.then((U)=>Q._zod.parse(U,H))}return Q._zod.parse(A,H)};Q._zod.run=(z,J)=>{if(J.skipChecks)return Q._zod.parse(z,J);if(J.direction==="backward"){let A=Q._zod.parse({value:z.value,issues:[]},{...J,skipChecks:!0});if(A instanceof Promise)return A.then((U)=>{return $(U,z,J)});return $(A,z,J)}let H=Q._zod.parse(z,J);if(H instanceof Promise){if(J.async===!1)throw new t0;return H.then((A)=>G(A,W,J))}return G(H,W,J)}}Q["~standard"]={validate:(G)=>{try{let $=U4(Q,G);return $.success?{value:$.data}:{issues:$.error?.issues}}catch($){return A6(Q,G).then((z)=>z.success?{value:z.data}:{issues:z.error?.issues})}},vendor:"zod",version:1}}),B6=q("$ZodString",(Q,Y)=>{o.init(Q,Y),Q._zod.pattern=[...Q?._zod.bag?.patterns??[]].pop()??U8(Q._zod.bag),Q._zod.parse=(X,W)=>{if(Y.coerce)try{X.value=String(X.value)}catch(G){}if(typeof X.value==="string")return X;return X.issues.push({expected:"string",code:"invalid_type",input:X.value,inst:Q}),X}}),t=q("$ZodStringFormat",(Q,Y)=>{D4.init(Q,Y),B6.init(Q,Y)}),f8=q("$ZodGUID",(Q,Y)=>{Y.pattern??(Y.pattern=oX),t.init(Q,Y)}),l8=q("$ZodUUID",(Q,Y)=>{if(Y.version){let W={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[Y.version];if(W===void 0)throw Error(`Invalid UUID version: "${Y.version}"`);Y.pattern??(Y.pattern=uQ(W))}else Y.pattern??(Y.pattern=uQ());t.init(Q,Y)}),m8=q("$ZodEmail",(Q,Y)=>{Y.pattern??(Y.pattern=tX),t.init(Q,Y)}),c8=q("$ZodURL",(Q,Y)=>{t.init(Q,Y),Q._zod.check=(X)=>{try{let W=X.value.trim(),G=new URL(W);if(Y.hostname){if(Y.hostname.lastIndex=0,!Y.hostname.test(G.hostname))X.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:W8.source,input:X.value,inst:Q,continue:!Y.abort})}if(Y.protocol){if(Y.protocol.lastIndex=0,!Y.protocol.test(G.protocol.endsWith(":")?G.protocol.slice(0,-1):G.protocol))X.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:Y.protocol.source,input:X.value,inst:Q,continue:!Y.abort})}if(Y.normalize)X.value=G.href;else X.value=W;return}catch(W){X.issues.push({code:"invalid_format",format:"url",input:X.value,inst:Q,continue:!Y.abort})}}}),p8=q("$ZodEmoji",(Q,Y)=>{Y.pattern??(Y.pattern=aX()),t.init(Q,Y)}),i8=q("$ZodNanoID",(Q,Y)=>{Y.pattern??(Y.pattern=rX),t.init(Q,Y)}),n8=q("$ZodCUID",(Q,Y)=>{Y.pattern??(Y.pattern=mX),t.init(Q,Y)}),r8=q("$ZodCUID2",(Q,Y)=>{Y.pattern??(Y.pattern=cX),t.init(Q,Y)}),d8=q("$ZodULID",(Q,Y)=>{Y.pattern??(Y.pattern=pX),t.init(Q,Y)}),o8=q("$ZodXID",(Q,Y)=>{Y.pattern??(Y.pattern=iX),t.init(Q,Y)}),t8=q("$ZodKSUID",(Q,Y)=>{Y.pattern??(Y.pattern=nX),t.init(Q,Y)}),a8=q("$ZodISODateTime",(Q,Y)=>{Y.pattern??(Y.pattern=A8(Y)),t.init(Q,Y)}),s8=q("$ZodISODate",(Q,Y)=>{Y.pattern??(Y.pattern=z8),t.init(Q,Y)}),e8=q("$ZodISOTime",(Q,Y)=>{Y.pattern??(Y.pattern=H8(Y)),t.init(Q,Y)}),QW=q("$ZodISODuration",(Q,Y)=>{Y.pattern??(Y.pattern=dX),t.init(Q,Y)}),YW=q("$ZodIPv4",(Q,Y)=>{Y.pattern??(Y.pattern=sX),t.init(Q,Y),Q._zod.onattach.push((X)=>{let W=X._zod.bag;W.format="ipv4"})}),XW=q("$ZodIPv6",(Q,Y)=>{Y.pattern??(Y.pattern=eX),t.init(Q,Y),Q._zod.onattach.push((X)=>{let W=X._zod.bag;W.format="ipv6"}),Q._zod.check=(X)=>{try{new URL(`http://[${X.value}]`)}catch{X.issues.push({code:"invalid_format",format:"ipv6",input:X.value,inst:Q,continue:!Y.abort})}}}),WW=q("$ZodCIDRv4",(Q,Y)=>{Y.pattern??(Y.pattern=Q8),t.init(Q,Y)}),GW=q("$ZodCIDRv6",(Q,Y)=>{Y.pattern??(Y.pattern=Y8),t.init(Q,Y),Q._zod.check=(X)=>{let W=X.value.split("/");try{if(W.length!==2)throw Error();let[G,$]=W;if(!$)throw Error();let z=Number($);if(`${z}`!==$)throw Error();if(z<0||z>128)throw Error();new URL(`http://[${G}]`)}catch{X.issues.push({code:"invalid_format",format:"cidrv6",input:X.value,inst:Q,continue:!Y.abort})}}});function $W(Q){if(Q==="")return!0;if(Q.length%4!==0)return!1;try{return atob(Q),!0}catch{return!1}}var zW=q("$ZodBase64",(Q,Y)=>{Y.pattern??(Y.pattern=X8),t.init(Q,Y),Q._zod.onattach.push((X)=>{X._zod.bag.contentEncoding="base64"}),Q._zod.check=(X)=>{if($W(X.value))return;X.issues.push({code:"invalid_format",format:"base64",input:X.value,inst:Q,continue:!Y.abort})}});function BA(Q){if(!hQ.test(Q))return!1;let Y=Q.replace(/[-_]/g,(W)=>W==="-"?"+":"/"),X=Y.padEnd(Math.ceil(Y.length/4)*4,"=");return $W(X)}var JW=q("$ZodBase64URL",(Q,Y)=>{Y.pattern??(Y.pattern=hQ),t.init(Q,Y),Q._zod.onattach.push((X)=>{X._zod.bag.contentEncoding="base64url"}),Q._zod.check=(X)=>{if(BA(X.value))return;X.issues.push({code:"invalid_format",format:"base64url",input:X.value,inst:Q,continue:!Y.abort})}}),HW=q("$ZodE164",(Q,Y)=>{Y.pattern??(Y.pattern=G8),t.init(Q,Y)});function LA(Q,Y=null){try{let X=Q.split(".");if(X.length!==3)return!1;let[W]=X;if(!W)return!1;let G=JSON.parse(atob(W));if("typ"in G&&G?.typ!=="JWT")return!1;if(!G.alg)return!1;if(Y&&(!("alg"in G)||G.alg!==Y))return!1;return!0}catch{return!1}}var AW=q("$ZodJWT",(Q,Y)=>{t.init(Q,Y),Q._zod.check=(X)=>{if(LA(X.value,Y.alg))return;X.issues.push({code:"invalid_format",format:"jwt",input:X.value,inst:Q,continue:!Y.abort})}});var pQ=q("$ZodNumber",(Q,Y)=>{o.init(Q,Y),Q._zod.pattern=Q._zod.bag.pattern??D8,Q._zod.parse=(X,W)=>{if(Y.coerce)try{X.value=Number(X.value)}catch(z){}let G=X.value;if(typeof G==="number"&&!Number.isNaN(G)&&Number.isFinite(G))return X;let $=typeof G==="number"?Number.isNaN(G)?"NaN":!Number.isFinite(G)?"Infinity":void 0:void 0;return X.issues.push({expected:"number",code:"invalid_type",input:G,inst:Q,...$?{received:$}:{}}),X}}),UW=q("$ZodNumber",(Q,Y)=>{V8.init(Q,Y),pQ.init(Q,Y)}),KW=q("$ZodBoolean",(Q,Y)=>{o.init(Q,Y),Q._zod.pattern=B8,Q._zod.parse=(X,W)=>{if(Y.coerce)try{X.value=Boolean(X.value)}catch($){}let G=X.value;if(typeof G==="boolean")return X;return X.issues.push({expected:"boolean",code:"invalid_type",input:G,inst:Q}),X}});var DW=q("$ZodNull",(Q,Y)=>{o.init(Q,Y),Q._zod.pattern=L8,Q._zod.values=new Set([null]),Q._zod.parse=(X,W)=>{let G=X.value;if(G===null)return X;return X.issues.push({expected:"null",code:"invalid_type",input:G,inst:Q}),X}});var BW=q("$ZodUnknown",(Q,Y)=>{o.init(Q,Y),Q._zod.parse=(X)=>X}),LW=q("$ZodNever",(Q,Y)=>{o.init(Q,Y),Q._zod.parse=(X,W)=>{return X.issues.push({expected:"never",code:"invalid_type",input:X.value,inst:Q}),X}});function k8(Q,Y,X){if(Q.issues.length)Y.issues.push(...s0(X,Q.issues));Y.value[X]=Q.value}var FW=q("$ZodArray",(Q,Y)=>{o.init(Q,Y),Q._zod.parse=(X,W)=>{let G=X.value;if(!Array.isArray(G))return X.issues.push({expected:"array",code:"invalid_type",input:G,inst:Q}),X;X.value=Array(G.length);let $=[];for(let z=0;z<G.length;z++){let J=G[z],H=Y.element._zod.run({value:J,issues:[]},W);if(H instanceof Promise)$.push(H.then((A)=>k8(A,X,z)));else k8(H,X,z)}if($.length)return Promise.all($).then(()=>X);return X}});function D6(Q,Y,X,W){if(Q.issues.length)Y.issues.push(...s0(X,Q.issues));if(Q.value===void 0){if(X in W)Y.value[X]=void 0}else Y.value[X]=Q.value}function qW(Q){let Y=Object.keys(Q.shape);for(let W of Y)if(!Q.shape?.[W]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${W}": expected a Zod schema`);let X=_Q(Q.shape);return{...Q,keys:Y,keySet:new Set(Y),numKeys:Y.length,optionalKeys:new Set(X)}}function OW(Q,Y,X,W,G,$){let z=[],J=G.keySet,H=G.catchall._zod,A=H.def.type;for(let U of Object.keys(Y)){if(J.has(U))continue;if(A==="never"){z.push(U);continue}let K=H.run({value:Y[U],issues:[]},W);if(K instanceof Promise)Q.push(K.then((D)=>D6(D,X,U,Y)));else D6(K,X,U,Y)}if(z.length)X.issues.push({code:"unrecognized_keys",keys:z,input:Y,inst:$});if(!Q.length)return X;return Promise.all(Q).then(()=>{return X})}var FA=q("$ZodObject",(Q,Y)=>{if(o.init(Q,Y),!Object.getOwnPropertyDescriptor(Y,"shape")?.get){let J=Y.shape;Object.defineProperty(Y,"shape",{get:()=>{let H={...J};return Object.defineProperty(Y,"shape",{value:H}),H}})}let W=g1(()=>qW(Y));n(Q._zod,"propValues",()=>{let J=Y.shape,H={};for(let A in J){let U=J[A]._zod;if(U.values){H[A]??(H[A]=new Set);for(let K of U.values)H[A].add(K)}}return H});let G=j1,$=Y.catchall,z;Q._zod.parse=(J,H)=>{z??(z=W.value);let A=J.value;if(!G(A))return J.issues.push({expected:"object",code:"invalid_type",input:A,inst:Q}),J;J.value={};let U=[],K=z.shape;for(let D of z.keys){let O=K[D]._zod.run({value:A[D],issues:[]},H);if(O instanceof Promise)U.push(O.then((M)=>D6(M,J,D,A)));else D6(O,J,D,A)}if(!$)return U.length?Promise.all(U).then(()=>J):J;return OW(U,A,J,H,W.value,Q)}}),MW=q("$ZodObjectJIT",(Q,Y)=>{FA.init(Q,Y);let X=Q._zod.parse,W=g1(()=>qW(Y)),G=(D)=>{let L=new mQ(["shape","payload","ctx"]),O=W.value,M=(S)=>{let y=W6(S);return`shape[${y}]._zod.run({ value: input[${y}], issues: [] }, ctx)`};L.write("const input = payload.value;");let N=Object.create(null),Z=0;for(let S of O.keys)N[S]=`key_${Z++}`;L.write("const newResult = {};");for(let S of O.keys){let y=N[S],C=W6(S);L.write(`const ${y} = ${M(S)};`),L.write(`
13
13
  if (${y}.issues.length) {
14
14
  payload.issues = payload.issues.concat(${y}.issues.map(iss => ({
15
15
  ...iss,
@@ -26,7 +26,7 @@ var qH=Object.create;var{getPrototypeOf:OH,defineProperty:TQ,getOwnPropertyNames
26
26
  newResult[${C}] = ${y}.value;
27
27
  }
28
28
 
29
- `)}L.write("payload.value = newResult;"),L.write("return payload;");let k=L.compile();return(S,y)=>k(D,S,y)},$,z=j1,J=!Y6.jitless,A=J&&vQ.value,U=Y.catchall,K;Q._zod.parse=(D,L)=>{K??(K=W.value);let O=D.value;if(!z(O))return D.issues.push({expected:"object",code:"invalid_type",input:O,inst:Q}),D;if(J&&A&&L?.async===!1&&L.jitless!==!0){if(!$)$=G(Y.shape);if(D=$(D,L),!U)return D;return FW([],O,D,L,K,Q)}return X(D,L)}});function C8(Q,Y,X,W){for(let $ of Q)if($.issues.length===0)return Y.value=$.value,Y;let G=Q.filter(($)=>!A1($));if(G.length===1)return Y.value=G[0].value,G[0];return Y.issues.push({code:"invalid_union",input:Y.value,inst:X,errors:Q.map(($)=>$.issues.map((z)=>x0(z,W,T0())))}),Y}var iQ=q("$ZodUnion",(Q,Y)=>{o.init(Q,Y),n(Q._zod,"optin",()=>Y.options.some((G)=>G._zod.optin==="optional")?"optional":void 0),n(Q._zod,"optout",()=>Y.options.some((G)=>G._zod.optout==="optional")?"optional":void 0),n(Q._zod,"values",()=>{if(Y.options.every((G)=>G._zod.values))return new Set(Y.options.flatMap((G)=>Array.from(G._zod.values)));return}),n(Q._zod,"pattern",()=>{if(Y.options.every((G)=>G._zod.pattern)){let G=Y.options.map(($)=>$._zod.pattern);return new RegExp(`^(${G.map(($)=>J4($.source)).join("|")})$`)}return});let X=Y.options.length===1,W=Y.options[0]._zod.run;Q._zod.parse=(G,$)=>{if(X)return W(G,$);let z=!1,J=[];for(let H of Y.options){let A=H._zod.run({value:G.value,issues:[]},$);if(A instanceof Promise)J.push(A),z=!0;else{if(A.issues.length===0)return A;J.push(A)}}if(!z)return C8(J,G,Q,$);return Promise.all(J).then((H)=>{return C8(H,G,Q,$)})}}),OW=q("$ZodDiscriminatedUnion",(Q,Y)=>{iQ.init(Q,Y);let X=Q._zod.parse;n(Q._zod,"propValues",()=>{let G={};for(let $ of Y.options){let z=$._zod.propValues;if(!z||Object.keys(z).length===0)throw Error(`Invalid discriminated union option at index "${Y.options.indexOf($)}"`);for(let[J,H]of Object.entries(z)){if(!G[J])G[J]=new Set;for(let A of H)G[J].add(A)}}return G});let W=g1(()=>{let G=Y.options,$=new Map;for(let z of G){let J=z._zod.propValues?.[Y.discriminator];if(!J||J.size===0)throw Error(`Invalid discriminated union option at index "${Y.options.indexOf(z)}"`);for(let H of J){if($.has(H))throw Error(`Duplicate discriminator value "${String(H)}"`);$.set(H,z)}}return $});Q._zod.parse=(G,$)=>{let z=G.value;if(!j1(z))return G.issues.push({code:"invalid_type",expected:"object",input:z,inst:Q}),G;let J=W.value.get(z?.[Y.discriminator]);if(J)return J._zod.run(G,$);if(Y.unionFallback)return X(G,$);return G.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:Y.discriminator,input:z,path:[Y.discriminator],inst:Q}),G}}),MW=q("$ZodIntersection",(Q,Y)=>{o.init(Q,Y),Q._zod.parse=(X,W)=>{let G=X.value,$=Y.left._zod.run({value:G,issues:[]},W),z=Y.right._zod.run({value:G,issues:[]},W);if($ instanceof Promise||z instanceof Promise)return Promise.all([$,z]).then(([H,A])=>{return k8(X,H,A)});return k8(X,$,z)}});function cQ(Q,Y){if(Q===Y)return{valid:!0,data:Q};if(Q instanceof Date&&Y instanceof Date&&+Q===+Y)return{valid:!0,data:Q};if(H1(Q)&&H1(Y)){let X=Object.keys(Y),W=Object.keys(Q).filter(($)=>X.indexOf($)!==-1),G={...Q,...Y};for(let $ of W){let z=cQ(Q[$],Y[$]);if(!z.valid)return{valid:!1,mergeErrorPath:[$,...z.mergeErrorPath]};G[$]=z.data}return{valid:!0,data:G}}if(Array.isArray(Q)&&Array.isArray(Y)){if(Q.length!==Y.length)return{valid:!1,mergeErrorPath:[]};let X=[];for(let W=0;W<Q.length;W++){let G=Q[W],$=Y[W],z=cQ(G,$);if(!z.valid)return{valid:!1,mergeErrorPath:[W,...z.mergeErrorPath]};X.push(z.data)}return{valid:!0,data:X}}return{valid:!1,mergeErrorPath:[]}}function k8(Q,Y,X){if(Y.issues.length)Q.issues.push(...Y.issues);if(X.issues.length)Q.issues.push(...X.issues);if(A1(Q))return Q;let W=cQ(Y.value,X.value);if(!W.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(W.mergeErrorPath)}`);return Q.value=W.data,Q}var VW=q("$ZodRecord",(Q,Y)=>{o.init(Q,Y),Q._zod.parse=(X,W)=>{let G=X.value;if(!H1(G))return X.issues.push({expected:"record",code:"invalid_type",input:G,inst:Q}),X;let $=[];if(Y.keyType._zod.values){let z=Y.keyType._zod.values;X.value={};for(let H of z)if(typeof H==="string"||typeof H==="number"||typeof H==="symbol"){let A=Y.valueType._zod.run({value:G[H],issues:[]},W);if(A instanceof Promise)$.push(A.then((U)=>{if(U.issues.length)X.issues.push(...s0(H,U.issues));X.value[H]=U.value}));else{if(A.issues.length)X.issues.push(...s0(H,A.issues));X.value[H]=A.value}}let J;for(let H in G)if(!z.has(H))J=J??[],J.push(H);if(J&&J.length>0)X.issues.push({code:"unrecognized_keys",input:G,inst:Q,keys:J})}else{X.value={};for(let z of Reflect.ownKeys(G)){if(z==="__proto__")continue;let J=Y.keyType._zod.run({value:z,issues:[]},W);if(J instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(J.issues.length){X.issues.push({code:"invalid_key",origin:"record",issues:J.issues.map((A)=>x0(A,W,T0())),input:z,path:[z],inst:Q}),X.value[J.value]=J.value;continue}let H=Y.valueType._zod.run({value:G[z],issues:[]},W);if(H instanceof Promise)$.push(H.then((A)=>{if(A.issues.length)X.issues.push(...s0(z,A.issues));X.value[J.value]=A.value}));else{if(H.issues.length)X.issues.push(...s0(z,H.issues));X.value[J.value]=H.value}}}if($.length)return Promise.all($).then(()=>X);return X}});var ZW=q("$ZodEnum",(Q,Y)=>{o.init(Q,Y);let X=CQ(Y.entries),W=new Set(X);Q._zod.values=W,Q._zod.pattern=new RegExp(`^(${X.filter((G)=>xQ.has(typeof G)).map((G)=>typeof G==="string"?a0(G):G.toString()).join("|")})$`),Q._zod.parse=(G,$)=>{let z=G.value;if(W.has(z))return G;return G.issues.push({code:"invalid_value",values:X,input:z,inst:Q}),G}}),NW=q("$ZodLiteral",(Q,Y)=>{if(o.init(Q,Y),Y.values.length===0)throw Error("Cannot create literal schema with no valid values");Q._zod.values=new Set(Y.values),Q._zod.pattern=new RegExp(`^(${Y.values.map((X)=>typeof X==="string"?a0(X):X?a0(X.toString()):String(X)).join("|")})$`),Q._zod.parse=(X,W)=>{let G=X.value;if(Q._zod.values.has(G))return X;return X.issues.push({code:"invalid_value",values:Y.values,input:G,inst:Q}),X}});var wW=q("$ZodTransform",(Q,Y)=>{o.init(Q,Y),Q._zod.parse=(X,W)=>{if(W.direction==="backward")throw new G4(Q.constructor.name);let G=Y.transform(X.value,X);if(W.async)return(G instanceof Promise?G:Promise.resolve(G)).then((z)=>{return X.value=z,X});if(G instanceof Promise)throw new t0;return X.value=G,X}});function v8(Q,Y){if(Q.issues.length&&Y===void 0)return{issues:[],value:void 0};return Q}var PW=q("$ZodOptional",(Q,Y)=>{o.init(Q,Y),Q._zod.optin="optional",Q._zod.optout="optional",n(Q._zod,"values",()=>{return Y.innerType._zod.values?new Set([...Y.innerType._zod.values,void 0]):void 0}),n(Q._zod,"pattern",()=>{let X=Y.innerType._zod.pattern;return X?new RegExp(`^(${J4(X.source)})?$`):void 0}),Q._zod.parse=(X,W)=>{if(Y.innerType._zod.optin==="optional"){let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then(($)=>v8($,X.value));return v8(G,X.value)}if(X.value===void 0)return X;return Y.innerType._zod.run(X,W)}}),bW=q("$ZodNullable",(Q,Y)=>{o.init(Q,Y),n(Q._zod,"optin",()=>Y.innerType._zod.optin),n(Q._zod,"optout",()=>Y.innerType._zod.optout),n(Q._zod,"pattern",()=>{let X=Y.innerType._zod.pattern;return X?new RegExp(`^(${J4(X.source)}|null)$`):void 0}),n(Q._zod,"values",()=>{return Y.innerType._zod.values?new Set([...Y.innerType._zod.values,null]):void 0}),Q._zod.parse=(X,W)=>{if(X.value===null)return X;return Y.innerType._zod.run(X,W)}}),jW=q("$ZodDefault",(Q,Y)=>{o.init(Q,Y),Q._zod.optin="optional",n(Q._zod,"values",()=>Y.innerType._zod.values),Q._zod.parse=(X,W)=>{if(W.direction==="backward")return Y.innerType._zod.run(X,W);if(X.value===void 0)return X.value=Y.defaultValue,X;let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then(($)=>x8($,Y));return x8(G,Y)}});function x8(Q,Y){if(Q.value===void 0)Q.value=Y.defaultValue;return Q}var IW=q("$ZodPrefault",(Q,Y)=>{o.init(Q,Y),Q._zod.optin="optional",n(Q._zod,"values",()=>Y.innerType._zod.values),Q._zod.parse=(X,W)=>{if(W.direction==="backward")return Y.innerType._zod.run(X,W);if(X.value===void 0)X.value=Y.defaultValue;return Y.innerType._zod.run(X,W)}}),EW=q("$ZodNonOptional",(Q,Y)=>{o.init(Q,Y),n(Q._zod,"values",()=>{let X=Y.innerType._zod.values;return X?new Set([...X].filter((W)=>W!==void 0)):void 0}),Q._zod.parse=(X,W)=>{let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then(($)=>_8($,Q));return _8(G,Q)}});function _8(Q,Y){if(!Q.issues.length&&Q.value===void 0)Q.issues.push({code:"invalid_type",expected:"nonoptional",input:Q.value,inst:Y});return Q}var TW=q("$ZodCatch",(Q,Y)=>{o.init(Q,Y),n(Q._zod,"optin",()=>Y.innerType._zod.optin),n(Q._zod,"optout",()=>Y.innerType._zod.optout),n(Q._zod,"values",()=>Y.innerType._zod.values),Q._zod.parse=(X,W)=>{if(W.direction==="backward")return Y.innerType._zod.run(X,W);let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then(($)=>{if(X.value=$.value,$.issues.length)X.value=Y.catchValue({...X,error:{issues:$.issues.map((z)=>x0(z,W,T0()))},input:X.value}),X.issues=[];return X});if(X.value=G.value,G.issues.length)X.value=Y.catchValue({...X,error:{issues:G.issues.map(($)=>x0($,W,T0()))},input:X.value}),X.issues=[];return X}});var SW=q("$ZodPipe",(Q,Y)=>{o.init(Q,Y),n(Q._zod,"values",()=>Y.in._zod.values),n(Q._zod,"optin",()=>Y.in._zod.optin),n(Q._zod,"optout",()=>Y.out._zod.optout),n(Q._zod,"propValues",()=>Y.in._zod.propValues),Q._zod.parse=(X,W)=>{if(W.direction==="backward"){let $=Y.out._zod.run(X,W);if($ instanceof Promise)return $.then((z)=>K6(z,Y.in,W));return K6($,Y.in,W)}let G=Y.in._zod.run(X,W);if(G instanceof Promise)return G.then(($)=>K6($,Y.out,W));return K6(G,Y.out,W)}});function K6(Q,Y,X){if(Q.issues.length)return Q.aborted=!0,Q;return Y._zod.run({value:Q.value,issues:Q.issues},X)}var RW=q("$ZodReadonly",(Q,Y)=>{o.init(Q,Y),n(Q._zod,"propValues",()=>Y.innerType._zod.propValues),n(Q._zod,"values",()=>Y.innerType._zod.values),n(Q._zod,"optin",()=>Y.innerType._zod.optin),n(Q._zod,"optout",()=>Y.innerType._zod.optout),Q._zod.parse=(X,W)=>{if(W.direction==="backward")return Y.innerType._zod.run(X,W);let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then(g8);return g8(G)}});function g8(Q){return Q.value=Object.freeze(Q.value),Q}var CW=q("$ZodCustom",(Q,Y)=>{A0.init(Q,Y),o.init(Q,Y),Q._zod.parse=(X,W)=>{return X},Q._zod.check=(X)=>{let W=X.value,G=Y.fn(W);if(G instanceof Promise)return G.then(($)=>y8($,X,W,Q));y8(G,X,W,Q);return}});function y8(Q,Y,X,W){if(!Q){let G={code:"custom",input:X,inst:W,path:[...W._zod.def.path??[]],continue:!W._zod.def.abort};if(W._zod.def.params)G.params=W._zod.def.params;Y.issues.push(y1(G))}}var UA=(Q)=>{let Y=typeof Q;switch(Y){case"number":return Number.isNaN(Q)?"NaN":"number";case"object":{if(Array.isArray(Q))return"array";if(Q===null)return"null";if(Object.getPrototypeOf(Q)!==Object.prototype&&Q.constructor)return Q.constructor.name}}return Y},KA=()=>{let Q={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 Y(W){return Q[W]??null}let X={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 ${UA(W.input)}`;case"invalid_value":if(W.values.length===1)return`Invalid input: expected ${$6(W.values[0])}`;return`Invalid option: expected one of ${X6(W.values,"|")}`;case"too_big":{let G=W.inclusive?"<=":"<",$=Y(W.origin);if($)return`Too big: expected ${W.origin??"value"} to have ${G}${W.maximum.toString()} ${$.unit??"elements"}`;return`Too big: expected ${W.origin??"value"} to be ${G}${W.maximum.toString()}`}case"too_small":{let G=W.inclusive?">=":">",$=Y(W.origin);if($)return`Too small: expected ${W.origin} to have ${G}${W.minimum.toString()} ${$.unit}`;return`Too small: expected ${W.origin} to be ${G}${W.minimum.toString()}`}case"invalid_format":{let G=W;if(G.format==="starts_with")return`Invalid string: must start with "${G.prefix}"`;if(G.format==="ends_with")return`Invalid string: must end with "${G.suffix}"`;if(G.format==="includes")return`Invalid string: must include "${G.includes}"`;if(G.format==="regex")return`Invalid string: must match pattern ${G.pattern}`;return`Invalid ${X[G.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":""}: ${X6(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 nQ(){return{localeError:KA()}}var kZ=Symbol("ZodOutput"),vZ=Symbol("ZodInput");class kW{constructor(){this._map=new WeakMap,this._idmap=new Map}add(Q,...Y){let X=Y[0];if(this._map.set(Q,X),X&&typeof X==="object"&&"id"in X){if(this._idmap.has(X.id))throw Error(`ID ${X.id} already exists in the registry`);this._idmap.set(X.id,Q)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(Q){let Y=this._map.get(Q);if(Y&&typeof Y==="object"&&"id"in Y)this._idmap.delete(Y.id);return this._map.delete(Q),this}get(Q){let Y=Q._zod.parent;if(Y){let X={...this.get(Y)??{}};delete X.id;let W={...X,...this._map.get(Q)};return Object.keys(W).length?W:void 0}return this._map.get(Q)}has(Q){return this._map.has(Q)}}function DA(){return new kW}var B4=DA();function vW(Q,Y){return new Q({type:"string",...T(Y)})}function xW(Q,Y){return new Q({type:"string",format:"email",check:"string_format",abort:!1,...T(Y)})}function rQ(Q,Y){return new Q({type:"string",format:"guid",check:"string_format",abort:!1,...T(Y)})}function _W(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,...T(Y)})}function gW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...T(Y)})}function yW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...T(Y)})}function uW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...T(Y)})}function hW(Q,Y){return new Q({type:"string",format:"url",check:"string_format",abort:!1,...T(Y)})}function fW(Q,Y){return new Q({type:"string",format:"emoji",check:"string_format",abort:!1,...T(Y)})}function lW(Q,Y){return new Q({type:"string",format:"nanoid",check:"string_format",abort:!1,...T(Y)})}function mW(Q,Y){return new Q({type:"string",format:"cuid",check:"string_format",abort:!1,...T(Y)})}function cW(Q,Y){return new Q({type:"string",format:"cuid2",check:"string_format",abort:!1,...T(Y)})}function pW(Q,Y){return new Q({type:"string",format:"ulid",check:"string_format",abort:!1,...T(Y)})}function iW(Q,Y){return new Q({type:"string",format:"xid",check:"string_format",abort:!1,...T(Y)})}function nW(Q,Y){return new Q({type:"string",format:"ksuid",check:"string_format",abort:!1,...T(Y)})}function rW(Q,Y){return new Q({type:"string",format:"ipv4",check:"string_format",abort:!1,...T(Y)})}function dW(Q,Y){return new Q({type:"string",format:"ipv6",check:"string_format",abort:!1,...T(Y)})}function oW(Q,Y){return new Q({type:"string",format:"cidrv4",check:"string_format",abort:!1,...T(Y)})}function tW(Q,Y){return new Q({type:"string",format:"cidrv6",check:"string_format",abort:!1,...T(Y)})}function aW(Q,Y){return new Q({type:"string",format:"base64",check:"string_format",abort:!1,...T(Y)})}function sW(Q,Y){return new Q({type:"string",format:"base64url",check:"string_format",abort:!1,...T(Y)})}function eW(Q,Y){return new Q({type:"string",format:"e164",check:"string_format",abort:!1,...T(Y)})}function QG(Q,Y){return new Q({type:"string",format:"jwt",check:"string_format",abort:!1,...T(Y)})}function YG(Q,Y){return new Q({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...T(Y)})}function XG(Q,Y){return new Q({type:"string",format:"date",check:"string_format",...T(Y)})}function WG(Q,Y){return new Q({type:"string",format:"time",check:"string_format",precision:null,...T(Y)})}function GG(Q,Y){return new Q({type:"string",format:"duration",check:"string_format",...T(Y)})}function $G(Q,Y){return new Q({type:"number",checks:[],...T(Y)})}function zG(Q,Y){return new Q({type:"number",check:"number_format",abort:!1,format:"safeint",...T(Y)})}function JG(Q,Y){return new Q({type:"boolean",...T(Y)})}function HG(Q,Y){return new Q({type:"null",...T(Y)})}function AG(Q){return new Q({type:"unknown"})}function UG(Q,Y){return new Q({type:"never",...T(Y)})}function L6(Q,Y){return new fQ({check:"less_than",...T(Y),value:Q,inclusive:!1})}function L4(Q,Y){return new fQ({check:"less_than",...T(Y),value:Q,inclusive:!0})}function F6(Q,Y){return new lQ({check:"greater_than",...T(Y),value:Q,inclusive:!1})}function F4(Q,Y){return new lQ({check:"greater_than",...T(Y),value:Q,inclusive:!0})}function q6(Q,Y){return new q8({check:"multiple_of",...T(Y),value:Q})}function O6(Q,Y){return new M8({check:"max_length",...T(Y),maximum:Q})}function u1(Q,Y){return new V8({check:"min_length",...T(Y),minimum:Q})}function M6(Q,Y){return new Z8({check:"length_equals",...T(Y),length:Q})}function dQ(Q,Y){return new N8({check:"string_format",format:"regex",...T(Y),pattern:Q})}function oQ(Q){return new w8({check:"string_format",format:"lowercase",...T(Q)})}function tQ(Q){return new P8({check:"string_format",format:"uppercase",...T(Q)})}function aQ(Q,Y){return new b8({check:"string_format",format:"includes",...T(Y),includes:Q})}function sQ(Q,Y){return new j8({check:"string_format",format:"starts_with",...T(Y),prefix:Q})}function eQ(Q,Y){return new I8({check:"string_format",format:"ends_with",...T(Y),suffix:Q})}function I1(Q){return new E8({check:"overwrite",tx:Q})}function Q9(Q){return I1((Y)=>Y.normalize(Q))}function Y9(){return I1((Q)=>Q.trim())}function X9(){return I1((Q)=>Q.toLowerCase())}function W9(){return I1((Q)=>Q.toUpperCase())}function KG(Q,Y,X){return new Q({type:"array",element:Y,...T(X)})}function DG(Q,Y,X){let W=T(X);return W.abort??(W.abort=!0),new Q({type:"custom",check:"custom",fn:Y,...W})}function BG(Q,Y,X){return new Q({type:"custom",check:"custom",fn:Y,...T(X)})}function LG(Q){let Y=BA((X)=>{return X.addIssue=(W)=>{if(typeof W==="string")X.issues.push(y1(W,X.value,Y._zod.def));else{let G=W;if(G.fatal)G.continue=!1;G.code??(G.code="custom"),G.input??(G.input=X.value),G.inst??(G.inst=Y),G.continue??(G.continue=!Y._zod.def.abort),X.issues.push(y1(G))}},Q(X.value,X)});return Y}function BA(Q,Y){let X=new A0({check:"custom",...T(Y)});return X._zod.check=Q,X}function h1(Q){return!!Q._zod}function U1(Q,Y){if(h1(Q))return U4(Q,Y);return Q.safeParse(Y)}function V6(Q){if(!Q)return;let Y;if(h1(Q))Y=Q._zod?.def?.shape;else Y=Q.shape;if(!Y)return;if(typeof Y==="function")try{return Y()}catch{return}return Y}function FG(Q){if(h1(Q)){let $=Q._zod?.def;if($){if($.value!==void 0)return $.value;if(Array.isArray($.values)&&$.values.length>0)return $.values[0]}}let X=Q._def;if(X){if(X.value!==void 0)return X.value;if(Array.isArray(X.values)&&X.values.length>0)return X.values[0]}let W=Q.value;if(W!==void 0)return W;return}var O4={};LX(O4,{time:()=>z9,duration:()=>J9,datetime:()=>G9,date:()=>$9,ZodISOTime:()=>MG,ZodISODuration:()=>VG,ZodISODateTime:()=>qG,ZodISODate:()=>OG});var qG=q("ZodISODateTime",(Q,Y)=>{o8.init(Q,Y),s.init(Q,Y)});function G9(Q){return YG(qG,Q)}var OG=q("ZodISODate",(Q,Y)=>{t8.init(Q,Y),s.init(Q,Y)});function $9(Q){return XG(OG,Q)}var MG=q("ZodISOTime",(Q,Y)=>{a8.init(Q,Y),s.init(Q,Y)});function z9(Q){return WG(MG,Q)}var VG=q("ZodISODuration",(Q,Y)=>{s8.init(Q,Y),s.init(Q,Y)});function J9(Q){return GG(VG,Q)}var ZG=(Q,Y)=>{z6.init(Q,Y),Q.name="ZodError",Object.defineProperties(Q,{format:{value:(X)=>CX(Q,X)},flatten:{value:(X)=>RX(Q,X)},addIssue:{value:(X)=>{Q.issues.push(X),Q.message=JSON.stringify(Q.issues,_1,2)}},addIssues:{value:(X)=>{Q.issues.push(...X),Q.message=JSON.stringify(Q.issues,_1,2)}},isEmpty:{get(){return Q.issues.length===0}}})},MN=q("ZodError",ZG),I0=q("ZodError",ZG,{Parent:Error});var NG=J6(I0),wG=H6(I0),PG=A4(I0),bG=K4(I0),jG=kX(I0),IG=vX(I0),EG=xX(I0),TG=_X(I0),SG=gX(I0),RG=yX(I0),CG=uX(I0),kG=hX(I0);var X0=q("ZodType",(Q,Y)=>{return o.init(Q,Y),Q.def=Y,Q.type=Y.type,Object.defineProperty(Q,"_def",{value:Y}),Q.check=(...X)=>{return Q.clone(m.mergeDefs(Y,{checks:[...Y.checks??[],...X.map((W)=>typeof W==="function"?{_zod:{check:W,def:{check:"custom"},onattach:[]}}:W)]}))},Q.clone=(X,W)=>v0(Q,X,W),Q.brand=()=>Q,Q.register=(X,W)=>{return X.add(Q,W),Q},Q.parse=(X,W)=>NG(Q,X,W,{callee:Q.parse}),Q.safeParse=(X,W)=>PG(Q,X,W),Q.parseAsync=async(X,W)=>wG(Q,X,W,{callee:Q.parseAsync}),Q.safeParseAsync=async(X,W)=>bG(Q,X,W),Q.spa=Q.safeParseAsync,Q.encode=(X,W)=>jG(Q,X,W),Q.decode=(X,W)=>IG(Q,X,W),Q.encodeAsync=async(X,W)=>EG(Q,X,W),Q.decodeAsync=async(X,W)=>TG(Q,X,W),Q.safeEncode=(X,W)=>SG(Q,X,W),Q.safeDecode=(X,W)=>RG(Q,X,W),Q.safeEncodeAsync=async(X,W)=>CG(Q,X,W),Q.safeDecodeAsync=async(X,W)=>kG(Q,X,W),Q.refine=(X,W)=>Q.check(A3(X,W)),Q.superRefine=(X)=>Q.check(U3(X)),Q.overwrite=(X)=>Q.check(I1(X)),Q.optional=()=>Y0(Q),Q.nullable=()=>_G(Q),Q.nullish=()=>Y0(_G(Q)),Q.nonoptional=(X)=>W3(Q,X),Q.array=()=>u(Q),Q.or=(X)=>d([Q,X]),Q.and=(X)=>N6(Q,X),Q.transform=(X)=>A9(Q,fG(X)),Q.default=(X)=>Q3(Q,X),Q.prefault=(X)=>X3(Q,X),Q.catch=(X)=>$3(Q,X),Q.pipe=(X)=>A9(Q,X),Q.readonly=()=>H3(Q),Q.describe=(X)=>{let W=Q.clone();return B4.add(W,{description:X}),W},Object.defineProperty(Q,"description",{get(){return B4.get(Q)?.description},configurable:!0}),Q.meta=(...X)=>{if(X.length===0)return B4.get(Q);let W=Q.clone();return B4.add(W,X[0]),W},Q.isOptional=()=>Q.safeParse(void 0).success,Q.isNullable=()=>Q.safeParse(null).success,Q}),gG=q("_ZodString",(Q,Y)=>{B6.init(Q,Y),X0.init(Q,Y);let X=Q._zod.bag;Q.format=X.format??null,Q.minLength=X.minimum??null,Q.maxLength=X.maximum??null,Q.regex=(...W)=>Q.check(dQ(...W)),Q.includes=(...W)=>Q.check(aQ(...W)),Q.startsWith=(...W)=>Q.check(sQ(...W)),Q.endsWith=(...W)=>Q.check(eQ(...W)),Q.min=(...W)=>Q.check(u1(...W)),Q.max=(...W)=>Q.check(O6(...W)),Q.length=(...W)=>Q.check(M6(...W)),Q.nonempty=(...W)=>Q.check(u1(1,...W)),Q.lowercase=(W)=>Q.check(oQ(W)),Q.uppercase=(W)=>Q.check(tQ(W)),Q.trim=()=>Q.check(Y9()),Q.normalize=(...W)=>Q.check(Q9(...W)),Q.toLowerCase=()=>Q.check(X9()),Q.toUpperCase=()=>Q.check(W9())}),wA=q("ZodString",(Q,Y)=>{B6.init(Q,Y),gG.init(Q,Y),Q.email=(X)=>Q.check(xW(PA,X)),Q.url=(X)=>Q.check(hW(bA,X)),Q.jwt=(X)=>Q.check(QG(hA,X)),Q.emoji=(X)=>Q.check(fW(jA,X)),Q.guid=(X)=>Q.check(rQ(vG,X)),Q.uuid=(X)=>Q.check(_W(Z6,X)),Q.uuidv4=(X)=>Q.check(gW(Z6,X)),Q.uuidv6=(X)=>Q.check(yW(Z6,X)),Q.uuidv7=(X)=>Q.check(uW(Z6,X)),Q.nanoid=(X)=>Q.check(lW(IA,X)),Q.guid=(X)=>Q.check(rQ(vG,X)),Q.cuid=(X)=>Q.check(mW(EA,X)),Q.cuid2=(X)=>Q.check(cW(TA,X)),Q.ulid=(X)=>Q.check(pW(SA,X)),Q.base64=(X)=>Q.check(aW(gA,X)),Q.base64url=(X)=>Q.check(sW(yA,X)),Q.xid=(X)=>Q.check(iW(RA,X)),Q.ksuid=(X)=>Q.check(nW(CA,X)),Q.ipv4=(X)=>Q.check(rW(kA,X)),Q.ipv6=(X)=>Q.check(dW(vA,X)),Q.cidrv4=(X)=>Q.check(oW(xA,X)),Q.cidrv6=(X)=>Q.check(tW(_A,X)),Q.e164=(X)=>Q.check(eW(uA,X)),Q.datetime=(X)=>Q.check(G9(X)),Q.date=(X)=>Q.check($9(X)),Q.time=(X)=>Q.check(z9(X)),Q.duration=(X)=>Q.check(J9(X))});function F(Q){return vW(wA,Q)}var s=q("ZodStringFormat",(Q,Y)=>{t.init(Q,Y),gG.init(Q,Y)}),PA=q("ZodEmail",(Q,Y)=>{f8.init(Q,Y),s.init(Q,Y)});var vG=q("ZodGUID",(Q,Y)=>{u8.init(Q,Y),s.init(Q,Y)});var Z6=q("ZodUUID",(Q,Y)=>{h8.init(Q,Y),s.init(Q,Y)});var bA=q("ZodURL",(Q,Y)=>{l8.init(Q,Y),s.init(Q,Y)});var jA=q("ZodEmoji",(Q,Y)=>{m8.init(Q,Y),s.init(Q,Y)});var IA=q("ZodNanoID",(Q,Y)=>{c8.init(Q,Y),s.init(Q,Y)});var EA=q("ZodCUID",(Q,Y)=>{p8.init(Q,Y),s.init(Q,Y)});var TA=q("ZodCUID2",(Q,Y)=>{i8.init(Q,Y),s.init(Q,Y)});var SA=q("ZodULID",(Q,Y)=>{n8.init(Q,Y),s.init(Q,Y)});var RA=q("ZodXID",(Q,Y)=>{r8.init(Q,Y),s.init(Q,Y)});var CA=q("ZodKSUID",(Q,Y)=>{d8.init(Q,Y),s.init(Q,Y)});var kA=q("ZodIPv4",(Q,Y)=>{e8.init(Q,Y),s.init(Q,Y)});var vA=q("ZodIPv6",(Q,Y)=>{QW.init(Q,Y),s.init(Q,Y)});var xA=q("ZodCIDRv4",(Q,Y)=>{YW.init(Q,Y),s.init(Q,Y)});var _A=q("ZodCIDRv6",(Q,Y)=>{XW.init(Q,Y),s.init(Q,Y)});var gA=q("ZodBase64",(Q,Y)=>{GW.init(Q,Y),s.init(Q,Y)});var yA=q("ZodBase64URL",(Q,Y)=>{$W.init(Q,Y),s.init(Q,Y)});var uA=q("ZodE164",(Q,Y)=>{zW.init(Q,Y),s.init(Q,Y)});var hA=q("ZodJWT",(Q,Y)=>{JW.init(Q,Y),s.init(Q,Y)});var yG=q("ZodNumber",(Q,Y)=>{pQ.init(Q,Y),X0.init(Q,Y),Q.gt=(W,G)=>Q.check(F6(W,G)),Q.gte=(W,G)=>Q.check(F4(W,G)),Q.min=(W,G)=>Q.check(F4(W,G)),Q.lt=(W,G)=>Q.check(L6(W,G)),Q.lte=(W,G)=>Q.check(L4(W,G)),Q.max=(W,G)=>Q.check(L4(W,G)),Q.int=(W)=>Q.check(xG(W)),Q.safe=(W)=>Q.check(xG(W)),Q.positive=(W)=>Q.check(F6(0,W)),Q.nonnegative=(W)=>Q.check(F4(0,W)),Q.negative=(W)=>Q.check(L6(0,W)),Q.nonpositive=(W)=>Q.check(L4(0,W)),Q.multipleOf=(W,G)=>Q.check(q6(W,G)),Q.step=(W,G)=>Q.check(q6(W,G)),Q.finite=()=>Q;let X=Q._zod.bag;Q.minValue=Math.max(X.minimum??Number.NEGATIVE_INFINITY,X.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,Q.maxValue=Math.min(X.maximum??Number.POSITIVE_INFINITY,X.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,Q.isInt=(X.format??"").includes("int")||Number.isSafeInteger(X.multipleOf??0.5),Q.isFinite=!0,Q.format=X.format??null});function i(Q){return $G(yG,Q)}var fA=q("ZodNumberFormat",(Q,Y)=>{HW.init(Q,Y),yG.init(Q,Y)});function xG(Q){return zG(fA,Q)}var lA=q("ZodBoolean",(Q,Y)=>{AW.init(Q,Y),X0.init(Q,Y)});function H0(Q){return JG(lA,Q)}var mA=q("ZodNull",(Q,Y)=>{UW.init(Q,Y),X0.init(Q,Y)});function U9(Q){return HG(mA,Q)}var cA=q("ZodUnknown",(Q,Y)=>{KW.init(Q,Y),X0.init(Q,Y)});function e(){return AG(cA)}var pA=q("ZodNever",(Q,Y)=>{DW.init(Q,Y),X0.init(Q,Y)});function iA(Q){return UG(pA,Q)}var nA=q("ZodArray",(Q,Y)=>{BW.init(Q,Y),X0.init(Q,Y),Q.element=Y.element,Q.min=(X,W)=>Q.check(u1(X,W)),Q.nonempty=(X)=>Q.check(u1(1,X)),Q.max=(X,W)=>Q.check(O6(X,W)),Q.length=(X,W)=>Q.check(M6(X,W)),Q.unwrap=()=>Q.element});function u(Q,Y){return KG(nA,Q,Y)}var uG=q("ZodObject",(Q,Y)=>{qW.init(Q,Y),X0.init(Q,Y),m.defineLazy(Q,"shape",()=>{return Y.shape}),Q.keyof=()=>V0(Object.keys(Q._zod.def.shape)),Q.catchall=(X)=>Q.clone({...Q._zod.def,catchall:X}),Q.passthrough=()=>Q.clone({...Q._zod.def,catchall:e()}),Q.loose=()=>Q.clone({...Q._zod.def,catchall:e()}),Q.strict=()=>Q.clone({...Q._zod.def,catchall:iA()}),Q.strip=()=>Q.clone({...Q._zod.def,catchall:void 0}),Q.extend=(X)=>{return m.extend(Q,X)},Q.safeExtend=(X)=>{return m.safeExtend(Q,X)},Q.merge=(X)=>m.merge(Q,X),Q.pick=(X)=>m.pick(Q,X),Q.omit=(X)=>m.omit(Q,X),Q.partial=(...X)=>m.partial(lG,Q,X[0]),Q.required=(...X)=>m.required(mG,Q,X[0])});function b(Q,Y){let X={type:"object",shape:Q??{},...m.normalizeParams(Y)};return new uG(X)}function q0(Q,Y){return new uG({type:"object",shape:Q,catchall:e(),...m.normalizeParams(Y)})}var hG=q("ZodUnion",(Q,Y)=>{iQ.init(Q,Y),X0.init(Q,Y),Q.options=Y.options});function d(Q,Y){return new hG({type:"union",options:Q,...m.normalizeParams(Y)})}var rA=q("ZodDiscriminatedUnion",(Q,Y)=>{hG.init(Q,Y),OW.init(Q,Y)});function K9(Q,Y,X){return new rA({type:"union",options:Y,discriminator:Q,...m.normalizeParams(X)})}var dA=q("ZodIntersection",(Q,Y)=>{MW.init(Q,Y),X0.init(Q,Y)});function N6(Q,Y){return new dA({type:"intersection",left:Q,right:Y})}var oA=q("ZodRecord",(Q,Y)=>{VW.init(Q,Y),X0.init(Q,Y),Q.keyType=Y.keyType,Q.valueType=Y.valueType});function Q0(Q,Y,X){return new oA({type:"record",keyType:Q,valueType:Y,...m.normalizeParams(X)})}var H9=q("ZodEnum",(Q,Y)=>{ZW.init(Q,Y),X0.init(Q,Y),Q.enum=Y.entries,Q.options=Object.values(Y.entries);let X=new Set(Object.keys(Y.entries));Q.extract=(W,G)=>{let $={};for(let z of W)if(X.has(z))$[z]=Y.entries[z];else throw Error(`Key ${z} not found in enum`);return new H9({...Y,checks:[],...m.normalizeParams(G),entries:$})},Q.exclude=(W,G)=>{let $={...Y.entries};for(let z of W)if(X.has(z))delete $[z];else throw Error(`Key ${z} not found in enum`);return new H9({...Y,checks:[],...m.normalizeParams(G),entries:$})}});function V0(Q,Y){let X=Array.isArray(Q)?Object.fromEntries(Q.map((W)=>[W,W])):Q;return new H9({type:"enum",entries:X,...m.normalizeParams(Y)})}var tA=q("ZodLiteral",(Q,Y)=>{NW.init(Q,Y),X0.init(Q,Y),Q.values=new Set(Y.values),Object.defineProperty(Q,"value",{get(){if(Y.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return Y.values[0]}})});function j(Q,Y){return new tA({type:"literal",values:Array.isArray(Q)?Q:[Q],...m.normalizeParams(Y)})}var aA=q("ZodTransform",(Q,Y)=>{wW.init(Q,Y),X0.init(Q,Y),Q._zod.parse=(X,W)=>{if(W.direction==="backward")throw new G4(Q.constructor.name);X.addIssue=($)=>{if(typeof $==="string")X.issues.push(m.issue($,X.value,Y));else{let z=$;if(z.fatal)z.continue=!1;z.code??(z.code="custom"),z.input??(z.input=X.value),z.inst??(z.inst=Q),X.issues.push(m.issue(z))}};let G=Y.transform(X.value,X);if(G instanceof Promise)return G.then(($)=>{return X.value=$,X});return X.value=G,X}});function fG(Q){return new aA({type:"transform",transform:Q})}var lG=q("ZodOptional",(Q,Y)=>{PW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function Y0(Q){return new lG({type:"optional",innerType:Q})}var sA=q("ZodNullable",(Q,Y)=>{bW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function _G(Q){return new sA({type:"nullable",innerType:Q})}var eA=q("ZodDefault",(Q,Y)=>{jW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType,Q.removeDefault=Q.unwrap});function Q3(Q,Y){return new eA({type:"default",innerType:Q,get defaultValue(){return typeof Y==="function"?Y():m.shallowClone(Y)}})}var Y3=q("ZodPrefault",(Q,Y)=>{IW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function X3(Q,Y){return new Y3({type:"prefault",innerType:Q,get defaultValue(){return typeof Y==="function"?Y():m.shallowClone(Y)}})}var mG=q("ZodNonOptional",(Q,Y)=>{EW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function W3(Q,Y){return new mG({type:"nonoptional",innerType:Q,...m.normalizeParams(Y)})}var G3=q("ZodCatch",(Q,Y)=>{TW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType,Q.removeCatch=Q.unwrap});function $3(Q,Y){return new G3({type:"catch",innerType:Q,catchValue:typeof Y==="function"?Y:()=>Y})}var z3=q("ZodPipe",(Q,Y)=>{SW.init(Q,Y),X0.init(Q,Y),Q.in=Y.in,Q.out=Y.out});function A9(Q,Y){return new z3({type:"pipe",in:Q,out:Y})}var J3=q("ZodReadonly",(Q,Y)=>{RW.init(Q,Y),X0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function H3(Q){return new J3({type:"readonly",innerType:Q})}var cG=q("ZodCustom",(Q,Y)=>{CW.init(Q,Y),X0.init(Q,Y)});function pG(Q,Y){return DG(cG,Q??(()=>!0),Y)}function A3(Q,Y={}){return BG(cG,Q,Y)}function U3(Q){return LG(Q)}function D9(Q,Y){return A9(fG(Q),Y)}T0(nQ());var B9="2025-11-25";var iG=[B9,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],K1="io.modelcontextprotocol/related-task",P6="2.0",U0=pG((Q)=>Q!==null&&(typeof Q==="object"||typeof Q==="function")),nG=d([F(),i().int()]),rG=F(),Bw=q0({ttl:d([i(),U9()]).optional(),pollInterval:i().optional()}),K3=b({ttl:i().optional()}),D3=b({taskId:F()}),L9=q0({progressToken:nG.optional(),[K1]:D3.optional()}),E0=b({_meta:L9.optional()}),M4=E0.extend({task:K3.optional()}),dG=(Q)=>M4.safeParse(Q).success,K0=b({method:F(),params:E0.loose().optional()}),S0=b({_meta:L9.optional()}),R0=b({method:F(),params:S0.loose().optional()}),D0=q0({_meta:L9.optional()}),b6=d([F(),i().int()]),oG=b({jsonrpc:j(P6),id:b6,...K0.shape}).strict(),F9=(Q)=>oG.safeParse(Q).success,tG=b({jsonrpc:j(P6),...R0.shape}).strict(),aG=(Q)=>tG.safeParse(Q).success,q9=b({jsonrpc:j(P6),id:b6,result:D0}).strict(),V4=(Q)=>q9.safeParse(Q).success;var h;(function(Q){Q[Q.ConnectionClosed=-32000]="ConnectionClosed",Q[Q.RequestTimeout=-32001]="RequestTimeout",Q[Q.ParseError=-32700]="ParseError",Q[Q.InvalidRequest=-32600]="InvalidRequest",Q[Q.MethodNotFound=-32601]="MethodNotFound",Q[Q.InvalidParams=-32602]="InvalidParams",Q[Q.InternalError=-32603]="InternalError",Q[Q.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(h||(h={}));var O9=b({jsonrpc:j(P6),id:b6.optional(),error:b({code:i().int(),message:F(),data:e().optional()})}).strict();var sG=(Q)=>O9.safeParse(Q).success;var eG=d([oG,tG,q9,O9]),Lw=d([q9,O9]),j6=D0.strict(),B3=S0.extend({requestId:b6.optional(),reason:F().optional()}),I6=R0.extend({method:j("notifications/cancelled"),params:B3}),L3=b({src:F(),mimeType:F().optional(),sizes:u(F()).optional(),theme:V0(["light","dark"]).optional()}),Z4=b({icons:u(L3).optional()}),f1=b({name:F(),title:F().optional()}),Q$=f1.extend({...f1.shape,...Z4.shape,version:F(),websiteUrl:F().optional(),description:F().optional()}),F3=N6(b({applyDefaults:H0().optional()}),Q0(F(),e())),q3=D9((Q)=>{if(Q&&typeof Q==="object"&&!Array.isArray(Q)){if(Object.keys(Q).length===0)return{form:{}}}return Q},N6(b({form:F3.optional(),url:U0.optional()}),Q0(F(),e()).optional())),O3=q0({list:U0.optional(),cancel:U0.optional(),requests:q0({sampling:q0({createMessage:U0.optional()}).optional(),elicitation:q0({create:U0.optional()}).optional()}).optional()}),M3=q0({list:U0.optional(),cancel:U0.optional(),requests:q0({tools:q0({call:U0.optional()}).optional()}).optional()}),V3=b({experimental:Q0(F(),U0).optional(),sampling:b({context:U0.optional(),tools:U0.optional()}).optional(),elicitation:q3.optional(),roots:b({listChanged:H0().optional()}).optional(),tasks:O3.optional()}),Z3=E0.extend({protocolVersion:F(),capabilities:V3,clientInfo:Q$}),M9=K0.extend({method:j("initialize"),params:Z3});var N3=b({experimental:Q0(F(),U0).optional(),logging:U0.optional(),completions:U0.optional(),prompts:b({listChanged:H0().optional()}).optional(),resources:b({subscribe:H0().optional(),listChanged:H0().optional()}).optional(),tools:b({listChanged:H0().optional()}).optional(),tasks:M3.optional()}),w3=D0.extend({protocolVersion:F(),capabilities:N3,serverInfo:Q$,instructions:F().optional()}),V9=R0.extend({method:j("notifications/initialized"),params:S0.optional()});var E6=K0.extend({method:j("ping"),params:E0.optional()}),P3=b({progress:i(),total:Y0(i()),message:Y0(F())}),b3=b({...S0.shape,...P3.shape,progressToken:nG}),T6=R0.extend({method:j("notifications/progress"),params:b3}),j3=E0.extend({cursor:rG.optional()}),N4=K0.extend({params:j3.optional()}),w4=D0.extend({nextCursor:rG.optional()}),I3=V0(["working","input_required","completed","failed","cancelled"]),P4=b({taskId:F(),status:I3,ttl:d([i(),U9()]),createdAt:F(),lastUpdatedAt:F(),pollInterval:Y0(i()),statusMessage:Y0(F())}),l1=D0.extend({task:P4}),E3=S0.merge(P4),b4=R0.extend({method:j("notifications/tasks/status"),params:E3}),S6=K0.extend({method:j("tasks/get"),params:E0.extend({taskId:F()})}),R6=D0.merge(P4),C6=K0.extend({method:j("tasks/result"),params:E0.extend({taskId:F()})}),Fw=D0.loose(),k6=N4.extend({method:j("tasks/list")}),v6=w4.extend({tasks:u(P4)}),x6=K0.extend({method:j("tasks/cancel"),params:E0.extend({taskId:F()})}),Y$=D0.merge(P4),X$=b({uri:F(),mimeType:Y0(F()),_meta:Q0(F(),e()).optional()}),W$=X$.extend({text:F()}),Z9=F().refine((Q)=>{try{return atob(Q),!0}catch{return!1}},{message:"Invalid Base64 string"}),G$=X$.extend({blob:Z9}),j4=V0(["user","assistant"]),m1=b({audience:u(j4).optional(),priority:i().min(0).max(1).optional(),lastModified:O4.datetime({offset:!0}).optional()}),$$=b({...f1.shape,...Z4.shape,uri:F(),description:Y0(F()),mimeType:Y0(F()),annotations:m1.optional(),_meta:Y0(q0({}))}),T3=b({...f1.shape,...Z4.shape,uriTemplate:F(),description:Y0(F()),mimeType:Y0(F()),annotations:m1.optional(),_meta:Y0(q0({}))}),N9=N4.extend({method:j("resources/list")}),S3=w4.extend({resources:u($$)}),R3=N4.extend({method:j("resources/templates/list")}),C3=w4.extend({resourceTemplates:u(T3)}),w9=E0.extend({uri:F()}),k3=w9,P9=K0.extend({method:j("resources/read"),params:k3}),v3=D0.extend({contents:u(d([W$,G$]))}),x3=R0.extend({method:j("notifications/resources/list_changed"),params:S0.optional()}),_3=w9,g3=K0.extend({method:j("resources/subscribe"),params:_3}),y3=w9,u3=K0.extend({method:j("resources/unsubscribe"),params:y3}),h3=S0.extend({uri:F()}),f3=R0.extend({method:j("notifications/resources/updated"),params:h3}),l3=b({name:F(),description:Y0(F()),required:Y0(H0())}),m3=b({...f1.shape,...Z4.shape,description:Y0(F()),arguments:Y0(u(l3)),_meta:Y0(q0({}))}),c3=N4.extend({method:j("prompts/list")}),p3=w4.extend({prompts:u(m3)}),i3=E0.extend({name:F(),arguments:Q0(F(),F()).optional()}),n3=K0.extend({method:j("prompts/get"),params:i3}),b9=b({type:j("text"),text:F(),annotations:m1.optional(),_meta:Q0(F(),e()).optional()}),j9=b({type:j("image"),data:Z9,mimeType:F(),annotations:m1.optional(),_meta:Q0(F(),e()).optional()}),I9=b({type:j("audio"),data:Z9,mimeType:F(),annotations:m1.optional(),_meta:Q0(F(),e()).optional()}),r3=b({type:j("tool_use"),name:F(),id:F(),input:Q0(F(),e()),_meta:Q0(F(),e()).optional()}),d3=b({type:j("resource"),resource:d([W$,G$]),annotations:m1.optional(),_meta:Q0(F(),e()).optional()}),o3=$$.extend({type:j("resource_link")}),E9=d([b9,j9,I9,o3,d3]),t3=b({role:j4,content:E9}),a3=D0.extend({description:F().optional(),messages:u(t3)}),s3=R0.extend({method:j("notifications/prompts/list_changed"),params:S0.optional()}),e3=b({title:F().optional(),readOnlyHint:H0().optional(),destructiveHint:H0().optional(),idempotentHint:H0().optional(),openWorldHint:H0().optional()}),QU=b({taskSupport:V0(["required","optional","forbidden"]).optional()}),z$=b({...f1.shape,...Z4.shape,description:F().optional(),inputSchema:b({type:j("object"),properties:Q0(F(),U0).optional(),required:u(F()).optional()}).catchall(e()),outputSchema:b({type:j("object"),properties:Q0(F(),U0).optional(),required:u(F()).optional()}).catchall(e()).optional(),annotations:e3.optional(),execution:QU.optional(),_meta:Q0(F(),e()).optional()}),T9=N4.extend({method:j("tools/list")}),YU=w4.extend({tools:u(z$)}),_6=D0.extend({content:u(E9).default([]),structuredContent:Q0(F(),e()).optional(),isError:H0().optional()}),qw=_6.or(D0.extend({toolResult:e()})),XU=M4.extend({name:F(),arguments:Q0(F(),e()).optional()}),I4=K0.extend({method:j("tools/call"),params:XU}),WU=R0.extend({method:j("notifications/tools/list_changed"),params:S0.optional()}),Ow=b({autoRefresh:H0().default(!0),debounceMs:i().int().nonnegative().default(300)}),E4=V0(["debug","info","notice","warning","error","critical","alert","emergency"]),GU=E0.extend({level:E4}),S9=K0.extend({method:j("logging/setLevel"),params:GU}),$U=S0.extend({level:E4,logger:F().optional(),data:e()}),zU=R0.extend({method:j("notifications/message"),params:$U}),JU=b({name:F().optional()}),HU=b({hints:u(JU).optional(),costPriority:i().min(0).max(1).optional(),speedPriority:i().min(0).max(1).optional(),intelligencePriority:i().min(0).max(1).optional()}),AU=b({mode:V0(["auto","required","none"]).optional()}),UU=b({type:j("tool_result"),toolUseId:F().describe("The unique identifier for the corresponding tool call."),content:u(E9).default([]),structuredContent:b({}).loose().optional(),isError:H0().optional(),_meta:Q0(F(),e()).optional()}),KU=K9("type",[b9,j9,I9]),w6=K9("type",[b9,j9,I9,r3,UU]),DU=b({role:j4,content:d([w6,u(w6)]),_meta:Q0(F(),e()).optional()}),BU=M4.extend({messages:u(DU),modelPreferences:HU.optional(),systemPrompt:F().optional(),includeContext:V0(["none","thisServer","allServers"]).optional(),temperature:i().optional(),maxTokens:i().int(),stopSequences:u(F()).optional(),metadata:U0.optional(),tools:u(z$).optional(),toolChoice:AU.optional()}),LU=K0.extend({method:j("sampling/createMessage"),params:BU}),R9=D0.extend({model:F(),stopReason:Y0(V0(["endTurn","stopSequence","maxTokens"]).or(F())),role:j4,content:KU}),C9=D0.extend({model:F(),stopReason:Y0(V0(["endTurn","stopSequence","maxTokens","toolUse"]).or(F())),role:j4,content:d([w6,u(w6)])}),FU=b({type:j("boolean"),title:F().optional(),description:F().optional(),default:H0().optional()}),qU=b({type:j("string"),title:F().optional(),description:F().optional(),minLength:i().optional(),maxLength:i().optional(),format:V0(["email","uri","date","date-time"]).optional(),default:F().optional()}),OU=b({type:V0(["number","integer"]),title:F().optional(),description:F().optional(),minimum:i().optional(),maximum:i().optional(),default:i().optional()}),MU=b({type:j("string"),title:F().optional(),description:F().optional(),enum:u(F()),default:F().optional()}),VU=b({type:j("string"),title:F().optional(),description:F().optional(),oneOf:u(b({const:F(),title:F()})),default:F().optional()}),ZU=b({type:j("string"),title:F().optional(),description:F().optional(),enum:u(F()),enumNames:u(F()).optional(),default:F().optional()}),NU=d([MU,VU]),wU=b({type:j("array"),title:F().optional(),description:F().optional(),minItems:i().optional(),maxItems:i().optional(),items:b({type:j("string"),enum:u(F())}),default:u(F()).optional()}),PU=b({type:j("array"),title:F().optional(),description:F().optional(),minItems:i().optional(),maxItems:i().optional(),items:b({anyOf:u(b({const:F(),title:F()}))}),default:u(F()).optional()}),bU=d([wU,PU]),jU=d([ZU,NU,bU]),IU=d([jU,FU,qU,OU]),EU=M4.extend({mode:j("form").optional(),message:F(),requestedSchema:b({type:j("object"),properties:Q0(F(),IU),required:u(F()).optional()})}),TU=M4.extend({mode:j("url"),message:F(),elicitationId:F(),url:F().url()}),SU=d([EU,TU]),RU=K0.extend({method:j("elicitation/create"),params:SU}),CU=S0.extend({elicitationId:F()}),kU=R0.extend({method:j("notifications/elicitation/complete"),params:CU}),g6=D0.extend({action:V0(["accept","decline","cancel"]),content:D9((Q)=>Q===null?void 0:Q,Q0(F(),d([F(),i(),H0(),u(F())])).optional())}),vU=b({type:j("ref/resource"),uri:F()});var xU=b({type:j("ref/prompt"),name:F()}),_U=E0.extend({ref:d([xU,vU]),argument:b({name:F(),value:F()}),context:b({arguments:Q0(F(),F()).optional()}).optional()}),gU=K0.extend({method:j("completion/complete"),params:_U});var yU=D0.extend({completion:q0({values:u(F()).max(100),total:Y0(i().int()),hasMore:Y0(H0())})}),uU=b({uri:F().startsWith("file://"),name:F().optional(),_meta:Q0(F(),e()).optional()}),hU=K0.extend({method:j("roots/list"),params:E0.optional()}),k9=D0.extend({roots:u(uU)}),fU=R0.extend({method:j("notifications/roots/list_changed"),params:S0.optional()}),Mw=d([E6,M9,gU,S9,n3,c3,N9,R3,P9,g3,u3,I4,T9,S6,C6,k6,x6]),Vw=d([I6,T6,V9,fU,b4]),Zw=d([j6,R9,C9,g6,k9,R6,v6,l1]),Nw=d([E6,LU,RU,hU,S6,C6,k6,x6]),ww=d([I6,T6,zU,f3,x3,WU,s3,b4,kU]),Pw=d([j6,w3,yU,a3,p3,S3,C3,v3,_6,YU,R6,v6,l1]);class _ extends Error{constructor(Q,Y,X){super(`MCP error ${Q}: ${Y}`);this.code=Q,this.data=X,this.name="McpError"}static fromError(Q,Y,X){if(Q===h.UrlElicitationRequired&&X){let W=X;if(W.elicitations)return new J$(W.elicitations,Y)}return new _(Q,Y,X)}}class J$ extends _{constructor(Q,Y=`URL elicitation${Q.length>1?"s":""} required`){super(h.UrlElicitationRequired,Y,{elicitations:Q})}get elicitations(){return this.data?.elicitations??[]}}function D1(Q){return Q==="completed"||Q==="failed"||Q==="cancelled"}var lU=Symbol("Let zodToJsonSchema decide on which parser to use");var XP=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function v9(Q){let X=V6(Q)?.method;if(!X)throw Error("Schema is missing a method literal");let W=FG(X);if(typeof W!=="string")throw Error("Schema method literal must be a string");return W}function x9(Q,Y){let X=U1(Q,Y);if(!X.success)throw X.error;return X.data}var rU=60000;class _9{constructor(Q){if(this._options=Q,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(I6,(Y)=>{this._oncancel(Y)}),this.setNotificationHandler(T6,(Y)=>{this._onprogress(Y)}),this.setRequestHandler(E6,(Y)=>({})),this._taskStore=Q?.taskStore,this._taskMessageQueue=Q?.taskMessageQueue,this._taskStore)this.setRequestHandler(S6,async(Y,X)=>{let W=await this._taskStore.getTask(Y.params.taskId,X.sessionId);if(!W)throw new _(h.InvalidParams,"Failed to retrieve task: Task not found");return{...W}}),this.setRequestHandler(C6,async(Y,X)=>{let W=async()=>{let G=Y.params.taskId;if(this._taskMessageQueue){let z;while(z=await this._taskMessageQueue.dequeue(G,X.sessionId)){if(z.type==="response"||z.type==="error"){let J=z.message,H=J.id,A=this._requestResolvers.get(H);if(A)if(this._requestResolvers.delete(H),z.type==="response")A(J);else{let U=J,K=new _(U.error.code,U.error.message,U.error.data);A(K)}else{let U=z.type==="response"?"Response":"Error";this._onerror(Error(`${U} handler missing for request ${H}`))}continue}await this._transport?.send(z.message,{relatedRequestId:X.requestId})}}let $=await this._taskStore.getTask(G,X.sessionId);if(!$)throw new _(h.InvalidParams,`Task not found: ${G}`);if(!D1($.status))return await this._waitForTaskUpdate(G,X.signal),await W();if(D1($.status)){let z=await this._taskStore.getTaskResult(G,X.sessionId);return this._clearTaskQueue(G),{...z,_meta:{...z._meta,[K1]:{taskId:G}}}}return await W()};return await W()}),this.setRequestHandler(k6,async(Y,X)=>{try{let{tasks:W,nextCursor:G}=await this._taskStore.listTasks(Y.params?.cursor,X.sessionId);return{tasks:W,nextCursor:G,_meta:{}}}catch(W){throw new _(h.InvalidParams,`Failed to list tasks: ${W instanceof Error?W.message:String(W)}`)}}),this.setRequestHandler(x6,async(Y,X)=>{try{let W=await this._taskStore.getTask(Y.params.taskId,X.sessionId);if(!W)throw new _(h.InvalidParams,`Task not found: ${Y.params.taskId}`);if(D1(W.status))throw new _(h.InvalidParams,`Cannot cancel task in terminal status: ${W.status}`);await this._taskStore.updateTaskStatus(Y.params.taskId,"cancelled","Client cancelled task execution.",X.sessionId),this._clearTaskQueue(Y.params.taskId);let G=await this._taskStore.getTask(Y.params.taskId,X.sessionId);if(!G)throw new _(h.InvalidParams,`Task not found after cancellation: ${Y.params.taskId}`);return{_meta:{},...G}}catch(W){if(W instanceof _)throw W;throw new _(h.InvalidRequest,`Failed to cancel task: ${W instanceof Error?W.message:String(W)}`)}})}async _oncancel(Q){if(!Q.params.requestId)return;this._requestHandlerAbortControllers.get(Q.params.requestId)?.abort(Q.params.reason)}_setupTimeout(Q,Y,X,W,G=!1){this._timeoutInfo.set(Q,{timeoutId:setTimeout(W,Y),startTime:Date.now(),timeout:Y,maxTotalTimeout:X,resetTimeoutOnProgress:G,onTimeout:W})}_resetTimeout(Q){let Y=this._timeoutInfo.get(Q);if(!Y)return!1;let X=Date.now()-Y.startTime;if(Y.maxTotalTimeout&&X>=Y.maxTotalTimeout)throw this._timeoutInfo.delete(Q),_.fromError(h.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:Y.maxTotalTimeout,totalElapsed:X});return clearTimeout(Y.timeoutId),Y.timeoutId=setTimeout(Y.onTimeout,Y.timeout),!0}_cleanupTimeout(Q){let Y=this._timeoutInfo.get(Q);if(Y)clearTimeout(Y.timeoutId),this._timeoutInfo.delete(Q)}async connect(Q){this._transport=Q;let Y=this.transport?.onclose;this._transport.onclose=()=>{Y?.(),this._onclose()};let X=this.transport?.onerror;this._transport.onerror=(G)=>{X?.(G),this._onerror(G)};let W=this._transport?.onmessage;this._transport.onmessage=(G,$)=>{if(W?.(G,$),V4(G)||sG(G))this._onresponse(G);else if(F9(G))this._onrequest(G,$);else if(aG(G))this._onnotification(G);else this._onerror(Error(`Unknown message type: ${JSON.stringify(G)}`))},await this._transport.start()}_onclose(){let Q=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();let Y=_.fromError(h.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let X of Q.values())X(Y)}_onerror(Q){this.onerror?.(Q)}_onnotification(Q){let Y=this._notificationHandlers.get(Q.method)??this.fallbackNotificationHandler;if(Y===void 0)return;Promise.resolve().then(()=>Y(Q)).catch((X)=>this._onerror(Error(`Uncaught error in notification handler: ${X}`)))}_onrequest(Q,Y){let X=this._requestHandlers.get(Q.method)??this.fallbackRequestHandler,W=this._transport,G=Q.params?._meta?.[K1]?.taskId;if(X===void 0){let A={jsonrpc:"2.0",id:Q.id,error:{code:h.MethodNotFound,message:"Method not found"}};if(G&&this._taskMessageQueue)this._enqueueTaskMessage(G,{type:"error",message:A,timestamp:Date.now()},W?.sessionId).catch((U)=>this._onerror(Error(`Failed to enqueue error response: ${U}`)));else W?.send(A).catch((U)=>this._onerror(Error(`Failed to send an error response: ${U}`)));return}let $=new AbortController;this._requestHandlerAbortControllers.set(Q.id,$);let z=dG(Q.params)?Q.params.task:void 0,J=this._taskStore?this.requestTaskStore(Q,W?.sessionId):void 0,H={signal:$.signal,sessionId:W?.sessionId,_meta:Q.params?._meta,sendNotification:async(A)=>{let U={relatedRequestId:Q.id};if(G)U.relatedTask={taskId:G};await this.notification(A,U)},sendRequest:async(A,U,K)=>{let D={...K,relatedRequestId:Q.id};if(G&&!D.relatedTask)D.relatedTask={taskId:G};let L=D.relatedTask?.taskId??G;if(L&&J)await J.updateTaskStatus(L,"input_required");return await this.request(A,U,D)},authInfo:Y?.authInfo,requestId:Q.id,requestInfo:Y?.requestInfo,taskId:G,taskStore:J,taskRequestedTtl:z?.ttl,closeSSEStream:Y?.closeSSEStream,closeStandaloneSSEStream:Y?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(z)this.assertTaskHandlerCapability(Q.method)}).then(()=>X(Q,H)).then(async(A)=>{if($.signal.aborted)return;let U={result:A,jsonrpc:"2.0",id:Q.id};if(G&&this._taskMessageQueue)await this._enqueueTaskMessage(G,{type:"response",message:U,timestamp:Date.now()},W?.sessionId);else await W?.send(U)},async(A)=>{if($.signal.aborted)return;let U={jsonrpc:"2.0",id:Q.id,error:{code:Number.isSafeInteger(A.code)?A.code:h.InternalError,message:A.message??"Internal error",...A.data!==void 0&&{data:A.data}}};if(G&&this._taskMessageQueue)await this._enqueueTaskMessage(G,{type:"error",message:U,timestamp:Date.now()},W?.sessionId);else await W?.send(U)}).catch((A)=>this._onerror(Error(`Failed to send response: ${A}`))).finally(()=>{this._requestHandlerAbortControllers.delete(Q.id)})}_onprogress(Q){let{progressToken:Y,...X}=Q.params,W=Number(Y),G=this._progressHandlers.get(W);if(!G){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(Q)}`));return}let $=this._responseHandlers.get(W),z=this._timeoutInfo.get(W);if(z&&$&&z.resetTimeoutOnProgress)try{this._resetTimeout(W)}catch(J){this._responseHandlers.delete(W),this._progressHandlers.delete(W),this._cleanupTimeout(W),$(J);return}G(X)}_onresponse(Q){let Y=Number(Q.id),X=this._requestResolvers.get(Y);if(X){if(this._requestResolvers.delete(Y),V4(Q))X(Q);else{let $=new _(Q.error.code,Q.error.message,Q.error.data);X($)}return}let W=this._responseHandlers.get(Y);if(W===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(Q)}`));return}this._responseHandlers.delete(Y),this._cleanupTimeout(Y);let G=!1;if(V4(Q)&&Q.result&&typeof Q.result==="object"){let $=Q.result;if($.task&&typeof $.task==="object"){let z=$.task;if(typeof z.taskId==="string")G=!0,this._taskProgressTokens.set(z.taskId,Y)}}if(!G)this._progressHandlers.delete(Y);if(V4(Q))W(Q);else{let $=_.fromError(Q.error.code,Q.error.message,Q.error.data);W($)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(Q,Y,X){let{task:W}=X??{};if(!W){try{yield{type:"result",result:await this.request(Q,Y,X)}}catch($){yield{type:"error",error:$ instanceof _?$:new _(h.InternalError,String($))}}return}let G;try{let $=await this.request(Q,l1,X);if($.task)G=$.task.taskId,yield{type:"taskCreated",task:$.task};else throw new _(h.InternalError,"Task creation did not return a task");while(!0){let z=await this.getTask({taskId:G},X);if(yield{type:"taskStatus",task:z},D1(z.status)){if(z.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:G},Y,X)};else if(z.status==="failed")yield{type:"error",error:new _(h.InternalError,`Task ${G} failed`)};else if(z.status==="cancelled")yield{type:"error",error:new _(h.InternalError,`Task ${G} was cancelled`)};return}if(z.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:G},Y,X)};return}let J=z.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((H)=>setTimeout(H,J)),X?.signal?.throwIfAborted()}}catch($){yield{type:"error",error:$ instanceof _?$:new _(h.InternalError,String($))}}}request(Q,Y,X){let{relatedRequestId:W,resumptionToken:G,onresumptiontoken:$,task:z,relatedTask:J}=X??{};return new Promise((H,A)=>{let U=(Z)=>{A(Z)};if(!this._transport){U(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(Q.method),z)this.assertTaskCapability(Q.method)}catch(Z){U(Z);return}X?.signal?.throwIfAborted();let K=this._requestMessageId++,D={...Q,jsonrpc:"2.0",id:K};if(X?.onprogress)this._progressHandlers.set(K,X.onprogress),D.params={...Q.params,_meta:{...Q.params?._meta||{},progressToken:K}};if(z)D.params={...D.params,task:z};if(J)D.params={...D.params,_meta:{...D.params?._meta||{},[K1]:J}};let L=(Z)=>{this._responseHandlers.delete(K),this._progressHandlers.delete(K),this._cleanupTimeout(K),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:K,reason:String(Z)}},{relatedRequestId:W,resumptionToken:G,onresumptiontoken:$}).catch((S)=>this._onerror(Error(`Failed to send cancellation: ${S}`)));let k=Z instanceof _?Z:new _(h.RequestTimeout,String(Z));A(k)};this._responseHandlers.set(K,(Z)=>{if(X?.signal?.aborted)return;if(Z instanceof Error)return A(Z);try{let k=U1(Y,Z.result);if(!k.success)A(k.error);else H(k.data)}catch(k){A(k)}}),X?.signal?.addEventListener("abort",()=>{L(X?.signal?.reason)});let O=X?.timeout??rU,M=()=>L(_.fromError(h.RequestTimeout,"Request timed out",{timeout:O}));this._setupTimeout(K,O,X?.maxTotalTimeout,M,X?.resetTimeoutOnProgress??!1);let N=J?.taskId;if(N){let Z=(k)=>{let S=this._responseHandlers.get(K);if(S)S(k);else this._onerror(Error(`Response handler missing for side-channeled request ${K}`))};this._requestResolvers.set(K,Z),this._enqueueTaskMessage(N,{type:"request",message:D,timestamp:Date.now()}).catch((k)=>{this._cleanupTimeout(K),A(k)})}else this._transport.send(D,{relatedRequestId:W,resumptionToken:G,onresumptiontoken:$}).catch((Z)=>{this._cleanupTimeout(K),A(Z)})})}async getTask(Q,Y){return this.request({method:"tasks/get",params:Q},R6,Y)}async getTaskResult(Q,Y,X){return this.request({method:"tasks/result",params:Q},Y,X)}async listTasks(Q,Y){return this.request({method:"tasks/list",params:Q},v6,Y)}async cancelTask(Q,Y){return this.request({method:"tasks/cancel",params:Q},Y$,Y)}async notification(Q,Y){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(Q.method);let X=Y?.relatedTask?.taskId;if(X){let z={...Q,jsonrpc:"2.0",params:{...Q.params,_meta:{...Q.params?._meta||{},[K1]:Y.relatedTask}}};await this._enqueueTaskMessage(X,{type:"notification",message:z,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(Q.method)&&!Q.params&&!Y?.relatedRequestId&&!Y?.relatedTask){if(this._pendingDebouncedNotifications.has(Q.method))return;this._pendingDebouncedNotifications.add(Q.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(Q.method),!this._transport)return;let z={...Q,jsonrpc:"2.0"};if(Y?.relatedTask)z={...z,params:{...z.params,_meta:{...z.params?._meta||{},[K1]:Y.relatedTask}}};this._transport?.send(z,Y).catch((J)=>this._onerror(J))});return}let $={...Q,jsonrpc:"2.0"};if(Y?.relatedTask)$={...$,params:{...$.params,_meta:{...$.params?._meta||{},[K1]:Y.relatedTask}}};await this._transport.send($,Y)}setRequestHandler(Q,Y){let X=v9(Q);this.assertRequestHandlerCapability(X),this._requestHandlers.set(X,(W,G)=>{let $=x9(Q,W);return Promise.resolve(Y($,G))})}removeRequestHandler(Q){this._requestHandlers.delete(Q)}assertCanSetRequestHandler(Q){if(this._requestHandlers.has(Q))throw Error(`A request handler for ${Q} already exists, which would be overridden`)}setNotificationHandler(Q,Y){let X=v9(Q);this._notificationHandlers.set(X,(W)=>{let G=x9(Q,W);return Promise.resolve(Y(G))})}removeNotificationHandler(Q){this._notificationHandlers.delete(Q)}_cleanupTaskProgressHandler(Q){let Y=this._taskProgressTokens.get(Q);if(Y!==void 0)this._progressHandlers.delete(Y),this._taskProgressTokens.delete(Q)}async _enqueueTaskMessage(Q,Y,X){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(Q,Y,X,W)}async _clearTaskQueue(Q,Y){if(this._taskMessageQueue){let X=await this._taskMessageQueue.dequeueAll(Q,Y);for(let W of X)if(W.type==="request"&&F9(W.message)){let G=W.message.id,$=this._requestResolvers.get(G);if($)$(new _(h.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(G);else this._onerror(Error(`Resolver missing for request ${G} during task ${Q} cleanup`))}}}async _waitForTaskUpdate(Q,Y){let X=this._options?.defaultTaskPollInterval??1000;try{let W=await this._taskStore?.getTask(Q);if(W?.pollInterval)X=W.pollInterval}catch{}return new Promise((W,G)=>{if(Y.aborted){G(new _(h.InvalidRequest,"Request cancelled"));return}let $=setTimeout(W,X);Y.addEventListener("abort",()=>{clearTimeout($),G(new _(h.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(Q,Y){let X=this._taskStore;if(!X)throw Error("No task store configured");return{createTask:async(W)=>{if(!Q)throw Error("No request provided");return await X.createTask(W,Q.id,{method:Q.method,params:Q.params},Y)},getTask:async(W)=>{let G=await X.getTask(W,Y);if(!G)throw new _(h.InvalidParams,"Failed to retrieve task: Task not found");return G},storeTaskResult:async(W,G,$)=>{await X.storeTaskResult(W,G,$,Y);let z=await X.getTask(W,Y);if(z){let J=b4.parse({method:"notifications/tasks/status",params:z});if(await this.notification(J),D1(z.status))this._cleanupTaskProgressHandler(W)}},getTaskResult:(W)=>{return X.getTaskResult(W,Y)},updateTaskStatus:async(W,G,$)=>{let z=await X.getTask(W,Y);if(!z)throw new _(h.InvalidParams,`Task "${W}" not found - it may have been cleaned up`);if(D1(z.status))throw new _(h.InvalidParams,`Cannot update task "${W}" from terminal status "${z.status}" to "${G}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await X.updateTaskStatus(W,G,$,Y);let J=await X.getTask(W,Y);if(J){let H=b4.parse({method:"notifications/tasks/status",params:J});if(await this.notification(H),D1(J.status))this._cleanupTaskProgressHandler(W)}},listTasks:(W)=>{return X.listTasks(W,Y)}}}}function H$(Q){return Q!==null&&typeof Q==="object"&&!Array.isArray(Q)}function A$(Q,Y){let X={...Q};for(let W in Y){let G=W,$=Y[G];if($===void 0)continue;let z=X[G];if(H$(z)&&H$($))X[G]={...z,...$};else X[G]=$}return X}var f5=BX(SY(),1),l5=BX(h5(),1);function XV(){let Q=new f5.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return l5.default(Q),Q}class hY{constructor(Q){this._ajv=Q??XV()}getValidator(Q){let Y="$id"in Q&&typeof Q.$id==="string"?this._ajv.getSchema(Q.$id)??this._ajv.compile(Q):this._ajv.compile(Q);return(X)=>{if(Y(X))return{valid:!0,data:X,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(Y.errors)}}}}class fY{constructor(Q){this._server=Q}requestStream(Q,Y,X){return this._server.requestStream(Q,Y,X)}async getTask(Q,Y){return this._server.getTask({taskId:Q},Y)}async getTaskResult(Q,Y,X){return this._server.getTaskResult({taskId:Q},Y,X)}async listTasks(Q,Y){return this._server.listTasks(Q?{cursor:Q}:void 0,Y)}async cancelTask(Q,Y){return this._server.cancelTask({taskId:Q},Y)}}function m5(Q,Y,X){if(!Q)throw Error(`${X} does not support task creation (required for ${Y})`);switch(Y){case"tools/call":if(!Q.tools?.call)throw Error(`${X} does not support task creation for tools/call (required for ${Y})`);break;default:break}}function c5(Q,Y,X){if(!Q)throw Error(`${X} does not support task creation (required for ${Y})`);switch(Y){case"sampling/createMessage":if(!Q.sampling?.createMessage)throw Error(`${X} does not support task creation for sampling/createMessage (required for ${Y})`);break;case"elicitation/create":if(!Q.elicitation?.create)throw Error(`${X} does not support task creation for elicitation/create (required for ${Y})`);break;default:break}}class lY extends _9{constructor(Q,Y){super(Y);if(this._serverInfo=Q,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(E4.options.map((X,W)=>[X,W])),this.isMessageIgnored=(X,W)=>{let G=this._loggingLevels.get(W);return G?this.LOG_LEVEL_SEVERITY.get(X)<this.LOG_LEVEL_SEVERITY.get(G):!1},this._capabilities=Y?.capabilities??{},this._instructions=Y?.instructions,this._jsonSchemaValidator=Y?.jsonSchemaValidator??new hY,this.setRequestHandler(M9,(X)=>this._oninitialize(X)),this.setNotificationHandler(V9,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(S9,async(X,W)=>{let G=W.sessionId||W.requestInfo?.headers["mcp-session-id"]||void 0,{level:$}=X.params,z=E4.safeParse($);if(z.success)this._loggingLevels.set(G,z.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new fY(this)};return this._experimental}registerCapabilities(Q){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=A$(this._capabilities,Q)}setRequestHandler(Q,Y){let W=V6(Q)?.method;if(!W)throw Error("Schema is missing a method literal");let G;if(h1(W)){let z=W;G=z._zod?.def?.value??z.value}else{let z=W;G=z._def?.value??z.value}if(typeof G!=="string")throw Error("Schema method literal must be a string");if(G==="tools/call"){let z=async(J,H)=>{let A=U1(I4,J);if(!A.success){let L=A.error instanceof Error?A.error.message:String(A.error);throw new _(h.InvalidParams,`Invalid tools/call request: ${L}`)}let{params:U}=A.data,K=await Promise.resolve(Y(J,H));if(U.task){let L=U1(l1,K);if(!L.success){let O=L.error instanceof Error?L.error.message:String(L.error);throw new _(h.InvalidParams,`Invalid task creation result: ${O}`)}return L.data}let D=U1(_6,K);if(!D.success){let L=D.error instanceof Error?D.error.message:String(D.error);throw new _(h.InvalidParams,`Invalid tools/call result: ${L}`)}return D.data};return super.setRequestHandler(Q,z)}return super.setRequestHandler(Q,Y)}assertCapabilityForMethod(Q){switch(Q){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${Q})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${Q})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${Q})`);break;case"ping":break}}assertNotificationCapability(Q){switch(Q){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${Q})`);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 ${Q})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${Q})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${Q})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${Q})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(Q){if(!this._capabilities)return;switch(Q){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${Q})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${Q})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${Q})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${Q})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${Q})`);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 ${Q})`);break;case"ping":case"initialize":break}}assertTaskCapability(Q){c5(this._clientCapabilities?.tasks?.requests,Q,"Client")}assertTaskHandlerCapability(Q){if(!this._capabilities)return;m5(this._capabilities.tasks?.requests,Q,"Server")}async _oninitialize(Q){let Y=Q.params.protocolVersion;return this._clientCapabilities=Q.params.capabilities,this._clientVersion=Q.params.clientInfo,{protocolVersion:iG.includes(Y)?Y:B9,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"},j6)}async createMessage(Q,Y){if(Q.tools||Q.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if(Q.messages.length>0){let X=Q.messages[Q.messages.length-1],W=Array.isArray(X.content)?X.content:[X.content],G=W.some((H)=>H.type==="tool_result"),$=Q.messages.length>1?Q.messages[Q.messages.length-2]:void 0,z=$?Array.isArray($.content)?$.content:[$.content]:[],J=z.some((H)=>H.type==="tool_use");if(G){if(W.some((H)=>H.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!J)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(J){let H=new Set(z.filter((U)=>U.type==="tool_use").map((U)=>U.id)),A=new Set(W.filter((U)=>U.type==="tool_result").map((U)=>U.toolUseId));if(H.size!==A.size||![...H].every((U)=>A.has(U)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if(Q.tools)return this.request({method:"sampling/createMessage",params:Q},C9,Y);return this.request({method:"sampling/createMessage",params:Q},R9,Y)}async elicitInput(Q,Y){switch(Q.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let W=Q;return this.request({method:"elicitation/create",params:W},g6,Y)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let W=Q.mode==="form"?Q:{...Q,mode:"form"},G=await this.request({method:"elicitation/create",params:W},g6,Y);if(G.action==="accept"&&G.content&&W.requestedSchema)try{let z=this._jsonSchemaValidator.getValidator(W.requestedSchema)(G.content);if(!z.valid)throw new _(h.InvalidParams,`Elicitation response content does not match requested schema: ${z.errorMessage}`)}catch($){if($ instanceof _)throw $;throw new _(h.InternalError,`Error validating elicitation response: ${$ instanceof Error?$.message:String($)}`)}return G}}}createElicitationCompletionNotifier(Q,Y){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:Q}},Y)}async listRoots(Q,Y){return this.request({method:"roots/list",params:Q},k9,Y)}async sendLoggingMessage(Q,Y){if(this._capabilities.logging){if(!this.isMessageIgnored(Q.level,Y))return this.notification({method:"notifications/message",params:Q})}}async sendResourceUpdated(Q){return this.notification({method:"notifications/resources/updated",params:Q})}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 p5={name:"@sequenzy/mcp",version:"0.0.101",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 mY=["product-info","domain","tracking","localization","integrations","products","events","tags","labels","goals","sync-rules","api-keys","widgets","team","danger"],i5={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 GV(Q){let X=(Q??process.env.SEQUENZY_APP_URL??"https://sequenzy.com").trim().replace(/\/+$/,"");return X.length>0?X:"https://sequenzy.com"}function l0(Q){let Y=Q?.trim();return Y?Y:void 0}function r0(Q){return encodeURIComponent(Q)}function $0(Q,Y){return`${Q}${Y}`}function z0(Q,Y=""){return`/dashboard/company/${r0(Q)}${Y}`}function n5(Q,Y,X){return $0(Q,`${z0(Y,"/settings")}?tab=${encodeURIComponent(X)}`)}function $V(Q,Y){let X=mY.map((W)=>[W,Y?n5(Q,Y,W):""]);return Object.fromEntries(X)}function Z1(Q={},Y){let X=GV(Y),W=l0(Q.companyId),G={},$=$V(X,W);if(!W)return{appUrl:X,routeTemplates:i5,settingsTabValues:mY,urls:G,settingsUrls:$};G.dashboard=$0(X,z0(W)),G.campaigns=$0(X,z0(W,"/campaign")),G.landingPages=$0(X,z0(W,"/landing-pages")),G.sequences=$0(X,z0(W,"/sequences")),G.settings=$0(X,z0(W,"/settings")),G.emails=$0(X,z0(W,"/emails")),G.subscribers=$0(X,z0(W,"/subscribers")),G.sentEmails=$0(X,z0(W,"/sent-emails")),G.segments=$0(X,z0(W,"/segments")),G.metrics=$0(X,z0(W,"/metrics")),G.transactional=$0(X,z0(W,"/transactional"));let z=l0(Q.campaignId);if(z)G.campaign=$0(X,z0(W,`/campaign/${r0(z)}`)),G.campaignPreview=`${G.campaign}?step=review`;let J=l0(Q.landingPageId);if(J)G.landingPage=$0(X,z0(W,`/landing-pages/${r0(J)}`));let H=l0(Q.sequenceId);if(H)G.sequence=$0(X,z0(W,`/sequences/${r0(H)}`));let A=l0(Q.emailId)??l0(Q.templateId);if(A)G.email=$0(X,z0(W,`/emails/${r0(A)}`)),G.template=G.email;let U=l0(Q.transactionalId);if(U)G.transactionalEmail=$0(X,z0(W,`/transactional/${r0(U)}`));let K=l0(Q.emailSendId);if(K)G.emailSend=$0(X,z0(W,`/sent-emails/${r0(K)}`));let D=l0(Q.domainId);if(D)G.domain=$0(X,z0(W,`/settings/domain/${r0(D)}`)),G.domainVerify=`${G.domain}/verify`;let L=l0(Q.status);if(L)G.campaignList=$0(X,z0(W,`/campaign/list/${r0(L)}`)),G.sequenceList=$0(X,z0(W,`/sequences/list/${r0(L)}`));let O=l0(Q.settingsTab);if(O)G.settingsTab=n5(X,W,O);return{appUrl:X,routeTemplates:i5,settingsTabValues:mY,urls:G,settingsUrls:$}}var r5=[{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 d5(Q){try{let Y;switch(Q){case"sequenzy://dashboard":Y=await B("GET","/api/v1/metrics?period=7d");break;case"sequenzy://company":{let X=await B("GET","/api/v1/account"),W=b1()??X.currentCompanyId;if(!W)throw Error("No company available. Create or select a company first.");Y=await B("GET",`/api/v1/companies/${W}`);break}case"sequenzy://campaigns/recent":Y=await B("GET","/api/v1/campaigns?limit=10");break;case"sequenzy://subscribers/recent":Y=await B("GET","/api/v1/subscribers?sort=createdAt&limit=20");break;case"sequenzy://subscribers/engaged":Y=await B("GET","/api/v1/subscribers?sort=engagement&limit=20");break;case"sequenzy://sequences":Y=await B("GET","/api/v1/sequences");break;case"sequenzy://templates":Y=await B("GET","/api/v1/templates");break;case"sequenzy://segments":Y=await B("GET","/api/v1/segments");break;case"sequenzy://tags":Y=await B("GET","/api/v1/tags");break;case"sequenzy://health":Y=await B("GET","/api/v1/health/deliverability");break;case"sequenzy://app-routes":Y=Z1();break;default:throw Error(`Unknown resource: ${Q}`)}return{contents:[{uri:Q,mimeType:"application/json",text:JSON.stringify(Y,null,2)}]}}catch(Y){return{contents:[{uri:Q,mimeType:"text/plain",text:$1(Y)}]}}}import{readFileSync as zV,statSync as JV}from"node:fs";import{basename as HV}from"node:path";var GX=' Any block accepts a `conditions` array so it only renders for matching recipients. To branch on a value passed in the transactional send `variables` or an automation `event` payload, use { "id": "c1", "field": "variable", "operator": "is", "value": "plan:pro" } where the text before the colon is a {{merge tag}} path (nested paths like "order.total" or "event.plan" work) and the text after it is the comparison value. `field` may also be "attribute" (same "name:value" form) or "email"/"firstName"/"lastName" (the value is the plain comparison string). Operators: is, is_not, contains, not_contains, gt, gte, lt, lte, is_empty, is_not_empty. For if/else, use a { type: "conditional-group", conditions: [...], ifBranch: { children: [...] }, elseBranch: { children: [...] } } block.',s4=`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: [...] }.${GX}`,Q4=`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\`.${GX}`,tY=`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.${GX}`,NQ="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.",AV="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.",o5=500,t5=500,N1={type:"boolean",description:"If true, include machine-classified bot/scanner opens and clicks. Defaults to false, so metrics and activity are human-only."},cY=["send","delivery","bounce","complaint","open","click","unsubscribe","delivery_delay"],a5={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},UV={type:"object",description:"Offset relative to a wait-until date.",properties:{days:{type:"number"},hours:{type:"number"},minutes:{type:"number"}},additionalProperties:!1},aY={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:UV,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},sY={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},wQ=["gray","red","orange","amber","yellow","lime","green","emerald","teal","cyan","sky","blue","indigo","violet","purple","fuchsia","pink","rose"],PQ=["email.sent","email.delivered","email.delivery_delayed","email.bounced","email.complained","email.opened","email.clicked","email.replied","email.unsubscribed","sms.sent","sms.delivered","sms.failed","sms.opted_out","subscriber.invalid","subscriber.updated","subscriber.unsubscribed","sequence.finished","sequence.failed"],KV=new Set(["get_account","get_app_urls","get_company","get_sync_rules","get_shopify_automation_settings","list_websites","check_website","get_integration_guide","get_subscriber","list_subscriber_notes","search_subscribers","list_products","list_tags","list_lists","list_segments","get_segment_count","list_audience_syncs","list_ad_accounts","list_templates","get_template","list_ab_tests","get_ab_test","get_ab_test_stats","list_campaigns","get_campaign","get_email_send","list_landing_pages","get_landing_page","list_sequences","get_sequence","list_transactional_emails","get_transactional_email","get_stats","get_campaign_stats","get_sequence_stats","list_campaign_events","list_sequence_events","get_subscriber_activity","list_team_members","list_conversations","get_conversation","list_webhooks","list_webhook_deliveries","generate_email","generate_sequence","generate_subject_lines","generate_sms","get_sms_settings"]),DV=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","sync_products","create_tag","update_tag","delete_tag","create_list","update_list","delete_list","add_subscribers_to_list","remove_subscribers_from_list","create_segment","update_segment","delete_segment","create_audience_sync","update_audience_sync","delete_audience_sync","sync_audience_now","create_template","update_template","delete_template","restart_ab_test","update_ab_test_variant","create_ab_test","add_ab_test_variant","delete_ab_test_variant","delete_ab_test","create_campaign","update_campaign","schedule_campaign","send_test_email","send_test_sms","cancel_campaign","pause_campaign","resume_campaign","delete_campaign","duplicate_campaign","resend_campaign_to_non_openers","create_landing_page","update_landing_page","delete_landing_page","publish_landing_page","unpublish_landing_page","connect_landing_page_domain","update_landing_page_domain_settings","create_sequence","update_sequence","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"]),BV=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"]),LV=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","cancel_sequence_enrollments","delete_sequence","cancel_team_invitation","delete_webhook"]);function FV(Q){let Y=KV.has(Q),X=DV.has(Q);if(Y===X)throw Error(`MCP tool "${Q}" must be classified as exactly one of read-only or mutating.`);return{readOnlyHint:Y,destructiveHint:Y?!1:LV.has(Q),openWorldHint:BV.has(Q)}}function qV(Q){return{...Q,annotations:{...Q.annotations,...FV(Q.name)}}}var eY={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"],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"]},OV=Object.entries(eY).map(([Q,Y])=>`${Q}: ${Y.join(", ")}`).join("; "),s5={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","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."},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: ${OV}.`},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)."}},required:["field","operator","value"],additionalProperties:!1},e5={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 QX(Q){if(!Array.isArray(Q))return Q;return Q.map((Y)=>{if(typeof Y!=="object"||Y===null)return Y;let X=Y;if(typeof X.id==="string"&&X.id.trim()!=="")return X;return{...X,id:crypto.randomUUID()}})}function YX(Q){if(typeof Q!=="object"||Q===null)return Q;let Y=Q;if(Y.kind==="filter"||"field"in Y||"operator"in Y||"value"in Y){let X=QX([Y]);return Array.isArray(X)?X[0]:Y}if(Y.kind!=="group")return Q;return{...Y,id:typeof Y.id==="string"&&Y.id.trim()!==""?Y.id:crypto.randomUUID(),children:Array.isArray(Y.children)?Y.children.map(YX):[]}}function MV(Q){let Y=Q.indexOf(":");return Y!==-1&&Q.substring(0,Y).trim().length>0}function VV(Q){let Y=Q.indexOf(":");return Y!==-1&&Q.substring(Y+1).trim().length>0}function QH(Q){if(Q==="all")return!0;let Y=Q.match(/^(\d+)d$/);if(!Y?.[1])return!1;let X=Number.parseInt(Y[1],10);return Number.isInteger(X)&&X>0}function ZV(Q,Y){let X=Y.split(":");if(Q==="at_least"||Q==="less_than_count"){if(X.length<3)return'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".';let $=X.slice(0,-2).join(":").trim(),z=X.at(-2),J=X.at(-1),H=z===void 0?Number.NaN:Number.parseInt(z,10);return $&&Number.isInteger(H)&&H>0&&J!==void 0&&QH(J)?null:'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".'}if(X.length<2)return'Event filters must use "eventName:timeRange", like "saas.purchase:30d".';let W=X.slice(0,-1).join(":").trim(),G=X.at(-1);return W&&G!==void 0&&QH(G)?null:'Event filters must use "eventName:timeRange", like "saas.purchase:30d".'}function NV(Q){let Y=Q.indexOf(":");if(Y===-1)return{productId:Q,subfilter:null,rawValue:null};let X=Q.substring(0,Y),W=Q.substring(Y+1),G=W.indexOf(":");if(G===-1)return{productId:X,subfilter:W,rawValue:null};return{productId:X,subfilter:W.substring(0,G),rawValue:W.substring(G+1)}}function wV(Q){return Q.trim().toLowerCase().replace(/[-\s]+/g,"_")}function PV(Q){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(Q)}function bV(Q,Y){if(Y==="cancels_at"||Y==="cancel_at"||Y==="cancellation_at")return!0;if(Q==="stripeCurrentProduct")return["end_at","ends_at","period_end","period_ends_at","current_period_end"].includes(Y);return["start_at","started_at","trial_start","trial_started_at","end_at","ends_at","trial_end","trial_ends_at"].includes(Y)}function jV(Q){return["is","is_not","gte","lte","gt","lt"].includes(Q)}function IV(Q,Y,X){if(Q==="stripeProduct"){if(Y!=="at_least"&&Y!=="less_than_count")return null;let J=X.indexOf(":");if(J===-1)return null;let H=X.substring(0,J).trim(),A=Number.parseInt(X.substring(J+1).trim(),10);return H&&Number.isInteger(A)&&A>=1?null:'Stripe Product threshold filters must use "productId:count" with a count of at least 1.'}if(Q!=="stripeCurrentProduct"&&Q!=="stripeTrialProduct")return null;let{productId:W,subfilter:G,rawValue:$}=NV(X);if(!W.trim())return"Stripe product filters must include a product ID.";if(!G)return Y==="is"||Y==="is_not"?null:'Stripe current/trial date filters must use "productId:dateField:value".';let z=wV(G);if(PV(z))return Y==="is"||Y==="is_not"?null:"Stripe cancellation flag filters only support is and is_not operators.";if(!bV(Q,z))return`Unsupported Stripe product subfilter "${G}".`;if(!jV(Y))return"Stripe date filters only support is, is_not, gte, lte, gt, and lt operators.";return $?.trim()?null:'Stripe date filters must include a value like "productId:end_at:2026-05-26".'}var EV=new Set(["shopify","woocommerce","api"]);function TV(Q,Y){let X=Y.trim(),W=X.indexOf(":");if(W!==-1&&EV.has(X.substring(0,W).trim()))X=X.substring(W+1).trim();if(!X)return'Purchased Product filters must include a product ID, like "shopify:42".';if(Q!=="at_least"&&Q!=="less_than_count")return null;let G=X.lastIndexOf(":");if(G===-1)return null;let $=X.substring(0,G).trim(),z=Number.parseInt(X.substring(G+1).trim(),10);return $&&Number.isInteger(z)&&z>=1?null:'Purchased Product threshold filters must use "provider:productId:count" with a count of at least 1.'}function $X(Q){if(typeof Q!=="object"||Q===null)return"Segment filters must be objects.";let Y=Q,X=Y.field,W=Y.operator,G=Y.value;if(typeof X!=="string"||!(X in eY))return`Unsupported segment filter field "${String(X)}".`;if(typeof W!=="string")return`Segment filter "${X}" must include an operator.`;let $=eY[X];if(!$.includes(W))return`Operator "${W}" is not supported for ${X} filters. Use one of: ${$.join(", ")}.`;if(W!=="is_empty"&&W!=="is_not_empty"&&(typeof G!=="string"||G.trim().length===0))return`Segment filter "${X}" must include a value.`;if(X==="attribute"&&typeof G==="string"){if(!MV(G))return'Attribute filters must use "attributeName:value" or "attributeName:" for empty checks.';if(W!=="is_empty"&&W!=="is_not_empty"&&!VV(G))return'Attribute filters must include a value after "attributeName:".'}if(X==="event"&&typeof G==="string"){let z=ZV(W,G);if(z)return z}if((X==="stripeProduct"||X==="stripeCurrentProduct"||X==="stripeTrialProduct")&&typeof G==="string"){let z=IV(X,W,G);if(z)return z}if(X==="commerceProduct"&&typeof G==="string"){let z=TV(W,G);if(z)return z}if(X==="tag"&&(W==="contains"||W==="not_contains")){if(!(typeof G==="string"&&G.split(",").map((J)=>J.trim()).some(Boolean)))return"Tag filters must include at least one tag name."}return null}function zX(Q){if(typeof Q!=="object"||Q===null)return[];let Y=Q;if(Y.kind==="filter"||"field"in Y||"operator"in Y||"value"in Y){let X=$X(Y);return X?[X]:[]}if(Array.isArray(Y.children))return Y.children.flatMap(zX);return[]}function w1(Q,Y,X){if(Y.html!==void 0&&Y.blocks!==void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${Q}\`, not both.`);if(Y.blocks!==void 0&&!Array.isArray(Y.blocks))throw Error(`\`blocks\` must be an array when calling \`${Q}\`.`);if(X?.requireContent&&Y.html===void 0&&Y.blocks===void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${Q}\`.`)}function bQ(Q,Y){if(Y.labels===void 0)return;if(!Array.isArray(Y.labels))throw Error(`\`labels\` must be an array when calling \`${Q}\`.`);if(Y.labels.some((X)=>typeof X!=="string"||X.trim().length===0))throw Error(`\`labels\` must contain only non-empty strings when calling \`${Q}\`.`)}function SV(Q){let Y=Q.filters!==void 0,X=Q.root!==void 0;if(Y&&X)throw Error("Provide either `filters` or `root` when calling `create_segment`, not both.");if(!Y&&!X)throw Error("Provide either `filters` or `root` when calling `create_segment`.");if(Y){if(!Array.isArray(Q.filters))throw Error("`filters` must be an array when calling `create_segment`.");if(Q.filters.length===0)throw Error("`filters` must include at least one filter when calling `create_segment`.")}if(X&&(typeof Q.root!=="object"||Q.root===null))throw Error("`root` must be an object when calling `create_segment`.");let W=Y?Q.filters.flatMap((G)=>{let $=$X(G);return $?[$]:[]}):zX(Q.root);if(W.length>0)throw Error(W[0]??"Invalid segment filter in `create_segment`.")}function RV(Q){let Y=Q.filters!==void 0,X=Q.root!==void 0;if(Y&&X)throw Error("Provide either `filters` or `root` when calling `update_segment`, not both.");if(Q.name===void 0&&Q.filterJoinOperator===void 0&&!Y&&!X)throw Error("Provide at least one of `name`, `filters`, `root`, or `filterJoinOperator` when calling `update_segment`.");if(Y){if(!Array.isArray(Q.filters))throw Error("`filters` must be an array when calling `update_segment`.");if(Q.filters.length===0)throw Error("`filters` must include at least one filter when calling `update_segment`.")}if(X&&(typeof Q.root!=="object"||Q.root===null))throw Error("`root` must be an object when calling `update_segment`.");let W=Y?Q.filters.flatMap((G)=>{let $=$X(G);return $?[$]:[]}):X?zX(Q.root):[];if(W.length>0)throw Error(W[0]??"Invalid segment filter in `update_segment`.")}var pY=["name","description","logoUrl","founderName","primaryColor","brandColors","valueProps","testimonials","toneVoice","companyContext","emailLengthPreference","socialLinks","privacyPolicyUrl","termsUrl","address","language","pricing","fontFamily","emailDirection","fromEmail","fromName","replyTo","replyToName"];function iY(Q,Y,X){if(Y[X]!==void 0&&!J0(Y[X]))throw Error(`\`${X}\` must be an object when calling \`${Q}\`.`)}function YH(Q,Y,X){if(Y[X]!==void 0&&!Array.isArray(Y[X]))throw Error(`\`${X}\` must be an array when calling \`${Q}\`.`)}function CV(Q){let Y=new Set(["companyId",...pY]),X=Object.keys(Q).filter((G)=>!Y.has(G));if(X.length>0)throw Error(`\`update_company\` accepts only company product-info fields. Unsupported field${X.length===1?"":"s"}: ${X.map((G)=>`\`${G}\``).join(", ")}.`);let W={};for(let G of pY)if(Q[G]!==void 0)W[G]=Q[G];if(Object.keys(W).length===0)throw Error(`Provide at least one of ${pY.map((G)=>`\`${G}\``).join(", ")} when calling \`update_company\`.`);for(let G of["name","description","logoUrl","founderName","primaryColor","toneVoice","companyContext","emailLengthPreference","privacyPolicyUrl","termsUrl","address","language","fontFamily","emailDirection","fromEmail","fromName","replyTo","replyToName"])if(Q[G]!==void 0&&typeof Q[G]!=="string")throw Error(`\`${G}\` must be a string when calling \`update_company\`.`);if(iY("update_company",Q,"brandColors"),iY("update_company",Q,"socialLinks"),iY("update_company",Q,"pricing"),YH("update_company",Q,"valueProps"),YH("update_company",Q,"testimonials"),typeof Q.primaryColor==="string"&&!/^#[0-9a-f]{6}$/i.test(Q.primaryColor.trim()))throw Error("`primaryColor` must be a 6-digit hex color such as #f97316 when calling `update_company`.");for(let G of["fromEmail","replyTo"]){let $=Q[G];if(typeof $==="string"&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test($.trim()))throw Error(`\`${G}\` must be a valid email address when calling \`update_company\`.`)}if(Q.fromName!==void 0&&Q.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `update_company`.");if(Q.replyToName!==void 0&&Q.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `update_company`.");return W}function kV(Q){if(Q.fromEmail!==void 0&&Q.senderProfileId!==void 0)throw Error("Provide either `fromEmail` or `senderProfileId` when calling `update_sequence`, not both.");if(Q.replyTo!==void 0&&Q.replyProfileId!==void 0)throw Error("Provide either `replyTo` or `replyProfileId` when calling `update_sequence`, not both.");if(Q.fromName!==void 0&&Q.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `update_sequence`.");if(Q.replyToName!==void 0&&Q.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `update_sequence`.");if(Q.clearEnrollmentFieldPath===!0&&Q.enrollmentFieldPath!==void 0)throw Error("Provide either `enrollmentFieldPath` or `clearEnrollmentFieldPath` when calling `update_sequence`, not both.");if(Q.clearSendingWindow===!0&&Q.sendingWindow!==void 0)throw Error("Provide either `sendingWindow` or `clearSendingWindow` when calling `update_sequence`, not both.");if(Q.clearBccEmails===!0&&Q.bccEmails!==void 0)throw Error("Provide either `bccEmails` or `clearBccEmails` when calling `update_sequence`, not both.");if(Q.branch!==void 0&&Q.insertSteps!==void 0)throw Error("Provide either `branch` or `insertSteps` when calling `update_sequence`, not both.");let Y={...Q};if(delete Y.clearEnrollmentFieldPath,delete Y.clearSendingWindow,delete Y.clearBccEmails,Q.clearEnrollmentFieldPath===!0)Y.enrollmentFieldPath=null;if(Q.clearSendingWindow===!0)Y.sendingWindow=null;if(Q.clearBccEmails===!0)Y.bccEmails=null;return Y}function vV(Q){let Y=Q.type==="sms",X;if(Y){let G=w(Q,"text"),$=Array.isArray(Q.blocks)&&Q.blocks.length>0;if(G===void 0&&!$)throw Error("Provide `text` (or `blocks`) when inserting an SMS step with `insert_sequence_step`.");X={type:"sms"};for(let z of["text","blocks","imageUrls","label","name","ineligibleAction","delay","delayMs","waitUntil"])if(Q[z]!==void 0)X[z]=Q[z]}else{w1("insert_sequence_step",Q,{requireContent:!0}),X={subject:R("insert_sequence_step",Q,"subject")};for(let G of["name","previewText","html","blocks","delay","delayMs","waitUntil"])if(Q[G]!==void 0)X[G]=Q[G]}let W={steps:[X]};if(Q.afterNodeId!==void 0)W.afterNodeId=Q.afterNodeId;return{...Q.confirmStructuralChange!==void 0&&{confirmStructuralChange:Q.confirmStructuralChange},insertSteps:W}}function xV(Q){let Y=w(Q,"subscriberId"),X=Q.fieldValues,W=X===void 0?void 0:Array.isArray(X)?X:void 0;if(X!==void 0&&W===void 0)throw Error("`fieldValues` must be an array when calling `cancel_sequence_enrollments`.");let G=W?.map((J)=>typeof J==="string"?J.trim():"").filter((J)=>J.length>0)??[];if(W?.some((J)=>typeof J!=="string")||W!==void 0&&G.length===0)throw Error("`fieldValues` must contain at least one non-empty string when calling `cancel_sequence_enrollments`.");if(Y!==void 0===G.length>0)throw Error("Provide exactly one target when calling `cancel_sequence_enrollments`: `subscriberId` or `fieldValues`.");let $=w(Q,"fieldPath"),z=w(Q,"reason");return{...Y!==void 0&&{subscriberId:Y},...$!==void 0&&{fieldPath:$},...G.length>0&&{fieldValues:G},...typeof Q.dryRun==="boolean"&&{dryRun:Q.dryRun},...z!==void 0&&{reason:z}}}function _V(Q){w1("create_campaign",Q),bQ("create_campaign",Q);let Y=w(Q,"prompt")!==void 0,X=Q.html!==void 0,W=Q.blocks!==void 0,G=Q.templateId!==void 0;if(Q.prompt!==void 0&&!Y)throw Error("`prompt` cannot be empty when calling `create_campaign`.");if(Y&&(X||W||G))throw Error("Provide either `prompt`, `html`, `blocks`, or `templateId` when calling `create_campaign`, not multiple content sources.");if(!Y&&(Q.style!==void 0||Q.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_campaign`.");if(!Y&&w(Q,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_campaign`.")}function gV(Q){w1("create_template",Q),bQ("create_template",Q);let Y=w(Q,"prompt")!==void 0,X=[Y,Q.html!==void 0,Q.blocks!==void 0].filter(Boolean).length;if(Q.prompt!==void 0&&!Y)throw Error("`prompt` cannot be empty when calling `create_template`.");if(X!==1)throw Error("Provide exactly one of `prompt`, `html`, or `blocks` when calling `create_template`.");if(!Y&&(Q.style!==void 0||Q.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_template`.");if(!Y&&w(Q,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_template`.")}function yV(Q){if(w(Q,"scheduledAt")===void 0)throw Error("`scheduledAt` is required when calling `schedule_campaign`.");if(Q.targetLists!==void 0&&!J0(Q.targetLists))throw Error("`targetLists` must be an object when calling `schedule_campaign`.");if(Q.sendTimeOptimization!==void 0){if(typeof Q.sendTimeOptimization!=="boolean")throw Error("`sendTimeOptimization` must be a boolean when calling `schedule_campaign`.")}if(Q.spreadOverHours!==void 0){if(typeof Q.spreadOverHours!=="number"||!Number.isInteger(Q.spreadOverHours)||Q.spreadOverHours<1||Q.spreadOverHours>72)throw Error("`spreadOverHours` must be an integer between 1 and 72 when calling `schedule_campaign`.")}if(Q.recurringInterval!==void 0&&Q.recurringInterval!=="weekly"&&Q.recurringInterval!=="monthly")throw Error("`recurringInterval` must be 'weekly' or 'monthly' when calling `schedule_campaign`.")}function nY(Q,Y,X){let W=new Set(["companyId","landingPageId","name","slug","content"]),G=Object.keys(Y).filter(($)=>!W.has($));if(G.length>0)throw Error(`\`${Q}\` accepts only \`name\`, \`slug\`, and \`content\` update fields. Unsupported field${G.length===1?"":"s"}: ${G.map(($)=>`\`${$}\``).join(", ")}.`);if(X.requireUpdate&&Y.name===void 0&&Y.slug===void 0&&Y.content===void 0)throw Error(`Provide at least one of \`name\`, \`slug\`, or \`content\` when calling \`${Q}\`.`);return{...Y.name!==void 0&&{name:Y.name},...Y.slug!==void 0&&{slug:Y.slug},...Y.content!==void 0&&{content:Y.content}}}function uV(Q){let Y=new Set(["companyId","domain","verify"]),X=Object.keys(Q).filter((W)=>!Y.has(W));if(X.length>0)throw Error(`\`update_landing_page_domain_settings\` accepts only \`domain\` and \`verify\`. Unsupported field${X.length===1?"":"s"}: ${X.map((W)=>`\`${W}\``).join(", ")}.`);if(Q.domain===void 0&&Q.verify!==!0)throw Error("Provide `domain` or `verify: true` when calling `update_landing_page_domain_settings`.");return{...Q.domain!==void 0&&{domain:Q.domain},...typeof Q.verify==="boolean"&&{verify:Q.verify}}}function hV(Q){w1("create_transactional_email",Q);let Y=w(Q,"prompt")!==void 0,X=Q.html!==void 0,W=Q.blocks!==void 0;if(Q.prompt!==void 0&&!Y)throw Error("`prompt` cannot be empty when calling `create_transactional_email`.");if(Y&&(X||W))throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`, not multiple content sources.");if(!Y&&(Q.style!==void 0||Q.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_transactional_email`.");if(!Y&&!X&&!W)throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`.");if(!Y&&w(Q,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_transactional_email`.")}var XX={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},rY={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:{...XX,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:tY,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:sY,delayMs:{type:"number",description:"Delay in milliseconds. Useful for standalone type:'delay' steps."},waitUntil:aY,name:{type:"string",description:"Email template name for email steps."},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 fV(Q){if(!Q||typeof Q!=="object")return null;let Y=Q;if(Y.success!==!1)return null;if(typeof Y.error==="string")return Error(Y.error);if(Y.error&&typeof Y.error==="object"&&typeof Y.error.message==="string")return Error(Y.error.message);if(typeof Y.message==="string")return Error(Y.message);return Error("The tool returned an unsuccessful response.")}function J0(Q){return typeof Q==="object"&&Q!==null&&!Array.isArray(Q)}function XH(Q){return Q.trim().toLowerCase().replace(/\s+/g,"-")}function lV(Q){let Y=new URLSearchParams;if(typeof Q.query==="string"&&Q.query.trim()!=="")Y.set("query",Q.query.trim());if(Array.isArray(Q.tags)&&Q.tags.length>0)Y.set("tags",Q.tags.filter((X)=>typeof X==="string"&&X.trim()!=="").join(","));if(typeof Q.list==="string"&&Q.list.trim()!=="")Y.set("list",Q.list.trim());if(typeof Q.listId==="string"&&Q.listId.trim()!=="")Y.set("listId",Q.listId.trim());if(typeof Q.listName==="string"&&Q.listName.trim()!=="")Y.set("listName",Q.listName.trim());if(typeof Q.segmentId==="string"&&Q.segmentId.trim()!=="")Y.set("segmentId",Q.segmentId);if(typeof Q.status==="string"&&Q.status.trim()!=="")Y.set("status",Q.status.trim());return Y.set("page",String(Q.page)),Y.set("limit",String(Q.pageSize)),Y}async function mV(Q,Y){let X=typeof Q.limit==="number"&&Number.isFinite(Q.limit)?Math.max(1,Math.trunc(Q.limit)):void 0,W=Math.min(100,Math.max(1,X??100)),G=[],$=1,z=0,J=0,H=0;while(!0){let U=lV({query:Q.query,tags:Q.tags,list:Q.list,listId:Q.listId,listName:Q.listName,segmentId:Q.segmentId,status:Q.status,page:$,pageSize:W}),K=await B("GET",`/api/v1/subscribers?${U.toString()}`,void 0,Y);z=K.pagination?.total??K.subscribers.length,J=K.pagination?.totalPages??1,H+=1,G.push(...K.subscribers??[]);let D=X!==void 0&&G.length>=X,L=K.pagination?$>=K.pagination.totalPages:(K.subscribers??[]).length<W;if(D||L)break;$+=1}let A=X!==void 0?G.slice(0,X):G;return{success:!0,subscribers:A,pagination:{page:1,limit:W,total:z,totalPages:J,fetchedPages:H},returned:A.length,truncated:X!==void 0&&z>0&&A.length<z}}function cV(Q){let Y=typeof Q.email==="string"&&Q.email.trim()!==""?Q.email.trim():void 0,X=typeof Q.externalId==="string"&&Q.externalId.trim()!==""?Q.externalId.trim():void 0;return{...Y?{email:Y}:{},...X?{externalId:X}:{}}}function v1(Q,Y){let X=cV(Y);if(!X.email&&!X.externalId)throw Error(`Provide either \`email\` or \`externalId\` when calling \`${Q}\`.`);return X}function WX(Q,Y){let X=new URLSearchParams;if(Y?.includeMachineEngagement)X.set("includeMachineEngagement","true");let W=X.toString(),G=W?`?${W}`:"";if(Q.email)return`/api/v1/subscribers/${encodeURIComponent(Q.email)}${G}`;return X.set("externalId",String(Q.externalId)),`/api/v1/subscribers/external?${X.toString()}`}function WH(Q){if(Q.email)return`/api/v1/subscribers/${encodeURIComponent(Q.email)}/notes`;let Y=new URLSearchParams;return Y.set("externalId",String(Q.externalId)),`/api/v1/subscribers/external/notes?${Y.toString()}`}async function dY(Q,Y,X){return B("GET",WX(Q,X),void 0,Y)}function w(Q,Y){let X=Q[Y];if(typeof X!=="string")return;let W=X.trim();return W.length>0?W:void 0}function R(Q,Y,X){let W=w(Y,X);if(W===void 0)throw Error(`\`${X}\` is required when calling \`${Q}\`.`);return W}function m0(Q,Y,X,W){let G=w(Y,X);if(G===void 0)return;if(!W.includes(G))throw Error(`\`${X}\` must be one of ${W.join(", ")} when calling \`${Q}\`.`);return G}function oY(Q,Y,X,W){let G=R(Q,Y,X);if(!W.includes(G))throw Error(`\`${X}\` must be one of ${W.join(", ")} when calling \`${Q}\`.`);return G}function x1(Q,Y,X,W,G){let $=Y[X];if($===void 0)return;if(typeof $!=="number"||!Number.isInteger($)||$<W||$>G)throw Error(`\`${X}\` must be an integer between ${W} and ${G} when calling \`${Q}\`.`);return $}function pV(Q,Y){let X=[],W=m0(Q,Y,"eventType",cY);if(W)X.push(W);if(Y.eventTypes!==void 0){if(!Array.isArray(Y.eventTypes))throw Error(`\`eventTypes\` must be an array when calling \`${Q}\`.`);Y.eventTypes.forEach((G,$)=>{if(typeof G!=="string")throw Error(`\`eventTypes\` item ${$+1} must be a string when calling \`${Q}\`.`);let z=G.trim();if(!cY.includes(z))throw Error(`\`eventTypes\` item ${$+1} must be one of ${cY.join(", ")} when calling \`${Q}\`.`);X.push(z)})}return[...new Set(X)]}function GH(Q,Y){let X=new URLSearchParams,W=pV(Q,Y);if(W.length>0)X.set("eventTypes",W.join(","));let G=m0(Q,Y,"period",["1h","24h","7d","30d","90d"]);if(G)X.set("period",G);let $=w(Y,"start");if($)X.set("start",$);let z=w(Y,"end");if(z)X.set("end",z);let J=x1(Q,Y,"page",1,1e6);if(J!==void 0)X.set("page",String(J));let H=x1(Q,Y,"limit",1,500);if(H!==void 0)X.set("limit",String(H));if(Y.includeMachineEngagement===!0)X.set("includeMachineEngagement","true");return X}function $H(Q,Y){if(Y.events===void 0)return;if(!Array.isArray(Y.events))throw Error(`\`events\` must be an array when calling \`${Q}\`.`);let X=Y.events.map((W,G)=>{if(typeof W!=="string"||!PQ.includes(W))throw Error(`\`events\` item ${G+1} must be one of ${PQ.join(", ")} when calling \`${Q}\`.`);return W});if(X.length===0)throw Error(`\`events\` must include at least one event type when calling \`${Q}\`.`);return X}function zH(Q,Y){if(!Array.isArray(Y.emails))throw Error(`\`emails\` must be an array when calling \`${Q}\`.`);let X=[];if(Y.emails.forEach((W,G)=>{if(typeof W!=="string")throw Error(`\`emails\` item ${G+1} must be a string when calling \`${Q}\`.`);let $=W.trim();if($.length>0)X.push($)}),X.length===0)throw Error(`\`emails\` must include at least one email address when calling \`${Q}\`.`);if(X.length>o5)throw Error(`\`emails\` must include no more than ${o5} email addresses when calling \`${Q}\`. Split larger batches into multiple calls.`);return X}function JH(Q,Y,X,W){let G=Y[X];if(G===void 0)return;if(!Array.isArray(G))throw Error(`\`${X}\` must be an array when calling \`${Q}\`.`);let $=[];if(G.forEach((z,J)=>{if(typeof z!=="string")throw Error(`\`${X}\` item ${J+1} must be a string when calling \`${Q}\`.`);let H=z.trim();if(H.length>0)$.push(H)}),$.length===0)throw Error(`\`${X}\` must include at least one ${W} when calling \`${Q}\`.`);return $}function iV(Q){let X=JH("enroll_subscribers_in_sequence",Q,"emails","email address"),W=JH("enroll_subscribers_in_sequence",Q,"subscriberIds","subscriber ID"),G=(X?.length??0)+(W?.length??0);if(G===0)throw Error("Provide `emails` or `subscriberIds` when calling `enroll_subscribers_in_sequence`.");if(G>t5)throw Error(`\`emails\` and \`subscriberIds\` must include no more than ${t5} total targets when calling \`enroll_subscribers_in_sequence\`. Split larger batches into multiple calls.`);let $=w(Q,"targetNodeId");return{...X!==void 0&&{emails:X},...W!==void 0&&{subscriberIds:W},...$!==void 0&&{targetNodeId:$}}}var nV={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 rV(Q){let Y=Q.split(".").pop()?.toLowerCase()??"";return nV[Y]??null}var dV=104857600;async function oV(Q,Y){if(!OX())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 X=rV(Q);if(!X)throw Error("Unsupported file type. Use PDF, ePub, ZIP, image, audio, video, or text files.");let W=JV(Q).size;if(W>dV)throw Error(`File is too large (${Math.round(W/1048576)}MB). Delivery files must be 100MB or smaller.`);let G=zV(Q),$=await B("POST","/api/v1/products/delivery/upload-url",{filename:HV(Q),contentType:X,fileSizeBytes:W},Y),z=await fetch($.uploadUrl,{method:"PUT",headers:{"Content-Type":X},body:G});if(!z.ok)throw Error(`File upload failed (${z.status})`);return{url:$.publicUrl,fileName:$.fileName,fileSizeBytes:W,mimeType:X}}async function JX(Q){let Y=w(Q,"companyId");if(Y)return Y;let X=b1();if(X)return X;try{return(await B("GET","/api/v1/account")).currentCompanyId??void 0}catch{return}}async function tV(Q,Y){let X=await JX(Y);if(!X)throw Error(`A company is required when calling \`${Q}\`. Call \`get_account\`, then \`select_company\`, or pass \`companyId\` explicitly.`);return X}function Y4(Q,Y){if(!J0(Q)||!Y)return Q;return{...Q,url:Y}}function HH(Q,Y){if(!J0(Q))return Q;return{...Q,...Y.campaign!==void 0&&{url:Y.campaign},...Y.campaignPreview!==void 0&&{previewUrl:Y.campaignPreview}}}function e4(Q,Y,X){if(!Array.isArray(Q)||!Y)return Q;return Q.map((W)=>{if(!J0(W))return W;let G=w(W,"id");if(!G)return W;let $=Z1({companyId:Y,...X==="campaign"&&{campaignId:G},...X==="landingPage"&&{landingPageId:G},...X==="sequence"&&{sequenceId:G},...X==="template"&&{emailId:G},...X==="transactional"&&{transactionalId:G}});if(X==="campaign")return HH(W,$.urls);let z=X==="sequence"?$.urls.sequence:X==="landingPage"?$.urls.landingPage:X==="template"?$.urls.email:$.urls.transactionalEmail;return Y4(W,z)})}function aV(Q){if(!Array.isArray(Q))return Q;return Q.map((Y)=>{if(!J0(Y))return Y;let X=w(Y,"id");if(!X)return Y;let W=Z1({companyId:X});return{...Y,url:W.urls.dashboard,settingsUrl:W.urls.settings}})}var AH=new Set(["get_account","select_company","create_company","get_company","update_company","list_campaigns","get_campaign","get_email_send","create_campaign","update_campaign","schedule_campaign","send_test_email","cancel_campaign","pause_campaign","resume_campaign","duplicate_campaign","resend_campaign_to_non_openers","list_landing_pages","get_landing_page","create_landing_page","update_landing_page","publish_landing_page","unpublish_landing_page","delete_landing_page","list_sequences","get_sequence","create_sequence","update_sequence","insert_sequence_step","enable_sequence","disable_sequence","pause_sequence_enrollments","resume_sequence_enrollments","cancel_sequence_enrollments","list_ab_tests","get_ab_test","get_ab_test_stats","update_ab_test_variant","list_templates","get_template","create_template","update_template","list_transactional_emails","get_transactional_email","create_transactional_email","update_transactional_email"]);async function sV(Q,Y,X){if(!J0(X)||!AH.has(Q))return X;let W=J0(X.company)?X.company:void 0,$=w(X,"selectedCompanyId")??w(X,"currentCompanyId")??w(X,"companyId")??(W?w(W,"id"):void 0)??(W?w(W,"companyId"):void 0)??await JX(Y);if(!$)return X;let z=J0(X.campaign)?X.campaign:void 0,J=J0(X.sequence)?X.sequence:void 0,H=J0(X.landingPage)?X.landingPage:void 0,A=J0(X.template)?X.template:void 0,U=J0(X.transactional)&&!Array.isArray(X.transactional)?X.transactional:void 0,K={companyId:$,campaignId:w(Y,"campaignId")??w(X,"campaignId")??(z?w(z,"id"):void 0),landingPageId:w(Y,"landingPageId")??w(X,"landingPageId")??(H?w(H,"id"):void 0),sequenceId:w(Y,"sequenceId")??w(X,"sequenceId")??(J?w(J,"id"):void 0),emailId:w(X,"templateId")??(A?w(A,"id"):void 0)??(U?w(U,"emailId"):void 0)??w(Y,"templateId"),transactionalId:w(Y,"transactionalId")??(U?w(U,"id"):void 0)??w(Y,"idOrSlug"),emailSendId:w(Y,"emailSendId")??w(X,"emailSendId")??(J0(X.emailSend)?w(X.emailSend,"id"):void 0),status:w(Y,"status")},D=Z1(K),L=W?Z1({companyId:$}):void 0;return{...X,...Array.isArray(X.companies)&&{companies:aV(X.companies)},...Array.isArray(X.campaigns)&&{campaigns:e4(X.campaigns,$,"campaign")},...Array.isArray(X.landingPages)&&{landingPages:e4(X.landingPages,$,"landingPage")},...Array.isArray(X.sequences)&&{sequences:e4(X.sequences,$,"sequence")},...Array.isArray(X.templates)&&{templates:e4(X.templates,$,"template")},...Array.isArray(X.transactional)&&{transactional:e4(X.transactional,$,"transactional")},...W&&L!==void 0&&{company:{...W,url:L.urls.dashboard,settingsUrl:L.urls.settings}},...z&&D.urls.campaign!==void 0&&{campaign:HH(z,D.urls)},...J&&D.urls.sequence!==void 0&&{sequence:Y4(J,D.urls.sequence)},...H&&D.urls.landingPage!==void 0&&{landingPage:Y4(H,D.urls.landingPage)},...A&&D.urls.email!==void 0&&{template:Y4(A,D.urls.email)},...U&&D.urls.transactionalEmail!==void 0&&{transactional:Y4(U,D.urls.transactionalEmail)},...J0(X.emailSend)&&D.urls.emailSend!==void 0&&{emailSend:Y4(X.emailSend,D.urls.emailSend)},appUrls:D.urls}}var eV={type:"boolean",description:"Whether the Sequenzy operation succeeded."},QZ={type:"string",description:"Human-readable status, confirmation, or next-step message."},YZ={type:"string",description:"Additional context about the result."};function W0(Q){return{type:"object",description:Q,additionalProperties:!0}}function XZ(Q){return{type:"array",description:Q,items:W0("One item in the returned collection.")}}function E(Q){return{type:"string",description:Q}}function b0(Q){return{type:"number",description:Q}}function d0(Q){return{type:"boolean",description:Q}}function V(Q){return W0(`The ${Q} record returned by Sequenzy.`)}function p(Q){return XZ(`List of ${Q} records returned by Sequenzy.`)}var WZ={appUrls:W0("Dashboard URLs for relevant Sequenzy resources."),url:E("Primary dashboard URL for this result."),settingsUrl:E("Company settings URL when available.")},GZ={success:eV,message:QZ,note:YZ,items:{type:"array",description:"Fallback array wrapper used only when a tool returns a bare array.",items:W0("One returned item.")},value:W0("Fallback object wrapper used only when a tool returns a non-object value.")},$Z={get_account:{account:V("account"),companies:p("company"),apiKeyPermissions:W0("Current API key preset and scopes, whether common marketing work is discoverable, any missing marketing read scopes, and the API Keys management URL."),currentCompanyId:E("Company ID selected by the authenticated API key, when available."),selectedCompanyId:E("Company ID selected locally for subsequent MCP calls, when available.")},select_company:{companyId:E("Selected company ID."),companyName:E("Selected company name.")},get_app_urls:{dashboard:E("Company dashboard URL."),settings:E("Company settings URL."),campaign:E("Campaign editor URL."),landingPage:E("Landing page editor URL."),sequence:E("Sequence editor URL."),email:E("Email editor URL."),transactionalEmail:E("Transactional email URL."),emailSend:E("Sent email detail URL."),domain:E("Sending domain settings URL."),urls:W0("All generated URLs keyed by resource type.")},create_company:{company:V("company"),autoSelected:d0("Whether the new company was selected for subsequent MCP calls.")},update_company:{company:V("company")},get_company:{company:V("company")},get_sync_rules:{syncRules:{type:"array",description:"Effective sync rules for the company.",items:W0("One sync rule.")},isDefault:d0("Whether the company still uses the platform default rules.")},update_sync_rules:{syncRules:{type:"array",description:"Effective sync rules after the update.",items:W0("One sync rule.")},isDefault:d0("Whether the company now uses the platform default rules.")},get_shopify_automation_settings:{browseAbandonment:W0("Effective browse-abandonment settings (defaults applied)."),priceDrop:W0("Effective price-drop settings (defaults applied)."),shopDomain:E("Connected Shopify store domain.")},update_shopify_automation_settings:{browseAbandonment:W0("Effective browse-abandonment settings after the update."),priceDrop:W0("Effective price-drop settings after the update."),shopDomain:E("Connected Shopify store domain.")},create_api_key:{apiKey:W0("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:E("Newly created API key if the API response uses the short key field.")},list_websites:{websites:p("sender website")},add_website:{website:V("Sending domain with the SPF, DKIM, MAIL FROM, and inbound DNS records required for setup.")},add_sending_domain:{website:V("Sending domain with the SPF, DKIM, MAIL FROM, and inbound DNS records required for setup.")},check_website:{website:V("sender website"),ready:d0("Whether the sender website is ready."),status:E("Current processing or verification status.")},verify_sending_domain:{website:V("Sending domain with current aggregate, SPF, DKIM, and MAIL FROM verification details."),verified:d0("Whether the sending domain passed the fresh verification check."),message:E("Verification result summary.")},get_integration_guide:{guide:V("integration guide"),code:E("Generated integration code or example."),steps:{type:"array",description:"Setup steps for the requested integration.",items:W0("One setup step.")}},add_subscriber:{subscriber:V("subscriber")},update_subscriber:{subscriber:V("subscriber")},remove_subscriber:{subscriber:V("subscriber"),hardDeleted:d0("Whether the subscriber was permanently deleted.")},get_subscriber:{subscriber:V("subscriber")},list_subscriber_notes:{notes:p("subscriber note")},add_subscriber_note:{note:V("subscriber note")},delete_subscriber_note:{id:E("Deleted subscriber note ID."),deleted:d0("Whether the subscriber note was deleted.")},search_subscribers:{subscribers:p("subscriber"),pagination:W0("Pagination metadata."),returned:b0("Number of subscribers returned."),truncated:d0("Whether the result was truncated by the requested limit.")},list_products:{products:p("product")},upsert_products:{products:p("product"),created:b0("Number of products created."),updated:b0("Number of products updated.")},delete_product:{productId:E("Deleted product ID.")},attach_product_file:{product:V("product"),delivery:V("digital delivery file")},remove_product_file:{product:V("product")},sync_products:{job:V("product sync job"),jobId:E("Queued product sync job ID.")},list_tags:{tags:p("tag")},create_tag:{tag:V("tag")},update_tag:{tag:V("tag")},delete_tag:{tagId:E("Deleted tag ID.")},list_lists:{lists:p("list")},create_list:{list:V("list")},update_list:{list:V("list")},delete_list:{listId:E("Deleted list ID.")},add_subscribers_to_list:{list:V("list"),added:b0("Number of subscribers added to the list."),skipped:b0("Number of subscribers skipped.")},remove_subscribers_from_list:{list:V("list"),removed:b0("Number of subscribers removed from the list."),skipped:b0("Number of subscribers skipped.")},list_segments:{segments:p("segment")},create_segment:{segment:V("segment")},update_segment:{segment:V("segment")},delete_segment:{segmentId:E("Deleted segment ID.")},get_segment_count:{count:b0("Number of subscribers matching the segment."),segmentId:E("Segment ID that was counted.")},list_audience_syncs:{audienceSyncs:p("audience sync")},list_ad_accounts:{adAccounts:p("ad account")},create_audience_sync:{audienceSync:V("audience sync")},update_audience_sync:{audienceSync:V("audience sync")},delete_audience_sync:{audienceSyncId:E("Deleted audience sync ID.")},sync_audience_now:{audienceSync:V("audience sync"),job:V("audience sync job"),jobId:E("Queued audience sync job ID.")},list_templates:{templates:p("email template")},get_template:{template:V("email template")},create_template:{template:V("email template")},update_template:{template:V("email template")},delete_template:{templateId:E("Deleted template ID.")},list_ab_tests:{abTests:p("A/B test")},get_ab_test:{abTest:V("A/B test")},get_ab_test_stats:{abTest:V("A/B test"),stats:V("A/B test statistics")},restart_ab_test:{abTest:V("A/B test")},update_ab_test_variant:{abTest:V("A/B test"),variant:V("A/B test variant")},create_ab_test:{abTest:V("A/B test")},add_ab_test_variant:{abTest:V("A/B test"),variant:V("A/B test variant")},delete_ab_test_variant:{abTest:V("A/B test"),variantId:E("Deleted A/B test variant ID.")},delete_ab_test:{abTestId:E("Deleted A/B test ID.")},list_campaigns:{campaigns:p("campaign")},get_campaign:{campaign:V("campaign")},get_email_send:{emailSend:V("email send")},create_campaign:{campaign:V("campaign")},update_campaign:{campaign:V("campaign")},schedule_campaign:{campaign:V("campaign"),scheduledAt:E("Scheduled send timestamp.")},send_test_email:{emailSend:V("test email send"),recipient:E("Test email recipient.")},send_test_sms:{smsSendId:E("Created test SMS send ID."),toPhone:E("Normalized E.164 destination phone.")},cancel_campaign:{campaign:V("campaign")},pause_campaign:{campaign:V("campaign")},resume_campaign:{campaign:V("campaign")},delete_campaign:{campaignId:E("Deleted campaign ID.")},duplicate_campaign:{campaign:V("duplicated campaign")},resend_campaign_to_non_openers:{campaign:V("non-opener resend draft campaign"),estimatedNonOpenerCount:b0("Estimated number of subscribers who haven't opened the original campaign.")},list_landing_pages:{landingPages:p("landing page")},get_landing_page:{landingPage:V("landing page")},create_landing_page:{landingPage:V("landing page")},update_landing_page:{landingPage:V("landing page")},delete_landing_page:{landingPageId:E("Deleted landing page ID.")},publish_landing_page:{landingPage:V("landing page")},unpublish_landing_page:{landingPage:V("landing page")},connect_landing_page_domain:{landingPage:V("landing page"),domain:E("Connected landing page domain.")},update_landing_page_domain_settings:{landingPage:V("landing page"),domain:E("Landing page domain.")},list_sequences:{sequences:p("sequence")},get_sequence:{sequence:V("sequence")},create_sequence:{sequence:V("sequence")},update_sequence:{sequence:V("sequence")},insert_sequence_step:{sequence:V("sequence"),insertedNodeIds:{type:"array",description:"Node IDs created for the inserted step, including any delay node.",items:E("Inserted automation node ID.")},insertedEmailIds:{type:"array",description:"Email template IDs created for the inserted step.",items:E("Inserted email template ID.")},insertedEmailCount:b0("Number of email steps inserted.")},enable_sequence:{sequence:V("sequence")},disable_sequence:{sequence:V("sequence")},pause_sequence_enrollments:{sequenceId:E("Sequence ID."),enrollmentPaused:d0("Whether new sequence enrollments are paused.")},resume_sequence_enrollments:{sequenceId:E("Sequence ID."),enrollmentPaused:d0("Whether new sequence enrollments are paused.")},enroll_subscribers_in_sequence:{sequence:V("sequence"),enrollments:p("sequence enrollment"),enrolled:b0("Number of subscribers enrolled."),skipped:b0("Number of subscribers skipped.")},cancel_sequence_enrollments:{sequence:V("sequence"),cancelled:b0("Number of enrollments cancelled."),skipped:b0("Number of enrollments skipped.")},delete_sequence:{sequenceId:E("Deleted sequence ID.")},list_transactional_emails:{transactional:p("transactional email")},get_transactional_email:{transactional:V("transactional email")},create_transactional_email:{transactional:V("transactional email")},update_transactional_email:{transactional:V("transactional email")},send_email:{emailSend:V("transactional email send"),transactional:V("transactional email")},get_stats:{stats:V("account or company statistics")},get_campaign_stats:{campaign:V("campaign"),stats:V("campaign statistics")},get_sequence_stats:{sequence:V("sequence"),stats:V("sequence statistics")},list_campaign_events:{events:p("campaign email event"),pagination:W0("Pagination metadata.")},list_sequence_events:{events:p("sequence email event"),pagination:W0("Pagination metadata.")},get_subscriber_activity:{activity:p("subscriber activity event"),subscribers:p("subscriber"),pagination:W0("Pagination metadata.")},list_team_members:{members:p("team member"),invitations:p("team invitation")},invite_team_member:{invitation:V("team invitation")},cancel_team_invitation:{invitationId:E("Cancelled invitation ID.")},list_conversations:{conversations:p("inbox conversation"),pagination:W0("Pagination metadata.")},get_conversation:{conversation:V("inbox conversation"),messages:p("conversation message")},reply_to_conversation:{conversation:V("inbox conversation"),message:V("conversation message")},update_conversation_status:{conversation:V("inbox conversation")},mark_conversation_read:{conversation:V("inbox conversation")},list_webhooks:{webhooks:p("outbound webhook")},create_webhook:{webhook:V("outbound webhook")},update_webhook:{webhook:V("outbound webhook")},delete_webhook:{webhookId:E("Deleted outbound webhook ID.")},test_webhook:{webhook:V("outbound webhook"),delivery:V("test webhook delivery")},list_webhook_deliveries:{deliveries:p("webhook delivery")},replay_webhook_delivery:{delivery:V("webhook delivery"),job:V("webhook replay job")},generate_email:{email:V("generated email"),html:E("Generated HTML email body."),blocks:{type:"array",description:"Generated Sequenzy email blocks, wrapped with company branding (logo + footer) unless applyBranding was false.",items:W0("One generated email block.")},subject:E("Generated subject line."),previewText:E("Generated inbox preview text.")},generate_sequence:{sequence:V("generated sequence"),steps:p("generated sequence step")},generate_subject_lines:{subjectLines:{type:"array",description:"Generated subject line variants.",items:E("One generated subject line.")},variants:p("generated subject line variant")},generate_sms:{prompt:E("The prompt the messages were generated for."),messages:{type:"array",description:"Generated SMS message variants with encoding and segment counts.",items:W0("One generated SMS message.")}},get_sms_settings:{sms:W0("SMS add-on status: enabled, planEligible, creditsBalance, brandPrefix, numbers, readyToSend (paid plan or credits plus an active number).")},submit_feedback:{}};function zZ(Q){let Y=$Z[Q];if(Y===void 0)throw Error(`MCP tool "${Q}" must define outputSchema properties.`);return{type:"object",description:`Structured content returned by the \`${Q}\` MCP tool.`,properties:{...GZ,...Y,...AH.has(Q)?WZ:{}},additionalProperties:!0}}function JZ(Q){return{...Q,outputSchema:zZ(Q.name)}}function HZ(Q){if(J0(Q))return Q;if(Array.isArray(Q))return{items:Q};return{value:Q}}var AZ=[{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
+ `)}L.write("payload.value = newResult;"),L.write("return payload;");let k=L.compile();return(S,y)=>k(D,S,y)},$,z=j1,J=!Y6.jitless,A=J&&vQ.value,U=Y.catchall,K;Q._zod.parse=(D,L)=>{K??(K=W.value);let O=D.value;if(!z(O))return D.issues.push({expected:"object",code:"invalid_type",input:O,inst:Q}),D;if(J&&A&&L?.async===!1&&L.jitless!==!0){if(!$)$=G(Y.shape);if(D=$(D,L),!U)return D;return OW([],O,D,L,K,Q)}return X(D,L)}});function v8(Q,Y,X,W){for(let $ of Q)if($.issues.length===0)return Y.value=$.value,Y;let G=Q.filter(($)=>!A1($));if(G.length===1)return Y.value=G[0].value,G[0];return Y.issues.push({code:"invalid_union",input:Y.value,inst:X,errors:Q.map(($)=>$.issues.map((z)=>x0(z,W,T0())))}),Y}var iQ=q("$ZodUnion",(Q,Y)=>{o.init(Q,Y),n(Q._zod,"optin",()=>Y.options.some((G)=>G._zod.optin==="optional")?"optional":void 0),n(Q._zod,"optout",()=>Y.options.some((G)=>G._zod.optout==="optional")?"optional":void 0),n(Q._zod,"values",()=>{if(Y.options.every((G)=>G._zod.values))return new Set(Y.options.flatMap((G)=>Array.from(G._zod.values)));return}),n(Q._zod,"pattern",()=>{if(Y.options.every((G)=>G._zod.pattern)){let G=Y.options.map(($)=>$._zod.pattern);return new RegExp(`^(${G.map(($)=>J4($.source)).join("|")})$`)}return});let X=Y.options.length===1,W=Y.options[0]._zod.run;Q._zod.parse=(G,$)=>{if(X)return W(G,$);let z=!1,J=[];for(let H of Y.options){let A=H._zod.run({value:G.value,issues:[]},$);if(A instanceof Promise)J.push(A),z=!0;else{if(A.issues.length===0)return A;J.push(A)}}if(!z)return v8(J,G,Q,$);return Promise.all(J).then((H)=>{return v8(H,G,Q,$)})}}),VW=q("$ZodDiscriminatedUnion",(Q,Y)=>{iQ.init(Q,Y);let X=Q._zod.parse;n(Q._zod,"propValues",()=>{let G={};for(let $ of Y.options){let z=$._zod.propValues;if(!z||Object.keys(z).length===0)throw Error(`Invalid discriminated union option at index "${Y.options.indexOf($)}"`);for(let[J,H]of Object.entries(z)){if(!G[J])G[J]=new Set;for(let A of H)G[J].add(A)}}return G});let W=g1(()=>{let G=Y.options,$=new Map;for(let z of G){let J=z._zod.propValues?.[Y.discriminator];if(!J||J.size===0)throw Error(`Invalid discriminated union option at index "${Y.options.indexOf(z)}"`);for(let H of J){if($.has(H))throw Error(`Duplicate discriminator value "${String(H)}"`);$.set(H,z)}}return $});Q._zod.parse=(G,$)=>{let z=G.value;if(!j1(z))return G.issues.push({code:"invalid_type",expected:"object",input:z,inst:Q}),G;let J=W.value.get(z?.[Y.discriminator]);if(J)return J._zod.run(G,$);if(Y.unionFallback)return X(G,$);return G.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:Y.discriminator,input:z,path:[Y.discriminator],inst:Q}),G}}),ZW=q("$ZodIntersection",(Q,Y)=>{o.init(Q,Y),Q._zod.parse=(X,W)=>{let G=X.value,$=Y.left._zod.run({value:G,issues:[]},W),z=Y.right._zod.run({value:G,issues:[]},W);if($ instanceof Promise||z instanceof Promise)return Promise.all([$,z]).then(([H,A])=>{return x8(X,H,A)});return x8(X,$,z)}});function cQ(Q,Y){if(Q===Y)return{valid:!0,data:Q};if(Q instanceof Date&&Y instanceof Date&&+Q===+Y)return{valid:!0,data:Q};if(H1(Q)&&H1(Y)){let X=Object.keys(Y),W=Object.keys(Q).filter(($)=>X.indexOf($)!==-1),G={...Q,...Y};for(let $ of W){let z=cQ(Q[$],Y[$]);if(!z.valid)return{valid:!1,mergeErrorPath:[$,...z.mergeErrorPath]};G[$]=z.data}return{valid:!0,data:G}}if(Array.isArray(Q)&&Array.isArray(Y)){if(Q.length!==Y.length)return{valid:!1,mergeErrorPath:[]};let X=[];for(let W=0;W<Q.length;W++){let G=Q[W],$=Y[W],z=cQ(G,$);if(!z.valid)return{valid:!1,mergeErrorPath:[W,...z.mergeErrorPath]};X.push(z.data)}return{valid:!0,data:X}}return{valid:!1,mergeErrorPath:[]}}function x8(Q,Y,X){if(Y.issues.length)Q.issues.push(...Y.issues);if(X.issues.length)Q.issues.push(...X.issues);if(A1(Q))return Q;let W=cQ(Y.value,X.value);if(!W.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(W.mergeErrorPath)}`);return Q.value=W.data,Q}var NW=q("$ZodRecord",(Q,Y)=>{o.init(Q,Y),Q._zod.parse=(X,W)=>{let G=X.value;if(!H1(G))return X.issues.push({expected:"record",code:"invalid_type",input:G,inst:Q}),X;let $=[];if(Y.keyType._zod.values){let z=Y.keyType._zod.values;X.value={};for(let H of z)if(typeof H==="string"||typeof H==="number"||typeof H==="symbol"){let A=Y.valueType._zod.run({value:G[H],issues:[]},W);if(A instanceof Promise)$.push(A.then((U)=>{if(U.issues.length)X.issues.push(...s0(H,U.issues));X.value[H]=U.value}));else{if(A.issues.length)X.issues.push(...s0(H,A.issues));X.value[H]=A.value}}let J;for(let H in G)if(!z.has(H))J=J??[],J.push(H);if(J&&J.length>0)X.issues.push({code:"unrecognized_keys",input:G,inst:Q,keys:J})}else{X.value={};for(let z of Reflect.ownKeys(G)){if(z==="__proto__")continue;let J=Y.keyType._zod.run({value:z,issues:[]},W);if(J instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(J.issues.length){X.issues.push({code:"invalid_key",origin:"record",issues:J.issues.map((A)=>x0(A,W,T0())),input:z,path:[z],inst:Q}),X.value[J.value]=J.value;continue}let H=Y.valueType._zod.run({value:G[z],issues:[]},W);if(H instanceof Promise)$.push(H.then((A)=>{if(A.issues.length)X.issues.push(...s0(z,A.issues));X.value[J.value]=A.value}));else{if(H.issues.length)X.issues.push(...s0(z,H.issues));X.value[J.value]=H.value}}}if($.length)return Promise.all($).then(()=>X);return X}});var wW=q("$ZodEnum",(Q,Y)=>{o.init(Q,Y);let X=CQ(Y.entries),W=new Set(X);Q._zod.values=W,Q._zod.pattern=new RegExp(`^(${X.filter((G)=>xQ.has(typeof G)).map((G)=>typeof G==="string"?a0(G):G.toString()).join("|")})$`),Q._zod.parse=(G,$)=>{let z=G.value;if(W.has(z))return G;return G.issues.push({code:"invalid_value",values:X,input:z,inst:Q}),G}}),PW=q("$ZodLiteral",(Q,Y)=>{if(o.init(Q,Y),Y.values.length===0)throw Error("Cannot create literal schema with no valid values");Q._zod.values=new Set(Y.values),Q._zod.pattern=new RegExp(`^(${Y.values.map((X)=>typeof X==="string"?a0(X):X?a0(X.toString()):String(X)).join("|")})$`),Q._zod.parse=(X,W)=>{let G=X.value;if(Q._zod.values.has(G))return X;return X.issues.push({code:"invalid_value",values:Y.values,input:G,inst:Q}),X}});var bW=q("$ZodTransform",(Q,Y)=>{o.init(Q,Y),Q._zod.parse=(X,W)=>{if(W.direction==="backward")throw new G4(Q.constructor.name);let G=Y.transform(X.value,X);if(W.async)return(G instanceof Promise?G:Promise.resolve(G)).then((z)=>{return X.value=z,X});if(G instanceof Promise)throw new t0;return X.value=G,X}});function _8(Q,Y){if(Q.issues.length&&Y===void 0)return{issues:[],value:void 0};return Q}var jW=q("$ZodOptional",(Q,Y)=>{o.init(Q,Y),Q._zod.optin="optional",Q._zod.optout="optional",n(Q._zod,"values",()=>{return Y.innerType._zod.values?new Set([...Y.innerType._zod.values,void 0]):void 0}),n(Q._zod,"pattern",()=>{let X=Y.innerType._zod.pattern;return X?new RegExp(`^(${J4(X.source)})?$`):void 0}),Q._zod.parse=(X,W)=>{if(Y.innerType._zod.optin==="optional"){let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then(($)=>_8($,X.value));return _8(G,X.value)}if(X.value===void 0)return X;return Y.innerType._zod.run(X,W)}}),IW=q("$ZodNullable",(Q,Y)=>{o.init(Q,Y),n(Q._zod,"optin",()=>Y.innerType._zod.optin),n(Q._zod,"optout",()=>Y.innerType._zod.optout),n(Q._zod,"pattern",()=>{let X=Y.innerType._zod.pattern;return X?new RegExp(`^(${J4(X.source)}|null)$`):void 0}),n(Q._zod,"values",()=>{return Y.innerType._zod.values?new Set([...Y.innerType._zod.values,null]):void 0}),Q._zod.parse=(X,W)=>{if(X.value===null)return X;return Y.innerType._zod.run(X,W)}}),EW=q("$ZodDefault",(Q,Y)=>{o.init(Q,Y),Q._zod.optin="optional",n(Q._zod,"values",()=>Y.innerType._zod.values),Q._zod.parse=(X,W)=>{if(W.direction==="backward")return Y.innerType._zod.run(X,W);if(X.value===void 0)return X.value=Y.defaultValue,X;let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then(($)=>g8($,Y));return g8(G,Y)}});function g8(Q,Y){if(Q.value===void 0)Q.value=Y.defaultValue;return Q}var TW=q("$ZodPrefault",(Q,Y)=>{o.init(Q,Y),Q._zod.optin="optional",n(Q._zod,"values",()=>Y.innerType._zod.values),Q._zod.parse=(X,W)=>{if(W.direction==="backward")return Y.innerType._zod.run(X,W);if(X.value===void 0)X.value=Y.defaultValue;return Y.innerType._zod.run(X,W)}}),SW=q("$ZodNonOptional",(Q,Y)=>{o.init(Q,Y),n(Q._zod,"values",()=>{let X=Y.innerType._zod.values;return X?new Set([...X].filter((W)=>W!==void 0)):void 0}),Q._zod.parse=(X,W)=>{let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then(($)=>y8($,Q));return y8(G,Q)}});function y8(Q,Y){if(!Q.issues.length&&Q.value===void 0)Q.issues.push({code:"invalid_type",expected:"nonoptional",input:Q.value,inst:Y});return Q}var RW=q("$ZodCatch",(Q,Y)=>{o.init(Q,Y),n(Q._zod,"optin",()=>Y.innerType._zod.optin),n(Q._zod,"optout",()=>Y.innerType._zod.optout),n(Q._zod,"values",()=>Y.innerType._zod.values),Q._zod.parse=(X,W)=>{if(W.direction==="backward")return Y.innerType._zod.run(X,W);let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then(($)=>{if(X.value=$.value,$.issues.length)X.value=Y.catchValue({...X,error:{issues:$.issues.map((z)=>x0(z,W,T0()))},input:X.value}),X.issues=[];return X});if(X.value=G.value,G.issues.length)X.value=Y.catchValue({...X,error:{issues:G.issues.map(($)=>x0($,W,T0()))},input:X.value}),X.issues=[];return X}});var CW=q("$ZodPipe",(Q,Y)=>{o.init(Q,Y),n(Q._zod,"values",()=>Y.in._zod.values),n(Q._zod,"optin",()=>Y.in._zod.optin),n(Q._zod,"optout",()=>Y.out._zod.optout),n(Q._zod,"propValues",()=>Y.in._zod.propValues),Q._zod.parse=(X,W)=>{if(W.direction==="backward"){let $=Y.out._zod.run(X,W);if($ instanceof Promise)return $.then((z)=>K6(z,Y.in,W));return K6($,Y.in,W)}let G=Y.in._zod.run(X,W);if(G instanceof Promise)return G.then(($)=>K6($,Y.out,W));return K6(G,Y.out,W)}});function K6(Q,Y,X){if(Q.issues.length)return Q.aborted=!0,Q;return Y._zod.run({value:Q.value,issues:Q.issues},X)}var kW=q("$ZodReadonly",(Q,Y)=>{o.init(Q,Y),n(Q._zod,"propValues",()=>Y.innerType._zod.propValues),n(Q._zod,"values",()=>Y.innerType._zod.values),n(Q._zod,"optin",()=>Y.innerType._zod.optin),n(Q._zod,"optout",()=>Y.innerType._zod.optout),Q._zod.parse=(X,W)=>{if(W.direction==="backward")return Y.innerType._zod.run(X,W);let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then(u8);return u8(G)}});function u8(Q){return Q.value=Object.freeze(Q.value),Q}var vW=q("$ZodCustom",(Q,Y)=>{A0.init(Q,Y),o.init(Q,Y),Q._zod.parse=(X,W)=>{return X},Q._zod.check=(X)=>{let W=X.value,G=Y.fn(W);if(G instanceof Promise)return G.then(($)=>h8($,X,W,Q));h8(G,X,W,Q);return}});function h8(Q,Y,X,W){if(!Q){let G={code:"custom",input:X,inst:W,path:[...W._zod.def.path??[]],continue:!W._zod.def.abort};if(W._zod.def.params)G.params=W._zod.def.params;Y.issues.push(y1(G))}}var qA=(Q)=>{let Y=typeof Q;switch(Y){case"number":return Number.isNaN(Q)?"NaN":"number";case"object":{if(Array.isArray(Q))return"array";if(Q===null)return"null";if(Object.getPrototypeOf(Q)!==Object.prototype&&Q.constructor)return Q.constructor.name}}return Y},OA=()=>{let Q={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 Y(W){return Q[W]??null}let X={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 ${qA(W.input)}`;case"invalid_value":if(W.values.length===1)return`Invalid input: expected ${$6(W.values[0])}`;return`Invalid option: expected one of ${X6(W.values,"|")}`;case"too_big":{let G=W.inclusive?"<=":"<",$=Y(W.origin);if($)return`Too big: expected ${W.origin??"value"} to have ${G}${W.maximum.toString()} ${$.unit??"elements"}`;return`Too big: expected ${W.origin??"value"} to be ${G}${W.maximum.toString()}`}case"too_small":{let G=W.inclusive?">=":">",$=Y(W.origin);if($)return`Too small: expected ${W.origin} to have ${G}${W.minimum.toString()} ${$.unit}`;return`Too small: expected ${W.origin} to be ${G}${W.minimum.toString()}`}case"invalid_format":{let G=W;if(G.format==="starts_with")return`Invalid string: must start with "${G.prefix}"`;if(G.format==="ends_with")return`Invalid string: must end with "${G.suffix}"`;if(G.format==="includes")return`Invalid string: must include "${G.includes}"`;if(G.format==="regex")return`Invalid string: must match pattern ${G.pattern}`;return`Invalid ${X[G.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":""}: ${X6(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 nQ(){return{localeError:OA()}}var lZ=Symbol("ZodOutput"),mZ=Symbol("ZodInput");class xW{constructor(){this._map=new WeakMap,this._idmap=new Map}add(Q,...Y){let X=Y[0];if(this._map.set(Q,X),X&&typeof X==="object"&&"id"in X){if(this._idmap.has(X.id))throw Error(`ID ${X.id} already exists in the registry`);this._idmap.set(X.id,Q)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(Q){let Y=this._map.get(Q);if(Y&&typeof Y==="object"&&"id"in Y)this._idmap.delete(Y.id);return this._map.delete(Q),this}get(Q){let Y=Q._zod.parent;if(Y){let X={...this.get(Y)??{}};delete X.id;let W={...X,...this._map.get(Q)};return Object.keys(W).length?W:void 0}return this._map.get(Q)}has(Q){return this._map.has(Q)}}function MA(){return new xW}var B4=MA();function _W(Q,Y){return new Q({type:"string",...T(Y)})}function gW(Q,Y){return new Q({type:"string",format:"email",check:"string_format",abort:!1,...T(Y)})}function rQ(Q,Y){return new Q({type:"string",format:"guid",check:"string_format",abort:!1,...T(Y)})}function yW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,...T(Y)})}function uW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...T(Y)})}function hW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...T(Y)})}function fW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...T(Y)})}function lW(Q,Y){return new Q({type:"string",format:"url",check:"string_format",abort:!1,...T(Y)})}function mW(Q,Y){return new Q({type:"string",format:"emoji",check:"string_format",abort:!1,...T(Y)})}function cW(Q,Y){return new Q({type:"string",format:"nanoid",check:"string_format",abort:!1,...T(Y)})}function pW(Q,Y){return new Q({type:"string",format:"cuid",check:"string_format",abort:!1,...T(Y)})}function iW(Q,Y){return new Q({type:"string",format:"cuid2",check:"string_format",abort:!1,...T(Y)})}function nW(Q,Y){return new Q({type:"string",format:"ulid",check:"string_format",abort:!1,...T(Y)})}function rW(Q,Y){return new Q({type:"string",format:"xid",check:"string_format",abort:!1,...T(Y)})}function dW(Q,Y){return new Q({type:"string",format:"ksuid",check:"string_format",abort:!1,...T(Y)})}function oW(Q,Y){return new Q({type:"string",format:"ipv4",check:"string_format",abort:!1,...T(Y)})}function tW(Q,Y){return new Q({type:"string",format:"ipv6",check:"string_format",abort:!1,...T(Y)})}function aW(Q,Y){return new Q({type:"string",format:"cidrv4",check:"string_format",abort:!1,...T(Y)})}function sW(Q,Y){return new Q({type:"string",format:"cidrv6",check:"string_format",abort:!1,...T(Y)})}function eW(Q,Y){return new Q({type:"string",format:"base64",check:"string_format",abort:!1,...T(Y)})}function QG(Q,Y){return new Q({type:"string",format:"base64url",check:"string_format",abort:!1,...T(Y)})}function YG(Q,Y){return new Q({type:"string",format:"e164",check:"string_format",abort:!1,...T(Y)})}function XG(Q,Y){return new Q({type:"string",format:"jwt",check:"string_format",abort:!1,...T(Y)})}function WG(Q,Y){return new Q({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...T(Y)})}function GG(Q,Y){return new Q({type:"string",format:"date",check:"string_format",...T(Y)})}function $G(Q,Y){return new Q({type:"string",format:"time",check:"string_format",precision:null,...T(Y)})}function zG(Q,Y){return new Q({type:"string",format:"duration",check:"string_format",...T(Y)})}function JG(Q,Y){return new Q({type:"number",checks:[],...T(Y)})}function HG(Q,Y){return new Q({type:"number",check:"number_format",abort:!1,format:"safeint",...T(Y)})}function AG(Q,Y){return new Q({type:"boolean",...T(Y)})}function UG(Q,Y){return new Q({type:"null",...T(Y)})}function KG(Q){return new Q({type:"unknown"})}function DG(Q,Y){return new Q({type:"never",...T(Y)})}function L6(Q,Y){return new fQ({check:"less_than",...T(Y),value:Q,inclusive:!1})}function L4(Q,Y){return new fQ({check:"less_than",...T(Y),value:Q,inclusive:!0})}function F6(Q,Y){return new lQ({check:"greater_than",...T(Y),value:Q,inclusive:!1})}function F4(Q,Y){return new lQ({check:"greater_than",...T(Y),value:Q,inclusive:!0})}function q6(Q,Y){return new M8({check:"multiple_of",...T(Y),value:Q})}function O6(Q,Y){return new Z8({check:"max_length",...T(Y),maximum:Q})}function u1(Q,Y){return new N8({check:"min_length",...T(Y),minimum:Q})}function M6(Q,Y){return new w8({check:"length_equals",...T(Y),length:Q})}function dQ(Q,Y){return new P8({check:"string_format",format:"regex",...T(Y),pattern:Q})}function oQ(Q){return new b8({check:"string_format",format:"lowercase",...T(Q)})}function tQ(Q){return new j8({check:"string_format",format:"uppercase",...T(Q)})}function aQ(Q,Y){return new I8({check:"string_format",format:"includes",...T(Y),includes:Q})}function sQ(Q,Y){return new E8({check:"string_format",format:"starts_with",...T(Y),prefix:Q})}function eQ(Q,Y){return new T8({check:"string_format",format:"ends_with",...T(Y),suffix:Q})}function I1(Q){return new S8({check:"overwrite",tx:Q})}function Q9(Q){return I1((Y)=>Y.normalize(Q))}function Y9(){return I1((Q)=>Q.trim())}function X9(){return I1((Q)=>Q.toLowerCase())}function W9(){return I1((Q)=>Q.toUpperCase())}function BG(Q,Y,X){return new Q({type:"array",element:Y,...T(X)})}function LG(Q,Y,X){let W=T(X);return W.abort??(W.abort=!0),new Q({type:"custom",check:"custom",fn:Y,...W})}function FG(Q,Y,X){return new Q({type:"custom",check:"custom",fn:Y,...T(X)})}function qG(Q){let Y=VA((X)=>{return X.addIssue=(W)=>{if(typeof W==="string")X.issues.push(y1(W,X.value,Y._zod.def));else{let G=W;if(G.fatal)G.continue=!1;G.code??(G.code="custom"),G.input??(G.input=X.value),G.inst??(G.inst=Y),G.continue??(G.continue=!Y._zod.def.abort),X.issues.push(y1(G))}},Q(X.value,X)});return Y}function VA(Q,Y){let X=new A0({check:"custom",...T(Y)});return X._zod.check=Q,X}function h1(Q){return!!Q._zod}function U1(Q,Y){if(h1(Q))return U4(Q,Y);return Q.safeParse(Y)}function V6(Q){if(!Q)return;let Y;if(h1(Q))Y=Q._zod?.def?.shape;else Y=Q.shape;if(!Y)return;if(typeof Y==="function")try{return Y()}catch{return}return Y}function OG(Q){if(h1(Q)){let $=Q._zod?.def;if($){if($.value!==void 0)return $.value;if(Array.isArray($.values)&&$.values.length>0)return $.values[0]}}let X=Q._def;if(X){if(X.value!==void 0)return X.value;if(Array.isArray(X.values)&&X.values.length>0)return X.values[0]}let W=Q.value;if(W!==void 0)return W;return}var O4={};qX(O4,{time:()=>z9,duration:()=>J9,datetime:()=>G9,date:()=>$9,ZodISOTime:()=>ZG,ZodISODuration:()=>NG,ZodISODateTime:()=>MG,ZodISODate:()=>VG});var MG=q("ZodISODateTime",(Q,Y)=>{a8.init(Q,Y),s.init(Q,Y)});function G9(Q){return WG(MG,Q)}var VG=q("ZodISODate",(Q,Y)=>{s8.init(Q,Y),s.init(Q,Y)});function $9(Q){return GG(VG,Q)}var ZG=q("ZodISOTime",(Q,Y)=>{e8.init(Q,Y),s.init(Q,Y)});function z9(Q){return $G(ZG,Q)}var NG=q("ZodISODuration",(Q,Y)=>{QW.init(Q,Y),s.init(Q,Y)});function J9(Q){return zG(NG,Q)}var wG=(Q,Y)=>{z6.init(Q,Y),Q.name="ZodError",Object.defineProperties(Q,{format:{value:(X)=>vX(Q,X)},flatten:{value:(X)=>kX(Q,X)},addIssue:{value:(X)=>{Q.issues.push(X),Q.message=JSON.stringify(Q.issues,_1,2)}},addIssues:{value:(X)=>{Q.issues.push(...X),Q.message=JSON.stringify(Q.issues,_1,2)}},isEmpty:{get(){return Q.issues.length===0}}})},EN=q("ZodError",wG),I0=q("ZodError",wG,{Parent:Error});var PG=J6(I0),bG=H6(I0),jG=A4(I0),IG=K4(I0),EG=xX(I0),TG=_X(I0),SG=gX(I0),RG=yX(I0),CG=uX(I0),kG=hX(I0),vG=fX(I0),xG=lX(I0);var W0=q("ZodType",(Q,Y)=>{return o.init(Q,Y),Q.def=Y,Q.type=Y.type,Object.defineProperty(Q,"_def",{value:Y}),Q.check=(...X)=>{return Q.clone(m.mergeDefs(Y,{checks:[...Y.checks??[],...X.map((W)=>typeof W==="function"?{_zod:{check:W,def:{check:"custom"},onattach:[]}}:W)]}))},Q.clone=(X,W)=>v0(Q,X,W),Q.brand=()=>Q,Q.register=(X,W)=>{return X.add(Q,W),Q},Q.parse=(X,W)=>PG(Q,X,W,{callee:Q.parse}),Q.safeParse=(X,W)=>jG(Q,X,W),Q.parseAsync=async(X,W)=>bG(Q,X,W,{callee:Q.parseAsync}),Q.safeParseAsync=async(X,W)=>IG(Q,X,W),Q.spa=Q.safeParseAsync,Q.encode=(X,W)=>EG(Q,X,W),Q.decode=(X,W)=>TG(Q,X,W),Q.encodeAsync=async(X,W)=>SG(Q,X,W),Q.decodeAsync=async(X,W)=>RG(Q,X,W),Q.safeEncode=(X,W)=>CG(Q,X,W),Q.safeDecode=(X,W)=>kG(Q,X,W),Q.safeEncodeAsync=async(X,W)=>vG(Q,X,W),Q.safeDecodeAsync=async(X,W)=>xG(Q,X,W),Q.refine=(X,W)=>Q.check(F3(X,W)),Q.superRefine=(X)=>Q.check(q3(X)),Q.overwrite=(X)=>Q.check(I1(X)),Q.optional=()=>X0(Q),Q.nullable=()=>yG(Q),Q.nullish=()=>X0(yG(Q)),Q.nonoptional=(X)=>A3(Q,X),Q.array=()=>u(Q),Q.or=(X)=>d([Q,X]),Q.and=(X)=>N6(Q,X),Q.transform=(X)=>A9(Q,mG(X)),Q.default=(X)=>z3(Q,X),Q.prefault=(X)=>H3(Q,X),Q.catch=(X)=>K3(Q,X),Q.pipe=(X)=>A9(Q,X),Q.readonly=()=>L3(Q),Q.describe=(X)=>{let W=Q.clone();return B4.add(W,{description:X}),W},Object.defineProperty(Q,"description",{get(){return B4.get(Q)?.description},configurable:!0}),Q.meta=(...X)=>{if(X.length===0)return B4.get(Q);let W=Q.clone();return B4.add(W,X[0]),W},Q.isOptional=()=>Q.safeParse(void 0).success,Q.isNullable=()=>Q.safeParse(null).success,Q}),uG=q("_ZodString",(Q,Y)=>{B6.init(Q,Y),W0.init(Q,Y);let X=Q._zod.bag;Q.format=X.format??null,Q.minLength=X.minimum??null,Q.maxLength=X.maximum??null,Q.regex=(...W)=>Q.check(dQ(...W)),Q.includes=(...W)=>Q.check(aQ(...W)),Q.startsWith=(...W)=>Q.check(sQ(...W)),Q.endsWith=(...W)=>Q.check(eQ(...W)),Q.min=(...W)=>Q.check(u1(...W)),Q.max=(...W)=>Q.check(O6(...W)),Q.length=(...W)=>Q.check(M6(...W)),Q.nonempty=(...W)=>Q.check(u1(1,...W)),Q.lowercase=(W)=>Q.check(oQ(W)),Q.uppercase=(W)=>Q.check(tQ(W)),Q.trim=()=>Q.check(Y9()),Q.normalize=(...W)=>Q.check(Q9(...W)),Q.toLowerCase=()=>Q.check(X9()),Q.toUpperCase=()=>Q.check(W9())}),TA=q("ZodString",(Q,Y)=>{B6.init(Q,Y),uG.init(Q,Y),Q.email=(X)=>Q.check(gW(SA,X)),Q.url=(X)=>Q.check(lW(RA,X)),Q.jwt=(X)=>Q.check(XG(iA,X)),Q.emoji=(X)=>Q.check(mW(CA,X)),Q.guid=(X)=>Q.check(rQ(_G,X)),Q.uuid=(X)=>Q.check(yW(Z6,X)),Q.uuidv4=(X)=>Q.check(uW(Z6,X)),Q.uuidv6=(X)=>Q.check(hW(Z6,X)),Q.uuidv7=(X)=>Q.check(fW(Z6,X)),Q.nanoid=(X)=>Q.check(cW(kA,X)),Q.guid=(X)=>Q.check(rQ(_G,X)),Q.cuid=(X)=>Q.check(pW(vA,X)),Q.cuid2=(X)=>Q.check(iW(xA,X)),Q.ulid=(X)=>Q.check(nW(_A,X)),Q.base64=(X)=>Q.check(eW(mA,X)),Q.base64url=(X)=>Q.check(QG(cA,X)),Q.xid=(X)=>Q.check(rW(gA,X)),Q.ksuid=(X)=>Q.check(dW(yA,X)),Q.ipv4=(X)=>Q.check(oW(uA,X)),Q.ipv6=(X)=>Q.check(tW(hA,X)),Q.cidrv4=(X)=>Q.check(aW(fA,X)),Q.cidrv6=(X)=>Q.check(sW(lA,X)),Q.e164=(X)=>Q.check(YG(pA,X)),Q.datetime=(X)=>Q.check(G9(X)),Q.date=(X)=>Q.check($9(X)),Q.time=(X)=>Q.check(z9(X)),Q.duration=(X)=>Q.check(J9(X))});function F(Q){return _W(TA,Q)}var s=q("ZodStringFormat",(Q,Y)=>{t.init(Q,Y),uG.init(Q,Y)}),SA=q("ZodEmail",(Q,Y)=>{m8.init(Q,Y),s.init(Q,Y)});var _G=q("ZodGUID",(Q,Y)=>{f8.init(Q,Y),s.init(Q,Y)});var Z6=q("ZodUUID",(Q,Y)=>{l8.init(Q,Y),s.init(Q,Y)});var RA=q("ZodURL",(Q,Y)=>{c8.init(Q,Y),s.init(Q,Y)});var CA=q("ZodEmoji",(Q,Y)=>{p8.init(Q,Y),s.init(Q,Y)});var kA=q("ZodNanoID",(Q,Y)=>{i8.init(Q,Y),s.init(Q,Y)});var vA=q("ZodCUID",(Q,Y)=>{n8.init(Q,Y),s.init(Q,Y)});var xA=q("ZodCUID2",(Q,Y)=>{r8.init(Q,Y),s.init(Q,Y)});var _A=q("ZodULID",(Q,Y)=>{d8.init(Q,Y),s.init(Q,Y)});var gA=q("ZodXID",(Q,Y)=>{o8.init(Q,Y),s.init(Q,Y)});var yA=q("ZodKSUID",(Q,Y)=>{t8.init(Q,Y),s.init(Q,Y)});var uA=q("ZodIPv4",(Q,Y)=>{YW.init(Q,Y),s.init(Q,Y)});var hA=q("ZodIPv6",(Q,Y)=>{XW.init(Q,Y),s.init(Q,Y)});var fA=q("ZodCIDRv4",(Q,Y)=>{WW.init(Q,Y),s.init(Q,Y)});var lA=q("ZodCIDRv6",(Q,Y)=>{GW.init(Q,Y),s.init(Q,Y)});var mA=q("ZodBase64",(Q,Y)=>{zW.init(Q,Y),s.init(Q,Y)});var cA=q("ZodBase64URL",(Q,Y)=>{JW.init(Q,Y),s.init(Q,Y)});var pA=q("ZodE164",(Q,Y)=>{HW.init(Q,Y),s.init(Q,Y)});var iA=q("ZodJWT",(Q,Y)=>{AW.init(Q,Y),s.init(Q,Y)});var hG=q("ZodNumber",(Q,Y)=>{pQ.init(Q,Y),W0.init(Q,Y),Q.gt=(W,G)=>Q.check(F6(W,G)),Q.gte=(W,G)=>Q.check(F4(W,G)),Q.min=(W,G)=>Q.check(F4(W,G)),Q.lt=(W,G)=>Q.check(L6(W,G)),Q.lte=(W,G)=>Q.check(L4(W,G)),Q.max=(W,G)=>Q.check(L4(W,G)),Q.int=(W)=>Q.check(gG(W)),Q.safe=(W)=>Q.check(gG(W)),Q.positive=(W)=>Q.check(F6(0,W)),Q.nonnegative=(W)=>Q.check(F4(0,W)),Q.negative=(W)=>Q.check(L6(0,W)),Q.nonpositive=(W)=>Q.check(L4(0,W)),Q.multipleOf=(W,G)=>Q.check(q6(W,G)),Q.step=(W,G)=>Q.check(q6(W,G)),Q.finite=()=>Q;let X=Q._zod.bag;Q.minValue=Math.max(X.minimum??Number.NEGATIVE_INFINITY,X.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,Q.maxValue=Math.min(X.maximum??Number.POSITIVE_INFINITY,X.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,Q.isInt=(X.format??"").includes("int")||Number.isSafeInteger(X.multipleOf??0.5),Q.isFinite=!0,Q.format=X.format??null});function i(Q){return JG(hG,Q)}var nA=q("ZodNumberFormat",(Q,Y)=>{UW.init(Q,Y),hG.init(Q,Y)});function gG(Q){return HG(nA,Q)}var rA=q("ZodBoolean",(Q,Y)=>{KW.init(Q,Y),W0.init(Q,Y)});function H0(Q){return AG(rA,Q)}var dA=q("ZodNull",(Q,Y)=>{DW.init(Q,Y),W0.init(Q,Y)});function U9(Q){return UG(dA,Q)}var oA=q("ZodUnknown",(Q,Y)=>{BW.init(Q,Y),W0.init(Q,Y)});function e(){return KG(oA)}var tA=q("ZodNever",(Q,Y)=>{LW.init(Q,Y),W0.init(Q,Y)});function aA(Q){return DG(tA,Q)}var sA=q("ZodArray",(Q,Y)=>{FW.init(Q,Y),W0.init(Q,Y),Q.element=Y.element,Q.min=(X,W)=>Q.check(u1(X,W)),Q.nonempty=(X)=>Q.check(u1(1,X)),Q.max=(X,W)=>Q.check(O6(X,W)),Q.length=(X,W)=>Q.check(M6(X,W)),Q.unwrap=()=>Q.element});function u(Q,Y){return BG(sA,Q,Y)}var fG=q("ZodObject",(Q,Y)=>{MW.init(Q,Y),W0.init(Q,Y),m.defineLazy(Q,"shape",()=>{return Y.shape}),Q.keyof=()=>V0(Object.keys(Q._zod.def.shape)),Q.catchall=(X)=>Q.clone({...Q._zod.def,catchall:X}),Q.passthrough=()=>Q.clone({...Q._zod.def,catchall:e()}),Q.loose=()=>Q.clone({...Q._zod.def,catchall:e()}),Q.strict=()=>Q.clone({...Q._zod.def,catchall:aA()}),Q.strip=()=>Q.clone({...Q._zod.def,catchall:void 0}),Q.extend=(X)=>{return m.extend(Q,X)},Q.safeExtend=(X)=>{return m.safeExtend(Q,X)},Q.merge=(X)=>m.merge(Q,X),Q.pick=(X)=>m.pick(Q,X),Q.omit=(X)=>m.omit(Q,X),Q.partial=(...X)=>m.partial(cG,Q,X[0]),Q.required=(...X)=>m.required(pG,Q,X[0])});function b(Q,Y){let X={type:"object",shape:Q??{},...m.normalizeParams(Y)};return new fG(X)}function q0(Q,Y){return new fG({type:"object",shape:Q,catchall:e(),...m.normalizeParams(Y)})}var lG=q("ZodUnion",(Q,Y)=>{iQ.init(Q,Y),W0.init(Q,Y),Q.options=Y.options});function d(Q,Y){return new lG({type:"union",options:Q,...m.normalizeParams(Y)})}var eA=q("ZodDiscriminatedUnion",(Q,Y)=>{lG.init(Q,Y),VW.init(Q,Y)});function K9(Q,Y,X){return new eA({type:"union",options:Y,discriminator:Q,...m.normalizeParams(X)})}var Q3=q("ZodIntersection",(Q,Y)=>{ZW.init(Q,Y),W0.init(Q,Y)});function N6(Q,Y){return new Q3({type:"intersection",left:Q,right:Y})}var Y3=q("ZodRecord",(Q,Y)=>{NW.init(Q,Y),W0.init(Q,Y),Q.keyType=Y.keyType,Q.valueType=Y.valueType});function Q0(Q,Y,X){return new Y3({type:"record",keyType:Q,valueType:Y,...m.normalizeParams(X)})}var H9=q("ZodEnum",(Q,Y)=>{wW.init(Q,Y),W0.init(Q,Y),Q.enum=Y.entries,Q.options=Object.values(Y.entries);let X=new Set(Object.keys(Y.entries));Q.extract=(W,G)=>{let $={};for(let z of W)if(X.has(z))$[z]=Y.entries[z];else throw Error(`Key ${z} not found in enum`);return new H9({...Y,checks:[],...m.normalizeParams(G),entries:$})},Q.exclude=(W,G)=>{let $={...Y.entries};for(let z of W)if(X.has(z))delete $[z];else throw Error(`Key ${z} not found in enum`);return new H9({...Y,checks:[],...m.normalizeParams(G),entries:$})}});function V0(Q,Y){let X=Array.isArray(Q)?Object.fromEntries(Q.map((W)=>[W,W])):Q;return new H9({type:"enum",entries:X,...m.normalizeParams(Y)})}var X3=q("ZodLiteral",(Q,Y)=>{PW.init(Q,Y),W0.init(Q,Y),Q.values=new Set(Y.values),Object.defineProperty(Q,"value",{get(){if(Y.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return Y.values[0]}})});function j(Q,Y){return new X3({type:"literal",values:Array.isArray(Q)?Q:[Q],...m.normalizeParams(Y)})}var W3=q("ZodTransform",(Q,Y)=>{bW.init(Q,Y),W0.init(Q,Y),Q._zod.parse=(X,W)=>{if(W.direction==="backward")throw new G4(Q.constructor.name);X.addIssue=($)=>{if(typeof $==="string")X.issues.push(m.issue($,X.value,Y));else{let z=$;if(z.fatal)z.continue=!1;z.code??(z.code="custom"),z.input??(z.input=X.value),z.inst??(z.inst=Q),X.issues.push(m.issue(z))}};let G=Y.transform(X.value,X);if(G instanceof Promise)return G.then(($)=>{return X.value=$,X});return X.value=G,X}});function mG(Q){return new W3({type:"transform",transform:Q})}var cG=q("ZodOptional",(Q,Y)=>{jW.init(Q,Y),W0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function X0(Q){return new cG({type:"optional",innerType:Q})}var G3=q("ZodNullable",(Q,Y)=>{IW.init(Q,Y),W0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function yG(Q){return new G3({type:"nullable",innerType:Q})}var $3=q("ZodDefault",(Q,Y)=>{EW.init(Q,Y),W0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType,Q.removeDefault=Q.unwrap});function z3(Q,Y){return new $3({type:"default",innerType:Q,get defaultValue(){return typeof Y==="function"?Y():m.shallowClone(Y)}})}var J3=q("ZodPrefault",(Q,Y)=>{TW.init(Q,Y),W0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function H3(Q,Y){return new J3({type:"prefault",innerType:Q,get defaultValue(){return typeof Y==="function"?Y():m.shallowClone(Y)}})}var pG=q("ZodNonOptional",(Q,Y)=>{SW.init(Q,Y),W0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function A3(Q,Y){return new pG({type:"nonoptional",innerType:Q,...m.normalizeParams(Y)})}var U3=q("ZodCatch",(Q,Y)=>{RW.init(Q,Y),W0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType,Q.removeCatch=Q.unwrap});function K3(Q,Y){return new U3({type:"catch",innerType:Q,catchValue:typeof Y==="function"?Y:()=>Y})}var D3=q("ZodPipe",(Q,Y)=>{CW.init(Q,Y),W0.init(Q,Y),Q.in=Y.in,Q.out=Y.out});function A9(Q,Y){return new D3({type:"pipe",in:Q,out:Y})}var B3=q("ZodReadonly",(Q,Y)=>{kW.init(Q,Y),W0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function L3(Q){return new B3({type:"readonly",innerType:Q})}var iG=q("ZodCustom",(Q,Y)=>{vW.init(Q,Y),W0.init(Q,Y)});function nG(Q,Y){return LG(iG,Q??(()=>!0),Y)}function F3(Q,Y={}){return FG(iG,Q,Y)}function q3(Q){return qG(Q)}function D9(Q,Y){return A9(mG(Q),Y)}T0(nQ());var B9="2025-11-25";var rG=[B9,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],K1="io.modelcontextprotocol/related-task",P6="2.0",U0=nG((Q)=>Q!==null&&(typeof Q==="object"||typeof Q==="function")),dG=d([F(),i().int()]),oG=F(),ww=q0({ttl:d([i(),U9()]).optional(),pollInterval:i().optional()}),O3=b({ttl:i().optional()}),M3=b({taskId:F()}),L9=q0({progressToken:dG.optional(),[K1]:M3.optional()}),E0=b({_meta:L9.optional()}),M4=E0.extend({task:O3.optional()}),tG=(Q)=>M4.safeParse(Q).success,K0=b({method:F(),params:E0.loose().optional()}),S0=b({_meta:L9.optional()}),R0=b({method:F(),params:S0.loose().optional()}),D0=q0({_meta:L9.optional()}),b6=d([F(),i().int()]),aG=b({jsonrpc:j(P6),id:b6,...K0.shape}).strict(),F9=(Q)=>aG.safeParse(Q).success,sG=b({jsonrpc:j(P6),...R0.shape}).strict(),eG=(Q)=>sG.safeParse(Q).success,q9=b({jsonrpc:j(P6),id:b6,result:D0}).strict(),V4=(Q)=>q9.safeParse(Q).success;var h;(function(Q){Q[Q.ConnectionClosed=-32000]="ConnectionClosed",Q[Q.RequestTimeout=-32001]="RequestTimeout",Q[Q.ParseError=-32700]="ParseError",Q[Q.InvalidRequest=-32600]="InvalidRequest",Q[Q.MethodNotFound=-32601]="MethodNotFound",Q[Q.InvalidParams=-32602]="InvalidParams",Q[Q.InternalError=-32603]="InternalError",Q[Q.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(h||(h={}));var O9=b({jsonrpc:j(P6),id:b6.optional(),error:b({code:i().int(),message:F(),data:e().optional()})}).strict();var Q$=(Q)=>O9.safeParse(Q).success;var Y$=d([aG,sG,q9,O9]),Pw=d([q9,O9]),j6=D0.strict(),V3=S0.extend({requestId:b6.optional(),reason:F().optional()}),I6=R0.extend({method:j("notifications/cancelled"),params:V3}),Z3=b({src:F(),mimeType:F().optional(),sizes:u(F()).optional(),theme:V0(["light","dark"]).optional()}),Z4=b({icons:u(Z3).optional()}),f1=b({name:F(),title:F().optional()}),X$=f1.extend({...f1.shape,...Z4.shape,version:F(),websiteUrl:F().optional(),description:F().optional()}),N3=N6(b({applyDefaults:H0().optional()}),Q0(F(),e())),w3=D9((Q)=>{if(Q&&typeof Q==="object"&&!Array.isArray(Q)){if(Object.keys(Q).length===0)return{form:{}}}return Q},N6(b({form:N3.optional(),url:U0.optional()}),Q0(F(),e()).optional())),P3=q0({list:U0.optional(),cancel:U0.optional(),requests:q0({sampling:q0({createMessage:U0.optional()}).optional(),elicitation:q0({create:U0.optional()}).optional()}).optional()}),b3=q0({list:U0.optional(),cancel:U0.optional(),requests:q0({tools:q0({call:U0.optional()}).optional()}).optional()}),j3=b({experimental:Q0(F(),U0).optional(),sampling:b({context:U0.optional(),tools:U0.optional()}).optional(),elicitation:w3.optional(),roots:b({listChanged:H0().optional()}).optional(),tasks:P3.optional()}),I3=E0.extend({protocolVersion:F(),capabilities:j3,clientInfo:X$}),M9=K0.extend({method:j("initialize"),params:I3});var E3=b({experimental:Q0(F(),U0).optional(),logging:U0.optional(),completions:U0.optional(),prompts:b({listChanged:H0().optional()}).optional(),resources:b({subscribe:H0().optional(),listChanged:H0().optional()}).optional(),tools:b({listChanged:H0().optional()}).optional(),tasks:b3.optional()}),T3=D0.extend({protocolVersion:F(),capabilities:E3,serverInfo:X$,instructions:F().optional()}),V9=R0.extend({method:j("notifications/initialized"),params:S0.optional()});var E6=K0.extend({method:j("ping"),params:E0.optional()}),S3=b({progress:i(),total:X0(i()),message:X0(F())}),R3=b({...S0.shape,...S3.shape,progressToken:dG}),T6=R0.extend({method:j("notifications/progress"),params:R3}),C3=E0.extend({cursor:oG.optional()}),N4=K0.extend({params:C3.optional()}),w4=D0.extend({nextCursor:oG.optional()}),k3=V0(["working","input_required","completed","failed","cancelled"]),P4=b({taskId:F(),status:k3,ttl:d([i(),U9()]),createdAt:F(),lastUpdatedAt:F(),pollInterval:X0(i()),statusMessage:X0(F())}),l1=D0.extend({task:P4}),v3=S0.merge(P4),b4=R0.extend({method:j("notifications/tasks/status"),params:v3}),S6=K0.extend({method:j("tasks/get"),params:E0.extend({taskId:F()})}),R6=D0.merge(P4),C6=K0.extend({method:j("tasks/result"),params:E0.extend({taskId:F()})}),bw=D0.loose(),k6=N4.extend({method:j("tasks/list")}),v6=w4.extend({tasks:u(P4)}),x6=K0.extend({method:j("tasks/cancel"),params:E0.extend({taskId:F()})}),W$=D0.merge(P4),G$=b({uri:F(),mimeType:X0(F()),_meta:Q0(F(),e()).optional()}),$$=G$.extend({text:F()}),Z9=F().refine((Q)=>{try{return atob(Q),!0}catch{return!1}},{message:"Invalid Base64 string"}),z$=G$.extend({blob:Z9}),j4=V0(["user","assistant"]),m1=b({audience:u(j4).optional(),priority:i().min(0).max(1).optional(),lastModified:O4.datetime({offset:!0}).optional()}),J$=b({...f1.shape,...Z4.shape,uri:F(),description:X0(F()),mimeType:X0(F()),annotations:m1.optional(),_meta:X0(q0({}))}),x3=b({...f1.shape,...Z4.shape,uriTemplate:F(),description:X0(F()),mimeType:X0(F()),annotations:m1.optional(),_meta:X0(q0({}))}),N9=N4.extend({method:j("resources/list")}),_3=w4.extend({resources:u(J$)}),g3=N4.extend({method:j("resources/templates/list")}),y3=w4.extend({resourceTemplates:u(x3)}),w9=E0.extend({uri:F()}),u3=w9,P9=K0.extend({method:j("resources/read"),params:u3}),h3=D0.extend({contents:u(d([$$,z$]))}),f3=R0.extend({method:j("notifications/resources/list_changed"),params:S0.optional()}),l3=w9,m3=K0.extend({method:j("resources/subscribe"),params:l3}),c3=w9,p3=K0.extend({method:j("resources/unsubscribe"),params:c3}),i3=S0.extend({uri:F()}),n3=R0.extend({method:j("notifications/resources/updated"),params:i3}),r3=b({name:F(),description:X0(F()),required:X0(H0())}),d3=b({...f1.shape,...Z4.shape,description:X0(F()),arguments:X0(u(r3)),_meta:X0(q0({}))}),o3=N4.extend({method:j("prompts/list")}),t3=w4.extend({prompts:u(d3)}),a3=E0.extend({name:F(),arguments:Q0(F(),F()).optional()}),s3=K0.extend({method:j("prompts/get"),params:a3}),b9=b({type:j("text"),text:F(),annotations:m1.optional(),_meta:Q0(F(),e()).optional()}),j9=b({type:j("image"),data:Z9,mimeType:F(),annotations:m1.optional(),_meta:Q0(F(),e()).optional()}),I9=b({type:j("audio"),data:Z9,mimeType:F(),annotations:m1.optional(),_meta:Q0(F(),e()).optional()}),e3=b({type:j("tool_use"),name:F(),id:F(),input:Q0(F(),e()),_meta:Q0(F(),e()).optional()}),QU=b({type:j("resource"),resource:d([$$,z$]),annotations:m1.optional(),_meta:Q0(F(),e()).optional()}),YU=J$.extend({type:j("resource_link")}),E9=d([b9,j9,I9,YU,QU]),XU=b({role:j4,content:E9}),WU=D0.extend({description:F().optional(),messages:u(XU)}),GU=R0.extend({method:j("notifications/prompts/list_changed"),params:S0.optional()}),$U=b({title:F().optional(),readOnlyHint:H0().optional(),destructiveHint:H0().optional(),idempotentHint:H0().optional(),openWorldHint:H0().optional()}),zU=b({taskSupport:V0(["required","optional","forbidden"]).optional()}),H$=b({...f1.shape,...Z4.shape,description:F().optional(),inputSchema:b({type:j("object"),properties:Q0(F(),U0).optional(),required:u(F()).optional()}).catchall(e()),outputSchema:b({type:j("object"),properties:Q0(F(),U0).optional(),required:u(F()).optional()}).catchall(e()).optional(),annotations:$U.optional(),execution:zU.optional(),_meta:Q0(F(),e()).optional()}),T9=N4.extend({method:j("tools/list")}),JU=w4.extend({tools:u(H$)}),_6=D0.extend({content:u(E9).default([]),structuredContent:Q0(F(),e()).optional(),isError:H0().optional()}),jw=_6.or(D0.extend({toolResult:e()})),HU=M4.extend({name:F(),arguments:Q0(F(),e()).optional()}),I4=K0.extend({method:j("tools/call"),params:HU}),AU=R0.extend({method:j("notifications/tools/list_changed"),params:S0.optional()}),Iw=b({autoRefresh:H0().default(!0),debounceMs:i().int().nonnegative().default(300)}),E4=V0(["debug","info","notice","warning","error","critical","alert","emergency"]),UU=E0.extend({level:E4}),S9=K0.extend({method:j("logging/setLevel"),params:UU}),KU=S0.extend({level:E4,logger:F().optional(),data:e()}),DU=R0.extend({method:j("notifications/message"),params:KU}),BU=b({name:F().optional()}),LU=b({hints:u(BU).optional(),costPriority:i().min(0).max(1).optional(),speedPriority:i().min(0).max(1).optional(),intelligencePriority:i().min(0).max(1).optional()}),FU=b({mode:V0(["auto","required","none"]).optional()}),qU=b({type:j("tool_result"),toolUseId:F().describe("The unique identifier for the corresponding tool call."),content:u(E9).default([]),structuredContent:b({}).loose().optional(),isError:H0().optional(),_meta:Q0(F(),e()).optional()}),OU=K9("type",[b9,j9,I9]),w6=K9("type",[b9,j9,I9,e3,qU]),MU=b({role:j4,content:d([w6,u(w6)]),_meta:Q0(F(),e()).optional()}),VU=M4.extend({messages:u(MU),modelPreferences:LU.optional(),systemPrompt:F().optional(),includeContext:V0(["none","thisServer","allServers"]).optional(),temperature:i().optional(),maxTokens:i().int(),stopSequences:u(F()).optional(),metadata:U0.optional(),tools:u(H$).optional(),toolChoice:FU.optional()}),ZU=K0.extend({method:j("sampling/createMessage"),params:VU}),R9=D0.extend({model:F(),stopReason:X0(V0(["endTurn","stopSequence","maxTokens"]).or(F())),role:j4,content:OU}),C9=D0.extend({model:F(),stopReason:X0(V0(["endTurn","stopSequence","maxTokens","toolUse"]).or(F())),role:j4,content:d([w6,u(w6)])}),NU=b({type:j("boolean"),title:F().optional(),description:F().optional(),default:H0().optional()}),wU=b({type:j("string"),title:F().optional(),description:F().optional(),minLength:i().optional(),maxLength:i().optional(),format:V0(["email","uri","date","date-time"]).optional(),default:F().optional()}),PU=b({type:V0(["number","integer"]),title:F().optional(),description:F().optional(),minimum:i().optional(),maximum:i().optional(),default:i().optional()}),bU=b({type:j("string"),title:F().optional(),description:F().optional(),enum:u(F()),default:F().optional()}),jU=b({type:j("string"),title:F().optional(),description:F().optional(),oneOf:u(b({const:F(),title:F()})),default:F().optional()}),IU=b({type:j("string"),title:F().optional(),description:F().optional(),enum:u(F()),enumNames:u(F()).optional(),default:F().optional()}),EU=d([bU,jU]),TU=b({type:j("array"),title:F().optional(),description:F().optional(),minItems:i().optional(),maxItems:i().optional(),items:b({type:j("string"),enum:u(F())}),default:u(F()).optional()}),SU=b({type:j("array"),title:F().optional(),description:F().optional(),minItems:i().optional(),maxItems:i().optional(),items:b({anyOf:u(b({const:F(),title:F()}))}),default:u(F()).optional()}),RU=d([TU,SU]),CU=d([IU,EU,RU]),kU=d([CU,NU,wU,PU]),vU=M4.extend({mode:j("form").optional(),message:F(),requestedSchema:b({type:j("object"),properties:Q0(F(),kU),required:u(F()).optional()})}),xU=M4.extend({mode:j("url"),message:F(),elicitationId:F(),url:F().url()}),_U=d([vU,xU]),gU=K0.extend({method:j("elicitation/create"),params:_U}),yU=S0.extend({elicitationId:F()}),uU=R0.extend({method:j("notifications/elicitation/complete"),params:yU}),g6=D0.extend({action:V0(["accept","decline","cancel"]),content:D9((Q)=>Q===null?void 0:Q,Q0(F(),d([F(),i(),H0(),u(F())])).optional())}),hU=b({type:j("ref/resource"),uri:F()});var fU=b({type:j("ref/prompt"),name:F()}),lU=E0.extend({ref:d([fU,hU]),argument:b({name:F(),value:F()}),context:b({arguments:Q0(F(),F()).optional()}).optional()}),mU=K0.extend({method:j("completion/complete"),params:lU});var cU=D0.extend({completion:q0({values:u(F()).max(100),total:X0(i().int()),hasMore:X0(H0())})}),pU=b({uri:F().startsWith("file://"),name:F().optional(),_meta:Q0(F(),e()).optional()}),iU=K0.extend({method:j("roots/list"),params:E0.optional()}),k9=D0.extend({roots:u(pU)}),nU=R0.extend({method:j("notifications/roots/list_changed"),params:S0.optional()}),Ew=d([E6,M9,mU,S9,s3,o3,N9,g3,P9,m3,p3,I4,T9,S6,C6,k6,x6]),Tw=d([I6,T6,V9,nU,b4]),Sw=d([j6,R9,C9,g6,k9,R6,v6,l1]),Rw=d([E6,ZU,gU,iU,S6,C6,k6,x6]),Cw=d([I6,T6,DU,n3,f3,AU,GU,b4,uU]),kw=d([j6,T3,cU,WU,t3,_3,y3,h3,_6,JU,R6,v6,l1]);class _ extends Error{constructor(Q,Y,X){super(`MCP error ${Q}: ${Y}`);this.code=Q,this.data=X,this.name="McpError"}static fromError(Q,Y,X){if(Q===h.UrlElicitationRequired&&X){let W=X;if(W.elicitations)return new A$(W.elicitations,Y)}return new _(Q,Y,X)}}class A$ extends _{constructor(Q,Y=`URL elicitation${Q.length>1?"s":""} required`){super(h.UrlElicitationRequired,Y,{elicitations:Q})}get elicitations(){return this.data?.elicitations??[]}}function D1(Q){return Q==="completed"||Q==="failed"||Q==="cancelled"}var rU=Symbol("Let zodToJsonSchema decide on which parser to use");var KP=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function v9(Q){let X=V6(Q)?.method;if(!X)throw Error("Schema is missing a method literal");let W=OG(X);if(typeof W!=="string")throw Error("Schema method literal must be a string");return W}function x9(Q,Y){let X=U1(Q,Y);if(!X.success)throw X.error;return X.data}var eU=60000;class _9{constructor(Q){if(this._options=Q,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(I6,(Y)=>{this._oncancel(Y)}),this.setNotificationHandler(T6,(Y)=>{this._onprogress(Y)}),this.setRequestHandler(E6,(Y)=>({})),this._taskStore=Q?.taskStore,this._taskMessageQueue=Q?.taskMessageQueue,this._taskStore)this.setRequestHandler(S6,async(Y,X)=>{let W=await this._taskStore.getTask(Y.params.taskId,X.sessionId);if(!W)throw new _(h.InvalidParams,"Failed to retrieve task: Task not found");return{...W}}),this.setRequestHandler(C6,async(Y,X)=>{let W=async()=>{let G=Y.params.taskId;if(this._taskMessageQueue){let z;while(z=await this._taskMessageQueue.dequeue(G,X.sessionId)){if(z.type==="response"||z.type==="error"){let J=z.message,H=J.id,A=this._requestResolvers.get(H);if(A)if(this._requestResolvers.delete(H),z.type==="response")A(J);else{let U=J,K=new _(U.error.code,U.error.message,U.error.data);A(K)}else{let U=z.type==="response"?"Response":"Error";this._onerror(Error(`${U} handler missing for request ${H}`))}continue}await this._transport?.send(z.message,{relatedRequestId:X.requestId})}}let $=await this._taskStore.getTask(G,X.sessionId);if(!$)throw new _(h.InvalidParams,`Task not found: ${G}`);if(!D1($.status))return await this._waitForTaskUpdate(G,X.signal),await W();if(D1($.status)){let z=await this._taskStore.getTaskResult(G,X.sessionId);return this._clearTaskQueue(G),{...z,_meta:{...z._meta,[K1]:{taskId:G}}}}return await W()};return await W()}),this.setRequestHandler(k6,async(Y,X)=>{try{let{tasks:W,nextCursor:G}=await this._taskStore.listTasks(Y.params?.cursor,X.sessionId);return{tasks:W,nextCursor:G,_meta:{}}}catch(W){throw new _(h.InvalidParams,`Failed to list tasks: ${W instanceof Error?W.message:String(W)}`)}}),this.setRequestHandler(x6,async(Y,X)=>{try{let W=await this._taskStore.getTask(Y.params.taskId,X.sessionId);if(!W)throw new _(h.InvalidParams,`Task not found: ${Y.params.taskId}`);if(D1(W.status))throw new _(h.InvalidParams,`Cannot cancel task in terminal status: ${W.status}`);await this._taskStore.updateTaskStatus(Y.params.taskId,"cancelled","Client cancelled task execution.",X.sessionId),this._clearTaskQueue(Y.params.taskId);let G=await this._taskStore.getTask(Y.params.taskId,X.sessionId);if(!G)throw new _(h.InvalidParams,`Task not found after cancellation: ${Y.params.taskId}`);return{_meta:{},...G}}catch(W){if(W instanceof _)throw W;throw new _(h.InvalidRequest,`Failed to cancel task: ${W instanceof Error?W.message:String(W)}`)}})}async _oncancel(Q){if(!Q.params.requestId)return;this._requestHandlerAbortControllers.get(Q.params.requestId)?.abort(Q.params.reason)}_setupTimeout(Q,Y,X,W,G=!1){this._timeoutInfo.set(Q,{timeoutId:setTimeout(W,Y),startTime:Date.now(),timeout:Y,maxTotalTimeout:X,resetTimeoutOnProgress:G,onTimeout:W})}_resetTimeout(Q){let Y=this._timeoutInfo.get(Q);if(!Y)return!1;let X=Date.now()-Y.startTime;if(Y.maxTotalTimeout&&X>=Y.maxTotalTimeout)throw this._timeoutInfo.delete(Q),_.fromError(h.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:Y.maxTotalTimeout,totalElapsed:X});return clearTimeout(Y.timeoutId),Y.timeoutId=setTimeout(Y.onTimeout,Y.timeout),!0}_cleanupTimeout(Q){let Y=this._timeoutInfo.get(Q);if(Y)clearTimeout(Y.timeoutId),this._timeoutInfo.delete(Q)}async connect(Q){this._transport=Q;let Y=this.transport?.onclose;this._transport.onclose=()=>{Y?.(),this._onclose()};let X=this.transport?.onerror;this._transport.onerror=(G)=>{X?.(G),this._onerror(G)};let W=this._transport?.onmessage;this._transport.onmessage=(G,$)=>{if(W?.(G,$),V4(G)||Q$(G))this._onresponse(G);else if(F9(G))this._onrequest(G,$);else if(eG(G))this._onnotification(G);else this._onerror(Error(`Unknown message type: ${JSON.stringify(G)}`))},await this._transport.start()}_onclose(){let Q=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();let Y=_.fromError(h.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let X of Q.values())X(Y)}_onerror(Q){this.onerror?.(Q)}_onnotification(Q){let Y=this._notificationHandlers.get(Q.method)??this.fallbackNotificationHandler;if(Y===void 0)return;Promise.resolve().then(()=>Y(Q)).catch((X)=>this._onerror(Error(`Uncaught error in notification handler: ${X}`)))}_onrequest(Q,Y){let X=this._requestHandlers.get(Q.method)??this.fallbackRequestHandler,W=this._transport,G=Q.params?._meta?.[K1]?.taskId;if(X===void 0){let A={jsonrpc:"2.0",id:Q.id,error:{code:h.MethodNotFound,message:"Method not found"}};if(G&&this._taskMessageQueue)this._enqueueTaskMessage(G,{type:"error",message:A,timestamp:Date.now()},W?.sessionId).catch((U)=>this._onerror(Error(`Failed to enqueue error response: ${U}`)));else W?.send(A).catch((U)=>this._onerror(Error(`Failed to send an error response: ${U}`)));return}let $=new AbortController;this._requestHandlerAbortControllers.set(Q.id,$);let z=tG(Q.params)?Q.params.task:void 0,J=this._taskStore?this.requestTaskStore(Q,W?.sessionId):void 0,H={signal:$.signal,sessionId:W?.sessionId,_meta:Q.params?._meta,sendNotification:async(A)=>{let U={relatedRequestId:Q.id};if(G)U.relatedTask={taskId:G};await this.notification(A,U)},sendRequest:async(A,U,K)=>{let D={...K,relatedRequestId:Q.id};if(G&&!D.relatedTask)D.relatedTask={taskId:G};let L=D.relatedTask?.taskId??G;if(L&&J)await J.updateTaskStatus(L,"input_required");return await this.request(A,U,D)},authInfo:Y?.authInfo,requestId:Q.id,requestInfo:Y?.requestInfo,taskId:G,taskStore:J,taskRequestedTtl:z?.ttl,closeSSEStream:Y?.closeSSEStream,closeStandaloneSSEStream:Y?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(z)this.assertTaskHandlerCapability(Q.method)}).then(()=>X(Q,H)).then(async(A)=>{if($.signal.aborted)return;let U={result:A,jsonrpc:"2.0",id:Q.id};if(G&&this._taskMessageQueue)await this._enqueueTaskMessage(G,{type:"response",message:U,timestamp:Date.now()},W?.sessionId);else await W?.send(U)},async(A)=>{if($.signal.aborted)return;let U={jsonrpc:"2.0",id:Q.id,error:{code:Number.isSafeInteger(A.code)?A.code:h.InternalError,message:A.message??"Internal error",...A.data!==void 0&&{data:A.data}}};if(G&&this._taskMessageQueue)await this._enqueueTaskMessage(G,{type:"error",message:U,timestamp:Date.now()},W?.sessionId);else await W?.send(U)}).catch((A)=>this._onerror(Error(`Failed to send response: ${A}`))).finally(()=>{this._requestHandlerAbortControllers.delete(Q.id)})}_onprogress(Q){let{progressToken:Y,...X}=Q.params,W=Number(Y),G=this._progressHandlers.get(W);if(!G){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(Q)}`));return}let $=this._responseHandlers.get(W),z=this._timeoutInfo.get(W);if(z&&$&&z.resetTimeoutOnProgress)try{this._resetTimeout(W)}catch(J){this._responseHandlers.delete(W),this._progressHandlers.delete(W),this._cleanupTimeout(W),$(J);return}G(X)}_onresponse(Q){let Y=Number(Q.id),X=this._requestResolvers.get(Y);if(X){if(this._requestResolvers.delete(Y),V4(Q))X(Q);else{let $=new _(Q.error.code,Q.error.message,Q.error.data);X($)}return}let W=this._responseHandlers.get(Y);if(W===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(Q)}`));return}this._responseHandlers.delete(Y),this._cleanupTimeout(Y);let G=!1;if(V4(Q)&&Q.result&&typeof Q.result==="object"){let $=Q.result;if($.task&&typeof $.task==="object"){let z=$.task;if(typeof z.taskId==="string")G=!0,this._taskProgressTokens.set(z.taskId,Y)}}if(!G)this._progressHandlers.delete(Y);if(V4(Q))W(Q);else{let $=_.fromError(Q.error.code,Q.error.message,Q.error.data);W($)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(Q,Y,X){let{task:W}=X??{};if(!W){try{yield{type:"result",result:await this.request(Q,Y,X)}}catch($){yield{type:"error",error:$ instanceof _?$:new _(h.InternalError,String($))}}return}let G;try{let $=await this.request(Q,l1,X);if($.task)G=$.task.taskId,yield{type:"taskCreated",task:$.task};else throw new _(h.InternalError,"Task creation did not return a task");while(!0){let z=await this.getTask({taskId:G},X);if(yield{type:"taskStatus",task:z},D1(z.status)){if(z.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:G},Y,X)};else if(z.status==="failed")yield{type:"error",error:new _(h.InternalError,`Task ${G} failed`)};else if(z.status==="cancelled")yield{type:"error",error:new _(h.InternalError,`Task ${G} was cancelled`)};return}if(z.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:G},Y,X)};return}let J=z.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((H)=>setTimeout(H,J)),X?.signal?.throwIfAborted()}}catch($){yield{type:"error",error:$ instanceof _?$:new _(h.InternalError,String($))}}}request(Q,Y,X){let{relatedRequestId:W,resumptionToken:G,onresumptiontoken:$,task:z,relatedTask:J}=X??{};return new Promise((H,A)=>{let U=(Z)=>{A(Z)};if(!this._transport){U(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(Q.method),z)this.assertTaskCapability(Q.method)}catch(Z){U(Z);return}X?.signal?.throwIfAborted();let K=this._requestMessageId++,D={...Q,jsonrpc:"2.0",id:K};if(X?.onprogress)this._progressHandlers.set(K,X.onprogress),D.params={...Q.params,_meta:{...Q.params?._meta||{},progressToken:K}};if(z)D.params={...D.params,task:z};if(J)D.params={...D.params,_meta:{...D.params?._meta||{},[K1]:J}};let L=(Z)=>{this._responseHandlers.delete(K),this._progressHandlers.delete(K),this._cleanupTimeout(K),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:K,reason:String(Z)}},{relatedRequestId:W,resumptionToken:G,onresumptiontoken:$}).catch((S)=>this._onerror(Error(`Failed to send cancellation: ${S}`)));let k=Z instanceof _?Z:new _(h.RequestTimeout,String(Z));A(k)};this._responseHandlers.set(K,(Z)=>{if(X?.signal?.aborted)return;if(Z instanceof Error)return A(Z);try{let k=U1(Y,Z.result);if(!k.success)A(k.error);else H(k.data)}catch(k){A(k)}}),X?.signal?.addEventListener("abort",()=>{L(X?.signal?.reason)});let O=X?.timeout??eU,M=()=>L(_.fromError(h.RequestTimeout,"Request timed out",{timeout:O}));this._setupTimeout(K,O,X?.maxTotalTimeout,M,X?.resetTimeoutOnProgress??!1);let N=J?.taskId;if(N){let Z=(k)=>{let S=this._responseHandlers.get(K);if(S)S(k);else this._onerror(Error(`Response handler missing for side-channeled request ${K}`))};this._requestResolvers.set(K,Z),this._enqueueTaskMessage(N,{type:"request",message:D,timestamp:Date.now()}).catch((k)=>{this._cleanupTimeout(K),A(k)})}else this._transport.send(D,{relatedRequestId:W,resumptionToken:G,onresumptiontoken:$}).catch((Z)=>{this._cleanupTimeout(K),A(Z)})})}async getTask(Q,Y){return this.request({method:"tasks/get",params:Q},R6,Y)}async getTaskResult(Q,Y,X){return this.request({method:"tasks/result",params:Q},Y,X)}async listTasks(Q,Y){return this.request({method:"tasks/list",params:Q},v6,Y)}async cancelTask(Q,Y){return this.request({method:"tasks/cancel",params:Q},W$,Y)}async notification(Q,Y){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(Q.method);let X=Y?.relatedTask?.taskId;if(X){let z={...Q,jsonrpc:"2.0",params:{...Q.params,_meta:{...Q.params?._meta||{},[K1]:Y.relatedTask}}};await this._enqueueTaskMessage(X,{type:"notification",message:z,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(Q.method)&&!Q.params&&!Y?.relatedRequestId&&!Y?.relatedTask){if(this._pendingDebouncedNotifications.has(Q.method))return;this._pendingDebouncedNotifications.add(Q.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(Q.method),!this._transport)return;let z={...Q,jsonrpc:"2.0"};if(Y?.relatedTask)z={...z,params:{...z.params,_meta:{...z.params?._meta||{},[K1]:Y.relatedTask}}};this._transport?.send(z,Y).catch((J)=>this._onerror(J))});return}let $={...Q,jsonrpc:"2.0"};if(Y?.relatedTask)$={...$,params:{...$.params,_meta:{...$.params?._meta||{},[K1]:Y.relatedTask}}};await this._transport.send($,Y)}setRequestHandler(Q,Y){let X=v9(Q);this.assertRequestHandlerCapability(X),this._requestHandlers.set(X,(W,G)=>{let $=x9(Q,W);return Promise.resolve(Y($,G))})}removeRequestHandler(Q){this._requestHandlers.delete(Q)}assertCanSetRequestHandler(Q){if(this._requestHandlers.has(Q))throw Error(`A request handler for ${Q} already exists, which would be overridden`)}setNotificationHandler(Q,Y){let X=v9(Q);this._notificationHandlers.set(X,(W)=>{let G=x9(Q,W);return Promise.resolve(Y(G))})}removeNotificationHandler(Q){this._notificationHandlers.delete(Q)}_cleanupTaskProgressHandler(Q){let Y=this._taskProgressTokens.get(Q);if(Y!==void 0)this._progressHandlers.delete(Y),this._taskProgressTokens.delete(Q)}async _enqueueTaskMessage(Q,Y,X){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(Q,Y,X,W)}async _clearTaskQueue(Q,Y){if(this._taskMessageQueue){let X=await this._taskMessageQueue.dequeueAll(Q,Y);for(let W of X)if(W.type==="request"&&F9(W.message)){let G=W.message.id,$=this._requestResolvers.get(G);if($)$(new _(h.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(G);else this._onerror(Error(`Resolver missing for request ${G} during task ${Q} cleanup`))}}}async _waitForTaskUpdate(Q,Y){let X=this._options?.defaultTaskPollInterval??1000;try{let W=await this._taskStore?.getTask(Q);if(W?.pollInterval)X=W.pollInterval}catch{}return new Promise((W,G)=>{if(Y.aborted){G(new _(h.InvalidRequest,"Request cancelled"));return}let $=setTimeout(W,X);Y.addEventListener("abort",()=>{clearTimeout($),G(new _(h.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(Q,Y){let X=this._taskStore;if(!X)throw Error("No task store configured");return{createTask:async(W)=>{if(!Q)throw Error("No request provided");return await X.createTask(W,Q.id,{method:Q.method,params:Q.params},Y)},getTask:async(W)=>{let G=await X.getTask(W,Y);if(!G)throw new _(h.InvalidParams,"Failed to retrieve task: Task not found");return G},storeTaskResult:async(W,G,$)=>{await X.storeTaskResult(W,G,$,Y);let z=await X.getTask(W,Y);if(z){let J=b4.parse({method:"notifications/tasks/status",params:z});if(await this.notification(J),D1(z.status))this._cleanupTaskProgressHandler(W)}},getTaskResult:(W)=>{return X.getTaskResult(W,Y)},updateTaskStatus:async(W,G,$)=>{let z=await X.getTask(W,Y);if(!z)throw new _(h.InvalidParams,`Task "${W}" not found - it may have been cleaned up`);if(D1(z.status))throw new _(h.InvalidParams,`Cannot update task "${W}" from terminal status "${z.status}" to "${G}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await X.updateTaskStatus(W,G,$,Y);let J=await X.getTask(W,Y);if(J){let H=b4.parse({method:"notifications/tasks/status",params:J});if(await this.notification(H),D1(J.status))this._cleanupTaskProgressHandler(W)}},listTasks:(W)=>{return X.listTasks(W,Y)}}}}function U$(Q){return Q!==null&&typeof Q==="object"&&!Array.isArray(Q)}function K$(Q,Y){let X={...Q};for(let W in Y){let G=W,$=Y[G];if($===void 0)continue;let z=X[G];if(U$(z)&&U$($))X[G]={...z,...$};else X[G]=$}return X}var m5=FX(SY(),1),c5=FX(l5(),1);function HV(){let Q=new m5.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return c5.default(Q),Q}class hY{constructor(Q){this._ajv=Q??HV()}getValidator(Q){let Y="$id"in Q&&typeof Q.$id==="string"?this._ajv.getSchema(Q.$id)??this._ajv.compile(Q):this._ajv.compile(Q);return(X)=>{if(Y(X))return{valid:!0,data:X,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(Y.errors)}}}}class fY{constructor(Q){this._server=Q}requestStream(Q,Y,X){return this._server.requestStream(Q,Y,X)}async getTask(Q,Y){return this._server.getTask({taskId:Q},Y)}async getTaskResult(Q,Y,X){return this._server.getTaskResult({taskId:Q},Y,X)}async listTasks(Q,Y){return this._server.listTasks(Q?{cursor:Q}:void 0,Y)}async cancelTask(Q,Y){return this._server.cancelTask({taskId:Q},Y)}}function p5(Q,Y,X){if(!Q)throw Error(`${X} does not support task creation (required for ${Y})`);switch(Y){case"tools/call":if(!Q.tools?.call)throw Error(`${X} does not support task creation for tools/call (required for ${Y})`);break;default:break}}function i5(Q,Y,X){if(!Q)throw Error(`${X} does not support task creation (required for ${Y})`);switch(Y){case"sampling/createMessage":if(!Q.sampling?.createMessage)throw Error(`${X} does not support task creation for sampling/createMessage (required for ${Y})`);break;case"elicitation/create":if(!Q.elicitation?.create)throw Error(`${X} does not support task creation for elicitation/create (required for ${Y})`);break;default:break}}class lY extends _9{constructor(Q,Y){super(Y);if(this._serverInfo=Q,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(E4.options.map((X,W)=>[X,W])),this.isMessageIgnored=(X,W)=>{let G=this._loggingLevels.get(W);return G?this.LOG_LEVEL_SEVERITY.get(X)<this.LOG_LEVEL_SEVERITY.get(G):!1},this._capabilities=Y?.capabilities??{},this._instructions=Y?.instructions,this._jsonSchemaValidator=Y?.jsonSchemaValidator??new hY,this.setRequestHandler(M9,(X)=>this._oninitialize(X)),this.setNotificationHandler(V9,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(S9,async(X,W)=>{let G=W.sessionId||W.requestInfo?.headers["mcp-session-id"]||void 0,{level:$}=X.params,z=E4.safeParse($);if(z.success)this._loggingLevels.set(G,z.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new fY(this)};return this._experimental}registerCapabilities(Q){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=K$(this._capabilities,Q)}setRequestHandler(Q,Y){let W=V6(Q)?.method;if(!W)throw Error("Schema is missing a method literal");let G;if(h1(W)){let z=W;G=z._zod?.def?.value??z.value}else{let z=W;G=z._def?.value??z.value}if(typeof G!=="string")throw Error("Schema method literal must be a string");if(G==="tools/call"){let z=async(J,H)=>{let A=U1(I4,J);if(!A.success){let L=A.error instanceof Error?A.error.message:String(A.error);throw new _(h.InvalidParams,`Invalid tools/call request: ${L}`)}let{params:U}=A.data,K=await Promise.resolve(Y(J,H));if(U.task){let L=U1(l1,K);if(!L.success){let O=L.error instanceof Error?L.error.message:String(L.error);throw new _(h.InvalidParams,`Invalid task creation result: ${O}`)}return L.data}let D=U1(_6,K);if(!D.success){let L=D.error instanceof Error?D.error.message:String(D.error);throw new _(h.InvalidParams,`Invalid tools/call result: ${L}`)}return D.data};return super.setRequestHandler(Q,z)}return super.setRequestHandler(Q,Y)}assertCapabilityForMethod(Q){switch(Q){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${Q})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${Q})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${Q})`);break;case"ping":break}}assertNotificationCapability(Q){switch(Q){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${Q})`);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 ${Q})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${Q})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${Q})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${Q})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(Q){if(!this._capabilities)return;switch(Q){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${Q})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${Q})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${Q})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${Q})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${Q})`);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 ${Q})`);break;case"ping":case"initialize":break}}assertTaskCapability(Q){i5(this._clientCapabilities?.tasks?.requests,Q,"Client")}assertTaskHandlerCapability(Q){if(!this._capabilities)return;p5(this._capabilities.tasks?.requests,Q,"Server")}async _oninitialize(Q){let Y=Q.params.protocolVersion;return this._clientCapabilities=Q.params.capabilities,this._clientVersion=Q.params.clientInfo,{protocolVersion:rG.includes(Y)?Y:B9,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"},j6)}async createMessage(Q,Y){if(Q.tools||Q.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if(Q.messages.length>0){let X=Q.messages[Q.messages.length-1],W=Array.isArray(X.content)?X.content:[X.content],G=W.some((H)=>H.type==="tool_result"),$=Q.messages.length>1?Q.messages[Q.messages.length-2]:void 0,z=$?Array.isArray($.content)?$.content:[$.content]:[],J=z.some((H)=>H.type==="tool_use");if(G){if(W.some((H)=>H.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!J)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(J){let H=new Set(z.filter((U)=>U.type==="tool_use").map((U)=>U.id)),A=new Set(W.filter((U)=>U.type==="tool_result").map((U)=>U.toolUseId));if(H.size!==A.size||![...H].every((U)=>A.has(U)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if(Q.tools)return this.request({method:"sampling/createMessage",params:Q},C9,Y);return this.request({method:"sampling/createMessage",params:Q},R9,Y)}async elicitInput(Q,Y){switch(Q.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let W=Q;return this.request({method:"elicitation/create",params:W},g6,Y)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let W=Q.mode==="form"?Q:{...Q,mode:"form"},G=await this.request({method:"elicitation/create",params:W},g6,Y);if(G.action==="accept"&&G.content&&W.requestedSchema)try{let z=this._jsonSchemaValidator.getValidator(W.requestedSchema)(G.content);if(!z.valid)throw new _(h.InvalidParams,`Elicitation response content does not match requested schema: ${z.errorMessage}`)}catch($){if($ instanceof _)throw $;throw new _(h.InternalError,`Error validating elicitation response: ${$ instanceof Error?$.message:String($)}`)}return G}}}createElicitationCompletionNotifier(Q,Y){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:Q}},Y)}async listRoots(Q,Y){return this.request({method:"roots/list",params:Q},k9,Y)}async sendLoggingMessage(Q,Y){if(this._capabilities.logging){if(!this.isMessageIgnored(Q.level,Y))return this.notification({method:"notifications/message",params:Q})}}async sendResourceUpdated(Q){return this.notification({method:"notifications/resources/updated",params:Q})}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 n5={name:"@sequenzy/mcp",version:"0.0.102",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 mY=["product-info","domain","tracking","localization","integrations","products","events","tags","labels","goals","sync-rules","api-keys","widgets","team","danger"],r5={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 UV(Q){let X=(Q??process.env.SEQUENZY_APP_URL??"https://sequenzy.com").trim().replace(/\/+$/,"");return X.length>0?X:"https://sequenzy.com"}function l0(Q){let Y=Q?.trim();return Y?Y:void 0}function r0(Q){return encodeURIComponent(Q)}function z0(Q,Y){return`${Q}${Y}`}function J0(Q,Y=""){return`/dashboard/company/${r0(Q)}${Y}`}function d5(Q,Y,X){return z0(Q,`${J0(Y,"/settings")}?tab=${encodeURIComponent(X)}`)}function KV(Q,Y){let X=mY.map((W)=>[W,Y?d5(Q,Y,W):""]);return Object.fromEntries(X)}function Z1(Q={},Y){let X=UV(Y),W=l0(Q.companyId),G={},$=KV(X,W);if(!W)return{appUrl:X,routeTemplates:r5,settingsTabValues:mY,urls:G,settingsUrls:$};G.dashboard=z0(X,J0(W)),G.campaigns=z0(X,J0(W,"/campaign")),G.landingPages=z0(X,J0(W,"/landing-pages")),G.sequences=z0(X,J0(W,"/sequences")),G.settings=z0(X,J0(W,"/settings")),G.emails=z0(X,J0(W,"/emails")),G.subscribers=z0(X,J0(W,"/subscribers")),G.sentEmails=z0(X,J0(W,"/sent-emails")),G.segments=z0(X,J0(W,"/segments")),G.metrics=z0(X,J0(W,"/metrics")),G.transactional=z0(X,J0(W,"/transactional"));let z=l0(Q.campaignId);if(z)G.campaign=z0(X,J0(W,`/campaign/${r0(z)}`)),G.campaignPreview=`${G.campaign}?step=review`;let J=l0(Q.landingPageId);if(J)G.landingPage=z0(X,J0(W,`/landing-pages/${r0(J)}`));let H=l0(Q.sequenceId);if(H)G.sequence=z0(X,J0(W,`/sequences/${r0(H)}`));let A=l0(Q.emailId)??l0(Q.templateId);if(A)G.email=z0(X,J0(W,`/emails/${r0(A)}`)),G.template=G.email;let U=l0(Q.transactionalId);if(U)G.transactionalEmail=z0(X,J0(W,`/transactional/${r0(U)}`));let K=l0(Q.emailSendId);if(K)G.emailSend=z0(X,J0(W,`/sent-emails/${r0(K)}`));let D=l0(Q.domainId);if(D)G.domain=z0(X,J0(W,`/settings/domain/${r0(D)}`)),G.domainVerify=`${G.domain}/verify`;let L=l0(Q.status);if(L)G.campaignList=z0(X,J0(W,`/campaign/list/${r0(L)}`)),G.sequenceList=z0(X,J0(W,`/sequences/list/${r0(L)}`));let O=l0(Q.settingsTab);if(O)G.settingsTab=d5(X,W,O);return{appUrl:X,routeTemplates:r5,settingsTabValues:mY,urls:G,settingsUrls:$}}var o5=[{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 t5(Q){try{let Y;switch(Q){case"sequenzy://dashboard":Y=await B("GET","/api/v1/metrics?period=7d");break;case"sequenzy://company":{let X=await B("GET","/api/v1/account"),W=b1()??X.currentCompanyId;if(!W)throw Error("No company available. Create or select a company first.");Y=await B("GET",`/api/v1/companies/${W}`);break}case"sequenzy://campaigns/recent":Y=await B("GET","/api/v1/campaigns?limit=10");break;case"sequenzy://subscribers/recent":Y=await B("GET","/api/v1/subscribers?sort=createdAt&limit=20");break;case"sequenzy://subscribers/engaged":Y=await B("GET","/api/v1/subscribers?sort=engagement&limit=20");break;case"sequenzy://sequences":Y=await B("GET","/api/v1/sequences");break;case"sequenzy://templates":Y=await B("GET","/api/v1/templates");break;case"sequenzy://segments":Y=await B("GET","/api/v1/segments");break;case"sequenzy://tags":Y=await B("GET","/api/v1/tags");break;case"sequenzy://health":Y=await B("GET","/api/v1/health/deliverability");break;case"sequenzy://app-routes":Y=Z1();break;default:throw Error(`Unknown resource: ${Q}`)}return{contents:[{uri:Q,mimeType:"application/json",text:JSON.stringify(Y,null,2)}]}}catch(Y){return{contents:[{uri:Q,mimeType:"text/plain",text:$1(Y)}]}}}import{readFileSync as DV,statSync as BV}from"node:fs";import{basename as LV}from"node:path";var $X=' Any block accepts a `conditions` array so it only renders for matching recipients. To branch on a value passed in the transactional send `variables` or an automation `event` payload, use { "id": "c1", "field": "variable", "operator": "is", "value": "plan:pro" } where the text before the colon is a {{merge tag}} path (nested paths like "order.total" or "event.plan" work) and the text after it is the comparison value. `field` may also be "attribute" (same "name:value" form) or "email"/"firstName"/"lastName" (the value is the plain comparison string). Operators: is, is_not, contains, not_contains, gt, gte, lt, lte, is_empty, is_not_empty. For if/else, use a { type: "conditional-group", conditions: [...], ifBranch: { children: [...] }, elseBranch: { children: [...] } } block.',s4=`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: [...] }.${$X}`,Q4=`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\`.${$X}`,aY=`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.${$X}`,NQ="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.",FV="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.",a5=500,s5=500,N1={type:"boolean",description:"If true, include machine-classified bot/scanner opens and clicks. Defaults to false, so metrics and activity are human-only."},cY=["send","delivery","bounce","complaint","open","click","unsubscribe","delivery_delay"],e5={type:"object",description:"Optional send window for every email step in the sequence. When set, email actions that become due outside the window wait until the next allowed local time. Omit days to allow every day.",properties:{enabled:{type:"boolean",description:"Set false to disable the sending window when creating a sequence. For updates, prefer clearSendingWindow."},timezone:{type:"string",description:"IANA timezone for the window, e.g. Europe/Kiev or America/New_York."},startTime:{type:"string",description:"Earliest local send time in 24-hour HH:mm format, e.g. 08:00."},endTime:{type:"string",description:"Latest local send cutoff in 24-hour HH:mm format, e.g. 20:00. Must be later than startTime."},days:{type:"array",description:"Allowed local days. Use full names or short names such as monday, tuesday, mon, tue. Omit for every day.",items:{type:"string"}}},additionalProperties:!1},qV={type:"object",description:"Offset relative to a wait-until date.",properties:{days:{type:"number"},hours:{type:"number"},minutes:{type:"number"}},additionalProperties:!1},sY={type:"object",description:"Wait until a date from the trigger event before this step. Use this for renewal reminders, appointment follow-ups, trial-expiry nudges, and other subscriber-specific dates. The field value must be an ISO date string or Unix timestamp.",properties:{field:{type:"string",description:"Dot-path into the trigger event properties, e.g. renews_at or booking.startsAt."},untilDateField:{type:"string",description:"Alias for field."},offset:qV,days:{type:"number",description:"Offset days shorthand. Ignored when offset is provided."},hours:{type:"number",description:"Offset hours shorthand. Ignored when offset is provided."},minutes:{type:"number",description:"Offset minutes shorthand. Ignored when offset is provided."},direction:{type:"string",enum:["before","after"],description:"Whether the offset applies before or after the resolved date. Defaults to after."},untilOffsetDirection:{type:"string",enum:["before","after"],description:"Alias for direction."},missingAction:{type:"string",enum:["continue","exit"],description:"What to do if the event field is missing or invalid. Defaults to continue."},untilMissingAction:{type:"string",enum:["continue","exit"],description:"Alias for missingAction."}},additionalProperties:!1},eY={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},wQ=["gray","red","orange","amber","yellow","lime","green","emerald","teal","cyan","sky","blue","indigo","violet","purple","fuchsia","pink","rose"],PQ=["email.sent","email.delivered","email.delivery_delayed","email.bounced","email.complained","email.opened","email.clicked","email.replied","email.unsubscribed","sms.sent","sms.delivered","sms.failed","sms.opted_out","subscriber.invalid","subscriber.updated","subscriber.unsubscribed","sequence.finished","sequence.failed"],OV=new Set(["get_account","get_app_urls","get_company","get_sync_rules","get_shopify_automation_settings","list_websites","check_website","get_integration_guide","get_subscriber","list_subscriber_notes","search_subscribers","list_products","list_tags","list_lists","list_segments","get_segment_count","list_audience_syncs","list_ad_accounts","list_templates","get_template","list_ab_tests","get_ab_test","get_ab_test_stats","list_campaigns","get_campaign","get_email_send","list_landing_pages","get_landing_page","list_sequences","get_sequence","list_transactional_emails","get_transactional_email","get_stats","get_campaign_stats","get_sequence_stats","list_campaign_events","list_sequence_events","get_subscriber_activity","list_team_members","list_conversations","get_conversation","list_webhooks","list_webhook_deliveries","generate_email","generate_sequence","generate_subject_lines","generate_sms","get_sms_settings"]),MV=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","sync_products","create_tag","update_tag","delete_tag","create_list","update_list","delete_list","add_subscribers_to_list","remove_subscribers_from_list","create_segment","update_segment","delete_segment","create_audience_sync","update_audience_sync","delete_audience_sync","sync_audience_now","create_template","update_template","delete_template","restart_ab_test","update_ab_test_variant","create_ab_test","add_ab_test_variant","delete_ab_test_variant","delete_ab_test","create_campaign","update_campaign","schedule_campaign","send_test_email","send_test_sms","cancel_campaign","pause_campaign","resume_campaign","delete_campaign","duplicate_campaign","resend_campaign_to_non_openers","create_landing_page","update_landing_page","delete_landing_page","publish_landing_page","unpublish_landing_page","connect_landing_page_domain","update_landing_page_domain_settings","create_sequence","update_sequence","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"]),VV=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"]),ZV=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","cancel_sequence_enrollments","delete_sequence","cancel_team_invitation","delete_webhook"]);function NV(Q){let Y=OV.has(Q),X=MV.has(Q);if(Y===X)throw Error(`MCP tool "${Q}" must be classified as exactly one of read-only or mutating.`);return{readOnlyHint:Y,destructiveHint:Y?!1:ZV.has(Q),openWorldHint:VV.has(Q)}}function wV(Q){return{...Q,annotations:{...Q.annotations,...NV(Q.name)}}}var QX={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"],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"]},PV=Object.entries(QX).map(([Q,Y])=>`${Q}: ${Y.join(", ")}`).join("; "),QH={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","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."},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: ${PV}.`},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)."}},required:["field","operator","value"],additionalProperties:!1},YH={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 YX(Q){if(!Array.isArray(Q))return Q;return Q.map((Y)=>{if(typeof Y!=="object"||Y===null)return Y;let X=Y;if(typeof X.id==="string"&&X.id.trim()!=="")return X;return{...X,id:crypto.randomUUID()}})}function XX(Q){if(typeof Q!=="object"||Q===null)return Q;let Y=Q;if(Y.kind==="filter"||"field"in Y||"operator"in Y||"value"in Y){let X=YX([Y]);return Array.isArray(X)?X[0]:Y}if(Y.kind!=="group")return Q;return{...Y,id:typeof Y.id==="string"&&Y.id.trim()!==""?Y.id:crypto.randomUUID(),children:Array.isArray(Y.children)?Y.children.map(XX):[]}}function bV(Q){let Y=Q.indexOf(":");return Y!==-1&&Q.substring(0,Y).trim().length>0}function jV(Q){let Y=Q.indexOf(":");return Y!==-1&&Q.substring(Y+1).trim().length>0}function XH(Q){if(Q==="all")return!0;let Y=Q.match(/^(\d+)d$/);if(!Y?.[1])return!1;let X=Number.parseInt(Y[1],10);return Number.isInteger(X)&&X>0}function IV(Q,Y){let X=Y.split(":");if(Q==="at_least"||Q==="less_than_count"){if(X.length<3)return'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".';let $=X.slice(0,-2).join(":").trim(),z=X.at(-2),J=X.at(-1),H=z===void 0?Number.NaN:Number.parseInt(z,10);return $&&Number.isInteger(H)&&H>0&&J!==void 0&&XH(J)?null:'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".'}if(X.length<2)return'Event filters must use "eventName:timeRange", like "saas.purchase:30d".';let W=X.slice(0,-1).join(":").trim(),G=X.at(-1);return W&&G!==void 0&&XH(G)?null:'Event filters must use "eventName:timeRange", like "saas.purchase:30d".'}function EV(Q){let Y=Q.indexOf(":");if(Y===-1)return{productId:Q,subfilter:null,rawValue:null};let X=Q.substring(0,Y),W=Q.substring(Y+1),G=W.indexOf(":");if(G===-1)return{productId:X,subfilter:W,rawValue:null};return{productId:X,subfilter:W.substring(0,G),rawValue:W.substring(G+1)}}function TV(Q){return Q.trim().toLowerCase().replace(/[-\s]+/g,"_")}function SV(Q){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(Q)}function RV(Q,Y){if(Y==="cancels_at"||Y==="cancel_at"||Y==="cancellation_at")return!0;if(Q==="stripeCurrentProduct")return["end_at","ends_at","period_end","period_ends_at","current_period_end"].includes(Y);return["start_at","started_at","trial_start","trial_started_at","end_at","ends_at","trial_end","trial_ends_at"].includes(Y)}function CV(Q){return["is","is_not","gte","lte","gt","lt"].includes(Q)}function kV(Q,Y,X){if(Q==="stripeProduct"){if(Y!=="at_least"&&Y!=="less_than_count")return null;let J=X.indexOf(":");if(J===-1)return null;let H=X.substring(0,J).trim(),A=Number.parseInt(X.substring(J+1).trim(),10);return H&&Number.isInteger(A)&&A>=1?null:'Stripe Product threshold filters must use "productId:count" with a count of at least 1.'}if(Q!=="stripeCurrentProduct"&&Q!=="stripeTrialProduct")return null;let{productId:W,subfilter:G,rawValue:$}=EV(X);if(!W.trim())return"Stripe product filters must include a product ID.";if(!G)return Y==="is"||Y==="is_not"?null:'Stripe current/trial date filters must use "productId:dateField:value".';let z=TV(G);if(SV(z))return Y==="is"||Y==="is_not"?null:"Stripe cancellation flag filters only support is and is_not operators.";if(!RV(Q,z))return`Unsupported Stripe product subfilter "${G}".`;if(!CV(Y))return"Stripe date filters only support is, is_not, gte, lte, gt, and lt operators.";return $?.trim()?null:'Stripe date filters must include a value like "productId:end_at:2026-05-26".'}var vV=new Set(["shopify","woocommerce","api"]);function xV(Q,Y){let X=Y.trim(),W=X.indexOf(":");if(W!==-1&&vV.has(X.substring(0,W).trim()))X=X.substring(W+1).trim();if(!X)return'Purchased Product filters must include a product ID, like "shopify:42".';if(Q!=="at_least"&&Q!=="less_than_count")return null;let G=X.lastIndexOf(":");if(G===-1)return null;let $=X.substring(0,G).trim(),z=Number.parseInt(X.substring(G+1).trim(),10);return $&&Number.isInteger(z)&&z>=1?null:'Purchased Product threshold filters must use "provider:productId:count" with a count of at least 1.'}function zX(Q){if(typeof Q!=="object"||Q===null)return"Segment filters must be objects.";let Y=Q,X=Y.field,W=Y.operator,G=Y.value;if(typeof X!=="string"||!(X in QX))return`Unsupported segment filter field "${String(X)}".`;if(typeof W!=="string")return`Segment filter "${X}" must include an operator.`;let $=QX[X];if(!$.includes(W))return`Operator "${W}" is not supported for ${X} filters. Use one of: ${$.join(", ")}.`;if(W!=="is_empty"&&W!=="is_not_empty"&&(typeof G!=="string"||G.trim().length===0))return`Segment filter "${X}" must include a value.`;if(X==="attribute"&&typeof G==="string"){if(!bV(G))return'Attribute filters must use "attributeName:value" or "attributeName:" for empty checks.';if(W!=="is_empty"&&W!=="is_not_empty"&&!jV(G))return'Attribute filters must include a value after "attributeName:".'}if(X==="event"&&typeof G==="string"){let z=IV(W,G);if(z)return z}if((X==="stripeProduct"||X==="stripeCurrentProduct"||X==="stripeTrialProduct")&&typeof G==="string"){let z=kV(X,W,G);if(z)return z}if(X==="commerceProduct"&&typeof G==="string"){let z=xV(W,G);if(z)return z}if(X==="tag"&&(W==="contains"||W==="not_contains")){if(!(typeof G==="string"&&G.split(",").map((J)=>J.trim()).some(Boolean)))return"Tag filters must include at least one tag name."}return null}function JX(Q){if(typeof Q!=="object"||Q===null)return[];let Y=Q;if(Y.kind==="filter"||"field"in Y||"operator"in Y||"value"in Y){let X=zX(Y);return X?[X]:[]}if(Array.isArray(Y.children))return Y.children.flatMap(JX);return[]}function w1(Q,Y,X){if(Y.html!==void 0&&Y.blocks!==void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${Q}\`, not both.`);if(Y.blocks!==void 0&&!Array.isArray(Y.blocks))throw Error(`\`blocks\` must be an array when calling \`${Q}\`.`);if(X?.requireContent&&Y.html===void 0&&Y.blocks===void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${Q}\`.`)}function bQ(Q,Y){if(Y.labels===void 0)return;if(!Array.isArray(Y.labels))throw Error(`\`labels\` must be an array when calling \`${Q}\`.`);if(Y.labels.some((X)=>typeof X!=="string"||X.trim().length===0))throw Error(`\`labels\` must contain only non-empty strings when calling \`${Q}\`.`)}function _V(Q){let Y=Q.filters!==void 0,X=Q.root!==void 0;if(Y&&X)throw Error("Provide either `filters` or `root` when calling `create_segment`, not both.");if(!Y&&!X)throw Error("Provide either `filters` or `root` when calling `create_segment`.");if(Y){if(!Array.isArray(Q.filters))throw Error("`filters` must be an array when calling `create_segment`.");if(Q.filters.length===0)throw Error("`filters` must include at least one filter when calling `create_segment`.")}if(X&&(typeof Q.root!=="object"||Q.root===null))throw Error("`root` must be an object when calling `create_segment`.");let W=Y?Q.filters.flatMap((G)=>{let $=zX(G);return $?[$]:[]}):JX(Q.root);if(W.length>0)throw Error(W[0]??"Invalid segment filter in `create_segment`.")}function gV(Q){let Y=Q.filters!==void 0,X=Q.root!==void 0;if(Y&&X)throw Error("Provide either `filters` or `root` when calling `update_segment`, not both.");if(Q.name===void 0&&Q.filterJoinOperator===void 0&&!Y&&!X)throw Error("Provide at least one of `name`, `filters`, `root`, or `filterJoinOperator` when calling `update_segment`.");if(Y){if(!Array.isArray(Q.filters))throw Error("`filters` must be an array when calling `update_segment`.");if(Q.filters.length===0)throw Error("`filters` must include at least one filter when calling `update_segment`.")}if(X&&(typeof Q.root!=="object"||Q.root===null))throw Error("`root` must be an object when calling `update_segment`.");let W=Y?Q.filters.flatMap((G)=>{let $=zX(G);return $?[$]:[]}):X?JX(Q.root):[];if(W.length>0)throw Error(W[0]??"Invalid segment filter in `update_segment`.")}var pY=["name","description","logoUrl","founderName","primaryColor","brandColors","valueProps","testimonials","toneVoice","companyContext","emailLengthPreference","socialLinks","privacyPolicyUrl","termsUrl","address","language","pricing","fontFamily","emailDirection","fromEmail","fromName","replyTo","replyToName"];function iY(Q,Y,X){if(Y[X]!==void 0&&!Y0(Y[X]))throw Error(`\`${X}\` must be an object when calling \`${Q}\`.`)}function WH(Q,Y,X){if(Y[X]!==void 0&&!Array.isArray(Y[X]))throw Error(`\`${X}\` must be an array when calling \`${Q}\`.`)}function yV(Q){let Y=new Set(["companyId",...pY]),X=Object.keys(Q).filter((G)=>!Y.has(G));if(X.length>0)throw Error(`\`update_company\` accepts only company product-info fields. Unsupported field${X.length===1?"":"s"}: ${X.map((G)=>`\`${G}\``).join(", ")}.`);let W={};for(let G of pY)if(Q[G]!==void 0)W[G]=Q[G];if(Object.keys(W).length===0)throw Error(`Provide at least one of ${pY.map((G)=>`\`${G}\``).join(", ")} when calling \`update_company\`.`);for(let G of["name","description","logoUrl","founderName","primaryColor","toneVoice","companyContext","emailLengthPreference","privacyPolicyUrl","termsUrl","address","language","fontFamily","emailDirection","fromEmail","fromName","replyTo","replyToName"])if(Q[G]!==void 0&&typeof Q[G]!=="string")throw Error(`\`${G}\` must be a string when calling \`update_company\`.`);if(iY("update_company",Q,"brandColors"),iY("update_company",Q,"socialLinks"),iY("update_company",Q,"pricing"),WH("update_company",Q,"valueProps"),WH("update_company",Q,"testimonials"),typeof Q.primaryColor==="string"&&!/^#[0-9a-f]{6}$/i.test(Q.primaryColor.trim()))throw Error("`primaryColor` must be a 6-digit hex color such as #f97316 when calling `update_company`.");for(let G of["fromEmail","replyTo"]){let $=Q[G];if(typeof $==="string"&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test($.trim()))throw Error(`\`${G}\` must be a valid email address when calling \`update_company\`.`)}if(Q.fromName!==void 0&&Q.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `update_company`.");if(Q.replyToName!==void 0&&Q.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `update_company`.");return W}var DH=["senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName"];function uV(Q){return DH.some((Y)=>Q[Y]!==void 0)}function hV(Q){if(typeof Q.nodeType==="string")return Q.nodeType==="action_email";return Q.type===void 0||Q.type==="email"}function HX(Q,Y,X){for(let W of DH){let G=X[W];if(G!==void 0&&typeof G!=="string")throw Error(`\`${W}\` must be a string for ${Y} when calling \`${Q}\`.`)}if(X.senderProfileId!==void 0&&X.fromEmail!==void 0)throw Error(`Provide either \`senderProfileId\` or \`fromEmail\` for ${Y} when calling \`${Q}\`, not both.`);if(X.replyProfileId!==void 0&&X.replyTo!==void 0)throw Error(`Provide either \`replyProfileId\` or \`replyTo\` for ${Y} when calling \`${Q}\`, not both.`);if(X.replyToName!==void 0&&X.replyTo===void 0)throw Error(`\`replyToName\` requires \`replyTo\` for ${Y} when calling \`${Q}\`.`)}function BH(Q,Y,X){if(uV(X)&&!hV(X))throw Error(`Sender identity fields are only supported for email steps at ${Y} when calling \`${Q}\`.`);HX(Q,Y,X)}function GH(Q,Y,X){if(!Array.isArray(X))return;X.forEach((W,G)=>{if(Y0(W))HX(Q,`${Y}[${G}]`,W)})}function nY(Q,Y,X){if(!Array.isArray(X))return;X.forEach((W,G)=>{if(Y0(W))BH(Q,`${Y}[${G}]`,W)})}function fV(Q){if(GH("update_sequence","emails",Q.emails),GH("update_sequence","steps",Q.steps),Y0(Q.insertSteps))nY("update_sequence","insertSteps.steps",Q.insertSteps.steps);if(!Y0(Q.branch))return;if(Array.isArray(Q.branch.branches))Q.branch.branches.forEach((X,W)=>{if(Y0(X))nY("update_sequence",`branch.branches[${W}].steps`,X.steps)});nY("update_sequence","branch.elseSteps",Q.branch.elseSteps)}function lV(Q){if(Q.fromEmail!==void 0&&Q.senderProfileId!==void 0)throw Error("Provide either `fromEmail` or `senderProfileId` when calling `update_sequence`, not both.");if(Q.replyTo!==void 0&&Q.replyProfileId!==void 0)throw Error("Provide either `replyTo` or `replyProfileId` when calling `update_sequence`, not both.");if(Q.fromName!==void 0&&Q.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `update_sequence`.");if(Q.replyToName!==void 0&&Q.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `update_sequence`.");if(Q.clearEnrollmentFieldPath===!0&&Q.enrollmentFieldPath!==void 0)throw Error("Provide either `enrollmentFieldPath` or `clearEnrollmentFieldPath` when calling `update_sequence`, not both.");if(Q.clearSendingWindow===!0&&Q.sendingWindow!==void 0)throw Error("Provide either `sendingWindow` or `clearSendingWindow` when calling `update_sequence`, not both.");if(Q.clearBccEmails===!0&&Q.bccEmails!==void 0)throw Error("Provide either `bccEmails` or `clearBccEmails` when calling `update_sequence`, not both.");if(Q.branch!==void 0&&Q.insertSteps!==void 0)throw Error("Provide either `branch` or `insertSteps` when calling `update_sequence`, not both.");fV(Q);let Y={...Q};if(delete Y.clearEnrollmentFieldPath,delete Y.clearSendingWindow,delete Y.clearBccEmails,Q.clearEnrollmentFieldPath===!0)Y.enrollmentFieldPath=null;if(Q.clearSendingWindow===!0)Y.sendingWindow=null;if(Q.clearBccEmails===!0)Y.bccEmails=null;return Y}function mV(Q){let Y=Q.type==="sms",X;if(Y){BH("insert_sequence_step","SMS step",Q);let G=w(Q,"text"),$=Array.isArray(Q.blocks)&&Q.blocks.length>0;if(G===void 0&&!$)throw Error("Provide `text` (or `blocks`) when inserting an SMS step with `insert_sequence_step`.");X={type:"sms"};for(let z of["text","blocks","imageUrls","label","name","ineligibleAction","delay","delayMs","waitUntil"])if(Q[z]!==void 0)X[z]=Q[z]}else{w1("insert_sequence_step",Q,{requireContent:!0}),HX("insert_sequence_step","email step",Q),X={subject:R("insert_sequence_step",Q,"subject")};for(let G of["name","previewText","html","blocks","delay","delayMs","waitUntil","senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName"])if(Q[G]!==void 0)X[G]=Q[G]}let W={steps:[X]};if(Q.afterNodeId!==void 0)W.afterNodeId=Q.afterNodeId;return{...Q.confirmStructuralChange!==void 0&&{confirmStructuralChange:Q.confirmStructuralChange},insertSteps:W}}function cV(Q){let Y=w(Q,"subscriberId"),X=Q.fieldValues,W=X===void 0?void 0:Array.isArray(X)?X:void 0;if(X!==void 0&&W===void 0)throw Error("`fieldValues` must be an array when calling `cancel_sequence_enrollments`.");let G=W?.map((J)=>typeof J==="string"?J.trim():"").filter((J)=>J.length>0)??[];if(W?.some((J)=>typeof J!=="string")||W!==void 0&&G.length===0)throw Error("`fieldValues` must contain at least one non-empty string when calling `cancel_sequence_enrollments`.");if(Y!==void 0===G.length>0)throw Error("Provide exactly one target when calling `cancel_sequence_enrollments`: `subscriberId` or `fieldValues`.");let $=w(Q,"fieldPath"),z=w(Q,"reason");return{...Y!==void 0&&{subscriberId:Y},...$!==void 0&&{fieldPath:$},...G.length>0&&{fieldValues:G},...typeof Q.dryRun==="boolean"&&{dryRun:Q.dryRun},...z!==void 0&&{reason:z}}}function pV(Q){w1("create_campaign",Q),bQ("create_campaign",Q);let Y=w(Q,"prompt")!==void 0,X=Q.html!==void 0,W=Q.blocks!==void 0,G=Q.templateId!==void 0;if(Q.prompt!==void 0&&!Y)throw Error("`prompt` cannot be empty when calling `create_campaign`.");if(Y&&(X||W||G))throw Error("Provide either `prompt`, `html`, `blocks`, or `templateId` when calling `create_campaign`, not multiple content sources.");if(!Y&&(Q.style!==void 0||Q.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_campaign`.");if(!Y&&w(Q,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_campaign`.")}function iV(Q){w1("create_template",Q),bQ("create_template",Q);let Y=w(Q,"prompt")!==void 0,X=[Y,Q.html!==void 0,Q.blocks!==void 0].filter(Boolean).length;if(Q.prompt!==void 0&&!Y)throw Error("`prompt` cannot be empty when calling `create_template`.");if(X!==1)throw Error("Provide exactly one of `prompt`, `html`, or `blocks` when calling `create_template`.");if(!Y&&(Q.style!==void 0||Q.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_template`.");if(!Y&&w(Q,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_template`.")}function nV(Q){if(w(Q,"scheduledAt")===void 0)throw Error("`scheduledAt` is required when calling `schedule_campaign`.");if(Q.targetLists!==void 0&&!Y0(Q.targetLists))throw Error("`targetLists` must be an object when calling `schedule_campaign`.");if(Q.sendTimeOptimization!==void 0){if(typeof Q.sendTimeOptimization!=="boolean")throw Error("`sendTimeOptimization` must be a boolean when calling `schedule_campaign`.")}if(Q.spreadOverHours!==void 0){if(typeof Q.spreadOverHours!=="number"||!Number.isInteger(Q.spreadOverHours)||Q.spreadOverHours<1||Q.spreadOverHours>72)throw Error("`spreadOverHours` must be an integer between 1 and 72 when calling `schedule_campaign`.")}if(Q.recurringInterval!==void 0&&Q.recurringInterval!=="weekly"&&Q.recurringInterval!=="monthly")throw Error("`recurringInterval` must be 'weekly' or 'monthly' when calling `schedule_campaign`.")}function rY(Q,Y,X){let W=new Set(["companyId","landingPageId","name","slug","content"]),G=Object.keys(Y).filter(($)=>!W.has($));if(G.length>0)throw Error(`\`${Q}\` accepts only \`name\`, \`slug\`, and \`content\` update fields. Unsupported field${G.length===1?"":"s"}: ${G.map(($)=>`\`${$}\``).join(", ")}.`);if(X.requireUpdate&&Y.name===void 0&&Y.slug===void 0&&Y.content===void 0)throw Error(`Provide at least one of \`name\`, \`slug\`, or \`content\` when calling \`${Q}\`.`);return{...Y.name!==void 0&&{name:Y.name},...Y.slug!==void 0&&{slug:Y.slug},...Y.content!==void 0&&{content:Y.content}}}function rV(Q){let Y=new Set(["companyId","domain","verify"]),X=Object.keys(Q).filter((W)=>!Y.has(W));if(X.length>0)throw Error(`\`update_landing_page_domain_settings\` accepts only \`domain\` and \`verify\`. Unsupported field${X.length===1?"":"s"}: ${X.map((W)=>`\`${W}\``).join(", ")}.`);if(Q.domain===void 0&&Q.verify!==!0)throw Error("Provide `domain` or `verify: true` when calling `update_landing_page_domain_settings`.");return{...Q.domain!==void 0&&{domain:Q.domain},...typeof Q.verify==="boolean"&&{verify:Q.verify}}}function dV(Q){w1("create_transactional_email",Q);let Y=w(Q,"prompt")!==void 0,X=Q.html!==void 0,W=Q.blocks!==void 0;if(Q.prompt!==void 0&&!Y)throw Error("`prompt` cannot be empty when calling `create_transactional_email`.");if(Y&&(X||W))throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`, not multiple content sources.");if(!Y&&(Q.style!==void 0||Q.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_transactional_email`.");if(!Y&&!X&&!W)throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`.");if(!Y&&w(Q,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_transactional_email`.")}var WX={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},$H={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."}},dY={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:{...WX,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:aY,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:eY,delayMs:{type:"number",description:"Delay in milliseconds. Useful for standalone type:'delay' steps."},waitUntil:sY,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 oV(Q){if(!Q||typeof Q!=="object")return null;let Y=Q;if(Y.success!==!1)return null;if(typeof Y.error==="string")return Error(Y.error);if(Y.error&&typeof Y.error==="object"&&typeof Y.error.message==="string")return Error(Y.error.message);if(typeof Y.message==="string")return Error(Y.message);return Error("The tool returned an unsuccessful response.")}function Y0(Q){return typeof Q==="object"&&Q!==null&&!Array.isArray(Q)}function zH(Q){return Q.trim().toLowerCase().replace(/\s+/g,"-")}function tV(Q){let Y=new URLSearchParams;if(typeof Q.query==="string"&&Q.query.trim()!=="")Y.set("query",Q.query.trim());if(Array.isArray(Q.tags)&&Q.tags.length>0)Y.set("tags",Q.tags.filter((X)=>typeof X==="string"&&X.trim()!=="").join(","));if(typeof Q.list==="string"&&Q.list.trim()!=="")Y.set("list",Q.list.trim());if(typeof Q.listId==="string"&&Q.listId.trim()!=="")Y.set("listId",Q.listId.trim());if(typeof Q.listName==="string"&&Q.listName.trim()!=="")Y.set("listName",Q.listName.trim());if(typeof Q.segmentId==="string"&&Q.segmentId.trim()!=="")Y.set("segmentId",Q.segmentId);if(typeof Q.status==="string"&&Q.status.trim()!=="")Y.set("status",Q.status.trim());return Y.set("page",String(Q.page)),Y.set("limit",String(Q.pageSize)),Y}async function aV(Q,Y){let X=typeof Q.limit==="number"&&Number.isFinite(Q.limit)?Math.max(1,Math.trunc(Q.limit)):void 0,W=Math.min(100,Math.max(1,X??100)),G=[],$=1,z=0,J=0,H=0;while(!0){let U=tV({query:Q.query,tags:Q.tags,list:Q.list,listId:Q.listId,listName:Q.listName,segmentId:Q.segmentId,status:Q.status,page:$,pageSize:W}),K=await B("GET",`/api/v1/subscribers?${U.toString()}`,void 0,Y);z=K.pagination?.total??K.subscribers.length,J=K.pagination?.totalPages??1,H+=1,G.push(...K.subscribers??[]);let D=X!==void 0&&G.length>=X,L=K.pagination?$>=K.pagination.totalPages:(K.subscribers??[]).length<W;if(D||L)break;$+=1}let A=X!==void 0?G.slice(0,X):G;return{success:!0,subscribers:A,pagination:{page:1,limit:W,total:z,totalPages:J,fetchedPages:H},returned:A.length,truncated:X!==void 0&&z>0&&A.length<z}}function sV(Q){let Y=typeof Q.email==="string"&&Q.email.trim()!==""?Q.email.trim():void 0,X=typeof Q.externalId==="string"&&Q.externalId.trim()!==""?Q.externalId.trim():void 0;return{...Y?{email:Y}:{},...X?{externalId:X}:{}}}function v1(Q,Y){let X=sV(Y);if(!X.email&&!X.externalId)throw Error(`Provide either \`email\` or \`externalId\` when calling \`${Q}\`.`);return X}function GX(Q,Y){let X=new URLSearchParams;if(Y?.includeMachineEngagement)X.set("includeMachineEngagement","true");let W=X.toString(),G=W?`?${W}`:"";if(Q.email)return`/api/v1/subscribers/${encodeURIComponent(Q.email)}${G}`;return X.set("externalId",String(Q.externalId)),`/api/v1/subscribers/external?${X.toString()}`}function JH(Q){if(Q.email)return`/api/v1/subscribers/${encodeURIComponent(Q.email)}/notes`;let Y=new URLSearchParams;return Y.set("externalId",String(Q.externalId)),`/api/v1/subscribers/external/notes?${Y.toString()}`}async function oY(Q,Y,X){return B("GET",GX(Q,X),void 0,Y)}function w(Q,Y){let X=Q[Y];if(typeof X!=="string")return;let W=X.trim();return W.length>0?W:void 0}function R(Q,Y,X){let W=w(Y,X);if(W===void 0)throw Error(`\`${X}\` is required when calling \`${Q}\`.`);return W}function m0(Q,Y,X,W){let G=w(Y,X);if(G===void 0)return;if(!W.includes(G))throw Error(`\`${X}\` must be one of ${W.join(", ")} when calling \`${Q}\`.`);return G}function tY(Q,Y,X,W){let G=R(Q,Y,X);if(!W.includes(G))throw Error(`\`${X}\` must be one of ${W.join(", ")} when calling \`${Q}\`.`);return G}function x1(Q,Y,X,W,G){let $=Y[X];if($===void 0)return;if(typeof $!=="number"||!Number.isInteger($)||$<W||$>G)throw Error(`\`${X}\` must be an integer between ${W} and ${G} when calling \`${Q}\`.`);return $}function eV(Q,Y){let X=[],W=m0(Q,Y,"eventType",cY);if(W)X.push(W);if(Y.eventTypes!==void 0){if(!Array.isArray(Y.eventTypes))throw Error(`\`eventTypes\` must be an array when calling \`${Q}\`.`);Y.eventTypes.forEach((G,$)=>{if(typeof G!=="string")throw Error(`\`eventTypes\` item ${$+1} must be a string when calling \`${Q}\`.`);let z=G.trim();if(!cY.includes(z))throw Error(`\`eventTypes\` item ${$+1} must be one of ${cY.join(", ")} when calling \`${Q}\`.`);X.push(z)})}return[...new Set(X)]}function HH(Q,Y){let X=new URLSearchParams,W=eV(Q,Y);if(W.length>0)X.set("eventTypes",W.join(","));let G=m0(Q,Y,"period",["1h","24h","7d","30d","90d"]);if(G)X.set("period",G);let $=w(Y,"start");if($)X.set("start",$);let z=w(Y,"end");if(z)X.set("end",z);let J=x1(Q,Y,"page",1,1e6);if(J!==void 0)X.set("page",String(J));let H=x1(Q,Y,"limit",1,500);if(H!==void 0)X.set("limit",String(H));if(Y.includeMachineEngagement===!0)X.set("includeMachineEngagement","true");return X}function AH(Q,Y){if(Y.events===void 0)return;if(!Array.isArray(Y.events))throw Error(`\`events\` must be an array when calling \`${Q}\`.`);let X=Y.events.map((W,G)=>{if(typeof W!=="string"||!PQ.includes(W))throw Error(`\`events\` item ${G+1} must be one of ${PQ.join(", ")} when calling \`${Q}\`.`);return W});if(X.length===0)throw Error(`\`events\` must include at least one event type when calling \`${Q}\`.`);return X}function UH(Q,Y){if(!Array.isArray(Y.emails))throw Error(`\`emails\` must be an array when calling \`${Q}\`.`);let X=[];if(Y.emails.forEach((W,G)=>{if(typeof W!=="string")throw Error(`\`emails\` item ${G+1} must be a string when calling \`${Q}\`.`);let $=W.trim();if($.length>0)X.push($)}),X.length===0)throw Error(`\`emails\` must include at least one email address when calling \`${Q}\`.`);if(X.length>a5)throw Error(`\`emails\` must include no more than ${a5} email addresses when calling \`${Q}\`. Split larger batches into multiple calls.`);return X}function KH(Q,Y,X,W){let G=Y[X];if(G===void 0)return;if(!Array.isArray(G))throw Error(`\`${X}\` must be an array when calling \`${Q}\`.`);let $=[];if(G.forEach((z,J)=>{if(typeof z!=="string")throw Error(`\`${X}\` item ${J+1} must be a string when calling \`${Q}\`.`);let H=z.trim();if(H.length>0)$.push(H)}),$.length===0)throw Error(`\`${X}\` must include at least one ${W} when calling \`${Q}\`.`);return $}function QZ(Q){let X=KH("enroll_subscribers_in_sequence",Q,"emails","email address"),W=KH("enroll_subscribers_in_sequence",Q,"subscriberIds","subscriber ID"),G=(X?.length??0)+(W?.length??0);if(G===0)throw Error("Provide `emails` or `subscriberIds` when calling `enroll_subscribers_in_sequence`.");if(G>s5)throw Error(`\`emails\` and \`subscriberIds\` must include no more than ${s5} total targets when calling \`enroll_subscribers_in_sequence\`. Split larger batches into multiple calls.`);let $=w(Q,"targetNodeId");return{...X!==void 0&&{emails:X},...W!==void 0&&{subscriberIds:W},...$!==void 0&&{targetNodeId:$}}}var YZ={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 XZ(Q){let Y=Q.split(".").pop()?.toLowerCase()??"";return YZ[Y]??null}var WZ=104857600;async function GZ(Q,Y){if(!VX())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 X=XZ(Q);if(!X)throw Error("Unsupported file type. Use PDF, ePub, ZIP, image, audio, video, or text files.");let W=BV(Q).size;if(W>WZ)throw Error(`File is too large (${Math.round(W/1048576)}MB). Delivery files must be 100MB or smaller.`);let G=DV(Q),$=await B("POST","/api/v1/products/delivery/upload-url",{filename:LV(Q),contentType:X,fileSizeBytes:W},Y),z=await fetch($.uploadUrl,{method:"PUT",headers:{"Content-Type":X},body:G});if(!z.ok)throw Error(`File upload failed (${z.status})`);return{url:$.publicUrl,fileName:$.fileName,fileSizeBytes:W,mimeType:X}}async function AX(Q){let Y=w(Q,"companyId");if(Y)return Y;let X=b1();if(X)return X;try{return(await B("GET","/api/v1/account")).currentCompanyId??void 0}catch{return}}async function $Z(Q,Y){let X=await AX(Y);if(!X)throw Error(`A company is required when calling \`${Q}\`. Call \`get_account\`, then \`select_company\`, or pass \`companyId\` explicitly.`);return X}function Y4(Q,Y){if(!Y0(Q)||!Y)return Q;return{...Q,url:Y}}function LH(Q,Y){if(!Y0(Q))return Q;return{...Q,...Y.campaign!==void 0&&{url:Y.campaign},...Y.campaignPreview!==void 0&&{previewUrl:Y.campaignPreview}}}function e4(Q,Y,X){if(!Array.isArray(Q)||!Y)return Q;return Q.map((W)=>{if(!Y0(W))return W;let G=w(W,"id");if(!G)return W;let $=Z1({companyId:Y,...X==="campaign"&&{campaignId:G},...X==="landingPage"&&{landingPageId:G},...X==="sequence"&&{sequenceId:G},...X==="template"&&{emailId:G},...X==="transactional"&&{transactionalId:G}});if(X==="campaign")return LH(W,$.urls);let z=X==="sequence"?$.urls.sequence:X==="landingPage"?$.urls.landingPage:X==="template"?$.urls.email:$.urls.transactionalEmail;return Y4(W,z)})}function zZ(Q){if(!Array.isArray(Q))return Q;return Q.map((Y)=>{if(!Y0(Y))return Y;let X=w(Y,"id");if(!X)return Y;let W=Z1({companyId:X});return{...Y,url:W.urls.dashboard,settingsUrl:W.urls.settings}})}var FH=new Set(["get_account","select_company","create_company","get_company","update_company","list_campaigns","get_campaign","get_email_send","create_campaign","update_campaign","schedule_campaign","send_test_email","cancel_campaign","pause_campaign","resume_campaign","duplicate_campaign","resend_campaign_to_non_openers","list_landing_pages","get_landing_page","create_landing_page","update_landing_page","publish_landing_page","unpublish_landing_page","delete_landing_page","list_sequences","get_sequence","create_sequence","update_sequence","insert_sequence_step","enable_sequence","disable_sequence","pause_sequence_enrollments","resume_sequence_enrollments","cancel_sequence_enrollments","list_ab_tests","get_ab_test","get_ab_test_stats","update_ab_test_variant","list_templates","get_template","create_template","update_template","list_transactional_emails","get_transactional_email","create_transactional_email","update_transactional_email"]);async function JZ(Q,Y,X){if(!Y0(X)||!FH.has(Q))return X;let W=Y0(X.company)?X.company:void 0,$=w(X,"selectedCompanyId")??w(X,"currentCompanyId")??w(X,"companyId")??(W?w(W,"id"):void 0)??(W?w(W,"companyId"):void 0)??await AX(Y);if(!$)return X;let z=Y0(X.campaign)?X.campaign:void 0,J=Y0(X.sequence)?X.sequence:void 0,H=Y0(X.landingPage)?X.landingPage:void 0,A=Y0(X.template)?X.template:void 0,U=Y0(X.transactional)&&!Array.isArray(X.transactional)?X.transactional:void 0,K={companyId:$,campaignId:w(Y,"campaignId")??w(X,"campaignId")??(z?w(z,"id"):void 0),landingPageId:w(Y,"landingPageId")??w(X,"landingPageId")??(H?w(H,"id"):void 0),sequenceId:w(Y,"sequenceId")??w(X,"sequenceId")??(J?w(J,"id"):void 0),emailId:w(X,"templateId")??(A?w(A,"id"):void 0)??(U?w(U,"emailId"):void 0)??w(Y,"templateId"),transactionalId:w(Y,"transactionalId")??(U?w(U,"id"):void 0)??w(Y,"idOrSlug"),emailSendId:w(Y,"emailSendId")??w(X,"emailSendId")??(Y0(X.emailSend)?w(X.emailSend,"id"):void 0),status:w(Y,"status")},D=Z1(K),L=W?Z1({companyId:$}):void 0;return{...X,...Array.isArray(X.companies)&&{companies:zZ(X.companies)},...Array.isArray(X.campaigns)&&{campaigns:e4(X.campaigns,$,"campaign")},...Array.isArray(X.landingPages)&&{landingPages:e4(X.landingPages,$,"landingPage")},...Array.isArray(X.sequences)&&{sequences:e4(X.sequences,$,"sequence")},...Array.isArray(X.templates)&&{templates:e4(X.templates,$,"template")},...Array.isArray(X.transactional)&&{transactional:e4(X.transactional,$,"transactional")},...W&&L!==void 0&&{company:{...W,url:L.urls.dashboard,settingsUrl:L.urls.settings}},...z&&D.urls.campaign!==void 0&&{campaign:LH(z,D.urls)},...J&&D.urls.sequence!==void 0&&{sequence:Y4(J,D.urls.sequence)},...H&&D.urls.landingPage!==void 0&&{landingPage:Y4(H,D.urls.landingPage)},...A&&D.urls.email!==void 0&&{template:Y4(A,D.urls.email)},...U&&D.urls.transactionalEmail!==void 0&&{transactional:Y4(U,D.urls.transactionalEmail)},...Y0(X.emailSend)&&D.urls.emailSend!==void 0&&{emailSend:Y4(X.emailSend,D.urls.emailSend)},appUrls:D.urls}}var HZ={type:"boolean",description:"Whether the Sequenzy operation succeeded."},AZ={type:"string",description:"Human-readable status, confirmation, or next-step message."},UZ={type:"string",description:"Additional context about the result."};function G0(Q){return{type:"object",description:Q,additionalProperties:!0}}function KZ(Q){return{type:"array",description:Q,items:G0("One item in the returned collection.")}}function E(Q){return{type:"string",description:Q}}function b0(Q){return{type:"number",description:Q}}function d0(Q){return{type:"boolean",description:Q}}function V(Q){return G0(`The ${Q} record returned by Sequenzy.`)}function p(Q){return KZ(`List of ${Q} records returned by Sequenzy.`)}var DZ={appUrls:G0("Dashboard URLs for relevant Sequenzy resources."),url:E("Primary dashboard URL for this result."),settingsUrl:E("Company settings URL when available.")},BZ={success:HZ,message:AZ,note:UZ,items:{type:"array",description:"Fallback array wrapper used only when a tool returns a bare array.",items:G0("One returned item.")},value:G0("Fallback object wrapper used only when a tool returns a non-object value.")},LZ={get_account:{account:V("account"),companies:p("company"),apiKeyPermissions:G0("Current API key preset and scopes, whether common marketing work is discoverable, any missing marketing read scopes, and the API Keys management URL."),currentCompanyId:E("Company ID selected by the authenticated API key, when available."),selectedCompanyId:E("Company ID selected locally for subsequent MCP calls, when available.")},select_company:{companyId:E("Selected company ID."),companyName:E("Selected company name.")},get_app_urls:{dashboard:E("Company dashboard URL."),settings:E("Company settings URL."),campaign:E("Campaign editor URL."),landingPage:E("Landing page editor URL."),sequence:E("Sequence editor URL."),email:E("Email editor URL."),transactionalEmail:E("Transactional email URL."),emailSend:E("Sent email detail URL."),domain:E("Sending domain settings URL."),urls:G0("All generated URLs keyed by resource type.")},create_company:{company:V("company"),autoSelected:d0("Whether the new company was selected for subsequent MCP calls.")},update_company:{company:V("company")},get_company:{company:V("company")},get_sync_rules:{syncRules:{type:"array",description:"Effective sync rules for the company.",items:G0("One sync rule.")},isDefault:d0("Whether the company still uses the platform default rules.")},update_sync_rules:{syncRules:{type:"array",description:"Effective sync rules after the update.",items:G0("One sync rule.")},isDefault:d0("Whether the company now uses the platform default rules.")},get_shopify_automation_settings:{browseAbandonment:G0("Effective browse-abandonment settings (defaults applied)."),priceDrop:G0("Effective price-drop settings (defaults applied)."),shopDomain:E("Connected Shopify store domain.")},update_shopify_automation_settings:{browseAbandonment:G0("Effective browse-abandonment settings after the update."),priceDrop:G0("Effective price-drop settings after the update."),shopDomain:E("Connected Shopify store domain.")},create_api_key:{apiKey:G0("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:E("Newly created API key if the API response uses the short key field.")},list_websites:{websites:p("sender website")},add_website:{website:V("Sending domain with the SPF, DKIM, MAIL FROM, and inbound DNS records required for setup.")},add_sending_domain:{website:V("Sending domain with the SPF, DKIM, MAIL FROM, and inbound DNS records required for setup.")},check_website:{website:V("sender website"),ready:d0("Whether the sender website is ready."),status:E("Current processing or verification status.")},verify_sending_domain:{website:V("Sending domain with current aggregate, SPF, DKIM, and MAIL FROM verification details."),verified:d0("Whether the sending domain passed the fresh verification check."),message:E("Verification result summary.")},get_integration_guide:{guide:V("integration guide"),code:E("Generated integration code or example."),steps:{type:"array",description:"Setup steps for the requested integration.",items:G0("One setup step.")}},add_subscriber:{subscriber:V("subscriber")},update_subscriber:{subscriber:V("subscriber")},remove_subscriber:{subscriber:V("subscriber"),hardDeleted:d0("Whether the subscriber was permanently deleted.")},get_subscriber:{subscriber:V("subscriber")},list_subscriber_notes:{notes:p("subscriber note")},add_subscriber_note:{note:V("subscriber note")},delete_subscriber_note:{id:E("Deleted subscriber note ID."),deleted:d0("Whether the subscriber note was deleted.")},search_subscribers:{subscribers:p("subscriber"),pagination:G0("Pagination metadata."),returned:b0("Number of subscribers returned."),truncated:d0("Whether the result was truncated by the requested limit.")},list_products:{products:p("product")},upsert_products:{products:p("product"),created:b0("Number of products created."),updated:b0("Number of products updated.")},delete_product:{productId:E("Deleted product ID.")},attach_product_file:{product:V("product"),delivery:V("digital delivery file")},remove_product_file:{product:V("product")},sync_products:{job:V("product sync job"),jobId:E("Queued product sync job ID.")},list_tags:{tags:p("tag")},create_tag:{tag:V("tag")},update_tag:{tag:V("tag")},delete_tag:{tagId:E("Deleted tag ID.")},list_lists:{lists:p("list")},create_list:{list:V("list")},update_list:{list:V("list")},delete_list:{listId:E("Deleted list ID.")},add_subscribers_to_list:{list:V("list"),added:b0("Number of subscribers added to the list."),skipped:b0("Number of subscribers skipped.")},remove_subscribers_from_list:{list:V("list"),removed:b0("Number of subscribers removed from the list."),skipped:b0("Number of subscribers skipped.")},list_segments:{segments:p("segment")},create_segment:{segment:V("segment")},update_segment:{segment:V("segment")},delete_segment:{segmentId:E("Deleted segment ID.")},get_segment_count:{count:b0("Number of subscribers matching the segment."),segmentId:E("Segment ID that was counted.")},list_audience_syncs:{audienceSyncs:p("audience sync")},list_ad_accounts:{adAccounts:p("ad account")},create_audience_sync:{audienceSync:V("audience sync")},update_audience_sync:{audienceSync:V("audience sync")},delete_audience_sync:{audienceSyncId:E("Deleted audience sync ID.")},sync_audience_now:{audienceSync:V("audience sync"),job:V("audience sync job"),jobId:E("Queued audience sync job ID.")},list_templates:{templates:p("email template")},get_template:{template:V("email template")},create_template:{template:V("email template")},update_template:{template:V("email template")},delete_template:{templateId:E("Deleted template ID.")},list_ab_tests:{abTests:p("A/B test")},get_ab_test:{abTest:V("A/B test")},get_ab_test_stats:{abTest:V("A/B test"),stats:V("A/B test statistics")},restart_ab_test:{abTest:V("A/B test")},update_ab_test_variant:{abTest:V("A/B test"),variant:V("A/B test variant")},create_ab_test:{abTest:V("A/B test")},add_ab_test_variant:{abTest:V("A/B test"),variant:V("A/B test variant")},delete_ab_test_variant:{abTest:V("A/B test"),variantId:E("Deleted A/B test variant ID.")},delete_ab_test:{abTestId:E("Deleted A/B test ID.")},list_campaigns:{campaigns:p("campaign")},get_campaign:{campaign:V("campaign")},get_email_send:{emailSend:V("email send")},create_campaign:{campaign:V("campaign")},update_campaign:{campaign:V("campaign")},schedule_campaign:{campaign:V("campaign"),scheduledAt:E("Scheduled send timestamp.")},send_test_email:{emailSend:V("test email send"),recipient:E("Test email recipient.")},send_test_sms:{smsSendId:E("Created test SMS send ID."),toPhone:E("Normalized E.164 destination phone.")},cancel_campaign:{campaign:V("campaign")},pause_campaign:{campaign:V("campaign")},resume_campaign:{campaign:V("campaign")},delete_campaign:{campaignId:E("Deleted campaign ID.")},duplicate_campaign:{campaign:V("duplicated campaign")},resend_campaign_to_non_openers:{campaign:V("non-opener resend draft campaign"),estimatedNonOpenerCount:b0("Estimated number of subscribers who haven't opened the original campaign.")},list_landing_pages:{landingPages:p("landing page")},get_landing_page:{landingPage:V("landing page")},create_landing_page:{landingPage:V("landing page")},update_landing_page:{landingPage:V("landing page")},delete_landing_page:{landingPageId:E("Deleted landing page ID.")},publish_landing_page:{landingPage:V("landing page")},unpublish_landing_page:{landingPage:V("landing page")},connect_landing_page_domain:{landingPage:V("landing page"),domain:E("Connected landing page domain.")},update_landing_page_domain_settings:{landingPage:V("landing page"),domain:E("Landing page domain.")},list_sequences:{sequences:p("sequence")},get_sequence:{sequence:V("sequence")},create_sequence:{sequence:V("sequence")},update_sequence:{sequence:V("sequence")},insert_sequence_step:{sequence:V("sequence"),insertedNodeIds:{type:"array",description:"Node IDs created for the inserted step, including any delay node.",items:E("Inserted automation node ID.")},insertedEmailIds:{type:"array",description:"Email template IDs created for the inserted step.",items:E("Inserted email template ID.")},insertedEmailCount:b0("Number of email steps inserted.")},enable_sequence:{sequence:V("sequence")},disable_sequence:{sequence:V("sequence")},pause_sequence_enrollments:{sequenceId:E("Sequence ID."),enrollmentPaused:d0("Whether new sequence enrollments are paused.")},resume_sequence_enrollments:{sequenceId:E("Sequence ID."),enrollmentPaused:d0("Whether new sequence enrollments are paused.")},enroll_subscribers_in_sequence:{sequence:V("sequence"),enrollments:p("sequence enrollment"),enrolled:b0("Number of subscribers enrolled."),skipped:b0("Number of subscribers skipped.")},cancel_sequence_enrollments:{sequence:V("sequence"),cancelled:b0("Number of enrollments cancelled."),skipped:b0("Number of enrollments skipped.")},delete_sequence:{sequenceId:E("Deleted sequence ID.")},list_transactional_emails:{transactional:p("transactional email")},get_transactional_email:{transactional:V("transactional email")},create_transactional_email:{transactional:V("transactional email")},update_transactional_email:{transactional:V("transactional email")},send_email:{emailSend:V("transactional email send"),transactional:V("transactional email")},get_stats:{stats:V("account or company statistics")},get_campaign_stats:{campaign:V("campaign"),stats:V("campaign statistics")},get_sequence_stats:{sequence:V("sequence"),stats:V("sequence statistics")},list_campaign_events:{events:p("campaign email event"),pagination:G0("Pagination metadata.")},list_sequence_events:{events:p("sequence email event"),pagination:G0("Pagination metadata.")},get_subscriber_activity:{activity:p("subscriber activity event"),subscribers:p("subscriber"),pagination:G0("Pagination metadata.")},list_team_members:{members:p("team member"),invitations:p("team invitation")},invite_team_member:{invitation:V("team invitation")},cancel_team_invitation:{invitationId:E("Cancelled invitation ID.")},list_conversations:{conversations:p("inbox conversation"),pagination:G0("Pagination metadata.")},get_conversation:{conversation:V("inbox conversation"),messages:p("conversation message")},reply_to_conversation:{conversation:V("inbox conversation"),message:V("conversation message")},update_conversation_status:{conversation:V("inbox conversation")},mark_conversation_read:{conversation:V("inbox conversation")},list_webhooks:{webhooks:p("outbound webhook")},create_webhook:{webhook:V("outbound webhook")},update_webhook:{webhook:V("outbound webhook")},delete_webhook:{webhookId:E("Deleted outbound webhook ID.")},test_webhook:{webhook:V("outbound webhook"),delivery:V("test webhook delivery")},list_webhook_deliveries:{deliveries:p("webhook delivery")},replay_webhook_delivery:{delivery:V("webhook delivery"),job:V("webhook replay job")},generate_email:{email:V("generated email"),html:E("Generated HTML email body."),blocks:{type:"array",description:"Generated Sequenzy email blocks, wrapped with company branding (logo + footer) unless applyBranding was false.",items:G0("One generated email block.")},subject:E("Generated subject line."),previewText:E("Generated inbox preview text.")},generate_sequence:{sequence:V("generated sequence"),steps:p("generated sequence step")},generate_subject_lines:{subjectLines:{type:"array",description:"Generated subject line variants.",items:E("One generated subject line.")},variants:p("generated subject line variant")},generate_sms:{prompt:E("The prompt the messages were generated for."),messages:{type:"array",description:"Generated SMS message variants with encoding and segment counts.",items:G0("One generated SMS message.")}},get_sms_settings:{sms:G0("SMS add-on status: enabled, planEligible, creditsBalance, brandPrefix, numbers, readyToSend (paid plan or credits plus an active number).")},submit_feedback:{}};function FZ(Q){let Y=LZ[Q];if(Y===void 0)throw Error(`MCP tool "${Q}" must define outputSchema properties.`);return{type:"object",description:`Structured content returned by the \`${Q}\` MCP tool.`,properties:{...BZ,...Y,...FH.has(Q)?DZ:{}},additionalProperties:!0}}function qZ(Q){return{...Q,outputSchema:FZ(Q.name)}}function OZ(Q){if(Y0(Q))return Q;if(Array.isArray(Q))return{items:Q};return{value:Q}}var MZ=[{name:"get_account",description:`Get current account information including available companies, the current API key's permission scopes, and the API Keys management URL. Call this after a missing-scope error to inspect access and find the replacement-key settings. IMPORTANT: If you have access to multiple companies, you MUST either:
30
30
  1. Call select_company first to choose which company to work with, OR
31
31
  2. Pass companyId explicitly in each tool call
32
32
 
@@ -48,7 +48,7 @@ Use cases:
48
48
  - 'event_tracking': Tracking CUSTOM events only (not payment events - those come from the integration)
49
49
  - 'ecommerce': Connecting a custom e-commerce platform via the Commerce API (sync products, push orders/checkouts, power abandoned cart + back-in-stock automations)
50
50
 
51
- Before implementing, use create_api_key to generate an API key and save it to .env as SEQUENZY_API_KEY.`,inputSchema:{type:"object",properties:{framework:{type:"string",description:"Framework/language (nextjs, express, python, etc.)"},use_case:{type:"string",description:"Use case: 'transactional' (sending emails), 'subscribe_form' (adding subscribers), 'event_tracking' (tracking CUSTOM events only - payment events should come from Stripe/Polar/etc integration), 'ecommerce' (connecting a custom e-commerce platform via the Commerce API)"}}}},{name:"add_subscriber",description:"Add a new subscriber to your list",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to add subscriber to. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address"},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide this with email when creating, or instead of email for an existing subscriber."},attributes:{type:"object",description:"Custom attributes (name, plan, etc.)"},tags:{type:"array",items:{type:"string"},description:"Tags to apply to the subscriber"},listIds:{type:"array",items:{type:"string"},description:"List IDs to add subscriber to"},status:{type:"string",description:"Initial subscriber status: active, unsubscribed, or bounced. Defaults to active."},optInMode:{type:"string",description:"Consent mode: confirmed creates active immediately when consent is verified, double_opt_in sends a confirmation email before activation, and default obeys company double opt-in settings."}},required:[]}},{name:"update_subscriber",description:"Update an existing subscriber's attributes or tags",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},attributes:{type:"object",description:"Attributes to update"},addTags:{type:"array",items:{type:"string"},description:"Tags to add"},removeTags:{type:"array",items:{type:"string"},description:"Tags to remove"}},required:[]}},{name:"remove_subscriber",description:"Unsubscribe or delete a subscriber",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},hardDelete:{type:"boolean",description:"If true, permanently deletes. If false, just unsubscribes."}},required:[]}},{name:"get_subscriber",description:"Get the full subscriber profile, including tags, notes, list memberships, sequence enrollments, email stats, and recent activity",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},includeMachineEngagement:N1},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."}}}},{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."}}}},{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:[...wQ],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:[...wQ],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:s5,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:{...e5,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:s5,minItems:1,description:"Replacement segment filters. Same shape and validation rules as create_segment. Mutually exclusive with `root`."},root:{...e5,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"]}},{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"]}},{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:s4,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:s4,items:{type:"object"}},labels:{type:"array",description:"Replacement label names. Send an empty array to clear labels. Missing labels are created automatically.",items:{type:"string"}}},required:["templateId"],additionalProperties:!1}},{name:"delete_template",description:"Delete a template",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID"}},required:["templateId"]}},{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:N1},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:`${Q4} 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:Q4,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:Q4,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"]}},{name:"list_campaigns",description:"List all campaigns",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list campaigns for. If not provided, uses the currently selected company."},status:{type:"string",description:"Filter by status (draft, scheduled, sent)"},label:{type:"string",description:"Optional label name filter. Only campaigns assigned this label are returned."}}}},{name:"get_campaign",description:"Get campaign details and stats",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"}},required:["campaignId"]}},{name:"get_email_send",description:"Get a sent email by emailSendId, including the stored HTML body when available and the ClickHouse event timeline. If the short-lived email send row has been cleaned up, returns the retained ClickHouse events and a sparse summary.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},emailSendId:{type:"string",description:"Email send ID to inspect."}},required:["emailSendId"]}},{name:"create_campaign",description:"Create a new campaign. Omit all content fields to create an empty draft. For net-new natural-language content use `prompt`; do not author HTML or blocks. `blocks` are finished caller-supplied Sequenzy content and `html` is preserved/imported markup. Defaults to draft; status 'sent' only archives an already-sent campaign.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the campaign in. If not provided, uses the currently selected company."},name:{type:"string",description:"Campaign name"},subject:{type:"string",description:"Email subject line. Optional when `prompt` is provided because the generated subject will be used."},previewText:{type:["string","null"],description:"Email preview text. Optional when `prompt` is provided because the generated preview text will be used."},trackingCode:{type:"string",description:"Optional campaign tracking code for UTM templates. Use only when explicitly requested."},status:{type:"string",description:"Initial status: draft or sent. Defaults to draft. Use sent only for imported/already-sent campaigns; it does not send email or create delivery history."},sentAt:{type:"string",description:"ISO date-time for an imported/already-sent campaign. Only valid when status is sent; defaults to now if omitted."},html:{type:"string",description:"Email HTML content. Mutually exclusive with `blocks`. Use this for imported provider campaigns; Sequenzy stores it as one raw HTML block to preserve the design."},blocks:{type:"array",description:s4,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:s4,items:{type:"object"}},replyTo:{type:"string",description:"Set reply-to using an existing reply profile email address for this company."},replyProfileId:{type:"string",description:"Set reply-to using a reply profile ID for this company."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo."},fromEmail:{type:"string",description:"Set this campaign's From address. Its domain must be configured and verified."},fromName:{type:"string",description:"Display name for a newly created sender profile. Requires fromEmail."},senderProfileId:{type:"string",description:"Set an existing sender profile. Mutually exclusive with fromEmail."},campaignData:{type:"object",description:"Set campaign-scoped JSON data for repeat blocks and personalization."},computedLists:{type:"array",description:"Set computed list definitions derived from campaignData at send time.",items:{type:"object"}},labels:{type:"array",description:"Replacement label names. Send an empty array to clear labels. Missing labels are created automatically.",items:{type:"string"}}},required:["campaignId"],additionalProperties:!1}},{name:"schedule_campaign",description:"Schedule a draft or already scheduled campaign. Returns dashboard edit and preview URLs.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"},scheduledAt:{type:"string",description:"Future ISO 8601 timestamp for the send, for example 2026-06-01T14:00:00Z."},targetLists:{type:"object",description:"Optional campaign targeting object. Omit to use saved targeting or all active subscribers. Examples: {type:'all'}, {type:'lists', listIds:['list_123']}, {type:'segment', segmentId:'seg_123'}, {type:'filtered', filters:[...], filterJoinOperator:'and'}, or {type:'rules', include:[{type:'lists', listIds:['list_123']}], exclude:[{type:'segments', segmentIds:['seg_123']}]}. Rules audiences require at least one include rule.",additionalProperties:!0},sendTimeOptimization:{type:"boolean",description:"Whether to use send-time optimization."},spreadOverHours:{type:"number",description:"Spread delivery over an integer number of hours from 1 to 72. When set, spread delivery takes precedence over send-time optimization."},recurringInterval:{type:"string",enum:["weekly","monthly"],description:"Repeat this campaign on a cadence starting at scheduledAt. The campaign becomes a recurring template: each run is duplicated and sent automatically, re-evaluating audience membership every time. Omit for a one-shot send; scheduling again without it stops the recurrence."}},required:["campaignId","scheduledAt"],additionalProperties:!1}},{name:"send_test_email",description:"Send a test email to a single address",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to test"},to:{type:"string",description:"Email address to send test to"}},required:["campaignId","to"]}},{name:"cancel_campaign",description:"Cancel a campaign. Stops scheduled and sending campaigns (also works for paused and approval-pending ones). Remaining emails will not be sent and the campaign cannot be restarted - this cannot be undone.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to cancel."}},required:["campaignId"]}},{name:"pause_campaign",description:"Pause a campaign that is currently sending. Only campaigns in sending status can be paused. Use resume_campaign to continue delivery later.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to pause."}},required:["campaignId"]}},{name:"resume_campaign",description:"Resume a paused campaign. Only campaigns in paused status can be resumed. Optionally spread the remaining delivery over a number of hours.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to resume."},spreadOverHours:{type:"number",description:"Spread the remaining delivery over an integer number of hours from 1 to 72."}},required:["campaignId"]}},{name:"delete_campaign",description:"Permanently delete a campaign. This cannot be undone. Sending, scheduled, or paused campaigns must be cancelled with cancel_campaign first.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to delete."}},required:["campaignId"]}},{name:"duplicate_campaign",description:"Duplicate a campaign as a new draft. mode 'campaign' (default) copies the campaign and its email, 'ab_test' also duplicates the campaign's A/B test with all variants, and 'variant' copies a single variant's content as the new campaign email (requires variantId).",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to duplicate."},mode:{type:"string",enum:["campaign","ab_test","variant"],description:"Duplication mode. Defaults to campaign."},variantId:{type:"string",description:"A/B test variant ID whose content becomes the new campaign email. Required when mode is variant."}},required:["campaignId"]}},{name:"resend_campaign_to_non_openers",description:"Create a draft that resends a sent campaign to everyone in the same audience who didn't open it. Copies the campaign email and reuses the original audience with a 'didn't open this campaign' rule added. Only available 6 hours after the campaign finishes sending. The draft must be scheduled or sent separately. Returns the new draft and an estimate of how many subscribers haven't opened the original.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"ID of the sent campaign to resend to non-openers."}},required:["campaignId"]}},{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:AV},content:{type:"object",description:NQ,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:NQ,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:NQ,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:NQ,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}},{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 plus editable step content. The response includes sequence.emails with each step's nodeId, linked emailId, subject, previewText, and blocks.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"],additionalProperties:!1}},{name:"create_sequence",description:`Create a new email sequence. For net-new natural-language sequence content, provide goal and emailCount so Sequenzy generates it. Use explicit steps only for finished caller-supplied content, exact workflows, or migrations. Explicit steps can include email content, native SMS steps (type: 'sms' with 'text'; check get_sms_settings first and generate copy with generate_sms), and create_discount actions that dynamically create a provider discount/code when each subscriber reaches the step; emails after a discount action can use merge tags such as {{discount.code}} and {{discount.percentOff}}. For AI-generated sequences, the tool polls until emails are generated (typically 30-60 seconds).
51
+ Before implementing, use create_api_key to generate an API key and save it to .env as SEQUENZY_API_KEY.`,inputSchema:{type:"object",properties:{framework:{type:"string",description:"Framework/language (nextjs, express, python, etc.)"},use_case:{type:"string",description:"Use case: 'transactional' (sending emails), 'subscribe_form' (adding subscribers), 'event_tracking' (tracking CUSTOM events only - payment events should come from Stripe/Polar/etc integration), 'ecommerce' (connecting a custom e-commerce platform via the Commerce API)"}}}},{name:"add_subscriber",description:"Add a new subscriber to your list",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to add subscriber to. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address"},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide this with email when creating, or instead of email for an existing subscriber."},attributes:{type:"object",description:"Custom attributes (name, plan, etc.)"},tags:{type:"array",items:{type:"string"},description:"Tags to apply to the subscriber"},listIds:{type:"array",items:{type:"string"},description:"List IDs to add subscriber to"},status:{type:"string",description:"Initial subscriber status: active, unsubscribed, or bounced. Defaults to active."},optInMode:{type:"string",description:"Consent mode: confirmed creates active immediately when consent is verified, double_opt_in sends a confirmation email before activation, and default obeys company double opt-in settings."}},required:[]}},{name:"update_subscriber",description:"Update an existing subscriber's attributes or tags",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},attributes:{type:"object",description:"Attributes to update"},addTags:{type:"array",items:{type:"string"},description:"Tags to add"},removeTags:{type:"array",items:{type:"string"},description:"Tags to remove"}},required:[]}},{name:"remove_subscriber",description:"Unsubscribe or delete a subscriber",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},hardDelete:{type:"boolean",description:"If true, permanently deletes. If false, just unsubscribes."}},required:[]}},{name:"get_subscriber",description:"Get the full subscriber profile, including tags, notes, list memberships, sequence enrollments, email stats, and recent activity",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},includeMachineEngagement:N1},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."}}}},{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."}}}},{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:[...wQ],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:[...wQ],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:QH,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:{...YH,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:QH,minItems:1,description:"Replacement segment filters. Same shape and validation rules as create_segment. Mutually exclusive with `root`."},root:{...YH,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"]}},{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"]}},{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:s4,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:s4,items:{type:"object"}},labels:{type:"array",description:"Replacement label names. Send an empty array to clear labels. Missing labels are created automatically.",items:{type:"string"}}},required:["templateId"],additionalProperties:!1}},{name:"delete_template",description:"Delete a template",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID"}},required:["templateId"]}},{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:N1},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:`${Q4} 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:Q4,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:Q4,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"]}},{name:"list_campaigns",description:"List all campaigns",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list campaigns for. If not provided, uses the currently selected company."},status:{type:"string",description:"Filter by status (draft, scheduled, sent)"},label:{type:"string",description:"Optional label name filter. Only campaigns assigned this label are returned."}}}},{name:"get_campaign",description:"Get campaign details and stats",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"}},required:["campaignId"]}},{name:"get_email_send",description:"Get a sent email by emailSendId, including the stored HTML body when available and the ClickHouse event timeline. If the short-lived email send row has been cleaned up, returns the retained ClickHouse events and a sparse summary.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},emailSendId:{type:"string",description:"Email send ID to inspect."}},required:["emailSendId"]}},{name:"create_campaign",description:"Create a new campaign. Omit all content fields to create an empty draft. For net-new natural-language content use `prompt`; do not author HTML or blocks. `blocks` are finished caller-supplied Sequenzy content and `html` is preserved/imported markup. Defaults to draft; status 'sent' only archives an already-sent campaign.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the campaign in. If not provided, uses the currently selected company."},name:{type:"string",description:"Campaign name"},subject:{type:"string",description:"Email subject line. Optional when `prompt` is provided because the generated subject will be used."},previewText:{type:["string","null"],description:"Email preview text. Optional when `prompt` is provided because the generated preview text will be used."},trackingCode:{type:"string",description:"Optional campaign tracking code for UTM templates. Use only when explicitly requested."},status:{type:"string",description:"Initial status: draft or sent. Defaults to draft. Use sent only for imported/already-sent campaigns; it does not send email or create delivery history."},sentAt:{type:"string",description:"ISO date-time for an imported/already-sent campaign. Only valid when status is sent; defaults to now if omitted."},html:{type:"string",description:"Email HTML content. Mutually exclusive with `blocks`. Use this for imported provider campaigns; Sequenzy stores it as one raw HTML block to preserve the design."},blocks:{type:"array",description:s4,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:s4,items:{type:"object"}},replyTo:{type:"string",description:"Set reply-to using an existing reply profile email address for this company."},replyProfileId:{type:"string",description:"Set reply-to using a reply profile ID for this company."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo."},fromEmail:{type:"string",description:"Set this campaign's From address. Its domain must be configured and verified."},fromName:{type:"string",description:"Display name for a newly created sender profile. Requires fromEmail."},senderProfileId:{type:"string",description:"Set an existing sender profile. Mutually exclusive with fromEmail."},campaignData:{type:"object",description:"Set campaign-scoped JSON data for repeat blocks and personalization."},computedLists:{type:"array",description:"Set computed list definitions derived from campaignData at send time.",items:{type:"object"}},labels:{type:"array",description:"Replacement label names. Send an empty array to clear labels. Missing labels are created automatically.",items:{type:"string"}}},required:["campaignId"],additionalProperties:!1}},{name:"schedule_campaign",description:"Schedule a draft or already scheduled campaign. Returns dashboard edit and preview URLs.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"},scheduledAt:{type:"string",description:"Future ISO 8601 timestamp for the send, for example 2026-06-01T14:00:00Z."},targetLists:{type:"object",description:"Optional campaign targeting object. Omit to use saved targeting or all active subscribers. Examples: {type:'all'}, {type:'lists', listIds:['list_123']}, {type:'segment', segmentId:'seg_123'}, {type:'filtered', filters:[...], filterJoinOperator:'and'}, or {type:'rules', include:[{type:'lists', listIds:['list_123']}], exclude:[{type:'segments', segmentIds:['seg_123']}]}. Rules audiences require at least one include rule.",additionalProperties:!0},sendTimeOptimization:{type:"boolean",description:"Whether to use send-time optimization."},spreadOverHours:{type:"number",description:"Spread delivery over an integer number of hours from 1 to 72. When set, spread delivery takes precedence over send-time optimization."},recurringInterval:{type:"string",enum:["weekly","monthly"],description:"Repeat this campaign on a cadence starting at scheduledAt. The campaign becomes a recurring template: each run is duplicated and sent automatically, re-evaluating audience membership every time. Omit for a one-shot send; scheduling again without it stops the recurrence."}},required:["campaignId","scheduledAt"],additionalProperties:!1}},{name:"send_test_email",description:"Send a test email to a single address",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to test"},to:{type:"string",description:"Email address to send test to"}},required:["campaignId","to"]}},{name:"cancel_campaign",description:"Cancel a campaign. Stops scheduled and sending campaigns (also works for paused and approval-pending ones). Remaining emails will not be sent and the campaign cannot be restarted - this cannot be undone.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to cancel."}},required:["campaignId"]}},{name:"pause_campaign",description:"Pause a campaign that is currently sending. Only campaigns in sending status can be paused. Use resume_campaign to continue delivery later.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to pause."}},required:["campaignId"]}},{name:"resume_campaign",description:"Resume a paused campaign. Only campaigns in paused status can be resumed. Optionally spread the remaining delivery over a number of hours.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to resume."},spreadOverHours:{type:"number",description:"Spread the remaining delivery over an integer number of hours from 1 to 72."}},required:["campaignId"]}},{name:"delete_campaign",description:"Permanently delete a campaign. This cannot be undone. Sending, scheduled, or paused campaigns must be cancelled with cancel_campaign first.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to delete."}},required:["campaignId"]}},{name:"duplicate_campaign",description:"Duplicate a campaign as a new draft. mode 'campaign' (default) copies the campaign and its email, 'ab_test' also duplicates the campaign's A/B test with all variants, and 'variant' copies a single variant's content as the new campaign email (requires variantId).",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to duplicate."},mode:{type:"string",enum:["campaign","ab_test","variant"],description:"Duplication mode. Defaults to campaign."},variantId:{type:"string",description:"A/B test variant ID whose content becomes the new campaign email. Required when mode is variant."}},required:["campaignId"]}},{name:"resend_campaign_to_non_openers",description:"Create a draft that resends a sent campaign to everyone in the same audience who didn't open it. Copies the campaign email and reuses the original audience with a 'didn't open this campaign' rule added. Only available 6 hours after the campaign finishes sending. The draft must be scheduled or sent separately. Returns the new draft and an estimate of how many subscribers haven't opened the original.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"ID of the sent campaign to resend to non-openers."}},required:["campaignId"]}},{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:FV},content:{type:"object",description:NQ,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:NQ,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:NQ,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:NQ,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}},{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 plus editable step content. The response includes sequence.emails with each step's nodeId, linked emailId, subject, previewText, and blocks.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"],additionalProperties:!1}},{name:"create_sequence",description:`Create a new email sequence. For net-new natural-language sequence content, provide goal and emailCount so Sequenzy generates it. Use explicit steps only for finished caller-supplied content, exact workflows, or migrations. Explicit steps can include email content, native SMS steps (type: 'sms' with 'text'; check get_sms_settings first and generate copy with generate_sms), and create_discount actions that dynamically create a provider discount/code when each subscriber reaches the step; emails after a discount action can use merge tags such as {{discount.code}} and {{discount.percentOff}}. For AI-generated sequences, the tool polls until emails are generated (typically 30-60 seconds).
52
52
 
53
53
  MIGRATIONS: When moving sequences or flows from Brevo, Mailchimp, Klaviyo, MailerLite, or another provider, pass the exact provider HTML in each email step's html field and pass fixed waits as delay or delayMs. Use waitUntil when a wait should resolve from the trigger event payload, for example { "field": "renews_at", "direction": "before", "offset": { "days": 1 } }. The API stores provider HTML as raw HTML blocks and creates real logic_delay nodes for waits.
54
54
 
@@ -187,7 +187,7 @@ BUILT-IN EVENTS (auto-fired by payment integrations):
187
187
 
188
188
  OTHER BUILT-IN EVENTS:
189
189
  - email.opened, email.clicked, email.replied, email.bounced, email.unsubscribed
190
- - contact.subscribed, contact.unsubscribed`,inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the sequence in. If not provided, uses the currently selected company."},fromEmail:{type:"string",description:"From address for all emails in this sequence. Its domain must be configured and verified."},fromName:{type:"string",description:"Display name for a newly created sender profile. Requires fromEmail."},senderProfileId:{type:"string",description:"Existing sender profile ID. Mutually exclusive with fromEmail."},replyTo:{type:"string",description:"Reply-To address for all emails in this sequence. A reply profile is created when needed."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo."},replyProfileId:{type:"string",description:"Existing reply profile ID. Mutually exclusive with replyTo."},name:{type:"string",description:"Sequence name (e.g., 'User Onboarding', 'Welcome Series')"},trigger:{type:"string",enum:["contact_added","tag_added","segment_entered","event_received","inactivity","frequency"],description:"Trigger type: 'contact_added' (when added to a list), 'tag_added' (when tag is applied), 'segment_entered' (when a contact newly enters a saved segment), 'event_received' (when custom event fires), 'inactivity' (when subscriber hasn't performed an event for X days), 'frequency' (when subscriber performs event X times in Y days)"},listId:{type:"string",description:"List ID to trigger on (for contact_added trigger). If not provided, triggers on any list."},tagName:{type:"string",description:"Tag name to trigger on (required for tag_added trigger)"},segmentId:{type:"string",description:"Segment ID to trigger on (required for segment_entered trigger). Use list_segments first to choose a saved segment."},eventName:{type:"string",description:"Event name to trigger on (required for event_received, inactivity, and frequency triggers)"},propertyFilters:{type:"array",description:"Optional event property filters for event_received triggers. The sequence only starts when the triggering event's properties match ALL filters. Use a dot-path into the event properties; use [] to match inside arrays. Examples: scope a purchase sequence to one product with { path: 'lineItems[].providerProductId', operator: 'equals', value: 'prod_123' } (ecommerce.order_placed) or { path: 'productIds', operator: 'equals', value: 'prod_123' } (saas.purchase); to match any of several products use { path: 'lineItems[].providerProductId', operator: 'one_of', value: ['prod_123', 'prod_456'] }. Max 10 filters.",items:{type:"object",properties:{path:{type:"string",description:"Dot-path into the event properties, e.g. 'lineItems[].providerProductId' or 'plan'."},operator:{type:"string",enum:["exists","not_exists","equals","not_equals","one_of","contains","greater_than","less_than"],description:"Comparison operator. one_of matches when the property equals any entry of the value array."},value:{type:["string","number","boolean","array"],items:{type:["string","number"]},maxItems:50,description:"Value to compare against. Required for every operator except exists/not_exists. For one_of, pass an array of strings or numbers (max 50 values); all other operators take a single value."}},required:["path","operator"]}},inactiveDays:{type:"number",description:"Number of days of inactivity (required for inactivity trigger, must be >= 1)"},inactivityBaseline:{type:"string",enum:["sequence_created_at","subscriber_created_at"],description:"When to start counting inactivity for subscribers who never had the event. Defaults to sequence_created_at."},minCount:{type:"number",description:"Minimum event count (required for frequency trigger, must be >= 1)"},timeWindowDays:{type:"number",description:"Time window in days for frequency trigger (required for frequency trigger, must be >= 1)"},emailCount:{type:"number",description:"Number of emails in the sequence (default: 5, max: 10)"},durationDays:{type:"number",description:"Total duration in days used to space AI-generated sequence emails. Only applies when using goal-based AI generation."},goal:{type:"string",description:"What this sequence should accomplish for AI generation. Be specific to the app's actual features and user journey. Avoid generic goals that don't match the app's business model."},enrollmentMode:{type:"string",enum:["unlimited","one_time","matching_field"],description:"Sequence re-entry mode. Use 'matching_field' only for event_received triggers when duplicate active runs should be blocked per event field value."},enrollmentFieldPath:{type:"string",description:"Dot-path event property used by enrollmentMode='matching_field', such as 'order.id' or 'product.providerVariantId'. Leave omitted for Shopify back-in-stock/replenishment product-variant defaults."},sendingWindow:a5,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:XX,subject:{type:"string",description:"Email subject. Required for email steps."},previewText:{type:"string",description:"Email preview text."},blocks:{type:"array",description:tY,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:sY,delayMs:{type:"number",description:"Delay before this step in milliseconds. Prefer delay for readability; use delayMs when importing provider waits."},waitUntil:aY,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"]}},{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:"Dot-path event property used by enrollmentMode='matching_field', such as 'order.id' or 'product.providerVariantId'. 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:a5,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:rY}},required:["conditionType"]}},elseSteps:{type:"array",description:"Steps to create inside the else fallback path. Required by default so the else arm is usable.",items:rY},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:rY}},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:Q4,items:{type:"object"}}}}},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:Q4,items:{type:"object"}}}}},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:XX},required:["nodeId","config"]}}},required:["sequenceId"]}},{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:tY,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."},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:sY,delayMs:{type:"number",description:"Optional wait in milliseconds before the new step. Prefer delay for readability."},waitUntil:aY},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"]}},{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:`${s4} 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:`${Q4} Mutually exclusive with \`html\`.`,items:{type:"object"}}},required:["idOrSlug"],additionalProperties:!1}},{name:"send_email",description:"Send a transactional email to a single recipient",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},to:{type:"string",description:"Recipient email address"},subject:{type:"string",description:"Email subject (required if not using templateId)"},html:{type:"string",description:"Email HTML content (required if not using templateId)"},templateId:{type:"string",description:"Template ID to use (alternative to html)"},variables:{type:"object",description:"Variables for template personalization. Nested objects and arrays are supported for repeat blocks, for example { items: [...] }."},subscriberExternalId:{type:"string",description:"Customer-owned subscriber ID for attaching analytics/localization on single-recipient sends. Maximum length: 255 characters."}},required:["to"]}},{name:"get_stats",description:"Get overview statistics for a time period",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},period:{type:"string",description:"Time period: 7d, 30d, or 90d (default: 7d)"},includeMachineEngagement:N1}}},{name:"get_campaign_stats",description:"Get detailed statistics for a campaign, including attributed conversions and revenue (revenueCents)",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:N1},required:["campaignId"]}},{name:"get_sequence_stats",description:"Get statistics for a sequence, including attributed conversions and revenue (revenueCents) plus per-step failed subscribers and failure reasons",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"},includeMachineEngagement:N1},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:N1},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:N1},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:N1},required:[]}},{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"]}},{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"]}},{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:[...PQ]},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:[...PQ]},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"]}},{name:"generate_email",description:"Generate email blocks from a prompt. Generated blocks include the company's branding chrome (logo, footer with company name/address/unsubscribe) by default, matching emails created in the dashboard.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},prompt:{type:"string",description:"Description of the email to generate"},style:{type:"string",description:"Style: minimal, branded, promotional"},tone:{type:"string",description:"Tone: professional, casual, friendly"},applyBranding:{type:"boolean",description:"Wrap the generated content with company branding (logo + footer). Defaults to true; set false to get raw content blocks only."},emailType:{type:"string",enum:["marketing","transactional"],description:"Email type. Transactional emails get a footer without the unsubscribe link. Defaults to marketing."}},required:["prompt"]}},{name:"generate_sequence",description:"[DEPRECATED - Use create_sequence instead] Generate a multi-email sequence from a goal. Note: create_sequence now handles AI generation automatically.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},goal:{type:"string",description:"Goal of the sequence (e.g., 'onboard new SaaS trial users')"},emailCount:{type:"number",description:"Number of emails in the sequence (default: 5, max: 10)"},durationDays:{type:"number",description:"Total duration in days (default: 14)"}},required:["goal"]}},{name:"generate_subject_lines",description:"Generate A/B test subject line variants",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},topic:{type:"string",description:"Topic or context for the subject lines"},count:{type:"number",description:"Number of variants to generate (default: 5)"}},required:["topic"]}},{name:"generate_sms",description:"Generate SMS marketing message variants from a prompt. Returns plain-text messages with per-message encoding and segment counts. Use the results as the 'text' of an SMS sequence step (insert_sequence_step with type 'sms' or a create_sequence sms step). Messages exclude opt-out footers and brand prefixes - the platform adds those automatically at send time.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},prompt:{type:"string",description:"Description of the SMS to generate (e.g., 'cart reminder with a free-shipping hook')"},count:{type:"number",description:"Number of message variants to generate (default: 3, max: 10)"}},required:["prompt"]}},{name:"get_sms_settings",description:"Get the company's SMS add-on status: whether SMS is enabled, plan eligibility, credit balance, brand prefix, phone numbers, and whether SMS steps will actually send. Check this before adding SMS steps to sequences so you can warn the user when SMS is not ready.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"send_test_sms",description:"Send a test SMS to a phone number. IMPORTANT: sends a real text message and charges SMS credits - only call when the user explicitly asks for a test send. Requires the SMS add-on with a verified number (check get_sms_settings). Limited to 5 test sends per hour; bypasses quiet hours; excluded from step stats.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},to:{type:"string",description:"Destination phone number in international E.164 format, e.g. +15550100123."},text:{type:"string",description:"Plain-text message body. Merge tags are not resolved for test sends to arbitrary numbers. Provide text or blocks."},imageUrls:{type:"array",items:{type:"string"},description:"Up to 2 publicly reachable image URLs sent as MMS media (US/CA only)."},blocks:{type:"array",items:{type:"object"},description:"SMS content blocks (text + image subset). Provide text or blocks, not both."}},required:["to"]}},{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"]}}],UH=AZ.map(JZ).map(qV);async function KH(Q,Y){try{let X;switch(Q){case"get_account":{let G=await B("GET","/api/v1/account"),$=b1();X={...G,selectedCompanyId:$??G.currentCompanyId};break}case"select_company":{let G=Y.companyId,$=await B("GET","/api/v1/account"),z=$.companies?.find((J)=>J.id===G);if(!z)throw Error(`Company not found. Available companies: ${$.companies?.map((J)=>`${J.name} (${J.id})`).join(", ")??"none"}`);Q6(G),X={success:!0,message:`Switched to company: ${z.name}`,companyId:z.id,companyName:z.name};break}case"get_app_urls":{let G=await JX(Y);X={...Z1({companyId:G,campaignId:w(Y,"campaignId"),landingPageId:w(Y,"landingPageId"),sequenceId:w(Y,"sequenceId"),emailId:w(Y,"emailId")??w(Y,"templateId"),transactionalId:w(Y,"transactionalId"),emailSendId:w(Y,"emailSendId"),domainId:w(Y,"domainId"),status:w(Y,"status"),settingsTab:w(Y,"settingsTab")}),...G===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 G=await B("POST","/api/v1/companies",{name:Y.name,domain:Y.domain});if(!G.success)throw Error("Failed to create company");let $=G.company.id,z=6,J=0,H=G.company.status;while(H==="processing"&&J<z){await new Promise((K)=>setTimeout(K,20000)),J++;let U=await B("GET",`/api/v1/companies/${$}`);if(U.success)H=U.company.status}Q6($);let A=await B("GET",`/api/v1/companies/${$}`);X={success:!0,company:A.company,message:H==="processing"?"Company created but still processing. You can continue using it while processing completes.":`Company '${A.company.name}' created and ready to use.`,autoSelected:!0};break}case"get_company":{let G=Y.companyId;X=await B("GET",`/api/v1/companies/${G}`);break}case"update_company":{let G=await tV("update_company",Y),$=CV(Y);X=await B("PATCH",`/api/v1/companies/${G}`,$);break}case"get_sync_rules":{let G=Y.companyId;X=await B("GET","/api/v1/sync-rules",void 0,G);break}case"update_sync_rules":{let G=Y.companyId;if(Y.syncRules!==null&&!Array.isArray(Y.syncRules))throw Error("`syncRules` must be an array of rules or null when calling `update_sync_rules`.");X=await B("PUT","/api/v1/sync-rules",{syncRules:Y.syncRules},G);break}case"get_shopify_automation_settings":{let G=Y.companyId;X=await B("GET","/api/v1/shopify/automation-settings",void 0,G);break}case"update_shopify_automation_settings":{let G=Y.companyId,$={};if(Y.browseAbandonment!==void 0)$.browseAbandonment=Y.browseAbandonment;if(Y.priceDrop!==void 0)$.priceDrop=Y.priceDrop;if(Object.keys($).length===0)throw Error("Provide `browseAbandonment` and/or `priceDrop` when calling `update_shopify_automation_settings`.");X=await B("PUT","/api/v1/shopify/automation-settings",$,G);break}case"create_api_key":{let G=Y.companyId,$={};if(typeof Y.name==="string")$.name=Y.name;if(typeof Y.preset==="string")$.preset=Y.preset;if(Array.isArray(Y.scopes))$.scopes=Y.scopes;X=await B("POST","/api/v1/api-keys",$,G);break}case"list_websites":{let G=Y.companyId;X=await B("GET","/api/v1/websites",void 0,G);break}case"add_sending_domain":case"add_website":{let G=Y.companyId;X=await B("POST","/api/v1/websites",{domain:Y.domain},G);break}case"check_website":{let G=Y.companyId;X=await B("GET",`/api/v1/websites/${encodeURIComponent(String(Y.domain))}`,void 0,G);break}case"verify_sending_domain":{let G=Y.companyId;X=await B("POST",`/api/v1/websites/${encodeURIComponent(String(Y.domain))}/verify`,void 0,G);break}case"get_integration_guide":X=await B("POST","/api/v1/integration-guide",Y);break;case"add_subscriber":{let G=Y.companyId,$=v1("add_subscriber",Y);X=await B("POST","/api/v1/subscribers",{...$,customAttributes:Y.attributes,tags:Y.tags,lists:Y.listIds,...Y.status!==void 0&&{status:Y.status},...Y.optInMode!==void 0&&{optInMode:Y.optInMode}},G);break}case"update_subscriber":{let G=Y.companyId,$=v1("update_subscriber",Y),z=await dY($,G),J=Array.isArray(z.subscriber.tags)?z.subscriber.tags.filter((D)=>typeof D==="string"):[],H=Array.isArray(Y.addTags)?Y.addTags.filter((D)=>typeof D==="string"&&D.trim()!=="").map(XH):[],A=new Set(Array.isArray(Y.removeTags)?Y.removeTags.filter((D)=>typeof D==="string"&&D.trim()!=="").map(XH):[]),U=J.filter((D)=>!A.has(D));for(let D of H)if(!U.includes(D))U.push(D);let K={};if($.email&&$.externalId)K.externalId=$.externalId;if(J0(Y.attributes))K.customAttributes={...J0(z.subscriber.customAttributes)?z.subscriber.customAttributes:{},...Y.attributes};if(Y.addTags||Y.removeTags)K.tags=U;X=await B("PATCH",WX($),K,G);break}case"remove_subscriber":{let G=Y.companyId,$=v1("remove_subscriber",Y),z=WX($);if(Y.hardDelete===!0)X=await B("DELETE",z,void 0,G);else X=await B("PATCH",z,{status:"unsubscribed"},G);break}case"get_subscriber":{let G=Y.companyId,$=v1("get_subscriber",Y);X=await dY($,G,{includeMachineEngagement:Y.includeMachineEngagement===!0});break}case"list_subscriber_notes":{let G=Y.companyId,$=v1("list_subscriber_notes",Y);X=await B("GET",WH($),void 0,G);break}case"add_subscriber_note":{let G=Y.companyId,$=v1("add_subscriber_note",Y),z=typeof Y.body==="string"?Y.body.trim():void 0;if(!z)throw Error("`body` is required when calling `add_subscriber_note`.");if(z.length>5000)throw Error("`body` must be 5000 characters or fewer when calling `add_subscriber_note`.");X=await B("POST",WH($),{body:z},G);break}case"delete_subscriber_note":{let G=Y.companyId,$=typeof Y.noteId==="string"?Y.noteId.trim():"";if(!$)throw Error("`noteId` is required when calling `delete_subscriber_note`.");X=await B("DELETE",`/api/v1/subscribers/notes/${encodeURIComponent($)}`,void 0,G);break}case"search_subscribers":{let G=Y.companyId;X=await mV(Y,G);break}case"list_products":{let G=Y.companyId,$=new URLSearchParams;if(typeof Y.provider==="string"&&Y.provider.trim())$.set("provider",Y.provider.trim());if(typeof Y.search==="string"&&Y.search.trim())$.set("search",Y.search.trim());let z=$.size>0?`?${$.toString()}`:"";X=await B("GET",`/api/v1/products${z}`,void 0,G);break}case"upsert_products":{let G=Y.companyId;if(!Array.isArray(Y.products)||Y.products.length===0)throw Error("`products` must be a non-empty array when calling `upsert_products`.");X=await B("POST","/api/v1/products",{products:Y.products},G);break}case"delete_product":{let G=Y.companyId,$=R("delete_product",Y,"productId");X=await B("DELETE",`/api/v1/products/${encodeURIComponent($)}`,void 0,G);break}case"attach_product_file":{let G=Y.companyId,$=R("attach_product_file",Y,"productId"),z=w(Y,"url"),J=w(Y,"filePath");if(z===void 0===(J===void 0))throw Error("Provide either `url` or `filePath` (not both) when calling `attach_product_file`.");let H;if(J!==void 0){let A=await oV(J,G);H={url:A.url,source:"upload",fileName:w(Y,"fileName")??A.fileName,fileSizeBytes:A.fileSizeBytes,mimeType:A.mimeType}}else{H={url:z};let A=w(Y,"fileName");if(A)H.fileName=A}X=await B("PUT",`/api/v1/products/${encodeURIComponent($)}/delivery`,H,G);break}case"remove_product_file":{let G=Y.companyId,$=R("remove_product_file",Y,"productId");X=await B("DELETE",`/api/v1/products/${encodeURIComponent($)}/delivery`,void 0,G);break}case"sync_products":{let G=Y.companyId;X=await B("POST","/api/v1/products/sync",void 0,G);break}case"list_tags":{let G=Y.companyId;X=await B("GET","/api/v1/tags",void 0,G);break}case"create_tag":{let G=Y.companyId,$=R("create_tag",Y,"name"),z=m0("create_tag",Y,"color",wQ);X=await B("POST","/api/v1/tags",{name:$,...z!==void 0&&{color:z}},G);break}case"update_tag":{let G=Y.companyId,$=R("update_tag",Y,"tagId"),z=oY("update_tag",Y,"color",wQ);X=await B("PATCH",`/api/v1/tags/${encodeURIComponent($)}`,{color:z},G);break}case"delete_tag":{let G=Y.companyId,$=R("delete_tag",Y,"tagId");X=await B("DELETE",`/api/v1/tags/${encodeURIComponent($)}`,void 0,G);break}case"list_lists":{let G=Y.companyId;X=await B("GET","/api/v1/lists",void 0,G);break}case"create_list":{let G=Y.companyId;X=await B("POST","/api/v1/lists",Y,G);break}case"update_list":{let G=Y.companyId,$=R("update_list",Y,"listId");if(Y.name===void 0&&Y.description===void 0&&Y.isPrivate===void 0)throw Error("Provide at least one of `name`, `description`, or `isPrivate` when calling `update_list`.");if(Y.name!==void 0&&w(Y,"name")===void 0)throw Error("`name` cannot be empty when calling `update_list`.");if(Y.description!==void 0&&Y.description!==null&&typeof Y.description!=="string")throw Error("`description` must be a string or null when calling `update_list`.");if(Y.isPrivate!==void 0&&typeof Y.isPrivate!=="boolean")throw Error("`isPrivate` must be a boolean when calling `update_list`.");X=await B("PATCH",`/api/v1/lists/${encodeURIComponent($)}`,{...Y.name!==void 0&&{name:w(Y,"name")},...Y.description!==void 0&&{description:Y.description},...Y.isPrivate!==void 0&&{isPrivate:Y.isPrivate}},G);break}case"delete_list":{let G=Y.companyId,$=R("delete_list",Y,"listId");X=await B("DELETE",`/api/v1/lists/${encodeURIComponent($)}`,void 0,G);break}case"add_subscribers_to_list":{let G=Y.companyId,$=R("add_subscribers_to_list",Y,"listId"),z=zH("add_subscribers_to_list",Y),J=m0("add_subscribers_to_list",Y,"duplicateStrategy",["skip","merge","overwrite"])??"skip",H=m0("add_subscribers_to_list",Y,"optInMode",["default","confirmed","double_opt_in"])??"default";X=await B("POST",`/api/v1/lists/${encodeURIComponent($)}/subscribers`,{emails:z,duplicateStrategy:J,enrollInSequences:Y.enrollInSequences===!0,optInMode:H},G);break}case"remove_subscribers_from_list":{let G=Y.companyId,$=R("remove_subscribers_from_list",Y,"listId"),z=zH("remove_subscribers_from_list",Y);X=await B("POST",`/api/v1/lists/${encodeURIComponent($)}/subscribers/remove`,{emails:z},G);break}case"list_segments":{let G=Y.companyId;X=await B("GET","/api/v1/segments",void 0,G);break}case"create_segment":{SV(Y);let G=Y.companyId;X=await B("POST","/api/v1/segments",{...Y,...Y.filters!==void 0?{filters:QX(Y.filters)}:{},...Y.root!==void 0?{root:YX(Y.root)}:{}},G);break}case"update_segment":{RV(Y);let G=Y.companyId,$=R("update_segment",Y,"segmentId"),z=w(Y,"name"),J=m0("update_segment",Y,"filterJoinOperator",["and","or"]);X=await B("PATCH",`/api/v1/segments/${encodeURIComponent($)}`,{...z!==void 0&&{name:z},...J!==void 0&&{filterJoinOperator:J},...Y.filters!==void 0?{filters:QX(Y.filters)}:{},...Y.root!==void 0?{root:YX(Y.root)}:{}},G);break}case"delete_segment":{let G=Y.companyId,$=R("delete_segment",Y,"segmentId");X=await B("DELETE",`/api/v1/segments/${encodeURIComponent($)}`,void 0,G);break}case"get_segment_count":{let G=Y.companyId;X=await B("GET",`/api/v1/segments/${Y.segmentId}/count`,void 0,G);break}case"list_audience_syncs":{let G=Y.companyId;X=await B("GET","/api/v1/audience-syncs",void 0,G);break}case"list_ad_accounts":{let G=Y.companyId;X=await B("GET","/api/v1/ad-accounts",void 0,G);break}case"create_audience_sync":{let G=Y.companyId,$=w(Y,"segmentId"),z=w(Y,"predefinedSegmentId");if($&&z)throw Error("Provide either `segmentId` or `predefinedSegmentId` when calling `create_audience_sync`, not both.");if(!$&&!z)throw Error("Provide either `segmentId` or `predefinedSegmentId` when calling `create_audience_sync`.");X=await B("POST","/api/v1/audience-syncs",{segmentId:$,predefinedSegmentId:z,adAccountId:R("create_audience_sync",Y,"adAccountId"),audienceName:R("create_audience_sync",Y,"audienceName"),...Y.frequency!==void 0?{frequency:Y.frequency}:{}},G);break}case"update_audience_sync":{let G=Y.companyId,$=R("update_audience_sync",Y,"syncId");X=await B("PATCH",`/api/v1/audience-syncs/${encodeURIComponent($)}`,{...Y.frequency!==void 0?{frequency:Y.frequency}:{},...Y.isActive!==void 0?{isActive:Y.isActive}:{}},G);break}case"delete_audience_sync":{let G=Y.companyId,$=R("delete_audience_sync",Y,"syncId");X=await B("DELETE",`/api/v1/audience-syncs/${encodeURIComponent($)}`,void 0,G);break}case"sync_audience_now":{let G=Y.companyId,$=R("sync_audience_now",Y,"syncId");X=await B("POST",`/api/v1/audience-syncs/${encodeURIComponent($)}/sync`,void 0,G);break}case"list_templates":{let G=Y.companyId,$=new URLSearchParams,z=w(Y,"label");if(z)$.set("label",z);X=await B("GET",`/api/v1/templates${$.size>0?`?${$}`:""}`,void 0,G);break}case"get_template":{let G=Y.companyId;X=await B("GET",`/api/v1/templates/${Y.templateId}`,void 0,G);break}case"create_template":{let G=Y.companyId;gV(Y);let $=Object.fromEntries(Object.entries(Y).filter(([z])=>z!=="companyId"));X=await B("POST","/api/v1/templates",$,G);break}case"update_template":{let G=Y.companyId,$=new Set(["companyId","templateId","name","subject","html","blocks","labels"]),z=Object.keys(Y).filter((J)=>!$.has(J));if(z.length>0)throw Error(`\`update_template\` accepts only \`name\`, \`subject\`, \`html\`, \`blocks\`, and \`labels\` update fields. Unsupported field${z.length===1?"":"s"}: ${z.map((J)=>`\`${J}\``).join(", ")}.`);if(w1("update_template",Y),bQ("update_template",Y),Y.name===void 0&&Y.subject===void 0&&Y.html===void 0&&Y.blocks===void 0&&Y.labels===void 0)throw Error("Provide at least one of `name`, `subject`, `html`, `blocks`, or `labels` when calling `update_template`.");X=await B("PUT",`/api/v1/templates/${Y.templateId}`,Y,G);break}case"delete_template":{let G=Y.companyId;X=await B("DELETE",`/api/v1/templates/${Y.templateId}`,void 0,G);break}case"list_ab_tests":{let G=Y.companyId,$=new URLSearchParams,z=w(Y,"sequenceId");if(z)$.set("sequenceId",z);X=await B("GET",`/api/v1/ab-tests${$.size>0?`?${$}`:""}`,void 0,G);break}case"get_ab_test":{let G=Y.companyId;X=await B("GET",`/api/v1/ab-tests/${Y.abTestId}`,void 0,G);break}case"get_ab_test_stats":{let G=Y.companyId,$=new URLSearchParams,z=w(Y,"period"),J=w(Y,"start"),H=w(Y,"end");if(z)$.set("period",z);if(J)$.set("start",J);if(H)$.set("end",H);if(Y.includeMachineEngagement===!0)$.set("includeMachineEngagement","true");X=await B("GET",`/api/v1/ab-tests/${Y.abTestId}/stats${$.size>0?`?${$}`:""}`,void 0,G);break}case"restart_ab_test":{let G=Y.companyId,$=new Set(["companyId","abTestId","sourceVariantId","testType","winnerThreshold","variantCount"]),z=Object.keys(Y).filter((U)=>!$.has(U));if(z.length>0)throw Error(`\`restart_ab_test\` accepts only \`sourceVariantId\`, \`testType\`, \`winnerThreshold\`, and \`variantCount\` option fields. Unsupported field${z.length===1?"":"s"}: ${z.map((U)=>`\`${U}\``).join(", ")}.`);let J=w(Y,"testType");if(J!==void 0&&J!=="subject"&&J!=="content")throw Error("`restart_ab_test` testType must be `subject` or `content`.");let H=Y.winnerThreshold===void 0?void 0:Number(Y.winnerThreshold);if(H!==void 0&&(!Number.isInteger(H)||H<10||H>1000))throw Error("`restart_ab_test` winnerThreshold must be an integer from 10 to 1000.");let A=Y.variantCount===void 0?void 0:Number(Y.variantCount);if(A!==void 0&&(!Number.isInteger(A)||A<2||A>4))throw Error("`restart_ab_test` variantCount must be an integer from 2 to 4.");X=await B("POST",`/api/v1/ab-tests/${Y.abTestId}/restart`,{sourceVariantId:w(Y,"sourceVariantId"),testType:J,winnerThreshold:H,variantCount:A},G);break}case"update_ab_test_variant":{let G=Y.companyId,$=new Set(["companyId","abTestId","variantId","subject","previewText","html","blocks"]),z=Object.keys(Y).filter((J)=>!$.has(J));if(z.length>0)throw Error(`\`update_ab_test_variant\` accepts only \`subject\`, \`previewText\`, \`html\`, and \`blocks\` update fields. Unsupported field${z.length===1?"":"s"}: ${z.map((J)=>`\`${J}\``).join(", ")}.`);if(w1("update_ab_test_variant",Y),Y.subject===void 0&&Y.previewText===void 0&&Y.html===void 0&&Y.blocks===void 0)throw Error("Provide at least one of `subject`, `previewText`, `html`, or `blocks` when calling `update_ab_test_variant`.");X=await B("PATCH",`/api/v1/ab-tests/${Y.abTestId}/variants/${Y.variantId}`,Y,G);break}case"create_ab_test":{let G=Y.companyId,$=R("create_ab_test",Y,"campaignId"),z=w(Y,"name"),J=x1("create_ab_test",Y,"testPercentage",5,50),H=x1("create_ab_test",Y,"testDurationMinutes",15,1440),A=m0("create_ab_test",Y,"winnerCriteria",["open_rate","click_rate"]);if(Y.variants!==void 0){if(!Array.isArray(Y.variants))throw Error("`variants` must be an array when calling `create_ab_test`.");Y.variants.forEach((U,K)=>{if(!J0(U)||typeof U.subject!=="string"||U.subject.trim()==="")throw Error(`\`variants\` item ${K+1} must include a non-empty \`subject\` when calling \`create_ab_test\`.`);if(U.blocks!==void 0&&!Array.isArray(U.blocks))throw Error(`\`variants\` item ${K+1} \`blocks\` must be an array when calling \`create_ab_test\`.`)})}X=await B("POST","/api/v1/ab-tests",{campaignId:$,...z!==void 0&&{name:z},...J!==void 0&&{testPercentage:J},...H!==void 0&&{testDurationMinutes:H},...A!==void 0&&{winnerCriteria:A},...Y.variants!==void 0&&{variants:Y.variants}},G);break}case"add_ab_test_variant":{let G=Y.companyId,$=R("add_ab_test_variant",Y,"abTestId"),z=R("add_ab_test_variant",Y,"subject"),J=w(Y,"previewText");if(Y.blocks!==void 0&&!Array.isArray(Y.blocks))throw Error("`blocks` must be an array when calling `add_ab_test_variant`.");X=await B("POST",`/api/v1/ab-tests/${encodeURIComponent($)}/variants`,{subject:z,...J!==void 0&&{previewText:J},...Y.blocks!==void 0&&{blocks:Y.blocks}},G);break}case"delete_ab_test_variant":{let G=Y.companyId,$=R("delete_ab_test_variant",Y,"abTestId"),z=R("delete_ab_test_variant",Y,"variantId");X=await B("DELETE",`/api/v1/ab-tests/${encodeURIComponent($)}/variants/${encodeURIComponent(z)}`,void 0,G);break}case"delete_ab_test":{let G=Y.companyId,$=R("delete_ab_test",Y,"abTestId");X=await B("DELETE",`/api/v1/ab-tests/${encodeURIComponent($)}`,void 0,G);break}case"list_campaigns":{let G=Y.companyId,$=new URLSearchParams;if(Y.status)$.set("status",String(Y.status));let z=w(Y,"label");if(z)$.set("label",z);X=await B("GET",`/api/v1/campaigns?${$}`,void 0,G);break}case"get_campaign":{let G=Y.companyId;X=await B("GET",`/api/v1/campaigns/${Y.campaignId}`,void 0,G);break}case"get_email_send":{let G=Y.companyId;X=await B("GET",`/api/v1/email-sends/${encodeURIComponent(String(Y.emailSendId))}`,void 0,G);break}case"create_campaign":{let G=Y.companyId;if(_V(Y),Y.fromEmail!==void 0&&Y.senderProfileId!==void 0)throw Error("Provide either `fromEmail` or `senderProfileId` when calling `create_campaign`, not both.");if(Y.replyTo!==void 0&&Y.replyProfileId!==void 0)throw Error("Provide either `replyTo` or `replyProfileId` when calling `create_campaign`, not both.");if(Y.fromName!==void 0&&Y.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `create_campaign`.");if(Y.replyToName!==void 0&&Y.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `create_campaign`.");let $=Object.fromEntries(Object.entries(Y).filter(([z])=>z!=="companyId"));X=await B("POST","/api/v1/campaigns",$,G);break}case"update_campaign":{let G=Y.companyId,$=new Set(["companyId","campaignId","name","subject","trackingCode","html","blocks","fromEmail","fromName","senderProfileId","replyTo","replyToName","replyProfileId","campaignData","computedLists","labels"]),z=Object.keys(Y).filter((J)=>!$.has(J));if(z.length>0)throw Error(`\`update_campaign\` accepts only content, sending identity, campaign data, computed list, and label update fields. Unsupported field${z.length===1?"":"s"}: ${z.map((J)=>`\`${J}\``).join(", ")}.`);if(w1("update_campaign",Y),bQ("update_campaign",Y),Y.replyTo!==void 0&&Y.replyProfileId!==void 0)throw Error("Provide either `replyTo` or `replyProfileId` when calling `update_campaign`, not both.");if(Y.fromEmail!==void 0&&Y.senderProfileId!==void 0)throw Error("Provide either `fromEmail` or `senderProfileId` when calling `update_campaign`, not both.");if(Y.fromName!==void 0&&Y.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `update_campaign`.");if(Y.replyToName!==void 0&&Y.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `update_campaign`.");if(Y.name===void 0&&Y.subject===void 0&&Y.trackingCode===void 0&&Y.html===void 0&&Y.blocks===void 0&&Y.fromEmail===void 0&&Y.senderProfileId===void 0&&Y.replyTo===void 0&&Y.replyProfileId===void 0&&Y.campaignData===void 0&&Y.computedLists===void 0&&Y.labels===void 0)throw Error("Provide at least one campaign content, sending identity, campaign data, computed list, or label field when calling `update_campaign`.");X=await B("PUT",`/api/v1/campaigns/${Y.campaignId}`,Y,G);break}case"schedule_campaign":{let G=Y.companyId,$=new Set(["companyId","campaignId","scheduledAt","targetLists","sendTimeOptimization","spreadOverHours","recurringInterval"]),z=Object.keys(Y).filter((J)=>!$.has(J));if(z.length>0)throw Error(`\`schedule_campaign\` accepts only \`campaignId\`, \`scheduledAt\`, \`targetLists\`, \`sendTimeOptimization\`, \`spreadOverHours\`, and \`recurringInterval\`. Unsupported field${z.length===1?"":"s"}: ${z.map((J)=>`\`${J}\``).join(", ")}.`);yV(Y),X=await B("POST",`/api/v1/campaigns/${Y.campaignId}/schedule`,{scheduledAt:Y.scheduledAt,...Y.targetLists!==void 0&&{targetLists:Y.targetLists},...Y.sendTimeOptimization!==void 0&&{sendTimeOptimization:Y.sendTimeOptimization},...Y.spreadOverHours!==void 0&&{spreadOverHours:Y.spreadOverHours},...Y.recurringInterval!==void 0&&{recurringInterval:Y.recurringInterval}},G);break}case"send_test_email":{let G=Y.companyId;X=await B("POST",`/api/v1/campaigns/${Y.campaignId}/test`,{to:Y.to},G);break}case"cancel_campaign":{let G=Y.companyId,$=R("cancel_campaign",Y,"campaignId");X=await B("POST",`/api/v1/campaigns/${encodeURIComponent($)}/cancel`,void 0,G);break}case"pause_campaign":{let G=Y.companyId,$=R("pause_campaign",Y,"campaignId");X=await B("POST",`/api/v1/campaigns/${encodeURIComponent($)}/pause`,void 0,G);break}case"resume_campaign":{let G=Y.companyId,$=R("resume_campaign",Y,"campaignId"),z=x1("resume_campaign",Y,"spreadOverHours",1,72);X=await B("POST",`/api/v1/campaigns/${encodeURIComponent($)}/resume`,{...z!==void 0&&{spreadOverHours:z}},G);break}case"delete_campaign":{let G=Y.companyId,$=R("delete_campaign",Y,"campaignId");X=await B("DELETE",`/api/v1/campaigns/${encodeURIComponent($)}`,void 0,G);break}case"duplicate_campaign":{let G=Y.companyId,$=R("duplicate_campaign",Y,"campaignId"),z=m0("duplicate_campaign",Y,"mode",["campaign","ab_test","variant"]),J=w(Y,"variantId");if(z==="variant"&&J===void 0)throw Error("`variantId` is required when calling `duplicate_campaign` with mode `variant`.");X=await B("POST",`/api/v1/campaigns/${encodeURIComponent($)}/duplicate`,{...z!==void 0&&{mode:z},...J!==void 0&&{variantId:J}},G);break}case"resend_campaign_to_non_openers":{let G=Y.companyId,$=R("resend_campaign_to_non_openers",Y,"campaignId");X=await B("POST",`/api/v1/campaigns/${encodeURIComponent($)}/resend-to-non-openers`,void 0,G);break}case"list_landing_pages":{let G=Y.companyId;X=await B("GET","/api/v1/landing-pages",void 0,G);break}case"get_landing_page":{let G=Y.companyId;X=await B("GET",`/api/v1/landing-pages/${Y.landingPageId}`,void 0,G);break}case"create_landing_page":{let G=Y.companyId,$=new Set(["companyId","name","slug","template","content"]),z=Object.keys(Y).filter((J)=>!$.has(J));if(z.length>0)throw Error(`\`create_landing_page\` accepts only \`name\`, \`slug\`, \`template\`, and \`content\` fields. Unsupported field${z.length===1?"":"s"}: ${z.map((J)=>`\`${J}\``).join(", ")}.`);X=await B("POST","/api/v1/landing-pages",{...Y.name!==void 0&&{name:Y.name},...Y.slug!==void 0&&{slug:Y.slug},...Y.template!==void 0&&{template:Y.template},...Y.content!==void 0&&{content:Y.content}},G);break}case"update_landing_page":{let G=Y.companyId,$=nY("update_landing_page",Y,{requireUpdate:!0});X=await B("PUT",`/api/v1/landing-pages/${Y.landingPageId}`,$,G);break}case"publish_landing_page":{let G=Y.companyId,$=nY("publish_landing_page",Y,{requireUpdate:!1});X=await B("POST",`/api/v1/landing-pages/${Y.landingPageId}/publish`,$,G);break}case"unpublish_landing_page":{let G=Y.companyId,$=nY("unpublish_landing_page",Y,{requireUpdate:!1});X=await B("POST",`/api/v1/landing-pages/${Y.landingPageId}/unpublish`,$,G);break}case"delete_landing_page":{let G=Y.companyId;X=await B("DELETE",`/api/v1/landing-pages/${Y.landingPageId}`,void 0,G);break}case"connect_landing_page_domain":{let G=Y.companyId;X=await B("POST","/api/v1/landing-pages/domain",{domain:Y.domain},G);break}case"update_landing_page_domain_settings":{let G=Y.companyId,$=uV(Y);X=await B("PUT","/api/v1/landing-pages/domain",$,G);break}case"list_sequences":{let G=Y.companyId;X=await B("GET","/api/v1/sequences",void 0,G);break}case"get_sequence":{let G=Y.companyId;X=await B("GET",`/api/v1/sequences/${Y.sequenceId}`,void 0,G);break}case"create_sequence":{let G=Y.companyId;if(Y.fromEmail!==void 0&&Y.senderProfileId!==void 0)throw Error("Provide either `fromEmail` or `senderProfileId` when calling `create_sequence`, not both.");if(Y.replyTo!==void 0&&Y.replyProfileId!==void 0)throw Error("Provide either `replyTo` or `replyProfileId` when calling `create_sequence`, not both.");if(Y.fromName!==void 0&&Y.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `create_sequence`.");if(Y.replyToName!==void 0&&Y.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `create_sequence`.");let $=Array.isArray(Y.steps)&&Y.steps.length>0,z=await B("POST","/api/v1/sequences",Y,G);if(!z.success){X=z;break}let J=z.sequence.id;if($){let D=await B("GET",`/api/v1/sequences/${J}`,void 0,G);if(D.success)X={success:!0,sequence:D.sequence,message:`Sequence "${D.sequence.name}" created with explicit steps. Review it before enabling.`};else X=D;break}let H=6,A=0,U="pending";while(U!=="complete"&&A<H){await new Promise((L)=>setTimeout(L,20000)),A++;let D=await B("GET",`/api/v1/sequences/${J}`,void 0,G);if(D.success)U=D.sequence.enrichmentStatus}let K=await B("GET",`/api/v1/sequences/${J}`,void 0,G);if(K.success)X={success:!0,sequence:K.sequence,message:K.sequence.enrichmentStatus==="complete"?`Sequence "${K.sequence.name}" created with ${K.sequence.emailCount} AI-generated emails. The sequence is ready to review and enable.`:`Sequence "${K.sequence.name}" created. Email enrichment is still in progress (${K.sequence.enrichedCount}/${K.sequence.emailCount} emails generated). You can check status with get_sequence.`};else X=K;break}case"update_sequence":{let G=Y.companyId,$=kV(Y);X=await B("PUT",`/api/v1/sequences/${Y.sequenceId}`,$,G);break}case"insert_sequence_step":{let G=Y.companyId,$=vV(Y);X=await B("PUT",`/api/v1/sequences/${Y.sequenceId}`,$,G);break}case"enable_sequence":{let G=Y.companyId;X=await B("POST",`/api/v1/sequences/${Y.sequenceId}/enable`,void 0,G);break}case"disable_sequence":{let G=Y.companyId;X=await B("POST",`/api/v1/sequences/${Y.sequenceId}/disable`,void 0,G);break}case"pause_sequence_enrollments":{let G=Y.companyId;X=await B("POST",`/api/v1/sequences/${Y.sequenceId}/pause-enrollments`,void 0,G);break}case"resume_sequence_enrollments":{let G=Y.companyId;X=await B("POST",`/api/v1/sequences/${Y.sequenceId}/resume-enrollments`,void 0,G);break}case"enroll_subscribers_in_sequence":{let G=Y.companyId,$=R("enroll_subscribers_in_sequence",Y,"sequenceId"),z=iV(Y);X=await B("POST",`/api/v1/sequences/${encodeURIComponent($)}/enroll`,z,G);break}case"cancel_sequence_enrollments":{let G=Y.companyId,$=xV(Y);X=await B("POST",`/api/v1/sequences/${Y.sequenceId}/enrollments/cancel`,$,G);break}case"delete_sequence":{let G=Y.companyId;X=await B("DELETE",`/api/v1/sequences/${Y.sequenceId}`,void 0,G);break}case"list_transactional_emails":{let G=Y.companyId;X=await B("GET","/api/v1/transactional",void 0,G);break}case"get_transactional_email":{let G=Y.companyId;X=await B("GET",`/api/v1/transactional/${Y.idOrSlug}`,void 0,G);break}case"create_transactional_email":{let G=Y.companyId,$=new Set(["companyId","name","slug","subject","previewText","html","blocks","prompt","style","tone","enabled"]),z=Object.keys(Y).filter((H)=>!$.has(H));if(z.length>0)throw Error(`\`create_transactional_email\` accepts only \`name\`, \`slug\`, \`subject\`, \`previewText\`, \`html\`, \`blocks\`, \`prompt\`, \`style\`, \`tone\`, and \`enabled\` fields. Unsupported field${z.length===1?"":"s"}: ${z.map((H)=>`\`${H}\``).join(", ")}.`);hV(Y);let J=Object.fromEntries(Object.entries(Y).filter(([H])=>H!=="companyId"));X=await B("POST","/api/v1/transactional",J,G);break}case"update_transactional_email":{let G=Y.companyId,$=new Set(["companyId","idOrSlug","name","enabled","subject","previewText","html","blocks"]),z=Object.keys(Y).filter((H)=>!$.has(H));if(z.length>0)throw Error(`\`update_transactional_email\` accepts only \`name\`, \`enabled\`, \`subject\`, \`previewText\`, \`html\`, and \`blocks\` update fields. Unsupported field${z.length===1?"":"s"}: ${z.map((H)=>`\`${H}\``).join(", ")}.`);if(w1("update_transactional_email",Y),Y.name===void 0&&Y.enabled===void 0&&Y.subject===void 0&&Y.previewText===void 0&&Y.html===void 0&&Y.blocks===void 0)throw Error("Provide at least one of `name`, `enabled`, `subject`, `previewText`, `html`, or `blocks` when calling `update_transactional_email`.");let J=Object.fromEntries(Object.entries(Y).filter(([H])=>H!=="companyId"&&H!=="idOrSlug"));X=await B("PATCH",`/api/v1/transactional/${Y.idOrSlug}`,J,G);break}case"send_email":{let G=Y.companyId;X=await B("POST","/api/v1/transactional/send",Y,G);break}case"get_stats":{let G=Y.companyId,$=Y.period??"7d",z=new URLSearchParams({period:String($)});if(Y.includeMachineEngagement===!0)z.set("includeMachineEngagement","true");X=await B("GET",`/api/v1/metrics?${z.toString()}`,void 0,G);break}case"get_campaign_stats":{let G=Y.companyId,$=new URLSearchParams;if(Y.includeMachineEngagement===!0)$.set("includeMachineEngagement","true");let z=$.toString();X=await B("GET",`/api/v1/metrics/campaigns/${Y.campaignId}${z?`?${z}`:""}`,void 0,G);break}case"get_sequence_stats":{let G=Y.companyId,$=new URLSearchParams;if(Y.includeMachineEngagement===!0)$.set("includeMachineEngagement","true");let z=$.toString();X=await B("GET",`/api/v1/metrics/sequences/${Y.sequenceId}${z?`?${z}`:""}`,void 0,G);break}case"list_campaign_events":{let G=Y.companyId,$=R("list_campaign_events",Y,"campaignId"),J=GH("list_campaign_events",Y).toString();X=await B("GET",`/api/v1/metrics/campaigns/${encodeURIComponent($)}/events${J?`?${J}`:""}`,void 0,G);break}case"list_sequence_events":{let G=Y.companyId,$=R("list_sequence_events",Y,"sequenceId"),J=GH("list_sequence_events",Y).toString();X=await B("GET",`/api/v1/metrics/sequences/${encodeURIComponent($)}/events${J?`?${J}`:""}`,void 0,G);break}case"get_subscriber_activity":{let G=Y.companyId,$=v1("get_subscriber_activity",Y),z=await dY($,G,{includeMachineEngagement:Y.includeMachineEngagement===!0});X={success:z.success,email:z.subscriber.email,emailStats:z.subscriber.emailStats??null,activity:z.subscriber.activity??[],sequenceEnrollments:z.subscriber.sequenceEnrollments??[]};break}case"list_team_members":{let G=Y.companyId;X=await B("GET","/api/v1/team",void 0,G);break}case"invite_team_member":{let G=Y.companyId,$=R("invite_team_member",Y,"email"),z=oY("invite_team_member",Y,"role",["admin","viewer","restricted"]);if(Y.canManageBilling!==void 0&&typeof Y.canManageBilling!=="boolean")throw Error("`canManageBilling` must be a boolean when calling `invite_team_member`.");X=await B("POST","/api/v1/team/invitations",{email:$,role:z,...Y.canManageBilling!==void 0&&{canManageBilling:Y.canManageBilling}},G);break}case"cancel_team_invitation":{let G=Y.companyId,$=R("cancel_team_invitation",Y,"invitationId");X=await B("DELETE",`/api/v1/team/invitations/${encodeURIComponent($)}`,void 0,G);break}case"list_conversations":{let G=Y.companyId,$=new URLSearchParams,z=m0("list_conversations",Y,"status",["open","closed","all"]);if(z)$.set("status",z);let J=w(Y,"search");if(J)$.set("search",J);if(Y.unread!==void 0){if(typeof Y.unread!=="boolean")throw Error("`unread` must be a boolean when calling `list_conversations`.");if(Y.unread)$.set("unread","true")}if(Y.page!==void 0){if(typeof Y.page!=="number"||!Number.isInteger(Y.page)||Y.page<1)throw Error("`page` must be a positive integer when calling `list_conversations`.");$.set("page",String(Y.page))}let H=x1("list_conversations",Y,"limit",1,100);if(H!==void 0)$.set("limit",String(H));X=await B("GET",`/api/v1/conversations${$.size>0?`?${$}`:""}`,void 0,G);break}case"get_conversation":{let G=Y.companyId,$=R("get_conversation",Y,"conversationId");X=await B("GET",`/api/v1/conversations/${encodeURIComponent($)}`,void 0,G);break}case"reply_to_conversation":{let G=Y.companyId,$=R("reply_to_conversation",Y,"conversationId"),z=m0("reply_to_conversation",Y,"type",["outbound","note"])??"outbound",J=w(Y,"subject"),H=w(Y,"bodyText"),A=w(Y,"bodyHtml");if(z==="outbound"&&H===void 0&&A===void 0)throw Error("Provide `bodyText` or `bodyHtml` when calling `reply_to_conversation` with an outbound message.");X=await B("POST",`/api/v1/conversations/${encodeURIComponent($)}/messages`,{type:z,...J!==void 0&&{subject:J},...H!==void 0&&{bodyText:H},...A!==void 0&&{bodyHtml:A}},G);break}case"update_conversation_status":{let G=Y.companyId,$=R("update_conversation_status",Y,"conversationId"),z=oY("update_conversation_status",Y,"status",["open","closed"]);X=await B("POST",`/api/v1/conversations/${encodeURIComponent($)}/status`,{status:z},G);break}case"mark_conversation_read":{let G=Y.companyId,$=R("mark_conversation_read",Y,"conversationId");X=await B("POST",`/api/v1/conversations/${encodeURIComponent($)}/read`,void 0,G);break}case"list_webhooks":{let G=Y.companyId;X=await B("GET","/api/v1/webhooks",void 0,G);break}case"create_webhook":{let G=Y.companyId,$=R("create_webhook",Y,"name"),z=R("create_webhook",Y,"url"),J=$H("create_webhook",Y);X=await B("POST","/api/v1/webhooks",{name:$,url:z,...J!==void 0&&{events:J}},G);break}case"update_webhook":{let G=Y.companyId,$=R("update_webhook",Y,"webhookId"),z=w(Y,"name"),J=w(Y,"url"),H=$H("update_webhook",Y),A=m0("update_webhook",Y,"status",["enabled","disabled"]);if(z===void 0&&J===void 0&&H===void 0&&A===void 0)throw Error("Provide at least one of `name`, `url`, `events`, or `status` when calling `update_webhook`.");X=await B("PATCH",`/api/v1/webhooks/${encodeURIComponent($)}`,{...z!==void 0&&{name:z},...J!==void 0&&{url:J},...H!==void 0&&{events:H},...A!==void 0&&{status:A}},G);break}case"delete_webhook":{let G=Y.companyId,$=R("delete_webhook",Y,"webhookId");X=await B("DELETE",`/api/v1/webhooks/${encodeURIComponent($)}`,void 0,G);break}case"test_webhook":{let G=Y.companyId,$=R("test_webhook",Y,"webhookId");X=await B("POST",`/api/v1/webhooks/${encodeURIComponent($)}/test`,void 0,G);break}case"list_webhook_deliveries":{let G=Y.companyId,$=R("list_webhook_deliveries",Y,"webhookId"),z=x1("list_webhook_deliveries",Y,"limit",1,100),J=new URLSearchParams;if(z!==void 0)J.set("limit",String(z));X=await B("GET",`/api/v1/webhooks/${encodeURIComponent($)}/deliveries${J.size>0?`?${J}`:""}`,void 0,G);break}case"replay_webhook_delivery":{let G=Y.companyId,$=R("replay_webhook_delivery",Y,"webhookId"),z=R("replay_webhook_delivery",Y,"deliveryId");X=await B("POST",`/api/v1/webhooks/${encodeURIComponent($)}/deliveries/${encodeURIComponent(z)}/replay`,void 0,G);break}case"generate_email":{let G=Y.companyId;X=await B("POST","/api/v1/generate/email",Y,G);break}case"generate_sequence":{let G=Y.companyId;X=await B("POST","/api/v1/generate/sequence",Y,G);break}case"generate_subject_lines":{let G=Y.companyId;X=await B("POST","/api/v1/generate/subjects",Y,G);break}case"generate_sms":{let G=Y.companyId;X=await B("POST","/api/v1/generate/sms",Y,G);break}case"get_sms_settings":{let G=Y.companyId;X=await B("GET","/api/v1/sms/settings",void 0,G);break}case"send_test_sms":{let G=Y.companyId,$={to:R("send_test_sms",Y,"to")};for(let z of["text","imageUrls","blocks"])if(Y[z]!==void 0)$[z]=Y[z];X=await B("POST","/api/v1/sms/test",$,G);break}case"submit_feedback":{let G=Y.companyId,$={message:R("submit_feedback",Y,"message"),source:"mcp"};for(let z of["category","context"])if(Y[z]!==void 0)$[z]=Y[z];X=await B("POST","/api/v1/feedback",$,G);break}default:throw Error(`Unknown tool: ${Q}`)}let W=fV(X);if(W)throw W;return X=await sV(Q,Y,X),{structuredContent:HZ(X),content:[{type:"text",text:JSON.stringify(X,null,2)}]}}catch(X){return{isError:!0,content:[{type:"text",text:$1(X)}]}}}async function DH(Q,Y,X){let W=Y.getRequestContext?.(Q)??{};try{return await SQ(W,X)}finally{await Y.onRequestContextUpdated?.(W,Q)}}function HX(Q={}){let Y=new lY({name:"sequenzy",version:p5.version},{capabilities:{tools:{},resources:{}},instructions:["Sequenzy email marketing MCP server: manage subscribers, campaigns, sequences, templates, and delivery stats.","If you have access to multiple companies, call get_account and then select_company (or pass companyId per call) before other tools.","IMPORTANT: whenever the user wanted to accomplish something and these tools did not expose functionality for it (missing tool, missing argument, unsupported workflow, or broken behavior), call submit_feedback describing the gap before finishing the task. The Sequenzy team reads every submission and uses it to decide what to build next."].join(`
191
- `)});return Y.setRequestHandler(T9,async()=>{return{tools:UH}}),Y.setRequestHandler(I4,async(X,W)=>{let{name:G,arguments:$}=X.params;return DH(W,Q,()=>KH(G,$??{}))}),Y.setRequestHandler(N9,async()=>{return{resources:r5}}),Y.setRequestHandler(P9,async(X,W)=>{let{uri:G}=X.params;return DH(W,Q,()=>d5(G))}),Y}import LH from"node:process";class AX{append(Q){this._buffer=this._buffer?Buffer.concat([this._buffer,Q]):Q}readMessage(){if(!this._buffer)return null;let Q=this._buffer.indexOf(`
192
- `);if(Q===-1)return null;let Y=this._buffer.toString("utf8",0,Q).replace(/\r$/,"");return this._buffer=this._buffer.subarray(Q+1),UZ(Y)}clear(){this._buffer=void 0}}function UZ(Q){return eG.parse(JSON.parse(Q))}function BH(Q){return JSON.stringify(Q)+`
193
- `}class UX{constructor(Q=LH.stdin,Y=LH.stdout){this._stdin=Q,this._stdout=Y,this._readBuffer=new AX,this._started=!1,this._ondata=(X)=>{this._readBuffer.append(X),this.processReadBuffer()},this._onerror=(X)=>{this.onerror?.(X)}}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 Q=this._readBuffer.readMessage();if(Q===null)break;this.onmessage?.(Q)}catch(Q){this.onerror?.(Q)}}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(Q){return new Promise((Y)=>{let X=BH(Q);if(this._stdout.write(X))Y();else this._stdout.once("drain",Y)})}}async function KZ(){ZX(),qX();let Q=HX(),Y=new UX;await Q.connect(Y),console.error("Sequenzy MCP server running on stdio")}KZ().catch((Q)=>{console.error($1(Q)),process.exit(1)});export{SQ as withMcpRequestContext,Q6 as setSelectedCompanyId,b1 as getSelectedCompanyId,HX as createSequenzyMcpServer,B as apiRequest};
190
+ - contact.subscribed, contact.unsubscribed`,inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the sequence in. If not provided, uses the currently selected company."},fromEmail:{type:"string",description:"From address for all emails in this sequence. Its domain must be configured and verified."},fromName:{type:"string",description:"Display name for a newly created sender profile. Requires fromEmail."},senderProfileId:{type:"string",description:"Existing sender profile ID. Mutually exclusive with fromEmail."},replyTo:{type:"string",description:"Reply-To address for all emails in this sequence. A reply profile is created when needed."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo."},replyProfileId:{type:"string",description:"Existing reply profile ID. Mutually exclusive with replyTo."},name:{type:"string",description:"Sequence name (e.g., 'User Onboarding', 'Welcome Series')"},trigger:{type:"string",enum:["contact_added","tag_added","segment_entered","event_received","inactivity","frequency"],description:"Trigger type: 'contact_added' (when added to a list), 'tag_added' (when tag is applied), 'segment_entered' (when a contact newly enters a saved segment), 'event_received' (when custom event fires), 'inactivity' (when subscriber hasn't performed an event for X days), 'frequency' (when subscriber performs event X times in Y days)"},listId:{type:"string",description:"List ID to trigger on (for contact_added trigger). If not provided, triggers on any list."},tagName:{type:"string",description:"Tag name to trigger on (required for tag_added trigger)"},segmentId:{type:"string",description:"Segment ID to trigger on (required for segment_entered trigger). Use list_segments first to choose a saved segment."},eventName:{type:"string",description:"Event name to trigger on (required for event_received, inactivity, and frequency triggers)"},propertyFilters:{type:"array",description:"Optional event property filters for event_received triggers. The sequence only starts when the triggering event's properties match ALL filters. Use a dot-path into the event properties; use [] to match inside arrays. Examples: scope a purchase sequence to one product with { path: 'lineItems[].providerProductId', operator: 'equals', value: 'prod_123' } (ecommerce.order_placed) or { path: 'productIds', operator: 'equals', value: 'prod_123' } (saas.purchase); to match any of several products use { path: 'lineItems[].providerProductId', operator: 'one_of', value: ['prod_123', 'prod_456'] }. Max 10 filters.",items:{type:"object",properties:{path:{type:"string",description:"Dot-path into the event properties, e.g. 'lineItems[].providerProductId' or 'plan'."},operator:{type:"string",enum:["exists","not_exists","equals","not_equals","one_of","contains","greater_than","less_than"],description:"Comparison operator. one_of matches when the property equals any entry of the value array."},value:{type:["string","number","boolean","array"],items:{type:["string","number"]},maxItems:50,description:"Value to compare against. Required for every operator except exists/not_exists. For one_of, pass an array of strings or numbers (max 50 values); all other operators take a single value."}},required:["path","operator"]}},inactiveDays:{type:"number",description:"Number of days of inactivity (required for inactivity trigger, must be >= 1)"},inactivityBaseline:{type:"string",enum:["sequence_created_at","subscriber_created_at"],description:"When to start counting inactivity for subscribers who never had the event. Defaults to sequence_created_at."},minCount:{type:"number",description:"Minimum event count (required for frequency trigger, must be >= 1)"},timeWindowDays:{type:"number",description:"Time window in days for frequency trigger (required for frequency trigger, must be >= 1)"},emailCount:{type:"number",description:"Number of emails in the sequence (default: 5, max: 10)"},durationDays:{type:"number",description:"Total duration in days used to space AI-generated sequence emails. Only applies when using goal-based AI generation."},goal:{type:"string",description:"What this sequence should accomplish for AI generation. Be specific to the app's actual features and user journey. Avoid generic goals that don't match the app's business model."},enrollmentMode:{type:"string",enum:["unlimited","one_time","matching_field"],description:"Sequence re-entry mode. Use 'matching_field' only for event_received triggers when duplicate active runs should be blocked per event field value."},enrollmentFieldPath:{type:"string",description:"Dot-path event property used by enrollmentMode='matching_field', such as 'order.id' or 'product.providerVariantId'. Leave omitted for Shopify back-in-stock/replenishment product-variant defaults."},sendingWindow:e5,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:WX,subject:{type:"string",description:"Email subject. Required for email steps."},previewText:{type:"string",description:"Email preview text."},blocks:{type:"array",description:aY,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:eY,delayMs:{type:"number",description:"Delay before this step in milliseconds. Prefer delay for readability; use delayMs when importing provider waits."},waitUntil:sY,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"]}},{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:"Dot-path event property used by enrollmentMode='matching_field', such as 'order.id' or 'product.providerVariantId'. 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:e5,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:dY}},required:["conditionType"]}},elseSteps:{type:"array",description:"Steps to create inside the else fallback path. Required by default so the else arm is usable.",items:dY},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:dY}},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:Q4,items:{type:"object"}},...$H}}},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:Q4,items:{type:"object"}},...$H}}},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:WX},required:["nodeId","config"]}}},required:["sequenceId"]}},{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:aY,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:eY,delayMs:{type:"number",description:"Optional wait in milliseconds before the new step. Prefer delay for readability."},waitUntil:sY},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"]}},{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:`${s4} 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:`${Q4} Mutually exclusive with \`html\`.`,items:{type:"object"}}},required:["idOrSlug"],additionalProperties:!1}},{name:"send_email",description:"Send a transactional email to a single recipient",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},to:{type:"string",description:"Recipient email address"},subject:{type:"string",description:"Email subject (required if not using templateId)"},html:{type:"string",description:"Email HTML content (required if not using templateId)"},templateId:{type:"string",description:"Template ID to use (alternative to html)"},variables:{type:"object",description:"Variables for template personalization. Nested objects and arrays are supported for repeat blocks, for example { items: [...] }."},subscriberExternalId:{type:"string",description:"Customer-owned subscriber ID for attaching analytics/localization on single-recipient sends. Maximum length: 255 characters."}},required:["to"]}},{name:"get_stats",description:"Get overview statistics for a time period",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},period:{type:"string",description:"Time period: 7d, 30d, or 90d (default: 7d)"},includeMachineEngagement:N1}}},{name:"get_campaign_stats",description:"Get detailed statistics for a campaign, including attributed conversions and revenue (revenueCents)",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:N1},required:["campaignId"]}},{name:"get_sequence_stats",description:"Get statistics for a sequence, including attributed conversions and revenue (revenueCents) plus per-step failed subscribers and failure reasons",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"},includeMachineEngagement:N1},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:N1},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:N1},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:N1},required:[]}},{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"]}},{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"]}},{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:[...PQ]},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:[...PQ]},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"]}},{name:"generate_email",description:"Generate email blocks from a prompt. Generated blocks include the company's branding chrome (logo, footer with company name/address/unsubscribe) by default, matching emails created in the dashboard.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},prompt:{type:"string",description:"Description of the email to generate"},style:{type:"string",description:"Style: minimal, branded, promotional"},tone:{type:"string",description:"Tone: professional, casual, friendly"},applyBranding:{type:"boolean",description:"Wrap the generated content with company branding (logo + footer). Defaults to true; set false to get raw content blocks only."},emailType:{type:"string",enum:["marketing","transactional"],description:"Email type. Transactional emails get a footer without the unsubscribe link. Defaults to marketing."}},required:["prompt"]}},{name:"generate_sequence",description:"[DEPRECATED - Use create_sequence instead] Generate a multi-email sequence from a goal. Note: create_sequence now handles AI generation automatically.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},goal:{type:"string",description:"Goal of the sequence (e.g., 'onboard new SaaS trial users')"},emailCount:{type:"number",description:"Number of emails in the sequence (default: 5, max: 10)"},durationDays:{type:"number",description:"Total duration in days (default: 14)"}},required:["goal"]}},{name:"generate_subject_lines",description:"Generate A/B test subject line variants",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},topic:{type:"string",description:"Topic or context for the subject lines"},count:{type:"number",description:"Number of variants to generate (default: 5)"}},required:["topic"]}},{name:"generate_sms",description:"Generate SMS marketing message variants from a prompt. Returns plain-text messages with per-message encoding and segment counts. Use the results as the 'text' of an SMS sequence step (insert_sequence_step with type 'sms' or a create_sequence sms step). Messages exclude opt-out footers and brand prefixes - the platform adds those automatically at send time.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},prompt:{type:"string",description:"Description of the SMS to generate (e.g., 'cart reminder with a free-shipping hook')"},count:{type:"number",description:"Number of message variants to generate (default: 3, max: 10)"}},required:["prompt"]}},{name:"get_sms_settings",description:"Get the company's SMS add-on status: whether SMS is enabled, plan eligibility, credit balance, brand prefix, phone numbers, and whether SMS steps will actually send. Check this before adding SMS steps to sequences so you can warn the user when SMS is not ready.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"send_test_sms",description:"Send a test SMS to a phone number. IMPORTANT: sends a real text message and charges SMS credits - only call when the user explicitly asks for a test send. Requires the SMS add-on with a verified number (check get_sms_settings). Limited to 5 test sends per hour; bypasses quiet hours; excluded from step stats.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},to:{type:"string",description:"Destination phone number in international E.164 format, e.g. +15550100123."},text:{type:"string",description:"Plain-text message body. Merge tags are not resolved for test sends to arbitrary numbers. Provide text or blocks."},imageUrls:{type:"array",items:{type:"string"},description:"Up to 2 publicly reachable image URLs sent as MMS media (US/CA only)."},blocks:{type:"array",items:{type:"object"},description:"SMS content blocks (text + image subset). Provide text or blocks, not both."}},required:["to"]}},{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"]}}],qH=MZ.map(qZ).map(wV);async function OH(Q,Y){try{let X;switch(Q){case"get_account":{let G=await B("GET","/api/v1/account"),$=b1();X={...G,selectedCompanyId:$??G.currentCompanyId};break}case"select_company":{let G=Y.companyId,$=await B("GET","/api/v1/account"),z=$.companies?.find((J)=>J.id===G);if(!z)throw Error(`Company not found. Available companies: ${$.companies?.map((J)=>`${J.name} (${J.id})`).join(", ")??"none"}`);Q6(G),X={success:!0,message:`Switched to company: ${z.name}`,companyId:z.id,companyName:z.name};break}case"get_app_urls":{let G=await AX(Y);X={...Z1({companyId:G,campaignId:w(Y,"campaignId"),landingPageId:w(Y,"landingPageId"),sequenceId:w(Y,"sequenceId"),emailId:w(Y,"emailId")??w(Y,"templateId"),transactionalId:w(Y,"transactionalId"),emailSendId:w(Y,"emailSendId"),domainId:w(Y,"domainId"),status:w(Y,"status"),settingsTab:w(Y,"settingsTab")}),...G===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 G=await B("POST","/api/v1/companies",{name:Y.name,domain:Y.domain});if(!G.success)throw Error("Failed to create company");let $=G.company.id,z=6,J=0,H=G.company.status;while(H==="processing"&&J<z){await new Promise((K)=>setTimeout(K,20000)),J++;let U=await B("GET",`/api/v1/companies/${$}`);if(U.success)H=U.company.status}Q6($);let A=await B("GET",`/api/v1/companies/${$}`);X={success:!0,company:A.company,message:H==="processing"?"Company created but still processing. You can continue using it while processing completes.":`Company '${A.company.name}' created and ready to use.`,autoSelected:!0};break}case"get_company":{let G=Y.companyId;X=await B("GET",`/api/v1/companies/${G}`);break}case"update_company":{let G=await $Z("update_company",Y),$=yV(Y);X=await B("PATCH",`/api/v1/companies/${G}`,$);break}case"get_sync_rules":{let G=Y.companyId;X=await B("GET","/api/v1/sync-rules",void 0,G);break}case"update_sync_rules":{let G=Y.companyId;if(Y.syncRules!==null&&!Array.isArray(Y.syncRules))throw Error("`syncRules` must be an array of rules or null when calling `update_sync_rules`.");X=await B("PUT","/api/v1/sync-rules",{syncRules:Y.syncRules},G);break}case"get_shopify_automation_settings":{let G=Y.companyId;X=await B("GET","/api/v1/shopify/automation-settings",void 0,G);break}case"update_shopify_automation_settings":{let G=Y.companyId,$={};if(Y.browseAbandonment!==void 0)$.browseAbandonment=Y.browseAbandonment;if(Y.priceDrop!==void 0)$.priceDrop=Y.priceDrop;if(Object.keys($).length===0)throw Error("Provide `browseAbandonment` and/or `priceDrop` when calling `update_shopify_automation_settings`.");X=await B("PUT","/api/v1/shopify/automation-settings",$,G);break}case"create_api_key":{let G=Y.companyId,$={};if(typeof Y.name==="string")$.name=Y.name;if(typeof Y.preset==="string")$.preset=Y.preset;if(Array.isArray(Y.scopes))$.scopes=Y.scopes;X=await B("POST","/api/v1/api-keys",$,G);break}case"list_websites":{let G=Y.companyId;X=await B("GET","/api/v1/websites",void 0,G);break}case"add_sending_domain":case"add_website":{let G=Y.companyId;X=await B("POST","/api/v1/websites",{domain:Y.domain},G);break}case"check_website":{let G=Y.companyId;X=await B("GET",`/api/v1/websites/${encodeURIComponent(String(Y.domain))}`,void 0,G);break}case"verify_sending_domain":{let G=Y.companyId;X=await B("POST",`/api/v1/websites/${encodeURIComponent(String(Y.domain))}/verify`,void 0,G);break}case"get_integration_guide":X=await B("POST","/api/v1/integration-guide",Y);break;case"add_subscriber":{let G=Y.companyId,$=v1("add_subscriber",Y);X=await B("POST","/api/v1/subscribers",{...$,customAttributes:Y.attributes,tags:Y.tags,lists:Y.listIds,...Y.status!==void 0&&{status:Y.status},...Y.optInMode!==void 0&&{optInMode:Y.optInMode}},G);break}case"update_subscriber":{let G=Y.companyId,$=v1("update_subscriber",Y),z=await oY($,G),J=Array.isArray(z.subscriber.tags)?z.subscriber.tags.filter((D)=>typeof D==="string"):[],H=Array.isArray(Y.addTags)?Y.addTags.filter((D)=>typeof D==="string"&&D.trim()!=="").map(zH):[],A=new Set(Array.isArray(Y.removeTags)?Y.removeTags.filter((D)=>typeof D==="string"&&D.trim()!=="").map(zH):[]),U=J.filter((D)=>!A.has(D));for(let D of H)if(!U.includes(D))U.push(D);let K={};if($.email&&$.externalId)K.externalId=$.externalId;if(Y0(Y.attributes))K.customAttributes={...Y0(z.subscriber.customAttributes)?z.subscriber.customAttributes:{},...Y.attributes};if(Y.addTags||Y.removeTags)K.tags=U;X=await B("PATCH",GX($),K,G);break}case"remove_subscriber":{let G=Y.companyId,$=v1("remove_subscriber",Y),z=GX($);if(Y.hardDelete===!0)X=await B("DELETE",z,void 0,G);else X=await B("PATCH",z,{status:"unsubscribed"},G);break}case"get_subscriber":{let G=Y.companyId,$=v1("get_subscriber",Y);X=await oY($,G,{includeMachineEngagement:Y.includeMachineEngagement===!0});break}case"list_subscriber_notes":{let G=Y.companyId,$=v1("list_subscriber_notes",Y);X=await B("GET",JH($),void 0,G);break}case"add_subscriber_note":{let G=Y.companyId,$=v1("add_subscriber_note",Y),z=typeof Y.body==="string"?Y.body.trim():void 0;if(!z)throw Error("`body` is required when calling `add_subscriber_note`.");if(z.length>5000)throw Error("`body` must be 5000 characters or fewer when calling `add_subscriber_note`.");X=await B("POST",JH($),{body:z},G);break}case"delete_subscriber_note":{let G=Y.companyId,$=typeof Y.noteId==="string"?Y.noteId.trim():"";if(!$)throw Error("`noteId` is required when calling `delete_subscriber_note`.");X=await B("DELETE",`/api/v1/subscribers/notes/${encodeURIComponent($)}`,void 0,G);break}case"search_subscribers":{let G=Y.companyId;X=await aV(Y,G);break}case"list_products":{let G=Y.companyId,$=new URLSearchParams;if(typeof Y.provider==="string"&&Y.provider.trim())$.set("provider",Y.provider.trim());if(typeof Y.search==="string"&&Y.search.trim())$.set("search",Y.search.trim());let z=$.size>0?`?${$.toString()}`:"";X=await B("GET",`/api/v1/products${z}`,void 0,G);break}case"upsert_products":{let G=Y.companyId;if(!Array.isArray(Y.products)||Y.products.length===0)throw Error("`products` must be a non-empty array when calling `upsert_products`.");X=await B("POST","/api/v1/products",{products:Y.products},G);break}case"delete_product":{let G=Y.companyId,$=R("delete_product",Y,"productId");X=await B("DELETE",`/api/v1/products/${encodeURIComponent($)}`,void 0,G);break}case"attach_product_file":{let G=Y.companyId,$=R("attach_product_file",Y,"productId"),z=w(Y,"url"),J=w(Y,"filePath");if(z===void 0===(J===void 0))throw Error("Provide either `url` or `filePath` (not both) when calling `attach_product_file`.");let H;if(J!==void 0){let A=await GZ(J,G);H={url:A.url,source:"upload",fileName:w(Y,"fileName")??A.fileName,fileSizeBytes:A.fileSizeBytes,mimeType:A.mimeType}}else{H={url:z};let A=w(Y,"fileName");if(A)H.fileName=A}X=await B("PUT",`/api/v1/products/${encodeURIComponent($)}/delivery`,H,G);break}case"remove_product_file":{let G=Y.companyId,$=R("remove_product_file",Y,"productId");X=await B("DELETE",`/api/v1/products/${encodeURIComponent($)}/delivery`,void 0,G);break}case"sync_products":{let G=Y.companyId;X=await B("POST","/api/v1/products/sync",void 0,G);break}case"list_tags":{let G=Y.companyId;X=await B("GET","/api/v1/tags",void 0,G);break}case"create_tag":{let G=Y.companyId,$=R("create_tag",Y,"name"),z=m0("create_tag",Y,"color",wQ);X=await B("POST","/api/v1/tags",{name:$,...z!==void 0&&{color:z}},G);break}case"update_tag":{let G=Y.companyId,$=R("update_tag",Y,"tagId"),z=tY("update_tag",Y,"color",wQ);X=await B("PATCH",`/api/v1/tags/${encodeURIComponent($)}`,{color:z},G);break}case"delete_tag":{let G=Y.companyId,$=R("delete_tag",Y,"tagId");X=await B("DELETE",`/api/v1/tags/${encodeURIComponent($)}`,void 0,G);break}case"list_lists":{let G=Y.companyId;X=await B("GET","/api/v1/lists",void 0,G);break}case"create_list":{let G=Y.companyId;X=await B("POST","/api/v1/lists",Y,G);break}case"update_list":{let G=Y.companyId,$=R("update_list",Y,"listId");if(Y.name===void 0&&Y.description===void 0&&Y.isPrivate===void 0)throw Error("Provide at least one of `name`, `description`, or `isPrivate` when calling `update_list`.");if(Y.name!==void 0&&w(Y,"name")===void 0)throw Error("`name` cannot be empty when calling `update_list`.");if(Y.description!==void 0&&Y.description!==null&&typeof Y.description!=="string")throw Error("`description` must be a string or null when calling `update_list`.");if(Y.isPrivate!==void 0&&typeof Y.isPrivate!=="boolean")throw Error("`isPrivate` must be a boolean when calling `update_list`.");X=await B("PATCH",`/api/v1/lists/${encodeURIComponent($)}`,{...Y.name!==void 0&&{name:w(Y,"name")},...Y.description!==void 0&&{description:Y.description},...Y.isPrivate!==void 0&&{isPrivate:Y.isPrivate}},G);break}case"delete_list":{let G=Y.companyId,$=R("delete_list",Y,"listId");X=await B("DELETE",`/api/v1/lists/${encodeURIComponent($)}`,void 0,G);break}case"add_subscribers_to_list":{let G=Y.companyId,$=R("add_subscribers_to_list",Y,"listId"),z=UH("add_subscribers_to_list",Y),J=m0("add_subscribers_to_list",Y,"duplicateStrategy",["skip","merge","overwrite"])??"skip",H=m0("add_subscribers_to_list",Y,"optInMode",["default","confirmed","double_opt_in"])??"default";X=await B("POST",`/api/v1/lists/${encodeURIComponent($)}/subscribers`,{emails:z,duplicateStrategy:J,enrollInSequences:Y.enrollInSequences===!0,optInMode:H},G);break}case"remove_subscribers_from_list":{let G=Y.companyId,$=R("remove_subscribers_from_list",Y,"listId"),z=UH("remove_subscribers_from_list",Y);X=await B("POST",`/api/v1/lists/${encodeURIComponent($)}/subscribers/remove`,{emails:z},G);break}case"list_segments":{let G=Y.companyId;X=await B("GET","/api/v1/segments",void 0,G);break}case"create_segment":{_V(Y);let G=Y.companyId;X=await B("POST","/api/v1/segments",{...Y,...Y.filters!==void 0?{filters:YX(Y.filters)}:{},...Y.root!==void 0?{root:XX(Y.root)}:{}},G);break}case"update_segment":{gV(Y);let G=Y.companyId,$=R("update_segment",Y,"segmentId"),z=w(Y,"name"),J=m0("update_segment",Y,"filterJoinOperator",["and","or"]);X=await B("PATCH",`/api/v1/segments/${encodeURIComponent($)}`,{...z!==void 0&&{name:z},...J!==void 0&&{filterJoinOperator:J},...Y.filters!==void 0?{filters:YX(Y.filters)}:{},...Y.root!==void 0?{root:XX(Y.root)}:{}},G);break}case"delete_segment":{let G=Y.companyId,$=R("delete_segment",Y,"segmentId");X=await B("DELETE",`/api/v1/segments/${encodeURIComponent($)}`,void 0,G);break}case"get_segment_count":{let G=Y.companyId;X=await B("GET",`/api/v1/segments/${Y.segmentId}/count`,void 0,G);break}case"list_audience_syncs":{let G=Y.companyId;X=await B("GET","/api/v1/audience-syncs",void 0,G);break}case"list_ad_accounts":{let G=Y.companyId;X=await B("GET","/api/v1/ad-accounts",void 0,G);break}case"create_audience_sync":{let G=Y.companyId,$=w(Y,"segmentId"),z=w(Y,"predefinedSegmentId");if($&&z)throw Error("Provide either `segmentId` or `predefinedSegmentId` when calling `create_audience_sync`, not both.");if(!$&&!z)throw Error("Provide either `segmentId` or `predefinedSegmentId` when calling `create_audience_sync`.");X=await B("POST","/api/v1/audience-syncs",{segmentId:$,predefinedSegmentId:z,adAccountId:R("create_audience_sync",Y,"adAccountId"),audienceName:R("create_audience_sync",Y,"audienceName"),...Y.frequency!==void 0?{frequency:Y.frequency}:{}},G);break}case"update_audience_sync":{let G=Y.companyId,$=R("update_audience_sync",Y,"syncId");X=await B("PATCH",`/api/v1/audience-syncs/${encodeURIComponent($)}`,{...Y.frequency!==void 0?{frequency:Y.frequency}:{},...Y.isActive!==void 0?{isActive:Y.isActive}:{}},G);break}case"delete_audience_sync":{let G=Y.companyId,$=R("delete_audience_sync",Y,"syncId");X=await B("DELETE",`/api/v1/audience-syncs/${encodeURIComponent($)}`,void 0,G);break}case"sync_audience_now":{let G=Y.companyId,$=R("sync_audience_now",Y,"syncId");X=await B("POST",`/api/v1/audience-syncs/${encodeURIComponent($)}/sync`,void 0,G);break}case"list_templates":{let G=Y.companyId,$=new URLSearchParams,z=w(Y,"label");if(z)$.set("label",z);X=await B("GET",`/api/v1/templates${$.size>0?`?${$}`:""}`,void 0,G);break}case"get_template":{let G=Y.companyId;X=await B("GET",`/api/v1/templates/${Y.templateId}`,void 0,G);break}case"create_template":{let G=Y.companyId;iV(Y);let $=Object.fromEntries(Object.entries(Y).filter(([z])=>z!=="companyId"));X=await B("POST","/api/v1/templates",$,G);break}case"update_template":{let G=Y.companyId,$=new Set(["companyId","templateId","name","subject","html","blocks","labels"]),z=Object.keys(Y).filter((J)=>!$.has(J));if(z.length>0)throw Error(`\`update_template\` accepts only \`name\`, \`subject\`, \`html\`, \`blocks\`, and \`labels\` update fields. Unsupported field${z.length===1?"":"s"}: ${z.map((J)=>`\`${J}\``).join(", ")}.`);if(w1("update_template",Y),bQ("update_template",Y),Y.name===void 0&&Y.subject===void 0&&Y.html===void 0&&Y.blocks===void 0&&Y.labels===void 0)throw Error("Provide at least one of `name`, `subject`, `html`, `blocks`, or `labels` when calling `update_template`.");X=await B("PUT",`/api/v1/templates/${Y.templateId}`,Y,G);break}case"delete_template":{let G=Y.companyId;X=await B("DELETE",`/api/v1/templates/${Y.templateId}`,void 0,G);break}case"list_ab_tests":{let G=Y.companyId,$=new URLSearchParams,z=w(Y,"sequenceId");if(z)$.set("sequenceId",z);X=await B("GET",`/api/v1/ab-tests${$.size>0?`?${$}`:""}`,void 0,G);break}case"get_ab_test":{let G=Y.companyId;X=await B("GET",`/api/v1/ab-tests/${Y.abTestId}`,void 0,G);break}case"get_ab_test_stats":{let G=Y.companyId,$=new URLSearchParams,z=w(Y,"period"),J=w(Y,"start"),H=w(Y,"end");if(z)$.set("period",z);if(J)$.set("start",J);if(H)$.set("end",H);if(Y.includeMachineEngagement===!0)$.set("includeMachineEngagement","true");X=await B("GET",`/api/v1/ab-tests/${Y.abTestId}/stats${$.size>0?`?${$}`:""}`,void 0,G);break}case"restart_ab_test":{let G=Y.companyId,$=new Set(["companyId","abTestId","sourceVariantId","testType","winnerThreshold","variantCount"]),z=Object.keys(Y).filter((U)=>!$.has(U));if(z.length>0)throw Error(`\`restart_ab_test\` accepts only \`sourceVariantId\`, \`testType\`, \`winnerThreshold\`, and \`variantCount\` option fields. Unsupported field${z.length===1?"":"s"}: ${z.map((U)=>`\`${U}\``).join(", ")}.`);let J=w(Y,"testType");if(J!==void 0&&J!=="subject"&&J!=="content")throw Error("`restart_ab_test` testType must be `subject` or `content`.");let H=Y.winnerThreshold===void 0?void 0:Number(Y.winnerThreshold);if(H!==void 0&&(!Number.isInteger(H)||H<10||H>1000))throw Error("`restart_ab_test` winnerThreshold must be an integer from 10 to 1000.");let A=Y.variantCount===void 0?void 0:Number(Y.variantCount);if(A!==void 0&&(!Number.isInteger(A)||A<2||A>4))throw Error("`restart_ab_test` variantCount must be an integer from 2 to 4.");X=await B("POST",`/api/v1/ab-tests/${Y.abTestId}/restart`,{sourceVariantId:w(Y,"sourceVariantId"),testType:J,winnerThreshold:H,variantCount:A},G);break}case"update_ab_test_variant":{let G=Y.companyId,$=new Set(["companyId","abTestId","variantId","subject","previewText","html","blocks"]),z=Object.keys(Y).filter((J)=>!$.has(J));if(z.length>0)throw Error(`\`update_ab_test_variant\` accepts only \`subject\`, \`previewText\`, \`html\`, and \`blocks\` update fields. Unsupported field${z.length===1?"":"s"}: ${z.map((J)=>`\`${J}\``).join(", ")}.`);if(w1("update_ab_test_variant",Y),Y.subject===void 0&&Y.previewText===void 0&&Y.html===void 0&&Y.blocks===void 0)throw Error("Provide at least one of `subject`, `previewText`, `html`, or `blocks` when calling `update_ab_test_variant`.");X=await B("PATCH",`/api/v1/ab-tests/${Y.abTestId}/variants/${Y.variantId}`,Y,G);break}case"create_ab_test":{let G=Y.companyId,$=R("create_ab_test",Y,"campaignId"),z=w(Y,"name"),J=x1("create_ab_test",Y,"testPercentage",5,50),H=x1("create_ab_test",Y,"testDurationMinutes",15,1440),A=m0("create_ab_test",Y,"winnerCriteria",["open_rate","click_rate"]);if(Y.variants!==void 0){if(!Array.isArray(Y.variants))throw Error("`variants` must be an array when calling `create_ab_test`.");Y.variants.forEach((U,K)=>{if(!Y0(U)||typeof U.subject!=="string"||U.subject.trim()==="")throw Error(`\`variants\` item ${K+1} must include a non-empty \`subject\` when calling \`create_ab_test\`.`);if(U.blocks!==void 0&&!Array.isArray(U.blocks))throw Error(`\`variants\` item ${K+1} \`blocks\` must be an array when calling \`create_ab_test\`.`)})}X=await B("POST","/api/v1/ab-tests",{campaignId:$,...z!==void 0&&{name:z},...J!==void 0&&{testPercentage:J},...H!==void 0&&{testDurationMinutes:H},...A!==void 0&&{winnerCriteria:A},...Y.variants!==void 0&&{variants:Y.variants}},G);break}case"add_ab_test_variant":{let G=Y.companyId,$=R("add_ab_test_variant",Y,"abTestId"),z=R("add_ab_test_variant",Y,"subject"),J=w(Y,"previewText");if(Y.blocks!==void 0&&!Array.isArray(Y.blocks))throw Error("`blocks` must be an array when calling `add_ab_test_variant`.");X=await B("POST",`/api/v1/ab-tests/${encodeURIComponent($)}/variants`,{subject:z,...J!==void 0&&{previewText:J},...Y.blocks!==void 0&&{blocks:Y.blocks}},G);break}case"delete_ab_test_variant":{let G=Y.companyId,$=R("delete_ab_test_variant",Y,"abTestId"),z=R("delete_ab_test_variant",Y,"variantId");X=await B("DELETE",`/api/v1/ab-tests/${encodeURIComponent($)}/variants/${encodeURIComponent(z)}`,void 0,G);break}case"delete_ab_test":{let G=Y.companyId,$=R("delete_ab_test",Y,"abTestId");X=await B("DELETE",`/api/v1/ab-tests/${encodeURIComponent($)}`,void 0,G);break}case"list_campaigns":{let G=Y.companyId,$=new URLSearchParams;if(Y.status)$.set("status",String(Y.status));let z=w(Y,"label");if(z)$.set("label",z);X=await B("GET",`/api/v1/campaigns?${$}`,void 0,G);break}case"get_campaign":{let G=Y.companyId;X=await B("GET",`/api/v1/campaigns/${Y.campaignId}`,void 0,G);break}case"get_email_send":{let G=Y.companyId;X=await B("GET",`/api/v1/email-sends/${encodeURIComponent(String(Y.emailSendId))}`,void 0,G);break}case"create_campaign":{let G=Y.companyId;if(pV(Y),Y.fromEmail!==void 0&&Y.senderProfileId!==void 0)throw Error("Provide either `fromEmail` or `senderProfileId` when calling `create_campaign`, not both.");if(Y.replyTo!==void 0&&Y.replyProfileId!==void 0)throw Error("Provide either `replyTo` or `replyProfileId` when calling `create_campaign`, not both.");if(Y.fromName!==void 0&&Y.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `create_campaign`.");if(Y.replyToName!==void 0&&Y.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `create_campaign`.");let $=Object.fromEntries(Object.entries(Y).filter(([z])=>z!=="companyId"));X=await B("POST","/api/v1/campaigns",$,G);break}case"update_campaign":{let G=Y.companyId,$=new Set(["companyId","campaignId","name","subject","trackingCode","html","blocks","fromEmail","fromName","senderProfileId","replyTo","replyToName","replyProfileId","campaignData","computedLists","labels"]),z=Object.keys(Y).filter((J)=>!$.has(J));if(z.length>0)throw Error(`\`update_campaign\` accepts only content, sending identity, campaign data, computed list, and label update fields. Unsupported field${z.length===1?"":"s"}: ${z.map((J)=>`\`${J}\``).join(", ")}.`);if(w1("update_campaign",Y),bQ("update_campaign",Y),Y.replyTo!==void 0&&Y.replyProfileId!==void 0)throw Error("Provide either `replyTo` or `replyProfileId` when calling `update_campaign`, not both.");if(Y.fromEmail!==void 0&&Y.senderProfileId!==void 0)throw Error("Provide either `fromEmail` or `senderProfileId` when calling `update_campaign`, not both.");if(Y.fromName!==void 0&&Y.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `update_campaign`.");if(Y.replyToName!==void 0&&Y.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `update_campaign`.");if(Y.name===void 0&&Y.subject===void 0&&Y.trackingCode===void 0&&Y.html===void 0&&Y.blocks===void 0&&Y.fromEmail===void 0&&Y.senderProfileId===void 0&&Y.replyTo===void 0&&Y.replyProfileId===void 0&&Y.campaignData===void 0&&Y.computedLists===void 0&&Y.labels===void 0)throw Error("Provide at least one campaign content, sending identity, campaign data, computed list, or label field when calling `update_campaign`.");X=await B("PUT",`/api/v1/campaigns/${Y.campaignId}`,Y,G);break}case"schedule_campaign":{let G=Y.companyId,$=new Set(["companyId","campaignId","scheduledAt","targetLists","sendTimeOptimization","spreadOverHours","recurringInterval"]),z=Object.keys(Y).filter((J)=>!$.has(J));if(z.length>0)throw Error(`\`schedule_campaign\` accepts only \`campaignId\`, \`scheduledAt\`, \`targetLists\`, \`sendTimeOptimization\`, \`spreadOverHours\`, and \`recurringInterval\`. Unsupported field${z.length===1?"":"s"}: ${z.map((J)=>`\`${J}\``).join(", ")}.`);nV(Y),X=await B("POST",`/api/v1/campaigns/${Y.campaignId}/schedule`,{scheduledAt:Y.scheduledAt,...Y.targetLists!==void 0&&{targetLists:Y.targetLists},...Y.sendTimeOptimization!==void 0&&{sendTimeOptimization:Y.sendTimeOptimization},...Y.spreadOverHours!==void 0&&{spreadOverHours:Y.spreadOverHours},...Y.recurringInterval!==void 0&&{recurringInterval:Y.recurringInterval}},G);break}case"send_test_email":{let G=Y.companyId;X=await B("POST",`/api/v1/campaigns/${Y.campaignId}/test`,{to:Y.to},G);break}case"cancel_campaign":{let G=Y.companyId,$=R("cancel_campaign",Y,"campaignId");X=await B("POST",`/api/v1/campaigns/${encodeURIComponent($)}/cancel`,void 0,G);break}case"pause_campaign":{let G=Y.companyId,$=R("pause_campaign",Y,"campaignId");X=await B("POST",`/api/v1/campaigns/${encodeURIComponent($)}/pause`,void 0,G);break}case"resume_campaign":{let G=Y.companyId,$=R("resume_campaign",Y,"campaignId"),z=x1("resume_campaign",Y,"spreadOverHours",1,72);X=await B("POST",`/api/v1/campaigns/${encodeURIComponent($)}/resume`,{...z!==void 0&&{spreadOverHours:z}},G);break}case"delete_campaign":{let G=Y.companyId,$=R("delete_campaign",Y,"campaignId");X=await B("DELETE",`/api/v1/campaigns/${encodeURIComponent($)}`,void 0,G);break}case"duplicate_campaign":{let G=Y.companyId,$=R("duplicate_campaign",Y,"campaignId"),z=m0("duplicate_campaign",Y,"mode",["campaign","ab_test","variant"]),J=w(Y,"variantId");if(z==="variant"&&J===void 0)throw Error("`variantId` is required when calling `duplicate_campaign` with mode `variant`.");X=await B("POST",`/api/v1/campaigns/${encodeURIComponent($)}/duplicate`,{...z!==void 0&&{mode:z},...J!==void 0&&{variantId:J}},G);break}case"resend_campaign_to_non_openers":{let G=Y.companyId,$=R("resend_campaign_to_non_openers",Y,"campaignId");X=await B("POST",`/api/v1/campaigns/${encodeURIComponent($)}/resend-to-non-openers`,void 0,G);break}case"list_landing_pages":{let G=Y.companyId;X=await B("GET","/api/v1/landing-pages",void 0,G);break}case"get_landing_page":{let G=Y.companyId;X=await B("GET",`/api/v1/landing-pages/${Y.landingPageId}`,void 0,G);break}case"create_landing_page":{let G=Y.companyId,$=new Set(["companyId","name","slug","template","content"]),z=Object.keys(Y).filter((J)=>!$.has(J));if(z.length>0)throw Error(`\`create_landing_page\` accepts only \`name\`, \`slug\`, \`template\`, and \`content\` fields. Unsupported field${z.length===1?"":"s"}: ${z.map((J)=>`\`${J}\``).join(", ")}.`);X=await B("POST","/api/v1/landing-pages",{...Y.name!==void 0&&{name:Y.name},...Y.slug!==void 0&&{slug:Y.slug},...Y.template!==void 0&&{template:Y.template},...Y.content!==void 0&&{content:Y.content}},G);break}case"update_landing_page":{let G=Y.companyId,$=rY("update_landing_page",Y,{requireUpdate:!0});X=await B("PUT",`/api/v1/landing-pages/${Y.landingPageId}`,$,G);break}case"publish_landing_page":{let G=Y.companyId,$=rY("publish_landing_page",Y,{requireUpdate:!1});X=await B("POST",`/api/v1/landing-pages/${Y.landingPageId}/publish`,$,G);break}case"unpublish_landing_page":{let G=Y.companyId,$=rY("unpublish_landing_page",Y,{requireUpdate:!1});X=await B("POST",`/api/v1/landing-pages/${Y.landingPageId}/unpublish`,$,G);break}case"delete_landing_page":{let G=Y.companyId;X=await B("DELETE",`/api/v1/landing-pages/${Y.landingPageId}`,void 0,G);break}case"connect_landing_page_domain":{let G=Y.companyId;X=await B("POST","/api/v1/landing-pages/domain",{domain:Y.domain},G);break}case"update_landing_page_domain_settings":{let G=Y.companyId,$=rV(Y);X=await B("PUT","/api/v1/landing-pages/domain",$,G);break}case"list_sequences":{let G=Y.companyId;X=await B("GET","/api/v1/sequences",void 0,G);break}case"get_sequence":{let G=Y.companyId;X=await B("GET",`/api/v1/sequences/${Y.sequenceId}`,void 0,G);break}case"create_sequence":{let G=Y.companyId;if(Y.fromEmail!==void 0&&Y.senderProfileId!==void 0)throw Error("Provide either `fromEmail` or `senderProfileId` when calling `create_sequence`, not both.");if(Y.replyTo!==void 0&&Y.replyProfileId!==void 0)throw Error("Provide either `replyTo` or `replyProfileId` when calling `create_sequence`, not both.");if(Y.fromName!==void 0&&Y.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `create_sequence`.");if(Y.replyToName!==void 0&&Y.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `create_sequence`.");let $=Array.isArray(Y.steps)&&Y.steps.length>0,z=await B("POST","/api/v1/sequences",Y,G);if(!z.success){X=z;break}let J=z.sequence.id;if($){let D=await B("GET",`/api/v1/sequences/${J}`,void 0,G);if(D.success)X={success:!0,sequence:D.sequence,message:`Sequence "${D.sequence.name}" created with explicit steps. Review it before enabling.`};else X=D;break}let H=6,A=0,U="pending";while(U!=="complete"&&A<H){await new Promise((L)=>setTimeout(L,20000)),A++;let D=await B("GET",`/api/v1/sequences/${J}`,void 0,G);if(D.success)U=D.sequence.enrichmentStatus}let K=await B("GET",`/api/v1/sequences/${J}`,void 0,G);if(K.success)X={success:!0,sequence:K.sequence,message:K.sequence.enrichmentStatus==="complete"?`Sequence "${K.sequence.name}" created with ${K.sequence.emailCount} AI-generated emails. The sequence is ready to review and enable.`:`Sequence "${K.sequence.name}" created. Email enrichment is still in progress (${K.sequence.enrichedCount}/${K.sequence.emailCount} emails generated). You can check status with get_sequence.`};else X=K;break}case"update_sequence":{let G=Y.companyId,$=lV(Y);X=await B("PUT",`/api/v1/sequences/${Y.sequenceId}`,$,G);break}case"insert_sequence_step":{let G=Y.companyId,$=mV(Y);X=await B("PUT",`/api/v1/sequences/${Y.sequenceId}`,$,G);break}case"enable_sequence":{let G=Y.companyId;X=await B("POST",`/api/v1/sequences/${Y.sequenceId}/enable`,void 0,G);break}case"disable_sequence":{let G=Y.companyId;X=await B("POST",`/api/v1/sequences/${Y.sequenceId}/disable`,void 0,G);break}case"pause_sequence_enrollments":{let G=Y.companyId;X=await B("POST",`/api/v1/sequences/${Y.sequenceId}/pause-enrollments`,void 0,G);break}case"resume_sequence_enrollments":{let G=Y.companyId;X=await B("POST",`/api/v1/sequences/${Y.sequenceId}/resume-enrollments`,void 0,G);break}case"enroll_subscribers_in_sequence":{let G=Y.companyId,$=R("enroll_subscribers_in_sequence",Y,"sequenceId"),z=QZ(Y);X=await B("POST",`/api/v1/sequences/${encodeURIComponent($)}/enroll`,z,G);break}case"cancel_sequence_enrollments":{let G=Y.companyId,$=cV(Y);X=await B("POST",`/api/v1/sequences/${Y.sequenceId}/enrollments/cancel`,$,G);break}case"delete_sequence":{let G=Y.companyId;X=await B("DELETE",`/api/v1/sequences/${Y.sequenceId}`,void 0,G);break}case"list_transactional_emails":{let G=Y.companyId;X=await B("GET","/api/v1/transactional",void 0,G);break}case"get_transactional_email":{let G=Y.companyId;X=await B("GET",`/api/v1/transactional/${Y.idOrSlug}`,void 0,G);break}case"create_transactional_email":{let G=Y.companyId,$=new Set(["companyId","name","slug","subject","previewText","html","blocks","prompt","style","tone","enabled"]),z=Object.keys(Y).filter((H)=>!$.has(H));if(z.length>0)throw Error(`\`create_transactional_email\` accepts only \`name\`, \`slug\`, \`subject\`, \`previewText\`, \`html\`, \`blocks\`, \`prompt\`, \`style\`, \`tone\`, and \`enabled\` fields. Unsupported field${z.length===1?"":"s"}: ${z.map((H)=>`\`${H}\``).join(", ")}.`);dV(Y);let J=Object.fromEntries(Object.entries(Y).filter(([H])=>H!=="companyId"));X=await B("POST","/api/v1/transactional",J,G);break}case"update_transactional_email":{let G=Y.companyId,$=new Set(["companyId","idOrSlug","name","enabled","subject","previewText","html","blocks"]),z=Object.keys(Y).filter((H)=>!$.has(H));if(z.length>0)throw Error(`\`update_transactional_email\` accepts only \`name\`, \`enabled\`, \`subject\`, \`previewText\`, \`html\`, and \`blocks\` update fields. Unsupported field${z.length===1?"":"s"}: ${z.map((H)=>`\`${H}\``).join(", ")}.`);if(w1("update_transactional_email",Y),Y.name===void 0&&Y.enabled===void 0&&Y.subject===void 0&&Y.previewText===void 0&&Y.html===void 0&&Y.blocks===void 0)throw Error("Provide at least one of `name`, `enabled`, `subject`, `previewText`, `html`, or `blocks` when calling `update_transactional_email`.");let J=Object.fromEntries(Object.entries(Y).filter(([H])=>H!=="companyId"&&H!=="idOrSlug"));X=await B("PATCH",`/api/v1/transactional/${Y.idOrSlug}`,J,G);break}case"send_email":{let G=Y.companyId;X=await B("POST","/api/v1/transactional/send",Y,G);break}case"get_stats":{let G=Y.companyId,$=Y.period??"7d",z=new URLSearchParams({period:String($)});if(Y.includeMachineEngagement===!0)z.set("includeMachineEngagement","true");X=await B("GET",`/api/v1/metrics?${z.toString()}`,void 0,G);break}case"get_campaign_stats":{let G=Y.companyId,$=new URLSearchParams;if(Y.includeMachineEngagement===!0)$.set("includeMachineEngagement","true");let z=$.toString();X=await B("GET",`/api/v1/metrics/campaigns/${Y.campaignId}${z?`?${z}`:""}`,void 0,G);break}case"get_sequence_stats":{let G=Y.companyId,$=new URLSearchParams;if(Y.includeMachineEngagement===!0)$.set("includeMachineEngagement","true");let z=$.toString();X=await B("GET",`/api/v1/metrics/sequences/${Y.sequenceId}${z?`?${z}`:""}`,void 0,G);break}case"list_campaign_events":{let G=Y.companyId,$=R("list_campaign_events",Y,"campaignId"),J=HH("list_campaign_events",Y).toString();X=await B("GET",`/api/v1/metrics/campaigns/${encodeURIComponent($)}/events${J?`?${J}`:""}`,void 0,G);break}case"list_sequence_events":{let G=Y.companyId,$=R("list_sequence_events",Y,"sequenceId"),J=HH("list_sequence_events",Y).toString();X=await B("GET",`/api/v1/metrics/sequences/${encodeURIComponent($)}/events${J?`?${J}`:""}`,void 0,G);break}case"get_subscriber_activity":{let G=Y.companyId,$=v1("get_subscriber_activity",Y),z=await oY($,G,{includeMachineEngagement:Y.includeMachineEngagement===!0});X={success:z.success,email:z.subscriber.email,emailStats:z.subscriber.emailStats??null,activity:z.subscriber.activity??[],sequenceEnrollments:z.subscriber.sequenceEnrollments??[]};break}case"list_team_members":{let G=Y.companyId;X=await B("GET","/api/v1/team",void 0,G);break}case"invite_team_member":{let G=Y.companyId,$=R("invite_team_member",Y,"email"),z=tY("invite_team_member",Y,"role",["admin","viewer","restricted"]);if(Y.canManageBilling!==void 0&&typeof Y.canManageBilling!=="boolean")throw Error("`canManageBilling` must be a boolean when calling `invite_team_member`.");X=await B("POST","/api/v1/team/invitations",{email:$,role:z,...Y.canManageBilling!==void 0&&{canManageBilling:Y.canManageBilling}},G);break}case"cancel_team_invitation":{let G=Y.companyId,$=R("cancel_team_invitation",Y,"invitationId");X=await B("DELETE",`/api/v1/team/invitations/${encodeURIComponent($)}`,void 0,G);break}case"list_conversations":{let G=Y.companyId,$=new URLSearchParams,z=m0("list_conversations",Y,"status",["open","closed","all"]);if(z)$.set("status",z);let J=w(Y,"search");if(J)$.set("search",J);if(Y.unread!==void 0){if(typeof Y.unread!=="boolean")throw Error("`unread` must be a boolean when calling `list_conversations`.");if(Y.unread)$.set("unread","true")}if(Y.page!==void 0){if(typeof Y.page!=="number"||!Number.isInteger(Y.page)||Y.page<1)throw Error("`page` must be a positive integer when calling `list_conversations`.");$.set("page",String(Y.page))}let H=x1("list_conversations",Y,"limit",1,100);if(H!==void 0)$.set("limit",String(H));X=await B("GET",`/api/v1/conversations${$.size>0?`?${$}`:""}`,void 0,G);break}case"get_conversation":{let G=Y.companyId,$=R("get_conversation",Y,"conversationId");X=await B("GET",`/api/v1/conversations/${encodeURIComponent($)}`,void 0,G);break}case"reply_to_conversation":{let G=Y.companyId,$=R("reply_to_conversation",Y,"conversationId"),z=m0("reply_to_conversation",Y,"type",["outbound","note"])??"outbound",J=w(Y,"subject"),H=w(Y,"bodyText"),A=w(Y,"bodyHtml");if(z==="outbound"&&H===void 0&&A===void 0)throw Error("Provide `bodyText` or `bodyHtml` when calling `reply_to_conversation` with an outbound message.");X=await B("POST",`/api/v1/conversations/${encodeURIComponent($)}/messages`,{type:z,...J!==void 0&&{subject:J},...H!==void 0&&{bodyText:H},...A!==void 0&&{bodyHtml:A}},G);break}case"update_conversation_status":{let G=Y.companyId,$=R("update_conversation_status",Y,"conversationId"),z=tY("update_conversation_status",Y,"status",["open","closed"]);X=await B("POST",`/api/v1/conversations/${encodeURIComponent($)}/status`,{status:z},G);break}case"mark_conversation_read":{let G=Y.companyId,$=R("mark_conversation_read",Y,"conversationId");X=await B("POST",`/api/v1/conversations/${encodeURIComponent($)}/read`,void 0,G);break}case"list_webhooks":{let G=Y.companyId;X=await B("GET","/api/v1/webhooks",void 0,G);break}case"create_webhook":{let G=Y.companyId,$=R("create_webhook",Y,"name"),z=R("create_webhook",Y,"url"),J=AH("create_webhook",Y);X=await B("POST","/api/v1/webhooks",{name:$,url:z,...J!==void 0&&{events:J}},G);break}case"update_webhook":{let G=Y.companyId,$=R("update_webhook",Y,"webhookId"),z=w(Y,"name"),J=w(Y,"url"),H=AH("update_webhook",Y),A=m0("update_webhook",Y,"status",["enabled","disabled"]);if(z===void 0&&J===void 0&&H===void 0&&A===void 0)throw Error("Provide at least one of `name`, `url`, `events`, or `status` when calling `update_webhook`.");X=await B("PATCH",`/api/v1/webhooks/${encodeURIComponent($)}`,{...z!==void 0&&{name:z},...J!==void 0&&{url:J},...H!==void 0&&{events:H},...A!==void 0&&{status:A}},G);break}case"delete_webhook":{let G=Y.companyId,$=R("delete_webhook",Y,"webhookId");X=await B("DELETE",`/api/v1/webhooks/${encodeURIComponent($)}`,void 0,G);break}case"test_webhook":{let G=Y.companyId,$=R("test_webhook",Y,"webhookId");X=await B("POST",`/api/v1/webhooks/${encodeURIComponent($)}/test`,void 0,G);break}case"list_webhook_deliveries":{let G=Y.companyId,$=R("list_webhook_deliveries",Y,"webhookId"),z=x1("list_webhook_deliveries",Y,"limit",1,100),J=new URLSearchParams;if(z!==void 0)J.set("limit",String(z));X=await B("GET",`/api/v1/webhooks/${encodeURIComponent($)}/deliveries${J.size>0?`?${J}`:""}`,void 0,G);break}case"replay_webhook_delivery":{let G=Y.companyId,$=R("replay_webhook_delivery",Y,"webhookId"),z=R("replay_webhook_delivery",Y,"deliveryId");X=await B("POST",`/api/v1/webhooks/${encodeURIComponent($)}/deliveries/${encodeURIComponent(z)}/replay`,void 0,G);break}case"generate_email":{let G=Y.companyId;X=await B("POST","/api/v1/generate/email",Y,G);break}case"generate_sequence":{let G=Y.companyId;X=await B("POST","/api/v1/generate/sequence",Y,G);break}case"generate_subject_lines":{let G=Y.companyId;X=await B("POST","/api/v1/generate/subjects",Y,G);break}case"generate_sms":{let G=Y.companyId;X=await B("POST","/api/v1/generate/sms",Y,G);break}case"get_sms_settings":{let G=Y.companyId;X=await B("GET","/api/v1/sms/settings",void 0,G);break}case"send_test_sms":{let G=Y.companyId,$={to:R("send_test_sms",Y,"to")};for(let z of["text","imageUrls","blocks"])if(Y[z]!==void 0)$[z]=Y[z];X=await B("POST","/api/v1/sms/test",$,G);break}case"submit_feedback":{let G=Y.companyId,$={message:R("submit_feedback",Y,"message"),source:"mcp"};for(let z of["category","context"])if(Y[z]!==void 0)$[z]=Y[z];X=await B("POST","/api/v1/feedback",$,G);break}default:throw Error(`Unknown tool: ${Q}`)}let W=oV(X);if(W)throw W;return X=await JZ(Q,Y,X),{structuredContent:OZ(X),content:[{type:"text",text:JSON.stringify(X,null,2)}]}}catch(X){return{isError:!0,content:[{type:"text",text:$1(X)}]}}}async function MH(Q,Y,X){let W=Y.getRequestContext?.(Q)??{};try{return await SQ(W,X)}finally{await Y.onRequestContextUpdated?.(W,Q)}}function UX(Q={}){let Y=new lY({name:"sequenzy",version:n5.version},{capabilities:{tools:{},resources:{}},instructions:["Sequenzy email marketing MCP server: manage subscribers, campaigns, sequences, templates, and delivery stats.","If you have access to multiple companies, call get_account and then select_company (or pass companyId per call) before other tools.","IMPORTANT: whenever the user wanted to accomplish something and these tools did not expose functionality for it (missing tool, missing argument, unsupported workflow, or broken behavior), call submit_feedback describing the gap before finishing the task. The Sequenzy team reads every submission and uses it to decide what to build next."].join(`
191
+ `)});return Y.setRequestHandler(T9,async()=>{return{tools:qH}}),Y.setRequestHandler(I4,async(X,W)=>{let{name:G,arguments:$}=X.params;return MH(W,Q,()=>OH(G,$??{}))}),Y.setRequestHandler(N9,async()=>{return{resources:o5}}),Y.setRequestHandler(P9,async(X,W)=>{let{uri:G}=X.params;return MH(W,Q,()=>t5(G))}),Y}import ZH from"node:process";class KX{append(Q){this._buffer=this._buffer?Buffer.concat([this._buffer,Q]):Q}readMessage(){if(!this._buffer)return null;let Q=this._buffer.indexOf(`
192
+ `);if(Q===-1)return null;let Y=this._buffer.toString("utf8",0,Q).replace(/\r$/,"");return this._buffer=this._buffer.subarray(Q+1),VZ(Y)}clear(){this._buffer=void 0}}function VZ(Q){return Y$.parse(JSON.parse(Q))}function VH(Q){return JSON.stringify(Q)+`
193
+ `}class DX{constructor(Q=ZH.stdin,Y=ZH.stdout){this._stdin=Q,this._stdout=Y,this._readBuffer=new KX,this._started=!1,this._ondata=(X)=>{this._readBuffer.append(X),this.processReadBuffer()},this._onerror=(X)=>{this.onerror?.(X)}}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 Q=this._readBuffer.readMessage();if(Q===null)break;this.onmessage?.(Q)}catch(Q){this.onerror?.(Q)}}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(Q){return new Promise((Y)=>{let X=VH(Q);if(this._stdout.write(X))Y();else this._stdout.once("drain",Y)})}}async function ZZ(){wX(),MX();let Q=UX(),Y=new DX;await Q.connect(Y),console.error("Sequenzy MCP server running on stdio")}ZZ().catch((Q)=>{console.error($1(Q)),process.exit(1)});export{SQ as withMcpRequestContext,Q6 as setSelectedCompanyId,b1 as getSelectedCompanyId,UX as createSequenzyMcpServer,B as apiRequest};