@sequenzy/mcp 0.0.105 → 0.0.106
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 +24 -24
- package/dist/server.js +22 -22
- package/package.json +1 -1
- package/server.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,32 +1,32 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var jH=Object.create;var{getPrototypeOf:IH,defineProperty:TQ,getOwnPropertyNames:EH}=Object;var TH=Object.prototype.hasOwnProperty;function SH(Q){return this[Q]}var RH,CH,qX=(Q,Y,X)=>{var G=Q!=null&&typeof Q==="object";if(G){var W=Y?RH??=new WeakMap:CH??=new WeakMap,$=W.get(Q);if($)return $}X=Q!=null?jH(IH(Q)):{};let z=Y||!Q||!Q.__esModule?TQ(X,"default",{value:Q,enumerable:!0}):X;for(let J of EH(Q))if(!TH.call(z,J))TQ(z,J,{get:SH.bind(Q,J),enumerable:!0});if(G)W.set(Q,z);return z};var P=(Q,Y)=>()=>(Y||Q((Y={exports:{}}).exports,Y),Y.exports);var kH=(Q)=>Q;function vH(Q,Y){this[Q]=kH.bind(null,Y)}var OX=(Q,Y)=>{for(var X in Y)TQ(Q,X,{get:Y[X],enumerable:!0,configurable:!0,set:vH.bind(Y,X)})};var R4=P((F$)=>{Object.defineProperty(F$,"__esModule",{value:!0});F$.regexpCode=F$.getEsmExportName=F$.getProperty=F$.safeStringify=F$.stringify=F$.strConcat=F$.addCodeArg=F$.str=F$._=F$.nil=F$._Code=F$.Name=F$.IDENTIFIER=F$._CodeOrName=void 0;class y6{}F$._CodeOrName=y6;F$.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class c1 extends y6{constructor(Q){super();if(!F$.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}}}F$.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},{})}}F$._Code=_0;F$.nil=new _0("");function B$(Q,...Y){let X=[Q[0]],G=0;while(G<Y.length)y9(X,Y[G]),X.push(Q[++G]);return new _0(X)}F$._=B$;var g9=new _0("+");function L$(Q,...Y){let X=[S4(Q[0])],G=0;while(G<Y.length)X.push(g9),y9(X,Y[G]),X.push(g9,S4(Q[++G]));return WK(X),new _0(X)}F$.str=L$;function y9(Q,Y){if(Y instanceof _0)Q.push(...Y._items);else if(Y instanceof c1)Q.push(Y);else Q.push(zK(Y))}F$.addCodeArg=y9;function WK(Q){let Y=1;while(Y<Q.length-1){if(Q[Y]===g9){let X=GK(Q[Y-1],Q[Y+1]);if(X!==void 0){Q.splice(Y-1,3,X);continue}Q[Y++]="+"}Y++}}function GK(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 $K(Q,Y){return Y.emptyStr()?Q:Q.emptyStr()?Y:L$`${Q}${Y}`}F$.strConcat=$K;function zK(Q){return typeof Q=="number"||typeof Q=="boolean"||Q===null?Q:S4(Array.isArray(Q)?Q.join(","):Q)}function JK(Q){return new _0(S4(Q))}F$.stringify=JK;function S4(Q){return JSON.stringify(Q).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}F$.safeStringify=S4;function HK(Q){return typeof Q=="string"&&F$.IDENTIFIER.test(Q)?new _0(`.${Q}`):B$`[${Q}]`}F$.getProperty=HK;function AK(Q){if(typeof Q=="string"&&F$.IDENTIFIER.test(Q))return new _0(`${Q}`);throw Error(`CodeGen: invalid export name: ${Q}, use explicit $id name mapping`)}F$.getEsmExportName=AK;function UK(Q){return new _0(Q.toString())}F$.regexpCode=UK});var l9=P((V$)=>{Object.defineProperty(V$,"__esModule",{value:!0});V$.ValueScope=V$.ValueScopeName=V$.Scope=V$.varKinds=V$.UsedValueState=void 0;var Z0=R4();class O$ 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||(V$.UsedValueState=h6={}));V$.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}}}V$.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}]`}}V$.ValueScopeName=f9;var PK=Z0._`\n`;class M$ extends h9{constructor(Q){super(Q);this._values={},this._scope=Q.scope,this.opts={...Q,_n:Q.lines?PK: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 G=this.toName(Q),{prefix:W}=G,$=(X=Y.key)!==null&&X!==void 0?X:Y.ref,z=this._values[W];if(z){let A=z.get($);if(A)return A}else z=this._values[W]=new Map;z.set($,G);let J=this._scope[W]||(this._scope[W]=[]),H=J.length;return J[H]=Y.ref,G.setValue(Y,{property:W,itemIndex:H}),G}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,(G)=>{if(G.value===void 0)throw Error(`CodeGen: name "${G}" has no value`);return G.value.code},Y,X)}_reduceValues(Q,Y,X={},G){let W=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?V$.varKinds.var:V$.varKinds.const;W=Z0._`${W}${U} ${H} = ${A};${this.opts._n}`}else if(A=G===null||G===void 0?void 0:G(H))W=Z0._`${W}${A}${this.opts._n}`;else throw new O$(H);J.set(H,h6.Completed)})}return W}}V$.ValueScope=M$});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 N$ 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,G=this.rhs===void 0?"":` = ${this.rhs}`;return`${X} ${this.name}${G};`+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 w$ extends p9{constructor(Q,Y,X,G){super(Q,X,G);this.op=Y}render({_n:Q}){return`${this.lhs} ${this.op}= ${this.rhs};`+Q}}class P$ extends L1{constructor(Q){super();this.label=Q,this.names={}}render({_n:Q}){return`${this.label}:`+Q}}class b$ extends L1{constructor(Q){super();this.label=Q,this.names={}}render({_n:Q}){return`break${this.label?` ${this.label}`:""};`+Q}}class j$ extends L1{constructor(Q){super();this.error=Q}render({_n:Q}){return`throw ${this.error};`+Q}get names(){return this.error.names}}class I$ 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,G=X.length;while(G--){let W=X[G];if(W.optimizeNames(Q,Y))continue;EK(Q,W.names),X.splice(G,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 E$ 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(k$(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 T$ 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 S$ extends p1{constructor(Q,Y,X,G){super();this.varKind=Q,this.name=Y,this.from=X,this.to=G}render(Q){let Y=Q.es5?g0.varKinds.var:this.varKind,{name:X,from:G,to:W}=this;return`for(${Y} ${X}=${G}; ${X}<${W}; ${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,G){super();this.loop=Q,this.varKind=Y,this.name=X,this.iterable=G}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 R$ 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,G;return super.optimizeNames(Q,Y),(X=this.catch)===null||X===void 0||X.optimizeNames(Q,Y),(G=this.finally)===null||G===void 0||G.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 C${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 E$]}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,G){let W=this._scope.toName(Y);if(X!==void 0&&G)this._constants[W.str]=X;return this._leafNode(new N$(Q,W,X)),W}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 w$(Q,N0.operators.ADD,Y))}code(Q){if(typeof Q=="function")Q();else if(Q!==f.nil)this._leafNode(new I$(Q));return this}object(...Q){let Y=["{"];for(let[X,G]of Q){if(Y.length>1)Y.push(",");if(Y.push(X),X!==G||this.opts.es5)Y.push(":"),(0,f.addCodeArg)(Y,G)}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 T$(Q),Y)}forRange(Q,Y,X,G,W=this.opts.es5?g0.varKinds.var:g0.varKinds.let){let $=this._scope.toName(Q);return this._for(new S$(W,$,Y,X),()=>G($))}forOf(Q,Y,X,G=g0.varKinds.const){let W=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(W,f._`${$}[${z}]`),X(W)})}return this._for(new m9("of",G,W,Y),()=>X(W))}forIn(Q,Y,X,G=this.opts.es5?g0.varKinds.var:g0.varKinds.const){if(this.opts.ownProperties)return this.forOf(Q,f._`Object.keys(${Y})`,X);let W=this._scope.toName(Q);return this._for(new m9("in",G,W,Y),()=>X(W))}endFor(){return this._endBlockNode(p1)}label(Q){return this._leafNode(new P$(Q))}break(Q){return this._leafNode(new b$(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 G=new R$;if(this._blockNode(G),this.code(Q),Y){let W=this.name("e");this._currNode=G.catch=new m6(W),Y(W)}if(X)this._currNode=G.finally=new c6,this.code(X);return this._endBlockNode(m6,c6)}throw(Q){return this._leafNode(new j$(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,G){if(this._blockNode(new f6(Q,Y,X)),G)this.code(G).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=C$;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 G(Q);if(!W(Q))return Q;return new f._Code(Q._items.reduce(($,z)=>{if(z instanceof f.Name)z=G(z);if(z instanceof f._Code)$.push(...z._items);else $.push(z);return $},[]));function G($){let z=X[$.str];if(z===void 0||Y[$.str]!==1)return $;return delete Y[$.str],z}function W($){return $ instanceof f._Code&&$._items.some((z)=>z instanceof f.Name&&Y[z.str]===1&&X[z.str]!==void 0)}}function EK(Q,Y){for(let X in Y)Q[X]=(Q[X]||0)-(Y[X]||0)}function k$(Q){return typeof Q=="boolean"||typeof Q=="number"||Q===null?!Q:f._`!${c9(Q)}`}N0.not=k$;var TK=v$(N0.operators.AND);function SK(...Q){return Q.reduce(TK)}N0.and=SK;var RK=v$(N0.operators.OR);function CK(...Q){return Q.reduce(RK)}N0.or=CK;function v$(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((m$)=>{Object.defineProperty(m$,"__esModule",{value:!0});m$.checkStrictMode=m$.getErrorPath=m$.Type=m$.useFunc=m$.setEvaluated=m$.evaluatedPropsToName=m$.mergeEvaluated=m$.eachItem=m$.unescapeJsonPointer=m$.escapeJsonPointer=m$.escapeFragment=m$.unescapeFragment=m$.schemaRefOrVal=m$.schemaHasRulesButRef=m$.schemaHasRules=m$.checkUnknownRules=m$.alwaysValidSchema=m$.toHash=void 0;var d=g(),_K=R4();function gK(Q){let Y={};for(let X of Q)Y[X]=!0;return Y}m$.toHash=gK;function yK(Q,Y){if(typeof Y=="boolean")return Y;if(Object.keys(Y).length===0)return!0;return y$(Q,Y),!u$(Y,Q.self.RULES.all)}m$.alwaysValidSchema=yK;function y$(Q,Y=Q.schema){let{opts:X,self:G}=Q;if(!X.strictSchema)return;if(typeof Y==="boolean")return;let W=G.RULES.keywords;for(let $ in Y)if(!W[$])l$(Q,`unknown keyword: "${$}"`)}m$.checkUnknownRules=y$;function u$(Q,Y){if(typeof Q=="boolean")return!Q;for(let X in Q)if(Y[X])return!0;return!1}m$.schemaHasRules=u$;function uK(Q,Y){if(typeof Q=="boolean")return!Q;for(let X in Q)if(X!=="$ref"&&Y.all[X])return!0;return!1}m$.schemaHasRulesButRef=uK;function hK({topSchemaRef:Q,schemaPath:Y},X,G,W){if(!W){if(typeof X=="number"||typeof X=="boolean")return X;if(typeof X=="string")return d._`${X}`}return d._`${Q}${Y}${(0,d.getProperty)(G)}`}m$.schemaRefOrVal=hK;function fK(Q){return h$(decodeURIComponent(Q))}m$.unescapeFragment=fK;function lK(Q){return encodeURIComponent(n9(Q))}m$.escapeFragment=lK;function n9(Q){if(typeof Q=="number")return`${Q}`;return Q.replace(/~/g,"~0").replace(/\//g,"~1")}m$.escapeJsonPointer=n9;function h$(Q){return Q.replace(/~1/g,"/").replace(/~0/g,"~")}m$.unescapeJsonPointer=h$;function mK(Q,Y){if(Array.isArray(Q))for(let X of Q)Y(X);else Y(Q)}m$.eachItem=mK;function _$({mergeNames:Q,mergeToName:Y,mergeValues:X,resultToName:G}){return(W,$,z,J)=>{let H=z===void 0?$:z instanceof d.Name?($ instanceof d.Name?Q(W,$,z):Y(W,$,z),z):$ instanceof d.Name?(Y(W,z,$),$):X($,z);return J===d.Name&&!(H instanceof d.Name)?G(W,H):H}}m$.mergeEvaluated={props:_$({mergeNames:(Q,Y,X)=>Q.if(d._`${X} !== true && ${Y} !== undefined`,()=>{Q.if(d._`${Y} === true`,()=>Q.assign(X,!0),()=>Q.assign(X,d._`${X} || {}`).code(d._`Object.assign(${X}, ${Y})`))}),mergeToName:(Q,Y,X)=>Q.if(d._`${X} !== true`,()=>{if(Y===!0)Q.assign(X,!0);else Q.assign(X,d._`${X} || {}`),r9(Q,X,Y)}),mergeValues:(Q,Y)=>Q===!0?!0:{...Q,...Y},resultToName:f$}),items:_$({mergeNames:(Q,Y,X)=>Q.if(d._`${X} !== true && ${Y} !== undefined`,()=>Q.assign(X,d._`${Y} === true ? true : ${X} > ${Y} ? ${X} : ${Y}`)),mergeToName:(Q,Y,X)=>Q.if(d._`${X} !== true`,()=>Q.assign(X,Y===!0?!0:d._`${X} > ${Y} ? ${X} : ${Y}`)),mergeValues:(Q,Y)=>Q===!0?!0:Math.max(Q,Y),resultToName:(Q,Y)=>Q.var("items",Y)})};function f$(Q,Y){if(Y===!0)return Q.var("props",!0);let X=Q.var("props",d._`{}`);if(Y!==void 0)r9(Q,X,Y);return X}m$.evaluatedPropsToName=f$;function r9(Q,Y,X){Object.keys(X).forEach((G)=>Q.assign(d._`${Y}${(0,d.getProperty)(G)}`,!0))}m$.setEvaluated=r9;var g$={};function cK(Q,Y){return Q.scopeValue("func",{ref:Y,code:g$[Y.code]||(g$[Y.code]=new _K._Code(Y.code))})}m$.useFunc=cK;var i9;(function(Q){Q[Q.Num=0]="Num",Q[Q.Str=1]="Str"})(i9||(m$.Type=i9={}));function pK(Q,Y,X){if(Q instanceof d.Name){let G=Y===i9.Num;return X?G?d._`"[" + ${Q} + "]"`:d._`"['" + ${Q} + "']"`:G?d._`"/" + ${Q}`:d._`"/" + ${Q}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return X?(0,d.getProperty)(Q).toString():"/"+n9(Q)}m$.getErrorPath=pK;function l$(Q,Y,X=Q.opts.strictSchema){if(!X)return;if(Y=`strict mode: ${Y}`,X===!0)throw Error(Y);Q.self.logger.warn(Y)}m$.checkStrictMode=l$});var Y1=P((p$)=>{Object.defineProperty(p$,"__esModule",{value:!0});var F0=g(),HD={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")};p$.default=HD});var k4=P((d$)=>{Object.defineProperty(d$,"__esModule",{value:!0});d$.extendErrors=d$.resetErrorsCount=d$.reportExtraError=d$.reportError=d$.keyword$DataError=d$.keywordError=void 0;var l=g(),d6=c(),O0=Y1();d$.keywordError={message:({keyword:Q})=>l.str`must pass "${Q}" keyword validation`};d$.keyword$DataError={message:({keyword:Q,schemaType:Y})=>Y?l.str`"${Q}" keyword must be ${Y} ($data)`:l.str`"${Q}" keyword is invalid ($data)`};function UD(Q,Y=d$.keywordError,X,G){let{it:W}=Q,{gen:$,compositeRule:z,allErrors:J}=W,H=r$(Q,Y,X);if(G!==null&&G!==void 0?G:z||J)i$($,H);else n$(W,l._`[${H}]`)}d$.reportError=UD;function KD(Q,Y=d$.keywordError,X){let{it:G}=Q,{gen:W,compositeRule:$,allErrors:z}=G,J=r$(Q,Y,X);if(i$(W,J),!($||z))n$(G,O0.default.vErrors)}d$.reportExtraError=KD;function DD(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)))}d$.resetErrorsCount=DD;function BD({gen:Q,keyword:Y,schemaValue:X,data:G,errsCount:W,it:$}){if(W===void 0)throw Error("ajv implementation error");let z=Q.name("err");Q.forRange("i",W,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`,G)})}d$.extendErrors=BD;function i$(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 n$(Q,Y){let{gen:X,validateName:G,schemaEnv:W}=Q;if(W.$async)X.throw(l._`new ${Q.ValidationError}(${Y})`);else X.assign(l._`${G}.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 r$(Q,Y,X){let{createErrors:G}=Q.it;if(G===!1)return l._`{}`;return LD(Q,Y,X)}function LD(Q,Y,X={}){let{gen:G,it:W}=Q,$=[FD(W,X),qD(Q,X)];return OD(Q,Y,$),G.object(...$)}function FD({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 qD({keyword:Q,it:{errSchemaPath:Y}},{schemaPath:X,parentSchema:G}){let W=G?Y:l.str`${Y}/${Q}`;if(X)W=l.str`${W}${(0,d6.getErrorPath)(X,d6.Type.Str)}`;return[T1.schemaPath,W]}function OD(Q,{params:Y,message:X},G){let{keyword:W,data:$,schemaValue:z,it:J}=Q,{opts:H,propertyName:A,topSchemaRef:U,schemaPath:K}=J;if(G.push([T1.keyword,W],[T1.params,typeof Y=="function"?Y(Q):Y||l._`{}`]),H.messages)G.push([T1.message,typeof X=="function"?X(Q):X]);if(H.verbose)G.push([T1.schema,z],[T1.parentSchema,l._`${U}${K}`],[O0.default.data,$]);if(A)G.push([T1.propertyName,A])}});var e$=P((a$)=>{Object.defineProperty(a$,"__esModule",{value:!0});a$.boolOrEmptySchema=a$.topBoolOrEmptySchema=void 0;var wD=k4(),PD=g(),bD=Y1(),jD={message:"boolean schema is false"};function ID(Q){let{gen:Y,schema:X,validateName:G}=Q;if(X===!1)t$(Q,!1);else if(typeof X=="object"&&X.$async===!0)Y.return(bD.default.data);else Y.assign(PD._`${G}.errors`,null),Y.return(!0)}a$.topBoolOrEmptySchema=ID;function ED(Q,Y){let{gen:X,schema:G}=Q;if(G===!1)X.var(Y,!1),t$(Q);else X.var(Y,!0)}a$.boolOrEmptySchema=ED;function t$(Q,Y){let{gen:X,data:G}=Q,W={gen:X,keyword:"false schema",data:G,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:Q};(0,wD.reportError)(W,jD,void 0,Y)}});var o9=P((Qz)=>{Object.defineProperty(Qz,"__esModule",{value:!0});Qz.getRules=Qz.isJSONType=void 0;var SD=["string","number","integer","boolean","null","object","array"],RD=new Set(SD);function CD(Q){return typeof Q=="string"&&RD.has(Q)}Qz.isJSONType=CD;function kD(){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:{}}}Qz.getRules=kD});var t9=P((Gz)=>{Object.defineProperty(Gz,"__esModule",{value:!0});Gz.shouldUseRule=Gz.shouldUseGroup=Gz.schemaHasRulesForType=void 0;function xD({schema:Q,self:Y},X){let G=Y.RULES.types[X];return G&&G!==!0&&Xz(Q,G)}Gz.schemaHasRulesForType=xD;function Xz(Q,Y){return Y.rules.some((X)=>Wz(Q,X))}Gz.shouldUseGroup=Xz;function Wz(Q,Y){var X;return Q[Y.keyword]!==void 0||((X=Y.definition.implements)===null||X===void 0?void 0:X.some((G)=>Q[G]!==void 0))}Gz.shouldUseRule=Wz});var v4=P((Az)=>{Object.defineProperty(Az,"__esModule",{value:!0});Az.reportTypeError=Az.checkDataTypes=Az.checkDataType=Az.coerceAndCheckDataType=Az.getJSONTypes=Az.getSchemaTypes=Az.DataType=void 0;var yD=o9(),uD=t9(),hD=k4(),x=g(),zz=c(),n1;(function(Q){Q[Q.Correct=0]="Correct",Q[Q.Wrong=1]="Wrong"})(n1||(Az.DataType=n1={}));function fD(Q){let Y=Jz(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}Az.getSchemaTypes=fD;function Jz(Q){let Y=Array.isArray(Q)?Q:Q?[Q]:[];if(Y.every(yD.isJSONType))return Y;throw Error("type must be JSONType or JSONType[]: "+Y.join(","))}Az.getJSONTypes=Jz;function lD(Q,Y){let{gen:X,data:G,opts:W}=Q,$=mD(Y,W.coerceTypes),z=Y.length>0&&!($.length===0&&Y.length===1&&(0,uD.schemaHasRulesForType)(Q,Y[0]));if(z){let J=s9(Y,G,W.strictNumbers,n1.Wrong);X.if(J,()=>{if($.length)cD(Q,Y,$);else e9(Q)})}return z}Az.coerceAndCheckDataType=lD;var Hz=new Set(["string","number","integer","boolean","null"]);function mD(Q,Y){return Y?Q.filter((X)=>Hz.has(X)||Y==="array"&&X==="array"):[]}function cD(Q,Y,X){let{gen:G,data:W,opts:$}=Q,z=G.let("dataType",x._`typeof ${W}`),J=G.let("coerced",x._`undefined`);if($.coerceTypes==="array")G.if(x._`${z} == 'object' && Array.isArray(${W}) && ${W}.length == 1`,()=>G.assign(W,x._`${W}[0]`).assign(z,x._`typeof ${W}`).if(s9(Y,W,$.strictNumbers),()=>G.assign(J,W)));G.if(x._`${J} !== undefined`);for(let A of X)if(Hz.has(A)||A==="array"&&$.coerceTypes==="array")H(A);G.else(),e9(Q),G.endIf(),G.if(x._`${J} !== undefined`,()=>{G.assign(W,J),pD(Q,J)});function H(A){switch(A){case"string":G.elseIf(x._`${z} == "number" || ${z} == "boolean"`).assign(J,x._`"" + ${W}`).elseIf(x._`${W} === null`).assign(J,x._`""`);return;case"number":G.elseIf(x._`${z} == "boolean" || ${W} === null
|
|
4
|
-
|| (${
|
|
5
|
-
|| (${
|
|
6
|
-
|| ${z} === "boolean" || ${W} === null`).assign(J,x._`[${W}]`)}}}function pD({gen:Q,parentData:Y,parentDataProperty:X},G){Q.if(x._`${Y} !== undefined`,()=>Q.assign(x._`${Y}[${X}]`,G))}function a9(Q,Y,X,G=n1.Correct){let W=G===n1.Correct?x.operators.EQ:x.operators.NEQ,$;switch(Q){case"null":return x._`${Y} ${W} 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} ${W} ${Q}`}return G===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)}}Az.checkDataType=a9;function s9(Q,Y,X,G){if(Q.length===1)return a9(Q[0],Y,X,G);let W,$=(0,zz.toHash)(Q);if($.array&&$.object){let z=x._`typeof ${Y} != "object"`;W=$.null?z:x._`!${Y} || ${z}`,delete $.null,delete $.array,delete $.object}else W=x.nil;if($.number)delete $.integer;for(let z in $)W=(0,x.and)(W,a9(z,Y,X,G));return W}Az.checkDataTypes=s9;var iD={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=nD(Q);(0,hD.reportError)(Y,iD)}Az.reportTypeError=e9;function nD(Q){let{gen:Y,data:X,schema:G}=Q,W=(0,zz.schemaRefOrVal)(Q,G,"type");return{gen:Y,keyword:"type",data:X,schema:G.type,schemaCode:W,schemaValue:W,parentSchema:G,params:{},it:Q}}});var Lz=P((Dz)=>{Object.defineProperty(Dz,"__esModule",{value:!0});Dz.assignDefaults=void 0;var r1=g(),eD=c();function QB(Q,Y){let{properties:X,items:G}=Q.schema;if(Y==="object"&&X)for(let W in X)Kz(Q,W,X[W].default);else if(Y==="array"&&Array.isArray(G))G.forEach((W,$)=>Kz(Q,$,W.default))}Dz.assignDefaults=QB;function Kz(Q,Y,X){let{gen:G,compositeRule:W,data:$,opts:z}=Q;if(X===void 0)return;let J=r1._`${$}${(0,r1.getProperty)(Y)}`;if(W){(0,eD.checkStrictMode)(Q,`default is ignored for: ${J}`);return}let H=r1._`${J} === undefined`;if(z.useDefaults==="empty")H=r1._`${H} || ${J} === null || ${J} === ""`;G.if(H,r1._`${J} = ${(0,r1.stringify)(X)}`)}});var C0=P((Oz)=>{Object.defineProperty(Oz,"__esModule",{value:!0});Oz.validateUnion=Oz.validateArray=Oz.usePattern=Oz.callValidateCode=Oz.schemaProperties=Oz.allSchemaProperties=Oz.noPropertyInData=Oz.propertyInData=Oz.isOwnProperty=Oz.hasPropFunc=Oz.reportMissingProp=Oz.checkMissingProp=Oz.checkReportMissingProp=void 0;var s=g(),QY=c(),q1=Y1(),YB=c();function XB(Q,Y){let{gen:X,data:G,it:W}=Q;X.if(XY(X,G,Y,W.opts.ownProperties),()=>{Q.setParams({missingProperty:s._`${Y}`},!0),Q.error()})}Oz.checkReportMissingProp=XB;function WB({gen:Q,data:Y,it:{opts:X}},G,W){return(0,s.or)(...G.map(($)=>(0,s.and)(XY(Q,Y,$,X.ownProperties),s._`${W} = ${$}`)))}Oz.checkMissingProp=WB;function GB(Q,Y){Q.setParams({missingProperty:Y},!0),Q.error()}Oz.reportMissingProp=GB;function Fz(Q){return Q.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:s._`Object.prototype.hasOwnProperty`})}Oz.hasPropFunc=Fz;function YY(Q,Y,X){return s._`${Fz(Q)}.call(${Y}, ${X})`}Oz.isOwnProperty=YY;function $B(Q,Y,X,G){let W=s._`${Y}${(0,s.getProperty)(X)} !== undefined`;return G?s._`${W} && ${YY(Q,Y,X)}`:W}Oz.propertyInData=$B;function XY(Q,Y,X,G){let W=s._`${Y}${(0,s.getProperty)(X)} === undefined`;return G?(0,s.or)(W,(0,s.not)(YY(Q,Y,X))):W}Oz.noPropertyInData=XY;function qz(Q){return Q?Object.keys(Q).filter((Y)=>Y!=="__proto__"):[]}Oz.allSchemaProperties=qz;function zB(Q,Y){return qz(Y).filter((X)=>!(0,QY.alwaysValidSchema)(Q,Y[X]))}Oz.schemaProperties=zB;function JB({schemaCode:Q,data:Y,it:{gen:X,topSchemaRef:G,schemaPath:W,errorPath:$},it:z},J,H,A){let U=A?s._`${Q}, ${Y}, ${G}${W}`:Y,K=[[q1.default.instancePath,(0,s.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=s._`${U}, ${X.object(...K)}`;return H!==s.nil?s._`${J}.call(${H}, ${D})`:s._`${J}(${D})`}Oz.callValidateCode=JB;var HB=s._`new RegExp`;function AB({gen:Q,it:{opts:Y}},X){let G=Y.unicodeRegExp?"u":"",{regExp:W}=Y.code,$=W(X,G);return Q.scopeValue("pattern",{key:$.toString(),ref:$,code:s._`${W.code==="new RegExp"?HB:(0,YB.useFunc)(Q,W)}(${X}, ${G})`})}Oz.usePattern=AB;function UB(Q){let{gen:Y,data:X,keyword:G,it:W}=Q,$=Y.name("valid");if(W.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",s._`${X}.length`);Y.forRange("i",0,H,(A)=>{Q.subschema({keyword:G,dataProp:A,dataPropType:QY.Type.Num},$),Y.if((0,s.not)($),J)})}}Oz.validateArray=UB;function KB(Q){let{gen:Y,schema:X,keyword:G,it:W}=Q;if(!Array.isArray(X))throw Error("ajv implementation error");if(X.some((H)=>(0,QY.alwaysValidSchema)(W,H))&&!W.opts.unevaluated)return;let z=Y.let("valid",!1),J=Y.name("_valid");Y.block(()=>X.forEach((H,A)=>{let U=Q.subschema({keyword:G,schemaProp:A,compositeRule:!0},J);if(Y.assign(z,s._`${z} || ${J}`),!Q.mergeValidEvaluated(U,J))Y.if((0,s.not)(z))})),Q.result(z,()=>Q.reset(),()=>Q.error(!0))}Oz.validateUnion=KB});var Pz=P((Nz)=>{Object.defineProperty(Nz,"__esModule",{value:!0});Nz.validateKeywordUsage=Nz.validSchemaType=Nz.funcKeywordCode=Nz.macroKeywordCode=void 0;var M0=g(),S1=Y1(),bB=C0(),jB=k4();function IB(Q,Y){let{gen:X,keyword:G,schema:W,parentSchema:$,it:z}=Q,J=Y.macro.call(z.self,W,$,z),H=Zz(X,G,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}/${G}`,topSchemaRef:H,compositeRule:!0},A),Q.pass(A,()=>Q.error(!0))}Nz.macroKeywordCode=IB;function EB(Q,Y){var X;let{gen:G,keyword:W,schema:$,parentSchema:z,$data:J,it:H}=Q;SB(H,Y);let A=!J&&Y.compile?Y.compile.call(H.self,$,z,H):Y.validate,U=Zz(G,W,A),K=G.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)Vz(Q);w(()=>Q.error())}else{let Z=Y.async?L():O();if(Y.modifying)Vz(Q);w(()=>TB(Q,Z))}}function L(){let Z=G.let("ruleErrs",null);return G.try(()=>M(M0._`await `),(k)=>G.assign(K,!1).if(M0._`${k} instanceof ${H.ValidationError}`,()=>G.assign(Z,M0._`${k}.errors`),()=>G.throw(k))),Z}function O(){let Z=M0._`${U}.errors`;return G.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,R=!(("compile"in Y)&&!J||Y.schema===!1);G.assign(K,M0._`${Z}${(0,bB.callValidateCode)(Q,U,k,R)}`,Y.modifying)}function w(Z){var k;G.if((0,M0.not)((k=Y.valid)!==null&&k!==void 0?k:K),Z)}}Nz.funcKeywordCode=EB;function Vz(Q){let{gen:Y,data:X,it:G}=Q;Y.if(G.parentData,()=>Y.assign(X,M0._`${G.parentData}[${G.parentDataProperty}]`))}function TB(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,jB.extendErrors)(Q)},()=>Q.error())}function SB({schemaEnv:Q},Y){if(Y.async&&!Q.$async)throw Error("async keyword in sync schema")}function Zz(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 RB(Q,Y,X=!1){return!Y.length||Y.some((G)=>G==="array"?Array.isArray(Q):G==="object"?Q&&typeof Q=="object"&&!Array.isArray(Q):typeof Q==G||X&&typeof Q>"u")}Nz.validSchemaType=RB;function CB({schema:Q,opts:Y,self:X,errSchemaPath:G},W,$){if(Array.isArray(W.keyword)?!W.keyword.includes($):W.keyword!==$)throw Error("ajv implementation error");let z=W.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(W.validateSchema){if(!W.validateSchema(Q[$])){let H=`keyword "${$}" value is invalid at path "${G}": `+X.errorsText(W.validateSchema.errors);if(Y.validateSchema==="log")X.logger.error(H);else throw Error(H)}}}Nz.validateKeywordUsage=CB});var Ez=P((jz)=>{Object.defineProperty(jz,"__esModule",{value:!0});jz.extendSubschemaMode=jz.extendSubschemaData=jz.getSubschema=void 0;var p0=g(),bz=c();function _B(Q,{keyword:Y,schemaProp:X,schema:G,schemaPath:W,errSchemaPath:$,topSchemaRef:z}){if(Y!==void 0&&G!==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,bz.escapeFragment)(X)}`}}if(G!==void 0){if(W===void 0||$===void 0||z===void 0)throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:G,schemaPath:W,topSchemaRef:z,errSchemaPath:$}}throw Error('either "keyword" or "schema" must be passed')}jz.getSubschema=_B;function gB(Q,Y,{dataProp:X,dataPropType:G,data:W,dataTypes:$,propertyName:z}){if(W!==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,bz.getErrorPath)(X,G,K.jsPropertySyntax)}`,Q.parentDataProperty=p0._`${X}`,Q.dataPathArr=[...U,Q.parentDataProperty]}if(W!==void 0){let A=W instanceof p0.Name?W:J.let("data",W,!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]}}jz.extendSubschemaData=gB;function yB(Q,{jtdDiscriminator:Y,jtdMetadata:X,compositeRule:G,createErrors:W,allErrors:$}){if(G!==void 0)Q.compositeRule=G;if(W!==void 0)Q.createErrors=W;if($!==void 0)Q.allErrors=$;Q.jtdDiscriminator=Y,Q.jtdMetadata=X}jz.extendSubschemaMode=yB});var WY=P((lI,Tz)=>{Tz.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 G,W,$;if(Array.isArray(Y)){if(G=Y.length,G!=X.length)return!1;for(W=G;W--!==0;)if(!Q(Y[W],X[W]))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),G=$.length,G!==Object.keys(X).length)return!1;for(W=G;W--!==0;)if(!Object.prototype.hasOwnProperty.call(X,$[W]))return!1;for(W=G;W--!==0;){var z=$[W];if(!Q(Y[z],X[z]))return!1}return!0}return Y!==Y&&X!==X}});var Rz=P((mI,Sz)=>{var O1=Sz.exports=function(Q,Y,X){if(typeof Y=="function")X=Y,Y={};X=Y.cb||X;var G=typeof X=="function"?X:X.pre||function(){},W=X.post||function(){};o6(Y,G,W,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,G,W,$,z,J,H,A){if(G&&typeof G=="object"&&!Array.isArray(G)){Y(G,W,$,z,J,H,A);for(var U in G){var K=G[U];if(Array.isArray(K)){if(U in O1.arrayKeywords)for(var D=0;D<K.length;D++)o6(Q,Y,X,K[D],W+"/"+U+"/"+D,$,W,U,G,D)}else if(U in O1.propsKeywords){if(K&&typeof K=="object")for(var L in K)o6(Q,Y,X,K[L],W+"/"+U+"/"+fB(L),$,W,U,G,L)}else if(U in O1.keywords||Q.allKeys&&!(U in O1.skipKeywords))o6(Q,Y,X,K,W+"/"+U,$,W,U,G)}X(G,W,$,z,J,H,A)}}function fB(Q){return Q.replace(/~/g,"~0").replace(/\//g,"~1")}});var x4=P((xz)=>{Object.defineProperty(xz,"__esModule",{value:!0});xz.getSchemaRefs=xz.resolveUrl=xz.normalizeId=xz._getFullPath=xz.getFullPath=xz.inlineRef=void 0;var lB=c(),mB=WY(),cB=Rz(),pB=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function iB(Q,Y=!0){if(typeof Q=="boolean")return!0;if(Y===!0)return!GY(Q);if(!Y)return!1;return Cz(Q)<=Y}xz.inlineRef=iB;var nB=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function GY(Q){for(let Y in Q){if(nB.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 Cz(Q){let Y=0;for(let X in Q){if(X==="$ref")return 1/0;if(Y++,pB.has(X))continue;if(typeof Q[X]=="object")(0,lB.eachItem)(Q[X],(G)=>Y+=Cz(G));if(Y===1/0)return 1/0}return Y}function kz(Q,Y="",X){if(X!==!1)Y=d1(Y);let G=Q.parse(Y);return vz(Q,G)}xz.getFullPath=kz;function vz(Q,Y){return Q.serialize(Y).split("#")[0]+"#"}xz._getFullPath=vz;var rB=/#\/?$/;function d1(Q){return Q?Q.replace(rB,""):""}xz.normalizeId=d1;function dB(Q,Y,X){return X=d1(X),Q.resolve(Y,X)}xz.resolveUrl=dB;var oB=/^[a-z_][-a-z0-9._]*$/i;function tB(Q,Y){if(typeof Q=="boolean")return{};let{schemaId:X,uriResolver:G}=this.opts,W=d1(Q[X]||Y),$={"":W},z=kz(G,W,!1),J={},H=new Set;return cB(Q,{allKeys:!0},(K,D,L,O)=>{if(O===void 0)return;let M=z+D,w=$[O];if(typeof K[X]=="string")w=Z.call(this,K[X]);k.call(this,K.$anchor),k.call(this,K.$dynamicAnchor),$[D]=w;function Z(R){let y=this.opts.uriResolver.resolve;if(R=d1(w?y(w,R):R),H.has(R))throw U(R);H.add(R);let C=this.refs[R];if(typeof C=="string")C=this.refs[C];if(typeof C=="object")A(K,C.schema,R);else if(R!==d1(M))if(R[0]==="#")A(K,J[R],R),J[R]=K;else this.refs[R]=M;return R}function k(R){if(typeof R=="string"){if(!oB.test(R))throw Error(`invalid anchor "${R}"`);Z.call(this,`#${R}`)}}}),J;function A(K,D,L){if(D!==void 0&&!mB(K,D))throw U(L)}function U(K){return Error(`reference "${K}" resolves to more than one schema`)}}xz.getSchemaRefs=tB});var y4=P((tz)=>{Object.defineProperty(tz,"__esModule",{value:!0});tz.getData=tz.KeywordCxt=tz.validateFunctionCode=void 0;var fz=e$(),gz=v4(),zY=t9(),t6=v4(),XL=Lz(),g4=Pz(),$Y=Ez(),I=g(),v=Y1(),WL=x4(),X1=c(),_4=k4();function GL(Q){if(cz(Q)){if(pz(Q),mz(Q)){JL(Q);return}}lz(Q,()=>(0,fz.topBoolOrEmptySchema)(Q))}tz.validateFunctionCode=GL;function lz({gen:Q,validateName:Y,schema:X,schemaEnv:G,opts:W},$){if(W.code.es5)Q.func(Y,I._`${v.default.data}, ${v.default.valCxt}`,G.$async,()=>{Q.code(I._`"use strict"; ${yz(X,W)}`),zL(Q,W),Q.code($)});else Q.func(Y,I._`${v.default.data}, ${$L(W)}`,G.$async,()=>Q.code(yz(X,W)).code($))}function $L(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 zL(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 JL(Q){let{schema:Y,opts:X,gen:G}=Q;lz(Q,()=>{if(X.$comment&&Y.$comment)nz(Q);if(DL(Q),G.let(v.default.vErrors,null),G.let(v.default.errors,0),X.unevaluated)HL(Q);iz(Q),FL(Q)});return}function HL(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 yz(Q,Y){let X=typeof Q=="object"&&Q[Y.schemaId];return X&&(Y.code.source||Y.code.process)?I._`/*# sourceURL=${X} */`:I.nil}function AL(Q,Y){if(cz(Q)){if(pz(Q),mz(Q)){UL(Q,Y);return}}(0,fz.boolOrEmptySchema)(Q,Y)}function mz({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 cz(Q){return typeof Q.schema!="boolean"}function UL(Q,Y){let{schema:X,gen:G,opts:W}=Q;if(W.$comment&&X.$comment)nz(Q);BL(Q),LL(Q);let $=G.const("_errs",v.default.errors);iz(Q,$),G.var(Y,I._`${$} === ${v.default.errors}`)}function pz(Q){(0,X1.checkUnknownRules)(Q),KL(Q)}function iz(Q,Y){if(Q.opts.jtd)return uz(Q,[],!1,Y);let X=(0,gz.getSchemaTypes)(Q.schema),G=(0,gz.coerceAndCheckDataType)(Q,X);uz(Q,X,!G,Y)}function KL(Q){let{schema:Y,errSchemaPath:X,opts:G,self:W}=Q;if(Y.$ref&&G.ignoreKeywordsWithRef&&(0,X1.schemaHasRulesButRef)(Y,W.RULES))W.logger.warn(`$ref: keywords ignored in schema at path "${X}"`)}function DL(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 BL(Q){let Y=Q.schema[Q.opts.schemaId];if(Y)Q.baseId=(0,WL.resolveUrl)(Q.opts.uriResolver,Q.baseId,Y)}function LL(Q){if(Q.schema.$async&&!Q.schemaEnv.$async)throw Error("async schema in sync schema")}function nz({gen:Q,schemaEnv:Y,schema:X,errSchemaPath:G,opts:W}){let $=X.$comment;if(W.$comment===!0)Q.code(I._`${v.default.self}.logger.log(${$})`);else if(typeof W.$comment=="function"){let z=I.str`${G}/$comment`,J=Q.scopeValue("root",{ref:Y.root});Q.code(I._`${v.default.self}.opts.$comment(${$}, ${z}, ${J}.schema)`)}}function FL(Q){let{gen:Y,schemaEnv:X,validateName:G,ValidationError:W,opts:$}=Q;if(X.$async)Y.if(I._`${v.default.errors} === 0`,()=>Y.return(v.default.data),()=>Y.throw(I._`new ${W}(${v.default.vErrors})`));else{if(Y.assign(I._`${G}.errors`,v.default.vErrors),$.unevaluated)qL(Q);Y.return(I._`${v.default.errors} === 0`)}}function qL({gen:Q,evaluated:Y,props:X,items:G}){if(X instanceof I.Name)Q.assign(I._`${Y}.props`,X);if(G instanceof I.Name)Q.assign(I._`${Y}.items`,G)}function uz(Q,Y,X,G){let{gen:W,schema:$,data:z,allErrors:J,opts:H,self:A}=Q,{RULES:U}=A;if($.$ref&&(H.ignoreKeywordsWithRef||!(0,X1.schemaHasRulesButRef)($,U))){W.block(()=>dz(Q,"$ref",U.all.$ref.definition));return}if(!H.jtd)OL(Q,Y);W.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(W.if((0,t6.checkDataType)(D.type,z,H.strictNumbers)),hz(Q,D),Y.length===1&&Y[0]===D.type&&X)W.else(),(0,t6.reportTypeError)(Q);W.endIf()}else hz(Q,D);if(!J)W.if(I._`${v.default.errors} === ${G||0}`)}}function hz(Q,Y){let{gen:X,schema:G,opts:{useDefaults:W}}=Q;if(W)(0,XL.assignDefaults)(Q,Y.type);X.block(()=>{for(let $ of Y.rules)if((0,zY.shouldUseRule)(G,$))dz(Q,$.keyword,$.definition,Y.type)})}function OL(Q,Y){if(Q.schemaEnv.meta||!Q.opts.strictTypes)return;if(ML(Q,Y),!Q.opts.allowUnionTypes)VL(Q,Y);ZL(Q,Q.dataTypes)}function ML(Q,Y){if(!Y.length)return;if(!Q.dataTypes.length){Q.dataTypes=Y;return}Y.forEach((X)=>{if(!rz(Q.dataTypes,X))JY(Q,`type "${X}" not allowed by context "${Q.dataTypes.join(",")}"`)}),wL(Q,Y)}function VL(Q,Y){if(Y.length>1&&!(Y.length===2&&Y.includes("null")))JY(Q,"use allowUnionTypes to allow union type keyword")}function ZL(Q,Y){let X=Q.self.RULES.all;for(let G in X){let W=X[G];if(typeof W=="object"&&(0,zY.shouldUseRule)(Q.schema,W)){let{type:$}=W.definition;if($.length&&!$.some((z)=>NL(Y,z)))JY(Q,`missing type "${$.join(",")}" for keyword "${G}"`)}}}function NL(Q,Y){return Q.includes(Y)||Y==="number"&&Q.includes("integer")}function rz(Q,Y){return Q.includes(Y)||Y==="integer"&&Q.includes("number")}function wL(Q,Y){let X=[];for(let G of Q.dataTypes)if(rz(Y,G))X.push(G);else if(Y.includes("integer")&&G==="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",oz(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:G,schemaType:W,def:$}=this;if(X.if((0,I.or)(I._`${G} === undefined`,Y)),Q!==I.nil)X.assign(Q,!0);if(W.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:G,it:W}=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,W.opts.strictNumbers,t6.DataType.Wrong)}`}return I.nil}function z(){if(G.validateSchema){let J=Q.scopeValue("validate$data",{ref:G.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 G={...this.it,...X,items:void 0,props:void 0};return AL(G,Y),G}mergeEvaluated(Q,Y){let{it:X,gen:G}=this;if(!X.opts.unevaluated)return;if(X.props!==!0&&Q.props!==void 0)X.props=X1.mergeEvaluated.props(G,Q.props,X.props,Y);if(X.items!==!0&&Q.items!==void 0)X.items=X1.mergeEvaluated.items(G,Q.items,X.items,Y)}mergeValidEvaluated(Q,Y){let{it:X,gen:G}=this;if(X.opts.unevaluated&&(X.props!==!0||X.items!==!0))return G.if(Y,()=>this.mergeEvaluated(Q,I.Name)),!0}}tz.KeywordCxt=HY;function dz(Q,Y,X,G){let W=new HY(Q,X,Y);if("code"in X)X.code(W,G);else if(W.$data&&X.validate)(0,g4.funcKeywordCode)(W,X);else if("macro"in X)(0,g4.macroKeywordCode)(W,X);else if(X.compile||X.validate)(0,g4.funcKeywordCode)(W,X)}var PL=/^\/(?:[^~]|~0|~1)*$/,bL=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function oz(Q,{dataLevel:Y,dataNames:X,dataPathArr:G}){let W,$;if(Q==="")return v.default.rootData;if(Q[0]==="/"){if(!PL.test(Q))throw Error(`Invalid JSON-pointer: ${Q}`);W=Q,$=v.default.rootData}else{let A=bL.exec(Q);if(!A)throw Error(`Invalid JSON-pointer: ${Q}`);let U=+A[1];if(W=A[2],W==="#"){if(U>=Y)throw Error(H("property/index",U));return G[Y-U]}if(U>Y)throw Error(H("data",U));if($=X[Y-U],!W)return $}let z=$,J=W.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}`}}tz.getData=oz});var a6=P((ez)=>{Object.defineProperty(ez,"__esModule",{value:!0});class sz extends Error{constructor(Q){super("validation failed");this.errors=Q,this.ajv=this.validation=!0}}ez.default=sz});var u4=P((YJ)=>{Object.defineProperty(YJ,"__esModule",{value:!0});var AY=x4();class QJ extends Error{constructor(Q,Y,X,G){super(G||`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))}}YJ.default=QJ});var e6=P((GJ)=>{Object.defineProperty(GJ,"__esModule",{value:!0});GJ.resolveSchema=GJ.getCompilingSchema=GJ.resolveRef=GJ.compileSchema=GJ.SchemaEnv=void 0;var y0=g(),SL=a6(),R1=Y1(),u0=x4(),XJ=c(),RL=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={}}}GJ.SchemaEnv=h4;function KY(Q){let Y=WJ.call(this,Q);if(Y)return Y;let X=(0,u0.getFullPath)(this.opts.uriResolver,Q.root.baseId),{es5:G,lines:W}=this.opts.code,{ownProperties:$}=this.opts,z=new y0.CodeGen(this.scope,{es5:G,lines:W,ownProperties:$}),J;if(Q.$async)J=z.scopeValue("Error",{ref:SL.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,RL.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)}}GJ.compileSchema=KY;function CL(Q,Y,X){var G;X=(0,u0.resolveUrl)(this.opts.uriResolver,Y,X);let W=Q.refs[X];if(W)return W;let $=xL.call(this,Q,X);if($===void 0){let z=(G=Q.localRefs)===null||G===void 0?void 0:G[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]=kL.call(this,$)}GJ.resolveRef=CL;function kL(Q){if((0,u0.inlineRef)(Q.schema,this.opts.inlineRefs))return Q.schema;return Q.validate?Q:KY.call(this,Q)}function WJ(Q){for(let Y of this._compilations)if(vL(Y,Q))return Y}GJ.getCompilingSchema=WJ;function vL(Q,Y){return Q.schema===Y.schema&&Q.root===Y.root&&Q.baseId===Y.baseId}function xL(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),G=(0,u0._getFullPath)(this.opts.uriResolver,X),W=(0,u0.getFullPath)(this.opts.uriResolver,Q.baseId,void 0);if(Object.keys(Q.schema).length>0&&G===W)return UY.call(this,X,Q);let $=(0,u0.normalizeId)(G),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)W=(0,u0.resolveUrl)(this.opts.uriResolver,W,A);return new h4({schema:J,schemaId:H,root:Q,baseId:W})}return UY.call(this,X,z)}GJ.resolveSchema=s6;var _L=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function UY(Q,{baseId:Y,schema:X,root:G}){var W;if(((W=Q.fragment)===null||W===void 0?void 0:W[0])!=="/")return;for(let J of Q.fragment.slice(1).split("/")){if(typeof X==="boolean")return;let H=X[(0,XJ.unescapeFragment)(J)];if(H===void 0)return;X=H;let A=typeof X==="object"&&X[this.opts.schemaId];if(!_L.has(J)&&A)Y=(0,u0.resolveUrl)(this.opts.uriResolver,Y,A)}let $;if(typeof X!="boolean"&&X.$ref&&!(0,XJ.schemaHasRulesButRef)(X,this.RULES)){let J=(0,u0.resolveUrl)(this.opts.uriResolver,Y,X.$ref);$=s6.call(this,G,J)}let{schemaId:z}=this.opts;if($=$||new h4({schema:X,schemaId:z,root:G,baseId:Y}),$.schema!==$.root.schema)return $;return}});var zJ=P((dI,fL)=>{fL.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((oI,UJ)=>{var lL=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),HJ=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,G=0;for(G=0;G<Q.length;G++){if(X=Q[G].charCodeAt(0),X===48)continue;if(!(X>=48&&X<=57||X>=65&&X<=70||X>=97&&X<=102))return"";Y+=Q[G];break}for(G+=1;G<Q.length;G++){if(X=Q[G].charCodeAt(0),!(X>=48&&X<=57||X>=65&&X<=70||X>=97&&X<=102))return"";Y+=Q[G]}return Y}var mL=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function JJ(Q){return Q.length=0,!0}function cL(Q,Y,X){if(Q.length){let G=DY(Q);if(G!=="")Y.push(G);else return X.error=!0,!1;Q.length=0}return!0}function pL(Q){let Y=0,X={error:!1,address:"",zone:""},G=[],W=[],$=!1,z=!1,J=cL;for(let H=0;H<Q.length;H++){let A=Q[H];if(A==="["||A==="]")continue;if(A===":"){if($===!0)z=!0;if(!J(W,G,X))break;if(++Y>7){X.error=!0;break}if(H>0&&Q[H-1]===":")$=!0;G.push(":");continue}else if(A==="%"){if(!J(W,G,X))break;J=JJ}else{W.push(A);continue}}if(W.length)if(J===JJ)X.zone=W.join("");else if(z)G.push(W.join(""));else G.push(DY(W));return X.address=G.join(""),X}function AJ(Q){if(iL(Q,":")<2)return{host:Q,isIPV6:!1};let Y=pL(Q);if(!Y.error){let{address:X,address:G}=Y;if(Y.zone)X+="%"+Y.zone,G+="%25"+Y.zone;return{host:X,isIPV6:!0,escapedHost:G}}else return{host:Q,isIPV6:!1}}function iL(Q,Y){let X=0;for(let G=0;G<Q.length;G++)if(Q[G]===Y)X++;return X}function nL(Q){let Y=Q,X=[],G=-1,W=0;while(W=Y.length){if(W===1)if(Y===".")break;else if(Y==="/"){X.push("/");break}else{X.push(Y);break}else if(W===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(W===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((G=Y.indexOf("/",1))===-1){X.push(Y);break}else X.push(Y.slice(0,G)),Y=Y.slice(G)}return X.join("")}function rL(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 dL(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(!HJ(X)){let G=AJ(X);if(G.isIPV6===!0)X=`[${G.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}UJ.exports={nonSimpleDomain:mL,recomposeAuthority:dL,normalizeComponentEncoding:rL,removeDotSegments:nL,isIPv4:HJ,isUUID:lL,normalizeIPv6:AJ,stringArrayToHexStripped:DY}});var FJ=P((tI,LJ)=>{var{isUUID:oL}=BY(),tL=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,aL=["http","https","ws","wss","urn","urn:uuid"];function sL(Q){return aL.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 KJ(Q){if(!Q.host)Q.error=Q.error||"HTTP URIs must have a host.";return Q}function DJ(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 eL(Q){return Q.secure=LY(Q),Q.resourceName=(Q.path||"/")+(Q.query?"?"+Q.query:""),Q.path=void 0,Q.query=void 0,Q}function QF(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 YF(Q,Y){if(!Q.path)return Q.error="URN can not be parsed",Q;let X=Q.path.match(tL);if(X){let G=Y.scheme||Q.scheme||"urn";Q.nid=X[1].toLowerCase(),Q.nss=X[2];let W=`${G}:${Y.nid||Q.nid}`,$=FY(W);if(Q.path=void 0,$)Q=$.parse(Q,Y)}else Q.error=Q.error||"URN can not be parsed.";return Q}function XF(Q,Y){if(Q.nid===void 0)throw Error("URN without nid cannot be serialized");let X=Y.scheme||Q.scheme||"urn",G=Q.nid.toLowerCase(),W=`${X}:${Y.nid||G}`,$=FY(W);if($)Q=$.serialize(Q,Y);let z=Q,J=Q.nss;return z.path=`${G||Y.nid}:${J}`,Y.skipEscape=!0,z}function WF(Q,Y){let X=Q;if(X.uuid=X.nss,X.nss=void 0,!Y.tolerant&&(!X.uuid||!oL(X.uuid)))X.error=X.error||"UUID is not valid.";return X}function GF(Q){let Y=Q;return Y.nss=(Q.uuid||"").toLowerCase(),Y}var BJ={scheme:"http",domainHost:!0,parse:KJ,serialize:DJ},$F={scheme:"https",domainHost:BJ.domainHost,parse:KJ,serialize:DJ},QQ={scheme:"ws",domainHost:!0,parse:eL,serialize:QF},zF={scheme:"wss",domainHost:QQ.domainHost,parse:QQ.parse,serialize:QQ.serialize},JF={scheme:"urn",parse:YF,serialize:XF,skipNormalize:!0},HF={scheme:"urn:uuid",parse:WF,serialize:GF,skipNormalize:!0},YQ={http:BJ,https:$F,ws:QQ,wss:zF,urn:JF,"urn:uuid":HF};Object.setPrototypeOf(YQ,null);function FY(Q){return Q&&(YQ[Q]||YQ[Q.toLowerCase()])||void 0}LJ.exports={wsIsSecure:LY,SCHEMES:YQ,isValidSchemeName:sL,getSchemeHandler:FY}});var MJ=P((aI,WQ)=>{var{normalizeIPv6:AF,removeDotSegments:f4,recomposeAuthority:UF,normalizeComponentEncoding:XQ,isIPv4:KF,nonSimpleDomain:DF}=BY(),{SCHEMES:BF,getSchemeHandler:qJ}=FJ();function LF(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 FF(Q,Y,X){let G=X?Object.assign({scheme:"null"},X):{scheme:"null"},W=OJ(W1(Q,G),W1(Y,G),G,!0);return G.skipEscape=!0,i0(W,G)}function OJ(Q,Y,X,G){let W={};if(!G)Q=W1(i0(Q,X),X),Y=W1(i0(Y,X),X);if(X=X||{},!X.tolerant&&Y.scheme)W.scheme=Y.scheme,W.userinfo=Y.userinfo,W.host=Y.host,W.port=Y.port,W.path=f4(Y.path||""),W.query=Y.query;else{if(Y.userinfo!==void 0||Y.host!==void 0||Y.port!==void 0)W.userinfo=Y.userinfo,W.host=Y.host,W.port=Y.port,W.path=f4(Y.path||""),W.query=Y.query;else{if(!Y.path)if(W.path=Q.path,Y.query!==void 0)W.query=Y.query;else W.query=Q.query;else{if(Y.path[0]==="/")W.path=f4(Y.path);else{if((Q.userinfo!==void 0||Q.host!==void 0||Q.port!==void 0)&&!Q.path)W.path="/"+Y.path;else if(!Q.path)W.path=Y.path;else W.path=Q.path.slice(0,Q.path.lastIndexOf("/")+1)+Y.path;W.path=f4(W.path)}W.query=Y.query}W.userinfo=Q.userinfo,W.host=Q.host,W.port=Q.port}W.scheme=Q.scheme}return W.fragment=Y.fragment,W}function qF(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:""},G=Object.assign({},Y),W=[],$=qJ(G.scheme||X.scheme);if($&&$.serialize)$.serialize(X,G);if(X.path!==void 0)if(!G.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(G.reference!=="suffix"&&X.scheme)W.push(X.scheme,":");let z=UF(X);if(z!==void 0){if(G.reference!=="suffix")W.push("//");if(W.push(z),X.path&&X.path[0]!=="/")W.push("/")}if(X.path!==void 0){let J=X.path;if(!G.absolutePath&&(!$||!$.absolutePath))J=f4(J);if(z===void 0&&J[0]==="/"&&J[1]==="/")J="/%2F"+J.slice(2);W.push(J)}if(X.query!==void 0)W.push("?",X.query);if(X.fragment!==void 0)W.push("#",X.fragment);return W.join("")}var OF=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function W1(Q,Y){let X=Object.assign({},Y),G={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},W=!1;if(X.reference==="suffix")if(X.scheme)Q=X.scheme+":"+Q;else Q="//"+Q;let $=Q.match(OF);if($){if(G.scheme=$[1],G.userinfo=$[3],G.host=$[4],G.port=parseInt($[5],10),G.path=$[6]||"",G.query=$[7],G.fragment=$[8],isNaN(G.port))G.port=$[5];if(G.host)if(KF(G.host)===!1){let H=AF(G.host);G.host=H.host.toLowerCase(),W=H.isIPV6}else W=!0;if(G.scheme===void 0&&G.userinfo===void 0&&G.host===void 0&&G.port===void 0&&G.query===void 0&&!G.path)G.reference="same-document";else if(G.scheme===void 0)G.reference="relative";else if(G.fragment===void 0)G.reference="absolute";else G.reference="uri";if(X.reference&&X.reference!=="suffix"&&X.reference!==G.reference)G.error=G.error||"URI is not a "+X.reference+" reference.";let z=qJ(X.scheme||G.scheme);if(!X.unicodeSupport&&(!z||!z.unicodeSupport)){if(G.host&&(X.domainHost||z&&z.domainHost)&&W===!1&&DF(G.host))try{G.host=URL.domainToASCII(G.host.toLowerCase())}catch(J){G.error=G.error||"Host's domain name can not be converted to ASCII: "+J}}if(!z||z&&!z.skipNormalize){if(Q.indexOf("%")!==-1){if(G.scheme!==void 0)G.scheme=unescape(G.scheme);if(G.host!==void 0)G.host=unescape(G.host)}if(G.path)G.path=escape(unescape(G.path));if(G.fragment)G.fragment=encodeURI(decodeURIComponent(G.fragment))}if(z&&z.parse)z.parse(G,X)}else G.error=G.error||"URI can not be parsed.";return G}var qY={SCHEMES:BF,normalize:LF,resolve:FF,resolveComponent:OJ,equal:qF,serialize:i0,parse:W1};WQ.exports=qY;WQ.exports.default=qY;WQ.exports.fastUri=qY});var NJ=P((ZJ)=>{Object.defineProperty(ZJ,"__esModule",{value:!0});var VJ=MJ();VJ.code='require("ajv/dist/runtime/uri").default';ZJ.default=VJ});var SJ=P((G1)=>{Object.defineProperty(G1,"__esModule",{value:!0});G1.CodeGen=G1.Name=G1.nil=G1.stringify=G1.str=G1._=G1.KeywordCxt=void 0;var VF=y4();Object.defineProperty(G1,"KeywordCxt",{enumerable:!0,get:function(){return VF.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 ZF=a6(),IJ=u4(),NF=o9(),l4=e6(),wF=g(),m4=x4(),GQ=v4(),MY=c(),wJ=zJ(),PF=NJ(),EJ=(Q,Y)=>new RegExp(Q,Y);EJ.code="new RegExp";var bF=["removeAdditional","useDefaults","coerceTypes"],jF=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),IF={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."},EF={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},PJ=200;function TF(Q){var Y,X,G,W,$,z,J,H,A,U,K,D,L,O,M,w,Z,k,R,y,C,c0,o0,jQ,IQ;let X4=Q.strict,EQ=(Y=Q.code)===null||Y===void 0?void 0:Y.optimize,LX=EQ===!0||EQ===void 0?1:EQ||0,FX=(G=(X=Q.code)===null||X===void 0?void 0:X.regExp)!==null&&G!==void 0?G:EJ,bH=(W=Q.uriResolver)!==null&&W!==void 0?W:PF.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:LX,regExp:FX}:{optimize:LX,regExp:FX},loopRequired:(M=Q.loopRequired)!==null&&M!==void 0?M:PJ,loopEnum:(w=Q.loopEnum)!==null&&w!==void 0?w:PJ,meta:(Z=Q.meta)!==null&&Z!==void 0?Z:!0,messages:(k=Q.messages)!==null&&k!==void 0?k:!0,inlineRefs:(R=Q.inlineRefs)!==null&&R!==void 0?R:!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:bH}}class $Q{constructor(Q={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,Q=this.opts={...Q,...TF(Q)};let{es5:Y,lines:X}=this.opts.code;this.scope=new wF.ValueScope({scope:{},prefixes:jF,es5:Y,lines:X}),this.logger=xF(Q.logger);let G=Q.validateFormats;if(Q.validateFormats=!1,this.RULES=(0,NF.getRules)(),bJ.call(this,IF,Q,"NOT SUPPORTED"),bJ.call(this,EF,Q,"DEPRECATED","warn"),this._metaOpts=kF.call(this),Q.formats)RF.call(this);if(this._addVocabularies(),this._addDefaultMetaSchema(),Q.keywords)CF.call(this,Q.keywords);if(typeof Q.meta=="object")this.addMetaSchema(Q.meta);SF.call(this),Q.validateFormats=G}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:Q,meta:Y,schemaId:X}=this.opts,G=wJ;if(X==="id")G={...wJ},G.id=G.$id,delete G.$id;if(Y&&Q)this.addMetaSchema(G,G[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 G=X(Y);if(!("$async"in X))this.errors=X.errors;return G}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 G.call(this,Q,Y);async function G(A,U){await W.call(this,A.$schema);let K=this._addSchema(A,U);return K.validate||$.call(this,K)}async function W(A){if(A&&!this.getSchema(A))await G.call(this,{$ref:A},!0)}async function $(A){try{return this._compileSchemaEnv(A)}catch(U){if(!(U instanceof IJ.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 W.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,G=this.opts.validateSchema){if(Array.isArray(Q)){for(let $ of Q)this.addSchema($,void 0,X,G);return this}let W;if(typeof Q==="object"){let{schemaId:$}=this.opts;if(W=Q[$],W!==void 0&&typeof W!="string")throw Error(`schema ${$} must be string`)}return Y=(0,m4.normalizeId)(Y||W),this._checkUnique(Y),this.schemas[Y]=this._addSchema(Q,X,Y,G,!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 G=this.validate(X,Q);if(!G&&Y){let W="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(W);else throw Error(W)}return G}getSchema(Q){let Y;while(typeof(Y=jJ.call(this,Q))=="string")Q=Y;if(Y===void 0){let{schemaId:X}=this.opts,G=new l4.SchemaEnv({schema:{},schemaId:X});if(Y=l4.resolveSchema.call(this,G,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=jJ.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(gF.call(this,X,Y),!Y)return(0,MY.eachItem)(X,(W)=>OY.call(this,W)),this;uF.call(this,Y);let G={...Y,type:(0,GQ.getJSONTypes)(Y.type),schemaType:(0,GQ.getJSONTypes)(Y.schemaType)};return(0,MY.eachItem)(X,G.type.length===0?(W)=>OY.call(this,W,G):(W)=>G.type.forEach(($)=>OY.call(this,W,G,$))),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 G=X.rules.findIndex((W)=>W.keyword===Q);if(G>=0)X.rules.splice(G,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((G)=>`${X}${G.instancePath} ${G.message}`).reduce((G,W)=>G+Y+W)}$dataMetaSchema(Q,Y){let X=this.RULES.all;Q=JSON.parse(JSON.stringify(Q));for(let G of Y){let W=G.split("/").slice(1),$=Q;for(let z of W)$=$[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]=TJ(A)}}return Q}_removeAllSchemas(Q,Y){for(let X in Q){let G=Q[X];if(!Y||Y.test(X)){if(typeof G=="string")delete Q[X];else if(G&&!G.meta)this._cache.delete(G.schema),delete Q[X]}}}_addSchema(Q,Y,X,G=this.opts.validateSchema,W=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),W&&!X.startsWith("#")){if(X)this._checkUnique(X);this.refs[X]=J}if(G)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=ZF.default;$Q.MissingRefError=IJ.default;G1.default=$Q;function bJ(Q,Y,X,G="error"){for(let W in Q){let $=W;if($ in Y)this.logger[G](`${X}: option ${W}. ${Q[$]}`)}}function jJ(Q){return Q=(0,m4.normalizeId)(Q),this.schemas[Q]||this.refs[Q]}function SF(){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 RF(){for(let Q in this.opts.formats){let Y=this.opts.formats[Q];if(Y)this.addFormat(Q,Y)}}function CF(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 kF(){let Q={...this.opts};for(let Y of bF)delete Q[Y];return Q}var vF={log(){},warn(){},error(){}};function xF(Q){if(Q===!1)return vF;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 _F=/^[a-z_$][a-z0-9_$:-]*$/i;function gF(Q,Y){let{RULES:X}=this;if((0,MY.eachItem)(Q,(G)=>{if(X.keywords[G])throw Error(`Keyword ${G} is already defined`);if(!_F.test(G))throw Error(`Keyword ${G} 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 G;let W=Y===null||Y===void 0?void 0:Y.post;if(X&&W)throw Error('keyword with "post" flag cannot have "type"');let{RULES:$}=this,z=W?$.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)yF.call(this,z,J,Y.before);else z.rules.push(J);$.all[Q]=J,(G=Y.implements)===null||G===void 0||G.forEach((H)=>this.addKeyword(H))}function yF(Q,Y,X){let G=Q.rules.findIndex((W)=>W.keyword===X);if(G>=0)Q.rules.splice(G,0,Y);else Q.rules.push(Y),this.logger.warn(`rule ${X} is not defined`)}function uF(Q){let{metaSchema:Y}=Q;if(Y===void 0)return;if(Q.$data&&this.opts.$data)Y=TJ(Y);Q.validateSchema=this.compile(Y,!0)}var hF={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function TJ(Q){return{anyOf:[Q,hF]}}});var CJ=P((RJ)=>{Object.defineProperty(RJ,"__esModule",{value:!0});var mF={keyword:"id",code(){throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};RJ.default=mF});var yJ=P((_J)=>{Object.defineProperty(_J,"__esModule",{value:!0});_J.callRef=_J.getValidate=void 0;var pF=u4(),kJ=C0(),w0=g(),t1=Y1(),vJ=e6(),zQ=c(),iF={keyword:"$ref",schemaType:"string",code(Q){let{gen:Y,schema:X,it:G}=Q,{baseId:W,schemaEnv:$,validateName:z,opts:J,self:H}=G,{root:A}=$;if((X==="#"||X==="#/")&&W===A.baseId)return K();let U=vJ.resolveRef.call(H,A,W,X);if(U===void 0)throw new pF.default(G.opts.uriResolver,W,X);if(U instanceof vJ.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=xJ(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}),w=Y.name("valid"),Z=Q.subschema({schema:O,dataTypes:[],schemaPath:w0.nil,topSchemaRef:M,errSchemaPath:X},w);Q.mergeEvaluated(Z),Q.ok(w)}}};function xJ(Q,Y){let{gen:X}=Q;return Y.validate?X.scopeValue("validate",{ref:Y.validate}):w0._`${X.scopeValue("wrapper",{ref:Y})}.validate`}_J.getValidate=xJ;function JQ(Q,Y,X,G){let{gen:W,it:$}=Q,{allErrors:z,schemaEnv:J,opts:H}=$,A=H.passContext?t1.default.this:w0.nil;if(G)U();else K();function U(){if(!J.$async)throw Error("async schema referenced by sync schema");let O=W.let("valid");W.try(()=>{if(W.code(w0._`await ${(0,kJ.callValidateCode)(Q,Y,A)}`),L(Y),!z)W.assign(O,!0)},(M)=>{if(W.if(w0._`!(${M} instanceof ${$.ValidationError})`,()=>W.throw(M)),D(M),!z)W.assign(O,!1)}),Q.ok(O)}function K(){Q.result((0,kJ.callValidateCode)(Q,Y,A),()=>L(Y),()=>D(Y))}function D(O){let M=w0._`${O}.errors`;W.assign(t1.default.vErrors,w0._`${t1.default.vErrors} === null ? ${M} : ${t1.default.vErrors}.concat(${M})`),W.assign(t1.default.errors,w0._`${t1.default.vErrors}.length`)}function L(O){var M;if(!$.opts.unevaluated)return;let w=(M=X===null||X===void 0?void 0:X.validate)===null||M===void 0?void 0:M.evaluated;if($.props!==!0)if(w&&!w.dynamicProps){if(w.props!==void 0)$.props=zQ.mergeEvaluated.props(W,w.props,$.props)}else{let Z=W.var("props",w0._`${O}.evaluated.props`);$.props=zQ.mergeEvaluated.props(W,Z,$.props,w0.Name)}if($.items!==!0)if(w&&!w.dynamicItems){if(w.items!==void 0)$.items=zQ.mergeEvaluated.items(W,w.items,$.items)}else{let Z=W.var("items",w0._`${O}.evaluated.items`);$.items=zQ.mergeEvaluated.items(W,Z,$.items,w0.Name)}}}_J.callRef=JQ;_J.default=iF});var hJ=P((uJ)=>{Object.defineProperty(uJ,"__esModule",{value:!0});var dF=CJ(),oF=yJ(),tF=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",dF.default,oF.default];uJ.default=tF});var lJ=P((fJ)=>{Object.defineProperty(fJ,"__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}},sF={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}}`},eF={keyword:Object.keys(AQ),type:"number",schemaType:"number",$data:!0,error:sF,code(Q){let{keyword:Y,data:X,schemaCode:G}=Q;Q.fail$data(HQ._`${X} ${AQ[Y].fail} ${G} || isNaN(${X})`)}};fJ.default=eF});var cJ=P((mJ)=>{Object.defineProperty(mJ,"__esModule",{value:!0});var c4=g(),Yq={message:({schemaCode:Q})=>c4.str`must be multiple of ${Q}`,params:({schemaCode:Q})=>c4._`{multipleOf: ${Q}}`},Xq={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:Yq,code(Q){let{gen:Y,data:X,schemaCode:G,it:W}=Q,$=W.opts.multipleOfPrecision,z=Y.let("res"),J=$?c4._`Math.abs(Math.round(${z}) - ${z}) > 1e-${$}`:c4._`${z} !== parseInt(${z})`;Q.fail$data(c4._`(${G} === 0 || (${z} = ${X}/${G}, ${J}))`)}};mJ.default=Xq});var nJ=P((iJ)=>{Object.defineProperty(iJ,"__esModule",{value:!0});function pJ(Q){let Y=Q.length,X=0,G=0,W;while(G<Y)if(X++,W=Q.charCodeAt(G++),W>=55296&&W<=56319&&G<Y){if(W=Q.charCodeAt(G),(W&64512)===56320)G++}return X}iJ.default=pJ;pJ.code='require("ajv/dist/runtime/ucs2length").default'});var dJ=P((rJ)=>{Object.defineProperty(rJ,"__esModule",{value:!0});var C1=g(),$q=c(),zq=nJ(),Jq={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}}`},Hq={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:Jq,code(Q){let{keyword:Y,data:X,schemaCode:G,it:W}=Q,$=Y==="maxLength"?C1.operators.GT:C1.operators.LT,z=W.opts.unicode===!1?C1._`${X}.length`:C1._`${(0,$q.useFunc)(Q.gen,zq.default)}(${X})`;Q.fail$data(C1._`${z} ${$} ${G}`)}};rJ.default=Hq});var tJ=P((oJ)=>{Object.defineProperty(oJ,"__esModule",{value:!0});var Uq=C0(),UQ=g(),Kq={message:({schemaCode:Q})=>UQ.str`must match pattern "${Q}"`,params:({schemaCode:Q})=>UQ._`{pattern: ${Q}}`},Dq={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:Kq,code(Q){let{data:Y,$data:X,schema:G,schemaCode:W,it:$}=Q,z=$.opts.unicodeRegExp?"u":"",J=X?UQ._`(new RegExp(${W}, ${z}))`:(0,Uq.usePattern)(Q,G);Q.fail$data(UQ._`!${J}.test(${Y})`)}};oJ.default=Dq});var sJ=P((aJ)=>{Object.defineProperty(aJ,"__esModule",{value:!0});var p4=g(),Lq={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}}`},Fq={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:Lq,code(Q){let{keyword:Y,data:X,schemaCode:G}=Q,W=Y==="maxProperties"?p4.operators.GT:p4.operators.LT;Q.fail$data(p4._`Object.keys(${X}).length ${W} ${G}`)}};aJ.default=Fq});var Q7=P((eJ)=>{Object.defineProperty(eJ,"__esModule",{value:!0});var i4=C0(),n4=g(),Oq=c(),Mq={message:({params:{missingProperty:Q}})=>n4.str`must have required property '${Q}'`,params:({params:{missingProperty:Q}})=>n4._`{missingProperty: ${Q}}`},Vq={keyword:"required",type:"object",schemaType:"array",$data:!0,error:Mq,code(Q){let{gen:Y,schema:X,schemaCode:G,data:W,$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 w=z.schemaEnv.baseId+z.errSchemaPath,Z=`required property "${M}" is not defined at "${w}" (strictRequired)`;(0,Oq.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",G,(L)=>{Q.setParams({missingProperty:L}),Y.if((0,i4.noPropertyInData)(Y,W,L,J.ownProperties),()=>Q.error())})}function D(L,O){Q.setParams({missingProperty:L}),Y.forOf(L,G,()=>{Y.assign(O,(0,i4.propertyInData)(Y,W,L,J.ownProperties)),Y.if((0,n4.not)(O),()=>{Q.error(),Y.break()})},n4.nil)}}};eJ.default=Vq});var X7=P((Y7)=>{Object.defineProperty(Y7,"__esModule",{value:!0});var r4=g(),Nq={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}}`},wq={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:Nq,code(Q){let{keyword:Y,data:X,schemaCode:G}=Q,W=Y==="maxItems"?r4.operators.GT:r4.operators.LT;Q.fail$data(r4._`${X}.length ${W} ${G}`)}};Y7.default=wq});var KQ=P((G7)=>{Object.defineProperty(G7,"__esModule",{value:!0});var W7=WY();W7.code='require("ajv/dist/runtime/equal").default';G7.default=W7});var z7=P(($7)=>{Object.defineProperty($7,"__esModule",{value:!0});var VY=v4(),L0=g(),jq=c(),Iq=KQ(),Eq={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}}`},Tq={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:Eq,code(Q){let{gen:Y,data:X,$data:G,schema:W,parentSchema:$,schemaCode:z,it:J}=Q;if(!G&&!W)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 w=Y.name("item"),Z=(0,VY.checkDataTypes)(A,w,J.opts.strictNumbers,VY.DataType.Wrong),k=Y.const("indices",L0._`{}`);Y.for(L0._`;${O}--;`,()=>{if(Y.let(w,L0._`${X}[${O}]`),Y.if(Z,L0._`continue`),A.length>1)Y.if(L0._`typeof ${w} == "string"`,L0._`${w} += "_"`);Y.if(L0._`typeof ${k}[${w}] == "number"`,()=>{Y.assign(M,L0._`${k}[${w}]`),Q.error(),Y.assign(H,!1).break()}).code(L0._`${k}[${w}] = ${O}`)})}function L(O,M){let w=(0,jq.useFunc)(Y,Iq.default),Z=Y.name("outer");Y.label(Z).for(L0._`;${O}--;`,()=>Y.for(L0._`${M} = ${O}; ${M}--;`,()=>Y.if(L0._`${w}(${X}[${O}], ${X}[${M}])`,()=>{Q.error(),Y.assign(H,!1).break(Z)})))}}};$7.default=Tq});var H7=P((J7)=>{Object.defineProperty(J7,"__esModule",{value:!0});var ZY=g(),Rq=c(),Cq=KQ(),kq={message:"must be equal to constant",params:({schemaCode:Q})=>ZY._`{allowedValue: ${Q}}`},vq={keyword:"const",$data:!0,error:kq,code(Q){let{gen:Y,data:X,$data:G,schemaCode:W,schema:$}=Q;if(G||$&&typeof $=="object")Q.fail$data(ZY._`!${(0,Rq.useFunc)(Y,Cq.default)}(${X}, ${W})`);else Q.fail(ZY._`${$} !== ${X}`)}};J7.default=vq});var U7=P((A7)=>{Object.defineProperty(A7,"__esModule",{value:!0});var d4=g(),_q=c(),gq=KQ(),yq={message:"must be equal to one of the allowed values",params:({schemaCode:Q})=>d4._`{allowedValues: ${Q}}`},uq={keyword:"enum",schemaType:"array",$data:!0,error:yq,code(Q){let{gen:Y,data:X,$data:G,schema:W,schemaCode:$,it:z}=Q;if(!G&&W.length===0)throw Error("enum must have non-empty array");let J=W.length>=z.opts.loopEnum,H,A=()=>H!==null&&H!==void 0?H:H=(0,_q.useFunc)(Y,gq.default),U;if(J||G)U=Y.let("valid"),Q.block$data(U,K);else{if(!Array.isArray(W))throw Error("ajv implementation error");let L=Y.const("vSchema",$);U=(0,d4.or)(...W.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=W[O];return typeof M==="object"&&M!==null?d4._`${A()}(${X}, ${L}[${O}])`:d4._`${X} === ${M}`}}};A7.default=uq});var D7=P((K7)=>{Object.defineProperty(K7,"__esModule",{value:!0});var fq=lJ(),lq=cJ(),mq=dJ(),cq=tJ(),pq=sJ(),iq=Q7(),nq=X7(),rq=z7(),dq=H7(),oq=U7(),tq=[fq.default,lq.default,mq.default,cq.default,pq.default,iq.default,nq.default,rq.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},dq.default,oq.default];K7.default=tq});var wY=P((L7)=>{Object.defineProperty(L7,"__esModule",{value:!0});L7.validateAdditionalItems=void 0;var k1=g(),NY=c(),sq={message:({params:{len:Q}})=>k1.str`must NOT have more than ${Q} items`,params:({params:{len:Q}})=>k1._`{limit: ${Q}}`},eq={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:sq,code(Q){let{parentSchema:Y,it:X}=Q,{items:G}=Y;if(!Array.isArray(G)){(0,NY.checkStrictMode)(X,'"additionalItems" is ignored when "items" is not an array of schemas');return}B7(Q,G)}};function B7(Q,Y){let{gen:X,schema:G,data:W,keyword:$,it:z}=Q;z.items=!0;let J=X.const("len",k1._`${W}.length`);if(G===!1)Q.setParams({len:Y.length}),Q.pass(k1._`${J} <= ${Y.length}`);else if(typeof G=="object"&&!(0,NY.alwaysValidSchema)(z,G)){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())})}}L7.validateAdditionalItems=B7;L7.default=eq});var PY=P((M7)=>{Object.defineProperty(M7,"__esModule",{value:!0});M7.validateTuple=void 0;var q7=g(),DQ=c(),YO=C0(),XO={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(Q){let{schema:Y,it:X}=Q;if(Array.isArray(Y))return O7(Q,"additionalItems",Y);if(X.items=!0,(0,DQ.alwaysValidSchema)(X,Y))return;Q.ok((0,YO.validateArray)(Q))}};function O7(Q,Y,X=Q.schema){let{gen:G,parentSchema:W,data:$,keyword:z,it:J}=Q;if(U(W),J.opts.unevaluated&&X.length&&J.items!==!0)J.items=DQ.mergeEvaluated.items(G,X.length,J.items);let H=G.name("valid"),A=G.const("len",q7._`${$}.length`);X.forEach((K,D)=>{if((0,DQ.alwaysValidSchema)(J,K))return;G.if(q7._`${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 w=`"${z}" is ${O}-tuple, but minItems or maxItems/${Y} are not specified or different at path "${L}"`;(0,DQ.checkStrictMode)(J,w,D.strictTuples)}}}M7.validateTuple=O7;M7.default=XO});var N7=P((Z7)=>{Object.defineProperty(Z7,"__esModule",{value:!0});var GO=PY(),$O={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:(Q)=>(0,GO.validateTuple)(Q,"items")};Z7.default=$O});var b7=P((P7)=>{Object.defineProperty(P7,"__esModule",{value:!0});var w7=g(),JO=c(),HO=C0(),AO=wY(),UO={message:({params:{len:Q}})=>w7.str`must NOT have more than ${Q} items`,params:({params:{len:Q}})=>w7._`{limit: ${Q}}`},KO={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:UO,code(Q){let{schema:Y,parentSchema:X,it:G}=Q,{prefixItems:W}=X;if(G.items=!0,(0,JO.alwaysValidSchema)(G,Y))return;if(W)(0,AO.validateAdditionalItems)(Q,W);else Q.ok((0,HO.validateArray)(Q))}};P7.default=KO});var I7=P((j7)=>{Object.defineProperty(j7,"__esModule",{value:!0});var k0=g(),BQ=c(),BO={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}}`},LO={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:BO,code(Q){let{gen:Y,schema:X,parentSchema:G,data:W,it:$}=Q,z,J,{minContains:H,maxContains:A}=G;if($.opts.next)z=H===void 0?1:H,J=A;else z=1;let U=Y.const("len",k0._`${W}.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._`${W}.length > 0`,D)}else Y.let(K,!1),D();Q.result(K,()=>Q.reset());function D(){let M=Y.name("_valid"),w=Y.let("count",0);L(M,()=>Y.if(M,()=>O(w)))}function L(M,w){Y.forRange("i",0,U,(Z)=>{Q.subschema({keyword:"contains",dataProp:Z,dataPropType:BQ.Type.Num,compositeRule:!0},M),w()})}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))}}};j7.default=LO});var k7=P((S7)=>{Object.defineProperty(S7,"__esModule",{value:!0});S7.validateSchemaDeps=S7.validatePropertyDeps=S7.error=void 0;var bY=g(),qO=c(),o4=C0();S7.error={message:({params:{property:Q,depsCount:Y,deps:X}})=>{let G=Y===1?"property":"properties";return bY.str`must have ${G} ${X} when property ${Q} is present`},params:({params:{property:Q,depsCount:Y,deps:X,missingProperty:G}})=>bY._`{property: ${Q},
|
|
7
|
-
missingProperty: ${
|
|
8
|
-
depsCount: ${
|
|
9
|
-
deps: ${X}}`};var OO={keyword:"dependencies",type:"object",schemaType:"object",error:S7.error,code(Q){let[Y,X]=MO(Q);E7(Q,Y),T7(Q,X)}};function MO({schema:Q}){let Y={},X={};for(let G in Q){if(G==="__proto__")continue;let W=Array.isArray(Q[G])?Y:X;W[G]=Q[G]}return[Y,X]}function E7(Q,Y=Q.schema){let{gen:X,data:G,it:W}=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,G,z,W.opts.ownProperties);if(Q.setParams({property:z,depsCount:J.length,deps:J.join(", ")}),W.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()}}S7.validatePropertyDeps=E7;function T7(Q,Y=Q.schema){let{gen:X,data:G,keyword:W,it:$}=Q,z=X.name("valid");for(let J in Y){if((0,qO.alwaysValidSchema)($,Y[J]))continue;X.if((0,o4.propertyInData)(X,G,J,$.opts.ownProperties),()=>{let H=Q.subschema({keyword:W,schemaProp:J},z);Q.mergeValidEvaluated(H,z)},()=>X.var(z,!0)),Q.ok(z)}}S7.validateSchemaDeps=T7;S7.default=OO});var _7=P((x7)=>{Object.defineProperty(x7,"__esModule",{value:!0});var v7=g(),NO=c(),wO={message:"property name must be valid",params:({params:Q})=>v7._`{propertyName: ${Q.propertyName}}`},PO={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:wO,code(Q){let{gen:Y,schema:X,data:G,it:W}=Q;if((0,NO.alwaysValidSchema)(W,X))return;let $=Y.name("valid");Y.forIn("key",G,(z)=>{Q.setParams({propertyName:z}),Q.subschema({keyword:"propertyNames",data:z,dataTypes:["string"],propertyName:z,compositeRule:!0},$),Y.if((0,v7.not)($),()=>{if(Q.error(!0),!W.allErrors)Y.break()})}),Q.ok($)}};x7.default=PO});var jY=P((g7)=>{Object.defineProperty(g7,"__esModule",{value:!0});var LQ=C0(),h0=g(),jO=Y1(),FQ=c(),IO={message:"must NOT have additional properties",params:({params:Q})=>h0._`{additionalProperty: ${Q.additionalProperty}}`},EO={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:IO,code(Q){let{gen:Y,schema:X,parentSchema:G,data:W,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)(G.properties),U=(0,LQ.allSchemaProperties)(G.patternProperties);K(),Q.ok(h0._`${$} === ${jO.default.errors}`);function K(){Y.forIn("key",W,(w)=>{if(!A.length&&!U.length)O(w);else Y.if(D(w),()=>O(w))})}function D(w){let Z;if(A.length>8){let k=(0,FQ.schemaRefOrVal)(z,G.properties,"properties");Z=(0,LQ.isOwnProperty)(Y,k,w)}else if(A.length)Z=(0,h0.or)(...A.map((k)=>h0._`${w} === ${k}`));else Z=h0.nil;if(U.length)Z=(0,h0.or)(Z,...U.map((k)=>h0._`${(0,LQ.usePattern)(Q,k)}.test(${w})`));return(0,h0.not)(Z)}function L(w){Y.code(h0._`delete ${W}[${w}]`)}function O(w){if(H.removeAdditional==="all"||H.removeAdditional&&X===!1){L(w);return}if(X===!1){if(Q.setParams({additionalProperty:w}),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(w,Z,!1),Y.if((0,h0.not)(Z),()=>{Q.reset(),L(w)});else if(M(w,Z),!J)Y.if((0,h0.not)(Z),()=>Y.break())}}function M(w,Z,k){let R={keyword:"additionalProperties",dataProp:w,dataPropType:FQ.Type.Str};if(k===!1)Object.assign(R,{compositeRule:!0,createErrors:!1,allErrors:!1});Q.subschema(R,Z)}}};g7.default=EO});var f7=P((h7)=>{Object.defineProperty(h7,"__esModule",{value:!0});var SO=y4(),y7=C0(),IY=c(),u7=jY(),RO={keyword:"properties",type:"object",schemaType:"object",code(Q){let{gen:Y,schema:X,parentSchema:G,data:W,it:$}=Q;if($.opts.removeAdditional==="all"&&G.additionalProperties===void 0)u7.default.code(new SO.KeywordCxt($,u7.default,"additionalProperties"));let z=(0,y7.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,y7.propertyInData)(Y,W,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)}}};h7.default=RO});var i7=P((p7)=>{Object.defineProperty(p7,"__esModule",{value:!0});var l7=C0(),qQ=g(),m7=c(),c7=c(),kO={keyword:"patternProperties",type:"object",schemaType:"object",code(Q){let{gen:Y,schema:X,data:G,parentSchema:W,it:$}=Q,{opts:z}=$,J=(0,l7.allSchemaProperties)(X),H=J.filter((M)=>(0,m7.alwaysValidSchema)($,X[M]));if(J.length===0||H.length===J.length&&(!$.opts.unevaluated||$.props===!0))return;let A=z.strictSchema&&!z.allowMatchingProperties&&W.properties,U=Y.name("valid");if($.props!==!0&&!($.props instanceof qQ.Name))$.props=(0,c7.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 w in A)if(new RegExp(M).test(w))(0,m7.checkStrictMode)($,`property ${w} matches pattern ${M} (use allowMatchingProperties)`)}function O(M){Y.forIn("key",G,(w)=>{Y.if(qQ._`${(0,l7.usePattern)(Q,M)}.test(${w})`,()=>{let Z=H.includes(M);if(!Z)Q.subschema({keyword:"patternProperties",schemaProp:M,dataProp:w,dataPropType:c7.Type.Str},U);if($.opts.unevaluated&&K!==!0)Y.assign(qQ._`${K}[${w}]`,!0);else if(!Z&&!$.allErrors)Y.if((0,qQ.not)(U),()=>Y.break())})})}}};p7.default=kO});var r7=P((n7)=>{Object.defineProperty(n7,"__esModule",{value:!0});var xO=c(),_O={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(Q){let{gen:Y,schema:X,it:G}=Q;if((0,xO.alwaysValidSchema)(G,X)){Q.fail();return}let W=Y.name("valid");Q.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},W),Q.failResult(W,()=>Q.reset(),()=>Q.error())},error:{message:"must NOT be valid"}};n7.default=_O});var o7=P((d7)=>{Object.defineProperty(d7,"__esModule",{value:!0});var yO=C0(),uO={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:yO.validateUnion,error:{message:"must match a schema in anyOf"}};d7.default=uO});var a7=P((t7)=>{Object.defineProperty(t7,"__esModule",{value:!0});var OQ=g(),fO=c(),lO={message:"must match exactly one schema in oneOf",params:({params:Q})=>OQ._`{passingSchemas: ${Q.passing}}`},mO={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:lO,code(Q){let{gen:Y,schema:X,parentSchema:G,it:W}=Q;if(!Array.isArray(X))throw Error("ajv implementation error");if(W.opts.discriminator&&G.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,fO.alwaysValidSchema)(W,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)})})}}};t7.default=mO});var e7=P((s7)=>{Object.defineProperty(s7,"__esModule",{value:!0});var pO=c(),iO={keyword:"allOf",schemaType:"array",code(Q){let{gen:Y,schema:X,it:G}=Q;if(!Array.isArray(X))throw Error("ajv implementation error");let W=Y.name("valid");X.forEach(($,z)=>{if((0,pO.alwaysValidSchema)(G,$))return;let J=Q.subschema({keyword:"allOf",schemaProp:z},W);Q.ok(W),Q.mergeEvaluated(J)})}};s7.default=iO});var W5=P((X5)=>{Object.defineProperty(X5,"__esModule",{value:!0});var MQ=g(),Y5=c(),rO={message:({params:Q})=>MQ.str`must match "${Q.ifClause}" schema`,params:({params:Q})=>MQ._`{failingKeyword: ${Q.ifClause}}`},dO={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:rO,code(Q){let{gen:Y,parentSchema:X,it:G}=Q;if(X.then===void 0&&X.else===void 0)(0,Y5.checkStrictMode)(G,'"if" without "then" and "else" is ignored');let W=Q5(G,"then"),$=Q5(G,"else");if(!W&&!$)return;let z=Y.let("valid",!0),J=Y.name("_valid");if(H(),Q.reset(),W&&$){let U=Y.let("ifClause");Q.setParams({ifClause:U}),Y.if(J,A("then",U),A("else",U))}else if(W)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 Q5(Q,Y){let X=Q.schema[Y];return X!==void 0&&!(0,Y5.alwaysValidSchema)(Q,X)}X5.default=dO});var $5=P((G5)=>{Object.defineProperty(G5,"__esModule",{value:!0});var tO=c(),aO={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:Q,parentSchema:Y,it:X}){if(Y.if===void 0)(0,tO.checkStrictMode)(X,`"${Q}" without "if" is ignored`)}};G5.default=aO});var J5=P((z5)=>{Object.defineProperty(z5,"__esModule",{value:!0});var eO=wY(),QM=N7(),YM=PY(),XM=b7(),WM=I7(),GM=k7(),$M=_7(),zM=jY(),JM=f7(),HM=i7(),AM=r7(),UM=o7(),KM=a7(),DM=e7(),BM=W5(),LM=$5();function FM(Q=!1){let Y=[AM.default,UM.default,KM.default,DM.default,BM.default,LM.default,$M.default,zM.default,GM.default,JM.default,HM.default];if(Q)Y.push(QM.default,XM.default);else Y.push(eO.default,YM.default);return Y.push(WM.default),Y}z5.default=FM});var A5=P((H5)=>{Object.defineProperty(H5,"__esModule",{value:!0});var $0=g(),OM={message:({schemaCode:Q})=>$0.str`must match format "${Q}"`,params:({schemaCode:Q})=>$0._`{format: ${Q}}`},MM={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:OM,code(Q,Y){let{gen:X,data:G,$data:W,schema:$,schemaCode:z,it:J}=Q,{opts:H,errSchemaPath:A,schemaEnv:U,self:K}=J;if(!H.validateFormats)return;if(W)D();else L();function D(){let O=X.scopeValue("formats",{ref:K.formats,code:H.code.formats}),M=X.const("fDef",$0._`${O}[${z}]`),w=X.let("fType"),Z=X.let("format");X.if($0._`typeof ${M} == "object" && !(${M} instanceof RegExp)`,()=>X.assign(w,$0._`${M}.type || "string"`).assign(Z,$0._`${M}.validate`),()=>X.assign(w,$0._`"string"`).assign(Z,M)),Q.fail$data((0,$0.or)(k(),R()));function k(){if(H.strictSchema===!1)return $0.nil;return $0._`${z} && !${Z}`}function R(){let y=U.$async?$0._`(${M}.async ? await ${Z}(${G}) : ${Z}(${G}))`:$0._`${Z}(${G})`,C=$0._`(typeof ${Z} == "function" ? ${y} : ${Z}.test(${G}))`;return $0._`${Z} && ${Z} !== true && ${w} === ${Y} && !${C}`}}function L(){let O=K.formats[$];if(!O){k();return}if(O===!0)return;let[M,w,Z]=R(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 R(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}(${G})`}return typeof w=="function"?$0._`${Z}(${G})`:$0._`${Z}.test(${G})`}}}};H5.default=MM});var K5=P((U5)=>{Object.defineProperty(U5,"__esModule",{value:!0});var ZM=A5(),NM=[ZM.default];U5.default=NM});var L5=P((D5)=>{Object.defineProperty(D5,"__esModule",{value:!0});D5.contentVocabulary=D5.metadataVocabulary=void 0;D5.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];D5.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var O5=P((q5)=>{Object.defineProperty(q5,"__esModule",{value:!0});var bM=hJ(),jM=D7(),IM=J5(),EM=K5(),F5=L5(),TM=[bM.default,jM.default,(0,IM.default)(),EM.default,F5.metadataVocabulary,F5.contentVocabulary];q5.default=TM});var N5=P((V5)=>{Object.defineProperty(V5,"__esModule",{value:!0});V5.DiscrError=void 0;var M5;(function(Q){Q.Tag="tag",Q.Mapping="mapping"})(M5||(V5.DiscrError=M5={}))});var b5=P((P5)=>{Object.defineProperty(P5,"__esModule",{value:!0});var a1=g(),EY=N5(),w5=e6(),RM=u4(),CM=c(),kM={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}}`},vM={keyword:"discriminator",type:"object",schemaType:"object",error:kM,code(Q){let{gen:Y,data:X,schema:G,parentSchema:W,it:$}=Q,{oneOf:z}=W;if(!$.opts.discriminator)throw Error("discriminator: requires discriminator option");let J=G.propertyName;if(typeof J!="string")throw Error("discriminator: requires propertyName");if(G.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(W),w=!0;for(let y=0;y<z.length;y++){let C=z[y];if((C===null||C===void 0?void 0:C.$ref)&&!(0,CM.schemaHasRulesButRef)(C,$.self.RULES)){let o0=C.$ref;if(C=w5.resolveRef.call($.self,$.schemaEnv.root,$.baseId,o0),C instanceof w5.SchemaEnv)C=C.schema;if(C===void 0)throw new RM.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}"`);w=w&&(M||Z(C)),k(c0,y)}if(!w)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)R(y.const,C);else if(y.enum)for(let c0 of y.enum)R(c0,C);else throw Error(`discriminator: "properties/${J}" must have "const" or "enum"`)}function R(y,C){if(typeof y!="string"||y in O)throw Error(`discriminator: "${J}" values must be unique strings`);O[y]=C}}}};P5.default=vM});var j5=P((iE,_M)=>{_M.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 gM=SJ(),yM=O5(),uM=b5(),I5=j5(),hM=["/properties"],VQ="http://json-schema.org/draft-07/schema";class t4 extends gM.default{_addVocabularies(){if(super._addVocabularies(),yM.default.forEach((Q)=>this.addVocabulary(Q)),this.opts.discriminator)this.addKeyword(uM.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let Q=this.opts.$data?this.$dataMetaSchema(I5,hM):I5;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 fM=y4();Object.defineProperty(P0,"KeywordCxt",{enumerable:!0,get:function(){return fM.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 lM=a6();Object.defineProperty(P0,"ValidationError",{enumerable:!0,get:function(){return lM.default}});var mM=u4();Object.defineProperty(P0,"MissingRefError",{enumerable:!0,get:function(){return mM.default}})});var g5=P((x5)=>{Object.defineProperty(x5,"__esModule",{value:!0});x5.formatNames=x5.fastFormats=x5.fullFormats=void 0;function n0(Q,Y){return{validate:Q,compare:Y}}x5.fullFormats={date:n0(R5,vY),time:n0(CY(!0),xY),"date-time":n0(E5(!0),k5),"iso-time":n0(CY(),C5),"iso-date-time":n0(E5(),v5),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:tM,"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:WV,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:aM,int32:{type:"number",validate:QV},int64:{type:"number",validate:YV},float:{type:"number",validate:S5},double:{type:"number",validate:S5},password:!0,binary:!0};x5.fastFormats={...x5.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,k5),"iso-time":n0(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,C5),"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,v5),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};x5.formatNames=Object.keys(x5.fullFormats);function iM(Q){return Q%4===0&&(Q%100!==0||Q%400===0)}var nM=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,rM=[0,31,28,31,30,31,30,31,31,30,31,30,31];function R5(Q){let Y=nM.exec(Q);if(!Y)return!1;let X=+Y[1],G=+Y[2],W=+Y[3];return G>=1&&G<=12&&W>=1&&W<=(G===2&&iM(X)?29:rM[G])}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 G=RY.exec(X);if(!G)return!1;let W=+G[1],$=+G[2],z=+G[3],J=G[4],H=G[5]==="-"?-1:1,A=+(G[6]||0),U=+(G[7]||0);if(A>23||U>59||Q&&!J)return!1;if(W<=23&&$<=59&&z<60)return!0;let K=$-U*H,D=W-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(),G=new Date("2020-01-01T"+Y).valueOf();if(!(X&&G))return;return X-G}function C5(Q,Y){if(!(Q&&Y))return;let X=RY.exec(Q),G=RY.exec(Y);if(!(X&&G))return;if(Q=X[1]+X[2]+X[3],Y=G[1]+G[2]+G[3],Q>Y)return 1;if(Q<Y)return-1;return 0}var kY=/t|\s/i;function E5(Q){let Y=CY(Q);return function(G){let W=G.split(kY);return W.length===2&&R5(W[0])&&Y(W[1])}}function k5(Q,Y){if(!(Q&&Y))return;let X=new Date(Q).valueOf(),G=new Date(Y).valueOf();if(!(X&&G))return;return X-G}function v5(Q,Y){if(!(Q&&Y))return;let[X,G]=Q.split(kY),[W,$]=Y.split(kY),z=vY(X,W);if(z===void 0)return;return z||xY(G,$)}var dM=/\/|:/,oM=/^(?:[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 tM(Q){return dM.test(Q)&&oM.test(Q)}var T5=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function aM(Q){return T5.lastIndex=0,T5.test(Q)}var sM=-2147483648,eM=2147483647;function QV(Q){return Number.isInteger(Q)&&Q<=eM&&Q>=sM}function YV(Q){return Number.isInteger(Q)}function S5(){return!0}var XV=/[^\\]\\Z/;function WV(Q){if(XV.test(Q))return!1;try{return new RegExp(Q),!0}catch(Y){return!1}}});var u5=P((y5)=>{Object.defineProperty(y5,"__esModule",{value:!0});y5.formatLimitDefinition=void 0;var $V=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}},zV={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}}`};y5.formatLimitDefinition={keyword:Object.keys(ZQ),type:"string",schemaType:"string",$data:!0,error:zV,code(Q){let{gen:Y,data:X,schemaCode:G,keyword:W,it:$}=Q,{opts:z,self:J}=$;if(!z.validateFormats)return;let H=new $V.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(`"${W}": 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}, ${G}) ${ZQ[W].fail} 0`}},dependencies:["format"]};var JV=(Q)=>{return Q.addKeyword(y5.formatLimitDefinition),Q};y5.default=JV});var m5=P((a4,l5)=>{Object.defineProperty(a4,"__esModule",{value:!0});var e1=g5(),AV=u5(),yY=g(),h5=new yY.Name("fullFormats"),UV=new yY.Name("fastFormats"),uY=(Q,Y={keywords:!0})=>{if(Array.isArray(Y))return f5(Q,Y,e1.fullFormats,h5),Q;let[X,G]=Y.mode==="fast"?[e1.fastFormats,UV]:[e1.fullFormats,h5],W=Y.formats||e1.formatNames;if(f5(Q,W,X,G),Y.keywords)(0,AV.default)(Q);return Q};uY.get=(Q,Y="full")=>{let G=(Y==="fast"?e1.fastFormats:e1.fullFormats)[Q];if(!G)throw Error(`Unknown format "${Q}"`);return G};function f5(Q,Y,X,G){var W,$;(W=($=Q.opts.code).formats)!==null&&W!==void 0||($.formats=yY._`require("ajv-formats/dist/formats").${G}`);for(let z of Y)Q.addFormat(z,X[z])}l5.exports=a4=uY;Object.defineProperty(a4,"__esModule",{value:!0});a4.default=uY});import{AsyncLocalStorage as yH}from"node:async_hooks";class P1 extends Error{statusCode;rawDetails;code;context;constructor(Q,Y,X,G,W){super(Q);this.statusCode=Y;this.rawDetails=X;this.code=G;this.context=W;this.name="McpApiError"}}function xH(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 _H(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 gH(Q){let Y=xH(Q),X=Y.message.trim()||"Unknown error",G=X.toLowerCase(),W=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:W};if(Y.code==="MCP_AUTH_REQUIRED"||G.includes("sequenzy_api_key environment variable is required"))return{title:"Missing MCP API key",description:"The MCP server started without a Sequenzy API key, so it cannot authenticate any tool or resource request.",howToFix:"Add `SEQUENZY_API_KEY` to the MCP server environment, or run `npx @sequenzy/setup` to configure the integration automatically.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:W};if(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:W};let $=_H(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:W}}if(Y.statusCode===403||G.includes("access denied"))return{title:"Access denied",description:"The current API key is valid, but it does not have permission to access the requested company or action.",howToFix:"Use an API key that belongs to the right account, or select a company the key can access before retrying the tool call.",docsUrl:"https://docs.sequenzy.com/authentication",details:W};if(G.includes("no company available")||G.includes("company not found"))return{title:"Company selection required",description:"The MCP server could not resolve a company for this request.",howToFix:"Call `get_account` to inspect available companies, then call `select_company`, or pass `companyId` explicitly in the next tool call.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:W};if(Y.statusCode===404||G.includes("not found"))return{title:"Requested resource not found",description:"Sequenzy could not find the requested campaign, template, sequence, company, or subscriber.",howToFix:"List or fetch the resource collection first, then retry the tool with a confirmed ID or email value.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:W};if(Y.statusCode===409||G.includes("already exists"))return{title:"Resource already exists",description:"Sequenzy rejected this MCP request because it would create a duplicate resource.",howToFix:"List the existing resources first, reuse the matching resource when appropriate, or retry with a unique name or domain.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:W};if(Y.statusCode===429||G.includes("rate limit"))return{title:"Rate limited",description:"Sequenzy temporarily slowed this MCP request because too many requests were sent too quickly.",howToFix:"Wait briefly before retrying. If the client is looping, reduce retries or add backoff before the next tool call.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:W};if(Y.code==="NETWORK_ERROR"||G.includes("fetch failed"))return{title:"Network or configuration error",description:"The MCP server could not reach the Sequenzy API from this environment.",howToFix:"Check connectivity and verify `SEQUENZY_API_URL` if you override it in the MCP environment.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:W};if(G.includes("unknown tool")||G.includes("unknown resource"))return{title:"Unsupported MCP request",description:"The client asked for a tool or resource name that this Sequenzy MCP server does not expose.",howToFix:"Refresh the client's tool list and call only the names returned by `list_tools` or `list_resources`.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:W};if(G.includes("is required")||G.includes("invalid"))return{title:"Invalid MCP input",description:"The tool call was missing a required field or included an invalid value.",howToFix:"Review the tool schema, supply the missing argument, and retry the request with corrected input.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:W};if(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:W};return{title:"Tool execution failed",description:"The MCP server could not complete the requested operation.",howToFix:"Review the details below, adjust the tool input or credentials, and retry.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:W}}function $1(Q){let Y=gH(Q);return[`Sequenzy MCP error: ${Y.title}`,`Description: ${Y.description}`,`How to fix: ${Y.howToFix}`,`Docs: ${Y.docsUrl}`,`Details: ${Y.details}`].join(`
|
|
10
|
-
`)}var uH="https://api.sequenzy.com",W4=new yH,MX=!1;function VX(){MX=!0}function ZX(){return MX}var NX=null;function b1(){let Q=W4.getStore();if(Q)return Q.selectedCompanyId??null;return NX}function Q6(Q){let Y=W4.getStore();if(Y){Y.selectedCompanyId=Q;return}NX=Q}function SQ(Q,Y){return W4.run(Q,Y)}function hH(){return W4.getStore()?.apiUrl??process.env.SEQUENZY_API_URL??uH}function wX(){return W4.getStore()?.apiKey??process.env.SEQUENZY_API_KEY}function PX(){if(wX())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 fH(Q){if(Q===void 0)return;if(typeof Q==="string")return Q.trim()||void 0;return JSON.stringify(Q)}function lH(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,G=j0(Y,"code")??(X?j0(X,"code"):void 0),W=(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=fH(Y.details);if(Object.keys(z).length>0||J)return{message:W,...G?{code:G}:{},...J?{details:J}:{},...Object.keys(z).length>0?{context:z}:{}};if(typeof Y.error==="string")return{message:Y.error,...G?{code:G}:{}};if(X)return{message:W,...G?{code:G}:{}};return{message:W,...G?{code:G}:{}}}catch{return{message:Q}}}async function B(Q,Y,X,G){let W=wX();if(!W)throw new P1("SEQUENZY_API_KEY environment variable is required",401,void 0,"MCP_AUTH_REQUIRED");let $={"Content-Type":"application/json",Authorization:`Bearer ${W}`},z=G??b1();if(z)$["x-company-id"]=z;let J;try{J=await fetch(`${hH()}${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=lH(H);throw new P1(A.message,J.status,A.details??H,A.code,A.context)}return J.json()}var kZ=Object.freeze({status:"aborted"});function q(Q,Y,X){function G(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 W=X?.Parent??Object;class $ extends W{}Object.defineProperty($,"name",{value:Q});function z(J){var H;let A=X?.Parent?new $:this;G(A,J),(H=A._zod).deferred??(H.deferred=[]);for(let U of A._zod.deferred)U();return A}return Object.defineProperty(z,"init",{value:G}),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 vZ=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={};OX(m,{unwrapMessage:()=>$4,uint8ArrayToHex:()=>DA,uint8ArrayToBase64url:()=>UA,uint8ArrayToBase64:()=>RX,stringifyPrimitive:()=>$6,shallowClone:()=>jX,safeExtend:()=>GA,required:()=>JA,randomString:()=>aH,propertyKeyTypes:()=>xQ,promiseAllObject:()=>tH,primitiveTypes:()=>IX,prefixIssues:()=>s0,pick:()=>YA,partial:()=>zA,optionalKeys:()=>_Q,omit:()=>XA,objectClone:()=>rH,numKeys:()=>sH,nullish:()=>z4,normalizeParams:()=>S,mergeDefs:()=>J1,merge:()=>$A,jsonStringifyReplacer:()=>_1,joinValues:()=>X6,issue:()=>y1,isPlainObject:()=>H1,isObject:()=>j1,hexToUint8Array:()=>KA,getSizableOrigin:()=>TX,getParsedType:()=>eH,getLengthableOrigin:()=>H4,getEnumValues:()=>CQ,getElementAtPath:()=>oH,floatSafeRemainder:()=>kQ,finalizeIssue:()=>x0,extend:()=>WA,escapeRegex:()=>a0,esc:()=>W6,defineLazy:()=>r,createTransparentProxy:()=>QA,cloneDef:()=>dH,clone:()=>v0,cleanRegex:()=>J4,cleanEnum:()=>HA,captureStackTrace:()=>G6,cached:()=>g1,base64urlToUint8Array:()=>AA,base64ToUint8Array:()=>SX,assignProp:()=>z1,assertNotEqual:()=>cH,assertNever:()=>iH,assertIs:()=>pH,assertEqual:()=>mH,assert:()=>nH,allowsEval:()=>vQ,aborted:()=>A1,NUMBER_FORMAT_RANGES:()=>gQ,Class:()=>CX,BIGINT_FORMAT_RANGES:()=>EX});function mH(Q){return Q}function cH(Q){return Q}function pH(Q){}function iH(Q){throw Error()}function nH(Q){}function CQ(Q){let Y=Object.values(Q).filter((G)=>typeof G==="number");return Object.entries(Q).filter(([G,W])=>Y.indexOf(+G)===-1).map(([G,W])=>W)}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,G=Y.toString(),W=(G.split(".")[1]||"").length;if(W===0&&/\d?e-\d?/.test(G)){let H=G.match(/\d?e-(\d?)/);if(H?.[1])W=Number.parseInt(H[1])}let $=X>W?X:W,z=Number.parseInt(Q.toFixed($).replace(".","")),J=Number.parseInt(Y.toFixed($).replace(".",""));return z%J/10**$}var bX=Symbol("evaluating");function r(Q,Y,X){let G=void 0;Object.defineProperty(Q,Y,{get(){if(G===bX)return;if(G===void 0)G=bX,G=X();return G},set(W){Object.defineProperty(Q,Y,{value:W})},configurable:!0})}function rH(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 G=Object.getOwnPropertyDescriptors(X);Object.assign(Y,G)}return Object.defineProperties({},Y)}function dH(Q){return J1(Q._zod.def)}function oH(Q,Y){if(!Y)return Q;return Y.reduce((X,G)=>X?.[G],Q)}function tH(Q){let Y=Object.keys(Q),X=Y.map((G)=>Q[G]);return Promise.all(X).then((G)=>{let W={};for(let $=0;$<Y.length;$++)W[Y[$]]=G[$];return W})}function aH(Q=10){let X="";for(let G=0;G<Q;G++)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 jX(Q){if(H1(Q))return{...Q};if(Array.isArray(Q))return[...Q];return Q}function sH(Q){let Y=0;for(let X in Q)if(Object.prototype.hasOwnProperty.call(Q,X))Y++;return Y}var eH=(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"]),IX=new Set(["string","number","bigint","boolean","symbol","undefined"]);function a0(Q){return Q.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function v0(Q,Y,X){let G=new Q._zod.constr(Y??Q._zod.def);if(!Y||X?.parent)G._zod.parent=Q;return G}function S(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 QA(Q){let Y;return new Proxy({},{get(X,G,W){return Y??(Y=Q()),Reflect.get(Y,G,W)},set(X,G,W,$){return Y??(Y=Q()),Reflect.set(Y,G,W,$)},has(X,G){return Y??(Y=Q()),Reflect.has(Y,G)},deleteProperty(X,G){return Y??(Y=Q()),Reflect.deleteProperty(Y,G)},ownKeys(X){return Y??(Y=Q()),Reflect.ownKeys(Y)},getOwnPropertyDescriptor(X,G){return Y??(Y=Q()),Reflect.getOwnPropertyDescriptor(Y,G)},defineProperty(X,G,W){return Y??(Y=Q()),Reflect.defineProperty(Y,G,W)}})}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]},EX={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function YA(Q,Y){let X=Q._zod.def,G=J1(Q._zod.def,{get shape(){let W={};for(let $ in Y){if(!($ in X.shape))throw Error(`Unrecognized key: "${$}"`);if(!Y[$])continue;W[$]=X.shape[$]}return z1(this,"shape",W),W},checks:[]});return v0(Q,G)}function XA(Q,Y){let X=Q._zod.def,G=J1(Q._zod.def,{get shape(){let W={...Q._zod.def.shape};for(let $ in Y){if(!($ in X.shape))throw Error(`Unrecognized key: "${$}"`);if(!Y[$])continue;delete W[$]}return z1(this,"shape",W),W},checks:[]});return v0(Q,G)}function WA(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 W=J1(Q._zod.def,{get shape(){let $={...Q._zod.def.shape,...Y};return z1(this,"shape",$),$},checks:[]});return v0(Q,W)}function GA(Q,Y){if(!H1(Y))throw Error("Invalid input to safeExtend: expected a plain object");let X={...Q._zod.def,get shape(){let G={...Q._zod.def.shape,...Y};return z1(this,"shape",G),G},checks:Q._zod.def.checks};return v0(Q,X)}function $A(Q,Y){let X=J1(Q._zod.def,{get shape(){let G={...Q._zod.def.shape,...Y._zod.def.shape};return z1(this,"shape",G),G},get catchall(){return Y._zod.def.catchall},checks:[]});return v0(Q,X)}function zA(Q,Y,X){let G=J1(Y._zod.def,{get shape(){let W=Y._zod.def.shape,$={...W};if(X)for(let z in X){if(!(z in W))throw Error(`Unrecognized key: "${z}"`);if(!X[z])continue;$[z]=Q?new Q({type:"optional",innerType:W[z]}):W[z]}else for(let z in W)$[z]=Q?new Q({type:"optional",innerType:W[z]}):W[z];return z1(this,"shape",$),$},checks:[]});return v0(Y,G)}function JA(Q,Y,X){let G=J1(Y._zod.def,{get shape(){let W=Y._zod.def.shape,$={...W};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:W[z]})}else for(let z in W)$[z]=new Q({type:"nonoptional",innerType:W[z]});return z1(this,"shape",$),$},checks:[]});return v0(Y,G)}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 G;return(G=X).path??(G.path=[]),X.path.unshift(Q),X})}function $4(Q){return typeof Q==="string"?Q:Q?.message}function x0(Q,Y,X){let G={...Q,path:Q.path??[]};if(!Q.message){let W=$4(Q.inst?._zod.def?.error?.(Q))??$4(Y?.error?.(Q))??$4(X.customError?.(Q))??$4(X.localeError?.(Q))??"Invalid input";G.message=W}if(delete G.inst,delete G.continue,!Y?.reportInput)delete G.input;return G}function TX(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,G]=Q;if(typeof Y==="string")return{message:Y,code:"custom",input:X,inst:G};return{...Y}}function HA(Q){return Object.entries(Q).filter(([Y,X])=>{return Number.isNaN(Number.parseInt(Y,10))}).map((Y)=>Y[1])}function SX(Q){let Y=atob(Q),X=new Uint8Array(Y.length);for(let G=0;G<Y.length;G++)X[G]=Y.charCodeAt(G);return X}function RX(Q){let Y="";for(let X=0;X<Q.length;X++)Y+=String.fromCharCode(Q[X]);return btoa(Y)}function AA(Q){let Y=Q.replace(/-/g,"+").replace(/_/g,"/"),X="=".repeat((4-Y.length%4)%4);return SX(Y+X)}function UA(Q){return RX(Q).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function KA(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 G=0;G<Y.length;G+=2)X[G/2]=Number.parseInt(Y.slice(G,G+2),16);return X}function DA(Q){return Array.from(Q).map((Y)=>Y.toString(16).padStart(2,"0")).join("")}class CX{constructor(...Q){}}var kX=(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",kX),yQ=q("$ZodError",kX,{Parent:Error});function vX(Q,Y=(X)=>X.message){let X={},G=[];for(let W of Q.issues)if(W.path.length>0)X[W.path[0]]=X[W.path[0]]||[],X[W.path[0]].push(Y(W));else G.push(Y(W));return{formErrors:G,fieldErrors:X}}function xX(Q,Y=(X)=>X.message){let X={_errors:[]},G=(W)=>{for(let $ of W.issues)if($.code==="invalid_union"&&$.errors.length)$.errors.map((z)=>G({issues:z}));else if($.code==="invalid_key")G({issues:$.issues});else if($.code==="invalid_element")G({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 G(Q),X}var J6=(Q)=>(Y,X,G,W)=>{let $=G?Object.assign(G,{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(W?.Err??Q)(z.issues.map((H)=>x0(H,$,T0())));throw G6(J,W?.callee),J}return z.value};var H6=(Q)=>async(Y,X,G,W)=>{let $=G?Object.assign(G,{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(W?.Err??Q)(z.issues.map((H)=>x0(H,$,T0())));throw G6(J,W?.callee),J}return z.value};var A4=(Q)=>(Y,X,G)=>{let W=G?{...G,async:!1}:{async:!1},$=Y._zod.run({value:X,issues:[]},W);if($ instanceof Promise)throw new t0;return $.issues.length?{success:!1,error:new(Q??z6)($.issues.map((z)=>x0(z,W,T0())))}:{success:!0,data:$.value}},U4=A4(yQ),K4=(Q)=>async(Y,X,G)=>{let W=G?Object.assign(G,{async:!0}):{async:!0},$=Y._zod.run({value:X,issues:[]},W);if($ instanceof Promise)$=await $;return $.issues.length?{success:!1,error:new Q($.issues.map((z)=>x0(z,W,T0())))}:{success:!0,data:$.value}},A6=K4(yQ),_X=(Q)=>(Y,X,G)=>{let W=G?Object.assign(G,{direction:"backward"}):{direction:"backward"};return J6(Q)(Y,X,W)};var gX=(Q)=>(Y,X,G)=>{return J6(Q)(Y,X,G)};var yX=(Q)=>async(Y,X,G)=>{let W=G?Object.assign(G,{direction:"backward"}):{direction:"backward"};return H6(Q)(Y,X,W)};var uX=(Q)=>async(Y,X,G)=>{return H6(Q)(Y,X,G)};var hX=(Q)=>(Y,X,G)=>{let W=G?Object.assign(G,{direction:"backward"}):{direction:"backward"};return A4(Q)(Y,X,W)};var fX=(Q)=>(Y,X,G)=>{return A4(Q)(Y,X,G)};var lX=(Q)=>async(Y,X,G)=>{let W=G?Object.assign(G,{direction:"backward"}):{direction:"backward"};return K4(Q)(Y,X,W)};var mX=(Q)=>async(Y,X,G)=>{return K4(Q)(Y,X,G)};var cX=/^[cC][^\s-]{8,}$/,pX=/^[0-9a-z]+$/,iX=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,nX=/^[0-9a-vA-V]{20}$/,rX=/^[A-Za-z0-9]{27}$/,dX=/^[a-zA-Z0-9_-]{21}$/,oX=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var tX=/^([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 aX=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function sX(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}var eX=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Q8=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,Y8=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,X8=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,W8=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,hQ=/^[A-Za-z0-9_-]*$/,G8=/^(?=.{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 $8=/^\+(?:[0-9]){6,14}[0-9]$/,z8="(?:(?:\\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])))",J8=new RegExp(`^${z8}$`);function H8(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 A8(Q){return new RegExp(`^${H8(Q)}$`)}function U8(Q){let Y=H8({precision:Q.precision}),X=["Z"];if(Q.local)X.push("");if(Q.offset)X.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let G=`${Y}(?:${X.join("|")})`;return new RegExp(`^${z8}T(?:${G})$`)}var K8=(Q)=>{let Y=Q?`[\\s\\S]{${Q?.minimum??0},${Q?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${Y}$`)};var D8=/^-?\d+$/,B8=/^-?\d+(?:\.\d+)?/,L8=/^(?:true|false)$/i,F8=/^null$/i;var q8=/^[^A-Z]*$/,O8=/^[^a-z]*$/;var A0=q("$ZodCheck",(Q,Y)=>{var X;Q._zod??(Q._zod={}),Q._zod.def=Y,(X=Q._zod).onattach??(X.onattach=[])}),M8={number:"number",bigint:"bigint",object:"date"},fQ=q("$ZodCheckLessThan",(Q,Y)=>{A0.init(Q,Y);let X=M8[typeof Y.value];Q._zod.onattach.push((G)=>{let W=G._zod.bag,$=(Y.inclusive?W.maximum:W.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(Y.value<$)if(Y.inclusive)W.maximum=Y.value;else W.exclusiveMaximum=Y.value}),Q._zod.check=(G)=>{if(Y.inclusive?G.value<=Y.value:G.value<Y.value)return;G.issues.push({origin:X,code:"too_big",maximum:Y.value,input:G.value,inclusive:Y.inclusive,inst:Q,continue:!Y.abort})}}),lQ=q("$ZodCheckGreaterThan",(Q,Y)=>{A0.init(Q,Y);let X=M8[typeof Y.value];Q._zod.onattach.push((G)=>{let W=G._zod.bag,$=(Y.inclusive?W.minimum:W.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(Y.value>$)if(Y.inclusive)W.minimum=Y.value;else W.exclusiveMinimum=Y.value}),Q._zod.check=(G)=>{if(Y.inclusive?G.value>=Y.value:G.value>Y.value)return;G.issues.push({origin:X,code:"too_small",minimum:Y.value,input:G.value,inclusive:Y.inclusive,inst:Q,continue:!Y.abort})}}),V8=q("$ZodCheckMultipleOf",(Q,Y)=>{A0.init(Q,Y),Q._zod.onattach.push((X)=>{var G;(G=X._zod.bag).multipleOf??(G.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})}}),Z8=q("$ZodCheckNumberFormat",(Q,Y)=>{A0.init(Q,Y),Y.format=Y.format||"float64";let X=Y.format?.includes("int"),G=X?"int":"number",[W,$]=gQ[Y.format];Q._zod.onattach.push((z)=>{let J=z._zod.bag;if(J.format=Y.format,J.minimum=W,J.maximum=$,X)J.pattern=D8}),Q._zod.check=(z)=>{let J=z.value;if(X){if(!Number.isInteger(J)){z.issues.push({expected:G,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:G,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:G,continue:!Y.abort});return}}if(J<W)z.issues.push({origin:"number",input:J,code:"too_small",minimum:W,inclusive:!0,inst:Q,continue:!Y.abort});if(J>$)z.issues.push({origin:"number",input:J,code:"too_big",maximum:$,inst:Q})}});var N8=q("$ZodCheckMaxLength",(Q,Y)=>{var X;A0.init(Q,Y),(X=Q._zod.def).when??(X.when=(G)=>{let W=G.value;return!z4(W)&&W.length!==void 0}),Q._zod.onattach.push((G)=>{let W=G._zod.bag.maximum??Number.POSITIVE_INFINITY;if(Y.maximum<W)G._zod.bag.maximum=Y.maximum}),Q._zod.check=(G)=>{let W=G.value;if(W.length<=Y.maximum)return;let z=H4(W);G.issues.push({origin:z,code:"too_big",maximum:Y.maximum,inclusive:!0,input:W,inst:Q,continue:!Y.abort})}}),w8=q("$ZodCheckMinLength",(Q,Y)=>{var X;A0.init(Q,Y),(X=Q._zod.def).when??(X.when=(G)=>{let W=G.value;return!z4(W)&&W.length!==void 0}),Q._zod.onattach.push((G)=>{let W=G._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(Y.minimum>W)G._zod.bag.minimum=Y.minimum}),Q._zod.check=(G)=>{let W=G.value;if(W.length>=Y.minimum)return;let z=H4(W);G.issues.push({origin:z,code:"too_small",minimum:Y.minimum,inclusive:!0,input:W,inst:Q,continue:!Y.abort})}}),P8=q("$ZodCheckLengthEquals",(Q,Y)=>{var X;A0.init(Q,Y),(X=Q._zod.def).when??(X.when=(G)=>{let W=G.value;return!z4(W)&&W.length!==void 0}),Q._zod.onattach.push((G)=>{let W=G._zod.bag;W.minimum=Y.length,W.maximum=Y.length,W.length=Y.length}),Q._zod.check=(G)=>{let W=G.value,$=W.length;if($===Y.length)return;let z=H4(W),J=$>Y.length;G.issues.push({origin:z,...J?{code:"too_big",maximum:Y.length}:{code:"too_small",minimum:Y.length},inclusive:!0,exact:!0,input:G.value,inst:Q,continue:!Y.abort})}}),D4=q("$ZodCheckStringFormat",(Q,Y)=>{var X,G;if(A0.init(Q,Y),Q._zod.onattach.push((W)=>{let $=W._zod.bag;if($.format=Y.format,Y.pattern)$.patterns??($.patterns=new Set),$.patterns.add(Y.pattern)}),Y.pattern)(X=Q._zod).check??(X.check=(W)=>{if(Y.pattern.lastIndex=0,Y.pattern.test(W.value))return;W.issues.push({origin:"string",code:"invalid_format",format:Y.format,input:W.value,...Y.pattern?{pattern:Y.pattern.toString()}:{},inst:Q,continue:!Y.abort})});else(G=Q._zod).check??(G.check=()=>{})}),b8=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})}}),j8=q("$ZodCheckLowerCase",(Q,Y)=>{Y.pattern??(Y.pattern=q8),D4.init(Q,Y)}),I8=q("$ZodCheckUpperCase",(Q,Y)=>{Y.pattern??(Y.pattern=O8),D4.init(Q,Y)}),E8=q("$ZodCheckIncludes",(Q,Y)=>{A0.init(Q,Y);let X=a0(Y.includes),G=new RegExp(typeof Y.position==="number"?`^.{${Y.position}}${X}`:X);Y.pattern=G,Q._zod.onattach.push((W)=>{let $=W._zod.bag;$.patterns??($.patterns=new Set),$.patterns.add(G)}),Q._zod.check=(W)=>{if(W.value.includes(Y.includes,Y.position))return;W.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:Y.includes,input:W.value,inst:Q,continue:!Y.abort})}}),T8=q("$ZodCheckStartsWith",(Q,Y)=>{A0.init(Q,Y);let X=new RegExp(`^${a0(Y.prefix)}.*`);Y.pattern??(Y.pattern=X),Q._zod.onattach.push((G)=>{let W=G._zod.bag;W.patterns??(W.patterns=new Set),W.patterns.add(X)}),Q._zod.check=(G)=>{if(G.value.startsWith(Y.prefix))return;G.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:Y.prefix,input:G.value,inst:Q,continue:!Y.abort})}}),S8=q("$ZodCheckEndsWith",(Q,Y)=>{A0.init(Q,Y);let X=new RegExp(`.*${a0(Y.suffix)}$`);Y.pattern??(Y.pattern=X),Q._zod.onattach.push((G)=>{let W=G._zod.bag;W.patterns??(W.patterns=new Set),W.patterns.add(X)}),Q._zod.check=(G)=>{if(G.value.endsWith(Y.suffix))return;G.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:Y.suffix,input:G.value,inst:Q,continue:!Y.abort})}});var R8=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
|
-
`).filter((
|
|
12
|
-
`))}}var
|
|
13
|
-
if (${
|
|
14
|
-
payload.issues = payload.issues.concat(${
|
|
2
|
+
var jA=Object.create;var{getPrototypeOf:NA,defineProperty:o$,getOwnPropertyNames:EA}=Object;var TA=Object.prototype.hasOwnProperty;function _A(b){return this[b]}var SA,RA,SQ=(b,w,$)=>{var Q=b!=null&&typeof b==="object";if(Q){var W=w?SA??=new WeakMap:RA??=new WeakMap,G=W.get(b);if(G)return G}$=b!=null?jA(NA(b)):{};let X=w||!b||!b.__esModule?o$($,"default",{value:b,enumerable:!0}):$;for(let Y of EA(b))if(!TA.call(X,Y))o$(X,Y,{get:_A.bind(b,Y),enumerable:!0});if(Q)W.set(b,X);return X};var I=(b,w)=>()=>(w||b((w={exports:{}}).exports,w),w.exports);var CA=(b)=>b;function vA(b,w){this[b]=CA.bind(null,w)}var RQ=(b,w)=>{for(var $ in w)o$(b,$,{get:w[$],enumerable:!0,configurable:!0,set:vA.bind(w,$)})};var h1=I((_G)=>{Object.defineProperty(_G,"__esModule",{value:!0});_G.regexpCode=_G.getEsmExportName=_G.getProperty=_G.safeStringify=_G.stringify=_G.strConcat=_G.addCodeArg=_G.str=_G._=_G.nil=_G._Code=_G.Name=_G.IDENTIFIER=_G._CodeOrName=void 0;class d0{}_G._CodeOrName=d0;_G.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class pw extends d0{constructor(b){super();if(!_G.IDENTIFIER.test(b))throw Error("CodeGen: name must be a valid identifier");this.str=b}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}_G.Name=pw;class yb extends d0{constructor(b){super();this._items=typeof b==="string"?[b]:b}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let b=this._items[0];return b===""||b==='""'}get str(){var b;return(b=this._str)!==null&&b!==void 0?b:this._str=this._items.reduce((w,$)=>`${w}${$}`,"")}get names(){var b;return(b=this._names)!==null&&b!==void 0?b:this._names=this._items.reduce((w,$)=>{if($ instanceof pw)w[$.str]=(w[$.str]||0)+1;return w},{})}}_G._Code=yb;_G.nil=new yb("");function EG(b,...w){let $=[b[0]],Q=0;while(Q<w.length)$4($,w[Q]),$.push(b[++Q]);return new yb($)}_G._=EG;var w4=new yb("+");function TG(b,...w){let $=[y1(b[0])],Q=0;while(Q<w.length)$.push(w4),$4($,w[Q]),$.push(w4,y1(b[++Q]));return QO($),new yb($)}_G.str=TG;function $4(b,w){if(w instanceof yb)b.push(...w._items);else if(w instanceof pw)b.push(w);else b.push(XO(w))}_G.addCodeArg=$4;function QO(b){let w=1;while(w<b.length-1){if(b[w]===w4){let $=WO(b[w-1],b[w+1]);if($!==void 0){b.splice(w-1,3,$);continue}b[w++]="+"}w++}}function WO(b,w){if(w==='""')return b;if(b==='""')return w;if(typeof b=="string"){if(w instanceof pw||b[b.length-1]!=='"')return;if(typeof w!="string")return`${b.slice(0,-1)}${w}"`;if(w[0]==='"')return b.slice(0,-1)+w.slice(1);return}if(typeof w=="string"&&w[0]==='"'&&!(b instanceof pw))return`"${b}${w.slice(1)}`;return}function GO(b,w){return w.emptyStr()?b:b.emptyStr()?w:TG`${b}${w}`}_G.strConcat=GO;function XO(b){return typeof b=="number"||typeof b=="boolean"||b===null?b:y1(Array.isArray(b)?b.join(","):b)}function YO(b){return new yb(y1(b))}_G.stringify=YO;function y1(b){return JSON.stringify(b).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}_G.safeStringify=y1;function JO(b){return typeof b=="string"&&_G.IDENTIFIER.test(b)?new yb(`.${b}`):EG`[${b}]`}_G.getProperty=JO;function zO(b){if(typeof b=="string"&&_G.IDENTIFIER.test(b))return new yb(`${b}`);throw Error(`CodeGen: invalid export name: ${b}, use explicit $id name mapping`)}_G.getEsmExportName=zO;function HO(b){return new yb(b.toString())}_G.regexpCode=HO});var X4=I((vG)=>{Object.defineProperty(vG,"__esModule",{value:!0});vG.ValueScope=vG.ValueScopeName=vG.Scope=vG.varKinds=vG.UsedValueState=void 0;var Mb=h1();class RG extends Error{constructor(b){super(`CodeGen: "code" for ${b} not defined`);this.value=b.value}}var t0;(function(b){b[b.Started=0]="Started",b[b.Completed=1]="Completed"})(t0||(vG.UsedValueState=t0={}));vG.varKinds={const:new Mb.Name("const"),let:new Mb.Name("let"),var:new Mb.Name("var")};class W4{constructor({prefixes:b,parent:w}={}){this._names={},this._prefixes=b,this._parent=w}toName(b){return b instanceof Mb.Name?b:this.name(b)}name(b){return new Mb.Name(this._newName(b))}_newName(b){let w=this._names[b]||this._nameGroup(b);return`${b}${w.index++}`}_nameGroup(b){var w,$;if((($=(w=this._parent)===null||w===void 0?void 0:w._prefixes)===null||$===void 0?void 0:$.has(b))||this._prefixes&&!this._prefixes.has(b))throw Error(`CodeGen: prefix "${b}" is not allowed in this scope`);return this._names[b]={prefix:b,index:0}}}vG.Scope=W4;class G4 extends Mb.Name{constructor(b,w){super(w);this.prefix=b}setValue(b,{property:w,itemIndex:$}){this.value=b,this.scopePath=Mb._`.${new Mb.Name(w)}[${$}]`}}vG.ValueScopeName=G4;var IO=Mb._`\n`;class CG extends W4{constructor(b){super(b);this._values={},this._scope=b.scope,this.opts={...b,_n:b.lines?IO:Mb.nil}}get(){return this._scope}name(b){return new G4(b,this._newName(b))}value(b,w){var $;if(w.ref===void 0)throw Error("CodeGen: ref must be passed in value");let Q=this.toName(b),{prefix:W}=Q,G=($=w.key)!==null&&$!==void 0?$:w.ref,X=this._values[W];if(X){let z=X.get(G);if(z)return z}else X=this._values[W]=new Map;X.set(G,Q);let Y=this._scope[W]||(this._scope[W]=[]),J=Y.length;return Y[J]=w.ref,Q.setValue(w,{property:W,itemIndex:J}),Q}getValue(b,w){let $=this._values[b];if(!$)return;return $.get(w)}scopeRefs(b,w=this._values){return this._reduceValues(w,($)=>{if($.scopePath===void 0)throw Error(`CodeGen: name "${$}" has no value`);return Mb._`${b}${$.scopePath}`})}scopeCode(b=this._values,w,$){return this._reduceValues(b,(Q)=>{if(Q.value===void 0)throw Error(`CodeGen: name "${Q}" has no value`);return Q.value.code},w,$)}_reduceValues(b,w,$={},Q){let W=Mb.nil;for(let G in b){let X=b[G];if(!X)continue;let Y=$[G]=$[G]||new Map;X.forEach((J)=>{if(Y.has(J))return;Y.set(J,t0.Started);let z=w(J);if(z){let H=this.opts.es5?vG.varKinds.var:vG.varKinds.const;W=Mb._`${W}${H} ${J} = ${z};${this.opts._n}`}else if(z=Q===null||Q===void 0?void 0:Q(J))W=Mb._`${W}${z}${this.opts._n}`;else throw new RG(J);Y.set(J,t0.Completed)})}return W}}vG.ValueScope=CG});var u=I((Pb)=>{Object.defineProperty(Pb,"__esModule",{value:!0});Pb.or=Pb.and=Pb.not=Pb.CodeGen=Pb.operators=Pb.varKinds=Pb.ValueScopeName=Pb.ValueScope=Pb.Scope=Pb.Name=Pb.regexpCode=Pb.stringify=Pb.getProperty=Pb.nil=Pb.strConcat=Pb.str=Pb._=void 0;var c=h1(),hb=X4(),Mw=h1();Object.defineProperty(Pb,"_",{enumerable:!0,get:function(){return Mw._}});Object.defineProperty(Pb,"str",{enumerable:!0,get:function(){return Mw.str}});Object.defineProperty(Pb,"strConcat",{enumerable:!0,get:function(){return Mw.strConcat}});Object.defineProperty(Pb,"nil",{enumerable:!0,get:function(){return Mw.nil}});Object.defineProperty(Pb,"getProperty",{enumerable:!0,get:function(){return Mw.getProperty}});Object.defineProperty(Pb,"stringify",{enumerable:!0,get:function(){return Mw.stringify}});Object.defineProperty(Pb,"regexpCode",{enumerable:!0,get:function(){return Mw.regexpCode}});Object.defineProperty(Pb,"Name",{enumerable:!0,get:function(){return Mw.Name}});var $$=X4();Object.defineProperty(Pb,"Scope",{enumerable:!0,get:function(){return $$.Scope}});Object.defineProperty(Pb,"ValueScope",{enumerable:!0,get:function(){return $$.ValueScope}});Object.defineProperty(Pb,"ValueScopeName",{enumerable:!0,get:function(){return $$.ValueScopeName}});Object.defineProperty(Pb,"varKinds",{enumerable:!0,get:function(){return $$.varKinds}});Pb.operators={GT:new c._Code(">"),GTE:new c._Code(">="),LT:new c._Code("<"),LTE:new c._Code("<="),EQ:new c._Code("==="),NEQ:new c._Code("!=="),NOT:new c._Code("!"),OR:new c._Code("||"),AND:new c._Code("&&"),ADD:new c._Code("+")};class Pw{optimizeNodes(){return this}optimizeNames(b,w){return this}}class xG extends Pw{constructor(b,w,$){super();this.varKind=b,this.name=w,this.rhs=$}render({es5:b,_n:w}){let $=b?hb.varKinds.var:this.varKind,Q=this.rhs===void 0?"":` = ${this.rhs}`;return`${$} ${this.name}${Q};`+w}optimizeNames(b,w){if(!b[this.name.str])return;if(this.rhs)this.rhs=dw(this.rhs,b,w);return this}get names(){return this.rhs instanceof c._CodeOrName?this.rhs.names:{}}}class z4 extends Pw{constructor(b,w,$){super();this.lhs=b,this.rhs=w,this.sideEffects=$}render({_n:b}){return`${this.lhs} = ${this.rhs};`+b}optimizeNames(b,w){if(this.lhs instanceof c.Name&&!b[this.lhs.str]&&!this.sideEffects)return;return this.rhs=dw(this.rhs,b,w),this}get names(){let b=this.lhs instanceof c.Name?{}:{...this.lhs.names};return w$(b,this.rhs)}}class uG extends z4{constructor(b,w,$,Q){super(b,$,Q);this.op=w}render({_n:b}){return`${this.lhs} ${this.op}= ${this.rhs};`+b}}class yG extends Pw{constructor(b){super();this.label=b,this.names={}}render({_n:b}){return`${this.label}:`+b}}class hG extends Pw{constructor(b){super();this.label=b,this.names={}}render({_n:b}){return`break${this.label?` ${this.label}`:""};`+b}}class fG extends Pw{constructor(b){super();this.error=b}render({_n:b}){return`throw ${this.error};`+b}get names(){return this.error.names}}class gG extends Pw{constructor(b){super();this.code=b}render({_n:b}){return`${this.code};`+b}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(b,w){return this.code=dw(this.code,b,w),this}get names(){return this.code instanceof c._CodeOrName?this.code.names:{}}}class Q$ extends Pw{constructor(b=[]){super();this.nodes=b}render(b){return this.nodes.reduce((w,$)=>w+$.render(b),"")}optimizeNodes(){let{nodes:b}=this,w=b.length;while(w--){let $=b[w].optimizeNodes();if(Array.isArray($))b.splice(w,1,...$);else if($)b[w]=$;else b.splice(w,1)}return b.length>0?this:void 0}optimizeNames(b,w){let{nodes:$}=this,Q=$.length;while(Q--){let W=$[Q];if(W.optimizeNames(b,w))continue;EO(b,W.names),$.splice(Q,1)}return $.length>0?this:void 0}get names(){return this.nodes.reduce((b,w)=>Cw(b,w.names),{})}}class Zw extends Q${render(b){return"{"+b._n+super.render(b)+"}"+b._n}}class cG extends Q${}class f1 extends Zw{}f1.kind="else";class $w extends Zw{constructor(b,w){super(w);this.condition=b}render(b){let w=`if(${this.condition})`+super.render(b);if(this.else)w+="else "+this.else.render(b);return w}optimizeNodes(){super.optimizeNodes();let b=this.condition;if(b===!0)return this.nodes;let w=this.else;if(w){let $=w.optimizeNodes();w=this.else=Array.isArray($)?new f1($):$}if(w){if(b===!1)return w instanceof $w?w:w.nodes;if(this.nodes.length)return this;return new $w(pG(b),w instanceof $w?[w]:w.nodes)}if(b===!1||!this.nodes.length)return;return this}optimizeNames(b,w){var $;if(this.else=($=this.else)===null||$===void 0?void 0:$.optimizeNames(b,w),!(super.optimizeNames(b,w)||this.else))return;return this.condition=dw(this.condition,b,w),this}get names(){let b=super.names;if(w$(b,this.condition),this.else)Cw(b,this.else.names);return b}}$w.kind="if";class ow extends Zw{}ow.kind="for";class mG extends ow{constructor(b){super();this.iteration=b}render(b){return`for(${this.iteration})`+super.render(b)}optimizeNames(b,w){if(!super.optimizeNames(b,w))return;return this.iteration=dw(this.iteration,b,w),this}get names(){return Cw(super.names,this.iteration.names)}}class lG extends ow{constructor(b,w,$,Q){super();this.varKind=b,this.name=w,this.from=$,this.to=Q}render(b){let w=b.es5?hb.varKinds.var:this.varKind,{name:$,from:Q,to:W}=this;return`for(${w} ${$}=${Q}; ${$}<${W}; ${$}++)`+super.render(b)}get names(){let b=w$(super.names,this.from);return w$(b,this.to)}}class Y4 extends ow{constructor(b,w,$,Q){super();this.loop=b,this.varKind=w,this.name=$,this.iterable=Q}render(b){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(b)}optimizeNames(b,w){if(!super.optimizeNames(b,w))return;return this.iterable=dw(this.iterable,b,w),this}get names(){return Cw(super.names,this.iterable.names)}}class e0 extends Zw{constructor(b,w,$){super();this.name=b,this.args=w,this.async=$}render(b){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(b)}}e0.kind="func";class s0 extends Q${render(b){return"return "+super.render(b)}}s0.kind="return";class nG extends Zw{render(b){let w="try"+super.render(b);if(this.catch)w+=this.catch.render(b);if(this.finally)w+=this.finally.render(b);return w}optimizeNodes(){var b,w;return super.optimizeNodes(),(b=this.catch)===null||b===void 0||b.optimizeNodes(),(w=this.finally)===null||w===void 0||w.optimizeNodes(),this}optimizeNames(b,w){var $,Q;return super.optimizeNames(b,w),($=this.catch)===null||$===void 0||$.optimizeNames(b,w),(Q=this.finally)===null||Q===void 0||Q.optimizeNames(b,w),this}get names(){let b=super.names;if(this.catch)Cw(b,this.catch.names);if(this.finally)Cw(b,this.finally.names);return b}}class a0 extends Zw{constructor(b){super();this.error=b}render(b){return`catch(${this.error})`+super.render(b)}}a0.kind="catch";class b$ extends Zw{render(b){return"finally"+super.render(b)}}b$.kind="finally";class iG{constructor(b,w={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...w,_n:w.lines?`
|
|
3
|
+
`:""},this._extScope=b,this._scope=new hb.Scope({parent:b}),this._nodes=[new cG]}toString(){return this._root.render(this.opts)}name(b){return this._scope.name(b)}scopeName(b){return this._extScope.name(b)}scopeValue(b,w){let $=this._extScope.value(b,w);return(this._values[$.prefix]||(this._values[$.prefix]=new Set)).add($),$}getScopeValue(b,w){return this._extScope.getValue(b,w)}scopeRefs(b){return this._extScope.scopeRefs(b,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(b,w,$,Q){let W=this._scope.toName(w);if($!==void 0&&Q)this._constants[W.str]=$;return this._leafNode(new xG(b,W,$)),W}const(b,w,$){return this._def(hb.varKinds.const,b,w,$)}let(b,w,$){return this._def(hb.varKinds.let,b,w,$)}var(b,w,$){return this._def(hb.varKinds.var,b,w,$)}assign(b,w,$){return this._leafNode(new z4(b,w,$))}add(b,w){return this._leafNode(new uG(b,Pb.operators.ADD,w))}code(b){if(typeof b=="function")b();else if(b!==c.nil)this._leafNode(new gG(b));return this}object(...b){let w=["{"];for(let[$,Q]of b){if(w.length>1)w.push(",");if(w.push($),$!==Q||this.opts.es5)w.push(":"),(0,c.addCodeArg)(w,Q)}return w.push("}"),new c._Code(w)}if(b,w,$){if(this._blockNode(new $w(b)),w&&$)this.code(w).else().code($).endIf();else if(w)this.code(w).endIf();else if($)throw Error('CodeGen: "else" body without "then" body');return this}elseIf(b){return this._elseNode(new $w(b))}else(){return this._elseNode(new f1)}endIf(){return this._endBlockNode($w,f1)}_for(b,w){if(this._blockNode(b),w)this.code(w).endFor();return this}for(b,w){return this._for(new mG(b),w)}forRange(b,w,$,Q,W=this.opts.es5?hb.varKinds.var:hb.varKinds.let){let G=this._scope.toName(b);return this._for(new lG(W,G,w,$),()=>Q(G))}forOf(b,w,$,Q=hb.varKinds.const){let W=this._scope.toName(b);if(this.opts.es5){let G=w instanceof c.Name?w:this.var("_arr",w);return this.forRange("_i",0,c._`${G}.length`,(X)=>{this.var(W,c._`${G}[${X}]`),$(W)})}return this._for(new Y4("of",Q,W,w),()=>$(W))}forIn(b,w,$,Q=this.opts.es5?hb.varKinds.var:hb.varKinds.const){if(this.opts.ownProperties)return this.forOf(b,c._`Object.keys(${w})`,$);let W=this._scope.toName(b);return this._for(new Y4("in",Q,W,w),()=>$(W))}endFor(){return this._endBlockNode(ow)}label(b){return this._leafNode(new yG(b))}break(b){return this._leafNode(new hG(b))}return(b){let w=new s0;if(this._blockNode(w),this.code(b),w.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(s0)}try(b,w,$){if(!w&&!$)throw Error('CodeGen: "try" without "catch" and "finally"');let Q=new nG;if(this._blockNode(Q),this.code(b),w){let W=this.name("e");this._currNode=Q.catch=new a0(W),w(W)}if($)this._currNode=Q.finally=new b$,this.code($);return this._endBlockNode(a0,b$)}throw(b){return this._leafNode(new fG(b))}block(b,w){if(this._blockStarts.push(this._nodes.length),b)this.code(b).endBlock(w);return this}endBlock(b){let w=this._blockStarts.pop();if(w===void 0)throw Error("CodeGen: not in self-balancing block");let $=this._nodes.length-w;if($<0||b!==void 0&&$!==b)throw Error(`CodeGen: wrong number of nodes: ${$} vs ${b} expected`);return this._nodes.length=w,this}func(b,w=c.nil,$,Q){if(this._blockNode(new e0(b,w,$)),Q)this.code(Q).endFunc();return this}endFunc(){return this._endBlockNode(e0)}optimize(b=1){while(b-- >0)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(b){return this._currNode.nodes.push(b),this}_blockNode(b){this._currNode.nodes.push(b),this._nodes.push(b)}_endBlockNode(b,w){let $=this._currNode;if($ instanceof b||w&&$ instanceof w)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${w?`${b.kind}/${w.kind}`:b.kind}"`)}_elseNode(b){let w=this._currNode;if(!(w instanceof $w))throw Error('CodeGen: "else" without "if"');return this._currNode=w.else=b,this}get _root(){return this._nodes[0]}get _currNode(){let b=this._nodes;return b[b.length-1]}set _currNode(b){let w=this._nodes;w[w.length-1]=b}}Pb.CodeGen=iG;function Cw(b,w){for(let $ in w)b[$]=(b[$]||0)+(w[$]||0);return b}function w$(b,w){return w instanceof c._CodeOrName?Cw(b,w.names):b}function dw(b,w,$){if(b instanceof c.Name)return Q(b);if(!W(b))return b;return new c._Code(b._items.reduce((G,X)=>{if(X instanceof c.Name)X=Q(X);if(X instanceof c._Code)G.push(...X._items);else G.push(X);return G},[]));function Q(G){let X=$[G.str];if(X===void 0||w[G.str]!==1)return G;return delete w[G.str],X}function W(G){return G instanceof c._Code&&G._items.some((X)=>X instanceof c.Name&&w[X.str]===1&&$[X.str]!==void 0)}}function EO(b,w){for(let $ in w)b[$]=(b[$]||0)-(w[$]||0)}function pG(b){return typeof b=="boolean"||typeof b=="number"||b===null?!b:c._`!${J4(b)}`}Pb.not=pG;var TO=oG(Pb.operators.AND);function _O(...b){return b.reduce(TO)}Pb.and=_O;var SO=oG(Pb.operators.OR);function RO(...b){return b.reduce(SO)}Pb.or=RO;function oG(b){return(w,$)=>w===c.nil?$:$===c.nil?w:c._`${J4(w)} ${b} ${J4($)}`}function J4(b){return b instanceof c.Name?b:c._`(${b})`}});var n=I(($X)=>{Object.defineProperty($X,"__esModule",{value:!0});$X.checkStrictMode=$X.getErrorPath=$X.Type=$X.useFunc=$X.setEvaluated=$X.evaluatedPropsToName=$X.mergeEvaluated=$X.eachItem=$X.unescapeJsonPointer=$X.escapeJsonPointer=$X.escapeFragment=$X.unescapeFragment=$X.schemaRefOrVal=$X.schemaHasRulesButRef=$X.schemaHasRules=$X.checkUnknownRules=$X.alwaysValidSchema=$X.toHash=void 0;var d=u(),xO=h1();function uO(b){let w={};for(let $ of b)w[$]=!0;return w}$X.toHash=uO;function yO(b,w){if(typeof w=="boolean")return w;if(Object.keys(w).length===0)return!0;return eG(b,w),!sG(w,b.self.RULES.all)}$X.alwaysValidSchema=yO;function eG(b,w=b.schema){let{opts:$,self:Q}=b;if(!$.strictSchema)return;if(typeof w==="boolean")return;let W=Q.RULES.keywords;for(let G in w)if(!W[G])wX(b,`unknown keyword: "${G}"`)}$X.checkUnknownRules=eG;function sG(b,w){if(typeof b=="boolean")return!b;for(let $ in b)if(w[$])return!0;return!1}$X.schemaHasRules=sG;function hO(b,w){if(typeof b=="boolean")return!b;for(let $ in b)if($!=="$ref"&&w.all[$])return!0;return!1}$X.schemaHasRulesButRef=hO;function fO({topSchemaRef:b,schemaPath:w},$,Q,W){if(!W){if(typeof $=="number"||typeof $=="boolean")return $;if(typeof $=="string")return d._`${$}`}return d._`${b}${w}${(0,d.getProperty)(Q)}`}$X.schemaRefOrVal=fO;function gO(b){return aG(decodeURIComponent(b))}$X.unescapeFragment=gO;function cO(b){return encodeURIComponent(A4(b))}$X.escapeFragment=cO;function A4(b){if(typeof b=="number")return`${b}`;return b.replace(/~/g,"~0").replace(/\//g,"~1")}$X.escapeJsonPointer=A4;function aG(b){return b.replace(/~1/g,"/").replace(/~0/g,"~")}$X.unescapeJsonPointer=aG;function mO(b,w){if(Array.isArray(b))for(let $ of b)w($);else w(b)}$X.eachItem=mO;function rG({mergeNames:b,mergeToName:w,mergeValues:$,resultToName:Q}){return(W,G,X,Y)=>{let J=X===void 0?G:X instanceof d.Name?(G instanceof d.Name?b(W,G,X):w(W,G,X),X):G instanceof d.Name?(w(W,X,G),G):$(G,X);return Y===d.Name&&!(J instanceof d.Name)?Q(W,J):J}}$X.mergeEvaluated={props:rG({mergeNames:(b,w,$)=>b.if(d._`${$} !== true && ${w} !== undefined`,()=>{b.if(d._`${w} === true`,()=>b.assign($,!0),()=>b.assign($,d._`${$} || {}`).code(d._`Object.assign(${$}, ${w})`))}),mergeToName:(b,w,$)=>b.if(d._`${$} !== true`,()=>{if(w===!0)b.assign($,!0);else b.assign($,d._`${$} || {}`),D4(b,$,w)}),mergeValues:(b,w)=>b===!0?!0:{...b,...w},resultToName:bX}),items:rG({mergeNames:(b,w,$)=>b.if(d._`${$} !== true && ${w} !== undefined`,()=>b.assign($,d._`${w} === true ? true : ${$} > ${w} ? ${$} : ${w}`)),mergeToName:(b,w,$)=>b.if(d._`${$} !== true`,()=>b.assign($,w===!0?!0:d._`${$} > ${w} ? ${$} : ${w}`)),mergeValues:(b,w)=>b===!0?!0:Math.max(b,w),resultToName:(b,w)=>b.var("items",w)})};function bX(b,w){if(w===!0)return b.var("props",!0);let $=b.var("props",d._`{}`);if(w!==void 0)D4(b,$,w);return $}$X.evaluatedPropsToName=bX;function D4(b,w,$){Object.keys($).forEach((Q)=>b.assign(d._`${w}${(0,d.getProperty)(Q)}`,!0))}$X.setEvaluated=D4;var tG={};function lO(b,w){return b.scopeValue("func",{ref:w,code:tG[w.code]||(tG[w.code]=new xO._Code(w.code))})}$X.useFunc=lO;var H4;(function(b){b[b.Num=0]="Num",b[b.Str=1]="Str"})(H4||($X.Type=H4={}));function nO(b,w,$){if(b instanceof d.Name){let Q=w===H4.Num;return $?Q?d._`"[" + ${b} + "]"`:d._`"['" + ${b} + "']"`:Q?d._`"/" + ${b}`:d._`"/" + ${b}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return $?(0,d.getProperty)(b).toString():"/"+A4(b)}$X.getErrorPath=nO;function wX(b,w,$=b.opts.strictSchema){if(!$)return;if(w=`strict mode: ${w}`,$===!0)throw Error(w);b.self.logger.warn(w)}$X.checkStrictMode=wX});var Qw=I((WX)=>{Object.defineProperty(WX,"__esModule",{value:!0});var Ub=u(),Jq={data:new Ub.Name("data"),valCxt:new Ub.Name("valCxt"),instancePath:new Ub.Name("instancePath"),parentData:new Ub.Name("parentData"),parentDataProperty:new Ub.Name("parentDataProperty"),rootData:new Ub.Name("rootData"),dynamicAnchors:new Ub.Name("dynamicAnchors"),vErrors:new Ub.Name("vErrors"),errors:new Ub.Name("errors"),this:new Ub.Name("this"),self:new Ub.Name("self"),scope:new Ub.Name("scope"),json:new Ub.Name("json"),jsonPos:new Ub.Name("jsonPos"),jsonLen:new Ub.Name("jsonLen"),jsonPart:new Ub.Name("jsonPart")};WX.default=Jq});var g1=I((JX)=>{Object.defineProperty(JX,"__esModule",{value:!0});JX.extendErrors=JX.resetErrorsCount=JX.reportExtraError=JX.reportError=JX.keyword$DataError=JX.keywordError=void 0;var m=u(),G$=n(),Bb=Qw();JX.keywordError={message:({keyword:b})=>m.str`must pass "${b}" keyword validation`};JX.keyword$DataError={message:({keyword:b,schemaType:w})=>w?m.str`"${b}" keyword must be ${w} ($data)`:m.str`"${b}" keyword is invalid ($data)`};function Hq(b,w=JX.keywordError,$,Q){let{it:W}=b,{gen:G,compositeRule:X,allErrors:Y}=W,J=YX(b,w,$);if(Q!==null&&Q!==void 0?Q:X||Y)GX(G,J);else XX(W,m._`[${J}]`)}JX.reportError=Hq;function Aq(b,w=JX.keywordError,$){let{it:Q}=b,{gen:W,compositeRule:G,allErrors:X}=Q,Y=YX(b,w,$);if(GX(W,Y),!(G||X))XX(Q,Bb.default.vErrors)}JX.reportExtraError=Aq;function Dq(b,w){b.assign(Bb.default.errors,w),b.if(m._`${Bb.default.vErrors} !== null`,()=>b.if(w,()=>b.assign(m._`${Bb.default.vErrors}.length`,w),()=>b.assign(Bb.default.vErrors,null)))}JX.resetErrorsCount=Dq;function Oq({gen:b,keyword:w,schemaValue:$,data:Q,errsCount:W,it:G}){if(W===void 0)throw Error("ajv implementation error");let X=b.name("err");b.forRange("i",W,Bb.default.errors,(Y)=>{if(b.const(X,m._`${Bb.default.vErrors}[${Y}]`),b.if(m._`${X}.instancePath === undefined`,()=>b.assign(m._`${X}.instancePath`,(0,m.strConcat)(Bb.default.instancePath,G.errorPath))),b.assign(m._`${X}.schemaPath`,m.str`${G.errSchemaPath}/${w}`),G.opts.verbose)b.assign(m._`${X}.schema`,$),b.assign(m._`${X}.data`,Q)})}JX.extendErrors=Oq;function GX(b,w){let $=b.const("err",w);b.if(m._`${Bb.default.vErrors} === null`,()=>b.assign(Bb.default.vErrors,m._`[${$}]`),m._`${Bb.default.vErrors}.push(${$})`),b.code(m._`${Bb.default.errors}++`)}function XX(b,w){let{gen:$,validateName:Q,schemaEnv:W}=b;if(W.$async)$.throw(m._`new ${b.ValidationError}(${w})`);else $.assign(m._`${Q}.errors`,w),$.return(!1)}var vw={keyword:new m.Name("keyword"),schemaPath:new m.Name("schemaPath"),params:new m.Name("params"),propertyName:new m.Name("propertyName"),message:new m.Name("message"),schema:new m.Name("schema"),parentSchema:new m.Name("parentSchema")};function YX(b,w,$){let{createErrors:Q}=b.it;if(Q===!1)return m._`{}`;return qq(b,w,$)}function qq(b,w,$={}){let{gen:Q,it:W}=b,G=[Uq(W,$),Lq(b,$)];return Bq(b,w,G),Q.object(...G)}function Uq({errorPath:b},{instancePath:w}){let $=w?m.str`${b}${(0,G$.getErrorPath)(w,G$.Type.Str)}`:b;return[Bb.default.instancePath,(0,m.strConcat)(Bb.default.instancePath,$)]}function Lq({keyword:b,it:{errSchemaPath:w}},{schemaPath:$,parentSchema:Q}){let W=Q?w:m.str`${w}/${b}`;if($)W=m.str`${W}${(0,G$.getErrorPath)($,G$.Type.Str)}`;return[vw.schemaPath,W]}function Bq(b,{params:w,message:$},Q){let{keyword:W,data:G,schemaValue:X,it:Y}=b,{opts:J,propertyName:z,topSchemaRef:H,schemaPath:A}=Y;if(Q.push([vw.keyword,W],[vw.params,typeof w=="function"?w(b):w||m._`{}`]),J.messages)Q.push([vw.message,typeof $=="function"?$(b):$]);if(J.verbose)Q.push([vw.schema,X],[vw.parentSchema,m._`${H}${A}`],[Bb.default.data,G]);if(z)Q.push([vw.propertyName,z])}});var OX=I((AX)=>{Object.defineProperty(AX,"__esModule",{value:!0});AX.boolOrEmptySchema=AX.topBoolOrEmptySchema=void 0;var Zq=g1(),Iq=u(),Vq=Qw(),jq={message:"boolean schema is false"};function Nq(b){let{gen:w,schema:$,validateName:Q}=b;if($===!1)HX(b,!1);else if(typeof $=="object"&&$.$async===!0)w.return(Vq.default.data);else w.assign(Iq._`${Q}.errors`,null),w.return(!0)}AX.topBoolOrEmptySchema=Nq;function Eq(b,w){let{gen:$,schema:Q}=b;if(Q===!1)$.var(w,!1),HX(b);else $.var(w,!0)}AX.boolOrEmptySchema=Eq;function HX(b,w){let{gen:$,data:Q}=b,W={gen:$,keyword:"false schema",data:Q,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:b};(0,Zq.reportError)(W,jq,void 0,w)}});var q4=I((qX)=>{Object.defineProperty(qX,"__esModule",{value:!0});qX.getRules=qX.isJSONType=void 0;var _q=["string","number","integer","boolean","null","object","array"],Sq=new Set(_q);function Rq(b){return typeof b=="string"&&Sq.has(b)}qX.isJSONType=Rq;function Cq(){let b={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...b,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},b.number,b.string,b.array,b.object],post:{rules:[]},all:{},keywords:{}}}qX.getRules=Cq});var U4=I((KX)=>{Object.defineProperty(KX,"__esModule",{value:!0});KX.shouldUseRule=KX.shouldUseGroup=KX.schemaHasRulesForType=void 0;function kq({schema:b,self:w},$){let Q=w.RULES.types[$];return Q&&Q!==!0&&LX(b,Q)}KX.schemaHasRulesForType=kq;function LX(b,w){return w.rules.some(($)=>BX(b,$))}KX.shouldUseGroup=LX;function BX(b,w){var $;return b[w.keyword]!==void 0||(($=w.definition.implements)===null||$===void 0?void 0:$.some((Q)=>b[Q]!==void 0))}KX.shouldUseRule=BX});var c1=I((IX)=>{Object.defineProperty(IX,"__esModule",{value:!0});IX.reportTypeError=IX.checkDataTypes=IX.checkDataType=IX.coerceAndCheckDataType=IX.getJSONTypes=IX.getSchemaTypes=IX.DataType=void 0;var yq=q4(),hq=U4(),fq=g1(),k=u(),MX=n(),rw;(function(b){b[b.Correct=0]="Correct",b[b.Wrong=1]="Wrong"})(rw||(IX.DataType=rw={}));function gq(b){let w=PX(b.type);if(w.includes("null")){if(b.nullable===!1)throw Error("type: null contradicts nullable: false")}else{if(!w.length&&b.nullable!==void 0)throw Error('"nullable" cannot be used without "type"');if(b.nullable===!0)w.push("null")}return w}IX.getSchemaTypes=gq;function PX(b){let w=Array.isArray(b)?b:b?[b]:[];if(w.every(yq.isJSONType))return w;throw Error("type must be JSONType or JSONType[]: "+w.join(","))}IX.getJSONTypes=PX;function cq(b,w){let{gen:$,data:Q,opts:W}=b,G=mq(w,W.coerceTypes),X=w.length>0&&!(G.length===0&&w.length===1&&(0,hq.schemaHasRulesForType)(b,w[0]));if(X){let Y=B4(w,Q,W.strictNumbers,rw.Wrong);$.if(Y,()=>{if(G.length)lq(b,w,G);else K4(b)})}return X}IX.coerceAndCheckDataType=cq;var ZX=new Set(["string","number","integer","boolean","null"]);function mq(b,w){return w?b.filter(($)=>ZX.has($)||w==="array"&&$==="array"):[]}function lq(b,w,$){let{gen:Q,data:W,opts:G}=b,X=Q.let("dataType",k._`typeof ${W}`),Y=Q.let("coerced",k._`undefined`);if(G.coerceTypes==="array")Q.if(k._`${X} == 'object' && Array.isArray(${W}) && ${W}.length == 1`,()=>Q.assign(W,k._`${W}[0]`).assign(X,k._`typeof ${W}`).if(B4(w,W,G.strictNumbers),()=>Q.assign(Y,W)));Q.if(k._`${Y} !== undefined`);for(let z of $)if(ZX.has(z)||z==="array"&&G.coerceTypes==="array")J(z);Q.else(),K4(b),Q.endIf(),Q.if(k._`${Y} !== undefined`,()=>{Q.assign(W,Y),nq(b,Y)});function J(z){switch(z){case"string":Q.elseIf(k._`${X} == "number" || ${X} == "boolean"`).assign(Y,k._`"" + ${W}`).elseIf(k._`${W} === null`).assign(Y,k._`""`);return;case"number":Q.elseIf(k._`${X} == "boolean" || ${W} === null
|
|
4
|
+
|| (${X} == "string" && ${W} && ${W} == +${W})`).assign(Y,k._`+${W}`);return;case"integer":Q.elseIf(k._`${X} === "boolean" || ${W} === null
|
|
5
|
+
|| (${X} === "string" && ${W} && ${W} == +${W} && !(${W} % 1))`).assign(Y,k._`+${W}`);return;case"boolean":Q.elseIf(k._`${W} === "false" || ${W} === 0 || ${W} === null`).assign(Y,!1).elseIf(k._`${W} === "true" || ${W} === 1`).assign(Y,!0);return;case"null":Q.elseIf(k._`${W} === "" || ${W} === 0 || ${W} === false`),Q.assign(Y,null);return;case"array":Q.elseIf(k._`${X} === "string" || ${X} === "number"
|
|
6
|
+
|| ${X} === "boolean" || ${W} === null`).assign(Y,k._`[${W}]`)}}}function nq({gen:b,parentData:w,parentDataProperty:$},Q){b.if(k._`${w} !== undefined`,()=>b.assign(k._`${w}[${$}]`,Q))}function L4(b,w,$,Q=rw.Correct){let W=Q===rw.Correct?k.operators.EQ:k.operators.NEQ,G;switch(b){case"null":return k._`${w} ${W} null`;case"array":G=k._`Array.isArray(${w})`;break;case"object":G=k._`${w} && typeof ${w} == "object" && !Array.isArray(${w})`;break;case"integer":G=X(k._`!(${w} % 1) && !isNaN(${w})`);break;case"number":G=X();break;default:return k._`typeof ${w} ${W} ${b}`}return Q===rw.Correct?G:(0,k.not)(G);function X(Y=k.nil){return(0,k.and)(k._`typeof ${w} == "number"`,Y,$?k._`isFinite(${w})`:k.nil)}}IX.checkDataType=L4;function B4(b,w,$,Q){if(b.length===1)return L4(b[0],w,$,Q);let W,G=(0,MX.toHash)(b);if(G.array&&G.object){let X=k._`typeof ${w} != "object"`;W=G.null?X:k._`!${w} || ${X}`,delete G.null,delete G.array,delete G.object}else W=k.nil;if(G.number)delete G.integer;for(let X in G)W=(0,k.and)(W,L4(X,w,$,Q));return W}IX.checkDataTypes=B4;var iq={message:({schema:b})=>`must be ${b}`,params:({schema:b,schemaValue:w})=>typeof b=="string"?k._`{type: ${b}}`:k._`{type: ${w}}`};function K4(b){let w=pq(b);(0,fq.reportError)(w,iq)}IX.reportTypeError=K4;function pq(b){let{gen:w,data:$,schema:Q}=b,W=(0,MX.schemaRefOrVal)(b,Q,"type");return{gen:w,keyword:"type",data:$,schema:Q.type,schemaCode:W,schemaValue:W,parentSchema:Q,params:{},it:b}}});var TX=I((NX)=>{Object.defineProperty(NX,"__esModule",{value:!0});NX.assignDefaults=void 0;var tw=u(),aq=n();function bU(b,w){let{properties:$,items:Q}=b.schema;if(w==="object"&&$)for(let W in $)jX(b,W,$[W].default);else if(w==="array"&&Array.isArray(Q))Q.forEach((W,G)=>jX(b,G,W.default))}NX.assignDefaults=bU;function jX(b,w,$){let{gen:Q,compositeRule:W,data:G,opts:X}=b;if($===void 0)return;let Y=tw._`${G}${(0,tw.getProperty)(w)}`;if(W){(0,aq.checkStrictMode)(b,`default is ignored for: ${Y}`);return}let J=tw._`${Y} === undefined`;if(X.useDefaults==="empty")J=tw._`${J} || ${Y} === null || ${Y} === ""`;Q.if(J,tw._`${Y} = ${(0,tw.stringify)($)}`)}});var Cb=I((RX)=>{Object.defineProperty(RX,"__esModule",{value:!0});RX.validateUnion=RX.validateArray=RX.usePattern=RX.callValidateCode=RX.schemaProperties=RX.allSchemaProperties=RX.noPropertyInData=RX.propertyInData=RX.isOwnProperty=RX.hasPropFunc=RX.reportMissingProp=RX.checkMissingProp=RX.checkReportMissingProp=void 0;var s=u(),F4=n(),Iw=Qw(),wU=n();function $U(b,w){let{gen:$,data:Q,it:W}=b;$.if(P4($,Q,w,W.opts.ownProperties),()=>{b.setParams({missingProperty:s._`${w}`},!0),b.error()})}RX.checkReportMissingProp=$U;function QU({gen:b,data:w,it:{opts:$}},Q,W){return(0,s.or)(...Q.map((G)=>(0,s.and)(P4(b,w,G,$.ownProperties),s._`${W} = ${G}`)))}RX.checkMissingProp=QU;function WU(b,w){b.setParams({missingProperty:w},!0),b.error()}RX.reportMissingProp=WU;function _X(b){return b.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:s._`Object.prototype.hasOwnProperty`})}RX.hasPropFunc=_X;function M4(b,w,$){return s._`${_X(b)}.call(${w}, ${$})`}RX.isOwnProperty=M4;function GU(b,w,$,Q){let W=s._`${w}${(0,s.getProperty)($)} !== undefined`;return Q?s._`${W} && ${M4(b,w,$)}`:W}RX.propertyInData=GU;function P4(b,w,$,Q){let W=s._`${w}${(0,s.getProperty)($)} === undefined`;return Q?(0,s.or)(W,(0,s.not)(M4(b,w,$))):W}RX.noPropertyInData=P4;function SX(b){return b?Object.keys(b).filter((w)=>w!=="__proto__"):[]}RX.allSchemaProperties=SX;function XU(b,w){return SX(w).filter(($)=>!(0,F4.alwaysValidSchema)(b,w[$]))}RX.schemaProperties=XU;function YU({schemaCode:b,data:w,it:{gen:$,topSchemaRef:Q,schemaPath:W,errorPath:G},it:X},Y,J,z){let H=z?s._`${b}, ${w}, ${Q}${W}`:w,A=[[Iw.default.instancePath,(0,s.strConcat)(Iw.default.instancePath,G)],[Iw.default.parentData,X.parentData],[Iw.default.parentDataProperty,X.parentDataProperty],[Iw.default.rootData,Iw.default.rootData]];if(X.opts.dynamicRef)A.push([Iw.default.dynamicAnchors,Iw.default.dynamicAnchors]);let O=s._`${H}, ${$.object(...A)}`;return J!==s.nil?s._`${Y}.call(${J}, ${O})`:s._`${Y}(${O})`}RX.callValidateCode=YU;var JU=s._`new RegExp`;function zU({gen:b,it:{opts:w}},$){let Q=w.unicodeRegExp?"u":"",{regExp:W}=w.code,G=W($,Q);return b.scopeValue("pattern",{key:G.toString(),ref:G,code:s._`${W.code==="new RegExp"?JU:(0,wU.useFunc)(b,W)}(${$}, ${Q})`})}RX.usePattern=zU;function HU(b){let{gen:w,data:$,keyword:Q,it:W}=b,G=w.name("valid");if(W.allErrors){let Y=w.let("valid",!0);return X(()=>w.assign(Y,!1)),Y}return w.var(G,!0),X(()=>w.break()),G;function X(Y){let J=w.const("len",s._`${$}.length`);w.forRange("i",0,J,(z)=>{b.subschema({keyword:Q,dataProp:z,dataPropType:F4.Type.Num},G),w.if((0,s.not)(G),Y)})}}RX.validateArray=HU;function AU(b){let{gen:w,schema:$,keyword:Q,it:W}=b;if(!Array.isArray($))throw Error("ajv implementation error");if($.some((J)=>(0,F4.alwaysValidSchema)(W,J))&&!W.opts.unevaluated)return;let X=w.let("valid",!1),Y=w.name("_valid");w.block(()=>$.forEach((J,z)=>{let H=b.subschema({keyword:Q,schemaProp:z,compositeRule:!0},Y);if(w.assign(X,s._`${X} || ${Y}`),!b.mergeValidEvaluated(H,Y))w.if((0,s.not)(X))})),b.result(X,()=>b.reset(),()=>b.error(!0))}RX.validateUnion=AU});var yX=I((xX)=>{Object.defineProperty(xX,"__esModule",{value:!0});xX.validateKeywordUsage=xX.validSchemaType=xX.funcKeywordCode=xX.macroKeywordCode=void 0;var Kb=u(),kw=Qw(),VU=Cb(),jU=g1();function NU(b,w){let{gen:$,keyword:Q,schema:W,parentSchema:G,it:X}=b,Y=w.macro.call(X.self,W,G,X),J=kX($,Q,Y);if(X.opts.validateSchema!==!1)X.self.validateSchema(Y,!0);let z=$.name("valid");b.subschema({schema:Y,schemaPath:Kb.nil,errSchemaPath:`${X.errSchemaPath}/${Q}`,topSchemaRef:J,compositeRule:!0},z),b.pass(z,()=>b.error(!0))}xX.macroKeywordCode=NU;function EU(b,w){var $;let{gen:Q,keyword:W,schema:G,parentSchema:X,$data:Y,it:J}=b;_U(J,w);let z=!Y&&w.compile?w.compile.call(J.self,G,X,J):w.validate,H=kX(Q,W,z),A=Q.let("valid");b.block$data(A,O),b.ok(($=w.valid)!==null&&$!==void 0?$:A);function O(){if(w.errors===!1){if(K(),w.modifying)vX(b);Z(()=>b.error())}else{let P=w.async?q():B();if(w.modifying)vX(b);Z(()=>TU(b,P))}}function q(){let P=Q.let("ruleErrs",null);return Q.try(()=>K(Kb._`await `),(C)=>Q.assign(A,!1).if(Kb._`${C} instanceof ${J.ValidationError}`,()=>Q.assign(P,Kb._`${C}.errors`),()=>Q.throw(C))),P}function B(){let P=Kb._`${H}.errors`;return Q.assign(P,null),K(Kb.nil),P}function K(P=w.async?Kb._`await `:Kb.nil){let C=J.opts.passContext?kw.default.this:kw.default.self,S=!(("compile"in w)&&!Y||w.schema===!1);Q.assign(A,Kb._`${P}${(0,VU.callValidateCode)(b,H,C,S)}`,w.modifying)}function Z(P){var C;Q.if((0,Kb.not)((C=w.valid)!==null&&C!==void 0?C:A),P)}}xX.funcKeywordCode=EU;function vX(b){let{gen:w,data:$,it:Q}=b;w.if(Q.parentData,()=>w.assign($,Kb._`${Q.parentData}[${Q.parentDataProperty}]`))}function TU(b,w){let{gen:$}=b;$.if(Kb._`Array.isArray(${w})`,()=>{$.assign(kw.default.vErrors,Kb._`${kw.default.vErrors} === null ? ${w} : ${kw.default.vErrors}.concat(${w})`).assign(kw.default.errors,Kb._`${kw.default.vErrors}.length`),(0,jU.extendErrors)(b)},()=>b.error())}function _U({schemaEnv:b},w){if(w.async&&!b.$async)throw Error("async keyword in sync schema")}function kX(b,w,$){if($===void 0)throw Error(`keyword "${w}" failed to compile`);return b.scopeValue("keyword",typeof $=="function"?{ref:$}:{ref:$,code:(0,Kb.stringify)($)})}function SU(b,w,$=!1){return!w.length||w.some((Q)=>Q==="array"?Array.isArray(b):Q==="object"?b&&typeof b=="object"&&!Array.isArray(b):typeof b==Q||$&&typeof b>"u")}xX.validSchemaType=SU;function RU({schema:b,opts:w,self:$,errSchemaPath:Q},W,G){if(Array.isArray(W.keyword)?!W.keyword.includes(G):W.keyword!==G)throw Error("ajv implementation error");let X=W.dependencies;if(X===null||X===void 0?void 0:X.some((Y)=>!Object.prototype.hasOwnProperty.call(b,Y)))throw Error(`parent schema must have dependencies of ${G}: ${X.join(",")}`);if(W.validateSchema){if(!W.validateSchema(b[G])){let J=`keyword "${G}" value is invalid at path "${Q}": `+$.errorsText(W.validateSchema.errors);if(w.validateSchema==="log")$.logger.error(J);else throw Error(J)}}}xX.validateKeywordUsage=RU});var cX=I((fX)=>{Object.defineProperty(fX,"__esModule",{value:!0});fX.extendSubschemaMode=fX.extendSubschemaData=fX.getSubschema=void 0;var pb=u(),hX=n();function xU(b,{keyword:w,schemaProp:$,schema:Q,schemaPath:W,errSchemaPath:G,topSchemaRef:X}){if(w!==void 0&&Q!==void 0)throw Error('both "keyword" and "schema" passed, only one allowed');if(w!==void 0){let Y=b.schema[w];return $===void 0?{schema:Y,schemaPath:pb._`${b.schemaPath}${(0,pb.getProperty)(w)}`,errSchemaPath:`${b.errSchemaPath}/${w}`}:{schema:Y[$],schemaPath:pb._`${b.schemaPath}${(0,pb.getProperty)(w)}${(0,pb.getProperty)($)}`,errSchemaPath:`${b.errSchemaPath}/${w}/${(0,hX.escapeFragment)($)}`}}if(Q!==void 0){if(W===void 0||G===void 0||X===void 0)throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:Q,schemaPath:W,topSchemaRef:X,errSchemaPath:G}}throw Error('either "keyword" or "schema" must be passed')}fX.getSubschema=xU;function uU(b,w,{dataProp:$,dataPropType:Q,data:W,dataTypes:G,propertyName:X}){if(W!==void 0&&$!==void 0)throw Error('both "data" and "dataProp" passed, only one allowed');let{gen:Y}=w;if($!==void 0){let{errorPath:z,dataPathArr:H,opts:A}=w,O=Y.let("data",pb._`${w.data}${(0,pb.getProperty)($)}`,!0);J(O),b.errorPath=pb.str`${z}${(0,hX.getErrorPath)($,Q,A.jsPropertySyntax)}`,b.parentDataProperty=pb._`${$}`,b.dataPathArr=[...H,b.parentDataProperty]}if(W!==void 0){let z=W instanceof pb.Name?W:Y.let("data",W,!0);if(J(z),X!==void 0)b.propertyName=X}if(G)b.dataTypes=G;function J(z){b.data=z,b.dataLevel=w.dataLevel+1,b.dataTypes=[],w.definedProperties=new Set,b.parentData=w.data,b.dataNames=[...w.dataNames,z]}}fX.extendSubschemaData=uU;function yU(b,{jtdDiscriminator:w,jtdMetadata:$,compositeRule:Q,createErrors:W,allErrors:G}){if(Q!==void 0)b.compositeRule=Q;if(W!==void 0)b.createErrors=W;if(G!==void 0)b.allErrors=G;b.jtdDiscriminator=w,b.jtdMetadata=$}fX.extendSubschemaMode=yU});var Z4=I((BE,mX)=>{mX.exports=function b(w,$){if(w===$)return!0;if(w&&$&&typeof w=="object"&&typeof $=="object"){if(w.constructor!==$.constructor)return!1;var Q,W,G;if(Array.isArray(w)){if(Q=w.length,Q!=$.length)return!1;for(W=Q;W--!==0;)if(!b(w[W],$[W]))return!1;return!0}if(w.constructor===RegExp)return w.source===$.source&&w.flags===$.flags;if(w.valueOf!==Object.prototype.valueOf)return w.valueOf()===$.valueOf();if(w.toString!==Object.prototype.toString)return w.toString()===$.toString();if(G=Object.keys(w),Q=G.length,Q!==Object.keys($).length)return!1;for(W=Q;W--!==0;)if(!Object.prototype.hasOwnProperty.call($,G[W]))return!1;for(W=Q;W--!==0;){var X=G[W];if(!b(w[X],$[X]))return!1}return!0}return w!==w&&$!==$}});var nX=I((KE,lX)=>{var Vw=lX.exports=function(b,w,$){if(typeof w=="function")$=w,w={};$=w.cb||$;var Q=typeof $=="function"?$:$.pre||function(){},W=$.post||function(){};X$(w,Q,W,b,"",b)};Vw.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Vw.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Vw.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Vw.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function X$(b,w,$,Q,W,G,X,Y,J,z){if(Q&&typeof Q=="object"&&!Array.isArray(Q)){w(Q,W,G,X,Y,J,z);for(var H in Q){var A=Q[H];if(Array.isArray(A)){if(H in Vw.arrayKeywords)for(var O=0;O<A.length;O++)X$(b,w,$,A[O],W+"/"+H+"/"+O,G,W,H,Q,O)}else if(H in Vw.propsKeywords){if(A&&typeof A=="object")for(var q in A)X$(b,w,$,A[q],W+"/"+H+"/"+gU(q),G,W,H,Q,q)}else if(H in Vw.keywords||b.allKeys&&!(H in Vw.skipKeywords))X$(b,w,$,A,W+"/"+H,G,W,H,Q)}$(Q,W,G,X,Y,J,z)}}function gU(b){return b.replace(/~/g,"~0").replace(/\//g,"~1")}});var m1=I((dX)=>{Object.defineProperty(dX,"__esModule",{value:!0});dX.getSchemaRefs=dX.resolveUrl=dX.normalizeId=dX._getFullPath=dX.getFullPath=dX.inlineRef=void 0;var cU=n(),mU=Z4(),lU=nX(),nU=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function iU(b,w=!0){if(typeof b=="boolean")return!0;if(w===!0)return!I4(b);if(!w)return!1;return iX(b)<=w}dX.inlineRef=iU;var pU=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function I4(b){for(let w in b){if(pU.has(w))return!0;let $=b[w];if(Array.isArray($)&&$.some(I4))return!0;if(typeof $=="object"&&I4($))return!0}return!1}function iX(b){let w=0;for(let $ in b){if($==="$ref")return 1/0;if(w++,nU.has($))continue;if(typeof b[$]=="object")(0,cU.eachItem)(b[$],(Q)=>w+=iX(Q));if(w===1/0)return 1/0}return w}function pX(b,w="",$){if($!==!1)w=ew(w);let Q=b.parse(w);return oX(b,Q)}dX.getFullPath=pX;function oX(b,w){return b.serialize(w).split("#")[0]+"#"}dX._getFullPath=oX;var oU=/#\/?$/;function ew(b){return b?b.replace(oU,""):""}dX.normalizeId=ew;function dU(b,w,$){return $=ew($),b.resolve(w,$)}dX.resolveUrl=dU;var rU=/^[a-z_][-a-z0-9._]*$/i;function tU(b,w){if(typeof b=="boolean")return{};let{schemaId:$,uriResolver:Q}=this.opts,W=ew(b[$]||w),G={"":W},X=pX(Q,W,!1),Y={},J=new Set;return lU(b,{allKeys:!0},(A,O,q,B)=>{if(B===void 0)return;let K=X+O,Z=G[B];if(typeof A[$]=="string")Z=P.call(this,A[$]);C.call(this,A.$anchor),C.call(this,A.$dynamicAnchor),G[O]=Z;function P(S){let h=this.opts.uriResolver.resolve;if(S=ew(Z?h(Z,S):S),J.has(S))throw H(S);J.add(S);let R=this.refs[S];if(typeof R=="string")R=this.refs[R];if(typeof R=="object")z(A,R.schema,S);else if(S!==ew(K))if(S[0]==="#")z(A,Y[S],S),Y[S]=A;else this.refs[S]=K;return S}function C(S){if(typeof S=="string"){if(!rU.test(S))throw Error(`invalid anchor "${S}"`);P.call(this,`#${S}`)}}}),Y;function z(A,O,q){if(O!==void 0&&!mU(A,O))throw H(q)}function H(A){return Error(`reference "${A}" resolves to more than one schema`)}}dX.getSchemaRefs=tU});var i1=I((HY)=>{Object.defineProperty(HY,"__esModule",{value:!0});HY.getData=HY.KeywordCxt=HY.validateFunctionCode=void 0;var bY=OX(),tX=c1(),j4=U4(),Y$=c1(),$L=TX(),n1=yX(),V4=cX(),E=u(),v=Qw(),QL=m1(),Ww=n(),l1=g1();function WL(b){if(QY(b)){if(WY(b),$Y(b)){YL(b);return}}wY(b,()=>(0,bY.topBoolOrEmptySchema)(b))}HY.validateFunctionCode=WL;function wY({gen:b,validateName:w,schema:$,schemaEnv:Q,opts:W},G){if(W.code.es5)b.func(w,E._`${v.default.data}, ${v.default.valCxt}`,Q.$async,()=>{b.code(E._`"use strict"; ${eX($,W)}`),XL(b,W),b.code(G)});else b.func(w,E._`${v.default.data}, ${GL(W)}`,Q.$async,()=>b.code(eX($,W)).code(G))}function GL(b){return E._`{${v.default.instancePath}="", ${v.default.parentData}, ${v.default.parentDataProperty}, ${v.default.rootData}=${v.default.data}${b.dynamicRef?E._`, ${v.default.dynamicAnchors}={}`:E.nil}}={}`}function XL(b,w){b.if(v.default.valCxt,()=>{if(b.var(v.default.instancePath,E._`${v.default.valCxt}.${v.default.instancePath}`),b.var(v.default.parentData,E._`${v.default.valCxt}.${v.default.parentData}`),b.var(v.default.parentDataProperty,E._`${v.default.valCxt}.${v.default.parentDataProperty}`),b.var(v.default.rootData,E._`${v.default.valCxt}.${v.default.rootData}`),w.dynamicRef)b.var(v.default.dynamicAnchors,E._`${v.default.valCxt}.${v.default.dynamicAnchors}`)},()=>{if(b.var(v.default.instancePath,E._`""`),b.var(v.default.parentData,E._`undefined`),b.var(v.default.parentDataProperty,E._`undefined`),b.var(v.default.rootData,v.default.data),w.dynamicRef)b.var(v.default.dynamicAnchors,E._`{}`)})}function YL(b){let{schema:w,opts:$,gen:Q}=b;wY(b,()=>{if($.$comment&&w.$comment)XY(b);if(DL(b),Q.let(v.default.vErrors,null),Q.let(v.default.errors,0),$.unevaluated)JL(b);GY(b),UL(b)});return}function JL(b){let{gen:w,validateName:$}=b;b.evaluated=w.const("evaluated",E._`${$}.evaluated`),w.if(E._`${b.evaluated}.dynamicProps`,()=>w.assign(E._`${b.evaluated}.props`,E._`undefined`)),w.if(E._`${b.evaluated}.dynamicItems`,()=>w.assign(E._`${b.evaluated}.items`,E._`undefined`))}function eX(b,w){let $=typeof b=="object"&&b[w.schemaId];return $&&(w.code.source||w.code.process)?E._`/*# sourceURL=${$} */`:E.nil}function zL(b,w){if(QY(b)){if(WY(b),$Y(b)){HL(b,w);return}}(0,bY.boolOrEmptySchema)(b,w)}function $Y({schema:b,self:w}){if(typeof b=="boolean")return!b;for(let $ in b)if(w.RULES.all[$])return!0;return!1}function QY(b){return typeof b.schema!="boolean"}function HL(b,w){let{schema:$,gen:Q,opts:W}=b;if(W.$comment&&$.$comment)XY(b);OL(b),qL(b);let G=Q.const("_errs",v.default.errors);GY(b,G),Q.var(w,E._`${G} === ${v.default.errors}`)}function WY(b){(0,Ww.checkUnknownRules)(b),AL(b)}function GY(b,w){if(b.opts.jtd)return sX(b,[],!1,w);let $=(0,tX.getSchemaTypes)(b.schema),Q=(0,tX.coerceAndCheckDataType)(b,$);sX(b,$,!Q,w)}function AL(b){let{schema:w,errSchemaPath:$,opts:Q,self:W}=b;if(w.$ref&&Q.ignoreKeywordsWithRef&&(0,Ww.schemaHasRulesButRef)(w,W.RULES))W.logger.warn(`$ref: keywords ignored in schema at path "${$}"`)}function DL(b){let{schema:w,opts:$}=b;if(w.default!==void 0&&$.useDefaults&&$.strictSchema)(0,Ww.checkStrictMode)(b,"default is ignored in the schema root")}function OL(b){let w=b.schema[b.opts.schemaId];if(w)b.baseId=(0,QL.resolveUrl)(b.opts.uriResolver,b.baseId,w)}function qL(b){if(b.schema.$async&&!b.schemaEnv.$async)throw Error("async schema in sync schema")}function XY({gen:b,schemaEnv:w,schema:$,errSchemaPath:Q,opts:W}){let G=$.$comment;if(W.$comment===!0)b.code(E._`${v.default.self}.logger.log(${G})`);else if(typeof W.$comment=="function"){let X=E.str`${Q}/$comment`,Y=b.scopeValue("root",{ref:w.root});b.code(E._`${v.default.self}.opts.$comment(${G}, ${X}, ${Y}.schema)`)}}function UL(b){let{gen:w,schemaEnv:$,validateName:Q,ValidationError:W,opts:G}=b;if($.$async)w.if(E._`${v.default.errors} === 0`,()=>w.return(v.default.data),()=>w.throw(E._`new ${W}(${v.default.vErrors})`));else{if(w.assign(E._`${Q}.errors`,v.default.vErrors),G.unevaluated)LL(b);w.return(E._`${v.default.errors} === 0`)}}function LL({gen:b,evaluated:w,props:$,items:Q}){if($ instanceof E.Name)b.assign(E._`${w}.props`,$);if(Q instanceof E.Name)b.assign(E._`${w}.items`,Q)}function sX(b,w,$,Q){let{gen:W,schema:G,data:X,allErrors:Y,opts:J,self:z}=b,{RULES:H}=z;if(G.$ref&&(J.ignoreKeywordsWithRef||!(0,Ww.schemaHasRulesButRef)(G,H))){W.block(()=>JY(b,"$ref",H.all.$ref.definition));return}if(!J.jtd)BL(b,w);W.block(()=>{for(let O of H.rules)A(O);A(H.post)});function A(O){if(!(0,j4.shouldUseGroup)(G,O))return;if(O.type){if(W.if((0,Y$.checkDataType)(O.type,X,J.strictNumbers)),aX(b,O),w.length===1&&w[0]===O.type&&$)W.else(),(0,Y$.reportTypeError)(b);W.endIf()}else aX(b,O);if(!Y)W.if(E._`${v.default.errors} === ${Q||0}`)}}function aX(b,w){let{gen:$,schema:Q,opts:{useDefaults:W}}=b;if(W)(0,$L.assignDefaults)(b,w.type);$.block(()=>{for(let G of w.rules)if((0,j4.shouldUseRule)(Q,G))JY(b,G.keyword,G.definition,w.type)})}function BL(b,w){if(b.schemaEnv.meta||!b.opts.strictTypes)return;if(KL(b,w),!b.opts.allowUnionTypes)FL(b,w);ML(b,b.dataTypes)}function KL(b,w){if(!w.length)return;if(!b.dataTypes.length){b.dataTypes=w;return}w.forEach(($)=>{if(!YY(b.dataTypes,$))N4(b,`type "${$}" not allowed by context "${b.dataTypes.join(",")}"`)}),ZL(b,w)}function FL(b,w){if(w.length>1&&!(w.length===2&&w.includes("null")))N4(b,"use allowUnionTypes to allow union type keyword")}function ML(b,w){let $=b.self.RULES.all;for(let Q in $){let W=$[Q];if(typeof W=="object"&&(0,j4.shouldUseRule)(b.schema,W)){let{type:G}=W.definition;if(G.length&&!G.some((X)=>PL(w,X)))N4(b,`missing type "${G.join(",")}" for keyword "${Q}"`)}}}function PL(b,w){return b.includes(w)||w==="number"&&b.includes("integer")}function YY(b,w){return b.includes(w)||w==="integer"&&b.includes("number")}function ZL(b,w){let $=[];for(let Q of b.dataTypes)if(YY(w,Q))$.push(Q);else if(w.includes("integer")&&Q==="number")$.push("integer");b.dataTypes=$}function N4(b,w){let $=b.schemaEnv.baseId+b.errSchemaPath;w+=` at "${$}" (strictTypes)`,(0,Ww.checkStrictMode)(b,w,b.opts.strictTypes)}class E4{constructor(b,w,$){if((0,n1.validateKeywordUsage)(b,w,$),this.gen=b.gen,this.allErrors=b.allErrors,this.keyword=$,this.data=b.data,this.schema=b.schema[$],this.$data=w.$data&&b.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Ww.schemaRefOrVal)(b,this.schema,$,this.$data),this.schemaType=w.schemaType,this.parentSchema=b.schema,this.params={},this.it=b,this.def=w,this.$data)this.schemaCode=b.gen.const("vSchema",zY(this.$data,b));else if(this.schemaCode=this.schemaValue,!(0,n1.validSchemaType)(this.schema,w.schemaType,w.allowUndefined))throw Error(`${$} value must be ${JSON.stringify(w.schemaType)}`);if("code"in w?w.trackErrors:w.errors!==!1)this.errsCount=b.gen.const("_errs",v.default.errors)}result(b,w,$){this.failResult((0,E.not)(b),w,$)}failResult(b,w,$){if(this.gen.if(b),$)$();else this.error();if(w){if(this.gen.else(),w(),this.allErrors)this.gen.endIf()}else if(this.allErrors)this.gen.endIf();else this.gen.else()}pass(b,w){this.failResult((0,E.not)(b),void 0,w)}fail(b){if(b===void 0){if(this.error(),!this.allErrors)this.gen.if(!1);return}if(this.gen.if(b),this.error(),this.allErrors)this.gen.endIf();else this.gen.else()}fail$data(b){if(!this.$data)return this.fail(b);let{schemaCode:w}=this;this.fail(E._`${w} !== undefined && (${(0,E.or)(this.invalid$data(),b)})`)}error(b,w,$){if(w){this.setParams(w),this._error(b,$),this.setParams({});return}this._error(b,$)}_error(b,w){(b?l1.reportExtraError:l1.reportError)(this,this.def.error,w)}$dataError(){(0,l1.reportError)(this,this.def.$dataError||l1.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error('add "trackErrors" to keyword definition');(0,l1.resetErrorsCount)(this.gen,this.errsCount)}ok(b){if(!this.allErrors)this.gen.if(b)}setParams(b,w){if(w)Object.assign(this.params,b);else this.params=b}block$data(b,w,$=E.nil){this.gen.block(()=>{this.check$data(b,$),w()})}check$data(b=E.nil,w=E.nil){if(!this.$data)return;let{gen:$,schemaCode:Q,schemaType:W,def:G}=this;if($.if((0,E.or)(E._`${Q} === undefined`,w)),b!==E.nil)$.assign(b,!0);if(W.length||G.validateSchema){if($.elseIf(this.invalid$data()),this.$dataError(),b!==E.nil)$.assign(b,!1)}$.else()}invalid$data(){let{gen:b,schemaCode:w,schemaType:$,def:Q,it:W}=this;return(0,E.or)(G(),X());function G(){if($.length){if(!(w instanceof E.Name))throw Error("ajv implementation error");let Y=Array.isArray($)?$:[$];return E._`${(0,Y$.checkDataTypes)(Y,w,W.opts.strictNumbers,Y$.DataType.Wrong)}`}return E.nil}function X(){if(Q.validateSchema){let Y=b.scopeValue("validate$data",{ref:Q.validateSchema});return E._`!${Y}(${w})`}return E.nil}}subschema(b,w){let $=(0,V4.getSubschema)(this.it,b);(0,V4.extendSubschemaData)($,this.it,b),(0,V4.extendSubschemaMode)($,b);let Q={...this.it,...$,items:void 0,props:void 0};return zL(Q,w),Q}mergeEvaluated(b,w){let{it:$,gen:Q}=this;if(!$.opts.unevaluated)return;if($.props!==!0&&b.props!==void 0)$.props=Ww.mergeEvaluated.props(Q,b.props,$.props,w);if($.items!==!0&&b.items!==void 0)$.items=Ww.mergeEvaluated.items(Q,b.items,$.items,w)}mergeValidEvaluated(b,w){let{it:$,gen:Q}=this;if($.opts.unevaluated&&($.props!==!0||$.items!==!0))return Q.if(w,()=>this.mergeEvaluated(b,E.Name)),!0}}HY.KeywordCxt=E4;function JY(b,w,$,Q){let W=new E4(b,$,w);if("code"in $)$.code(W,Q);else if(W.$data&&$.validate)(0,n1.funcKeywordCode)(W,$);else if("macro"in $)(0,n1.macroKeywordCode)(W,$);else if($.compile||$.validate)(0,n1.funcKeywordCode)(W,$)}var IL=/^\/(?:[^~]|~0|~1)*$/,VL=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function zY(b,{dataLevel:w,dataNames:$,dataPathArr:Q}){let W,G;if(b==="")return v.default.rootData;if(b[0]==="/"){if(!IL.test(b))throw Error(`Invalid JSON-pointer: ${b}`);W=b,G=v.default.rootData}else{let z=VL.exec(b);if(!z)throw Error(`Invalid JSON-pointer: ${b}`);let H=+z[1];if(W=z[2],W==="#"){if(H>=w)throw Error(J("property/index",H));return Q[w-H]}if(H>w)throw Error(J("data",H));if(G=$[w-H],!W)return G}let X=G,Y=W.split("/");for(let z of Y)if(z)G=E._`${G}${(0,E.getProperty)((0,Ww.unescapeJsonPointer)(z))}`,X=E._`${X} && ${G}`;return X;function J(z,H){return`Cannot access ${z} ${H} levels up, current level is ${w}`}}HY.getData=zY});var J$=I((OY)=>{Object.defineProperty(OY,"__esModule",{value:!0});class DY extends Error{constructor(b){super("validation failed");this.errors=b,this.ajv=this.validation=!0}}OY.default=DY});var p1=I((UY)=>{Object.defineProperty(UY,"__esModule",{value:!0});var T4=m1();class qY extends Error{constructor(b,w,$,Q){super(Q||`can't resolve reference ${$} from id ${w}`);this.missingRef=(0,T4.resolveUrl)(b,w,$),this.missingSchema=(0,T4.normalizeId)((0,T4.getFullPath)(b,this.missingRef))}}UY.default=qY});var H$=I((KY)=>{Object.defineProperty(KY,"__esModule",{value:!0});KY.resolveSchema=KY.getCompilingSchema=KY.resolveRef=KY.compileSchema=KY.SchemaEnv=void 0;var fb=u(),_L=J$(),xw=Qw(),gb=m1(),LY=n(),SL=i1();class o1{constructor(b){var w;this.refs={},this.dynamicAnchors={};let $;if(typeof b.schema=="object")$=b.schema;this.schema=b.schema,this.schemaId=b.schemaId,this.root=b.root||this,this.baseId=(w=b.baseId)!==null&&w!==void 0?w:(0,gb.normalizeId)($===null||$===void 0?void 0:$[b.schemaId||"$id"]),this.schemaPath=b.schemaPath,this.localRefs=b.localRefs,this.meta=b.meta,this.$async=$===null||$===void 0?void 0:$.$async,this.refs={}}}KY.SchemaEnv=o1;function S4(b){let w=BY.call(this,b);if(w)return w;let $=(0,gb.getFullPath)(this.opts.uriResolver,b.root.baseId),{es5:Q,lines:W}=this.opts.code,{ownProperties:G}=this.opts,X=new fb.CodeGen(this.scope,{es5:Q,lines:W,ownProperties:G}),Y;if(b.$async)Y=X.scopeValue("Error",{ref:_L.default,code:fb._`require("ajv/dist/runtime/validation_error").default`});let J=X.scopeName("validate");b.validateName=J;let z={gen:X,allErrors:this.opts.allErrors,data:xw.default.data,parentData:xw.default.parentData,parentDataProperty:xw.default.parentDataProperty,dataNames:[xw.default.data],dataPathArr:[fb.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:X.scopeValue("schema",this.opts.code.source===!0?{ref:b.schema,code:(0,fb.stringify)(b.schema)}:{ref:b.schema}),validateName:J,ValidationError:Y,schema:b.schema,schemaEnv:b,rootId:$,baseId:b.baseId||$,schemaPath:fb.nil,errSchemaPath:b.schemaPath||(this.opts.jtd?"":"#"),errorPath:fb._`""`,opts:this.opts,self:this},H;try{this._compilations.add(b),(0,SL.validateFunctionCode)(z),X.optimize(this.opts.code.optimize);let A=X.toString();if(H=`${X.scopeRefs(xw.default.scope)}return ${A}`,this.opts.code.process)H=this.opts.code.process(H,b);let q=Function(`${xw.default.self}`,`${xw.default.scope}`,H)(this,this.scope.get());if(this.scope.value(J,{ref:q}),q.errors=null,q.schema=b.schema,q.schemaEnv=b,b.$async)q.$async=!0;if(this.opts.code.source===!0)q.source={validateName:J,validateCode:A,scopeValues:X._values};if(this.opts.unevaluated){let{props:B,items:K}=z;if(q.evaluated={props:B instanceof fb.Name?void 0:B,items:K instanceof fb.Name?void 0:K,dynamicProps:B instanceof fb.Name,dynamicItems:K instanceof fb.Name},q.source)q.source.evaluated=(0,fb.stringify)(q.evaluated)}return b.validate=q,b}catch(A){if(delete b.validate,delete b.validateName,H)this.logger.error("Error compiling schema, function code:",H);throw A}finally{this._compilations.delete(b)}}KY.compileSchema=S4;function RL(b,w,$){var Q;$=(0,gb.resolveUrl)(this.opts.uriResolver,w,$);let W=b.refs[$];if(W)return W;let G=kL.call(this,b,$);if(G===void 0){let X=(Q=b.localRefs)===null||Q===void 0?void 0:Q[$],{schemaId:Y}=this.opts;if(X)G=new o1({schema:X,schemaId:Y,root:b,baseId:w})}if(G===void 0)return;return b.refs[$]=CL.call(this,G)}KY.resolveRef=RL;function CL(b){if((0,gb.inlineRef)(b.schema,this.opts.inlineRefs))return b.schema;return b.validate?b:S4.call(this,b)}function BY(b){for(let w of this._compilations)if(vL(w,b))return w}KY.getCompilingSchema=BY;function vL(b,w){return b.schema===w.schema&&b.root===w.root&&b.baseId===w.baseId}function kL(b,w){let $;while(typeof($=this.refs[w])=="string")w=$;return $||this.schemas[w]||z$.call(this,b,w)}function z$(b,w){let $=this.opts.uriResolver.parse(w),Q=(0,gb._getFullPath)(this.opts.uriResolver,$),W=(0,gb.getFullPath)(this.opts.uriResolver,b.baseId,void 0);if(Object.keys(b.schema).length>0&&Q===W)return _4.call(this,$,b);let G=(0,gb.normalizeId)(Q),X=this.refs[G]||this.schemas[G];if(typeof X=="string"){let Y=z$.call(this,b,X);if(typeof(Y===null||Y===void 0?void 0:Y.schema)!=="object")return;return _4.call(this,$,Y)}if(typeof(X===null||X===void 0?void 0:X.schema)!=="object")return;if(!X.validate)S4.call(this,X);if(G===(0,gb.normalizeId)(w)){let{schema:Y}=X,{schemaId:J}=this.opts,z=Y[J];if(z)W=(0,gb.resolveUrl)(this.opts.uriResolver,W,z);return new o1({schema:Y,schemaId:J,root:b,baseId:W})}return _4.call(this,$,X)}KY.resolveSchema=z$;var xL=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function _4(b,{baseId:w,schema:$,root:Q}){var W;if(((W=b.fragment)===null||W===void 0?void 0:W[0])!=="/")return;for(let Y of b.fragment.slice(1).split("/")){if(typeof $==="boolean")return;let J=$[(0,LY.unescapeFragment)(Y)];if(J===void 0)return;$=J;let z=typeof $==="object"&&$[this.opts.schemaId];if(!xL.has(Y)&&z)w=(0,gb.resolveUrl)(this.opts.uriResolver,w,z)}let G;if(typeof $!="boolean"&&$.$ref&&!(0,LY.schemaHasRulesButRef)($,this.RULES)){let Y=(0,gb.resolveUrl)(this.opts.uriResolver,w,$.$ref);G=z$.call(this,Q,Y)}let{schemaId:X}=this.opts;if(G=G||new o1({schema:$,schemaId:X,root:Q,baseId:w}),G.schema!==G.root.schema)return G;return}});var MY=I((VE,gL)=>{gL.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var C4=I((jE,VY)=>{var cL=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),ZY=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 R4(b){let w="",$=0,Q=0;for(Q=0;Q<b.length;Q++){if($=b[Q].charCodeAt(0),$===48)continue;if(!($>=48&&$<=57||$>=65&&$<=70||$>=97&&$<=102))return"";w+=b[Q];break}for(Q+=1;Q<b.length;Q++){if($=b[Q].charCodeAt(0),!($>=48&&$<=57||$>=65&&$<=70||$>=97&&$<=102))return"";w+=b[Q]}return w}var mL=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function PY(b){return b.length=0,!0}function lL(b,w,$){if(b.length){let Q=R4(b);if(Q!=="")w.push(Q);else return $.error=!0,!1;b.length=0}return!0}function nL(b){let w=0,$={error:!1,address:"",zone:""},Q=[],W=[],G=!1,X=!1,Y=lL;for(let J=0;J<b.length;J++){let z=b[J];if(z==="["||z==="]")continue;if(z===":"){if(G===!0)X=!0;if(!Y(W,Q,$))break;if(++w>7){$.error=!0;break}if(J>0&&b[J-1]===":")G=!0;Q.push(":");continue}else if(z==="%"){if(!Y(W,Q,$))break;Y=PY}else{W.push(z);continue}}if(W.length)if(Y===PY)$.zone=W.join("");else if(X)Q.push(W.join(""));else Q.push(R4(W));return $.address=Q.join(""),$}function IY(b){if(iL(b,":")<2)return{host:b,isIPV6:!1};let w=nL(b);if(!w.error){let{address:$,address:Q}=w;if(w.zone)$+="%"+w.zone,Q+="%25"+w.zone;return{host:$,isIPV6:!0,escapedHost:Q}}else return{host:b,isIPV6:!1}}function iL(b,w){let $=0;for(let Q=0;Q<b.length;Q++)if(b[Q]===w)$++;return $}function pL(b){let w=b,$=[],Q=-1,W=0;while(W=w.length){if(W===1)if(w===".")break;else if(w==="/"){$.push("/");break}else{$.push(w);break}else if(W===2){if(w[0]==="."){if(w[1]===".")break;else if(w[1]==="/"){w=w.slice(2);continue}}else if(w[0]==="/"){if(w[1]==="."||w[1]==="/"){$.push("/");break}}}else if(W===3){if(w==="/.."){if($.length!==0)$.pop();$.push("/");break}}if(w[0]==="."){if(w[1]==="."){if(w[2]==="/"){w=w.slice(3);continue}}else if(w[1]==="/"){w=w.slice(2);continue}}else if(w[0]==="/"){if(w[1]==="."){if(w[2]==="/"){w=w.slice(2);continue}else if(w[2]==="."){if(w[3]==="/"){if(w=w.slice(3),$.length!==0)$.pop();continue}}}}if((Q=w.indexOf("/",1))===-1){$.push(w);break}else $.push(w.slice(0,Q)),w=w.slice(Q)}return $.join("")}function oL(b,w){let $=w!==!0?escape:unescape;if(b.scheme!==void 0)b.scheme=$(b.scheme);if(b.userinfo!==void 0)b.userinfo=$(b.userinfo);if(b.host!==void 0)b.host=$(b.host);if(b.path!==void 0)b.path=$(b.path);if(b.query!==void 0)b.query=$(b.query);if(b.fragment!==void 0)b.fragment=$(b.fragment);return b}function dL(b){let w=[];if(b.userinfo!==void 0)w.push(b.userinfo),w.push("@");if(b.host!==void 0){let $=unescape(b.host);if(!ZY($)){let Q=IY($);if(Q.isIPV6===!0)$=`[${Q.escapedHost}]`;else $=b.host}w.push($)}if(typeof b.port==="number"||typeof b.port==="string")w.push(":"),w.push(String(b.port));return w.length?w.join(""):void 0}VY.exports={nonSimpleDomain:mL,recomposeAuthority:dL,normalizeComponentEncoding:oL,removeDotSegments:pL,isIPv4:ZY,isUUID:cL,normalizeIPv6:IY,stringArrayToHexStripped:R4}});var _Y=I((NE,TY)=>{var{isUUID:rL}=C4(),tL=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,eL=["http","https","ws","wss","urn","urn:uuid"];function sL(b){return eL.indexOf(b)!==-1}function v4(b){if(b.secure===!0)return!0;else if(b.secure===!1)return!1;else if(b.scheme)return b.scheme.length===3&&(b.scheme[0]==="w"||b.scheme[0]==="W")&&(b.scheme[1]==="s"||b.scheme[1]==="S")&&(b.scheme[2]==="s"||b.scheme[2]==="S");else return!1}function jY(b){if(!b.host)b.error=b.error||"HTTP URIs must have a host.";return b}function NY(b){let w=String(b.scheme).toLowerCase()==="https";if(b.port===(w?443:80)||b.port==="")b.port=void 0;if(!b.path)b.path="/";return b}function aL(b){return b.secure=v4(b),b.resourceName=(b.path||"/")+(b.query?"?"+b.query:""),b.path=void 0,b.query=void 0,b}function b3(b){if(b.port===(v4(b)?443:80)||b.port==="")b.port=void 0;if(typeof b.secure==="boolean")b.scheme=b.secure?"wss":"ws",b.secure=void 0;if(b.resourceName){let[w,$]=b.resourceName.split("?");b.path=w&&w!=="/"?w:void 0,b.query=$,b.resourceName=void 0}return b.fragment=void 0,b}function w3(b,w){if(!b.path)return b.error="URN can not be parsed",b;let $=b.path.match(tL);if($){let Q=w.scheme||b.scheme||"urn";b.nid=$[1].toLowerCase(),b.nss=$[2];let W=`${Q}:${w.nid||b.nid}`,G=k4(W);if(b.path=void 0,G)b=G.parse(b,w)}else b.error=b.error||"URN can not be parsed.";return b}function $3(b,w){if(b.nid===void 0)throw Error("URN without nid cannot be serialized");let $=w.scheme||b.scheme||"urn",Q=b.nid.toLowerCase(),W=`${$}:${w.nid||Q}`,G=k4(W);if(G)b=G.serialize(b,w);let X=b,Y=b.nss;return X.path=`${Q||w.nid}:${Y}`,w.skipEscape=!0,X}function Q3(b,w){let $=b;if($.uuid=$.nss,$.nss=void 0,!w.tolerant&&(!$.uuid||!rL($.uuid)))$.error=$.error||"UUID is not valid.";return $}function W3(b){let w=b;return w.nss=(b.uuid||"").toLowerCase(),w}var EY={scheme:"http",domainHost:!0,parse:jY,serialize:NY},G3={scheme:"https",domainHost:EY.domainHost,parse:jY,serialize:NY},A$={scheme:"ws",domainHost:!0,parse:aL,serialize:b3},X3={scheme:"wss",domainHost:A$.domainHost,parse:A$.parse,serialize:A$.serialize},Y3={scheme:"urn",parse:w3,serialize:$3,skipNormalize:!0},J3={scheme:"urn:uuid",parse:Q3,serialize:W3,skipNormalize:!0},D$={http:EY,https:G3,ws:A$,wss:X3,urn:Y3,"urn:uuid":J3};Object.setPrototypeOf(D$,null);function k4(b){return b&&(D$[b]||D$[b.toLowerCase()])||void 0}TY.exports={wsIsSecure:v4,SCHEMES:D$,isValidSchemeName:sL,getSchemeHandler:k4}});var CY=I((EE,q$)=>{var{normalizeIPv6:z3,removeDotSegments:d1,recomposeAuthority:H3,normalizeComponentEncoding:O$,isIPv4:A3,nonSimpleDomain:D3}=C4(),{SCHEMES:O3,getSchemeHandler:SY}=_Y();function q3(b,w){if(typeof b==="string")b=ob(Gw(b,w),w);else if(typeof b==="object")b=Gw(ob(b,w),w);return b}function U3(b,w,$){let Q=$?Object.assign({scheme:"null"},$):{scheme:"null"},W=RY(Gw(b,Q),Gw(w,Q),Q,!0);return Q.skipEscape=!0,ob(W,Q)}function RY(b,w,$,Q){let W={};if(!Q)b=Gw(ob(b,$),$),w=Gw(ob(w,$),$);if($=$||{},!$.tolerant&&w.scheme)W.scheme=w.scheme,W.userinfo=w.userinfo,W.host=w.host,W.port=w.port,W.path=d1(w.path||""),W.query=w.query;else{if(w.userinfo!==void 0||w.host!==void 0||w.port!==void 0)W.userinfo=w.userinfo,W.host=w.host,W.port=w.port,W.path=d1(w.path||""),W.query=w.query;else{if(!w.path)if(W.path=b.path,w.query!==void 0)W.query=w.query;else W.query=b.query;else{if(w.path[0]==="/")W.path=d1(w.path);else{if((b.userinfo!==void 0||b.host!==void 0||b.port!==void 0)&&!b.path)W.path="/"+w.path;else if(!b.path)W.path=w.path;else W.path=b.path.slice(0,b.path.lastIndexOf("/")+1)+w.path;W.path=d1(W.path)}W.query=w.query}W.userinfo=b.userinfo,W.host=b.host,W.port=b.port}W.scheme=b.scheme}return W.fragment=w.fragment,W}function L3(b,w,$){if(typeof b==="string")b=unescape(b),b=ob(O$(Gw(b,$),!0),{...$,skipEscape:!0});else if(typeof b==="object")b=ob(O$(b,!0),{...$,skipEscape:!0});if(typeof w==="string")w=unescape(w),w=ob(O$(Gw(w,$),!0),{...$,skipEscape:!0});else if(typeof w==="object")w=ob(O$(w,!0),{...$,skipEscape:!0});return b.toLowerCase()===w.toLowerCase()}function ob(b,w){let $={host:b.host,scheme:b.scheme,userinfo:b.userinfo,port:b.port,path:b.path,query:b.query,nid:b.nid,nss:b.nss,uuid:b.uuid,fragment:b.fragment,reference:b.reference,resourceName:b.resourceName,secure:b.secure,error:""},Q=Object.assign({},w),W=[],G=SY(Q.scheme||$.scheme);if(G&&G.serialize)G.serialize($,Q);if($.path!==void 0)if(!Q.skipEscape){if($.path=escape($.path),$.scheme!==void 0)$.path=$.path.split("%3A").join(":")}else $.path=unescape($.path);if(Q.reference!=="suffix"&&$.scheme)W.push($.scheme,":");let X=H3($);if(X!==void 0){if(Q.reference!=="suffix")W.push("//");if(W.push(X),$.path&&$.path[0]!=="/")W.push("/")}if($.path!==void 0){let Y=$.path;if(!Q.absolutePath&&(!G||!G.absolutePath))Y=d1(Y);if(X===void 0&&Y[0]==="/"&&Y[1]==="/")Y="/%2F"+Y.slice(2);W.push(Y)}if($.query!==void 0)W.push("?",$.query);if($.fragment!==void 0)W.push("#",$.fragment);return W.join("")}var B3=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function Gw(b,w){let $=Object.assign({},w),Q={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},W=!1;if($.reference==="suffix")if($.scheme)b=$.scheme+":"+b;else b="//"+b;let G=b.match(B3);if(G){if(Q.scheme=G[1],Q.userinfo=G[3],Q.host=G[4],Q.port=parseInt(G[5],10),Q.path=G[6]||"",Q.query=G[7],Q.fragment=G[8],isNaN(Q.port))Q.port=G[5];if(Q.host)if(A3(Q.host)===!1){let J=z3(Q.host);Q.host=J.host.toLowerCase(),W=J.isIPV6}else W=!0;if(Q.scheme===void 0&&Q.userinfo===void 0&&Q.host===void 0&&Q.port===void 0&&Q.query===void 0&&!Q.path)Q.reference="same-document";else if(Q.scheme===void 0)Q.reference="relative";else if(Q.fragment===void 0)Q.reference="absolute";else Q.reference="uri";if($.reference&&$.reference!=="suffix"&&$.reference!==Q.reference)Q.error=Q.error||"URI is not a "+$.reference+" reference.";let X=SY($.scheme||Q.scheme);if(!$.unicodeSupport&&(!X||!X.unicodeSupport)){if(Q.host&&($.domainHost||X&&X.domainHost)&&W===!1&&D3(Q.host))try{Q.host=URL.domainToASCII(Q.host.toLowerCase())}catch(Y){Q.error=Q.error||"Host's domain name can not be converted to ASCII: "+Y}}if(!X||X&&!X.skipNormalize){if(b.indexOf("%")!==-1){if(Q.scheme!==void 0)Q.scheme=unescape(Q.scheme);if(Q.host!==void 0)Q.host=unescape(Q.host)}if(Q.path)Q.path=escape(unescape(Q.path));if(Q.fragment)Q.fragment=encodeURI(decodeURIComponent(Q.fragment))}if(X&&X.parse)X.parse(Q,$)}else Q.error=Q.error||"URI can not be parsed.";return Q}var x4={SCHEMES:O3,normalize:q3,resolve:U3,resolveComponent:RY,equal:L3,serialize:ob,parse:Gw};q$.exports=x4;q$.exports.default=x4;q$.exports.fastUri=x4});var xY=I((kY)=>{Object.defineProperty(kY,"__esModule",{value:!0});var vY=CY();vY.code='require("ajv/dist/runtime/uri").default';kY.default=vY});var lY=I((Xw)=>{Object.defineProperty(Xw,"__esModule",{value:!0});Xw.CodeGen=Xw.Name=Xw.nil=Xw.stringify=Xw.str=Xw._=Xw.KeywordCxt=void 0;var F3=i1();Object.defineProperty(Xw,"KeywordCxt",{enumerable:!0,get:function(){return F3.KeywordCxt}});var sw=u();Object.defineProperty(Xw,"_",{enumerable:!0,get:function(){return sw._}});Object.defineProperty(Xw,"str",{enumerable:!0,get:function(){return sw.str}});Object.defineProperty(Xw,"stringify",{enumerable:!0,get:function(){return sw.stringify}});Object.defineProperty(Xw,"nil",{enumerable:!0,get:function(){return sw.nil}});Object.defineProperty(Xw,"Name",{enumerable:!0,get:function(){return sw.Name}});Object.defineProperty(Xw,"CodeGen",{enumerable:!0,get:function(){return sw.CodeGen}});var M3=J$(),gY=p1(),P3=q4(),r1=H$(),Z3=u(),t1=m1(),U$=c1(),y4=n(),uY=MY(),I3=xY(),cY=(b,w)=>new RegExp(b,w);cY.code="new RegExp";var V3=["removeAdditional","useDefaults","coerceTypes"],j3=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),N3={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."},E3={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},yY=200;function T3(b){var w,$,Q,W,G,X,Y,J,z,H,A,O,q,B,K,Z,P,C,S,h,R,ib,eb,n$,i$;let H1=b.strict,p$=(w=b.code)===null||w===void 0?void 0:w.optimize,TQ=p$===!0||p$===void 0?1:p$||0,_Q=(Q=($=b.code)===null||$===void 0?void 0:$.regExp)!==null&&Q!==void 0?Q:cY,VA=(W=b.uriResolver)!==null&&W!==void 0?W:I3.default;return{strictSchema:(X=(G=b.strictSchema)!==null&&G!==void 0?G:H1)!==null&&X!==void 0?X:!0,strictNumbers:(J=(Y=b.strictNumbers)!==null&&Y!==void 0?Y:H1)!==null&&J!==void 0?J:!0,strictTypes:(H=(z=b.strictTypes)!==null&&z!==void 0?z:H1)!==null&&H!==void 0?H:"log",strictTuples:(O=(A=b.strictTuples)!==null&&A!==void 0?A:H1)!==null&&O!==void 0?O:"log",strictRequired:(B=(q=b.strictRequired)!==null&&q!==void 0?q:H1)!==null&&B!==void 0?B:!1,code:b.code?{...b.code,optimize:TQ,regExp:_Q}:{optimize:TQ,regExp:_Q},loopRequired:(K=b.loopRequired)!==null&&K!==void 0?K:yY,loopEnum:(Z=b.loopEnum)!==null&&Z!==void 0?Z:yY,meta:(P=b.meta)!==null&&P!==void 0?P:!0,messages:(C=b.messages)!==null&&C!==void 0?C:!0,inlineRefs:(S=b.inlineRefs)!==null&&S!==void 0?S:!0,schemaId:(h=b.schemaId)!==null&&h!==void 0?h:"$id",addUsedSchema:(R=b.addUsedSchema)!==null&&R!==void 0?R:!0,validateSchema:(ib=b.validateSchema)!==null&&ib!==void 0?ib:!0,validateFormats:(eb=b.validateFormats)!==null&&eb!==void 0?eb:!0,unicodeRegExp:(n$=b.unicodeRegExp)!==null&&n$!==void 0?n$:!0,int32range:(i$=b.int32range)!==null&&i$!==void 0?i$:!0,uriResolver:VA}}class L${constructor(b={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,b=this.opts={...b,...T3(b)};let{es5:w,lines:$}=this.opts.code;this.scope=new Z3.ValueScope({scope:{},prefixes:j3,es5:w,lines:$}),this.logger=k3(b.logger);let Q=b.validateFormats;if(b.validateFormats=!1,this.RULES=(0,P3.getRules)(),hY.call(this,N3,b,"NOT SUPPORTED"),hY.call(this,E3,b,"DEPRECATED","warn"),this._metaOpts=C3.call(this),b.formats)S3.call(this);if(this._addVocabularies(),this._addDefaultMetaSchema(),b.keywords)R3.call(this,b.keywords);if(typeof b.meta=="object")this.addMetaSchema(b.meta);_3.call(this),b.validateFormats=Q}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:b,meta:w,schemaId:$}=this.opts,Q=uY;if($==="id")Q={...uY},Q.id=Q.$id,delete Q.$id;if(w&&b)this.addMetaSchema(Q,Q[$],!1)}defaultMeta(){let{meta:b,schemaId:w}=this.opts;return this.opts.defaultMeta=typeof b=="object"?b[w]||b:void 0}validate(b,w){let $;if(typeof b=="string"){if($=this.getSchema(b),!$)throw Error(`no schema with key or ref "${b}"`)}else $=this.compile(b);let Q=$(w);if(!("$async"in $))this.errors=$.errors;return Q}compile(b,w){let $=this._addSchema(b,w);return $.validate||this._compileSchemaEnv($)}compileAsync(b,w){if(typeof this.opts.loadSchema!="function")throw Error("options.loadSchema should be a function");let{loadSchema:$}=this.opts;return Q.call(this,b,w);async function Q(z,H){await W.call(this,z.$schema);let A=this._addSchema(z,H);return A.validate||G.call(this,A)}async function W(z){if(z&&!this.getSchema(z))await Q.call(this,{$ref:z},!0)}async function G(z){try{return this._compileSchemaEnv(z)}catch(H){if(!(H instanceof gY.default))throw H;return X.call(this,H),await Y.call(this,H.missingSchema),G.call(this,z)}}function X({missingSchema:z,missingRef:H}){if(this.refs[z])throw Error(`AnySchema ${z} is loaded but ${H} cannot be resolved`)}async function Y(z){let H=await J.call(this,z);if(!this.refs[z])await W.call(this,H.$schema);if(!this.refs[z])this.addSchema(H,z,w)}async function J(z){let H=this._loading[z];if(H)return H;try{return await(this._loading[z]=$(z))}finally{delete this._loading[z]}}}addSchema(b,w,$,Q=this.opts.validateSchema){if(Array.isArray(b)){for(let G of b)this.addSchema(G,void 0,$,Q);return this}let W;if(typeof b==="object"){let{schemaId:G}=this.opts;if(W=b[G],W!==void 0&&typeof W!="string")throw Error(`schema ${G} must be string`)}return w=(0,t1.normalizeId)(w||W),this._checkUnique(w),this.schemas[w]=this._addSchema(b,$,w,Q,!0),this}addMetaSchema(b,w,$=this.opts.validateSchema){return this.addSchema(b,w,!0,$),this}validateSchema(b,w){if(typeof b=="boolean")return!0;let $;if($=b.$schema,$!==void 0&&typeof $!="string")throw Error("$schema must be a string");if($=$||this.opts.defaultMeta||this.defaultMeta(),!$)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let Q=this.validate($,b);if(!Q&&w){let W="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(W);else throw Error(W)}return Q}getSchema(b){let w;while(typeof(w=fY.call(this,b))=="string")b=w;if(w===void 0){let{schemaId:$}=this.opts,Q=new r1.SchemaEnv({schema:{},schemaId:$});if(w=r1.resolveSchema.call(this,Q,b),!w)return;this.refs[b]=w}return w.validate||this._compileSchemaEnv(w)}removeSchema(b){if(b instanceof RegExp)return this._removeAllSchemas(this.schemas,b),this._removeAllSchemas(this.refs,b),this;switch(typeof b){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let w=fY.call(this,b);if(typeof w=="object")this._cache.delete(w.schema);return delete this.schemas[b],delete this.refs[b],this}case"object":{let w=b;this._cache.delete(w);let $=b[this.opts.schemaId];if($)$=(0,t1.normalizeId)($),delete this.schemas[$],delete this.refs[$];return this}default:throw Error("ajv.removeSchema: invalid parameter")}}addVocabulary(b){for(let w of b)this.addKeyword(w);return this}addKeyword(b,w){let $;if(typeof b=="string"){if($=b,typeof w=="object")this.logger.warn("these parameters are deprecated, see docs for addKeyword"),w.keyword=$}else if(typeof b=="object"&&w===void 0){if(w=b,$=w.keyword,Array.isArray($)&&!$.length)throw Error("addKeywords: keyword must be string or non-empty array")}else throw Error("invalid addKeywords parameters");if(u3.call(this,$,w),!w)return(0,y4.eachItem)($,(W)=>u4.call(this,W)),this;h3.call(this,w);let Q={...w,type:(0,U$.getJSONTypes)(w.type),schemaType:(0,U$.getJSONTypes)(w.schemaType)};return(0,y4.eachItem)($,Q.type.length===0?(W)=>u4.call(this,W,Q):(W)=>Q.type.forEach((G)=>u4.call(this,W,Q,G))),this}getKeyword(b){let w=this.RULES.all[b];return typeof w=="object"?w.definition:!!w}removeKeyword(b){let{RULES:w}=this;delete w.keywords[b],delete w.all[b];for(let $ of w.rules){let Q=$.rules.findIndex((W)=>W.keyword===b);if(Q>=0)$.rules.splice(Q,1)}return this}addFormat(b,w){if(typeof w=="string")w=new RegExp(w);return this.formats[b]=w,this}errorsText(b=this.errors,{separator:w=", ",dataVar:$="data"}={}){if(!b||b.length===0)return"No errors";return b.map((Q)=>`${$}${Q.instancePath} ${Q.message}`).reduce((Q,W)=>Q+w+W)}$dataMetaSchema(b,w){let $=this.RULES.all;b=JSON.parse(JSON.stringify(b));for(let Q of w){let W=Q.split("/").slice(1),G=b;for(let X of W)G=G[X];for(let X in $){let Y=$[X];if(typeof Y!="object")continue;let{$data:J}=Y.definition,z=G[X];if(J&&z)G[X]=mY(z)}}return b}_removeAllSchemas(b,w){for(let $ in b){let Q=b[$];if(!w||w.test($)){if(typeof Q=="string")delete b[$];else if(Q&&!Q.meta)this._cache.delete(Q.schema),delete b[$]}}}_addSchema(b,w,$,Q=this.opts.validateSchema,W=this.opts.addUsedSchema){let G,{schemaId:X}=this.opts;if(typeof b=="object")G=b[X];else if(this.opts.jtd)throw Error("schema must be object");else if(typeof b!="boolean")throw Error("schema must be object or boolean");let Y=this._cache.get(b);if(Y!==void 0)return Y;$=(0,t1.normalizeId)(G||$);let J=t1.getSchemaRefs.call(this,b,$);if(Y=new r1.SchemaEnv({schema:b,schemaId:X,meta:w,baseId:$,localRefs:J}),this._cache.set(Y.schema,Y),W&&!$.startsWith("#")){if($)this._checkUnique($);this.refs[$]=Y}if(Q)this.validateSchema(b,!0);return Y}_checkUnique(b){if(this.schemas[b]||this.refs[b])throw Error(`schema with key or id "${b}" already exists`)}_compileSchemaEnv(b){if(b.meta)this._compileMetaSchema(b);else r1.compileSchema.call(this,b);if(!b.validate)throw Error("ajv implementation error");return b.validate}_compileMetaSchema(b){let w=this.opts;this.opts=this._metaOpts;try{r1.compileSchema.call(this,b)}finally{this.opts=w}}}L$.ValidationError=M3.default;L$.MissingRefError=gY.default;Xw.default=L$;function hY(b,w,$,Q="error"){for(let W in b){let G=W;if(G in w)this.logger[Q](`${$}: option ${W}. ${b[G]}`)}}function fY(b){return b=(0,t1.normalizeId)(b),this.schemas[b]||this.refs[b]}function _3(){let b=this.opts.schemas;if(!b)return;if(Array.isArray(b))this.addSchema(b);else for(let w in b)this.addSchema(b[w],w)}function S3(){for(let b in this.opts.formats){let w=this.opts.formats[b];if(w)this.addFormat(b,w)}}function R3(b){if(Array.isArray(b)){this.addVocabulary(b);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let w in b){let $=b[w];if(!$.keyword)$.keyword=w;this.addKeyword($)}}function C3(){let b={...this.opts};for(let w of V3)delete b[w];return b}var v3={log(){},warn(){},error(){}};function k3(b){if(b===!1)return v3;if(b===void 0)return console;if(b.log&&b.warn&&b.error)return b;throw Error("logger must implement log, warn and error methods")}var x3=/^[a-z_$][a-z0-9_$:-]*$/i;function u3(b,w){let{RULES:$}=this;if((0,y4.eachItem)(b,(Q)=>{if($.keywords[Q])throw Error(`Keyword ${Q} is already defined`);if(!x3.test(Q))throw Error(`Keyword ${Q} has invalid name`)}),!w)return;if(w.$data&&!(("code"in w)||("validate"in w)))throw Error('$data keyword must have "code" or "validate" function')}function u4(b,w,$){var Q;let W=w===null||w===void 0?void 0:w.post;if($&&W)throw Error('keyword with "post" flag cannot have "type"');let{RULES:G}=this,X=W?G.post:G.rules.find(({type:J})=>J===$);if(!X)X={type:$,rules:[]},G.rules.push(X);if(G.keywords[b]=!0,!w)return;let Y={keyword:b,definition:{...w,type:(0,U$.getJSONTypes)(w.type),schemaType:(0,U$.getJSONTypes)(w.schemaType)}};if(w.before)y3.call(this,X,Y,w.before);else X.rules.push(Y);G.all[b]=Y,(Q=w.implements)===null||Q===void 0||Q.forEach((J)=>this.addKeyword(J))}function y3(b,w,$){let Q=b.rules.findIndex((W)=>W.keyword===$);if(Q>=0)b.rules.splice(Q,0,w);else b.rules.push(w),this.logger.warn(`rule ${$} is not defined`)}function h3(b){let{metaSchema:w}=b;if(w===void 0)return;if(b.$data&&this.opts.$data)w=mY(w);b.validateSchema=this.compile(w,!0)}var f3={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function mY(b){return{anyOf:[b,f3]}}});var iY=I((nY)=>{Object.defineProperty(nY,"__esModule",{value:!0});var m3={keyword:"id",code(){throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};nY.default=m3});var eY=I((rY)=>{Object.defineProperty(rY,"__esModule",{value:!0});rY.callRef=rY.getValidate=void 0;var n3=p1(),pY=Cb(),Zb=u(),aw=Qw(),oY=H$(),B$=n(),i3={keyword:"$ref",schemaType:"string",code(b){let{gen:w,schema:$,it:Q}=b,{baseId:W,schemaEnv:G,validateName:X,opts:Y,self:J}=Q,{root:z}=G;if(($==="#"||$==="#/")&&W===z.baseId)return A();let H=oY.resolveRef.call(J,z,W,$);if(H===void 0)throw new n3.default(Q.opts.uriResolver,W,$);if(H instanceof oY.SchemaEnv)return O(H);return q(H);function A(){if(G===z)return K$(b,X,G,G.$async);let B=w.scopeValue("root",{ref:z});return K$(b,Zb._`${B}.validate`,z,z.$async)}function O(B){let K=dY(b,B);K$(b,K,B,B.$async)}function q(B){let K=w.scopeValue("schema",Y.code.source===!0?{ref:B,code:(0,Zb.stringify)(B)}:{ref:B}),Z=w.name("valid"),P=b.subschema({schema:B,dataTypes:[],schemaPath:Zb.nil,topSchemaRef:K,errSchemaPath:$},Z);b.mergeEvaluated(P),b.ok(Z)}}};function dY(b,w){let{gen:$}=b;return w.validate?$.scopeValue("validate",{ref:w.validate}):Zb._`${$.scopeValue("wrapper",{ref:w})}.validate`}rY.getValidate=dY;function K$(b,w,$,Q){let{gen:W,it:G}=b,{allErrors:X,schemaEnv:Y,opts:J}=G,z=J.passContext?aw.default.this:Zb.nil;if(Q)H();else A();function H(){if(!Y.$async)throw Error("async schema referenced by sync schema");let B=W.let("valid");W.try(()=>{if(W.code(Zb._`await ${(0,pY.callValidateCode)(b,w,z)}`),q(w),!X)W.assign(B,!0)},(K)=>{if(W.if(Zb._`!(${K} instanceof ${G.ValidationError})`,()=>W.throw(K)),O(K),!X)W.assign(B,!1)}),b.ok(B)}function A(){b.result((0,pY.callValidateCode)(b,w,z),()=>q(w),()=>O(w))}function O(B){let K=Zb._`${B}.errors`;W.assign(aw.default.vErrors,Zb._`${aw.default.vErrors} === null ? ${K} : ${aw.default.vErrors}.concat(${K})`),W.assign(aw.default.errors,Zb._`${aw.default.vErrors}.length`)}function q(B){var K;if(!G.opts.unevaluated)return;let Z=(K=$===null||$===void 0?void 0:$.validate)===null||K===void 0?void 0:K.evaluated;if(G.props!==!0)if(Z&&!Z.dynamicProps){if(Z.props!==void 0)G.props=B$.mergeEvaluated.props(W,Z.props,G.props)}else{let P=W.var("props",Zb._`${B}.evaluated.props`);G.props=B$.mergeEvaluated.props(W,P,G.props,Zb.Name)}if(G.items!==!0)if(Z&&!Z.dynamicItems){if(Z.items!==void 0)G.items=B$.mergeEvaluated.items(W,Z.items,G.items)}else{let P=W.var("items",Zb._`${B}.evaluated.items`);G.items=B$.mergeEvaluated.items(W,P,G.items,Zb.Name)}}}rY.callRef=K$;rY.default=i3});var aY=I((sY)=>{Object.defineProperty(sY,"__esModule",{value:!0});var d3=iY(),r3=eY(),t3=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",d3.default,r3.default];sY.default=t3});var wJ=I((bJ)=>{Object.defineProperty(bJ,"__esModule",{value:!0});var F$=u(),jw=F$.operators,M$={maximum:{okStr:"<=",ok:jw.LTE,fail:jw.GT},minimum:{okStr:">=",ok:jw.GTE,fail:jw.LT},exclusiveMaximum:{okStr:"<",ok:jw.LT,fail:jw.GTE},exclusiveMinimum:{okStr:">",ok:jw.GT,fail:jw.LTE}},s3={message:({keyword:b,schemaCode:w})=>F$.str`must be ${M$[b].okStr} ${w}`,params:({keyword:b,schemaCode:w})=>F$._`{comparison: ${M$[b].okStr}, limit: ${w}}`},a3={keyword:Object.keys(M$),type:"number",schemaType:"number",$data:!0,error:s3,code(b){let{keyword:w,data:$,schemaCode:Q}=b;b.fail$data(F$._`${$} ${M$[w].fail} ${Q} || isNaN(${$})`)}};bJ.default=a3});var QJ=I(($J)=>{Object.defineProperty($J,"__esModule",{value:!0});var e1=u(),wB={message:({schemaCode:b})=>e1.str`must be multiple of ${b}`,params:({schemaCode:b})=>e1._`{multipleOf: ${b}}`},$B={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:wB,code(b){let{gen:w,data:$,schemaCode:Q,it:W}=b,G=W.opts.multipleOfPrecision,X=w.let("res"),Y=G?e1._`Math.abs(Math.round(${X}) - ${X}) > 1e-${G}`:e1._`${X} !== parseInt(${X})`;b.fail$data(e1._`(${Q} === 0 || (${X} = ${$}/${Q}, ${Y}))`)}};$J.default=$B});var XJ=I((GJ)=>{Object.defineProperty(GJ,"__esModule",{value:!0});function WJ(b){let w=b.length,$=0,Q=0,W;while(Q<w)if($++,W=b.charCodeAt(Q++),W>=55296&&W<=56319&&Q<w){if(W=b.charCodeAt(Q),(W&64512)===56320)Q++}return $}GJ.default=WJ;WJ.code='require("ajv/dist/runtime/ucs2length").default'});var JJ=I((YJ)=>{Object.defineProperty(YJ,"__esModule",{value:!0});var uw=u(),GB=n(),XB=XJ(),YB={message({keyword:b,schemaCode:w}){let $=b==="maxLength"?"more":"fewer";return uw.str`must NOT have ${$} than ${w} characters`},params:({schemaCode:b})=>uw._`{limit: ${b}}`},JB={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:YB,code(b){let{keyword:w,data:$,schemaCode:Q,it:W}=b,G=w==="maxLength"?uw.operators.GT:uw.operators.LT,X=W.opts.unicode===!1?uw._`${$}.length`:uw._`${(0,GB.useFunc)(b.gen,XB.default)}(${$})`;b.fail$data(uw._`${X} ${G} ${Q}`)}};YJ.default=JB});var HJ=I((zJ)=>{Object.defineProperty(zJ,"__esModule",{value:!0});var HB=Cb(),P$=u(),AB={message:({schemaCode:b})=>P$.str`must match pattern "${b}"`,params:({schemaCode:b})=>P$._`{pattern: ${b}}`},DB={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:AB,code(b){let{data:w,$data:$,schema:Q,schemaCode:W,it:G}=b,X=G.opts.unicodeRegExp?"u":"",Y=$?P$._`(new RegExp(${W}, ${X}))`:(0,HB.usePattern)(b,Q);b.fail$data(P$._`!${Y}.test(${w})`)}};zJ.default=DB});var DJ=I((AJ)=>{Object.defineProperty(AJ,"__esModule",{value:!0});var s1=u(),qB={message({keyword:b,schemaCode:w}){let $=b==="maxProperties"?"more":"fewer";return s1.str`must NOT have ${$} than ${w} properties`},params:({schemaCode:b})=>s1._`{limit: ${b}}`},UB={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:qB,code(b){let{keyword:w,data:$,schemaCode:Q}=b,W=w==="maxProperties"?s1.operators.GT:s1.operators.LT;b.fail$data(s1._`Object.keys(${$}).length ${W} ${Q}`)}};AJ.default=UB});var qJ=I((OJ)=>{Object.defineProperty(OJ,"__esModule",{value:!0});var a1=Cb(),b0=u(),BB=n(),KB={message:({params:{missingProperty:b}})=>b0.str`must have required property '${b}'`,params:({params:{missingProperty:b}})=>b0._`{missingProperty: ${b}}`},FB={keyword:"required",type:"object",schemaType:"array",$data:!0,error:KB,code(b){let{gen:w,schema:$,schemaCode:Q,data:W,$data:G,it:X}=b,{opts:Y}=X;if(!G&&$.length===0)return;let J=$.length>=Y.loopRequired;if(X.allErrors)z();else H();if(Y.strictRequired){let q=b.parentSchema.properties,{definedProperties:B}=b.it;for(let K of $)if((q===null||q===void 0?void 0:q[K])===void 0&&!B.has(K)){let Z=X.schemaEnv.baseId+X.errSchemaPath,P=`required property "${K}" is not defined at "${Z}" (strictRequired)`;(0,BB.checkStrictMode)(X,P,X.opts.strictRequired)}}function z(){if(J||G)b.block$data(b0.nil,A);else for(let q of $)(0,a1.checkReportMissingProp)(b,q)}function H(){let q=w.let("missing");if(J||G){let B=w.let("valid",!0);b.block$data(B,()=>O(q,B)),b.ok(B)}else w.if((0,a1.checkMissingProp)(b,$,q)),(0,a1.reportMissingProp)(b,q),w.else()}function A(){w.forOf("prop",Q,(q)=>{b.setParams({missingProperty:q}),w.if((0,a1.noPropertyInData)(w,W,q,Y.ownProperties),()=>b.error())})}function O(q,B){b.setParams({missingProperty:q}),w.forOf(q,Q,()=>{w.assign(B,(0,a1.propertyInData)(w,W,q,Y.ownProperties)),w.if((0,b0.not)(B),()=>{b.error(),w.break()})},b0.nil)}}};OJ.default=FB});var LJ=I((UJ)=>{Object.defineProperty(UJ,"__esModule",{value:!0});var w0=u(),PB={message({keyword:b,schemaCode:w}){let $=b==="maxItems"?"more":"fewer";return w0.str`must NOT have ${$} than ${w} items`},params:({schemaCode:b})=>w0._`{limit: ${b}}`},ZB={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:PB,code(b){let{keyword:w,data:$,schemaCode:Q}=b,W=w==="maxItems"?w0.operators.GT:w0.operators.LT;b.fail$data(w0._`${$}.length ${W} ${Q}`)}};UJ.default=ZB});var Z$=I((KJ)=>{Object.defineProperty(KJ,"__esModule",{value:!0});var BJ=Z4();BJ.code='require("ajv/dist/runtime/equal").default';KJ.default=BJ});var MJ=I((FJ)=>{Object.defineProperty(FJ,"__esModule",{value:!0});var h4=c1(),qb=u(),jB=n(),NB=Z$(),EB={message:({params:{i:b,j:w}})=>qb.str`must NOT have duplicate items (items ## ${w} and ${b} are identical)`,params:({params:{i:b,j:w}})=>qb._`{i: ${b}, j: ${w}}`},TB={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:EB,code(b){let{gen:w,data:$,$data:Q,schema:W,parentSchema:G,schemaCode:X,it:Y}=b;if(!Q&&!W)return;let J=w.let("valid"),z=G.items?(0,h4.getSchemaTypes)(G.items):[];b.block$data(J,H,qb._`${X} === false`),b.ok(J);function H(){let B=w.let("i",qb._`${$}.length`),K=w.let("j");b.setParams({i:B,j:K}),w.assign(J,!0),w.if(qb._`${B} > 1`,()=>(A()?O:q)(B,K))}function A(){return z.length>0&&!z.some((B)=>B==="object"||B==="array")}function O(B,K){let Z=w.name("item"),P=(0,h4.checkDataTypes)(z,Z,Y.opts.strictNumbers,h4.DataType.Wrong),C=w.const("indices",qb._`{}`);w.for(qb._`;${B}--;`,()=>{if(w.let(Z,qb._`${$}[${B}]`),w.if(P,qb._`continue`),z.length>1)w.if(qb._`typeof ${Z} == "string"`,qb._`${Z} += "_"`);w.if(qb._`typeof ${C}[${Z}] == "number"`,()=>{w.assign(K,qb._`${C}[${Z}]`),b.error(),w.assign(J,!1).break()}).code(qb._`${C}[${Z}] = ${B}`)})}function q(B,K){let Z=(0,jB.useFunc)(w,NB.default),P=w.name("outer");w.label(P).for(qb._`;${B}--;`,()=>w.for(qb._`${K} = ${B}; ${K}--;`,()=>w.if(qb._`${Z}(${$}[${B}], ${$}[${K}])`,()=>{b.error(),w.assign(J,!1).break(P)})))}}};FJ.default=TB});var ZJ=I((PJ)=>{Object.defineProperty(PJ,"__esModule",{value:!0});var f4=u(),SB=n(),RB=Z$(),CB={message:"must be equal to constant",params:({schemaCode:b})=>f4._`{allowedValue: ${b}}`},vB={keyword:"const",$data:!0,error:CB,code(b){let{gen:w,data:$,$data:Q,schemaCode:W,schema:G}=b;if(Q||G&&typeof G=="object")b.fail$data(f4._`!${(0,SB.useFunc)(w,RB.default)}(${$}, ${W})`);else b.fail(f4._`${G} !== ${$}`)}};PJ.default=vB});var VJ=I((IJ)=>{Object.defineProperty(IJ,"__esModule",{value:!0});var $0=u(),xB=n(),uB=Z$(),yB={message:"must be equal to one of the allowed values",params:({schemaCode:b})=>$0._`{allowedValues: ${b}}`},hB={keyword:"enum",schemaType:"array",$data:!0,error:yB,code(b){let{gen:w,data:$,$data:Q,schema:W,schemaCode:G,it:X}=b;if(!Q&&W.length===0)throw Error("enum must have non-empty array");let Y=W.length>=X.opts.loopEnum,J,z=()=>J!==null&&J!==void 0?J:J=(0,xB.useFunc)(w,uB.default),H;if(Y||Q)H=w.let("valid"),b.block$data(H,A);else{if(!Array.isArray(W))throw Error("ajv implementation error");let q=w.const("vSchema",G);H=(0,$0.or)(...W.map((B,K)=>O(q,K)))}b.pass(H);function A(){w.assign(H,!1),w.forOf("v",G,(q)=>w.if($0._`${z()}(${$}, ${q})`,()=>w.assign(H,!0).break()))}function O(q,B){let K=W[B];return typeof K==="object"&&K!==null?$0._`${z()}(${$}, ${q}[${B}])`:$0._`${$} === ${K}`}}};IJ.default=hB});var NJ=I((jJ)=>{Object.defineProperty(jJ,"__esModule",{value:!0});var gB=wJ(),cB=QJ(),mB=JJ(),lB=HJ(),nB=DJ(),iB=qJ(),pB=LJ(),oB=MJ(),dB=ZJ(),rB=VJ(),tB=[gB.default,cB.default,mB.default,lB.default,nB.default,iB.default,pB.default,oB.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},dB.default,rB.default];jJ.default=tB});var c4=I((TJ)=>{Object.defineProperty(TJ,"__esModule",{value:!0});TJ.validateAdditionalItems=void 0;var yw=u(),g4=n(),sB={message:({params:{len:b}})=>yw.str`must NOT have more than ${b} items`,params:({params:{len:b}})=>yw._`{limit: ${b}}`},aB={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:sB,code(b){let{parentSchema:w,it:$}=b,{items:Q}=w;if(!Array.isArray(Q)){(0,g4.checkStrictMode)($,'"additionalItems" is ignored when "items" is not an array of schemas');return}EJ(b,Q)}};function EJ(b,w){let{gen:$,schema:Q,data:W,keyword:G,it:X}=b;X.items=!0;let Y=$.const("len",yw._`${W}.length`);if(Q===!1)b.setParams({len:w.length}),b.pass(yw._`${Y} <= ${w.length}`);else if(typeof Q=="object"&&!(0,g4.alwaysValidSchema)(X,Q)){let z=$.var("valid",yw._`${Y} <= ${w.length}`);$.if((0,yw.not)(z),()=>J(z)),b.ok(z)}function J(z){$.forRange("i",w.length,Y,(H)=>{if(b.subschema({keyword:G,dataProp:H,dataPropType:g4.Type.Num},z),!X.allErrors)$.if((0,yw.not)(z),()=>$.break())})}}TJ.validateAdditionalItems=EJ;TJ.default=aB});var m4=I((CJ)=>{Object.defineProperty(CJ,"__esModule",{value:!0});CJ.validateTuple=void 0;var SJ=u(),I$=n(),wK=Cb(),$K={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(b){let{schema:w,it:$}=b;if(Array.isArray(w))return RJ(b,"additionalItems",w);if($.items=!0,(0,I$.alwaysValidSchema)($,w))return;b.ok((0,wK.validateArray)(b))}};function RJ(b,w,$=b.schema){let{gen:Q,parentSchema:W,data:G,keyword:X,it:Y}=b;if(H(W),Y.opts.unevaluated&&$.length&&Y.items!==!0)Y.items=I$.mergeEvaluated.items(Q,$.length,Y.items);let J=Q.name("valid"),z=Q.const("len",SJ._`${G}.length`);$.forEach((A,O)=>{if((0,I$.alwaysValidSchema)(Y,A))return;Q.if(SJ._`${z} > ${O}`,()=>b.subschema({keyword:X,schemaProp:O,dataProp:O},J)),b.ok(J)});function H(A){let{opts:O,errSchemaPath:q}=Y,B=$.length,K=B===A.minItems&&(B===A.maxItems||A[w]===!1);if(O.strictTuples&&!K){let Z=`"${X}" is ${B}-tuple, but minItems or maxItems/${w} are not specified or different at path "${q}"`;(0,I$.checkStrictMode)(Y,Z,O.strictTuples)}}}CJ.validateTuple=RJ;CJ.default=$K});var xJ=I((kJ)=>{Object.defineProperty(kJ,"__esModule",{value:!0});var WK=m4(),GK={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:(b)=>(0,WK.validateTuple)(b,"items")};kJ.default=GK});var hJ=I((yJ)=>{Object.defineProperty(yJ,"__esModule",{value:!0});var uJ=u(),YK=n(),JK=Cb(),zK=c4(),HK={message:({params:{len:b}})=>uJ.str`must NOT have more than ${b} items`,params:({params:{len:b}})=>uJ._`{limit: ${b}}`},AK={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:HK,code(b){let{schema:w,parentSchema:$,it:Q}=b,{prefixItems:W}=$;if(Q.items=!0,(0,YK.alwaysValidSchema)(Q,w))return;if(W)(0,zK.validateAdditionalItems)(b,W);else b.ok((0,JK.validateArray)(b))}};yJ.default=AK});var gJ=I((fJ)=>{Object.defineProperty(fJ,"__esModule",{value:!0});var vb=u(),V$=n(),OK={message:({params:{min:b,max:w}})=>w===void 0?vb.str`must contain at least ${b} valid item(s)`:vb.str`must contain at least ${b} and no more than ${w} valid item(s)`,params:({params:{min:b,max:w}})=>w===void 0?vb._`{minContains: ${b}}`:vb._`{minContains: ${b}, maxContains: ${w}}`},qK={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:OK,code(b){let{gen:w,schema:$,parentSchema:Q,data:W,it:G}=b,X,Y,{minContains:J,maxContains:z}=Q;if(G.opts.next)X=J===void 0?1:J,Y=z;else X=1;let H=w.const("len",vb._`${W}.length`);if(b.setParams({min:X,max:Y}),Y===void 0&&X===0){(0,V$.checkStrictMode)(G,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(Y!==void 0&&X>Y){(0,V$.checkStrictMode)(G,'"minContains" > "maxContains" is always invalid'),b.fail();return}if((0,V$.alwaysValidSchema)(G,$)){let K=vb._`${H} >= ${X}`;if(Y!==void 0)K=vb._`${K} && ${H} <= ${Y}`;b.pass(K);return}G.items=!0;let A=w.name("valid");if(Y===void 0&&X===1)q(A,()=>w.if(A,()=>w.break()));else if(X===0){if(w.let(A,!0),Y!==void 0)w.if(vb._`${W}.length > 0`,O)}else w.let(A,!1),O();b.result(A,()=>b.reset());function O(){let K=w.name("_valid"),Z=w.let("count",0);q(K,()=>w.if(K,()=>B(Z)))}function q(K,Z){w.forRange("i",0,H,(P)=>{b.subschema({keyword:"contains",dataProp:P,dataPropType:V$.Type.Num,compositeRule:!0},K),Z()})}function B(K){if(w.code(vb._`${K}++`),Y===void 0)w.if(vb._`${K} >= ${X}`,()=>w.assign(A,!0).break());else if(w.if(vb._`${K} > ${Y}`,()=>w.assign(A,!1).break()),X===1)w.assign(A,!0);else w.if(vb._`${K} >= ${X}`,()=>w.assign(A,!0))}}};fJ.default=qK});var pJ=I((lJ)=>{Object.defineProperty(lJ,"__esModule",{value:!0});lJ.validateSchemaDeps=lJ.validatePropertyDeps=lJ.error=void 0;var l4=u(),LK=n(),Q0=Cb();lJ.error={message:({params:{property:b,depsCount:w,deps:$}})=>{let Q=w===1?"property":"properties";return l4.str`must have ${Q} ${$} when property ${b} is present`},params:({params:{property:b,depsCount:w,deps:$,missingProperty:Q}})=>l4._`{property: ${b},
|
|
7
|
+
missingProperty: ${Q},
|
|
8
|
+
depsCount: ${w},
|
|
9
|
+
deps: ${$}}`};var BK={keyword:"dependencies",type:"object",schemaType:"object",error:lJ.error,code(b){let[w,$]=KK(b);cJ(b,w),mJ(b,$)}};function KK({schema:b}){let w={},$={};for(let Q in b){if(Q==="__proto__")continue;let W=Array.isArray(b[Q])?w:$;W[Q]=b[Q]}return[w,$]}function cJ(b,w=b.schema){let{gen:$,data:Q,it:W}=b;if(Object.keys(w).length===0)return;let G=$.let("missing");for(let X in w){let Y=w[X];if(Y.length===0)continue;let J=(0,Q0.propertyInData)($,Q,X,W.opts.ownProperties);if(b.setParams({property:X,depsCount:Y.length,deps:Y.join(", ")}),W.allErrors)$.if(J,()=>{for(let z of Y)(0,Q0.checkReportMissingProp)(b,z)});else $.if(l4._`${J} && (${(0,Q0.checkMissingProp)(b,Y,G)})`),(0,Q0.reportMissingProp)(b,G),$.else()}}lJ.validatePropertyDeps=cJ;function mJ(b,w=b.schema){let{gen:$,data:Q,keyword:W,it:G}=b,X=$.name("valid");for(let Y in w){if((0,LK.alwaysValidSchema)(G,w[Y]))continue;$.if((0,Q0.propertyInData)($,Q,Y,G.opts.ownProperties),()=>{let J=b.subschema({keyword:W,schemaProp:Y},X);b.mergeValidEvaluated(J,X)},()=>$.var(X,!0)),b.ok(X)}}lJ.validateSchemaDeps=mJ;lJ.default=BK});var rJ=I((dJ)=>{Object.defineProperty(dJ,"__esModule",{value:!0});var oJ=u(),PK=n(),ZK={message:"property name must be valid",params:({params:b})=>oJ._`{propertyName: ${b.propertyName}}`},IK={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:ZK,code(b){let{gen:w,schema:$,data:Q,it:W}=b;if((0,PK.alwaysValidSchema)(W,$))return;let G=w.name("valid");w.forIn("key",Q,(X)=>{b.setParams({propertyName:X}),b.subschema({keyword:"propertyNames",data:X,dataTypes:["string"],propertyName:X,compositeRule:!0},G),w.if((0,oJ.not)(G),()=>{if(b.error(!0),!W.allErrors)w.break()})}),b.ok(G)}};dJ.default=IK});var n4=I((tJ)=>{Object.defineProperty(tJ,"__esModule",{value:!0});var j$=Cb(),cb=u(),jK=Qw(),N$=n(),NK={message:"must NOT have additional properties",params:({params:b})=>cb._`{additionalProperty: ${b.additionalProperty}}`},EK={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:NK,code(b){let{gen:w,schema:$,parentSchema:Q,data:W,errsCount:G,it:X}=b;if(!G)throw Error("ajv implementation error");let{allErrors:Y,opts:J}=X;if(X.props=!0,J.removeAdditional!=="all"&&(0,N$.alwaysValidSchema)(X,$))return;let z=(0,j$.allSchemaProperties)(Q.properties),H=(0,j$.allSchemaProperties)(Q.patternProperties);A(),b.ok(cb._`${G} === ${jK.default.errors}`);function A(){w.forIn("key",W,(Z)=>{if(!z.length&&!H.length)B(Z);else w.if(O(Z),()=>B(Z))})}function O(Z){let P;if(z.length>8){let C=(0,N$.schemaRefOrVal)(X,Q.properties,"properties");P=(0,j$.isOwnProperty)(w,C,Z)}else if(z.length)P=(0,cb.or)(...z.map((C)=>cb._`${Z} === ${C}`));else P=cb.nil;if(H.length)P=(0,cb.or)(P,...H.map((C)=>cb._`${(0,j$.usePattern)(b,C)}.test(${Z})`));return(0,cb.not)(P)}function q(Z){w.code(cb._`delete ${W}[${Z}]`)}function B(Z){if(J.removeAdditional==="all"||J.removeAdditional&&$===!1){q(Z);return}if($===!1){if(b.setParams({additionalProperty:Z}),b.error(),!Y)w.break();return}if(typeof $=="object"&&!(0,N$.alwaysValidSchema)(X,$)){let P=w.name("valid");if(J.removeAdditional==="failing")K(Z,P,!1),w.if((0,cb.not)(P),()=>{b.reset(),q(Z)});else if(K(Z,P),!Y)w.if((0,cb.not)(P),()=>w.break())}}function K(Z,P,C){let S={keyword:"additionalProperties",dataProp:Z,dataPropType:N$.Type.Str};if(C===!1)Object.assign(S,{compositeRule:!0,createErrors:!1,allErrors:!1});b.subschema(S,P)}}};tJ.default=EK});var bz=I((aJ)=>{Object.defineProperty(aJ,"__esModule",{value:!0});var _K=i1(),eJ=Cb(),i4=n(),sJ=n4(),SK={keyword:"properties",type:"object",schemaType:"object",code(b){let{gen:w,schema:$,parentSchema:Q,data:W,it:G}=b;if(G.opts.removeAdditional==="all"&&Q.additionalProperties===void 0)sJ.default.code(new _K.KeywordCxt(G,sJ.default,"additionalProperties"));let X=(0,eJ.allSchemaProperties)($);for(let A of X)G.definedProperties.add(A);if(G.opts.unevaluated&&X.length&&G.props!==!0)G.props=i4.mergeEvaluated.props(w,(0,i4.toHash)(X),G.props);let Y=X.filter((A)=>!(0,i4.alwaysValidSchema)(G,$[A]));if(Y.length===0)return;let J=w.name("valid");for(let A of Y){if(z(A))H(A);else{if(w.if((0,eJ.propertyInData)(w,W,A,G.opts.ownProperties)),H(A),!G.allErrors)w.else().var(J,!0);w.endIf()}b.it.definedProperties.add(A),b.ok(J)}function z(A){return G.opts.useDefaults&&!G.compositeRule&&$[A].default!==void 0}function H(A){b.subschema({keyword:"properties",schemaProp:A,dataProp:A},J)}}};aJ.default=SK});var Gz=I((Wz)=>{Object.defineProperty(Wz,"__esModule",{value:!0});var wz=Cb(),E$=u(),$z=n(),Qz=n(),CK={keyword:"patternProperties",type:"object",schemaType:"object",code(b){let{gen:w,schema:$,data:Q,parentSchema:W,it:G}=b,{opts:X}=G,Y=(0,wz.allSchemaProperties)($),J=Y.filter((K)=>(0,$z.alwaysValidSchema)(G,$[K]));if(Y.length===0||J.length===Y.length&&(!G.opts.unevaluated||G.props===!0))return;let z=X.strictSchema&&!X.allowMatchingProperties&&W.properties,H=w.name("valid");if(G.props!==!0&&!(G.props instanceof E$.Name))G.props=(0,Qz.evaluatedPropsToName)(w,G.props);let{props:A}=G;O();function O(){for(let K of Y){if(z)q(K);if(G.allErrors)B(K);else w.var(H,!0),B(K),w.if(H)}}function q(K){for(let Z in z)if(new RegExp(K).test(Z))(0,$z.checkStrictMode)(G,`property ${Z} matches pattern ${K} (use allowMatchingProperties)`)}function B(K){w.forIn("key",Q,(Z)=>{w.if(E$._`${(0,wz.usePattern)(b,K)}.test(${Z})`,()=>{let P=J.includes(K);if(!P)b.subschema({keyword:"patternProperties",schemaProp:K,dataProp:Z,dataPropType:Qz.Type.Str},H);if(G.opts.unevaluated&&A!==!0)w.assign(E$._`${A}[${Z}]`,!0);else if(!P&&!G.allErrors)w.if((0,E$.not)(H),()=>w.break())})})}}};Wz.default=CK});var Yz=I((Xz)=>{Object.defineProperty(Xz,"__esModule",{value:!0});var kK=n(),xK={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(b){let{gen:w,schema:$,it:Q}=b;if((0,kK.alwaysValidSchema)(Q,$)){b.fail();return}let W=w.name("valid");b.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},W),b.failResult(W,()=>b.reset(),()=>b.error())},error:{message:"must NOT be valid"}};Xz.default=xK});var zz=I((Jz)=>{Object.defineProperty(Jz,"__esModule",{value:!0});var yK=Cb(),hK={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:yK.validateUnion,error:{message:"must match a schema in anyOf"}};Jz.default=hK});var Az=I((Hz)=>{Object.defineProperty(Hz,"__esModule",{value:!0});var T$=u(),gK=n(),cK={message:"must match exactly one schema in oneOf",params:({params:b})=>T$._`{passingSchemas: ${b.passing}}`},mK={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:cK,code(b){let{gen:w,schema:$,parentSchema:Q,it:W}=b;if(!Array.isArray($))throw Error("ajv implementation error");if(W.opts.discriminator&&Q.discriminator)return;let G=$,X=w.let("valid",!1),Y=w.let("passing",null),J=w.name("_valid");b.setParams({passing:Y}),w.block(z),b.result(X,()=>b.reset(),()=>b.error(!0));function z(){G.forEach((H,A)=>{let O;if((0,gK.alwaysValidSchema)(W,H))w.var(J,!0);else O=b.subschema({keyword:"oneOf",schemaProp:A,compositeRule:!0},J);if(A>0)w.if(T$._`${J} && ${X}`).assign(X,!1).assign(Y,T$._`[${Y}, ${A}]`).else();w.if(J,()=>{if(w.assign(X,!0),w.assign(Y,A),O)b.mergeEvaluated(O,T$.Name)})})}}};Hz.default=mK});var Oz=I((Dz)=>{Object.defineProperty(Dz,"__esModule",{value:!0});var nK=n(),iK={keyword:"allOf",schemaType:"array",code(b){let{gen:w,schema:$,it:Q}=b;if(!Array.isArray($))throw Error("ajv implementation error");let W=w.name("valid");$.forEach((G,X)=>{if((0,nK.alwaysValidSchema)(Q,G))return;let Y=b.subschema({keyword:"allOf",schemaProp:X},W);b.ok(W),b.mergeEvaluated(Y)})}};Dz.default=iK});var Bz=I((Lz)=>{Object.defineProperty(Lz,"__esModule",{value:!0});var _$=u(),Uz=n(),oK={message:({params:b})=>_$.str`must match "${b.ifClause}" schema`,params:({params:b})=>_$._`{failingKeyword: ${b.ifClause}}`},dK={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:oK,code(b){let{gen:w,parentSchema:$,it:Q}=b;if($.then===void 0&&$.else===void 0)(0,Uz.checkStrictMode)(Q,'"if" without "then" and "else" is ignored');let W=qz(Q,"then"),G=qz(Q,"else");if(!W&&!G)return;let X=w.let("valid",!0),Y=w.name("_valid");if(J(),b.reset(),W&&G){let H=w.let("ifClause");b.setParams({ifClause:H}),w.if(Y,z("then",H),z("else",H))}else if(W)w.if(Y,z("then"));else w.if((0,_$.not)(Y),z("else"));b.pass(X,()=>b.error(!0));function J(){let H=b.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},Y);b.mergeEvaluated(H)}function z(H,A){return()=>{let O=b.subschema({keyword:H},Y);if(w.assign(X,Y),b.mergeValidEvaluated(O,X),A)w.assign(A,_$._`${H}`);else b.setParams({ifClause:H})}}}};function qz(b,w){let $=b.schema[w];return $!==void 0&&!(0,Uz.alwaysValidSchema)(b,$)}Lz.default=dK});var Fz=I((Kz)=>{Object.defineProperty(Kz,"__esModule",{value:!0});var tK=n(),eK={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:b,parentSchema:w,it:$}){if(w.if===void 0)(0,tK.checkStrictMode)($,`"${b}" without "if" is ignored`)}};Kz.default=eK});var Pz=I((Mz)=>{Object.defineProperty(Mz,"__esModule",{value:!0});var aK=c4(),bF=xJ(),wF=m4(),$F=hJ(),QF=gJ(),WF=pJ(),GF=rJ(),XF=n4(),YF=bz(),JF=Gz(),zF=Yz(),HF=zz(),AF=Az(),DF=Oz(),OF=Bz(),qF=Fz();function UF(b=!1){let w=[zF.default,HF.default,AF.default,DF.default,OF.default,qF.default,GF.default,XF.default,WF.default,YF.default,JF.default];if(b)w.push(bF.default,$F.default);else w.push(aK.default,wF.default);return w.push(QF.default),w}Mz.default=UF});var Iz=I((Zz)=>{Object.defineProperty(Zz,"__esModule",{value:!0});var Gb=u(),BF={message:({schemaCode:b})=>Gb.str`must match format "${b}"`,params:({schemaCode:b})=>Gb._`{format: ${b}}`},KF={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:BF,code(b,w){let{gen:$,data:Q,$data:W,schema:G,schemaCode:X,it:Y}=b,{opts:J,errSchemaPath:z,schemaEnv:H,self:A}=Y;if(!J.validateFormats)return;if(W)O();else q();function O(){let B=$.scopeValue("formats",{ref:A.formats,code:J.code.formats}),K=$.const("fDef",Gb._`${B}[${X}]`),Z=$.let("fType"),P=$.let("format");$.if(Gb._`typeof ${K} == "object" && !(${K} instanceof RegExp)`,()=>$.assign(Z,Gb._`${K}.type || "string"`).assign(P,Gb._`${K}.validate`),()=>$.assign(Z,Gb._`"string"`).assign(P,K)),b.fail$data((0,Gb.or)(C(),S()));function C(){if(J.strictSchema===!1)return Gb.nil;return Gb._`${X} && !${P}`}function S(){let h=H.$async?Gb._`(${K}.async ? await ${P}(${Q}) : ${P}(${Q}))`:Gb._`${P}(${Q})`,R=Gb._`(typeof ${P} == "function" ? ${h} : ${P}.test(${Q}))`;return Gb._`${P} && ${P} !== true && ${Z} === ${w} && !${R}`}}function q(){let B=A.formats[G];if(!B){C();return}if(B===!0)return;let[K,Z,P]=S(B);if(K===w)b.pass(h());function C(){if(J.strictSchema===!1){A.logger.warn(R());return}throw Error(R());function R(){return`unknown format "${G}" ignored in schema at path "${z}"`}}function S(R){let ib=R instanceof RegExp?(0,Gb.regexpCode)(R):J.code.formats?Gb._`${J.code.formats}${(0,Gb.getProperty)(G)}`:void 0,eb=$.scopeValue("formats",{key:G,ref:R,code:ib});if(typeof R=="object"&&!(R instanceof RegExp))return[R.type||"string",R.validate,Gb._`${eb}.validate`];return["string",R,eb]}function h(){if(typeof B=="object"&&!(B instanceof RegExp)&&B.async){if(!H.$async)throw Error("async format in sync schema");return Gb._`await ${P}(${Q})`}return typeof Z=="function"?Gb._`${P}(${Q})`:Gb._`${P}.test(${Q})`}}}};Zz.default=KF});var jz=I((Vz)=>{Object.defineProperty(Vz,"__esModule",{value:!0});var MF=Iz(),PF=[MF.default];Vz.default=PF});var Tz=I((Nz)=>{Object.defineProperty(Nz,"__esModule",{value:!0});Nz.contentVocabulary=Nz.metadataVocabulary=void 0;Nz.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Nz.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Rz=I((Sz)=>{Object.defineProperty(Sz,"__esModule",{value:!0});var VF=aY(),jF=NJ(),NF=Pz(),EF=jz(),_z=Tz(),TF=[VF.default,jF.default,(0,NF.default)(),EF.default,_z.metadataVocabulary,_z.contentVocabulary];Sz.default=TF});var xz=I((vz)=>{Object.defineProperty(vz,"__esModule",{value:!0});vz.DiscrError=void 0;var Cz;(function(b){b.Tag="tag",b.Mapping="mapping"})(Cz||(vz.DiscrError=Cz={}))});var hz=I((yz)=>{Object.defineProperty(yz,"__esModule",{value:!0});var b1=u(),p4=xz(),uz=H$(),SF=p1(),RF=n(),CF={message:({params:{discrError:b,tagName:w}})=>b===p4.DiscrError.Tag?`tag "${w}" must be string`:`value of tag "${w}" must be in oneOf`,params:({params:{discrError:b,tag:w,tagName:$}})=>b1._`{error: ${b}, tag: ${$}, tagValue: ${w}}`},vF={keyword:"discriminator",type:"object",schemaType:"object",error:CF,code(b){let{gen:w,data:$,schema:Q,parentSchema:W,it:G}=b,{oneOf:X}=W;if(!G.opts.discriminator)throw Error("discriminator: requires discriminator option");let Y=Q.propertyName;if(typeof Y!="string")throw Error("discriminator: requires propertyName");if(Q.mapping)throw Error("discriminator: mapping is not supported");if(!X)throw Error("discriminator: requires oneOf keyword");let J=w.let("valid",!1),z=w.const("tag",b1._`${$}${(0,b1.getProperty)(Y)}`);w.if(b1._`typeof ${z} == "string"`,()=>H(),()=>b.error(!1,{discrError:p4.DiscrError.Tag,tag:z,tagName:Y})),b.ok(J);function H(){let q=O();w.if(!1);for(let B in q)w.elseIf(b1._`${z} === ${B}`),w.assign(J,A(q[B]));w.else(),b.error(!1,{discrError:p4.DiscrError.Mapping,tag:z,tagName:Y}),w.endIf()}function A(q){let B=w.name("valid"),K=b.subschema({keyword:"oneOf",schemaProp:q},B);return b.mergeEvaluated(K,b1.Name),B}function O(){var q;let B={},K=P(W),Z=!0;for(let h=0;h<X.length;h++){let R=X[h];if((R===null||R===void 0?void 0:R.$ref)&&!(0,RF.schemaHasRulesButRef)(R,G.self.RULES)){let eb=R.$ref;if(R=uz.resolveRef.call(G.self,G.schemaEnv.root,G.baseId,eb),R instanceof uz.SchemaEnv)R=R.schema;if(R===void 0)throw new SF.default(G.opts.uriResolver,G.baseId,eb)}let ib=(q=R===null||R===void 0?void 0:R.properties)===null||q===void 0?void 0:q[Y];if(typeof ib!="object")throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${Y}"`);Z=Z&&(K||P(R)),C(ib,h)}if(!Z)throw Error(`discriminator: "${Y}" must be required`);return B;function P({required:h}){return Array.isArray(h)&&h.includes(Y)}function C(h,R){if(h.const)S(h.const,R);else if(h.enum)for(let ib of h.enum)S(ib,R);else throw Error(`discriminator: "properties/${Y}" must have "const" or "enum"`)}function S(h,R){if(typeof h!="string"||h in B)throw Error(`discriminator: "${Y}" values must be unique strings`);B[h]=R}}}};yz.default=vF});var fz=I((PT,xF)=>{xF.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 d4=I((Ib,o4)=>{Object.defineProperty(Ib,"__esModule",{value:!0});Ib.MissingRefError=Ib.ValidationError=Ib.CodeGen=Ib.Name=Ib.nil=Ib.stringify=Ib.str=Ib._=Ib.KeywordCxt=Ib.Ajv=void 0;var uF=lY(),yF=Rz(),hF=hz(),gz=fz(),fF=["/properties"],S$="http://json-schema.org/draft-07/schema";class W0 extends uF.default{_addVocabularies(){if(super._addVocabularies(),yF.default.forEach((b)=>this.addVocabulary(b)),this.opts.discriminator)this.addKeyword(hF.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let b=this.opts.$data?this.$dataMetaSchema(gz,fF):gz;this.addMetaSchema(b,S$,!1),this.refs["http://json-schema.org/schema"]=S$}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(S$)?S$:void 0)}}Ib.Ajv=W0;o4.exports=Ib=W0;o4.exports.Ajv=W0;Object.defineProperty(Ib,"__esModule",{value:!0});Ib.default=W0;var gF=i1();Object.defineProperty(Ib,"KeywordCxt",{enumerable:!0,get:function(){return gF.KeywordCxt}});var w1=u();Object.defineProperty(Ib,"_",{enumerable:!0,get:function(){return w1._}});Object.defineProperty(Ib,"str",{enumerable:!0,get:function(){return w1.str}});Object.defineProperty(Ib,"stringify",{enumerable:!0,get:function(){return w1.stringify}});Object.defineProperty(Ib,"nil",{enumerable:!0,get:function(){return w1.nil}});Object.defineProperty(Ib,"Name",{enumerable:!0,get:function(){return w1.Name}});Object.defineProperty(Ib,"CodeGen",{enumerable:!0,get:function(){return w1.CodeGen}});var cF=J$();Object.defineProperty(Ib,"ValidationError",{enumerable:!0,get:function(){return cF.default}});var mF=p1();Object.defineProperty(Ib,"MissingRefError",{enumerable:!0,get:function(){return mF.default}})});var tz=I((dz)=>{Object.defineProperty(dz,"__esModule",{value:!0});dz.formatNames=dz.fastFormats=dz.fullFormats=void 0;function db(b,w){return{validate:b,compare:w}}dz.fullFormats={date:db(nz,s4),time:db(t4(!0),a4),"date-time":db(cz(!0),pz),"iso-time":db(t4(),iz),"iso-date-time":db(cz(),oz),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:tF,"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:QM,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:eF,int32:{type:"number",validate:bM},int64:{type:"number",validate:wM},float:{type:"number",validate:lz},double:{type:"number",validate:lz},password:!0,binary:!0};dz.fastFormats={...dz.fullFormats,date:db(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,s4),time:db(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,a4),"date-time":db(/^\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,pz),"iso-time":db(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,iz),"iso-date-time":db(/^\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,oz),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};dz.formatNames=Object.keys(dz.fullFormats);function iF(b){return b%4===0&&(b%100!==0||b%400===0)}var pF=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,oF=[0,31,28,31,30,31,30,31,31,30,31,30,31];function nz(b){let w=pF.exec(b);if(!w)return!1;let $=+w[1],Q=+w[2],W=+w[3];return Q>=1&&Q<=12&&W>=1&&W<=(Q===2&&iF($)?29:oF[Q])}function s4(b,w){if(!(b&&w))return;if(b>w)return 1;if(b<w)return-1;return 0}var r4=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function t4(b){return function($){let Q=r4.exec($);if(!Q)return!1;let W=+Q[1],G=+Q[2],X=+Q[3],Y=Q[4],J=Q[5]==="-"?-1:1,z=+(Q[6]||0),H=+(Q[7]||0);if(z>23||H>59||b&&!Y)return!1;if(W<=23&&G<=59&&X<60)return!0;let A=G-H*J,O=W-z*J-(A<0?1:0);return(O===23||O===-1)&&(A===59||A===-1)&&X<61}}function a4(b,w){if(!(b&&w))return;let $=new Date("2020-01-01T"+b).valueOf(),Q=new Date("2020-01-01T"+w).valueOf();if(!($&&Q))return;return $-Q}function iz(b,w){if(!(b&&w))return;let $=r4.exec(b),Q=r4.exec(w);if(!($&&Q))return;if(b=$[1]+$[2]+$[3],w=Q[1]+Q[2]+Q[3],b>w)return 1;if(b<w)return-1;return 0}var e4=/t|\s/i;function cz(b){let w=t4(b);return function(Q){let W=Q.split(e4);return W.length===2&&nz(W[0])&&w(W[1])}}function pz(b,w){if(!(b&&w))return;let $=new Date(b).valueOf(),Q=new Date(w).valueOf();if(!($&&Q))return;return $-Q}function oz(b,w){if(!(b&&w))return;let[$,Q]=b.split(e4),[W,G]=w.split(e4),X=s4($,W);if(X===void 0)return;return X||a4(Q,G)}var dF=/\/|:/,rF=/^(?:[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 tF(b){return dF.test(b)&&rF.test(b)}var mz=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function eF(b){return mz.lastIndex=0,mz.test(b)}var sF=-2147483648,aF=2147483647;function bM(b){return Number.isInteger(b)&&b<=aF&&b>=sF}function wM(b){return Number.isInteger(b)}function lz(){return!0}var $M=/[^\\]\\Z/;function QM(b){if($M.test(b))return!1;try{return new RegExp(b),!0}catch(w){return!1}}});var sz=I((ez)=>{Object.defineProperty(ez,"__esModule",{value:!0});ez.formatLimitDefinition=void 0;var GM=d4(),mb=u(),Nw=mb.operators,R$={formatMaximum:{okStr:"<=",ok:Nw.LTE,fail:Nw.GT},formatMinimum:{okStr:">=",ok:Nw.GTE,fail:Nw.LT},formatExclusiveMaximum:{okStr:"<",ok:Nw.LT,fail:Nw.GTE},formatExclusiveMinimum:{okStr:">",ok:Nw.GT,fail:Nw.LTE}},XM={message:({keyword:b,schemaCode:w})=>mb.str`should be ${R$[b].okStr} ${w}`,params:({keyword:b,schemaCode:w})=>mb._`{comparison: ${R$[b].okStr}, limit: ${w}}`};ez.formatLimitDefinition={keyword:Object.keys(R$),type:"string",schemaType:"string",$data:!0,error:XM,code(b){let{gen:w,data:$,schemaCode:Q,keyword:W,it:G}=b,{opts:X,self:Y}=G;if(!X.validateFormats)return;let J=new GM.KeywordCxt(G,Y.RULES.all.format.definition,"format");if(J.$data)z();else H();function z(){let O=w.scopeValue("formats",{ref:Y.formats,code:X.code.formats}),q=w.const("fmt",mb._`${O}[${J.schemaCode}]`);b.fail$data((0,mb.or)(mb._`typeof ${q} != "object"`,mb._`${q} instanceof RegExp`,mb._`typeof ${q}.compare != "function"`,A(q)))}function H(){let O=J.schema,q=Y.formats[O];if(!q||q===!0)return;if(typeof q!="object"||q instanceof RegExp||typeof q.compare!="function")throw Error(`"${W}": format "${O}" does not define "compare" function`);let B=w.scopeValue("formats",{key:O,ref:q,code:X.code.formats?mb._`${X.code.formats}${(0,mb.getProperty)(O)}`:void 0});b.fail$data(A(B))}function A(O){return mb._`${O}.compare(${$}, ${Q}) ${R$[W].fail} 0`}},dependencies:["format"]};var YM=(b)=>{return b.addKeyword(ez.formatLimitDefinition),b};ez.default=YM});var $H=I((G0,wH)=>{Object.defineProperty(G0,"__esModule",{value:!0});var $1=tz(),zM=sz(),$Q=u(),az=new $Q.Name("fullFormats"),HM=new $Q.Name("fastFormats"),QQ=(b,w={keywords:!0})=>{if(Array.isArray(w))return bH(b,w,$1.fullFormats,az),b;let[$,Q]=w.mode==="fast"?[$1.fastFormats,HM]:[$1.fullFormats,az],W=w.formats||$1.formatNames;if(bH(b,W,$,Q),w.keywords)(0,zM.default)(b);return b};QQ.get=(b,w="full")=>{let Q=(w==="fast"?$1.fastFormats:$1.fullFormats)[b];if(!Q)throw Error(`Unknown format "${b}"`);return Q};function bH(b,w,$,Q){var W,G;(W=(G=b.opts.code).formats)!==null&&W!==void 0||(G.formats=$Q._`require("ajv-formats/dist/formats").${Q}`);for(let X of w)b.addFormat(X,$[X])}wH.exports=G0=QQ;Object.defineProperty(G0,"__esModule",{value:!0});G0.default=QQ});import{AsyncLocalStorage as yA}from"node:async_hooks";class _w extends Error{statusCode;rawDetails;code;context;constructor(b,w,$,Q,W){super(b);this.statusCode=w;this.rawDetails=$;this.code=Q;this.context=W;this.name="McpApiError"}}function kA(b){if(b instanceof _w)return{message:b.message,statusCode:b.statusCode,code:b.code,rawDetails:b.rawDetails,context:b.context};if(b instanceof Error)return{message:b.message};return{message:String(b)}}function xA(b){let w=b.match(/api key is missing required scopes?:\s*(.+)$/i);if(!w?.[1])return[];return w[1].match(/[a-z_]+:[a-z_]+/gi)??[]}function uA(b){let w=kA(b),$=w.message.trim()||"Unknown error",Q=$.toLowerCase(),W=w.rawDetails?.trim()||$;if(w.context?.title||w.context?.description||w.context?.howToFix||w.context?.docsUrl)return{title:w.context.title??(w.statusCode===409?"Request conflict":"API request failed"),description:w.context.description??$,howToFix:w.context.howToFix??"Review the details below, adjust the tool input, and retry.",docsUrl:w.context.docsUrl??"https://docs.sequenzy.com/concepts/mcp",details:W};if(w.code==="MCP_AUTH_REQUIRED"||Q.includes("sequenzy_api_key environment variable is required"))return{title:"Missing MCP API key",description:"The MCP server started without a Sequenzy API key, so it cannot authenticate any tool or resource request.",howToFix:"Add `SEQUENZY_API_KEY` to the MCP server environment, or run `npx @sequenzy/setup` to configure the integration automatically.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:W};if(w.statusCode===401||w.code==="UNAUTHORIZED")return{title:"Authentication failed",description:"The MCP server reached Sequenzy, but the current API key was rejected.",howToFix:"Replace `SEQUENZY_API_KEY` with a valid personal API key, then restart the MCP client so it reconnects with fresh credentials.",docsUrl:"https://docs.sequenzy.com/authentication",details:W};let G=xA($);if(G.length>0){let X=G.map((J)=>`\`${J}\``).join(", "),Y=G.every((J)=>J.endsWith(":read"))?"the Read-only or Safer agent access preset":"Safer agent access when it covers the task, or Custom permissions";return{title:"API key permission required",description:`The current API key is valid, but this operation requires the missing ${G.length===1?"scope":"scopes"}: ${X}.`,howToFix:`For a local API-key connection, call \`get_account\` to inspect \`apiKeyPermissions\` and open \`apiKeyPermissions.manageUrl\` (or \`companies[].settingsUrl\` → API Keys). If \`get_account\` also requires \`account:read\`, open ${"https://sequenzy.com/dashboard"} directly and use the MCP setup or Settings → API Keys. Create a replacement key with ${Y} including ${X}, replace \`SEQUENZY_API_KEY\`, and restart the client. For hosted OAuth MCP, disconnect and reauthorize the Sequenzy connection with a preset or Custom permissions including ${X}. Existing key permissions cannot be edited in place.`,docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:W}}if(w.statusCode===403||Q.includes("access denied"))return{title:"Access denied",description:"The current API key is valid, but it does not have permission to access the requested company or action.",howToFix:"Use an API key that belongs to the right account, or select a company the key can access before retrying the tool call.",docsUrl:"https://docs.sequenzy.com/authentication",details:W};if(Q.includes("no company available")||Q.includes("company not found"))return{title:"Company selection required",description:"The MCP server could not resolve a company for this request.",howToFix:"Call `get_account` to inspect available companies, then call `select_company`, or pass `companyId` explicitly in the next tool call.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:W};if(w.statusCode===404||Q.includes("not found"))return{title:"Requested resource not found",description:"Sequenzy could not find the requested campaign, template, sequence, company, or subscriber.",howToFix:"List or fetch the resource collection first, then retry the tool with a confirmed ID or email value.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:W};if(w.statusCode===409||Q.includes("already exists"))return{title:"Resource already exists",description:"Sequenzy rejected this MCP request because it would create a duplicate resource.",howToFix:"List the existing resources first, reuse the matching resource when appropriate, or retry with a unique name or domain.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:W};if(w.statusCode===429||Q.includes("rate limit"))return{title:"Rate limited",description:"Sequenzy temporarily slowed this MCP request because too many requests were sent too quickly.",howToFix:"Wait briefly before retrying. If the client is looping, reduce retries or add backoff before the next tool call.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:W};if(w.code==="NETWORK_ERROR"||Q.includes("fetch failed"))return{title:"Network or configuration error",description:"The MCP server could not reach the Sequenzy API from this environment.",howToFix:"Check connectivity and verify `SEQUENZY_API_URL` if you override it in the MCP environment.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:W};if(Q.includes("unknown tool")||Q.includes("unknown resource"))return{title:"Unsupported MCP request",description:"The client asked for a tool or resource name that this Sequenzy MCP server does not expose.",howToFix:"Refresh the client's tool list and call only the names returned by `list_tools` or `list_resources`.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:W};if(Q.includes("is required")||Q.includes("invalid"))return{title:"Invalid MCP input",description:"The tool call was missing a required field or included an invalid value.",howToFix:"Review the tool schema, supply the missing argument, and retry the request with corrected input.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:W};if(w.statusCode&&w.statusCode>=500)return{title:"Sequenzy server error",description:"The request reached Sequenzy, but the server could not complete it successfully.",howToFix:"Retry once. If it still fails, keep the details below and consult the docs before escalating.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:W};return{title:"Tool execution failed",description:"The MCP server could not complete the requested operation.",howToFix:"Review the details below, adjust the tool input or credentials, and retry.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:W}}function Aw(b){let w=uA(b);return[`Sequenzy MCP error: ${w.title}`,`Description: ${w.description}`,`How to fix: ${w.howToFix}`,`Docs: ${w.docsUrl}`,`Details: ${w.details}`].join(`
|
|
10
|
+
`)}var hA="https://api.sequenzy.com",A1=new yA,CQ=!1;function vQ(){CQ=!0}function kQ(){return CQ}var xQ=null;function Dw(){let b=A1.getStore();if(b)return b.selectedCompanyId??null;return xQ}function A0(b){let w=A1.getStore();if(w){w.selectedCompanyId=b;return}xQ=b}function d$(b,w){return A1.run(b,w)}function fA(){return A1.getStore()?.apiUrl??process.env.SEQUENZY_API_URL??hA}function uQ(){return A1.getStore()?.apiKey??process.env.SEQUENZY_API_KEY}function yQ(){if(uQ())return;console.error(Aw(new _w("SEQUENZY_API_KEY environment variable is required",401,void 0,"MCP_AUTH_REQUIRED"))),process.exit(1)}function Nb(b,w){let $=b[w];return typeof $==="string"&&$.trim()!==""?$.trim():void 0}function gA(b){if(b===void 0)return;if(typeof b==="string")return b.trim()||void 0;return JSON.stringify(b)}function cA(b){if(!b.trim())return{message:"Request failed"};try{let w=JSON.parse(b);if(typeof w==="string")return{message:w};let $=typeof w.error==="object"&&w.error!==null?w.error:void 0,Q=Nb(w,"code")??($?Nb($,"code"):void 0),W=(typeof w.error==="string"?w.error:void 0)??($?Nb($,"message"):void 0)??Nb(w,"message")??Nb(w,"error")??b,G=Nb(w,"howToFix")??Nb(w,"resolution"),X={...Nb(w,"title")?{title:Nb(w,"title")}:{},...Nb(w,"description")?{description:Nb(w,"description")}:{},...G?{howToFix:G}:{},...Nb(w,"docsUrl")?{docsUrl:Nb(w,"docsUrl")}:{}},Y=gA(w.details);if(Object.keys(X).length>0||Y)return{message:W,...Q?{code:Q}:{},...Y?{details:Y}:{},...Object.keys(X).length>0?{context:X}:{}};if(typeof w.error==="string")return{message:w.error,...Q?{code:Q}:{}};if($)return{message:W,...Q?{code:Q}:{}};return{message:W,...Q?{code:Q}:{}}}catch{return{message:b}}}async function D(b,w,$,Q){let W=uQ();if(!W)throw new _w("SEQUENZY_API_KEY environment variable is required",401,void 0,"MCP_AUTH_REQUIRED");let G={"Content-Type":"application/json",Authorization:`Bearer ${W}`},X=Q??Dw();if(X)G["x-company-id"]=X;let Y;try{Y=await fetch(`${fA()}${w}`,{method:b,headers:G,body:$?JSON.stringify($):void 0})}catch(J){throw new _w(J instanceof Error?J.message:"Failed to reach Sequenzy API",0,void 0,"NETWORK_ERROR")}if(!Y.ok){let J=await Y.text(),z=cA(J);throw new _w(z.message,Y.status,z.details??J,z.code,z.context)}return Y.json()}var JP=Object.freeze({status:"aborted"});function L(b,w,$){function Q(Y,J){var z;Object.defineProperty(Y,"_zod",{value:Y._zod??{},enumerable:!1}),(z=Y._zod).traits??(z.traits=new Set),Y._zod.traits.add(b),w(Y,J);for(let H in X.prototype)if(!(H in Y))Object.defineProperty(Y,H,{value:X.prototype[H].bind(Y)});Y._zod.constr=X,Y._zod.def=J}let W=$?.Parent??Object;class G extends W{}Object.defineProperty(G,"name",{value:b});function X(Y){var J;let z=$?.Parent?new G:this;Q(z,Y),(J=z._zod).deferred??(J.deferred=[]);for(let H of z._zod.deferred)H();return z}return Object.defineProperty(X,"init",{value:Q}),Object.defineProperty(X,Symbol.hasInstance,{value:(Y)=>{if($?.Parent&&Y instanceof $.Parent)return!0;return Y?._zod?.traits?.has(b)}}),Object.defineProperty(X,"name",{value:b}),X}var zP=Symbol("zod_brand");class sb extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class D1 extends Error{constructor(b){super(`Encountered unidirectional transform during encode: ${b}`);this.name="ZodEncodeError"}}var D0={};function _b(b){if(b)Object.assign(D0,b);return D0}var l={};RQ(l,{unwrapMessage:()=>O1,uint8ArrayToHex:()=>DD,uint8ArrayToBase64url:()=>HD,uint8ArrayToBase64:()=>nQ,stringifyPrimitive:()=>L0,shallowClone:()=>fQ,safeExtend:()=>WD,required:()=>YD,randomString:()=>eA,propertyKeyTypes:()=>a$,promiseAllObject:()=>tA,primitiveTypes:()=>gQ,prefixIssues:()=>bw,pick:()=>wD,partial:()=>XD,optionalKeys:()=>b6,omit:()=>$D,objectClone:()=>oA,numKeys:()=>sA,nullish:()=>q1,normalizeParams:()=>_,mergeDefs:()=>qw,merge:()=>GD,jsonStringifyReplacer:()=>hw,joinValues:()=>O0,issue:()=>gw,isPlainObject:()=>Uw,isObject:()=>Sw,hexToUint8Array:()=>AD,getSizableOrigin:()=>mQ,getParsedType:()=>aA,getLengthableOrigin:()=>L1,getEnumValues:()=>t$,getElementAtPath:()=>rA,floatSafeRemainder:()=>e$,finalizeIssue:()=>ub,extend:()=>QD,escapeRegex:()=>ab,esc:()=>q0,defineLazy:()=>o,createTransparentProxy:()=>bD,cloneDef:()=>dA,clone:()=>xb,cleanRegex:()=>U1,cleanEnum:()=>JD,captureStackTrace:()=>U0,cached:()=>fw,base64urlToUint8Array:()=>zD,base64ToUint8Array:()=>lQ,assignProp:()=>Ow,assertNotEqual:()=>lA,assertNever:()=>iA,assertIs:()=>nA,assertEqual:()=>mA,assert:()=>pA,allowsEval:()=>s$,aborted:()=>Lw,NUMBER_FORMAT_RANGES:()=>w6,Class:()=>iQ,BIGINT_FORMAT_RANGES:()=>cQ});function mA(b){return b}function lA(b){return b}function nA(b){}function iA(b){throw Error()}function pA(b){}function t$(b){let w=Object.values(b).filter((Q)=>typeof Q==="number");return Object.entries(b).filter(([Q,W])=>w.indexOf(+Q)===-1).map(([Q,W])=>W)}function O0(b,w="|"){return b.map(($)=>L0($)).join(w)}function hw(b,w){if(typeof w==="bigint")return w.toString();return w}function fw(b){return{get value(){{let $=b();return Object.defineProperty(this,"value",{value:$}),$}throw Error("cached value already set")}}}function q1(b){return b===null||b===void 0}function U1(b){let w=b.startsWith("^")?1:0,$=b.endsWith("$")?b.length-1:b.length;return b.slice(w,$)}function e$(b,w){let $=(b.toString().split(".")[1]||"").length,Q=w.toString(),W=(Q.split(".")[1]||"").length;if(W===0&&/\d?e-\d?/.test(Q)){let J=Q.match(/\d?e-(\d?)/);if(J?.[1])W=Number.parseInt(J[1])}let G=$>W?$:W,X=Number.parseInt(b.toFixed(G).replace(".","")),Y=Number.parseInt(w.toFixed(G).replace(".",""));return X%Y/10**G}var hQ=Symbol("evaluating");function o(b,w,$){let Q=void 0;Object.defineProperty(b,w,{get(){if(Q===hQ)return;if(Q===void 0)Q=hQ,Q=$();return Q},set(W){Object.defineProperty(b,w,{value:W})},configurable:!0})}function oA(b){return Object.create(Object.getPrototypeOf(b),Object.getOwnPropertyDescriptors(b))}function Ow(b,w,$){Object.defineProperty(b,w,{value:$,writable:!0,enumerable:!0,configurable:!0})}function qw(...b){let w={};for(let $ of b){let Q=Object.getOwnPropertyDescriptors($);Object.assign(w,Q)}return Object.defineProperties({},w)}function dA(b){return qw(b._zod.def)}function rA(b,w){if(!w)return b;return w.reduce(($,Q)=>$?.[Q],b)}function tA(b){let w=Object.keys(b),$=w.map((Q)=>b[Q]);return Promise.all($).then((Q)=>{let W={};for(let G=0;G<w.length;G++)W[w[G]]=Q[G];return W})}function eA(b=10){let $="";for(let Q=0;Q<b;Q++)$+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return $}function q0(b){return JSON.stringify(b)}var U0="captureStackTrace"in Error?Error.captureStackTrace:(...b)=>{};function Sw(b){return typeof b==="object"&&b!==null&&!Array.isArray(b)}var s$=fw(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(b){return!1}});function Uw(b){if(Sw(b)===!1)return!1;let w=b.constructor;if(w===void 0)return!0;let $=w.prototype;if(Sw($)===!1)return!1;if(Object.prototype.hasOwnProperty.call($,"isPrototypeOf")===!1)return!1;return!0}function fQ(b){if(Uw(b))return{...b};if(Array.isArray(b))return[...b];return b}function sA(b){let w=0;for(let $ in b)if(Object.prototype.hasOwnProperty.call(b,$))w++;return w}var aA=(b)=>{let w=typeof b;switch(w){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(b)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(b))return"array";if(b===null)return"null";if(b.then&&typeof b.then==="function"&&b.catch&&typeof b.catch==="function")return"promise";if(typeof Map<"u"&&b instanceof Map)return"map";if(typeof Set<"u"&&b instanceof Set)return"set";if(typeof Date<"u"&&b instanceof Date)return"date";if(typeof File<"u"&&b instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${w}`)}},a$=new Set(["string","number","symbol"]),gQ=new Set(["string","number","bigint","boolean","symbol","undefined"]);function ab(b){return b.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function xb(b,w,$){let Q=new b._zod.constr(w??b._zod.def);if(!w||$?.parent)Q._zod.parent=b;return Q}function _(b){let w=b;if(!w)return{};if(typeof w==="string")return{error:()=>w};if(w?.message!==void 0){if(w?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");w.error=w.message}if(delete w.message,typeof w.error==="string")return{...w,error:()=>w.error};return w}function bD(b){let w;return new Proxy({},{get($,Q,W){return w??(w=b()),Reflect.get(w,Q,W)},set($,Q,W,G){return w??(w=b()),Reflect.set(w,Q,W,G)},has($,Q){return w??(w=b()),Reflect.has(w,Q)},deleteProperty($,Q){return w??(w=b()),Reflect.deleteProperty(w,Q)},ownKeys($){return w??(w=b()),Reflect.ownKeys(w)},getOwnPropertyDescriptor($,Q){return w??(w=b()),Reflect.getOwnPropertyDescriptor(w,Q)},defineProperty($,Q,W){return w??(w=b()),Reflect.defineProperty(w,Q,W)}})}function L0(b){if(typeof b==="bigint")return b.toString()+"n";if(typeof b==="string")return`"${b}"`;return`${b}`}function b6(b){return Object.keys(b).filter((w)=>{return b[w]._zod.optin==="optional"&&b[w]._zod.optout==="optional"})}var w6={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},cQ={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function wD(b,w){let $=b._zod.def,Q=qw(b._zod.def,{get shape(){let W={};for(let G in w){if(!(G in $.shape))throw Error(`Unrecognized key: "${G}"`);if(!w[G])continue;W[G]=$.shape[G]}return Ow(this,"shape",W),W},checks:[]});return xb(b,Q)}function $D(b,w){let $=b._zod.def,Q=qw(b._zod.def,{get shape(){let W={...b._zod.def.shape};for(let G in w){if(!(G in $.shape))throw Error(`Unrecognized key: "${G}"`);if(!w[G])continue;delete W[G]}return Ow(this,"shape",W),W},checks:[]});return xb(b,Q)}function QD(b,w){if(!Uw(w))throw Error("Invalid input to extend: expected a plain object");let $=b._zod.def.checks;if($&&$.length>0)throw Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");let W=qw(b._zod.def,{get shape(){let G={...b._zod.def.shape,...w};return Ow(this,"shape",G),G},checks:[]});return xb(b,W)}function WD(b,w){if(!Uw(w))throw Error("Invalid input to safeExtend: expected a plain object");let $={...b._zod.def,get shape(){let Q={...b._zod.def.shape,...w};return Ow(this,"shape",Q),Q},checks:b._zod.def.checks};return xb(b,$)}function GD(b,w){let $=qw(b._zod.def,{get shape(){let Q={...b._zod.def.shape,...w._zod.def.shape};return Ow(this,"shape",Q),Q},get catchall(){return w._zod.def.catchall},checks:[]});return xb(b,$)}function XD(b,w,$){let Q=qw(w._zod.def,{get shape(){let W=w._zod.def.shape,G={...W};if($)for(let X in $){if(!(X in W))throw Error(`Unrecognized key: "${X}"`);if(!$[X])continue;G[X]=b?new b({type:"optional",innerType:W[X]}):W[X]}else for(let X in W)G[X]=b?new b({type:"optional",innerType:W[X]}):W[X];return Ow(this,"shape",G),G},checks:[]});return xb(w,Q)}function YD(b,w,$){let Q=qw(w._zod.def,{get shape(){let W=w._zod.def.shape,G={...W};if($)for(let X in $){if(!(X in G))throw Error(`Unrecognized key: "${X}"`);if(!$[X])continue;G[X]=new b({type:"nonoptional",innerType:W[X]})}else for(let X in W)G[X]=new b({type:"nonoptional",innerType:W[X]});return Ow(this,"shape",G),G},checks:[]});return xb(w,Q)}function Lw(b,w=0){if(b.aborted===!0)return!0;for(let $=w;$<b.issues.length;$++)if(b.issues[$]?.continue!==!0)return!0;return!1}function bw(b,w){return w.map(($)=>{var Q;return(Q=$).path??(Q.path=[]),$.path.unshift(b),$})}function O1(b){return typeof b==="string"?b:b?.message}function ub(b,w,$){let Q={...b,path:b.path??[]};if(!b.message){let W=O1(b.inst?._zod.def?.error?.(b))??O1(w?.error?.(b))??O1($.customError?.(b))??O1($.localeError?.(b))??"Invalid input";Q.message=W}if(delete Q.inst,delete Q.continue,!w?.reportInput)delete Q.input;return Q}function mQ(b){if(b instanceof Set)return"set";if(b instanceof Map)return"map";if(b instanceof File)return"file";return"unknown"}function L1(b){if(Array.isArray(b))return"array";if(typeof b==="string")return"string";return"unknown"}function gw(...b){let[w,$,Q]=b;if(typeof w==="string")return{message:w,code:"custom",input:$,inst:Q};return{...w}}function JD(b){return Object.entries(b).filter(([w,$])=>{return Number.isNaN(Number.parseInt(w,10))}).map((w)=>w[1])}function lQ(b){let w=atob(b),$=new Uint8Array(w.length);for(let Q=0;Q<w.length;Q++)$[Q]=w.charCodeAt(Q);return $}function nQ(b){let w="";for(let $=0;$<b.length;$++)w+=String.fromCharCode(b[$]);return btoa(w)}function zD(b){let w=b.replace(/-/g,"+").replace(/_/g,"/"),$="=".repeat((4-w.length%4)%4);return lQ(w+$)}function HD(b){return nQ(b).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function AD(b){let w=b.replace(/^0x/,"");if(w.length%2!==0)throw Error("Invalid hex string length");let $=new Uint8Array(w.length/2);for(let Q=0;Q<w.length;Q+=2)$[Q/2]=Number.parseInt(w.slice(Q,Q+2),16);return $}function DD(b){return Array.from(b).map((w)=>w.toString(16).padStart(2,"0")).join("")}class iQ{constructor(...b){}}var pQ=(b,w)=>{b.name="$ZodError",Object.defineProperty(b,"_zod",{value:b._zod,enumerable:!1}),Object.defineProperty(b,"issues",{value:w,enumerable:!1}),b.message=JSON.stringify(w,hw,2),Object.defineProperty(b,"toString",{value:()=>b.message,enumerable:!1})},B0=L("$ZodError",pQ),$6=L("$ZodError",pQ,{Parent:Error});function oQ(b,w=($)=>$.message){let $={},Q=[];for(let W of b.issues)if(W.path.length>0)$[W.path[0]]=$[W.path[0]]||[],$[W.path[0]].push(w(W));else Q.push(w(W));return{formErrors:Q,fieldErrors:$}}function dQ(b,w=($)=>$.message){let $={_errors:[]},Q=(W)=>{for(let G of W.issues)if(G.code==="invalid_union"&&G.errors.length)G.errors.map((X)=>Q({issues:X}));else if(G.code==="invalid_key")Q({issues:G.issues});else if(G.code==="invalid_element")Q({issues:G.issues});else if(G.path.length===0)$._errors.push(w(G));else{let X=$,Y=0;while(Y<G.path.length){let J=G.path[Y];if(Y!==G.path.length-1)X[J]=X[J]||{_errors:[]};else X[J]=X[J]||{_errors:[]},X[J]._errors.push(w(G));X=X[J],Y++}}};return Q(b),$}var K0=(b)=>(w,$,Q,W)=>{let G=Q?Object.assign(Q,{async:!1}):{async:!1},X=w._zod.run({value:$,issues:[]},G);if(X instanceof Promise)throw new sb;if(X.issues.length){let Y=new(W?.Err??b)(X.issues.map((J)=>ub(J,G,_b())));throw U0(Y,W?.callee),Y}return X.value};var F0=(b)=>async(w,$,Q,W)=>{let G=Q?Object.assign(Q,{async:!0}):{async:!0},X=w._zod.run({value:$,issues:[]},G);if(X instanceof Promise)X=await X;if(X.issues.length){let Y=new(W?.Err??b)(X.issues.map((J)=>ub(J,G,_b())));throw U0(Y,W?.callee),Y}return X.value};var B1=(b)=>(w,$,Q)=>{let W=Q?{...Q,async:!1}:{async:!1},G=w._zod.run({value:$,issues:[]},W);if(G instanceof Promise)throw new sb;return G.issues.length?{success:!1,error:new(b??B0)(G.issues.map((X)=>ub(X,W,_b())))}:{success:!0,data:G.value}},K1=B1($6),F1=(b)=>async(w,$,Q)=>{let W=Q?Object.assign(Q,{async:!0}):{async:!0},G=w._zod.run({value:$,issues:[]},W);if(G instanceof Promise)G=await G;return G.issues.length?{success:!1,error:new b(G.issues.map((X)=>ub(X,W,_b())))}:{success:!0,data:G.value}},M0=F1($6),rQ=(b)=>(w,$,Q)=>{let W=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return K0(b)(w,$,W)};var tQ=(b)=>(w,$,Q)=>{return K0(b)(w,$,Q)};var eQ=(b)=>async(w,$,Q)=>{let W=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return F0(b)(w,$,W)};var sQ=(b)=>async(w,$,Q)=>{return F0(b)(w,$,Q)};var aQ=(b)=>(w,$,Q)=>{let W=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return B1(b)(w,$,W)};var b9=(b)=>(w,$,Q)=>{return B1(b)(w,$,Q)};var w9=(b)=>async(w,$,Q)=>{let W=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return F1(b)(w,$,W)};var $9=(b)=>async(w,$,Q)=>{return F1(b)(w,$,Q)};var Q9=/^[cC][^\s-]{8,}$/,W9=/^[0-9a-z]+$/,G9=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,X9=/^[0-9a-vA-V]{20}$/,Y9=/^[A-Za-z0-9]{27}$/,J9=/^[a-zA-Z0-9_-]{21}$/,z9=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var H9=/^([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})$/,Q6=(b)=>{if(!b)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${b}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)};var A9=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function D9(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}var O9=/^(?:(?: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])$/,q9=/^(([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}|:))$/,U9=/^((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])$/,L9=/^(([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])$/,B9=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,W6=/^[A-Za-z0-9_-]*$/,K9=/^(?=.{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 F9=/^\+(?:[0-9]){6,14}[0-9]$/,M9="(?:(?:\\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])))",P9=new RegExp(`^${M9}$`);function Z9(b){return typeof b.precision==="number"?b.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":b.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${b.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function I9(b){return new RegExp(`^${Z9(b)}$`)}function V9(b){let w=Z9({precision:b.precision}),$=["Z"];if(b.local)$.push("");if(b.offset)$.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let Q=`${w}(?:${$.join("|")})`;return new RegExp(`^${M9}T(?:${Q})$`)}var j9=(b)=>{let w=b?`[\\s\\S]{${b?.minimum??0},${b?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${w}$`)};var N9=/^-?\d+$/,E9=/^-?\d+(?:\.\d+)?/,T9=/^(?:true|false)$/i,_9=/^null$/i;var S9=/^[^A-Z]*$/,R9=/^[^a-z]*$/;var zb=L("$ZodCheck",(b,w)=>{var $;b._zod??(b._zod={}),b._zod.def=w,($=b._zod).onattach??($.onattach=[])}),C9={number:"number",bigint:"bigint",object:"date"},G6=L("$ZodCheckLessThan",(b,w)=>{zb.init(b,w);let $=C9[typeof w.value];b._zod.onattach.push((Q)=>{let W=Q._zod.bag,G=(w.inclusive?W.maximum:W.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(w.value<G)if(w.inclusive)W.maximum=w.value;else W.exclusiveMaximum=w.value}),b._zod.check=(Q)=>{if(w.inclusive?Q.value<=w.value:Q.value<w.value)return;Q.issues.push({origin:$,code:"too_big",maximum:w.value,input:Q.value,inclusive:w.inclusive,inst:b,continue:!w.abort})}}),X6=L("$ZodCheckGreaterThan",(b,w)=>{zb.init(b,w);let $=C9[typeof w.value];b._zod.onattach.push((Q)=>{let W=Q._zod.bag,G=(w.inclusive?W.minimum:W.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(w.value>G)if(w.inclusive)W.minimum=w.value;else W.exclusiveMinimum=w.value}),b._zod.check=(Q)=>{if(w.inclusive?Q.value>=w.value:Q.value>w.value)return;Q.issues.push({origin:$,code:"too_small",minimum:w.value,input:Q.value,inclusive:w.inclusive,inst:b,continue:!w.abort})}}),v9=L("$ZodCheckMultipleOf",(b,w)=>{zb.init(b,w),b._zod.onattach.push(($)=>{var Q;(Q=$._zod.bag).multipleOf??(Q.multipleOf=w.value)}),b._zod.check=($)=>{if(typeof $.value!==typeof w.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof $.value==="bigint"?$.value%w.value===BigInt(0):e$($.value,w.value)===0)return;$.issues.push({origin:typeof $.value,code:"not_multiple_of",divisor:w.value,input:$.value,inst:b,continue:!w.abort})}}),k9=L("$ZodCheckNumberFormat",(b,w)=>{zb.init(b,w),w.format=w.format||"float64";let $=w.format?.includes("int"),Q=$?"int":"number",[W,G]=w6[w.format];b._zod.onattach.push((X)=>{let Y=X._zod.bag;if(Y.format=w.format,Y.minimum=W,Y.maximum=G,$)Y.pattern=N9}),b._zod.check=(X)=>{let Y=X.value;if($){if(!Number.isInteger(Y)){X.issues.push({expected:Q,format:w.format,code:"invalid_type",continue:!1,input:Y,inst:b});return}if(!Number.isSafeInteger(Y)){if(Y>0)X.issues.push({input:Y,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:b,origin:Q,continue:!w.abort});else X.issues.push({input:Y,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:b,origin:Q,continue:!w.abort});return}}if(Y<W)X.issues.push({origin:"number",input:Y,code:"too_small",minimum:W,inclusive:!0,inst:b,continue:!w.abort});if(Y>G)X.issues.push({origin:"number",input:Y,code:"too_big",maximum:G,inst:b})}});var x9=L("$ZodCheckMaxLength",(b,w)=>{var $;zb.init(b,w),($=b._zod.def).when??($.when=(Q)=>{let W=Q.value;return!q1(W)&&W.length!==void 0}),b._zod.onattach.push((Q)=>{let W=Q._zod.bag.maximum??Number.POSITIVE_INFINITY;if(w.maximum<W)Q._zod.bag.maximum=w.maximum}),b._zod.check=(Q)=>{let W=Q.value;if(W.length<=w.maximum)return;let X=L1(W);Q.issues.push({origin:X,code:"too_big",maximum:w.maximum,inclusive:!0,input:W,inst:b,continue:!w.abort})}}),u9=L("$ZodCheckMinLength",(b,w)=>{var $;zb.init(b,w),($=b._zod.def).when??($.when=(Q)=>{let W=Q.value;return!q1(W)&&W.length!==void 0}),b._zod.onattach.push((Q)=>{let W=Q._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(w.minimum>W)Q._zod.bag.minimum=w.minimum}),b._zod.check=(Q)=>{let W=Q.value;if(W.length>=w.minimum)return;let X=L1(W);Q.issues.push({origin:X,code:"too_small",minimum:w.minimum,inclusive:!0,input:W,inst:b,continue:!w.abort})}}),y9=L("$ZodCheckLengthEquals",(b,w)=>{var $;zb.init(b,w),($=b._zod.def).when??($.when=(Q)=>{let W=Q.value;return!q1(W)&&W.length!==void 0}),b._zod.onattach.push((Q)=>{let W=Q._zod.bag;W.minimum=w.length,W.maximum=w.length,W.length=w.length}),b._zod.check=(Q)=>{let W=Q.value,G=W.length;if(G===w.length)return;let X=L1(W),Y=G>w.length;Q.issues.push({origin:X,...Y?{code:"too_big",maximum:w.length}:{code:"too_small",minimum:w.length},inclusive:!0,exact:!0,input:Q.value,inst:b,continue:!w.abort})}}),M1=L("$ZodCheckStringFormat",(b,w)=>{var $,Q;if(zb.init(b,w),b._zod.onattach.push((W)=>{let G=W._zod.bag;if(G.format=w.format,w.pattern)G.patterns??(G.patterns=new Set),G.patterns.add(w.pattern)}),w.pattern)($=b._zod).check??($.check=(W)=>{if(w.pattern.lastIndex=0,w.pattern.test(W.value))return;W.issues.push({origin:"string",code:"invalid_format",format:w.format,input:W.value,...w.pattern?{pattern:w.pattern.toString()}:{},inst:b,continue:!w.abort})});else(Q=b._zod).check??(Q.check=()=>{})}),h9=L("$ZodCheckRegex",(b,w)=>{M1.init(b,w),b._zod.check=($)=>{if(w.pattern.lastIndex=0,w.pattern.test($.value))return;$.issues.push({origin:"string",code:"invalid_format",format:"regex",input:$.value,pattern:w.pattern.toString(),inst:b,continue:!w.abort})}}),f9=L("$ZodCheckLowerCase",(b,w)=>{w.pattern??(w.pattern=S9),M1.init(b,w)}),g9=L("$ZodCheckUpperCase",(b,w)=>{w.pattern??(w.pattern=R9),M1.init(b,w)}),c9=L("$ZodCheckIncludes",(b,w)=>{zb.init(b,w);let $=ab(w.includes),Q=new RegExp(typeof w.position==="number"?`^.{${w.position}}${$}`:$);w.pattern=Q,b._zod.onattach.push((W)=>{let G=W._zod.bag;G.patterns??(G.patterns=new Set),G.patterns.add(Q)}),b._zod.check=(W)=>{if(W.value.includes(w.includes,w.position))return;W.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:w.includes,input:W.value,inst:b,continue:!w.abort})}}),m9=L("$ZodCheckStartsWith",(b,w)=>{zb.init(b,w);let $=new RegExp(`^${ab(w.prefix)}.*`);w.pattern??(w.pattern=$),b._zod.onattach.push((Q)=>{let W=Q._zod.bag;W.patterns??(W.patterns=new Set),W.patterns.add($)}),b._zod.check=(Q)=>{if(Q.value.startsWith(w.prefix))return;Q.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:w.prefix,input:Q.value,inst:b,continue:!w.abort})}}),l9=L("$ZodCheckEndsWith",(b,w)=>{zb.init(b,w);let $=new RegExp(`.*${ab(w.suffix)}$`);w.pattern??(w.pattern=$),b._zod.onattach.push((Q)=>{let W=Q._zod.bag;W.patterns??(W.patterns=new Set),W.patterns.add($)}),b._zod.check=(Q)=>{if(Q.value.endsWith(w.suffix))return;Q.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:w.suffix,input:Q.value,inst:b,continue:!w.abort})}});var n9=L("$ZodCheckOverwrite",(b,w)=>{zb.init(b,w),b._zod.check=($)=>{$.value=w.tx($.value)}});class Y6{constructor(b=[]){if(this.content=[],this.indent=0,this)this.args=b}indented(b){this.indent+=1,b(this),this.indent-=1}write(b){if(typeof b==="function"){b(this,{execution:"sync"}),b(this,{execution:"async"});return}let $=b.split(`
|
|
11
|
+
`).filter((G)=>G),Q=Math.min(...$.map((G)=>G.length-G.trimStart().length)),W=$.map((G)=>G.slice(Q)).map((G)=>" ".repeat(this.indent*2)+G);for(let G of W)this.content.push(G)}compile(){let b=Function,w=this?.args,Q=[...(this?.content??[""]).map((W)=>` ${W}`)];return new b(...w,Q.join(`
|
|
12
|
+
`))}}var p9={major:4,minor:1,patch:12};var t=L("$ZodType",(b,w)=>{var $;b??(b={}),b._zod.def=w,b._zod.bag=b._zod.bag||{},b._zod.version=p9;let Q=[...b._zod.def.checks??[]];if(b._zod.traits.has("$ZodCheck"))Q.unshift(b);for(let W of Q)for(let G of W._zod.onattach)G(b);if(Q.length===0)($=b._zod).deferred??($.deferred=[]),b._zod.deferred?.push(()=>{b._zod.run=b._zod.parse});else{let W=(X,Y,J)=>{let z=Lw(X),H;for(let A of Y){if(A._zod.def.when){if(!A._zod.def.when(X))continue}else if(z)continue;let O=X.issues.length,q=A._zod.check(X);if(q instanceof Promise&&J?.async===!1)throw new sb;if(H||q instanceof Promise)H=(H??Promise.resolve()).then(async()=>{if(await q,X.issues.length===O)return;if(!z)z=Lw(X,O)});else{if(X.issues.length===O)continue;if(!z)z=Lw(X,O)}}if(H)return H.then(()=>{return X});return X},G=(X,Y,J)=>{if(Lw(X))return X.aborted=!0,X;let z=W(Y,Q,J);if(z instanceof Promise){if(J.async===!1)throw new sb;return z.then((H)=>b._zod.parse(H,J))}return b._zod.parse(z,J)};b._zod.run=(X,Y)=>{if(Y.skipChecks)return b._zod.parse(X,Y);if(Y.direction==="backward"){let z=b._zod.parse({value:X.value,issues:[]},{...Y,skipChecks:!0});if(z instanceof Promise)return z.then((H)=>{return G(H,X,Y)});return G(z,X,Y)}let J=b._zod.parse(X,Y);if(J instanceof Promise){if(Y.async===!1)throw new sb;return J.then((z)=>W(z,Q,Y))}return W(J,Q,Y)}}b["~standard"]={validate:(W)=>{try{let G=K1(b,W);return G.success?{value:G.data}:{issues:G.error?.issues}}catch(G){return M0(b,W).then((X)=>X.success?{value:X.data}:{issues:X.error?.issues})}},vendor:"zod",version:1}}),V0=L("$ZodString",(b,w)=>{t.init(b,w),b._zod.pattern=[...b?._zod.bag?.patterns??[]].pop()??j9(b._zod.bag),b._zod.parse=($,Q)=>{if(w.coerce)try{$.value=String($.value)}catch(W){}if(typeof $.value==="string")return $;return $.issues.push({expected:"string",code:"invalid_type",input:$.value,inst:b}),$}}),e=L("$ZodStringFormat",(b,w)=>{M1.init(b,w),V0.init(b,w)}),wW=L("$ZodGUID",(b,w)=>{w.pattern??(w.pattern=H9),e.init(b,w)}),$W=L("$ZodUUID",(b,w)=>{if(w.version){let Q={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[w.version];if(Q===void 0)throw Error(`Invalid UUID version: "${w.version}"`);w.pattern??(w.pattern=Q6(Q))}else w.pattern??(w.pattern=Q6());e.init(b,w)}),QW=L("$ZodEmail",(b,w)=>{w.pattern??(w.pattern=A9),e.init(b,w)}),WW=L("$ZodURL",(b,w)=>{e.init(b,w),b._zod.check=($)=>{try{let Q=$.value.trim(),W=new URL(Q);if(w.hostname){if(w.hostname.lastIndex=0,!w.hostname.test(W.hostname))$.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:K9.source,input:$.value,inst:b,continue:!w.abort})}if(w.protocol){if(w.protocol.lastIndex=0,!w.protocol.test(W.protocol.endsWith(":")?W.protocol.slice(0,-1):W.protocol))$.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:w.protocol.source,input:$.value,inst:b,continue:!w.abort})}if(w.normalize)$.value=W.href;else $.value=Q;return}catch(Q){$.issues.push({code:"invalid_format",format:"url",input:$.value,inst:b,continue:!w.abort})}}}),GW=L("$ZodEmoji",(b,w)=>{w.pattern??(w.pattern=D9()),e.init(b,w)}),XW=L("$ZodNanoID",(b,w)=>{w.pattern??(w.pattern=J9),e.init(b,w)}),YW=L("$ZodCUID",(b,w)=>{w.pattern??(w.pattern=Q9),e.init(b,w)}),JW=L("$ZodCUID2",(b,w)=>{w.pattern??(w.pattern=W9),e.init(b,w)}),zW=L("$ZodULID",(b,w)=>{w.pattern??(w.pattern=G9),e.init(b,w)}),HW=L("$ZodXID",(b,w)=>{w.pattern??(w.pattern=X9),e.init(b,w)}),AW=L("$ZodKSUID",(b,w)=>{w.pattern??(w.pattern=Y9),e.init(b,w)}),DW=L("$ZodISODateTime",(b,w)=>{w.pattern??(w.pattern=V9(w)),e.init(b,w)}),OW=L("$ZodISODate",(b,w)=>{w.pattern??(w.pattern=P9),e.init(b,w)}),qW=L("$ZodISOTime",(b,w)=>{w.pattern??(w.pattern=I9(w)),e.init(b,w)}),UW=L("$ZodISODuration",(b,w)=>{w.pattern??(w.pattern=z9),e.init(b,w)}),LW=L("$ZodIPv4",(b,w)=>{w.pattern??(w.pattern=O9),e.init(b,w),b._zod.onattach.push(($)=>{let Q=$._zod.bag;Q.format="ipv4"})}),BW=L("$ZodIPv6",(b,w)=>{w.pattern??(w.pattern=q9),e.init(b,w),b._zod.onattach.push(($)=>{let Q=$._zod.bag;Q.format="ipv6"}),b._zod.check=($)=>{try{new URL(`http://[${$.value}]`)}catch{$.issues.push({code:"invalid_format",format:"ipv6",input:$.value,inst:b,continue:!w.abort})}}}),KW=L("$ZodCIDRv4",(b,w)=>{w.pattern??(w.pattern=U9),e.init(b,w)}),FW=L("$ZodCIDRv6",(b,w)=>{w.pattern??(w.pattern=L9),e.init(b,w),b._zod.check=($)=>{let Q=$.value.split("/");try{if(Q.length!==2)throw Error();let[W,G]=Q;if(!G)throw Error();let X=Number(G);if(`${X}`!==G)throw Error();if(X<0||X>128)throw Error();new URL(`http://[${W}]`)}catch{$.issues.push({code:"invalid_format",format:"cidrv6",input:$.value,inst:b,continue:!w.abort})}}});function MW(b){if(b==="")return!0;if(b.length%4!==0)return!1;try{return atob(b),!0}catch{return!1}}var PW=L("$ZodBase64",(b,w)=>{w.pattern??(w.pattern=B9),e.init(b,w),b._zod.onattach.push(($)=>{$._zod.bag.contentEncoding="base64"}),b._zod.check=($)=>{if(MW($.value))return;$.issues.push({code:"invalid_format",format:"base64",input:$.value,inst:b,continue:!w.abort})}});function LD(b){if(!W6.test(b))return!1;let w=b.replace(/[-_]/g,(Q)=>Q==="-"?"+":"/"),$=w.padEnd(Math.ceil(w.length/4)*4,"=");return MW($)}var ZW=L("$ZodBase64URL",(b,w)=>{w.pattern??(w.pattern=W6),e.init(b,w),b._zod.onattach.push(($)=>{$._zod.bag.contentEncoding="base64url"}),b._zod.check=($)=>{if(LD($.value))return;$.issues.push({code:"invalid_format",format:"base64url",input:$.value,inst:b,continue:!w.abort})}}),IW=L("$ZodE164",(b,w)=>{w.pattern??(w.pattern=F9),e.init(b,w)});function BD(b,w=null){try{let $=b.split(".");if($.length!==3)return!1;let[Q]=$;if(!Q)return!1;let W=JSON.parse(atob(Q));if("typ"in W&&W?.typ!=="JWT")return!1;if(!W.alg)return!1;if(w&&(!("alg"in W)||W.alg!==w))return!1;return!0}catch{return!1}}var VW=L("$ZodJWT",(b,w)=>{e.init(b,w),b._zod.check=($)=>{if(BD($.value,w.alg))return;$.issues.push({code:"invalid_format",format:"jwt",input:$.value,inst:b,continue:!w.abort})}});var z6=L("$ZodNumber",(b,w)=>{t.init(b,w),b._zod.pattern=b._zod.bag.pattern??E9,b._zod.parse=($,Q)=>{if(w.coerce)try{$.value=Number($.value)}catch(X){}let W=$.value;if(typeof W==="number"&&!Number.isNaN(W)&&Number.isFinite(W))return $;let G=typeof W==="number"?Number.isNaN(W)?"NaN":!Number.isFinite(W)?"Infinity":void 0:void 0;return $.issues.push({expected:"number",code:"invalid_type",input:W,inst:b,...G?{received:G}:{}}),$}}),jW=L("$ZodNumber",(b,w)=>{k9.init(b,w),z6.init(b,w)}),NW=L("$ZodBoolean",(b,w)=>{t.init(b,w),b._zod.pattern=T9,b._zod.parse=($,Q)=>{if(w.coerce)try{$.value=Boolean($.value)}catch(G){}let W=$.value;if(typeof W==="boolean")return $;return $.issues.push({expected:"boolean",code:"invalid_type",input:W,inst:b}),$}});var EW=L("$ZodNull",(b,w)=>{t.init(b,w),b._zod.pattern=_9,b._zod.values=new Set([null]),b._zod.parse=($,Q)=>{let W=$.value;if(W===null)return $;return $.issues.push({expected:"null",code:"invalid_type",input:W,inst:b}),$}});var TW=L("$ZodUnknown",(b,w)=>{t.init(b,w),b._zod.parse=($)=>$}),_W=L("$ZodNever",(b,w)=>{t.init(b,w),b._zod.parse=($,Q)=>{return $.issues.push({expected:"never",code:"invalid_type",input:$.value,inst:b}),$}});function o9(b,w,$){if(b.issues.length)w.issues.push(...bw($,b.issues));w.value[$]=b.value}var SW=L("$ZodArray",(b,w)=>{t.init(b,w),b._zod.parse=($,Q)=>{let W=$.value;if(!Array.isArray(W))return $.issues.push({expected:"array",code:"invalid_type",input:W,inst:b}),$;$.value=Array(W.length);let G=[];for(let X=0;X<W.length;X++){let Y=W[X],J=w.element._zod.run({value:Y,issues:[]},Q);if(J instanceof Promise)G.push(J.then((z)=>o9(z,$,X)));else o9(J,$,X)}if(G.length)return Promise.all(G).then(()=>$);return $}});function I0(b,w,$,Q){if(b.issues.length)w.issues.push(...bw($,b.issues));if(b.value===void 0){if($ in Q)w.value[$]=void 0}else w.value[$]=b.value}function RW(b){let w=Object.keys(b.shape);for(let Q of w)if(!b.shape?.[Q]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${Q}": expected a Zod schema`);let $=b6(b.shape);return{...b,keys:w,keySet:new Set(w),numKeys:w.length,optionalKeys:new Set($)}}function CW(b,w,$,Q,W,G){let X=[],Y=W.keySet,J=W.catchall._zod,z=J.def.type;for(let H of Object.keys(w)){if(Y.has(H))continue;if(z==="never"){X.push(H);continue}let A=J.run({value:w[H],issues:[]},Q);if(A instanceof Promise)b.push(A.then((O)=>I0(O,$,H,w)));else I0(A,$,H,w)}if(X.length)$.issues.push({code:"unrecognized_keys",keys:X,input:w,inst:G});if(!b.length)return $;return Promise.all(b).then(()=>{return $})}var KD=L("$ZodObject",(b,w)=>{if(t.init(b,w),!Object.getOwnPropertyDescriptor(w,"shape")?.get){let Y=w.shape;Object.defineProperty(w,"shape",{get:()=>{let J={...Y};return Object.defineProperty(w,"shape",{value:J}),J}})}let Q=fw(()=>RW(w));o(b._zod,"propValues",()=>{let Y=w.shape,J={};for(let z in Y){let H=Y[z]._zod;if(H.values){J[z]??(J[z]=new Set);for(let A of H.values)J[z].add(A)}}return J});let W=Sw,G=w.catchall,X;b._zod.parse=(Y,J)=>{X??(X=Q.value);let z=Y.value;if(!W(z))return Y.issues.push({expected:"object",code:"invalid_type",input:z,inst:b}),Y;Y.value={};let H=[],A=X.shape;for(let O of X.keys){let B=A[O]._zod.run({value:z[O],issues:[]},J);if(B instanceof Promise)H.push(B.then((K)=>I0(K,Y,O,z)));else I0(B,Y,O,z)}if(!G)return H.length?Promise.all(H).then(()=>Y):Y;return CW(H,z,Y,J,Q.value,b)}}),vW=L("$ZodObjectJIT",(b,w)=>{KD.init(b,w);let $=b._zod.parse,Q=fw(()=>RW(w)),W=(O)=>{let q=new Y6(["shape","payload","ctx"]),B=Q.value,K=(S)=>{let h=q0(S);return`shape[${h}]._zod.run({ value: input[${h}], issues: [] }, ctx)`};q.write("const input = payload.value;");let Z=Object.create(null),P=0;for(let S of B.keys)Z[S]=`key_${P++}`;q.write("const newResult = {};");for(let S of B.keys){let h=Z[S],R=q0(S);q.write(`const ${h} = ${K(S)};`),q.write(`
|
|
13
|
+
if (${h}.issues.length) {
|
|
14
|
+
payload.issues = payload.issues.concat(${h}.issues.map(iss => ({
|
|
15
15
|
...iss,
|
|
16
|
-
path: iss.path ? [${
|
|
16
|
+
path: iss.path ? [${R}, ...iss.path] : [${R}]
|
|
17
17
|
})));
|
|
18
18
|
}
|
|
19
19
|
|
|
20
20
|
|
|
21
|
-
if (${
|
|
22
|
-
if (${
|
|
23
|
-
newResult[${
|
|
21
|
+
if (${h}.value === undefined) {
|
|
22
|
+
if (${R} in input) {
|
|
23
|
+
newResult[${R}] = undefined;
|
|
24
24
|
}
|
|
25
25
|
} else {
|
|
26
|
-
newResult[${
|
|
26
|
+
newResult[${R}] = ${h}.value;
|
|
27
27
|
}
|
|
28
28
|
|
|
29
|
-
`)}L.write("payload.value = newResult;"),L.write("return payload;");let k=L.compile();return(R,y)=>k(D,R,y)},$,z=j1,J=!Y6.jitless,A=J&&vQ.value,U=Y.catchall,K;Q._zod.parse=(D,L)=>{K??(K=G.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(!$)$=W(Y.shape);if(D=$(D,L),!U)return D;return MW([],O,D,L,K,Q)}return X(D,L)}});function x8(Q,Y,X,G){for(let $ of Q)if($.issues.length===0)return Y.value=$.value,Y;let W=Q.filter(($)=>!A1($));if(W.length===1)return Y.value=W[0].value,W[0];return Y.issues.push({code:"invalid_union",input:Y.value,inst:X,errors:Q.map(($)=>$.issues.map((z)=>x0(z,G,T0())))}),Y}var iQ=q("$ZodUnion",(Q,Y)=>{t.init(Q,Y),r(Q._zod,"optin",()=>Y.options.some((W)=>W._zod.optin==="optional")?"optional":void 0),r(Q._zod,"optout",()=>Y.options.some((W)=>W._zod.optout==="optional")?"optional":void 0),r(Q._zod,"values",()=>{if(Y.options.every((W)=>W._zod.values))return new Set(Y.options.flatMap((W)=>Array.from(W._zod.values)));return}),r(Q._zod,"pattern",()=>{if(Y.options.every((W)=>W._zod.pattern)){let W=Y.options.map(($)=>$._zod.pattern);return new RegExp(`^(${W.map(($)=>J4($.source)).join("|")})$`)}return});let X=Y.options.length===1,G=Y.options[0]._zod.run;Q._zod.parse=(W,$)=>{if(X)return G(W,$);let z=!1,J=[];for(let H of Y.options){let A=H._zod.run({value:W.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 x8(J,W,Q,$);return Promise.all(J).then((H)=>{return x8(H,W,Q,$)})}}),ZW=q("$ZodDiscriminatedUnion",(Q,Y)=>{iQ.init(Q,Y);let X=Q._zod.parse;r(Q._zod,"propValues",()=>{let W={};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(!W[J])W[J]=new Set;for(let A of H)W[J].add(A)}}return W});let G=g1(()=>{let W=Y.options,$=new Map;for(let z of W){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=(W,$)=>{let z=W.value;if(!j1(z))return W.issues.push({code:"invalid_type",expected:"object",input:z,inst:Q}),W;let J=G.value.get(z?.[Y.discriminator]);if(J)return J._zod.run(W,$);if(Y.unionFallback)return X(W,$);return W.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:Y.discriminator,input:z,path:[Y.discriminator],inst:Q}),W}}),NW=q("$ZodIntersection",(Q,Y)=>{t.init(Q,Y),Q._zod.parse=(X,G)=>{let W=X.value,$=Y.left._zod.run({value:W,issues:[]},G),z=Y.right._zod.run({value:W,issues:[]},G);if($ instanceof Promise||z instanceof Promise)return Promise.all([$,z]).then(([H,A])=>{return _8(X,H,A)});return _8(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),G=Object.keys(Q).filter(($)=>X.indexOf($)!==-1),W={...Q,...Y};for(let $ of G){let z=cQ(Q[$],Y[$]);if(!z.valid)return{valid:!1,mergeErrorPath:[$,...z.mergeErrorPath]};W[$]=z.data}return{valid:!0,data:W}}if(Array.isArray(Q)&&Array.isArray(Y)){if(Q.length!==Y.length)return{valid:!1,mergeErrorPath:[]};let X=[];for(let G=0;G<Q.length;G++){let W=Q[G],$=Y[G],z=cQ(W,$);if(!z.valid)return{valid:!1,mergeErrorPath:[G,...z.mergeErrorPath]};X.push(z.data)}return{valid:!0,data:X}}return{valid:!1,mergeErrorPath:[]}}function _8(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 G=cQ(Y.value,X.value);if(!G.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(G.mergeErrorPath)}`);return Q.value=G.data,Q}var wW=q("$ZodRecord",(Q,Y)=>{t.init(Q,Y),Q._zod.parse=(X,G)=>{let W=X.value;if(!H1(W))return X.issues.push({expected:"record",code:"invalid_type",input:W,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:W[H],issues:[]},G);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 W)if(!z.has(H))J=J??[],J.push(H);if(J&&J.length>0)X.issues.push({code:"unrecognized_keys",input:W,inst:Q,keys:J})}else{X.value={};for(let z of Reflect.ownKeys(W)){if(z==="__proto__")continue;let J=Y.keyType._zod.run({value:z,issues:[]},G);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,G,T0())),input:z,path:[z],inst:Q}),X.value[J.value]=J.value;continue}let H=Y.valueType._zod.run({value:W[z],issues:[]},G);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 PW=q("$ZodEnum",(Q,Y)=>{t.init(Q,Y);let X=CQ(Y.entries),G=new Set(X);Q._zod.values=G,Q._zod.pattern=new RegExp(`^(${X.filter((W)=>xQ.has(typeof W)).map((W)=>typeof W==="string"?a0(W):W.toString()).join("|")})$`),Q._zod.parse=(W,$)=>{let z=W.value;if(G.has(z))return W;return W.issues.push({code:"invalid_value",values:X,input:z,inst:Q}),W}}),bW=q("$ZodLiteral",(Q,Y)=>{if(t.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,G)=>{let W=X.value;if(Q._zod.values.has(W))return X;return X.issues.push({code:"invalid_value",values:Y.values,input:W,inst:Q}),X}});var jW=q("$ZodTransform",(Q,Y)=>{t.init(Q,Y),Q._zod.parse=(X,G)=>{if(G.direction==="backward")throw new G4(Q.constructor.name);let W=Y.transform(X.value,X);if(G.async)return(W instanceof Promise?W:Promise.resolve(W)).then((z)=>{return X.value=z,X});if(W instanceof Promise)throw new t0;return X.value=W,X}});function g8(Q,Y){if(Q.issues.length&&Y===void 0)return{issues:[],value:void 0};return Q}var IW=q("$ZodOptional",(Q,Y)=>{t.init(Q,Y),Q._zod.optin="optional",Q._zod.optout="optional",r(Q._zod,"values",()=>{return Y.innerType._zod.values?new Set([...Y.innerType._zod.values,void 0]):void 0}),r(Q._zod,"pattern",()=>{let X=Y.innerType._zod.pattern;return X?new RegExp(`^(${J4(X.source)})?$`):void 0}),Q._zod.parse=(X,G)=>{if(Y.innerType._zod.optin==="optional"){let W=Y.innerType._zod.run(X,G);if(W instanceof Promise)return W.then(($)=>g8($,X.value));return g8(W,X.value)}if(X.value===void 0)return X;return Y.innerType._zod.run(X,G)}}),EW=q("$ZodNullable",(Q,Y)=>{t.init(Q,Y),r(Q._zod,"optin",()=>Y.innerType._zod.optin),r(Q._zod,"optout",()=>Y.innerType._zod.optout),r(Q._zod,"pattern",()=>{let X=Y.innerType._zod.pattern;return X?new RegExp(`^(${J4(X.source)}|null)$`):void 0}),r(Q._zod,"values",()=>{return Y.innerType._zod.values?new Set([...Y.innerType._zod.values,null]):void 0}),Q._zod.parse=(X,G)=>{if(X.value===null)return X;return Y.innerType._zod.run(X,G)}}),TW=q("$ZodDefault",(Q,Y)=>{t.init(Q,Y),Q._zod.optin="optional",r(Q._zod,"values",()=>Y.innerType._zod.values),Q._zod.parse=(X,G)=>{if(G.direction==="backward")return Y.innerType._zod.run(X,G);if(X.value===void 0)return X.value=Y.defaultValue,X;let W=Y.innerType._zod.run(X,G);if(W instanceof Promise)return W.then(($)=>y8($,Y));return y8(W,Y)}});function y8(Q,Y){if(Q.value===void 0)Q.value=Y.defaultValue;return Q}var SW=q("$ZodPrefault",(Q,Y)=>{t.init(Q,Y),Q._zod.optin="optional",r(Q._zod,"values",()=>Y.innerType._zod.values),Q._zod.parse=(X,G)=>{if(G.direction==="backward")return Y.innerType._zod.run(X,G);if(X.value===void 0)X.value=Y.defaultValue;return Y.innerType._zod.run(X,G)}}),RW=q("$ZodNonOptional",(Q,Y)=>{t.init(Q,Y),r(Q._zod,"values",()=>{let X=Y.innerType._zod.values;return X?new Set([...X].filter((G)=>G!==void 0)):void 0}),Q._zod.parse=(X,G)=>{let W=Y.innerType._zod.run(X,G);if(W instanceof Promise)return W.then(($)=>u8($,Q));return u8(W,Q)}});function u8(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 CW=q("$ZodCatch",(Q,Y)=>{t.init(Q,Y),r(Q._zod,"optin",()=>Y.innerType._zod.optin),r(Q._zod,"optout",()=>Y.innerType._zod.optout),r(Q._zod,"values",()=>Y.innerType._zod.values),Q._zod.parse=(X,G)=>{if(G.direction==="backward")return Y.innerType._zod.run(X,G);let W=Y.innerType._zod.run(X,G);if(W instanceof Promise)return W.then(($)=>{if(X.value=$.value,$.issues.length)X.value=Y.catchValue({...X,error:{issues:$.issues.map((z)=>x0(z,G,T0()))},input:X.value}),X.issues=[];return X});if(X.value=W.value,W.issues.length)X.value=Y.catchValue({...X,error:{issues:W.issues.map(($)=>x0($,G,T0()))},input:X.value}),X.issues=[];return X}});var kW=q("$ZodPipe",(Q,Y)=>{t.init(Q,Y),r(Q._zod,"values",()=>Y.in._zod.values),r(Q._zod,"optin",()=>Y.in._zod.optin),r(Q._zod,"optout",()=>Y.out._zod.optout),r(Q._zod,"propValues",()=>Y.in._zod.propValues),Q._zod.parse=(X,G)=>{if(G.direction==="backward"){let $=Y.out._zod.run(X,G);if($ instanceof Promise)return $.then((z)=>K6(z,Y.in,G));return K6($,Y.in,G)}let W=Y.in._zod.run(X,G);if(W instanceof Promise)return W.then(($)=>K6($,Y.out,G));return K6(W,Y.out,G)}});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 vW=q("$ZodReadonly",(Q,Y)=>{t.init(Q,Y),r(Q._zod,"propValues",()=>Y.innerType._zod.propValues),r(Q._zod,"values",()=>Y.innerType._zod.values),r(Q._zod,"optin",()=>Y.innerType._zod.optin),r(Q._zod,"optout",()=>Y.innerType._zod.optout),Q._zod.parse=(X,G)=>{if(G.direction==="backward")return Y.innerType._zod.run(X,G);let W=Y.innerType._zod.run(X,G);if(W instanceof Promise)return W.then(h8);return h8(W)}});function h8(Q){return Q.value=Object.freeze(Q.value),Q}var xW=q("$ZodCustom",(Q,Y)=>{A0.init(Q,Y),t.init(Q,Y),Q._zod.parse=(X,G)=>{return X},Q._zod.check=(X)=>{let G=X.value,W=Y.fn(G);if(W instanceof Promise)return W.then(($)=>f8($,X,G,Q));f8(W,X,G,Q);return}});function f8(Q,Y,X,G){if(!Q){let W={code:"custom",input:X,inst:G,path:[...G._zod.def.path??[]],continue:!G._zod.def.abort};if(G._zod.def.params)W.params=G._zod.def.params;Y.issues.push(y1(W))}}var VA=(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},ZA=()=>{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(G){return Q[G]??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(G)=>{switch(G.code){case"invalid_type":return`Invalid input: expected ${G.expected}, received ${VA(G.input)}`;case"invalid_value":if(G.values.length===1)return`Invalid input: expected ${$6(G.values[0])}`;return`Invalid option: expected one of ${X6(G.values,"|")}`;case"too_big":{let W=G.inclusive?"<=":"<",$=Y(G.origin);if($)return`Too big: expected ${G.origin??"value"} to have ${W}${G.maximum.toString()} ${$.unit??"elements"}`;return`Too big: expected ${G.origin??"value"} to be ${W}${G.maximum.toString()}`}case"too_small":{let W=G.inclusive?">=":">",$=Y(G.origin);if($)return`Too small: expected ${G.origin} to have ${W}${G.minimum.toString()} ${$.unit}`;return`Too small: expected ${G.origin} to be ${W}${G.minimum.toString()}`}case"invalid_format":{let W=G;if(W.format==="starts_with")return`Invalid string: must start with "${W.prefix}"`;if(W.format==="ends_with")return`Invalid string: must end with "${W.suffix}"`;if(W.format==="includes")return`Invalid string: must include "${W.includes}"`;if(W.format==="regex")return`Invalid string: must match pattern ${W.pattern}`;return`Invalid ${X[W.format]??G.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${G.divisor}`;case"unrecognized_keys":return`Unrecognized key${G.keys.length>1?"s":""}: ${X6(G.keys,", ")}`;case"invalid_key":return`Invalid key in ${G.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${G.origin}`;default:return"Invalid input"}}};function nQ(){return{localeError:ZA()}}var rZ=Symbol("ZodOutput"),dZ=Symbol("ZodInput");class _W{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 G={...X,...this._map.get(Q)};return Object.keys(G).length?G:void 0}return this._map.get(Q)}has(Q){return this._map.has(Q)}}function NA(){return new _W}var B4=NA();function gW(Q,Y){return new Q({type:"string",...S(Y)})}function yW(Q,Y){return new Q({type:"string",format:"email",check:"string_format",abort:!1,...S(Y)})}function rQ(Q,Y){return new Q({type:"string",format:"guid",check:"string_format",abort:!1,...S(Y)})}function uW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,...S(Y)})}function hW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...S(Y)})}function fW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...S(Y)})}function lW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...S(Y)})}function mW(Q,Y){return new Q({type:"string",format:"url",check:"string_format",abort:!1,...S(Y)})}function cW(Q,Y){return new Q({type:"string",format:"emoji",check:"string_format",abort:!1,...S(Y)})}function pW(Q,Y){return new Q({type:"string",format:"nanoid",check:"string_format",abort:!1,...S(Y)})}function iW(Q,Y){return new Q({type:"string",format:"cuid",check:"string_format",abort:!1,...S(Y)})}function nW(Q,Y){return new Q({type:"string",format:"cuid2",check:"string_format",abort:!1,...S(Y)})}function rW(Q,Y){return new Q({type:"string",format:"ulid",check:"string_format",abort:!1,...S(Y)})}function dW(Q,Y){return new Q({type:"string",format:"xid",check:"string_format",abort:!1,...S(Y)})}function oW(Q,Y){return new Q({type:"string",format:"ksuid",check:"string_format",abort:!1,...S(Y)})}function tW(Q,Y){return new Q({type:"string",format:"ipv4",check:"string_format",abort:!1,...S(Y)})}function aW(Q,Y){return new Q({type:"string",format:"ipv6",check:"string_format",abort:!1,...S(Y)})}function sW(Q,Y){return new Q({type:"string",format:"cidrv4",check:"string_format",abort:!1,...S(Y)})}function eW(Q,Y){return new Q({type:"string",format:"cidrv6",check:"string_format",abort:!1,...S(Y)})}function QG(Q,Y){return new Q({type:"string",format:"base64",check:"string_format",abort:!1,...S(Y)})}function YG(Q,Y){return new Q({type:"string",format:"base64url",check:"string_format",abort:!1,...S(Y)})}function XG(Q,Y){return new Q({type:"string",format:"e164",check:"string_format",abort:!1,...S(Y)})}function WG(Q,Y){return new Q({type:"string",format:"jwt",check:"string_format",abort:!1,...S(Y)})}function GG(Q,Y){return new Q({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...S(Y)})}function $G(Q,Y){return new Q({type:"string",format:"date",check:"string_format",...S(Y)})}function zG(Q,Y){return new Q({type:"string",format:"time",check:"string_format",precision:null,...S(Y)})}function JG(Q,Y){return new Q({type:"string",format:"duration",check:"string_format",...S(Y)})}function HG(Q,Y){return new Q({type:"number",checks:[],...S(Y)})}function AG(Q,Y){return new Q({type:"number",check:"number_format",abort:!1,format:"safeint",...S(Y)})}function UG(Q,Y){return new Q({type:"boolean",...S(Y)})}function KG(Q,Y){return new Q({type:"null",...S(Y)})}function DG(Q){return new Q({type:"unknown"})}function BG(Q,Y){return new Q({type:"never",...S(Y)})}function L6(Q,Y){return new fQ({check:"less_than",...S(Y),value:Q,inclusive:!1})}function L4(Q,Y){return new fQ({check:"less_than",...S(Y),value:Q,inclusive:!0})}function F6(Q,Y){return new lQ({check:"greater_than",...S(Y),value:Q,inclusive:!1})}function F4(Q,Y){return new lQ({check:"greater_than",...S(Y),value:Q,inclusive:!0})}function q6(Q,Y){return new V8({check:"multiple_of",...S(Y),value:Q})}function O6(Q,Y){return new N8({check:"max_length",...S(Y),maximum:Q})}function u1(Q,Y){return new w8({check:"min_length",...S(Y),minimum:Q})}function M6(Q,Y){return new P8({check:"length_equals",...S(Y),length:Q})}function dQ(Q,Y){return new b8({check:"string_format",format:"regex",...S(Y),pattern:Q})}function oQ(Q){return new j8({check:"string_format",format:"lowercase",...S(Q)})}function tQ(Q){return new I8({check:"string_format",format:"uppercase",...S(Q)})}function aQ(Q,Y){return new E8({check:"string_format",format:"includes",...S(Y),includes:Q})}function sQ(Q,Y){return new T8({check:"string_format",format:"starts_with",...S(Y),prefix:Q})}function eQ(Q,Y){return new S8({check:"string_format",format:"ends_with",...S(Y),suffix:Q})}function I1(Q){return new R8({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 LG(Q,Y,X){return new Q({type:"array",element:Y,...S(X)})}function FG(Q,Y,X){let G=S(X);return G.abort??(G.abort=!0),new Q({type:"custom",check:"custom",fn:Y,...G})}function qG(Q,Y,X){return new Q({type:"custom",check:"custom",fn:Y,...S(X)})}function OG(Q){let Y=wA((X)=>{return X.addIssue=(G)=>{if(typeof G==="string")X.issues.push(y1(G,X.value,Y._zod.def));else{let W=G;if(W.fatal)W.continue=!1;W.code??(W.code="custom"),W.input??(W.input=X.value),W.inst??(W.inst=Y),W.continue??(W.continue=!Y._zod.def.abort),X.issues.push(y1(W))}},Q(X.value,X)});return Y}function wA(Q,Y){let X=new A0({check:"custom",...S(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 MG(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 G=Q.value;if(G!==void 0)return G;return}var O4={};OX(O4,{time:()=>z9,duration:()=>J9,datetime:()=>G9,date:()=>$9,ZodISOTime:()=>NG,ZodISODuration:()=>wG,ZodISODateTime:()=>VG,ZodISODate:()=>ZG});var VG=q("ZodISODateTime",(Q,Y)=>{s8.init(Q,Y),e.init(Q,Y)});function G9(Q){return GG(VG,Q)}var ZG=q("ZodISODate",(Q,Y)=>{e8.init(Q,Y),e.init(Q,Y)});function $9(Q){return $G(ZG,Q)}var NG=q("ZodISOTime",(Q,Y)=>{QW.init(Q,Y),e.init(Q,Y)});function z9(Q){return zG(NG,Q)}var wG=q("ZodISODuration",(Q,Y)=>{YW.init(Q,Y),e.init(Q,Y)});function J9(Q){return JG(wG,Q)}var PG=(Q,Y)=>{z6.init(Q,Y),Q.name="ZodError",Object.defineProperties(Q,{format:{value:(X)=>xX(Q,X)},flatten:{value:(X)=>vX(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}}})},vN=q("ZodError",PG),I0=q("ZodError",PG,{Parent:Error});var bG=J6(I0),jG=H6(I0),IG=A4(I0),EG=K4(I0),TG=_X(I0),SG=gX(I0),RG=yX(I0),CG=uX(I0),kG=hX(I0),vG=fX(I0),xG=lX(I0),_G=mX(I0);var G0=q("ZodType",(Q,Y)=>{return t.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((G)=>typeof G==="function"?{_zod:{check:G,def:{check:"custom"},onattach:[]}}:G)]}))},Q.clone=(X,G)=>v0(Q,X,G),Q.brand=()=>Q,Q.register=(X,G)=>{return X.add(Q,G),Q},Q.parse=(X,G)=>bG(Q,X,G,{callee:Q.parse}),Q.safeParse=(X,G)=>IG(Q,X,G),Q.parseAsync=async(X,G)=>jG(Q,X,G,{callee:Q.parseAsync}),Q.safeParseAsync=async(X,G)=>EG(Q,X,G),Q.spa=Q.safeParseAsync,Q.encode=(X,G)=>TG(Q,X,G),Q.decode=(X,G)=>SG(Q,X,G),Q.encodeAsync=async(X,G)=>RG(Q,X,G),Q.decodeAsync=async(X,G)=>CG(Q,X,G),Q.safeEncode=(X,G)=>kG(Q,X,G),Q.safeDecode=(X,G)=>vG(Q,X,G),Q.safeEncodeAsync=async(X,G)=>xG(Q,X,G),Q.safeDecodeAsync=async(X,G)=>_G(Q,X,G),Q.refine=(X,G)=>Q.check(M3(X,G)),Q.superRefine=(X)=>Q.check(V3(X)),Q.overwrite=(X)=>Q.check(I1(X)),Q.optional=()=>W0(Q),Q.nullable=()=>uG(Q),Q.nullish=()=>W0(uG(Q)),Q.nonoptional=(X)=>D3(Q,X),Q.array=()=>u(Q),Q.or=(X)=>o([Q,X]),Q.and=(X)=>N6(Q,X),Q.transform=(X)=>A9(Q,cG(X)),Q.default=(X)=>A3(Q,X),Q.prefault=(X)=>K3(Q,X),Q.catch=(X)=>L3(Q,X),Q.pipe=(X)=>A9(Q,X),Q.readonly=()=>O3(Q),Q.describe=(X)=>{let G=Q.clone();return B4.add(G,{description:X}),G},Object.defineProperty(Q,"description",{get(){return B4.get(Q)?.description},configurable:!0}),Q.meta=(...X)=>{if(X.length===0)return B4.get(Q);let G=Q.clone();return B4.add(G,X[0]),G},Q.isOptional=()=>Q.safeParse(void 0).success,Q.isNullable=()=>Q.safeParse(null).success,Q}),hG=q("_ZodString",(Q,Y)=>{B6.init(Q,Y),G0.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=(...G)=>Q.check(dQ(...G)),Q.includes=(...G)=>Q.check(aQ(...G)),Q.startsWith=(...G)=>Q.check(sQ(...G)),Q.endsWith=(...G)=>Q.check(eQ(...G)),Q.min=(...G)=>Q.check(u1(...G)),Q.max=(...G)=>Q.check(O6(...G)),Q.length=(...G)=>Q.check(M6(...G)),Q.nonempty=(...G)=>Q.check(u1(1,...G)),Q.lowercase=(G)=>Q.check(oQ(G)),Q.uppercase=(G)=>Q.check(tQ(G)),Q.trim=()=>Q.check(Y9()),Q.normalize=(...G)=>Q.check(Q9(...G)),Q.toLowerCase=()=>Q.check(X9()),Q.toUpperCase=()=>Q.check(W9())}),CA=q("ZodString",(Q,Y)=>{B6.init(Q,Y),hG.init(Q,Y),Q.email=(X)=>Q.check(yW(kA,X)),Q.url=(X)=>Q.check(mW(vA,X)),Q.jwt=(X)=>Q.check(WG(dA,X)),Q.emoji=(X)=>Q.check(cW(xA,X)),Q.guid=(X)=>Q.check(rQ(gG,X)),Q.uuid=(X)=>Q.check(uW(Z6,X)),Q.uuidv4=(X)=>Q.check(hW(Z6,X)),Q.uuidv6=(X)=>Q.check(fW(Z6,X)),Q.uuidv7=(X)=>Q.check(lW(Z6,X)),Q.nanoid=(X)=>Q.check(pW(_A,X)),Q.guid=(X)=>Q.check(rQ(gG,X)),Q.cuid=(X)=>Q.check(iW(gA,X)),Q.cuid2=(X)=>Q.check(nW(yA,X)),Q.ulid=(X)=>Q.check(rW(uA,X)),Q.base64=(X)=>Q.check(QG(iA,X)),Q.base64url=(X)=>Q.check(YG(nA,X)),Q.xid=(X)=>Q.check(dW(hA,X)),Q.ksuid=(X)=>Q.check(oW(fA,X)),Q.ipv4=(X)=>Q.check(tW(lA,X)),Q.ipv6=(X)=>Q.check(aW(mA,X)),Q.cidrv4=(X)=>Q.check(sW(cA,X)),Q.cidrv6=(X)=>Q.check(eW(pA,X)),Q.e164=(X)=>Q.check(XG(rA,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 gW(CA,Q)}var e=q("ZodStringFormat",(Q,Y)=>{a.init(Q,Y),hG.init(Q,Y)}),kA=q("ZodEmail",(Q,Y)=>{c8.init(Q,Y),e.init(Q,Y)});var gG=q("ZodGUID",(Q,Y)=>{l8.init(Q,Y),e.init(Q,Y)});var Z6=q("ZodUUID",(Q,Y)=>{m8.init(Q,Y),e.init(Q,Y)});var vA=q("ZodURL",(Q,Y)=>{p8.init(Q,Y),e.init(Q,Y)});var xA=q("ZodEmoji",(Q,Y)=>{i8.init(Q,Y),e.init(Q,Y)});var _A=q("ZodNanoID",(Q,Y)=>{n8.init(Q,Y),e.init(Q,Y)});var gA=q("ZodCUID",(Q,Y)=>{r8.init(Q,Y),e.init(Q,Y)});var yA=q("ZodCUID2",(Q,Y)=>{d8.init(Q,Y),e.init(Q,Y)});var uA=q("ZodULID",(Q,Y)=>{o8.init(Q,Y),e.init(Q,Y)});var hA=q("ZodXID",(Q,Y)=>{t8.init(Q,Y),e.init(Q,Y)});var fA=q("ZodKSUID",(Q,Y)=>{a8.init(Q,Y),e.init(Q,Y)});var lA=q("ZodIPv4",(Q,Y)=>{XW.init(Q,Y),e.init(Q,Y)});var mA=q("ZodIPv6",(Q,Y)=>{WW.init(Q,Y),e.init(Q,Y)});var cA=q("ZodCIDRv4",(Q,Y)=>{GW.init(Q,Y),e.init(Q,Y)});var pA=q("ZodCIDRv6",(Q,Y)=>{$W.init(Q,Y),e.init(Q,Y)});var iA=q("ZodBase64",(Q,Y)=>{JW.init(Q,Y),e.init(Q,Y)});var nA=q("ZodBase64URL",(Q,Y)=>{HW.init(Q,Y),e.init(Q,Y)});var rA=q("ZodE164",(Q,Y)=>{AW.init(Q,Y),e.init(Q,Y)});var dA=q("ZodJWT",(Q,Y)=>{UW.init(Q,Y),e.init(Q,Y)});var fG=q("ZodNumber",(Q,Y)=>{pQ.init(Q,Y),G0.init(Q,Y),Q.gt=(G,W)=>Q.check(F6(G,W)),Q.gte=(G,W)=>Q.check(F4(G,W)),Q.min=(G,W)=>Q.check(F4(G,W)),Q.lt=(G,W)=>Q.check(L6(G,W)),Q.lte=(G,W)=>Q.check(L4(G,W)),Q.max=(G,W)=>Q.check(L4(G,W)),Q.int=(G)=>Q.check(yG(G)),Q.safe=(G)=>Q.check(yG(G)),Q.positive=(G)=>Q.check(F6(0,G)),Q.nonnegative=(G)=>Q.check(F4(0,G)),Q.negative=(G)=>Q.check(L6(0,G)),Q.nonpositive=(G)=>Q.check(L4(0,G)),Q.multipleOf=(G,W)=>Q.check(q6(G,W)),Q.step=(G,W)=>Q.check(q6(G,W)),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 HG(fG,Q)}var oA=q("ZodNumberFormat",(Q,Y)=>{KW.init(Q,Y),fG.init(Q,Y)});function yG(Q){return AG(oA,Q)}var tA=q("ZodBoolean",(Q,Y)=>{DW.init(Q,Y),G0.init(Q,Y)});function H0(Q){return UG(tA,Q)}var aA=q("ZodNull",(Q,Y)=>{BW.init(Q,Y),G0.init(Q,Y)});function U9(Q){return KG(aA,Q)}var sA=q("ZodUnknown",(Q,Y)=>{LW.init(Q,Y),G0.init(Q,Y)});function Q0(){return DG(sA)}var eA=q("ZodNever",(Q,Y)=>{FW.init(Q,Y),G0.init(Q,Y)});function Q3(Q){return BG(eA,Q)}var Y3=q("ZodArray",(Q,Y)=>{qW.init(Q,Y),G0.init(Q,Y),Q.element=Y.element,Q.min=(X,G)=>Q.check(u1(X,G)),Q.nonempty=(X)=>Q.check(u1(1,X)),Q.max=(X,G)=>Q.check(O6(X,G)),Q.length=(X,G)=>Q.check(M6(X,G)),Q.unwrap=()=>Q.element});function u(Q,Y){return LG(Y3,Q,Y)}var lG=q("ZodObject",(Q,Y)=>{VW.init(Q,Y),G0.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:Q0()}),Q.loose=()=>Q.clone({...Q._zod.def,catchall:Q0()}),Q.strict=()=>Q.clone({...Q._zod.def,catchall:Q3()}),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(pG,Q,X[0]),Q.required=(...X)=>m.required(iG,Q,X[0])});function b(Q,Y){let X={type:"object",shape:Q??{},...m.normalizeParams(Y)};return new lG(X)}function q0(Q,Y){return new lG({type:"object",shape:Q,catchall:Q0(),...m.normalizeParams(Y)})}var mG=q("ZodUnion",(Q,Y)=>{iQ.init(Q,Y),G0.init(Q,Y),Q.options=Y.options});function o(Q,Y){return new mG({type:"union",options:Q,...m.normalizeParams(Y)})}var X3=q("ZodDiscriminatedUnion",(Q,Y)=>{mG.init(Q,Y),ZW.init(Q,Y)});function K9(Q,Y,X){return new X3({type:"union",options:Y,discriminator:Q,...m.normalizeParams(X)})}var W3=q("ZodIntersection",(Q,Y)=>{NW.init(Q,Y),G0.init(Q,Y)});function N6(Q,Y){return new W3({type:"intersection",left:Q,right:Y})}var G3=q("ZodRecord",(Q,Y)=>{wW.init(Q,Y),G0.init(Q,Y),Q.keyType=Y.keyType,Q.valueType=Y.valueType});function Y0(Q,Y,X){return new G3({type:"record",keyType:Q,valueType:Y,...m.normalizeParams(X)})}var H9=q("ZodEnum",(Q,Y)=>{PW.init(Q,Y),G0.init(Q,Y),Q.enum=Y.entries,Q.options=Object.values(Y.entries);let X=new Set(Object.keys(Y.entries));Q.extract=(G,W)=>{let $={};for(let z of G)if(X.has(z))$[z]=Y.entries[z];else throw Error(`Key ${z} not found in enum`);return new H9({...Y,checks:[],...m.normalizeParams(W),entries:$})},Q.exclude=(G,W)=>{let $={...Y.entries};for(let z of G)if(X.has(z))delete $[z];else throw Error(`Key ${z} not found in enum`);return new H9({...Y,checks:[],...m.normalizeParams(W),entries:$})}});function V0(Q,Y){let X=Array.isArray(Q)?Object.fromEntries(Q.map((G)=>[G,G])):Q;return new H9({type:"enum",entries:X,...m.normalizeParams(Y)})}var $3=q("ZodLiteral",(Q,Y)=>{bW.init(Q,Y),G0.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 $3({type:"literal",values:Array.isArray(Q)?Q:[Q],...m.normalizeParams(Y)})}var z3=q("ZodTransform",(Q,Y)=>{jW.init(Q,Y),G0.init(Q,Y),Q._zod.parse=(X,G)=>{if(G.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 W=Y.transform(X.value,X);if(W instanceof Promise)return W.then(($)=>{return X.value=$,X});return X.value=W,X}});function cG(Q){return new z3({type:"transform",transform:Q})}var pG=q("ZodOptional",(Q,Y)=>{IW.init(Q,Y),G0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function W0(Q){return new pG({type:"optional",innerType:Q})}var J3=q("ZodNullable",(Q,Y)=>{EW.init(Q,Y),G0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function uG(Q){return new J3({type:"nullable",innerType:Q})}var H3=q("ZodDefault",(Q,Y)=>{TW.init(Q,Y),G0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType,Q.removeDefault=Q.unwrap});function A3(Q,Y){return new H3({type:"default",innerType:Q,get defaultValue(){return typeof Y==="function"?Y():m.shallowClone(Y)}})}var U3=q("ZodPrefault",(Q,Y)=>{SW.init(Q,Y),G0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function K3(Q,Y){return new U3({type:"prefault",innerType:Q,get defaultValue(){return typeof Y==="function"?Y():m.shallowClone(Y)}})}var iG=q("ZodNonOptional",(Q,Y)=>{RW.init(Q,Y),G0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function D3(Q,Y){return new iG({type:"nonoptional",innerType:Q,...m.normalizeParams(Y)})}var B3=q("ZodCatch",(Q,Y)=>{CW.init(Q,Y),G0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType,Q.removeCatch=Q.unwrap});function L3(Q,Y){return new B3({type:"catch",innerType:Q,catchValue:typeof Y==="function"?Y:()=>Y})}var F3=q("ZodPipe",(Q,Y)=>{kW.init(Q,Y),G0.init(Q,Y),Q.in=Y.in,Q.out=Y.out});function A9(Q,Y){return new F3({type:"pipe",in:Q,out:Y})}var q3=q("ZodReadonly",(Q,Y)=>{vW.init(Q,Y),G0.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function O3(Q){return new q3({type:"readonly",innerType:Q})}var nG=q("ZodCustom",(Q,Y)=>{xW.init(Q,Y),G0.init(Q,Y)});function rG(Q,Y){return FG(nG,Q??(()=>!0),Y)}function M3(Q,Y={}){return qG(nG,Q,Y)}function V3(Q){return OG(Q)}function D9(Q,Y){return A9(cG(Q),Y)}T0(nQ());var B9="2025-11-25";var dG=[B9,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],K1="io.modelcontextprotocol/related-task",P6="2.0",U0=rG((Q)=>Q!==null&&(typeof Q==="object"||typeof Q==="function")),oG=o([F(),i().int()]),tG=F(),Tw=q0({ttl:o([i(),U9()]).optional(),pollInterval:i().optional()}),Z3=b({ttl:i().optional()}),N3=b({taskId:F()}),L9=q0({progressToken:oG.optional(),[K1]:N3.optional()}),E0=b({_meta:L9.optional()}),M4=E0.extend({task:Z3.optional()}),aG=(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=o([F(),i().int()]),sG=b({jsonrpc:j(P6),id:b6,...K0.shape}).strict(),F9=(Q)=>sG.safeParse(Q).success,eG=b({jsonrpc:j(P6),...R0.shape}).strict(),Q$=(Q)=>eG.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:Q0().optional()})}).strict();var Y$=(Q)=>O9.safeParse(Q).success;var X$=o([sG,eG,q9,O9]),Sw=o([q9,O9]),j6=D0.strict(),w3=S0.extend({requestId:b6.optional(),reason:F().optional()}),I6=R0.extend({method:j("notifications/cancelled"),params:w3}),P3=b({src:F(),mimeType:F().optional(),sizes:u(F()).optional(),theme:V0(["light","dark"]).optional()}),Z4=b({icons:u(P3).optional()}),f1=b({name:F(),title:F().optional()}),W$=f1.extend({...f1.shape,...Z4.shape,version:F(),websiteUrl:F().optional(),description:F().optional()}),b3=N6(b({applyDefaults:H0().optional()}),Y0(F(),Q0())),j3=D9((Q)=>{if(Q&&typeof Q==="object"&&!Array.isArray(Q)){if(Object.keys(Q).length===0)return{form:{}}}return Q},N6(b({form:b3.optional(),url:U0.optional()}),Y0(F(),Q0()).optional())),I3=q0({list:U0.optional(),cancel:U0.optional(),requests:q0({sampling:q0({createMessage:U0.optional()}).optional(),elicitation:q0({create:U0.optional()}).optional()}).optional()}),E3=q0({list:U0.optional(),cancel:U0.optional(),requests:q0({tools:q0({call:U0.optional()}).optional()}).optional()}),T3=b({experimental:Y0(F(),U0).optional(),sampling:b({context:U0.optional(),tools:U0.optional()}).optional(),elicitation:j3.optional(),roots:b({listChanged:H0().optional()}).optional(),tasks:I3.optional()}),S3=E0.extend({protocolVersion:F(),capabilities:T3,clientInfo:W$}),M9=K0.extend({method:j("initialize"),params:S3});var R3=b({experimental:Y0(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:E3.optional()}),C3=D0.extend({protocolVersion:F(),capabilities:R3,serverInfo:W$,instructions:F().optional()}),V9=R0.extend({method:j("notifications/initialized"),params:S0.optional()});var E6=K0.extend({method:j("ping"),params:E0.optional()}),k3=b({progress:i(),total:W0(i()),message:W0(F())}),v3=b({...S0.shape,...k3.shape,progressToken:oG}),T6=R0.extend({method:j("notifications/progress"),params:v3}),x3=E0.extend({cursor:tG.optional()}),N4=K0.extend({params:x3.optional()}),w4=D0.extend({nextCursor:tG.optional()}),_3=V0(["working","input_required","completed","failed","cancelled"]),P4=b({taskId:F(),status:_3,ttl:o([i(),U9()]),createdAt:F(),lastUpdatedAt:F(),pollInterval:W0(i()),statusMessage:W0(F())}),l1=D0.extend({task:P4}),g3=S0.merge(P4),b4=R0.extend({method:j("notifications/tasks/status"),params:g3}),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()})}),Rw=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()})}),G$=D0.merge(P4),$$=b({uri:F(),mimeType:W0(F()),_meta:Y0(F(),Q0()).optional()}),z$=$$.extend({text:F()}),Z9=F().refine((Q)=>{try{return atob(Q),!0}catch{return!1}},{message:"Invalid Base64 string"}),J$=$$.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()}),H$=b({...f1.shape,...Z4.shape,uri:F(),description:W0(F()),mimeType:W0(F()),annotations:m1.optional(),_meta:W0(q0({}))}),y3=b({...f1.shape,...Z4.shape,uriTemplate:F(),description:W0(F()),mimeType:W0(F()),annotations:m1.optional(),_meta:W0(q0({}))}),N9=N4.extend({method:j("resources/list")}),u3=w4.extend({resources:u(H$)}),h3=N4.extend({method:j("resources/templates/list")}),f3=w4.extend({resourceTemplates:u(y3)}),w9=E0.extend({uri:F()}),l3=w9,P9=K0.extend({method:j("resources/read"),params:l3}),m3=D0.extend({contents:u(o([z$,J$]))}),c3=R0.extend({method:j("notifications/resources/list_changed"),params:S0.optional()}),p3=w9,i3=K0.extend({method:j("resources/subscribe"),params:p3}),n3=w9,r3=K0.extend({method:j("resources/unsubscribe"),params:n3}),d3=S0.extend({uri:F()}),o3=R0.extend({method:j("notifications/resources/updated"),params:d3}),t3=b({name:F(),description:W0(F()),required:W0(H0())}),a3=b({...f1.shape,...Z4.shape,description:W0(F()),arguments:W0(u(t3)),_meta:W0(q0({}))}),s3=N4.extend({method:j("prompts/list")}),e3=w4.extend({prompts:u(a3)}),QU=E0.extend({name:F(),arguments:Y0(F(),F()).optional()}),YU=K0.extend({method:j("prompts/get"),params:QU}),b9=b({type:j("text"),text:F(),annotations:m1.optional(),_meta:Y0(F(),Q0()).optional()}),j9=b({type:j("image"),data:Z9,mimeType:F(),annotations:m1.optional(),_meta:Y0(F(),Q0()).optional()}),I9=b({type:j("audio"),data:Z9,mimeType:F(),annotations:m1.optional(),_meta:Y0(F(),Q0()).optional()}),XU=b({type:j("tool_use"),name:F(),id:F(),input:Y0(F(),Q0()),_meta:Y0(F(),Q0()).optional()}),WU=b({type:j("resource"),resource:o([z$,J$]),annotations:m1.optional(),_meta:Y0(F(),Q0()).optional()}),GU=H$.extend({type:j("resource_link")}),E9=o([b9,j9,I9,GU,WU]),$U=b({role:j4,content:E9}),zU=D0.extend({description:F().optional(),messages:u($U)}),JU=R0.extend({method:j("notifications/prompts/list_changed"),params:S0.optional()}),HU=b({title:F().optional(),readOnlyHint:H0().optional(),destructiveHint:H0().optional(),idempotentHint:H0().optional(),openWorldHint:H0().optional()}),AU=b({taskSupport:V0(["required","optional","forbidden"]).optional()}),A$=b({...f1.shape,...Z4.shape,description:F().optional(),inputSchema:b({type:j("object"),properties:Y0(F(),U0).optional(),required:u(F()).optional()}).catchall(Q0()),outputSchema:b({type:j("object"),properties:Y0(F(),U0).optional(),required:u(F()).optional()}).catchall(Q0()).optional(),annotations:HU.optional(),execution:AU.optional(),_meta:Y0(F(),Q0()).optional()}),T9=N4.extend({method:j("tools/list")}),UU=w4.extend({tools:u(A$)}),_6=D0.extend({content:u(E9).default([]),structuredContent:Y0(F(),Q0()).optional(),isError:H0().optional()}),Cw=_6.or(D0.extend({toolResult:Q0()})),KU=M4.extend({name:F(),arguments:Y0(F(),Q0()).optional()}),I4=K0.extend({method:j("tools/call"),params:KU}),DU=R0.extend({method:j("notifications/tools/list_changed"),params:S0.optional()}),kw=b({autoRefresh:H0().default(!0),debounceMs:i().int().nonnegative().default(300)}),E4=V0(["debug","info","notice","warning","error","critical","alert","emergency"]),BU=E0.extend({level:E4}),S9=K0.extend({method:j("logging/setLevel"),params:BU}),LU=S0.extend({level:E4,logger:F().optional(),data:Q0()}),FU=R0.extend({method:j("notifications/message"),params:LU}),qU=b({name:F().optional()}),OU=b({hints:u(qU).optional(),costPriority:i().min(0).max(1).optional(),speedPriority:i().min(0).max(1).optional(),intelligencePriority:i().min(0).max(1).optional()}),MU=b({mode:V0(["auto","required","none"]).optional()}),VU=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:Y0(F(),Q0()).optional()}),ZU=K9("type",[b9,j9,I9]),w6=K9("type",[b9,j9,I9,XU,VU]),NU=b({role:j4,content:o([w6,u(w6)]),_meta:Y0(F(),Q0()).optional()}),wU=M4.extend({messages:u(NU),modelPreferences:OU.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(A$).optional(),toolChoice:MU.optional()}),PU=K0.extend({method:j("sampling/createMessage"),params:wU}),R9=D0.extend({model:F(),stopReason:W0(V0(["endTurn","stopSequence","maxTokens"]).or(F())),role:j4,content:ZU}),C9=D0.extend({model:F(),stopReason:W0(V0(["endTurn","stopSequence","maxTokens","toolUse"]).or(F())),role:j4,content:o([w6,u(w6)])}),bU=b({type:j("boolean"),title:F().optional(),description:F().optional(),default:H0().optional()}),jU=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()}),IU=b({type:V0(["number","integer"]),title:F().optional(),description:F().optional(),minimum:i().optional(),maximum:i().optional(),default:i().optional()}),EU=b({type:j("string"),title:F().optional(),description:F().optional(),enum:u(F()),default:F().optional()}),TU=b({type:j("string"),title:F().optional(),description:F().optional(),oneOf:u(b({const:F(),title:F()})),default:F().optional()}),SU=b({type:j("string"),title:F().optional(),description:F().optional(),enum:u(F()),enumNames:u(F()).optional(),default:F().optional()}),RU=o([EU,TU]),CU=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()}),kU=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()}),vU=o([CU,kU]),xU=o([SU,RU,vU]),_U=o([xU,bU,jU,IU]),gU=M4.extend({mode:j("form").optional(),message:F(),requestedSchema:b({type:j("object"),properties:Y0(F(),_U),required:u(F()).optional()})}),yU=M4.extend({mode:j("url"),message:F(),elicitationId:F(),url:F().url()}),uU=o([gU,yU]),hU=K0.extend({method:j("elicitation/create"),params:uU}),fU=S0.extend({elicitationId:F()}),lU=R0.extend({method:j("notifications/elicitation/complete"),params:fU}),g6=D0.extend({action:V0(["accept","decline","cancel"]),content:D9((Q)=>Q===null?void 0:Q,Y0(F(),o([F(),i(),H0(),u(F())])).optional())}),mU=b({type:j("ref/resource"),uri:F()});var cU=b({type:j("ref/prompt"),name:F()}),pU=E0.extend({ref:o([cU,mU]),argument:b({name:F(),value:F()}),context:b({arguments:Y0(F(),F()).optional()}).optional()}),iU=K0.extend({method:j("completion/complete"),params:pU});var nU=D0.extend({completion:q0({values:u(F()).max(100),total:W0(i().int()),hasMore:W0(H0())})}),rU=b({uri:F().startsWith("file://"),name:F().optional(),_meta:Y0(F(),Q0()).optional()}),dU=K0.extend({method:j("roots/list"),params:E0.optional()}),k9=D0.extend({roots:u(rU)}),oU=R0.extend({method:j("notifications/roots/list_changed"),params:S0.optional()}),vw=o([E6,M9,iU,S9,YU,s3,N9,h3,P9,i3,r3,I4,T9,S6,C6,k6,x6]),xw=o([I6,T6,V9,oU,b4]),_w=o([j6,R9,C9,g6,k9,R6,v6,l1]),gw=o([E6,PU,hU,dU,S6,C6,k6,x6]),yw=o([I6,T6,FU,o3,c3,DU,JU,b4,lU]),uw=o([j6,C3,nU,zU,e3,u3,f3,m3,_6,UU,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 G=X;if(G.elicitations)return new U$(G.elicitations,Y)}return new _(Q,Y,X)}}class U$ 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 tU=Symbol("Let zodToJsonSchema decide on which parser to use");var OP=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function v9(Q){let X=V6(Q)?.method;if(!X)throw Error("Schema is missing a method literal");let G=MG(X);if(typeof G!=="string")throw Error("Schema method literal must be a string");return G}function x9(Q,Y){let X=U1(Q,Y);if(!X.success)throw X.error;return X.data}var XK=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 G=await this._taskStore.getTask(Y.params.taskId,X.sessionId);if(!G)throw new _(h.InvalidParams,"Failed to retrieve task: Task not found");return{...G}}),this.setRequestHandler(C6,async(Y,X)=>{let G=async()=>{let W=Y.params.taskId;if(this._taskMessageQueue){let z;while(z=await this._taskMessageQueue.dequeue(W,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(W,X.sessionId);if(!$)throw new _(h.InvalidParams,`Task not found: ${W}`);if(!D1($.status))return await this._waitForTaskUpdate(W,X.signal),await G();if(D1($.status)){let z=await this._taskStore.getTaskResult(W,X.sessionId);return this._clearTaskQueue(W),{...z,_meta:{...z._meta,[K1]:{taskId:W}}}}return await G()};return await G()}),this.setRequestHandler(k6,async(Y,X)=>{try{let{tasks:G,nextCursor:W}=await this._taskStore.listTasks(Y.params?.cursor,X.sessionId);return{tasks:G,nextCursor:W,_meta:{}}}catch(G){throw new _(h.InvalidParams,`Failed to list tasks: ${G instanceof Error?G.message:String(G)}`)}}),this.setRequestHandler(x6,async(Y,X)=>{try{let G=await this._taskStore.getTask(Y.params.taskId,X.sessionId);if(!G)throw new _(h.InvalidParams,`Task not found: ${Y.params.taskId}`);if(D1(G.status))throw new _(h.InvalidParams,`Cannot cancel task in terminal status: ${G.status}`);await this._taskStore.updateTaskStatus(Y.params.taskId,"cancelled","Client cancelled task execution.",X.sessionId),this._clearTaskQueue(Y.params.taskId);let W=await this._taskStore.getTask(Y.params.taskId,X.sessionId);if(!W)throw new _(h.InvalidParams,`Task not found after cancellation: ${Y.params.taskId}`);return{_meta:{},...W}}catch(G){if(G instanceof _)throw G;throw new _(h.InvalidRequest,`Failed to cancel task: ${G instanceof Error?G.message:String(G)}`)}})}async _oncancel(Q){if(!Q.params.requestId)return;this._requestHandlerAbortControllers.get(Q.params.requestId)?.abort(Q.params.reason)}_setupTimeout(Q,Y,X,G,W=!1){this._timeoutInfo.set(Q,{timeoutId:setTimeout(G,Y),startTime:Date.now(),timeout:Y,maxTotalTimeout:X,resetTimeoutOnProgress:W,onTimeout:G})}_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=(W)=>{X?.(W),this._onerror(W)};let G=this._transport?.onmessage;this._transport.onmessage=(W,$)=>{if(G?.(W,$),V4(W)||Y$(W))this._onresponse(W);else if(F9(W))this._onrequest(W,$);else if(Q$(W))this._onnotification(W);else this._onerror(Error(`Unknown message type: ${JSON.stringify(W)}`))},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,G=this._transport,W=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(W&&this._taskMessageQueue)this._enqueueTaskMessage(W,{type:"error",message:A,timestamp:Date.now()},G?.sessionId).catch((U)=>this._onerror(Error(`Failed to enqueue error response: ${U}`)));else G?.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=aG(Q.params)?Q.params.task:void 0,J=this._taskStore?this.requestTaskStore(Q,G?.sessionId):void 0,H={signal:$.signal,sessionId:G?.sessionId,_meta:Q.params?._meta,sendNotification:async(A)=>{let U={relatedRequestId:Q.id};if(W)U.relatedTask={taskId:W};await this.notification(A,U)},sendRequest:async(A,U,K)=>{let D={...K,relatedRequestId:Q.id};if(W&&!D.relatedTask)D.relatedTask={taskId:W};let L=D.relatedTask?.taskId??W;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:W,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(W&&this._taskMessageQueue)await this._enqueueTaskMessage(W,{type:"response",message:U,timestamp:Date.now()},G?.sessionId);else await G?.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(W&&this._taskMessageQueue)await this._enqueueTaskMessage(W,{type:"error",message:U,timestamp:Date.now()},G?.sessionId);else await G?.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,G=Number(Y),W=this._progressHandlers.get(G);if(!W){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(Q)}`));return}let $=this._responseHandlers.get(G),z=this._timeoutInfo.get(G);if(z&&$&&z.resetTimeoutOnProgress)try{this._resetTimeout(G)}catch(J){this._responseHandlers.delete(G),this._progressHandlers.delete(G),this._cleanupTimeout(G),$(J);return}W(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 G=this._responseHandlers.get(Y);if(G===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 W=!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")W=!0,this._taskProgressTokens.set(z.taskId,Y)}}if(!W)this._progressHandlers.delete(Y);if(V4(Q))G(Q);else{let $=_.fromError(Q.error.code,Q.error.message,Q.error.data);G($)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(Q,Y,X){let{task:G}=X??{};if(!G){try{yield{type:"result",result:await this.request(Q,Y,X)}}catch($){yield{type:"error",error:$ instanceof _?$:new _(h.InternalError,String($))}}return}let W;try{let $=await this.request(Q,l1,X);if($.task)W=$.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:W},X);if(yield{type:"taskStatus",task:z},D1(z.status)){if(z.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:W},Y,X)};else if(z.status==="failed")yield{type:"error",error:new _(h.InternalError,`Task ${W} failed`)};else if(z.status==="cancelled")yield{type:"error",error:new _(h.InternalError,`Task ${W} was cancelled`)};return}if(z.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:W},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:G,resumptionToken:W,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:G,resumptionToken:W,onresumptiontoken:$}).catch((R)=>this._onerror(Error(`Failed to send cancellation: ${R}`)));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??XK,M=()=>L(_.fromError(h.RequestTimeout,"Request timed out",{timeout:O}));this._setupTimeout(K,O,X?.maxTotalTimeout,M,X?.resetTimeoutOnProgress??!1);let w=J?.taskId;if(w){let Z=(k)=>{let R=this._responseHandlers.get(K);if(R)R(k);else this._onerror(Error(`Response handler missing for side-channeled request ${K}`))};this._requestResolvers.set(K,Z),this._enqueueTaskMessage(w,{type:"request",message:D,timestamp:Date.now()}).catch((k)=>{this._cleanupTimeout(K),A(k)})}else this._transport.send(D,{relatedRequestId:G,resumptionToken:W,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},G$,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,(G,W)=>{let $=x9(Q,G);return Promise.resolve(Y($,W))})}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,(G)=>{let W=x9(Q,G);return Promise.resolve(Y(W))})}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 G=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(Q,Y,X,G)}async _clearTaskQueue(Q,Y){if(this._taskMessageQueue){let X=await this._taskMessageQueue.dequeueAll(Q,Y);for(let G of X)if(G.type==="request"&&F9(G.message)){let W=G.message.id,$=this._requestResolvers.get(W);if($)$(new _(h.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(W);else this._onerror(Error(`Resolver missing for request ${W} during task ${Q} cleanup`))}}}async _waitForTaskUpdate(Q,Y){let X=this._options?.defaultTaskPollInterval??1000;try{let G=await this._taskStore?.getTask(Q);if(G?.pollInterval)X=G.pollInterval}catch{}return new Promise((G,W)=>{if(Y.aborted){W(new _(h.InvalidRequest,"Request cancelled"));return}let $=setTimeout(G,X);Y.addEventListener("abort",()=>{clearTimeout($),W(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(G)=>{if(!Q)throw Error("No request provided");return await X.createTask(G,Q.id,{method:Q.method,params:Q.params},Y)},getTask:async(G)=>{let W=await X.getTask(G,Y);if(!W)throw new _(h.InvalidParams,"Failed to retrieve task: Task not found");return W},storeTaskResult:async(G,W,$)=>{await X.storeTaskResult(G,W,$,Y);let z=await X.getTask(G,Y);if(z){let J=b4.parse({method:"notifications/tasks/status",params:z});if(await this.notification(J),D1(z.status))this._cleanupTaskProgressHandler(G)}},getTaskResult:(G)=>{return X.getTaskResult(G,Y)},updateTaskStatus:async(G,W,$)=>{let z=await X.getTask(G,Y);if(!z)throw new _(h.InvalidParams,`Task "${G}" not found - it may have been cleaned up`);if(D1(z.status))throw new _(h.InvalidParams,`Cannot update task "${G}" from terminal status "${z.status}" to "${W}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await X.updateTaskStatus(G,W,$,Y);let J=await X.getTask(G,Y);if(J){let H=b4.parse({method:"notifications/tasks/status",params:J});if(await this.notification(H),D1(J.status))this._cleanupTaskProgressHandler(G)}},listTasks:(G)=>{return X.listTasks(G,Y)}}}}function K$(Q){return Q!==null&&typeof Q==="object"&&!Array.isArray(Q)}function D$(Q,Y){let X={...Q};for(let G in Y){let W=G,$=Y[W];if($===void 0)continue;let z=X[W];if(K$(z)&&K$($))X[W]={...z,...$};else X[W]=$}return X}var c5=qX(SY(),1),p5=qX(m5(),1);function KV(){let Q=new c5.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return p5.default(Q),Q}class hY{constructor(Q){this._ajv=Q??KV()}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 i5(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 n5(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,G)=>[X,G])),this.isMessageIgnored=(X,G)=>{let W=this._loggingLevels.get(G);return W?this.LOG_LEVEL_SEVERITY.get(X)<this.LOG_LEVEL_SEVERITY.get(W):!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,G)=>{let W=G.sessionId||G.requestInfo?.headers["mcp-session-id"]||void 0,{level:$}=X.params,z=E4.safeParse($);if(z.success)this._loggingLevels.set(W,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=D$(this._capabilities,Q)}setRequestHandler(Q,Y){let G=V6(Q)?.method;if(!G)throw Error("Schema is missing a method literal");let W;if(h1(G)){let z=G;W=z._zod?.def?.value??z.value}else{let z=G;W=z._def?.value??z.value}if(typeof W!=="string")throw Error("Schema method literal must be a string");if(W==="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){n5(this._clientCapabilities?.tasks?.requests,Q,"Client")}assertTaskHandlerCapability(Q){if(!this._capabilities)return;i5(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:dG.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],G=Array.isArray(X.content)?X.content:[X.content],W=G.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(W){if(G.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(G.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 G=Q;return this.request({method:"elicitation/create",params:G},g6,Y)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let G=Q.mode==="form"?Q:{...Q,mode:"form"},W=await this.request({method:"elicitation/create",params:G},g6,Y);if(W.action==="accept"&&W.content&&G.requestedSchema)try{let z=this._jsonSchemaValidator.getValidator(G.requestedSchema)(W.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 W}}}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 r5={name:"@sequenzy/mcp",version:"0.0.105",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"],d5={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 BV(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 o5(Q,Y,X){return z0(Q,`${J0(Y,"/settings")}?tab=${encodeURIComponent(X)}`)}function LV(Q,Y){let X=mY.map((G)=>[G,Y?o5(Q,Y,G):""]);return Object.fromEntries(X)}function Z1(Q={},Y){let X=BV(Y),G=l0(Q.companyId),W={},$=LV(X,G);if(!G)return{appUrl:X,routeTemplates:d5,settingsTabValues:mY,urls:W,settingsUrls:$};W.dashboard=z0(X,J0(G)),W.campaigns=z0(X,J0(G,"/campaign")),W.landingPages=z0(X,J0(G,"/landing-pages")),W.sequences=z0(X,J0(G,"/sequences")),W.settings=z0(X,J0(G,"/settings")),W.emails=z0(X,J0(G,"/emails")),W.subscribers=z0(X,J0(G,"/subscribers")),W.sentEmails=z0(X,J0(G,"/sent-emails")),W.segments=z0(X,J0(G,"/segments")),W.metrics=z0(X,J0(G,"/metrics")),W.transactional=z0(X,J0(G,"/transactional"));let z=l0(Q.campaignId);if(z)W.campaign=z0(X,J0(G,`/campaign/${r0(z)}`)),W.campaignPreview=`${W.campaign}?step=review`;let J=l0(Q.landingPageId);if(J)W.landingPage=z0(X,J0(G,`/landing-pages/${r0(J)}`));let H=l0(Q.sequenceId);if(H)W.sequence=z0(X,J0(G,`/sequences/${r0(H)}`));let A=l0(Q.emailId)??l0(Q.templateId);if(A)W.email=z0(X,J0(G,`/emails/${r0(A)}`)),W.template=W.email;let U=l0(Q.transactionalId);if(U)W.transactionalEmail=z0(X,J0(G,`/transactional/${r0(U)}`));let K=l0(Q.emailSendId);if(K)W.emailSend=z0(X,J0(G,`/sent-emails/${r0(K)}`));let D=l0(Q.domainId);if(D)W.domain=z0(X,J0(G,`/settings/domain/${r0(D)}`)),W.domainVerify=`${W.domain}/verify`;let L=l0(Q.status);if(L)W.campaignList=z0(X,J0(G,`/campaign/list/${r0(L)}`)),W.sequenceList=z0(X,J0(G,`/sequences/list/${r0(L)}`));let O=l0(Q.settingsTab);if(O)W.settingsTab=o5(X,G,O);return{appUrl:X,routeTemplates:d5,settingsTabValues:mY,urls:W,settingsUrls:$}}var t5=[{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 a5(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"),G=b1()??X.currentCompanyId;if(!G)throw Error("No company available. Create or select a company first.");Y=await B("GET",`/api/v1/companies/${G}`);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 FV,statSync as qV}from"node:fs";import{basename as OV}from"node:path";var zX=' 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: [...] }.${zX}`,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\`.${zX}`,sY=`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.${zX}`,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.",MV="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.",s5=500,e5=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"],QH={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},VV={type:"object",description:"Offset relative to a wait-until date.",properties:{days:{type:"number"},hours:{type:"number"},minutes:{type:"number"}},additionalProperties:!1},eY={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:VV,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},QX={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},BH={type:"object",description:"Type-aware patch for the existing node. Start from get_sequence.sequence.nodes[].config. For logic_delay, set exactly one of delay ({ days, hours, minutes }), delayMs, or waitUntil; optional label is also accepted. For action_email, use name/label, subject, previewText, html/htmlContent or blocks, isTransactional, and sender/reply identity fields. For action_sms, use text, blocks, imageUrls, label, or ineligibleAction. Other node types accept their editable config keys. Managed IDs, nodeType conversion, and branch path IDs/count are not editable here; use edit_sequence_graph for topology. Webhook header patches are merged, and redacted values from get_sequence must be omitted or replaced with a real new value.",additionalProperties:!0},pY={type:"object",properties:{nodeId:{type:"string",description:"Existing node ID from get_sequence.sequence.nodes[].id."},changes:BH,expectedUpdatedAt:{type:"string",description:"Required optimistic-concurrency value from get_sequence.sequence.nodes[].updatedAt. The update is rejected if that node or its linked email content changed after it was read."}},required:["nodeId","changes","expectedUpdatedAt"],additionalProperties:!1},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"],ZV=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"]),NV=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","update_sequence_node","update_sequence_nodes","edit_sequence_graph","insert_sequence_step","enable_sequence","disable_sequence","pause_sequence_enrollments","resume_sequence_enrollments","enroll_subscribers_in_sequence","cancel_sequence_enrollments","delete_sequence","create_transactional_email","update_transactional_email","send_email","invite_team_member","cancel_team_invitation","reply_to_conversation","update_conversation_status","mark_conversation_read","create_webhook","update_webhook","delete_webhook","test_webhook","replay_webhook_delivery","submit_feedback"]),wV=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"]),PV=new Set(["remove_subscriber","delete_subscriber_note","delete_product","remove_product_file","delete_tag","delete_list","remove_subscribers_from_list","delete_segment","delete_audience_sync","delete_template","restart_ab_test","delete_ab_test_variant","delete_ab_test","cancel_campaign","delete_campaign","delete_landing_page","unpublish_landing_page","disable_sequence","edit_sequence_graph","cancel_sequence_enrollments","delete_sequence","cancel_team_invitation","delete_webhook"]);function bV(Q){let Y=ZV.has(Q),X=NV.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:PV.has(Q),openWorldHint:wV.has(Q)}}function jV(Q){return{...Q,annotations:{...Q.annotations,...bV(Q.name)}}}var YX={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"]},IV=Object.entries(YX).map(([Q,Y])=>`${Q}: ${Y.join(", ")}`).join("; "),YH={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: ${IV}.`},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},XH={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 XX(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 WX(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=XX([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(WX):[]}}function EV(Q){let Y=Q.indexOf(":");return Y!==-1&&Q.substring(0,Y).trim().length>0}function TV(Q){let Y=Q.indexOf(":");return Y!==-1&&Q.substring(Y+1).trim().length>0}function WH(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 SV(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&&WH(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 G=X.slice(0,-1).join(":").trim(),W=X.at(-1);return G&&W!==void 0&&WH(W)?null:'Event filters must use "eventName:timeRange", like "saas.purchase:30d".'}function RV(Q){let Y=Q.indexOf(":");if(Y===-1)return{productId:Q,subfilter:null,rawValue:null};let X=Q.substring(0,Y),G=Q.substring(Y+1),W=G.indexOf(":");if(W===-1)return{productId:X,subfilter:G,rawValue:null};return{productId:X,subfilter:G.substring(0,W),rawValue:G.substring(W+1)}}function CV(Q){return Q.trim().toLowerCase().replace(/[-\s]+/g,"_")}function kV(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 vV(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 xV(Q){return["is","is_not","gte","lte","gt","lt"].includes(Q)}function _V(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:G,subfilter:W,rawValue:$}=RV(X);if(!G.trim())return"Stripe product filters must include a product ID.";if(!W)return Y==="is"||Y==="is_not"?null:'Stripe current/trial date filters must use "productId:dateField:value".';let z=CV(W);if(kV(z))return Y==="is"||Y==="is_not"?null:"Stripe cancellation flag filters only support is and is_not operators.";if(!vV(Q,z))return`Unsupported Stripe product subfilter "${W}".`;if(!xV(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 gV=new Set(["shopify","woocommerce","api"]);function yV(Q,Y){let X=Y.trim(),G=X.indexOf(":");if(G!==-1&&gV.has(X.substring(0,G).trim()))X=X.substring(G+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 W=X.lastIndexOf(":");if(W===-1)return null;let $=X.substring(0,W).trim(),z=Number.parseInt(X.substring(W+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 JX(Q){if(typeof Q!=="object"||Q===null)return"Segment filters must be objects.";let Y=Q,X=Y.field,G=Y.operator,W=Y.value;if(typeof X!=="string"||!(X in YX))return`Unsupported segment filter field "${String(X)}".`;if(typeof G!=="string")return`Segment filter "${X}" must include an operator.`;let $=YX[X];if(!$.includes(G))return`Operator "${G}" is not supported for ${X} filters. Use one of: ${$.join(", ")}.`;if(G!=="is_empty"&&G!=="is_not_empty"&&(typeof W!=="string"||W.trim().length===0))return`Segment filter "${X}" must include a value.`;if(X==="attribute"&&typeof W==="string"){if(!EV(W))return'Attribute filters must use "attributeName:value" or "attributeName:" for empty checks.';if(G!=="is_empty"&&G!=="is_not_empty"&&!TV(W))return'Attribute filters must include a value after "attributeName:".'}if(X==="event"&&typeof W==="string"){let z=SV(G,W);if(z)return z}if((X==="stripeProduct"||X==="stripeCurrentProduct"||X==="stripeTrialProduct")&&typeof W==="string"){let z=_V(X,G,W);if(z)return z}if(X==="commerceProduct"&&typeof W==="string"){let z=yV(G,W);if(z)return z}if(X==="tag"&&(G==="contains"||G==="not_contains")){if(!(typeof W==="string"&&W.split(",").map((J)=>J.trim()).some(Boolean)))return"Tag filters must include at least one tag name."}return null}function HX(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=JX(Y);return X?[X]:[]}if(Array.isArray(Y.children))return Y.children.flatMap(HX);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 uV(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 G=Y?Q.filters.flatMap((W)=>{let $=JX(W);return $?[$]:[]}):HX(Q.root);if(G.length>0)throw Error(G[0]??"Invalid segment filter in `create_segment`.")}function hV(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 G=Y?Q.filters.flatMap((W)=>{let $=JX(W);return $?[$]:[]}):X?HX(Q.root):[];if(G.length>0)throw Error(G[0]??"Invalid segment filter in `update_segment`.")}var iY=["name","description","logoUrl","founderName","primaryColor","brandColors","valueProps","testimonials","toneVoice","companyContext","emailLengthPreference","socialLinks","privacyPolicyUrl","termsUrl","address","language","pricing","fontFamily","emailDirection","fromEmail","fromName","replyTo","replyToName"];function nY(Q,Y,X){if(Y[X]!==void 0&&!n(Y[X]))throw Error(`\`${X}\` must be an object when calling \`${Q}\`.`)}function GH(Q,Y,X){if(Y[X]!==void 0&&!Array.isArray(Y[X]))throw Error(`\`${X}\` must be an array when calling \`${Q}\`.`)}function fV(Q){let Y=new Set(["companyId",...iY]),X=Object.keys(Q).filter((W)=>!Y.has(W));if(X.length>0)throw Error(`\`update_company\` accepts only company product-info fields. Unsupported field${X.length===1?"":"s"}: ${X.map((W)=>`\`${W}\``).join(", ")}.`);let G={};for(let W of iY)if(Q[W]!==void 0)G[W]=Q[W];if(Object.keys(G).length===0)throw Error(`Provide at least one of ${iY.map((W)=>`\`${W}\``).join(", ")} when calling \`update_company\`.`);for(let W of["name","description","logoUrl","founderName","primaryColor","toneVoice","companyContext","emailLengthPreference","privacyPolicyUrl","termsUrl","address","language","fontFamily","emailDirection","fromEmail","fromName","replyTo","replyToName"])if(Q[W]!==void 0&&typeof Q[W]!=="string")throw Error(`\`${W}\` must be a string when calling \`update_company\`.`);if(nY("update_company",Q,"brandColors"),nY("update_company",Q,"socialLinks"),nY("update_company",Q,"pricing"),GH("update_company",Q,"valueProps"),GH("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 W of["fromEmail","replyTo"]){let $=Q[W];if(typeof $==="string"&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test($.trim()))throw Error(`\`${W}\` 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 G}var LH=["senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName"];function lV(Q){return LH.some((Y)=>Q[Y]!==void 0)}function mV(Q){if(typeof Q.nodeType==="string")return Q.nodeType==="action_email";return Q.type===void 0||Q.type==="email"}function AX(Q,Y,X){for(let G of LH){let W=X[G];if(W!==void 0&&typeof W!=="string")throw Error(`\`${G}\` 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 FH(Q,Y,X){if(lV(X)&&!mV(X))throw Error(`Sender identity fields are only supported for email steps at ${Y} when calling \`${Q}\`.`);AX(Q,Y,X)}function $H(Q,Y,X){if(!Array.isArray(X))return;X.forEach((G,W)=>{if(n(G))AX(Q,`${Y}[${W}]`,G)})}function rY(Q,Y,X){if(!Array.isArray(X))return;X.forEach((G,W)=>{if(n(G))FH(Q,`${Y}[${W}]`,G)})}function cV(Q){if($H("update_sequence","emails",Q.emails),$H("update_sequence","steps",Q.steps),n(Q.insertSteps))rY("update_sequence","insertSteps.steps",Q.insertSteps.steps);if(!n(Q.branch))return;if(Array.isArray(Q.branch.branches))Q.branch.branches.forEach((X,G)=>{if(n(X))rY("update_sequence",`branch.branches[${G}].steps`,X.steps)});rY("update_sequence","branch.elseSteps",Q.branch.elseSteps)}function pV(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.");cV(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 qH(Q,Y,X){let G=E(Q,Y,"nodeId");if(!n(Y.changes)||Object.keys(Y.changes).length===0)throw Error(`\`changes\` must be a non-empty object for ${X} when calling \`${Q}\`.`);let W=E(Q,Y,"expectedUpdatedAt");return{nodeId:G,changes:Y.changes,expectedUpdatedAt:W}}function iV(Q){let Y=qH("update_sequence_node",Q,"the node update");return{...Q.confirmLiveChange!==void 0&&{confirmLiveChange:Q.confirmLiveChange},nodeUpdates:[Y]}}function nV(Q){if(!Array.isArray(Q.updates)||Q.updates.length===0)throw Error("`updates` must be a non-empty array when calling `update_sequence_nodes`.");let Y=new Set,X=Q.updates.map((G,W)=>{if(!n(G))throw Error(`\`updates[${W}]\` must be an object when calling \`update_sequence_nodes\`.`);let $=qH("update_sequence_nodes",G,`updates[${W}]`),z=String($.nodeId);if(Y.has(z))throw Error(`\`updates[${W}]\` targets duplicate nodeId '${z}' when calling \`update_sequence_nodes\`.`);return Y.add(z),$});return{...Q.confirmLiveChange!==void 0&&{confirmLiveChange:Q.confirmLiveChange},nodeUpdates:X}}function rV(Q){let Y=E("edit_sequence_graph",Q,"action"),X=E("edit_sequence_graph",Q,"graphRevision");if(!new Set(["move_node","delete_node","duplicate_node","replace_edges"]).has(Y))throw Error("`action` must be `move_node`, `delete_node`, `duplicate_node`, or `replace_edges` when calling `edit_sequence_graph`.");let W=N(Q,"nodeId"),$=N(Q,"afterNodeId"),z=N(Q,"beforeNodeId"),J=Q.edges;if(Y!=="replace_edges"&&!W)throw Error(`\`nodeId\` is required for ${Y} when calling \`edit_sequence_graph\`.`);if(Y==="replace_edges"&&W)throw Error("`nodeId` is not used with `replace_edges` when calling `edit_sequence_graph`.");let H=Y==="move_node"||Y==="duplicate_node";if(H&&($?1:0)+(z?1:0)!==1)throw Error(`Provide exactly one of \`afterNodeId\` or \`beforeNodeId\` for ${Y} when calling \`edit_sequence_graph\`.`);if(!H&&($||z))throw Error(`\`afterNodeId\` and \`beforeNodeId\` are not used with ${Y} when calling \`edit_sequence_graph\`.`);if((Y==="replace_edges"||Y==="delete_node"&&J!==void 0)&&(!Array.isArray(J)||J.length===0))throw Error(`\`edges\` must contain the complete replacement topology for ${Y} when calling \`edit_sequence_graph\`.`);if((Y==="move_node"||Y==="duplicate_node")&&J!==void 0)throw Error(`\`edges\` is not used with ${Y} when calling \`edit_sequence_graph\`.`);let A=Array.isArray(J)?J.map((U,K)=>{if(!n(U))throw Error(`\`edges\` item ${K+1} must be an object when calling \`edit_sequence_graph\`.`);let D=E("edit_sequence_graph",U,"sourceNodeId"),L=E("edit_sequence_graph",U,"targetNodeId");if(U.condition!==void 0&&U.condition!==null&&!n(U.condition))throw Error(`\`edges\` item ${K+1} \`condition\` must be an object when calling \`edit_sequence_graph\`.`);return{sourceNodeId:D,targetNodeId:L,...n(U.condition)?{condition:U.condition}:{}}}):void 0;return{...Q.confirmStructuralChange!==void 0&&{confirmStructuralChange:Q.confirmStructuralChange},graphEdit:{action:Y,expectedRevision:X,...W?{nodeId:W}:{},...$?{afterNodeId:$}:{},...z?{beforeNodeId:z}:{},...A?{edges:A}:{}}}}function dV(Q){let Y=Q.type==="sms",X;if(Y){FH("insert_sequence_step","SMS step",Q);let W=N(Q,"text"),$=Array.isArray(Q.blocks)&&Q.blocks.length>0;if(W===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}),AX("insert_sequence_step","email step",Q),X={subject:E("insert_sequence_step",Q,"subject")};for(let W of["name","previewText","html","blocks","delay","delayMs","waitUntil","senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName"])if(Q[W]!==void 0)X[W]=Q[W]}let G={steps:[X]};if(Q.afterNodeId!==void 0)G.afterNodeId=Q.afterNodeId;return{...Q.confirmStructuralChange!==void 0&&{confirmStructuralChange:Q.confirmStructuralChange},insertSteps:G}}function oV(Q){let Y=N(Q,"subscriberId"),X=Q.fieldValues,G=X===void 0?void 0:Array.isArray(X)?X:void 0;if(X!==void 0&&G===void 0)throw Error("`fieldValues` must be an array when calling `cancel_sequence_enrollments`.");let W=G?.map((J)=>typeof J==="string"?J.trim():"").filter((J)=>J.length>0)??[];if(G?.some((J)=>typeof J!=="string")||G!==void 0&&W.length===0)throw Error("`fieldValues` must contain at least one non-empty string when calling `cancel_sequence_enrollments`.");if(Y!==void 0===W.length>0)throw Error("Provide exactly one target when calling `cancel_sequence_enrollments`: `subscriberId` or `fieldValues`.");let $=N(Q,"fieldPath"),z=N(Q,"reason");return{...Y!==void 0&&{subscriberId:Y},...$!==void 0&&{fieldPath:$},...W.length>0&&{fieldValues:W},...typeof Q.dryRun==="boolean"&&{dryRun:Q.dryRun},...z!==void 0&&{reason:z}}}function tV(Q){w1("create_campaign",Q),bQ("create_campaign",Q);let Y=N(Q,"prompt")!==void 0,X=Q.html!==void 0,G=Q.blocks!==void 0,W=Q.templateId!==void 0;if(Q.prompt!==void 0&&!Y)throw Error("`prompt` cannot be empty when calling `create_campaign`.");if(Y&&(X||G||W))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&&N(Q,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_campaign`.")}function aV(Q){w1("create_template",Q),bQ("create_template",Q);let Y=N(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&&N(Q,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_template`.")}function sV(Q){if(N(Q,"scheduledAt")===void 0)throw Error("`scheduledAt` is required when calling `schedule_campaign`.");if(Q.targetLists!==void 0&&!n(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 dY(Q,Y,X){let G=new Set(["companyId","landingPageId","name","slug","content"]),W=Object.keys(Y).filter(($)=>!G.has($));if(W.length>0)throw Error(`\`${Q}\` accepts only \`name\`, \`slug\`, and \`content\` update fields. Unsupported field${W.length===1?"":"s"}: ${W.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 eV(Q){let Y=new Set(["companyId","domain","verify"]),X=Object.keys(Q).filter((G)=>!Y.has(G));if(X.length>0)throw Error(`\`update_landing_page_domain_settings\` accepts only \`domain\` and \`verify\`. Unsupported field${X.length===1?"":"s"}: ${X.map((G)=>`\`${G}\``).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 QZ(Q){w1("create_transactional_email",Q);let Y=N(Q,"prompt")!==void 0,X=Q.html!==void 0,G=Q.blocks!==void 0;if(Q.prompt!==void 0&&!Y)throw Error("`prompt` cannot be empty when calling `create_transactional_email`.");if(Y&&(X||G))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&&!G)throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`.");if(!Y&&N(Q,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_transactional_email`.")}var GX={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},zH={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."}},oY={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:{...GX,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:sY,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:QX,delayMs:{type:"number",description:"Delay in milliseconds. Useful for standalone type:'delay' steps."},waitUntil:eY,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 YZ(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 n(Q){return typeof Q==="object"&&Q!==null&&!Array.isArray(Q)}function JH(Q){return Q.trim().toLowerCase().replace(/\s+/g,"-")}function XZ(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 WZ(Q,Y){let X=typeof Q.limit==="number"&&Number.isFinite(Q.limit)?Math.max(1,Math.trunc(Q.limit)):void 0,G=Math.min(100,Math.max(1,X??100)),W=[],$=1,z=0,J=0,H=0;while(!0){let U=XZ({query:Q.query,tags:Q.tags,list:Q.list,listId:Q.listId,listName:Q.listName,segmentId:Q.segmentId,status:Q.status,page:$,pageSize:G}),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,W.push(...K.subscribers??[]);let D=X!==void 0&&W.length>=X,L=K.pagination?$>=K.pagination.totalPages:(K.subscribers??[]).length<G;if(D||L)break;$+=1}let A=X!==void 0?W.slice(0,X):W;return{success:!0,subscribers:A,pagination:{page:1,limit:G,total:z,totalPages:J,fetchedPages:H},returned:A.length,truncated:X!==void 0&&z>0&&A.length<z}}function GZ(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=GZ(Y);if(!X.email&&!X.externalId)throw Error(`Provide either \`email\` or \`externalId\` when calling \`${Q}\`.`);return X}function $X(Q,Y){let X=new URLSearchParams;if(Y?.includeMachineEngagement)X.set("includeMachineEngagement","true");let G=X.toString(),W=G?`?${G}`:"";if(Q.email)return`/api/v1/subscribers/${encodeURIComponent(Q.email)}${W}`;return X.set("externalId",String(Q.externalId)),`/api/v1/subscribers/external?${X.toString()}`}function HH(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 tY(Q,Y,X){return B("GET",$X(Q,X),void 0,Y)}function N(Q,Y){let X=Q[Y];if(typeof X!=="string")return;let G=X.trim();return G.length>0?G:void 0}function E(Q,Y,X){let G=N(Y,X);if(G===void 0)throw Error(`\`${X}\` is required when calling \`${Q}\`.`);return G}function m0(Q,Y,X,G){let W=N(Y,X);if(W===void 0)return;if(!G.includes(W))throw Error(`\`${X}\` must be one of ${G.join(", ")} when calling \`${Q}\`.`);return W}function aY(Q,Y,X,G){let W=E(Q,Y,X);if(!G.includes(W))throw Error(`\`${X}\` must be one of ${G.join(", ")} when calling \`${Q}\`.`);return W}function x1(Q,Y,X,G,W){let $=Y[X];if($===void 0)return;if(typeof $!=="number"||!Number.isInteger($)||$<G||$>W)throw Error(`\`${X}\` must be an integer between ${G} and ${W} when calling \`${Q}\`.`);return $}function $Z(Q,Y){let X=[],G=m0(Q,Y,"eventType",cY);if(G)X.push(G);if(Y.eventTypes!==void 0){if(!Array.isArray(Y.eventTypes))throw Error(`\`eventTypes\` must be an array when calling \`${Q}\`.`);Y.eventTypes.forEach((W,$)=>{if(typeof W!=="string")throw Error(`\`eventTypes\` item ${$+1} must be a string when calling \`${Q}\`.`);let z=W.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 AH(Q,Y){let X=new URLSearchParams,G=$Z(Q,Y);if(G.length>0)X.set("eventTypes",G.join(","));let W=m0(Q,Y,"period",["1h","24h","7d","30d","90d"]);if(W)X.set("period",W);let $=N(Y,"start");if($)X.set("start",$);let z=N(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 UH(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((G,W)=>{if(typeof G!=="string"||!PQ.includes(G))throw Error(`\`events\` item ${W+1} must be one of ${PQ.join(", ")} when calling \`${Q}\`.`);return G});if(X.length===0)throw Error(`\`events\` must include at least one event type when calling \`${Q}\`.`);return X}function KH(Q,Y){if(!Array.isArray(Y.emails))throw Error(`\`emails\` must be an array when calling \`${Q}\`.`);let X=[];if(Y.emails.forEach((G,W)=>{if(typeof G!=="string")throw Error(`\`emails\` item ${W+1} must be a string when calling \`${Q}\`.`);let $=G.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>s5)throw Error(`\`emails\` must include no more than ${s5} email addresses when calling \`${Q}\`. Split larger batches into multiple calls.`);return X}function DH(Q,Y,X,G){let W=Y[X];if(W===void 0)return;if(!Array.isArray(W))throw Error(`\`${X}\` must be an array when calling \`${Q}\`.`);let $=[];if(W.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 ${G} when calling \`${Q}\`.`);return $}function zZ(Q){let X=DH("enroll_subscribers_in_sequence",Q,"emails","email address"),G=DH("enroll_subscribers_in_sequence",Q,"subscriberIds","subscriber ID"),W=(X?.length??0)+(G?.length??0);if(W===0)throw Error("Provide `emails` or `subscriberIds` when calling `enroll_subscribers_in_sequence`.");if(W>e5)throw Error(`\`emails\` and \`subscriberIds\` must include no more than ${e5} total targets when calling \`enroll_subscribers_in_sequence\`. Split larger batches into multiple calls.`);let $=N(Q,"targetNodeId");return{...X!==void 0&&{emails:X},...G!==void 0&&{subscriberIds:G},...$!==void 0&&{targetNodeId:$}}}var JZ={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 HZ(Q){let Y=Q.split(".").pop()?.toLowerCase()??"";return JZ[Y]??null}var AZ=104857600;async function UZ(Q,Y){if(!ZX())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=HZ(Q);if(!X)throw Error("Unsupported file type. Use PDF, ePub, ZIP, image, audio, video, or text files.");let G=qV(Q).size;if(G>AZ)throw Error(`File is too large (${Math.round(G/1048576)}MB). Delivery files must be 100MB or smaller.`);let W=FV(Q),$=await B("POST","/api/v1/products/delivery/upload-url",{filename:OV(Q),contentType:X,fileSizeBytes:G},Y),z=await fetch($.uploadUrl,{method:"PUT",headers:{"Content-Type":X},body:W});if(!z.ok)throw Error(`File upload failed (${z.status})`);return{url:$.publicUrl,fileName:$.fileName,fileSizeBytes:G,mimeType:X}}async function UX(Q){let Y=N(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 KZ(Q,Y){let X=await UX(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(!n(Q)||!Y)return Q;return{...Q,url:Y}}function OH(Q,Y){if(!n(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((G)=>{if(!n(G))return G;let W=N(G,"id");if(!W)return G;let $=Z1({companyId:Y,...X==="campaign"&&{campaignId:W},...X==="landingPage"&&{landingPageId:W},...X==="sequence"&&{sequenceId:W},...X==="template"&&{emailId:W},...X==="transactional"&&{transactionalId:W}});if(X==="campaign")return OH(G,$.urls);let z=X==="sequence"?$.urls.sequence:X==="landingPage"?$.urls.landingPage:X==="template"?$.urls.email:$.urls.transactionalEmail;return Y4(G,z)})}function DZ(Q){if(!Array.isArray(Q))return Q;return Q.map((Y)=>{if(!n(Y))return Y;let X=N(Y,"id");if(!X)return Y;let G=Z1({companyId:X});return{...Y,url:G.urls.dashboard,settingsUrl:G.urls.settings}})}var MH=new Set(["get_account","select_company","create_company","get_company","update_company","list_campaigns","get_campaign","get_email_send","create_campaign","update_campaign","schedule_campaign","send_test_email","cancel_campaign","pause_campaign","resume_campaign","duplicate_campaign","resend_campaign_to_non_openers","list_landing_pages","get_landing_page","create_landing_page","update_landing_page","publish_landing_page","unpublish_landing_page","delete_landing_page","list_sequences","get_sequence","create_sequence","update_sequence","update_sequence_node","update_sequence_nodes","edit_sequence_graph","insert_sequence_step","enable_sequence","disable_sequence","pause_sequence_enrollments","resume_sequence_enrollments","cancel_sequence_enrollments","list_ab_tests","get_ab_test","get_ab_test_stats","update_ab_test_variant","list_templates","get_template","create_template","update_template","list_transactional_emails","get_transactional_email","create_transactional_email","update_transactional_email"]);async function BZ(Q,Y,X){if(!n(X)||!MH.has(Q))return X;let G=n(X.company)?X.company:void 0,$=N(X,"selectedCompanyId")??N(X,"currentCompanyId")??N(X,"companyId")??(G?N(G,"id"):void 0)??(G?N(G,"companyId"):void 0)??await UX(Y);if(!$)return X;let z=n(X.campaign)?X.campaign:void 0,J=n(X.sequence)?X.sequence:void 0,H=n(X.landingPage)?X.landingPage:void 0,A=n(X.template)?X.template:void 0,U=n(X.transactional)&&!Array.isArray(X.transactional)?X.transactional:void 0,K={companyId:$,campaignId:N(Y,"campaignId")??N(X,"campaignId")??(z?N(z,"id"):void 0),landingPageId:N(Y,"landingPageId")??N(X,"landingPageId")??(H?N(H,"id"):void 0),sequenceId:N(Y,"sequenceId")??N(X,"sequenceId")??(J?N(J,"id"):void 0),emailId:N(X,"templateId")??(A?N(A,"id"):void 0)??(U?N(U,"emailId"):void 0)??N(Y,"templateId"),transactionalId:N(Y,"transactionalId")??(U?N(U,"id"):void 0)??N(Y,"idOrSlug"),emailSendId:N(Y,"emailSendId")??N(X,"emailSendId")??(n(X.emailSend)?N(X.emailSend,"id"):void 0),status:N(Y,"status")},D=Z1(K),L=G?Z1({companyId:$}):void 0;return{...X,...Array.isArray(X.companies)&&{companies:DZ(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")},...G&&L!==void 0&&{company:{...G,url:L.urls.dashboard,settingsUrl:L.urls.settings}},...z&&D.urls.campaign!==void 0&&{campaign:OH(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)},...n(X.emailSend)&&D.urls.emailSend!==void 0&&{emailSend:Y4(X.emailSend,D.urls.emailSend)},appUrls:D.urls}}var LZ={type:"boolean",description:"Whether the Sequenzy operation succeeded."},FZ={type:"string",description:"Human-readable status, confirmation, or next-step message."},qZ={type:"string",description:"Additional context about the result."};function X0(Q){return{type:"object",description:Q,additionalProperties:!0}}function OZ(Q){return{type:"array",description:Q,items:X0("One item in the returned collection.")}}function T(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 X0(`The ${Q} record returned by Sequenzy.`)}function p(Q){return OZ(`List of ${Q} records returned by Sequenzy.`)}var MZ={appUrls:X0("Dashboard URLs for relevant Sequenzy resources."),url:T("Primary dashboard URL for this result."),settingsUrl:T("Company settings URL when available.")},VZ={success:LZ,message:FZ,note:qZ,items:{type:"array",description:"Fallback array wrapper used only when a tool returns a bare array.",items:X0("One returned item.")},value:X0("Fallback object wrapper used only when a tool returns a non-object value.")},ZZ={get_account:{account:V("account"),companies:p("company"),apiKeyPermissions:X0("Current API key preset and scopes, whether common marketing work is discoverable, any missing marketing read scopes, and the API Keys management URL."),currentCompanyId:T("Company ID selected by the authenticated API key, when available."),selectedCompanyId:T("Company ID selected locally for subsequent MCP calls, when available.")},select_company:{companyId:T("Selected company ID."),companyName:T("Selected company name.")},get_app_urls:{dashboard:T("Company dashboard URL."),settings:T("Company settings URL."),campaign:T("Campaign editor URL."),landingPage:T("Landing page editor URL."),sequence:T("Sequence editor URL."),email:T("Email editor URL."),transactionalEmail:T("Transactional email URL."),emailSend:T("Sent email detail URL."),domain:T("Sending domain settings URL."),urls:X0("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:X0("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:X0("One sync rule.")},isDefault:d0("Whether the company now uses the platform default rules.")},get_shopify_automation_settings:{browseAbandonment:X0("Effective browse-abandonment settings (defaults applied)."),priceDrop:X0("Effective price-drop settings (defaults applied)."),shopDomain:T("Connected Shopify store domain.")},update_shopify_automation_settings:{browseAbandonment:X0("Effective browse-abandonment settings after the update."),priceDrop:X0("Effective price-drop settings after the update."),shopDomain:T("Connected Shopify store domain.")},create_api_key:{apiKey:X0("Created API key metadata: the newly created secret in `key`, plus `scopes` listing the assigned permission scopes (null when the key has full access)."),key:T("Newly created API key if the API response uses the short key field.")},list_websites:{websites: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:T("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:T("Verification result summary.")},get_integration_guide:{guide:V("integration guide"),code:T("Generated integration code or example."),steps:{type:"array",description:"Setup steps for the requested integration.",items:X0("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:T("Deleted subscriber note ID."),deleted:d0("Whether the subscriber note was deleted.")},search_subscribers:{subscribers:p("subscriber"),pagination:X0("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:T("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:T("Queued product sync job ID.")},list_tags:{tags:p("tag")},create_tag:{tag:V("tag")},update_tag:{tag:V("tag")},delete_tag:{tagId:T("Deleted tag ID.")},list_lists:{lists:p("list")},create_list:{list:V("list")},update_list:{list:V("list")},delete_list:{listId:T("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:T("Deleted segment ID.")},get_segment_count:{count:b0("Number of subscribers matching the segment."),segmentId:T("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:T("Deleted audience sync ID.")},sync_audience_now:{audienceSync:V("audience sync"),job:V("audience sync job"),jobId:T("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:T("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:T("Deleted A/B test variant ID.")},delete_ab_test:{abTestId:T("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:T("Scheduled send timestamp.")},send_test_email:{emailSend:V("test email send"),recipient:T("Test email recipient.")},send_test_sms:{smsSendId:T("Created test SMS send ID."),toPhone:T("Normalized E.164 destination phone.")},cancel_campaign:{campaign:V("campaign")},pause_campaign:{campaign:V("campaign")},resume_campaign:{campaign:V("campaign")},delete_campaign:{campaignId:T("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:T("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:T("Connected landing page domain.")},update_landing_page_domain_settings:{landingPage:V("landing page"),domain:T("Landing page domain.")},list_sequences:{sequences:p("sequence")},get_sequence:{sequence:V("sequence")},create_sequence:{sequence:V("sequence"),eventTrackingCode:T("Ready-to-adapt code for sending a custom trigger event, including any matching-field property."),eventTracking:X0("Custom-event endpoint, payload contract, example payload, documentation URL, and get_integration_guide arguments."),requiredEvents:{type:"array",description:"Event names the application or an integration must send.",items:T("One required event name.")}},update_sequence:{sequence:V("sequence")},update_sequence_node:{sequence:V("sequence")},update_sequence_nodes:{sequence:V("sequence")},edit_sequence_graph:{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:T("Inserted automation node ID.")},insertedEmailIds:{type:"array",description:"Email template IDs created for the inserted step.",items:T("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:T("Sequence ID."),enrollmentPaused:d0("Whether new sequence enrollments are paused.")},resume_sequence_enrollments:{sequenceId:T("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:T("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:X0("Pagination metadata.")},list_sequence_events:{events:p("sequence email event"),pagination:X0("Pagination metadata.")},get_subscriber_activity:{activity:p("subscriber activity event"),subscribers:p("subscriber"),pagination:X0("Pagination metadata.")},list_team_members:{members:p("team member"),invitations:p("team invitation")},invite_team_member:{invitation:V("team invitation")},cancel_team_invitation:{invitationId:T("Cancelled invitation ID.")},list_conversations:{conversations:p("inbox conversation"),pagination:X0("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:T("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:T("Generated HTML email body."),blocks:{type:"array",description:"Generated Sequenzy email blocks, wrapped with company branding (logo + footer) unless applyBranding was false.",items:X0("One generated email block.")},subject:T("Generated subject line."),previewText:T("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:T("One generated subject line.")},variants:p("generated subject line variant")},generate_sms:{prompt:T("The prompt the messages were generated for."),messages:{type:"array",description:"Generated SMS message variants with encoding and segment counts.",items:X0("One generated SMS message.")}},get_sms_settings:{sms:X0("SMS add-on status: enabled, planEligible, creditsBalance, brandPrefix, numbers, readyToSend (paid plan or credits plus an active number).")},submit_feedback:{}};function NZ(Q){let Y=ZZ[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:{...VZ,...Y,...MH.has(Q)?MZ:{}},additionalProperties:!0}}function wZ(Q){return{...Q,outputSchema:NZ(Q.name)}}function PZ(Q){if(n(Q))return Q;if(Array.isArray(Q))return{items:Q};return{value:Q}}var bZ=[{name:"get_account",description:`Get current account information including available companies, the current API key's permission scopes, and the API Keys management URL. Call this after a missing-scope error to inspect access and find the replacement-key settings. IMPORTANT: If you have access to multiple companies, you MUST either:
|
|
29
|
+
`)}q.write("payload.value = newResult;"),q.write("return payload;");let C=q.compile();return(S,h)=>C(O,S,h)},G,X=Sw,Y=!D0.jitless,z=Y&&s$.value,H=w.catchall,A;b._zod.parse=(O,q)=>{A??(A=Q.value);let B=O.value;if(!X(B))return O.issues.push({expected:"object",code:"invalid_type",input:B,inst:b}),O;if(Y&&z&&q?.async===!1&&q.jitless!==!0){if(!G)G=W(w.shape);if(O=G(O,q),!H)return O;return CW([],B,O,q,A,b)}return $(O,q)}});function d9(b,w,$,Q){for(let G of b)if(G.issues.length===0)return w.value=G.value,w;let W=b.filter((G)=>!Lw(G));if(W.length===1)return w.value=W[0].value,W[0];return w.issues.push({code:"invalid_union",input:w.value,inst:$,errors:b.map((G)=>G.issues.map((X)=>ub(X,Q,_b())))}),w}var H6=L("$ZodUnion",(b,w)=>{t.init(b,w),o(b._zod,"optin",()=>w.options.some((W)=>W._zod.optin==="optional")?"optional":void 0),o(b._zod,"optout",()=>w.options.some((W)=>W._zod.optout==="optional")?"optional":void 0),o(b._zod,"values",()=>{if(w.options.every((W)=>W._zod.values))return new Set(w.options.flatMap((W)=>Array.from(W._zod.values)));return}),o(b._zod,"pattern",()=>{if(w.options.every((W)=>W._zod.pattern)){let W=w.options.map((G)=>G._zod.pattern);return new RegExp(`^(${W.map((G)=>U1(G.source)).join("|")})$`)}return});let $=w.options.length===1,Q=w.options[0]._zod.run;b._zod.parse=(W,G)=>{if($)return Q(W,G);let X=!1,Y=[];for(let J of w.options){let z=J._zod.run({value:W.value,issues:[]},G);if(z instanceof Promise)Y.push(z),X=!0;else{if(z.issues.length===0)return z;Y.push(z)}}if(!X)return d9(Y,W,b,G);return Promise.all(Y).then((J)=>{return d9(J,W,b,G)})}}),kW=L("$ZodDiscriminatedUnion",(b,w)=>{H6.init(b,w);let $=b._zod.parse;o(b._zod,"propValues",()=>{let W={};for(let G of w.options){let X=G._zod.propValues;if(!X||Object.keys(X).length===0)throw Error(`Invalid discriminated union option at index "${w.options.indexOf(G)}"`);for(let[Y,J]of Object.entries(X)){if(!W[Y])W[Y]=new Set;for(let z of J)W[Y].add(z)}}return W});let Q=fw(()=>{let W=w.options,G=new Map;for(let X of W){let Y=X._zod.propValues?.[w.discriminator];if(!Y||Y.size===0)throw Error(`Invalid discriminated union option at index "${w.options.indexOf(X)}"`);for(let J of Y){if(G.has(J))throw Error(`Duplicate discriminator value "${String(J)}"`);G.set(J,X)}}return G});b._zod.parse=(W,G)=>{let X=W.value;if(!Sw(X))return W.issues.push({code:"invalid_type",expected:"object",input:X,inst:b}),W;let Y=Q.value.get(X?.[w.discriminator]);if(Y)return Y._zod.run(W,G);if(w.unionFallback)return $(W,G);return W.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:w.discriminator,input:X,path:[w.discriminator],inst:b}),W}}),xW=L("$ZodIntersection",(b,w)=>{t.init(b,w),b._zod.parse=($,Q)=>{let W=$.value,G=w.left._zod.run({value:W,issues:[]},Q),X=w.right._zod.run({value:W,issues:[]},Q);if(G instanceof Promise||X instanceof Promise)return Promise.all([G,X]).then(([J,z])=>{return r9($,J,z)});return r9($,G,X)}});function J6(b,w){if(b===w)return{valid:!0,data:b};if(b instanceof Date&&w instanceof Date&&+b===+w)return{valid:!0,data:b};if(Uw(b)&&Uw(w)){let $=Object.keys(w),Q=Object.keys(b).filter((G)=>$.indexOf(G)!==-1),W={...b,...w};for(let G of Q){let X=J6(b[G],w[G]);if(!X.valid)return{valid:!1,mergeErrorPath:[G,...X.mergeErrorPath]};W[G]=X.data}return{valid:!0,data:W}}if(Array.isArray(b)&&Array.isArray(w)){if(b.length!==w.length)return{valid:!1,mergeErrorPath:[]};let $=[];for(let Q=0;Q<b.length;Q++){let W=b[Q],G=w[Q],X=J6(W,G);if(!X.valid)return{valid:!1,mergeErrorPath:[Q,...X.mergeErrorPath]};$.push(X.data)}return{valid:!0,data:$}}return{valid:!1,mergeErrorPath:[]}}function r9(b,w,$){if(w.issues.length)b.issues.push(...w.issues);if($.issues.length)b.issues.push(...$.issues);if(Lw(b))return b;let Q=J6(w.value,$.value);if(!Q.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(Q.mergeErrorPath)}`);return b.value=Q.data,b}var uW=L("$ZodRecord",(b,w)=>{t.init(b,w),b._zod.parse=($,Q)=>{let W=$.value;if(!Uw(W))return $.issues.push({expected:"record",code:"invalid_type",input:W,inst:b}),$;let G=[];if(w.keyType._zod.values){let X=w.keyType._zod.values;$.value={};for(let J of X)if(typeof J==="string"||typeof J==="number"||typeof J==="symbol"){let z=w.valueType._zod.run({value:W[J],issues:[]},Q);if(z instanceof Promise)G.push(z.then((H)=>{if(H.issues.length)$.issues.push(...bw(J,H.issues));$.value[J]=H.value}));else{if(z.issues.length)$.issues.push(...bw(J,z.issues));$.value[J]=z.value}}let Y;for(let J in W)if(!X.has(J))Y=Y??[],Y.push(J);if(Y&&Y.length>0)$.issues.push({code:"unrecognized_keys",input:W,inst:b,keys:Y})}else{$.value={};for(let X of Reflect.ownKeys(W)){if(X==="__proto__")continue;let Y=w.keyType._zod.run({value:X,issues:[]},Q);if(Y instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(Y.issues.length){$.issues.push({code:"invalid_key",origin:"record",issues:Y.issues.map((z)=>ub(z,Q,_b())),input:X,path:[X],inst:b}),$.value[Y.value]=Y.value;continue}let J=w.valueType._zod.run({value:W[X],issues:[]},Q);if(J instanceof Promise)G.push(J.then((z)=>{if(z.issues.length)$.issues.push(...bw(X,z.issues));$.value[Y.value]=z.value}));else{if(J.issues.length)$.issues.push(...bw(X,J.issues));$.value[Y.value]=J.value}}}if(G.length)return Promise.all(G).then(()=>$);return $}});var yW=L("$ZodEnum",(b,w)=>{t.init(b,w);let $=t$(w.entries),Q=new Set($);b._zod.values=Q,b._zod.pattern=new RegExp(`^(${$.filter((W)=>a$.has(typeof W)).map((W)=>typeof W==="string"?ab(W):W.toString()).join("|")})$`),b._zod.parse=(W,G)=>{let X=W.value;if(Q.has(X))return W;return W.issues.push({code:"invalid_value",values:$,input:X,inst:b}),W}}),hW=L("$ZodLiteral",(b,w)=>{if(t.init(b,w),w.values.length===0)throw Error("Cannot create literal schema with no valid values");b._zod.values=new Set(w.values),b._zod.pattern=new RegExp(`^(${w.values.map(($)=>typeof $==="string"?ab($):$?ab($.toString()):String($)).join("|")})$`),b._zod.parse=($,Q)=>{let W=$.value;if(b._zod.values.has(W))return $;return $.issues.push({code:"invalid_value",values:w.values,input:W,inst:b}),$}});var fW=L("$ZodTransform",(b,w)=>{t.init(b,w),b._zod.parse=($,Q)=>{if(Q.direction==="backward")throw new D1(b.constructor.name);let W=w.transform($.value,$);if(Q.async)return(W instanceof Promise?W:Promise.resolve(W)).then((X)=>{return $.value=X,$});if(W instanceof Promise)throw new sb;return $.value=W,$}});function t9(b,w){if(b.issues.length&&w===void 0)return{issues:[],value:void 0};return b}var gW=L("$ZodOptional",(b,w)=>{t.init(b,w),b._zod.optin="optional",b._zod.optout="optional",o(b._zod,"values",()=>{return w.innerType._zod.values?new Set([...w.innerType._zod.values,void 0]):void 0}),o(b._zod,"pattern",()=>{let $=w.innerType._zod.pattern;return $?new RegExp(`^(${U1($.source)})?$`):void 0}),b._zod.parse=($,Q)=>{if(w.innerType._zod.optin==="optional"){let W=w.innerType._zod.run($,Q);if(W instanceof Promise)return W.then((G)=>t9(G,$.value));return t9(W,$.value)}if($.value===void 0)return $;return w.innerType._zod.run($,Q)}}),cW=L("$ZodNullable",(b,w)=>{t.init(b,w),o(b._zod,"optin",()=>w.innerType._zod.optin),o(b._zod,"optout",()=>w.innerType._zod.optout),o(b._zod,"pattern",()=>{let $=w.innerType._zod.pattern;return $?new RegExp(`^(${U1($.source)}|null)$`):void 0}),o(b._zod,"values",()=>{return w.innerType._zod.values?new Set([...w.innerType._zod.values,null]):void 0}),b._zod.parse=($,Q)=>{if($.value===null)return $;return w.innerType._zod.run($,Q)}}),mW=L("$ZodDefault",(b,w)=>{t.init(b,w),b._zod.optin="optional",o(b._zod,"values",()=>w.innerType._zod.values),b._zod.parse=($,Q)=>{if(Q.direction==="backward")return w.innerType._zod.run($,Q);if($.value===void 0)return $.value=w.defaultValue,$;let W=w.innerType._zod.run($,Q);if(W instanceof Promise)return W.then((G)=>e9(G,w));return e9(W,w)}});function e9(b,w){if(b.value===void 0)b.value=w.defaultValue;return b}var lW=L("$ZodPrefault",(b,w)=>{t.init(b,w),b._zod.optin="optional",o(b._zod,"values",()=>w.innerType._zod.values),b._zod.parse=($,Q)=>{if(Q.direction==="backward")return w.innerType._zod.run($,Q);if($.value===void 0)$.value=w.defaultValue;return w.innerType._zod.run($,Q)}}),nW=L("$ZodNonOptional",(b,w)=>{t.init(b,w),o(b._zod,"values",()=>{let $=w.innerType._zod.values;return $?new Set([...$].filter((Q)=>Q!==void 0)):void 0}),b._zod.parse=($,Q)=>{let W=w.innerType._zod.run($,Q);if(W instanceof Promise)return W.then((G)=>s9(G,b));return s9(W,b)}});function s9(b,w){if(!b.issues.length&&b.value===void 0)b.issues.push({code:"invalid_type",expected:"nonoptional",input:b.value,inst:w});return b}var iW=L("$ZodCatch",(b,w)=>{t.init(b,w),o(b._zod,"optin",()=>w.innerType._zod.optin),o(b._zod,"optout",()=>w.innerType._zod.optout),o(b._zod,"values",()=>w.innerType._zod.values),b._zod.parse=($,Q)=>{if(Q.direction==="backward")return w.innerType._zod.run($,Q);let W=w.innerType._zod.run($,Q);if(W instanceof Promise)return W.then((G)=>{if($.value=G.value,G.issues.length)$.value=w.catchValue({...$,error:{issues:G.issues.map((X)=>ub(X,Q,_b()))},input:$.value}),$.issues=[];return $});if($.value=W.value,W.issues.length)$.value=w.catchValue({...$,error:{issues:W.issues.map((G)=>ub(G,Q,_b()))},input:$.value}),$.issues=[];return $}});var pW=L("$ZodPipe",(b,w)=>{t.init(b,w),o(b._zod,"values",()=>w.in._zod.values),o(b._zod,"optin",()=>w.in._zod.optin),o(b._zod,"optout",()=>w.out._zod.optout),o(b._zod,"propValues",()=>w.in._zod.propValues),b._zod.parse=($,Q)=>{if(Q.direction==="backward"){let G=w.out._zod.run($,Q);if(G instanceof Promise)return G.then((X)=>Z0(X,w.in,Q));return Z0(G,w.in,Q)}let W=w.in._zod.run($,Q);if(W instanceof Promise)return W.then((G)=>Z0(G,w.out,Q));return Z0(W,w.out,Q)}});function Z0(b,w,$){if(b.issues.length)return b.aborted=!0,b;return w._zod.run({value:b.value,issues:b.issues},$)}var oW=L("$ZodReadonly",(b,w)=>{t.init(b,w),o(b._zod,"propValues",()=>w.innerType._zod.propValues),o(b._zod,"values",()=>w.innerType._zod.values),o(b._zod,"optin",()=>w.innerType._zod.optin),o(b._zod,"optout",()=>w.innerType._zod.optout),b._zod.parse=($,Q)=>{if(Q.direction==="backward")return w.innerType._zod.run($,Q);let W=w.innerType._zod.run($,Q);if(W instanceof Promise)return W.then(a9);return a9(W)}});function a9(b){return b.value=Object.freeze(b.value),b}var dW=L("$ZodCustom",(b,w)=>{zb.init(b,w),t.init(b,w),b._zod.parse=($,Q)=>{return $},b._zod.check=($)=>{let Q=$.value,W=w.fn(Q);if(W instanceof Promise)return W.then((G)=>bW(G,$,Q,b));bW(W,$,Q,b);return}});function bW(b,w,$,Q){if(!b){let W={code:"custom",input:$,inst:Q,path:[...Q._zod.def.path??[]],continue:!Q._zod.def.abort};if(Q._zod.def.params)W.params=Q._zod.def.params;w.issues.push(gw(W))}}var FD=(b)=>{let w=typeof b;switch(w){case"number":return Number.isNaN(b)?"NaN":"number";case"object":{if(Array.isArray(b))return"array";if(b===null)return"null";if(Object.getPrototypeOf(b)!==Object.prototype&&b.constructor)return b.constructor.name}}return w},MD=()=>{let b={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function w(Q){return b[Q]??null}let $={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return(Q)=>{switch(Q.code){case"invalid_type":return`Invalid input: expected ${Q.expected}, received ${FD(Q.input)}`;case"invalid_value":if(Q.values.length===1)return`Invalid input: expected ${L0(Q.values[0])}`;return`Invalid option: expected one of ${O0(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",G=w(Q.origin);if(G)return`Too big: expected ${Q.origin??"value"} to have ${W}${Q.maximum.toString()} ${G.unit??"elements"}`;return`Too big: expected ${Q.origin??"value"} to be ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",G=w(Q.origin);if(G)return`Too small: expected ${Q.origin} to have ${W}${Q.minimum.toString()} ${G.unit}`;return`Too small: expected ${Q.origin} to be ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Invalid string: must start with "${W.prefix}"`;if(W.format==="ends_with")return`Invalid string: must end with "${W.suffix}"`;if(W.format==="includes")return`Invalid string: must include "${W.includes}"`;if(W.format==="regex")return`Invalid string: must match pattern ${W.pattern}`;return`Invalid ${$[W.format]??Q.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${Q.divisor}`;case"unrecognized_keys":return`Unrecognized key${Q.keys.length>1?"s":""}: ${O0(Q.keys,", ")}`;case"invalid_key":return`Invalid key in ${Q.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${Q.origin}`;default:return"Invalid input"}}};function A6(){return{localeError:MD()}}var IP=Symbol("ZodOutput"),VP=Symbol("ZodInput");class rW{constructor(){this._map=new WeakMap,this._idmap=new Map}add(b,...w){let $=w[0];if(this._map.set(b,$),$&&typeof $==="object"&&"id"in $){if(this._idmap.has($.id))throw Error(`ID ${$.id} already exists in the registry`);this._idmap.set($.id,b)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(b){let w=this._map.get(b);if(w&&typeof w==="object"&&"id"in w)this._idmap.delete(w.id);return this._map.delete(b),this}get(b){let w=b._zod.parent;if(w){let $={...this.get(w)??{}};delete $.id;let Q={...$,...this._map.get(b)};return Object.keys(Q).length?Q:void 0}return this._map.get(b)}has(b){return this._map.has(b)}}function PD(){return new rW}var P1=PD();function tW(b,w){return new b({type:"string",..._(w)})}function eW(b,w){return new b({type:"string",format:"email",check:"string_format",abort:!1,..._(w)})}function D6(b,w){return new b({type:"string",format:"guid",check:"string_format",abort:!1,..._(w)})}function sW(b,w){return new b({type:"string",format:"uuid",check:"string_format",abort:!1,..._(w)})}function aW(b,w){return new b({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",..._(w)})}function b8(b,w){return new b({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",..._(w)})}function w8(b,w){return new b({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",..._(w)})}function $8(b,w){return new b({type:"string",format:"url",check:"string_format",abort:!1,..._(w)})}function Q8(b,w){return new b({type:"string",format:"emoji",check:"string_format",abort:!1,..._(w)})}function W8(b,w){return new b({type:"string",format:"nanoid",check:"string_format",abort:!1,..._(w)})}function G8(b,w){return new b({type:"string",format:"cuid",check:"string_format",abort:!1,..._(w)})}function X8(b,w){return new b({type:"string",format:"cuid2",check:"string_format",abort:!1,..._(w)})}function Y8(b,w){return new b({type:"string",format:"ulid",check:"string_format",abort:!1,..._(w)})}function J8(b,w){return new b({type:"string",format:"xid",check:"string_format",abort:!1,..._(w)})}function z8(b,w){return new b({type:"string",format:"ksuid",check:"string_format",abort:!1,..._(w)})}function H8(b,w){return new b({type:"string",format:"ipv4",check:"string_format",abort:!1,..._(w)})}function A8(b,w){return new b({type:"string",format:"ipv6",check:"string_format",abort:!1,..._(w)})}function D8(b,w){return new b({type:"string",format:"cidrv4",check:"string_format",abort:!1,..._(w)})}function O8(b,w){return new b({type:"string",format:"cidrv6",check:"string_format",abort:!1,..._(w)})}function q8(b,w){return new b({type:"string",format:"base64",check:"string_format",abort:!1,..._(w)})}function U8(b,w){return new b({type:"string",format:"base64url",check:"string_format",abort:!1,..._(w)})}function L8(b,w){return new b({type:"string",format:"e164",check:"string_format",abort:!1,..._(w)})}function B8(b,w){return new b({type:"string",format:"jwt",check:"string_format",abort:!1,..._(w)})}function K8(b,w){return new b({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,..._(w)})}function F8(b,w){return new b({type:"string",format:"date",check:"string_format",..._(w)})}function M8(b,w){return new b({type:"string",format:"time",check:"string_format",precision:null,..._(w)})}function P8(b,w){return new b({type:"string",format:"duration",check:"string_format",..._(w)})}function Z8(b,w){return new b({type:"number",checks:[],..._(w)})}function I8(b,w){return new b({type:"number",check:"number_format",abort:!1,format:"safeint",..._(w)})}function V8(b,w){return new b({type:"boolean",..._(w)})}function j8(b,w){return new b({type:"null",..._(w)})}function N8(b){return new b({type:"unknown"})}function E8(b,w){return new b({type:"never",..._(w)})}function j0(b,w){return new G6({check:"less_than",..._(w),value:b,inclusive:!1})}function Z1(b,w){return new G6({check:"less_than",..._(w),value:b,inclusive:!0})}function N0(b,w){return new X6({check:"greater_than",..._(w),value:b,inclusive:!1})}function I1(b,w){return new X6({check:"greater_than",..._(w),value:b,inclusive:!0})}function E0(b,w){return new v9({check:"multiple_of",..._(w),value:b})}function T0(b,w){return new x9({check:"max_length",..._(w),maximum:b})}function cw(b,w){return new u9({check:"min_length",..._(w),minimum:b})}function _0(b,w){return new y9({check:"length_equals",..._(w),length:b})}function O6(b,w){return new h9({check:"string_format",format:"regex",..._(w),pattern:b})}function q6(b){return new f9({check:"string_format",format:"lowercase",..._(b)})}function U6(b){return new g9({check:"string_format",format:"uppercase",..._(b)})}function L6(b,w){return new c9({check:"string_format",format:"includes",..._(w),includes:b})}function B6(b,w){return new m9({check:"string_format",format:"starts_with",..._(w),prefix:b})}function K6(b,w){return new l9({check:"string_format",format:"ends_with",..._(w),suffix:b})}function Rw(b){return new n9({check:"overwrite",tx:b})}function F6(b){return Rw((w)=>w.normalize(b))}function M6(){return Rw((b)=>b.trim())}function P6(){return Rw((b)=>b.toLowerCase())}function Z6(){return Rw((b)=>b.toUpperCase())}function T8(b,w,$){return new b({type:"array",element:w,..._($)})}function _8(b,w,$){let Q=_($);return Q.abort??(Q.abort=!0),new b({type:"custom",check:"custom",fn:w,...Q})}function S8(b,w,$){return new b({type:"custom",check:"custom",fn:w,..._($)})}function R8(b){let w=ZD(($)=>{return $.addIssue=(Q)=>{if(typeof Q==="string")$.issues.push(gw(Q,$.value,w._zod.def));else{let W=Q;if(W.fatal)W.continue=!1;W.code??(W.code="custom"),W.input??(W.input=$.value),W.inst??(W.inst=w),W.continue??(W.continue=!w._zod.def.abort),$.issues.push(gw(W))}},b($.value,$)});return w}function ZD(b,w){let $=new zb({check:"custom",..._(w)});return $._zod.check=b,$}function mw(b){return!!b._zod}function Bw(b,w){if(mw(b))return K1(b,w);return b.safeParse(w)}function S0(b){if(!b)return;let w;if(mw(b))w=b._zod?.def?.shape;else w=b.shape;if(!w)return;if(typeof w==="function")try{return w()}catch{return}return w}function C8(b){if(mw(b)){let G=b._zod?.def;if(G){if(G.value!==void 0)return G.value;if(Array.isArray(G.values)&&G.values.length>0)return G.values[0]}}let $=b._def;if($){if($.value!==void 0)return $.value;if(Array.isArray($.values)&&$.values.length>0)return $.values[0]}let Q=b.value;if(Q!==void 0)return Q;return}var j1={};RQ(j1,{time:()=>j6,duration:()=>N6,datetime:()=>I6,date:()=>V6,ZodISOTime:()=>x8,ZodISODuration:()=>u8,ZodISODateTime:()=>v8,ZodISODate:()=>k8});var v8=L("ZodISODateTime",(b,w)=>{DW.init(b,w),bb.init(b,w)});function I6(b){return K8(v8,b)}var k8=L("ZodISODate",(b,w)=>{OW.init(b,w),bb.init(b,w)});function V6(b){return F8(k8,b)}var x8=L("ZodISOTime",(b,w)=>{qW.init(b,w),bb.init(b,w)});function j6(b){return M8(x8,b)}var u8=L("ZodISODuration",(b,w)=>{UW.init(b,w),bb.init(b,w)});function N6(b){return P8(u8,b)}var y8=(b,w)=>{B0.init(b,w),b.name="ZodError",Object.defineProperties(b,{format:{value:($)=>dQ(b,$)},flatten:{value:($)=>oQ(b,$)},addIssue:{value:($)=>{b.issues.push($),b.message=JSON.stringify(b.issues,hw,2)}},addIssues:{value:($)=>{b.issues.push(...$),b.message=JSON.stringify(b.issues,hw,2)}},isEmpty:{get(){return b.issues.length===0}}})},zZ=L("ZodError",y8),Eb=L("ZodError",y8,{Parent:Error});var h8=K0(Eb),f8=F0(Eb),g8=B1(Eb),c8=F1(Eb),m8=rQ(Eb),l8=tQ(Eb),n8=eQ(Eb),i8=sQ(Eb),p8=aQ(Eb),o8=b9(Eb),d8=w9(Eb),r8=$9(Eb);var Wb=L("ZodType",(b,w)=>{return t.init(b,w),b.def=w,b.type=w.type,Object.defineProperty(b,"_def",{value:w}),b.check=(...$)=>{return b.clone(l.mergeDefs(w,{checks:[...w.checks??[],...$.map((Q)=>typeof Q==="function"?{_zod:{check:Q,def:{check:"custom"},onattach:[]}}:Q)]}))},b.clone=($,Q)=>xb(b,$,Q),b.brand=()=>b,b.register=($,Q)=>{return $.add(b,Q),b},b.parse=($,Q)=>h8(b,$,Q,{callee:b.parse}),b.safeParse=($,Q)=>g8(b,$,Q),b.parseAsync=async($,Q)=>f8(b,$,Q,{callee:b.parseAsync}),b.safeParseAsync=async($,Q)=>c8(b,$,Q),b.spa=b.safeParseAsync,b.encode=($,Q)=>m8(b,$,Q),b.decode=($,Q)=>l8(b,$,Q),b.encodeAsync=async($,Q)=>n8(b,$,Q),b.decodeAsync=async($,Q)=>i8(b,$,Q),b.safeEncode=($,Q)=>p8(b,$,Q),b.safeDecode=($,Q)=>o8(b,$,Q),b.safeEncodeAsync=async($,Q)=>d8(b,$,Q),b.safeDecodeAsync=async($,Q)=>r8(b,$,Q),b.refine=($,Q)=>b.check(K7($,Q)),b.superRefine=($)=>b.check(F7($)),b.overwrite=($)=>b.check(Rw($)),b.optional=()=>Qb(b),b.nullable=()=>s8(b),b.nullish=()=>Qb(s8(b)),b.nonoptional=($)=>D7(b,$),b.array=()=>f(b),b.or=($)=>r([b,$]),b.and=($)=>C0(b,$),b.transform=($)=>T6(b,QG($)),b.default=($)=>z7(b,$),b.prefault=($)=>A7(b,$),b.catch=($)=>q7(b,$),b.pipe=($)=>T6(b,$),b.readonly=()=>B7(b),b.describe=($)=>{let Q=b.clone();return P1.add(Q,{description:$}),Q},Object.defineProperty(b,"description",{get(){return P1.get(b)?.description},configurable:!0}),b.meta=(...$)=>{if($.length===0)return P1.get(b);let Q=b.clone();return P1.add(Q,$[0]),Q},b.isOptional=()=>b.safeParse(void 0).success,b.isNullable=()=>b.safeParse(null).success,b}),a8=L("_ZodString",(b,w)=>{V0.init(b,w),Wb.init(b,w);let $=b._zod.bag;b.format=$.format??null,b.minLength=$.minimum??null,b.maxLength=$.maximum??null,b.regex=(...Q)=>b.check(O6(...Q)),b.includes=(...Q)=>b.check(L6(...Q)),b.startsWith=(...Q)=>b.check(B6(...Q)),b.endsWith=(...Q)=>b.check(K6(...Q)),b.min=(...Q)=>b.check(cw(...Q)),b.max=(...Q)=>b.check(T0(...Q)),b.length=(...Q)=>b.check(_0(...Q)),b.nonempty=(...Q)=>b.check(cw(1,...Q)),b.lowercase=(Q)=>b.check(q6(Q)),b.uppercase=(Q)=>b.check(U6(Q)),b.trim=()=>b.check(M6()),b.normalize=(...Q)=>b.check(F6(...Q)),b.toLowerCase=()=>b.check(P6()),b.toUpperCase=()=>b.check(Z6())}),RD=L("ZodString",(b,w)=>{V0.init(b,w),a8.init(b,w),b.email=($)=>b.check(eW(CD,$)),b.url=($)=>b.check($8(vD,$)),b.jwt=($)=>b.check(B8(dD,$)),b.emoji=($)=>b.check(Q8(kD,$)),b.guid=($)=>b.check(D6(t8,$)),b.uuid=($)=>b.check(sW(R0,$)),b.uuidv4=($)=>b.check(aW(R0,$)),b.uuidv6=($)=>b.check(b8(R0,$)),b.uuidv7=($)=>b.check(w8(R0,$)),b.nanoid=($)=>b.check(W8(xD,$)),b.guid=($)=>b.check(D6(t8,$)),b.cuid=($)=>b.check(G8(uD,$)),b.cuid2=($)=>b.check(X8(yD,$)),b.ulid=($)=>b.check(Y8(hD,$)),b.base64=($)=>b.check(q8(iD,$)),b.base64url=($)=>b.check(U8(pD,$)),b.xid=($)=>b.check(J8(fD,$)),b.ksuid=($)=>b.check(z8(gD,$)),b.ipv4=($)=>b.check(H8(cD,$)),b.ipv6=($)=>b.check(A8(mD,$)),b.cidrv4=($)=>b.check(D8(lD,$)),b.cidrv6=($)=>b.check(O8(nD,$)),b.e164=($)=>b.check(L8(oD,$)),b.datetime=($)=>b.check(I6($)),b.date=($)=>b.check(V6($)),b.time=($)=>b.check(j6($)),b.duration=($)=>b.check(N6($))});function U(b){return tW(RD,b)}var bb=L("ZodStringFormat",(b,w)=>{e.init(b,w),a8.init(b,w)}),CD=L("ZodEmail",(b,w)=>{QW.init(b,w),bb.init(b,w)});var t8=L("ZodGUID",(b,w)=>{wW.init(b,w),bb.init(b,w)});var R0=L("ZodUUID",(b,w)=>{$W.init(b,w),bb.init(b,w)});var vD=L("ZodURL",(b,w)=>{WW.init(b,w),bb.init(b,w)});var kD=L("ZodEmoji",(b,w)=>{GW.init(b,w),bb.init(b,w)});var xD=L("ZodNanoID",(b,w)=>{XW.init(b,w),bb.init(b,w)});var uD=L("ZodCUID",(b,w)=>{YW.init(b,w),bb.init(b,w)});var yD=L("ZodCUID2",(b,w)=>{JW.init(b,w),bb.init(b,w)});var hD=L("ZodULID",(b,w)=>{zW.init(b,w),bb.init(b,w)});var fD=L("ZodXID",(b,w)=>{HW.init(b,w),bb.init(b,w)});var gD=L("ZodKSUID",(b,w)=>{AW.init(b,w),bb.init(b,w)});var cD=L("ZodIPv4",(b,w)=>{LW.init(b,w),bb.init(b,w)});var mD=L("ZodIPv6",(b,w)=>{BW.init(b,w),bb.init(b,w)});var lD=L("ZodCIDRv4",(b,w)=>{KW.init(b,w),bb.init(b,w)});var nD=L("ZodCIDRv6",(b,w)=>{FW.init(b,w),bb.init(b,w)});var iD=L("ZodBase64",(b,w)=>{PW.init(b,w),bb.init(b,w)});var pD=L("ZodBase64URL",(b,w)=>{ZW.init(b,w),bb.init(b,w)});var oD=L("ZodE164",(b,w)=>{IW.init(b,w),bb.init(b,w)});var dD=L("ZodJWT",(b,w)=>{VW.init(b,w),bb.init(b,w)});var bG=L("ZodNumber",(b,w)=>{z6.init(b,w),Wb.init(b,w),b.gt=(Q,W)=>b.check(N0(Q,W)),b.gte=(Q,W)=>b.check(I1(Q,W)),b.min=(Q,W)=>b.check(I1(Q,W)),b.lt=(Q,W)=>b.check(j0(Q,W)),b.lte=(Q,W)=>b.check(Z1(Q,W)),b.max=(Q,W)=>b.check(Z1(Q,W)),b.int=(Q)=>b.check(e8(Q)),b.safe=(Q)=>b.check(e8(Q)),b.positive=(Q)=>b.check(N0(0,Q)),b.nonnegative=(Q)=>b.check(I1(0,Q)),b.negative=(Q)=>b.check(j0(0,Q)),b.nonpositive=(Q)=>b.check(Z1(0,Q)),b.multipleOf=(Q,W)=>b.check(E0(Q,W)),b.step=(Q,W)=>b.check(E0(Q,W)),b.finite=()=>b;let $=b._zod.bag;b.minValue=Math.max($.minimum??Number.NEGATIVE_INFINITY,$.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,b.maxValue=Math.min($.maximum??Number.POSITIVE_INFINITY,$.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,b.isInt=($.format??"").includes("int")||Number.isSafeInteger($.multipleOf??0.5),b.isFinite=!0,b.format=$.format??null});function p(b){return Z8(bG,b)}var rD=L("ZodNumberFormat",(b,w)=>{jW.init(b,w),bG.init(b,w)});function e8(b){return I8(rD,b)}var tD=L("ZodBoolean",(b,w)=>{NW.init(b,w),Wb.init(b,w)});function Jb(b){return V8(tD,b)}var eD=L("ZodNull",(b,w)=>{EW.init(b,w),Wb.init(b,w)});function _6(b){return j8(eD,b)}var sD=L("ZodUnknown",(b,w)=>{TW.init(b,w),Wb.init(b,w)});function wb(){return N8(sD)}var aD=L("ZodNever",(b,w)=>{_W.init(b,w),Wb.init(b,w)});function b7(b){return E8(aD,b)}var w7=L("ZodArray",(b,w)=>{SW.init(b,w),Wb.init(b,w),b.element=w.element,b.min=($,Q)=>b.check(cw($,Q)),b.nonempty=($)=>b.check(cw(1,$)),b.max=($,Q)=>b.check(T0($,Q)),b.length=($,Q)=>b.check(_0($,Q)),b.unwrap=()=>b.element});function f(b,w){return T8(w7,b,w)}var wG=L("ZodObject",(b,w)=>{vW.init(b,w),Wb.init(b,w),l.defineLazy(b,"shape",()=>{return w.shape}),b.keyof=()=>Fb(Object.keys(b._zod.def.shape)),b.catchall=($)=>b.clone({...b._zod.def,catchall:$}),b.passthrough=()=>b.clone({...b._zod.def,catchall:wb()}),b.loose=()=>b.clone({...b._zod.def,catchall:wb()}),b.strict=()=>b.clone({...b._zod.def,catchall:b7()}),b.strip=()=>b.clone({...b._zod.def,catchall:void 0}),b.extend=($)=>{return l.extend(b,$)},b.safeExtend=($)=>{return l.safeExtend(b,$)},b.merge=($)=>l.merge(b,$),b.pick=($)=>l.pick(b,$),b.omit=($)=>l.omit(b,$),b.partial=(...$)=>l.partial(WG,b,$[0]),b.required=(...$)=>l.required(GG,b,$[0])});function V(b,w){let $={type:"object",shape:b??{},...l.normalizeParams(w)};return new wG($)}function Lb(b,w){return new wG({type:"object",shape:b,catchall:wb(),...l.normalizeParams(w)})}var $G=L("ZodUnion",(b,w)=>{H6.init(b,w),Wb.init(b,w),b.options=w.options});function r(b,w){return new $G({type:"union",options:b,...l.normalizeParams(w)})}var $7=L("ZodDiscriminatedUnion",(b,w)=>{$G.init(b,w),kW.init(b,w)});function S6(b,w,$){return new $7({type:"union",options:w,discriminator:b,...l.normalizeParams($)})}var Q7=L("ZodIntersection",(b,w)=>{xW.init(b,w),Wb.init(b,w)});function C0(b,w){return new Q7({type:"intersection",left:b,right:w})}var W7=L("ZodRecord",(b,w)=>{uW.init(b,w),Wb.init(b,w),b.keyType=w.keyType,b.valueType=w.valueType});function $b(b,w,$){return new W7({type:"record",keyType:b,valueType:w,...l.normalizeParams($)})}var E6=L("ZodEnum",(b,w)=>{yW.init(b,w),Wb.init(b,w),b.enum=w.entries,b.options=Object.values(w.entries);let $=new Set(Object.keys(w.entries));b.extract=(Q,W)=>{let G={};for(let X of Q)if($.has(X))G[X]=w.entries[X];else throw Error(`Key ${X} not found in enum`);return new E6({...w,checks:[],...l.normalizeParams(W),entries:G})},b.exclude=(Q,W)=>{let G={...w.entries};for(let X of Q)if($.has(X))delete G[X];else throw Error(`Key ${X} not found in enum`);return new E6({...w,checks:[],...l.normalizeParams(W),entries:G})}});function Fb(b,w){let $=Array.isArray(b)?Object.fromEntries(b.map((Q)=>[Q,Q])):b;return new E6({type:"enum",entries:$,...l.normalizeParams(w)})}var G7=L("ZodLiteral",(b,w)=>{hW.init(b,w),Wb.init(b,w),b.values=new Set(w.values),Object.defineProperty(b,"value",{get(){if(w.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return w.values[0]}})});function N(b,w){return new G7({type:"literal",values:Array.isArray(b)?b:[b],...l.normalizeParams(w)})}var X7=L("ZodTransform",(b,w)=>{fW.init(b,w),Wb.init(b,w),b._zod.parse=($,Q)=>{if(Q.direction==="backward")throw new D1(b.constructor.name);$.addIssue=(G)=>{if(typeof G==="string")$.issues.push(l.issue(G,$.value,w));else{let X=G;if(X.fatal)X.continue=!1;X.code??(X.code="custom"),X.input??(X.input=$.value),X.inst??(X.inst=b),$.issues.push(l.issue(X))}};let W=w.transform($.value,$);if(W instanceof Promise)return W.then((G)=>{return $.value=G,$});return $.value=W,$}});function QG(b){return new X7({type:"transform",transform:b})}var WG=L("ZodOptional",(b,w)=>{gW.init(b,w),Wb.init(b,w),b.unwrap=()=>b._zod.def.innerType});function Qb(b){return new WG({type:"optional",innerType:b})}var Y7=L("ZodNullable",(b,w)=>{cW.init(b,w),Wb.init(b,w),b.unwrap=()=>b._zod.def.innerType});function s8(b){return new Y7({type:"nullable",innerType:b})}var J7=L("ZodDefault",(b,w)=>{mW.init(b,w),Wb.init(b,w),b.unwrap=()=>b._zod.def.innerType,b.removeDefault=b.unwrap});function z7(b,w){return new J7({type:"default",innerType:b,get defaultValue(){return typeof w==="function"?w():l.shallowClone(w)}})}var H7=L("ZodPrefault",(b,w)=>{lW.init(b,w),Wb.init(b,w),b.unwrap=()=>b._zod.def.innerType});function A7(b,w){return new H7({type:"prefault",innerType:b,get defaultValue(){return typeof w==="function"?w():l.shallowClone(w)}})}var GG=L("ZodNonOptional",(b,w)=>{nW.init(b,w),Wb.init(b,w),b.unwrap=()=>b._zod.def.innerType});function D7(b,w){return new GG({type:"nonoptional",innerType:b,...l.normalizeParams(w)})}var O7=L("ZodCatch",(b,w)=>{iW.init(b,w),Wb.init(b,w),b.unwrap=()=>b._zod.def.innerType,b.removeCatch=b.unwrap});function q7(b,w){return new O7({type:"catch",innerType:b,catchValue:typeof w==="function"?w:()=>w})}var U7=L("ZodPipe",(b,w)=>{pW.init(b,w),Wb.init(b,w),b.in=w.in,b.out=w.out});function T6(b,w){return new U7({type:"pipe",in:b,out:w})}var L7=L("ZodReadonly",(b,w)=>{oW.init(b,w),Wb.init(b,w),b.unwrap=()=>b._zod.def.innerType});function B7(b){return new L7({type:"readonly",innerType:b})}var XG=L("ZodCustom",(b,w)=>{dW.init(b,w),Wb.init(b,w)});function YG(b,w){return _8(XG,b??(()=>!0),w)}function K7(b,w={}){return S8(XG,b,w)}function F7(b){return R8(b)}function R6(b,w){return T6(QG(b),w)}_b(A6());var C6="2025-11-25";var JG=[C6,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Kw="io.modelcontextprotocol/related-task",k0="2.0",Hb=YG((b)=>b!==null&&(typeof b==="object"||typeof b==="function")),zG=r([U(),p().int()]),HG=U(),WI=Lb({ttl:r([p(),_6()]).optional(),pollInterval:p().optional()}),M7=V({ttl:p().optional()}),P7=V({taskId:U()}),v6=Lb({progressToken:zG.optional(),[Kw]:P7.optional()}),Tb=V({_meta:v6.optional()}),N1=Tb.extend({task:M7.optional()}),AG=(b)=>N1.safeParse(b).success,Ab=V({method:U(),params:Tb.loose().optional()}),Sb=V({_meta:v6.optional()}),Rb=V({method:U(),params:Sb.loose().optional()}),Db=Lb({_meta:v6.optional()}),x0=r([U(),p().int()]),DG=V({jsonrpc:N(k0),id:x0,...Ab.shape}).strict(),k6=(b)=>DG.safeParse(b).success,OG=V({jsonrpc:N(k0),...Rb.shape}).strict(),qG=(b)=>OG.safeParse(b).success,x6=V({jsonrpc:N(k0),id:x0,result:Db}).strict(),E1=(b)=>x6.safeParse(b).success;var g;(function(b){b[b.ConnectionClosed=-32000]="ConnectionClosed",b[b.RequestTimeout=-32001]="RequestTimeout",b[b.ParseError=-32700]="ParseError",b[b.InvalidRequest=-32600]="InvalidRequest",b[b.MethodNotFound=-32601]="MethodNotFound",b[b.InvalidParams=-32602]="InvalidParams",b[b.InternalError=-32603]="InternalError",b[b.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(g||(g={}));var u6=V({jsonrpc:N(k0),id:x0.optional(),error:V({code:p().int(),message:U(),data:wb().optional()})}).strict();var UG=(b)=>u6.safeParse(b).success;var LG=r([DG,OG,x6,u6]),GI=r([x6,u6]),u0=Db.strict(),Z7=Sb.extend({requestId:x0.optional(),reason:U().optional()}),y0=Rb.extend({method:N("notifications/cancelled"),params:Z7}),I7=V({src:U(),mimeType:U().optional(),sizes:f(U()).optional(),theme:Fb(["light","dark"]).optional()}),T1=V({icons:f(I7).optional()}),lw=V({name:U(),title:U().optional()}),BG=lw.extend({...lw.shape,...T1.shape,version:U(),websiteUrl:U().optional(),description:U().optional()}),V7=C0(V({applyDefaults:Jb().optional()}),$b(U(),wb())),j7=R6((b)=>{if(b&&typeof b==="object"&&!Array.isArray(b)){if(Object.keys(b).length===0)return{form:{}}}return b},C0(V({form:V7.optional(),url:Hb.optional()}),$b(U(),wb()).optional())),N7=Lb({list:Hb.optional(),cancel:Hb.optional(),requests:Lb({sampling:Lb({createMessage:Hb.optional()}).optional(),elicitation:Lb({create:Hb.optional()}).optional()}).optional()}),E7=Lb({list:Hb.optional(),cancel:Hb.optional(),requests:Lb({tools:Lb({call:Hb.optional()}).optional()}).optional()}),T7=V({experimental:$b(U(),Hb).optional(),sampling:V({context:Hb.optional(),tools:Hb.optional()}).optional(),elicitation:j7.optional(),roots:V({listChanged:Jb().optional()}).optional(),tasks:N7.optional()}),_7=Tb.extend({protocolVersion:U(),capabilities:T7,clientInfo:BG}),y6=Ab.extend({method:N("initialize"),params:_7});var S7=V({experimental:$b(U(),Hb).optional(),logging:Hb.optional(),completions:Hb.optional(),prompts:V({listChanged:Jb().optional()}).optional(),resources:V({subscribe:Jb().optional(),listChanged:Jb().optional()}).optional(),tools:V({listChanged:Jb().optional()}).optional(),tasks:E7.optional()}),R7=Db.extend({protocolVersion:U(),capabilities:S7,serverInfo:BG,instructions:U().optional()}),h6=Rb.extend({method:N("notifications/initialized"),params:Sb.optional()});var h0=Ab.extend({method:N("ping"),params:Tb.optional()}),C7=V({progress:p(),total:Qb(p()),message:Qb(U())}),v7=V({...Sb.shape,...C7.shape,progressToken:zG}),f0=Rb.extend({method:N("notifications/progress"),params:v7}),k7=Tb.extend({cursor:HG.optional()}),_1=Ab.extend({params:k7.optional()}),S1=Db.extend({nextCursor:HG.optional()}),x7=Fb(["working","input_required","completed","failed","cancelled"]),R1=V({taskId:U(),status:x7,ttl:r([p(),_6()]),createdAt:U(),lastUpdatedAt:U(),pollInterval:Qb(p()),statusMessage:Qb(U())}),nw=Db.extend({task:R1}),u7=Sb.merge(R1),C1=Rb.extend({method:N("notifications/tasks/status"),params:u7}),g0=Ab.extend({method:N("tasks/get"),params:Tb.extend({taskId:U()})}),c0=Db.merge(R1),m0=Ab.extend({method:N("tasks/result"),params:Tb.extend({taskId:U()})}),XI=Db.loose(),l0=_1.extend({method:N("tasks/list")}),n0=S1.extend({tasks:f(R1)}),i0=Ab.extend({method:N("tasks/cancel"),params:Tb.extend({taskId:U()})}),KG=Db.merge(R1),FG=V({uri:U(),mimeType:Qb(U()),_meta:$b(U(),wb()).optional()}),MG=FG.extend({text:U()}),f6=U().refine((b)=>{try{return atob(b),!0}catch{return!1}},{message:"Invalid Base64 string"}),PG=FG.extend({blob:f6}),v1=Fb(["user","assistant"]),iw=V({audience:f(v1).optional(),priority:p().min(0).max(1).optional(),lastModified:j1.datetime({offset:!0}).optional()}),ZG=V({...lw.shape,...T1.shape,uri:U(),description:Qb(U()),mimeType:Qb(U()),annotations:iw.optional(),_meta:Qb(Lb({}))}),y7=V({...lw.shape,...T1.shape,uriTemplate:U(),description:Qb(U()),mimeType:Qb(U()),annotations:iw.optional(),_meta:Qb(Lb({}))}),g6=_1.extend({method:N("resources/list")}),h7=S1.extend({resources:f(ZG)}),f7=_1.extend({method:N("resources/templates/list")}),g7=S1.extend({resourceTemplates:f(y7)}),c6=Tb.extend({uri:U()}),c7=c6,m6=Ab.extend({method:N("resources/read"),params:c7}),m7=Db.extend({contents:f(r([MG,PG]))}),l7=Rb.extend({method:N("notifications/resources/list_changed"),params:Sb.optional()}),n7=c6,i7=Ab.extend({method:N("resources/subscribe"),params:n7}),p7=c6,o7=Ab.extend({method:N("resources/unsubscribe"),params:p7}),d7=Sb.extend({uri:U()}),r7=Rb.extend({method:N("notifications/resources/updated"),params:d7}),t7=V({name:U(),description:Qb(U()),required:Qb(Jb())}),e7=V({...lw.shape,...T1.shape,description:Qb(U()),arguments:Qb(f(t7)),_meta:Qb(Lb({}))}),s7=_1.extend({method:N("prompts/list")}),a7=S1.extend({prompts:f(e7)}),b5=Tb.extend({name:U(),arguments:$b(U(),U()).optional()}),w5=Ab.extend({method:N("prompts/get"),params:b5}),l6=V({type:N("text"),text:U(),annotations:iw.optional(),_meta:$b(U(),wb()).optional()}),n6=V({type:N("image"),data:f6,mimeType:U(),annotations:iw.optional(),_meta:$b(U(),wb()).optional()}),i6=V({type:N("audio"),data:f6,mimeType:U(),annotations:iw.optional(),_meta:$b(U(),wb()).optional()}),$5=V({type:N("tool_use"),name:U(),id:U(),input:$b(U(),wb()),_meta:$b(U(),wb()).optional()}),Q5=V({type:N("resource"),resource:r([MG,PG]),annotations:iw.optional(),_meta:$b(U(),wb()).optional()}),W5=ZG.extend({type:N("resource_link")}),p6=r([l6,n6,i6,W5,Q5]),G5=V({role:v1,content:p6}),X5=Db.extend({description:U().optional(),messages:f(G5)}),Y5=Rb.extend({method:N("notifications/prompts/list_changed"),params:Sb.optional()}),J5=V({title:U().optional(),readOnlyHint:Jb().optional(),destructiveHint:Jb().optional(),idempotentHint:Jb().optional(),openWorldHint:Jb().optional()}),z5=V({taskSupport:Fb(["required","optional","forbidden"]).optional()}),IG=V({...lw.shape,...T1.shape,description:U().optional(),inputSchema:V({type:N("object"),properties:$b(U(),Hb).optional(),required:f(U()).optional()}).catchall(wb()),outputSchema:V({type:N("object"),properties:$b(U(),Hb).optional(),required:f(U()).optional()}).catchall(wb()).optional(),annotations:J5.optional(),execution:z5.optional(),_meta:$b(U(),wb()).optional()}),o6=_1.extend({method:N("tools/list")}),H5=S1.extend({tools:f(IG)}),p0=Db.extend({content:f(p6).default([]),structuredContent:$b(U(),wb()).optional(),isError:Jb().optional()}),YI=p0.or(Db.extend({toolResult:wb()})),A5=N1.extend({name:U(),arguments:$b(U(),wb()).optional()}),k1=Ab.extend({method:N("tools/call"),params:A5}),D5=Rb.extend({method:N("notifications/tools/list_changed"),params:Sb.optional()}),JI=V({autoRefresh:Jb().default(!0),debounceMs:p().int().nonnegative().default(300)}),x1=Fb(["debug","info","notice","warning","error","critical","alert","emergency"]),O5=Tb.extend({level:x1}),d6=Ab.extend({method:N("logging/setLevel"),params:O5}),q5=Sb.extend({level:x1,logger:U().optional(),data:wb()}),U5=Rb.extend({method:N("notifications/message"),params:q5}),L5=V({name:U().optional()}),B5=V({hints:f(L5).optional(),costPriority:p().min(0).max(1).optional(),speedPriority:p().min(0).max(1).optional(),intelligencePriority:p().min(0).max(1).optional()}),K5=V({mode:Fb(["auto","required","none"]).optional()}),F5=V({type:N("tool_result"),toolUseId:U().describe("The unique identifier for the corresponding tool call."),content:f(p6).default([]),structuredContent:V({}).loose().optional(),isError:Jb().optional(),_meta:$b(U(),wb()).optional()}),M5=S6("type",[l6,n6,i6]),v0=S6("type",[l6,n6,i6,$5,F5]),P5=V({role:v1,content:r([v0,f(v0)]),_meta:$b(U(),wb()).optional()}),Z5=N1.extend({messages:f(P5),modelPreferences:B5.optional(),systemPrompt:U().optional(),includeContext:Fb(["none","thisServer","allServers"]).optional(),temperature:p().optional(),maxTokens:p().int(),stopSequences:f(U()).optional(),metadata:Hb.optional(),tools:f(IG).optional(),toolChoice:K5.optional()}),I5=Ab.extend({method:N("sampling/createMessage"),params:Z5}),r6=Db.extend({model:U(),stopReason:Qb(Fb(["endTurn","stopSequence","maxTokens"]).or(U())),role:v1,content:M5}),t6=Db.extend({model:U(),stopReason:Qb(Fb(["endTurn","stopSequence","maxTokens","toolUse"]).or(U())),role:v1,content:r([v0,f(v0)])}),V5=V({type:N("boolean"),title:U().optional(),description:U().optional(),default:Jb().optional()}),j5=V({type:N("string"),title:U().optional(),description:U().optional(),minLength:p().optional(),maxLength:p().optional(),format:Fb(["email","uri","date","date-time"]).optional(),default:U().optional()}),N5=V({type:Fb(["number","integer"]),title:U().optional(),description:U().optional(),minimum:p().optional(),maximum:p().optional(),default:p().optional()}),E5=V({type:N("string"),title:U().optional(),description:U().optional(),enum:f(U()),default:U().optional()}),T5=V({type:N("string"),title:U().optional(),description:U().optional(),oneOf:f(V({const:U(),title:U()})),default:U().optional()}),_5=V({type:N("string"),title:U().optional(),description:U().optional(),enum:f(U()),enumNames:f(U()).optional(),default:U().optional()}),S5=r([E5,T5]),R5=V({type:N("array"),title:U().optional(),description:U().optional(),minItems:p().optional(),maxItems:p().optional(),items:V({type:N("string"),enum:f(U())}),default:f(U()).optional()}),C5=V({type:N("array"),title:U().optional(),description:U().optional(),minItems:p().optional(),maxItems:p().optional(),items:V({anyOf:f(V({const:U(),title:U()}))}),default:f(U()).optional()}),v5=r([R5,C5]),k5=r([_5,S5,v5]),x5=r([k5,V5,j5,N5]),u5=N1.extend({mode:N("form").optional(),message:U(),requestedSchema:V({type:N("object"),properties:$b(U(),x5),required:f(U()).optional()})}),y5=N1.extend({mode:N("url"),message:U(),elicitationId:U(),url:U().url()}),h5=r([u5,y5]),f5=Ab.extend({method:N("elicitation/create"),params:h5}),g5=Sb.extend({elicitationId:U()}),c5=Rb.extend({method:N("notifications/elicitation/complete"),params:g5}),o0=Db.extend({action:Fb(["accept","decline","cancel"]),content:R6((b)=>b===null?void 0:b,$b(U(),r([U(),p(),Jb(),f(U())])).optional())}),m5=V({type:N("ref/resource"),uri:U()});var l5=V({type:N("ref/prompt"),name:U()}),n5=Tb.extend({ref:r([l5,m5]),argument:V({name:U(),value:U()}),context:V({arguments:$b(U(),U()).optional()}).optional()}),i5=Ab.extend({method:N("completion/complete"),params:n5});var p5=Db.extend({completion:Lb({values:f(U()).max(100),total:Qb(p().int()),hasMore:Qb(Jb())})}),o5=V({uri:U().startsWith("file://"),name:U().optional(),_meta:$b(U(),wb()).optional()}),d5=Ab.extend({method:N("roots/list"),params:Tb.optional()}),e6=Db.extend({roots:f(o5)}),r5=Rb.extend({method:N("notifications/roots/list_changed"),params:Sb.optional()}),zI=r([h0,y6,i5,d6,w5,s7,g6,f7,m6,i7,o7,k1,o6,g0,m0,l0,i0]),HI=r([y0,f0,h6,r5,C1]),AI=r([u0,r6,t6,o0,e6,c0,n0,nw]),DI=r([h0,I5,f5,d5,g0,m0,l0,i0]),OI=r([y0,f0,U5,r7,l7,D5,Y5,C1,c5]),qI=r([u0,R7,p5,X5,a7,h7,g7,m7,p0,H5,c0,n0,nw]);class x extends Error{constructor(b,w,$){super(`MCP error ${b}: ${w}`);this.code=b,this.data=$,this.name="McpError"}static fromError(b,w,$){if(b===g.UrlElicitationRequired&&$){let Q=$;if(Q.elicitations)return new VG(Q.elicitations,w)}return new x(b,w,$)}}class VG extends x{constructor(b,w=`URL elicitation${b.length>1?"s":""} required`){super(g.UrlElicitationRequired,w,{elicitations:b})}get elicitations(){return this.data?.elicitations??[]}}function Fw(b){return b==="completed"||b==="failed"||b==="cancelled"}var t5=Symbol("Let zodToJsonSchema decide on which parser to use");var oI=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function s6(b){let $=S0(b)?.method;if(!$)throw Error("Schema is missing a method literal");let Q=C8($);if(typeof Q!=="string")throw Error("Schema method literal must be a string");return Q}function a6(b,w){let $=Bw(b,w);if(!$.success)throw $.error;return $.data}var $O=60000;class b4{constructor(b){if(this._options=b,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(y0,(w)=>{this._oncancel(w)}),this.setNotificationHandler(f0,(w)=>{this._onprogress(w)}),this.setRequestHandler(h0,(w)=>({})),this._taskStore=b?.taskStore,this._taskMessageQueue=b?.taskMessageQueue,this._taskStore)this.setRequestHandler(g0,async(w,$)=>{let Q=await this._taskStore.getTask(w.params.taskId,$.sessionId);if(!Q)throw new x(g.InvalidParams,"Failed to retrieve task: Task not found");return{...Q}}),this.setRequestHandler(m0,async(w,$)=>{let Q=async()=>{let W=w.params.taskId;if(this._taskMessageQueue){let X;while(X=await this._taskMessageQueue.dequeue(W,$.sessionId)){if(X.type==="response"||X.type==="error"){let Y=X.message,J=Y.id,z=this._requestResolvers.get(J);if(z)if(this._requestResolvers.delete(J),X.type==="response")z(Y);else{let H=Y,A=new x(H.error.code,H.error.message,H.error.data);z(A)}else{let H=X.type==="response"?"Response":"Error";this._onerror(Error(`${H} handler missing for request ${J}`))}continue}await this._transport?.send(X.message,{relatedRequestId:$.requestId})}}let G=await this._taskStore.getTask(W,$.sessionId);if(!G)throw new x(g.InvalidParams,`Task not found: ${W}`);if(!Fw(G.status))return await this._waitForTaskUpdate(W,$.signal),await Q();if(Fw(G.status)){let X=await this._taskStore.getTaskResult(W,$.sessionId);return this._clearTaskQueue(W),{...X,_meta:{...X._meta,[Kw]:{taskId:W}}}}return await Q()};return await Q()}),this.setRequestHandler(l0,async(w,$)=>{try{let{tasks:Q,nextCursor:W}=await this._taskStore.listTasks(w.params?.cursor,$.sessionId);return{tasks:Q,nextCursor:W,_meta:{}}}catch(Q){throw new x(g.InvalidParams,`Failed to list tasks: ${Q instanceof Error?Q.message:String(Q)}`)}}),this.setRequestHandler(i0,async(w,$)=>{try{let Q=await this._taskStore.getTask(w.params.taskId,$.sessionId);if(!Q)throw new x(g.InvalidParams,`Task not found: ${w.params.taskId}`);if(Fw(Q.status))throw new x(g.InvalidParams,`Cannot cancel task in terminal status: ${Q.status}`);await this._taskStore.updateTaskStatus(w.params.taskId,"cancelled","Client cancelled task execution.",$.sessionId),this._clearTaskQueue(w.params.taskId);let W=await this._taskStore.getTask(w.params.taskId,$.sessionId);if(!W)throw new x(g.InvalidParams,`Task not found after cancellation: ${w.params.taskId}`);return{_meta:{},...W}}catch(Q){if(Q instanceof x)throw Q;throw new x(g.InvalidRequest,`Failed to cancel task: ${Q instanceof Error?Q.message:String(Q)}`)}})}async _oncancel(b){if(!b.params.requestId)return;this._requestHandlerAbortControllers.get(b.params.requestId)?.abort(b.params.reason)}_setupTimeout(b,w,$,Q,W=!1){this._timeoutInfo.set(b,{timeoutId:setTimeout(Q,w),startTime:Date.now(),timeout:w,maxTotalTimeout:$,resetTimeoutOnProgress:W,onTimeout:Q})}_resetTimeout(b){let w=this._timeoutInfo.get(b);if(!w)return!1;let $=Date.now()-w.startTime;if(w.maxTotalTimeout&&$>=w.maxTotalTimeout)throw this._timeoutInfo.delete(b),x.fromError(g.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:w.maxTotalTimeout,totalElapsed:$});return clearTimeout(w.timeoutId),w.timeoutId=setTimeout(w.onTimeout,w.timeout),!0}_cleanupTimeout(b){let w=this._timeoutInfo.get(b);if(w)clearTimeout(w.timeoutId),this._timeoutInfo.delete(b)}async connect(b){this._transport=b;let w=this.transport?.onclose;this._transport.onclose=()=>{w?.(),this._onclose()};let $=this.transport?.onerror;this._transport.onerror=(W)=>{$?.(W),this._onerror(W)};let Q=this._transport?.onmessage;this._transport.onmessage=(W,G)=>{if(Q?.(W,G),E1(W)||UG(W))this._onresponse(W);else if(k6(W))this._onrequest(W,G);else if(qG(W))this._onnotification(W);else this._onerror(Error(`Unknown message type: ${JSON.stringify(W)}`))},await this._transport.start()}_onclose(){let b=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();let w=x.fromError(g.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let $ of b.values())$(w)}_onerror(b){this.onerror?.(b)}_onnotification(b){let w=this._notificationHandlers.get(b.method)??this.fallbackNotificationHandler;if(w===void 0)return;Promise.resolve().then(()=>w(b)).catch(($)=>this._onerror(Error(`Uncaught error in notification handler: ${$}`)))}_onrequest(b,w){let $=this._requestHandlers.get(b.method)??this.fallbackRequestHandler,Q=this._transport,W=b.params?._meta?.[Kw]?.taskId;if($===void 0){let z={jsonrpc:"2.0",id:b.id,error:{code:g.MethodNotFound,message:"Method not found"}};if(W&&this._taskMessageQueue)this._enqueueTaskMessage(W,{type:"error",message:z,timestamp:Date.now()},Q?.sessionId).catch((H)=>this._onerror(Error(`Failed to enqueue error response: ${H}`)));else Q?.send(z).catch((H)=>this._onerror(Error(`Failed to send an error response: ${H}`)));return}let G=new AbortController;this._requestHandlerAbortControllers.set(b.id,G);let X=AG(b.params)?b.params.task:void 0,Y=this._taskStore?this.requestTaskStore(b,Q?.sessionId):void 0,J={signal:G.signal,sessionId:Q?.sessionId,_meta:b.params?._meta,sendNotification:async(z)=>{let H={relatedRequestId:b.id};if(W)H.relatedTask={taskId:W};await this.notification(z,H)},sendRequest:async(z,H,A)=>{let O={...A,relatedRequestId:b.id};if(W&&!O.relatedTask)O.relatedTask={taskId:W};let q=O.relatedTask?.taskId??W;if(q&&Y)await Y.updateTaskStatus(q,"input_required");return await this.request(z,H,O)},authInfo:w?.authInfo,requestId:b.id,requestInfo:w?.requestInfo,taskId:W,taskStore:Y,taskRequestedTtl:X?.ttl,closeSSEStream:w?.closeSSEStream,closeStandaloneSSEStream:w?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(X)this.assertTaskHandlerCapability(b.method)}).then(()=>$(b,J)).then(async(z)=>{if(G.signal.aborted)return;let H={result:z,jsonrpc:"2.0",id:b.id};if(W&&this._taskMessageQueue)await this._enqueueTaskMessage(W,{type:"response",message:H,timestamp:Date.now()},Q?.sessionId);else await Q?.send(H)},async(z)=>{if(G.signal.aborted)return;let H={jsonrpc:"2.0",id:b.id,error:{code:Number.isSafeInteger(z.code)?z.code:g.InternalError,message:z.message??"Internal error",...z.data!==void 0&&{data:z.data}}};if(W&&this._taskMessageQueue)await this._enqueueTaskMessage(W,{type:"error",message:H,timestamp:Date.now()},Q?.sessionId);else await Q?.send(H)}).catch((z)=>this._onerror(Error(`Failed to send response: ${z}`))).finally(()=>{this._requestHandlerAbortControllers.delete(b.id)})}_onprogress(b){let{progressToken:w,...$}=b.params,Q=Number(w),W=this._progressHandlers.get(Q);if(!W){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(b)}`));return}let G=this._responseHandlers.get(Q),X=this._timeoutInfo.get(Q);if(X&&G&&X.resetTimeoutOnProgress)try{this._resetTimeout(Q)}catch(Y){this._responseHandlers.delete(Q),this._progressHandlers.delete(Q),this._cleanupTimeout(Q),G(Y);return}W($)}_onresponse(b){let w=Number(b.id),$=this._requestResolvers.get(w);if($){if(this._requestResolvers.delete(w),E1(b))$(b);else{let G=new x(b.error.code,b.error.message,b.error.data);$(G)}return}let Q=this._responseHandlers.get(w);if(Q===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(b)}`));return}this._responseHandlers.delete(w),this._cleanupTimeout(w);let W=!1;if(E1(b)&&b.result&&typeof b.result==="object"){let G=b.result;if(G.task&&typeof G.task==="object"){let X=G.task;if(typeof X.taskId==="string")W=!0,this._taskProgressTokens.set(X.taskId,w)}}if(!W)this._progressHandlers.delete(w);if(E1(b))Q(b);else{let G=x.fromError(b.error.code,b.error.message,b.error.data);Q(G)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(b,w,$){let{task:Q}=$??{};if(!Q){try{yield{type:"result",result:await this.request(b,w,$)}}catch(G){yield{type:"error",error:G instanceof x?G:new x(g.InternalError,String(G))}}return}let W;try{let G=await this.request(b,nw,$);if(G.task)W=G.task.taskId,yield{type:"taskCreated",task:G.task};else throw new x(g.InternalError,"Task creation did not return a task");while(!0){let X=await this.getTask({taskId:W},$);if(yield{type:"taskStatus",task:X},Fw(X.status)){if(X.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:W},w,$)};else if(X.status==="failed")yield{type:"error",error:new x(g.InternalError,`Task ${W} failed`)};else if(X.status==="cancelled")yield{type:"error",error:new x(g.InternalError,`Task ${W} was cancelled`)};return}if(X.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:W},w,$)};return}let Y=X.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((J)=>setTimeout(J,Y)),$?.signal?.throwIfAborted()}}catch(G){yield{type:"error",error:G instanceof x?G:new x(g.InternalError,String(G))}}}request(b,w,$){let{relatedRequestId:Q,resumptionToken:W,onresumptiontoken:G,task:X,relatedTask:Y}=$??{};return new Promise((J,z)=>{let H=(P)=>{z(P)};if(!this._transport){H(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(b.method),X)this.assertTaskCapability(b.method)}catch(P){H(P);return}$?.signal?.throwIfAborted();let A=this._requestMessageId++,O={...b,jsonrpc:"2.0",id:A};if($?.onprogress)this._progressHandlers.set(A,$.onprogress),O.params={...b.params,_meta:{...b.params?._meta||{},progressToken:A}};if(X)O.params={...O.params,task:X};if(Y)O.params={...O.params,_meta:{...O.params?._meta||{},[Kw]:Y}};let q=(P)=>{this._responseHandlers.delete(A),this._progressHandlers.delete(A),this._cleanupTimeout(A),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:A,reason:String(P)}},{relatedRequestId:Q,resumptionToken:W,onresumptiontoken:G}).catch((S)=>this._onerror(Error(`Failed to send cancellation: ${S}`)));let C=P instanceof x?P:new x(g.RequestTimeout,String(P));z(C)};this._responseHandlers.set(A,(P)=>{if($?.signal?.aborted)return;if(P instanceof Error)return z(P);try{let C=Bw(w,P.result);if(!C.success)z(C.error);else J(C.data)}catch(C){z(C)}}),$?.signal?.addEventListener("abort",()=>{q($?.signal?.reason)});let B=$?.timeout??$O,K=()=>q(x.fromError(g.RequestTimeout,"Request timed out",{timeout:B}));this._setupTimeout(A,B,$?.maxTotalTimeout,K,$?.resetTimeoutOnProgress??!1);let Z=Y?.taskId;if(Z){let P=(C)=>{let S=this._responseHandlers.get(A);if(S)S(C);else this._onerror(Error(`Response handler missing for side-channeled request ${A}`))};this._requestResolvers.set(A,P),this._enqueueTaskMessage(Z,{type:"request",message:O,timestamp:Date.now()}).catch((C)=>{this._cleanupTimeout(A),z(C)})}else this._transport.send(O,{relatedRequestId:Q,resumptionToken:W,onresumptiontoken:G}).catch((P)=>{this._cleanupTimeout(A),z(P)})})}async getTask(b,w){return this.request({method:"tasks/get",params:b},c0,w)}async getTaskResult(b,w,$){return this.request({method:"tasks/result",params:b},w,$)}async listTasks(b,w){return this.request({method:"tasks/list",params:b},n0,w)}async cancelTask(b,w){return this.request({method:"tasks/cancel",params:b},KG,w)}async notification(b,w){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(b.method);let $=w?.relatedTask?.taskId;if($){let X={...b,jsonrpc:"2.0",params:{...b.params,_meta:{...b.params?._meta||{},[Kw]:w.relatedTask}}};await this._enqueueTaskMessage($,{type:"notification",message:X,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(b.method)&&!b.params&&!w?.relatedRequestId&&!w?.relatedTask){if(this._pendingDebouncedNotifications.has(b.method))return;this._pendingDebouncedNotifications.add(b.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(b.method),!this._transport)return;let X={...b,jsonrpc:"2.0"};if(w?.relatedTask)X={...X,params:{...X.params,_meta:{...X.params?._meta||{},[Kw]:w.relatedTask}}};this._transport?.send(X,w).catch((Y)=>this._onerror(Y))});return}let G={...b,jsonrpc:"2.0"};if(w?.relatedTask)G={...G,params:{...G.params,_meta:{...G.params?._meta||{},[Kw]:w.relatedTask}}};await this._transport.send(G,w)}setRequestHandler(b,w){let $=s6(b);this.assertRequestHandlerCapability($),this._requestHandlers.set($,(Q,W)=>{let G=a6(b,Q);return Promise.resolve(w(G,W))})}removeRequestHandler(b){this._requestHandlers.delete(b)}assertCanSetRequestHandler(b){if(this._requestHandlers.has(b))throw Error(`A request handler for ${b} already exists, which would be overridden`)}setNotificationHandler(b,w){let $=s6(b);this._notificationHandlers.set($,(Q)=>{let W=a6(b,Q);return Promise.resolve(w(W))})}removeNotificationHandler(b){this._notificationHandlers.delete(b)}_cleanupTaskProgressHandler(b){let w=this._taskProgressTokens.get(b);if(w!==void 0)this._progressHandlers.delete(w),this._taskProgressTokens.delete(b)}async _enqueueTaskMessage(b,w,$){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let Q=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(b,w,$,Q)}async _clearTaskQueue(b,w){if(this._taskMessageQueue){let $=await this._taskMessageQueue.dequeueAll(b,w);for(let Q of $)if(Q.type==="request"&&k6(Q.message)){let W=Q.message.id,G=this._requestResolvers.get(W);if(G)G(new x(g.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(W);else this._onerror(Error(`Resolver missing for request ${W} during task ${b} cleanup`))}}}async _waitForTaskUpdate(b,w){let $=this._options?.defaultTaskPollInterval??1000;try{let Q=await this._taskStore?.getTask(b);if(Q?.pollInterval)$=Q.pollInterval}catch{}return new Promise((Q,W)=>{if(w.aborted){W(new x(g.InvalidRequest,"Request cancelled"));return}let G=setTimeout(Q,$);w.addEventListener("abort",()=>{clearTimeout(G),W(new x(g.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(b,w){let $=this._taskStore;if(!$)throw Error("No task store configured");return{createTask:async(Q)=>{if(!b)throw Error("No request provided");return await $.createTask(Q,b.id,{method:b.method,params:b.params},w)},getTask:async(Q)=>{let W=await $.getTask(Q,w);if(!W)throw new x(g.InvalidParams,"Failed to retrieve task: Task not found");return W},storeTaskResult:async(Q,W,G)=>{await $.storeTaskResult(Q,W,G,w);let X=await $.getTask(Q,w);if(X){let Y=C1.parse({method:"notifications/tasks/status",params:X});if(await this.notification(Y),Fw(X.status))this._cleanupTaskProgressHandler(Q)}},getTaskResult:(Q)=>{return $.getTaskResult(Q,w)},updateTaskStatus:async(Q,W,G)=>{let X=await $.getTask(Q,w);if(!X)throw new x(g.InvalidParams,`Task "${Q}" not found - it may have been cleaned up`);if(Fw(X.status))throw new x(g.InvalidParams,`Cannot update task "${Q}" from terminal status "${X.status}" to "${W}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await $.updateTaskStatus(Q,W,G,w);let Y=await $.getTask(Q,w);if(Y){let J=C1.parse({method:"notifications/tasks/status",params:Y});if(await this.notification(J),Fw(Y.status))this._cleanupTaskProgressHandler(Q)}},listTasks:(Q)=>{return $.listTasks(Q,w)}}}}function jG(b){return b!==null&&typeof b==="object"&&!Array.isArray(b)}function NG(b,w){let $={...b};for(let Q in w){let W=Q,G=w[W];if(G===void 0)continue;let X=$[W];if(jG(X)&&jG(G))$[W]={...X,...G};else $[W]=G}return $}var QH=SQ(d4(),1),WH=SQ($H(),1);function AM(){let b=new QH.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return WH.default(b),b}class WQ{constructor(b){this._ajv=b??AM()}getValidator(b){let w="$id"in b&&typeof b.$id==="string"?this._ajv.getSchema(b.$id)??this._ajv.compile(b):this._ajv.compile(b);return($)=>{if(w($))return{valid:!0,data:$,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(w.errors)}}}}class GQ{constructor(b){this._server=b}requestStream(b,w,$){return this._server.requestStream(b,w,$)}async getTask(b,w){return this._server.getTask({taskId:b},w)}async getTaskResult(b,w,$){return this._server.getTaskResult({taskId:b},w,$)}async listTasks(b,w){return this._server.listTasks(b?{cursor:b}:void 0,w)}async cancelTask(b,w){return this._server.cancelTask({taskId:b},w)}}function GH(b,w,$){if(!b)throw Error(`${$} does not support task creation (required for ${w})`);switch(w){case"tools/call":if(!b.tools?.call)throw Error(`${$} does not support task creation for tools/call (required for ${w})`);break;default:break}}function XH(b,w,$){if(!b)throw Error(`${$} does not support task creation (required for ${w})`);switch(w){case"sampling/createMessage":if(!b.sampling?.createMessage)throw Error(`${$} does not support task creation for sampling/createMessage (required for ${w})`);break;case"elicitation/create":if(!b.elicitation?.create)throw Error(`${$} does not support task creation for elicitation/create (required for ${w})`);break;default:break}}class XQ extends b4{constructor(b,w){super(w);if(this._serverInfo=b,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(x1.options.map(($,Q)=>[$,Q])),this.isMessageIgnored=($,Q)=>{let W=this._loggingLevels.get(Q);return W?this.LOG_LEVEL_SEVERITY.get($)<this.LOG_LEVEL_SEVERITY.get(W):!1},this._capabilities=w?.capabilities??{},this._instructions=w?.instructions,this._jsonSchemaValidator=w?.jsonSchemaValidator??new WQ,this.setRequestHandler(y6,($)=>this._oninitialize($)),this.setNotificationHandler(h6,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(d6,async($,Q)=>{let W=Q.sessionId||Q.requestInfo?.headers["mcp-session-id"]||void 0,{level:G}=$.params,X=x1.safeParse(G);if(X.success)this._loggingLevels.set(W,X.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new GQ(this)};return this._experimental}registerCapabilities(b){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=NG(this._capabilities,b)}setRequestHandler(b,w){let Q=S0(b)?.method;if(!Q)throw Error("Schema is missing a method literal");let W;if(mw(Q)){let X=Q;W=X._zod?.def?.value??X.value}else{let X=Q;W=X._def?.value??X.value}if(typeof W!=="string")throw Error("Schema method literal must be a string");if(W==="tools/call"){let X=async(Y,J)=>{let z=Bw(k1,Y);if(!z.success){let q=z.error instanceof Error?z.error.message:String(z.error);throw new x(g.InvalidParams,`Invalid tools/call request: ${q}`)}let{params:H}=z.data,A=await Promise.resolve(w(Y,J));if(H.task){let q=Bw(nw,A);if(!q.success){let B=q.error instanceof Error?q.error.message:String(q.error);throw new x(g.InvalidParams,`Invalid task creation result: ${B}`)}return q.data}let O=Bw(p0,A);if(!O.success){let q=O.error instanceof Error?O.error.message:String(O.error);throw new x(g.InvalidParams,`Invalid tools/call result: ${q}`)}return O.data};return super.setRequestHandler(b,X)}return super.setRequestHandler(b,w)}assertCapabilityForMethod(b){switch(b){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${b})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${b})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${b})`);break;case"ping":break}}assertNotificationCapability(b){switch(b){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${b})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${b})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${b})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${b})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${b})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(b){if(!this._capabilities)return;switch(b){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${b})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${b})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${b})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${b})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${b})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${b})`);break;case"ping":case"initialize":break}}assertTaskCapability(b){XH(this._clientCapabilities?.tasks?.requests,b,"Client")}assertTaskHandlerCapability(b){if(!this._capabilities)return;GH(this._capabilities.tasks?.requests,b,"Server")}async _oninitialize(b){let w=b.params.protocolVersion;return this._clientCapabilities=b.params.capabilities,this._clientVersion=b.params.clientInfo,{protocolVersion:JG.includes(w)?w:C6,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},u0)}async createMessage(b,w){if(b.tools||b.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if(b.messages.length>0){let $=b.messages[b.messages.length-1],Q=Array.isArray($.content)?$.content:[$.content],W=Q.some((J)=>J.type==="tool_result"),G=b.messages.length>1?b.messages[b.messages.length-2]:void 0,X=G?Array.isArray(G.content)?G.content:[G.content]:[],Y=X.some((J)=>J.type==="tool_use");if(W){if(Q.some((J)=>J.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!Y)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(Y){let J=new Set(X.filter((H)=>H.type==="tool_use").map((H)=>H.id)),z=new Set(Q.filter((H)=>H.type==="tool_result").map((H)=>H.toolUseId));if(J.size!==z.size||![...J].every((H)=>z.has(H)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if(b.tools)return this.request({method:"sampling/createMessage",params:b},t6,w);return this.request({method:"sampling/createMessage",params:b},r6,w)}async elicitInput(b,w){switch(b.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let Q=b;return this.request({method:"elicitation/create",params:Q},o0,w)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let Q=b.mode==="form"?b:{...b,mode:"form"},W=await this.request({method:"elicitation/create",params:Q},o0,w);if(W.action==="accept"&&W.content&&Q.requestedSchema)try{let X=this._jsonSchemaValidator.getValidator(Q.requestedSchema)(W.content);if(!X.valid)throw new x(g.InvalidParams,`Elicitation response content does not match requested schema: ${X.errorMessage}`)}catch(G){if(G instanceof x)throw G;throw new x(g.InternalError,`Error validating elicitation response: ${G instanceof Error?G.message:String(G)}`)}return W}}}createElicitationCompletionNotifier(b,w){if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:b}},w)}async listRoots(b,w){return this.request({method:"roots/list",params:b},e6,w)}async sendLoggingMessage(b,w){if(this._capabilities.logging){if(!this.isMessageIgnored(b.level,w))return this.notification({method:"notifications/message",params:b})}}async sendResourceUpdated(b){return this.notification({method:"notifications/resources/updated",params:b})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}var YH={name:"@sequenzy/mcp",version:"0.0.106",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 YQ=["product-info","domain","tracking","localization","integrations","products","events","tags","labels","goals","sync-rules","api-keys","widgets","team","danger"],JH={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 OM(b){let $=(b??process.env.SEQUENZY_APP_URL??"https://sequenzy.com").trim().replace(/\/+$/,"");return $.length>0?$:"https://sequenzy.com"}function lb(b){let w=b?.trim();return w?w:void 0}function rb(b){return encodeURIComponent(b)}function Xb(b,w){return`${b}${w}`}function Yb(b,w=""){return`/dashboard/company/${rb(b)}${w}`}function zH(b,w,$){return Xb(b,`${Yb(w,"/settings")}?tab=${encodeURIComponent($)}`)}function qM(b,w){let $=YQ.map((Q)=>[Q,w?zH(b,w,Q):""]);return Object.fromEntries($)}function Yw(b={},w){let $=OM(w),Q=lb(b.companyId),W={},G=qM($,Q);if(!Q)return{appUrl:$,routeTemplates:JH,settingsTabValues:YQ,urls:W,settingsUrls:G};W.dashboard=Xb($,Yb(Q)),W.campaigns=Xb($,Yb(Q,"/campaign")),W.landingPages=Xb($,Yb(Q,"/landing-pages")),W.sequences=Xb($,Yb(Q,"/sequences")),W.settings=Xb($,Yb(Q,"/settings")),W.emails=Xb($,Yb(Q,"/emails")),W.subscribers=Xb($,Yb(Q,"/subscribers")),W.sentEmails=Xb($,Yb(Q,"/sent-emails")),W.segments=Xb($,Yb(Q,"/segments")),W.metrics=Xb($,Yb(Q,"/metrics")),W.transactional=Xb($,Yb(Q,"/transactional"));let X=lb(b.campaignId);if(X)W.campaign=Xb($,Yb(Q,`/campaign/${rb(X)}`)),W.campaignPreview=`${W.campaign}?step=review`;let Y=lb(b.landingPageId);if(Y)W.landingPage=Xb($,Yb(Q,`/landing-pages/${rb(Y)}`));let J=lb(b.sequenceId);if(J)W.sequence=Xb($,Yb(Q,`/sequences/${rb(J)}`));let z=lb(b.emailId)??lb(b.templateId);if(z)W.email=Xb($,Yb(Q,`/emails/${rb(z)}`)),W.template=W.email;let H=lb(b.transactionalId);if(H)W.transactionalEmail=Xb($,Yb(Q,`/transactional/${rb(H)}`));let A=lb(b.emailSendId);if(A)W.emailSend=Xb($,Yb(Q,`/sent-emails/${rb(A)}`));let O=lb(b.domainId);if(O)W.domain=Xb($,Yb(Q,`/settings/domain/${rb(O)}`)),W.domainVerify=`${W.domain}/verify`;let q=lb(b.status);if(q)W.campaignList=Xb($,Yb(Q,`/campaign/list/${rb(q)}`)),W.sequenceList=Xb($,Yb(Q,`/sequences/list/${rb(q)}`));let B=lb(b.settingsTab);if(B)W.settingsTab=zH($,Q,B);return{appUrl:$,routeTemplates:JH,settingsTabValues:YQ,urls:W,settingsUrls:G}}var HH=[{uri:"sequenzy://dashboard",name:"Dashboard Overview",description:"Live overview stats for the last 7 days",mimeType:"application/json"},{uri:"sequenzy://company",name:"Current Company",description:"The currently selected company, including localization settings",mimeType:"application/json"},{uri:"sequenzy://campaigns/recent",name:"Recent Campaigns",description:"Last 10 campaigns with status and basic stats",mimeType:"application/json"},{uri:"sequenzy://subscribers/recent",name:"Recent Subscribers",description:"Most recently added subscribers",mimeType:"application/json"},{uri:"sequenzy://subscribers/engaged",name:"Engaged Subscribers",description:"Most active/engaged subscribers",mimeType:"application/json"},{uri:"sequenzy://sequences",name:"Sequences",description:"All email sequences with status",mimeType:"application/json"},{uri:"sequenzy://templates",name:"Templates",description:"All available email templates with localization status",mimeType:"application/json"},{uri:"sequenzy://segments",name:"Segments",description:"All defined segments with subscriber counts",mimeType:"application/json"},{uri:"sequenzy://tags",name:"Tags",description:"All tags with usage counts",mimeType:"application/json"},{uri:"sequenzy://health",name:"Deliverability Health",description:"Email deliverability metrics and health status",mimeType:"application/json"},{uri:"sequenzy://app-routes",name:"Dashboard URL Routes",description:"Route templates and settings tabs for building Sequenzy dashboard links",mimeType:"application/json"}];async function AH(b){try{let w;switch(b){case"sequenzy://dashboard":w=await D("GET","/api/v1/metrics?period=7d");break;case"sequenzy://company":{let $=await D("GET","/api/v1/account"),Q=Dw()??$.currentCompanyId;if(!Q)throw Error("No company available. Create or select a company first.");w=await D("GET",`/api/v1/companies/${Q}`);break}case"sequenzy://campaigns/recent":w=await D("GET","/api/v1/campaigns?limit=10");break;case"sequenzy://subscribers/recent":w=await D("GET","/api/v1/subscribers?sort=createdAt&limit=20");break;case"sequenzy://subscribers/engaged":w=await D("GET","/api/v1/subscribers?sort=engagement&limit=20");break;case"sequenzy://sequences":w=await D("GET","/api/v1/sequences");break;case"sequenzy://templates":w=await D("GET","/api/v1/templates");break;case"sequenzy://segments":w=await D("GET","/api/v1/segments");break;case"sequenzy://tags":w=await D("GET","/api/v1/tags");break;case"sequenzy://health":w=await D("GET","/api/v1/health/deliverability");break;case"sequenzy://app-routes":w=Yw();break;default:throw Error(`Unknown resource: ${b}`)}return{contents:[{uri:b,mimeType:"application/json",text:JSON.stringify(w,null,2)}]}}catch(w){return{contents:[{uri:b,mimeType:"text/plain",text:Aw(w)}]}}}function y(b){return typeof b==="object"&&b!==null&&!Array.isArray(b)}function M(b,w){let $=b[w];if(typeof $!=="string")return;let Q=$.trim();return Q.length>0?Q:void 0}function j(b,w,$){let Q=M(w,$);if(Q===void 0)throw Error(`\`${$}\` is required when calling \`${b}\`.`);return Q}var Ew='For exact historical Poll/NPS respondents, use field `pollResponse`, operator `is`, and a JSON value shaped like {"v":1,"campaignId":"camp_123","blockId":"poll_1","match":{"kind":"answer","value":"loved"}}. For NPS buckets, use match {"kind":"npsBucket","bucket":"promoters"}; bucket may be `promoters`, `passives`, or `detractors`.',Tw='Sequenzy email blocks. Use this for editor-compatible content, including conditional and repeat blocks. For provider-migrated HTML from another email platform, prefer the `html` field instead; Sequenzy stores it as one raw HTML block to preserve the original design. Use `styles` for per-block background, background opacity, text color, padding, border radius, border width, and border color. Top-level style aliases such as `backgroundColor`, `backgroundOpacity`, `borderColor`, `borderWidth`, and `borderRadius` are also accepted and saved under `styles`. Repeat blocks use { type: \'repeat\', source: \'items\', itemAlias: \'item\', children: [...] }. Any block accepts a `conditions` array so it only renders for matching recipients. To branch on a value passed in the transactional send `variables` or an automation `event` payload, use { "id": "c1", "field": "variable", "operator": "is", "value": "plan:pro" } where the text before the colon is a {{merge tag}} path (nested paths like "order.total" or "event.plan" work) and the text after it is the comparison value. `field` may also be "attribute" (same "name:value" form) or "email"/"firstName"/"lastName" (the value is the plain comparison string). Operators: is, is_not, contains, not_contains, gt, gte, lt, lte, is_empty, is_not_empty. For if/else, use a { type: "conditional-group", conditions: [...], ifBranch: { children: [...] }, elseBranch: { children: [...] } } block. Polls and NPS surveys use a native poll block. For answer buttons use { "type": "poll", "variant": "options", "question": "What did you think?", "options": [{ "label": "Loved it", "value": "loved" }, { "label": "Not for me", "value": "not_for_me" }], "attributeKey": "email_feedback" }. For NPS use { "type": "poll", "variant": "nps", "question": "How likely are you to recommend us?", "options": [], "attributeKey": "nps_score", "npsLowLabel": "Not likely", "npsHighLabel": "Very likely" }. `attributeKey` stores the latest response for segmentation. Optional `appearance` picks the answer style: "soft" (default), "pill", "outline", "filled", "pop" (hard-shadow boxes), "brutal" (square uppercase slabs), "quiz" (A/B/C letter badges), or "minimal" (bare ruled rows). Optional `confirmationMessage` customizes the hosted thank-you page; set `redirectUrl` only when respondents should land on another page.',Jw='Replacement Sequenzy email blocks. Use `styles` for per-block background, background opacity, text color, padding, border radius, border width, and border color. Top-level style aliases such as `backgroundColor`, `backgroundOpacity`, `borderColor`, `borderWidth`, and `borderRadius` are also accepted and saved under `styles`. Any block accepts a `conditions` array so it only renders for matching recipients. To branch on a value passed in the transactional send `variables` or an automation `event` payload, use { "id": "c1", "field": "variable", "operator": "is", "value": "plan:pro" } where the text before the colon is a {{merge tag}} path (nested paths like "order.total" or "event.plan" work) and the text after it is the comparison value. `field` may also be "attribute" (same "name:value" form) or "email"/"firstName"/"lastName" (the value is the plain comparison string). Operators: is, is_not, contains, not_contains, gt, gte, lt, lte, is_empty, is_not_empty. For if/else, use a { type: "conditional-group", conditions: [...], ifBranch: { children: [...] }, elseBranch: { children: [...] } } block. Polls and NPS surveys use a native poll block. For answer buttons use { "type": "poll", "variant": "options", "question": "What did you think?", "options": [{ "label": "Loved it", "value": "loved" }, { "label": "Not for me", "value": "not_for_me" }], "attributeKey": "email_feedback" }. For NPS use { "type": "poll", "variant": "nps", "question": "How likely are you to recommend us?", "options": [], "attributeKey": "nps_score", "npsLowLabel": "Not likely", "npsHighLabel": "Very likely" }. `attributeKey` stores the latest response for segmentation. Optional `appearance` picks the answer style: "soft" (default), "pill", "outline", "filled", "pop" (hard-shadow boxes), "brutal" (square uppercase slabs), "quiz" (A/B/C letter badges), or "minimal" (bare ruled rows). Optional `confirmationMessage` customizes the hosted thank-you page; set `redirectUrl` only when respondents should land on another page.',Q1='Sequenzy email blocks. Provide blocks or html for email steps. For migrated provider HTML, prefer `html`; Sequenzy stores it as one raw HTML block and does not recreate it as native blocks. Use `styles` for per-block background, background opacity, text color, padding, border radius, border width, and border color. Top-level style aliases such as `backgroundColor`, `backgroundOpacity`, `borderColor`, `borderWidth`, and `borderRadius` are also accepted and saved under `styles`. Blocks can include repeat blocks over array variables such as items. Any block accepts a `conditions` array so it only renders for matching recipients. To branch on a value passed in the transactional send `variables` or an automation `event` payload, use { "id": "c1", "field": "variable", "operator": "is", "value": "plan:pro" } where the text before the colon is a {{merge tag}} path (nested paths like "order.total" or "event.plan" work) and the text after it is the comparison value. `field` may also be "attribute" (same "name:value" form) or "email"/"firstName"/"lastName" (the value is the plain comparison string). Operators: is, is_not, contains, not_contains, gt, gte, lt, lte, is_empty, is_not_empty. For if/else, use a { type: "conditional-group", conditions: [...], ifBranch: { children: [...] }, elseBranch: { children: [...] } } block. Polls and NPS surveys use a native poll block. For answer buttons use { "type": "poll", "variant": "options", "question": "What did you think?", "options": [{ "label": "Loved it", "value": "loved" }, { "label": "Not for me", "value": "not_for_me" }], "attributeKey": "email_feedback" }. For NPS use { "type": "poll", "variant": "nps", "question": "How likely are you to recommend us?", "options": [], "attributeKey": "nps_score", "npsLowLabel": "Not likely", "npsHighLabel": "Very likely" }. `attributeKey` stores the latest response for segmentation. Optional `appearance` picks the answer style: "soft" (default), "pill", "outline", "filled", "pop" (hard-shadow boxes), "brutal" (square uppercase slabs), "quiz" (A/B/C letter badges), or "minimal" (bare ruled rows). Optional `confirmationMessage` customizes the hosted thank-you page; set `redirectUrl` only when respondents should land on another page.',X0="Complete Sequenzy landing page content JSON. Use this when replacing the page structure. The content must be the editor-compatible landing page schema with version, template, seo, theme, and blocks. Landing pages must include exactly one footer block and at most one form block.",DH="Optional template key for default content, such as from-scratch, waitlist, lead-magnet, launch, demo-request, webinar, newsletter, product-hunt, pricing-offer, agency-lead-gen, or feature-announcement.",JQ=500,zQ=500,nb={type:"boolean",description:"If true, include machine-classified bot/scanner opens and clicks. Defaults to false, so metrics and activity are human-only."},C$=["send","delivery","bounce","complaint","open","click","unsubscribe","delivery_delay"],v$={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},UM={type:"object",description:"Offset relative to a wait-until date.",properties:{days:{type:"number"},hours:{type:"number"},minutes:{type:"number"}},additionalProperties:!1},W1={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:UM,days:{type:"number",description:"Offset days shorthand. Ignored when offset is provided."},hours:{type:"number",description:"Offset hours shorthand. Ignored when offset is provided."},minutes:{type:"number",description:"Offset minutes shorthand. Ignored when offset is provided."},direction:{type:"string",enum:["before","after"],description:"Whether the offset applies before or after the resolved date. Defaults to after."},untilOffsetDirection:{type:"string",enum:["before","after"],description:"Alias for direction."},missingAction:{type:"string",enum:["continue","exit"],description:"What to do if the event field is missing or invalid. Defaults to continue."},untilMissingAction:{type:"string",enum:["continue","exit"],description:"Alias for missingAction."}},additionalProperties:!1},G1={type:"object",description:"Fixed delay before this step. For a dynamic wait-until-date delay, either set mode:'until_date' plus untilDateField here, or use waitUntil.",properties:{days:{type:"number"},hours:{type:"number"},minutes:{type:"number"},mode:{type:"string",enum:["duration","until_date"],description:"Use duration for a fixed wait, or until_date to resolve a date from the trigger event."},untilDateField:{type:"string",description:"For mode:'until_date', dot-path into the trigger event properties."},field:{type:"string",description:"Alias for untilDateField."},untilOffsetDirection:{type:"string",enum:["before","after"],description:"For mode:'until_date', whether days/hours/minutes are before or after the event date. Defaults to after."},direction:{type:"string",enum:["before","after"],description:"Alias for untilOffsetDirection."},untilMissingAction:{type:"string",enum:["continue","exit"],description:"For mode:'until_date', what to do when the field is missing or invalid. Defaults to continue."},missingAction:{type:"string",enum:["continue","exit"],description:"Alias for untilMissingAction."}},additionalProperties:!1},HQ={type:"object",description:"Type-aware patch for the existing node. Start from get_sequence.sequence.nodes[].config. For logic_delay, set exactly one of delay ({ days, hours, minutes }), delayMs, or waitUntil; optional label is also accepted. For action_email, use name/label, subject, previewText, html/htmlContent or blocks, isTransactional, and sender/reply identity fields. For action_sms, use text, blocks, imageUrls, label, or ineligibleAction. Other node types accept their editable config keys. Managed IDs, nodeType conversion, and branch path IDs/count are not editable here; use edit_sequence_graph for topology. Webhook header patches are merged, and redacted values from get_sequence must be omitted or replaced with a real new value.",additionalProperties:!0},k$={type:"object",properties:{nodeId:{type:"string",description:"Existing node ID from get_sequence.sequence.nodes[].id."},changes:HQ,expectedUpdatedAt:{type:"string",description:"Required optimistic-concurrency value from get_sequence.sequence.nodes[].updatedAt. The update is rejected if that node or its linked email content changed after it was read."}},required:["nodeId","changes","expectedUpdatedAt"],additionalProperties:!1},X1=["gray","red","orange","amber","yellow","lime","green","emerald","teal","cyan","sky","blue","indigo","violet","purple","fuchsia","pink","rose"],Y1=["email.sent","email.delivered","email.delivery_delayed","email.bounced","email.complained","email.opened","email.clicked","email.replied","email.unsubscribed","sms.sent","sms.delivered","sms.failed","sms.opted_out","subscriber.invalid","subscriber.updated","subscriber.unsubscribed","sequence.finished","sequence.failed","poll.answered"];var LM=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"]),BM=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","update_sequence_node","update_sequence_nodes","edit_sequence_graph","insert_sequence_step","enable_sequence","disable_sequence","pause_sequence_enrollments","resume_sequence_enrollments","enroll_subscribers_in_sequence","cancel_sequence_enrollments","delete_sequence","create_transactional_email","update_transactional_email","send_email","invite_team_member","cancel_team_invitation","reply_to_conversation","update_conversation_status","mark_conversation_read","create_webhook","update_webhook","delete_webhook","test_webhook","replay_webhook_delivery","submit_feedback"]),KM=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"]),FM=new Set(["remove_subscriber","delete_subscriber_note","delete_product","remove_product_file","delete_tag","delete_list","remove_subscribers_from_list","delete_segment","delete_audience_sync","delete_template","restart_ab_test","delete_ab_test_variant","delete_ab_test","cancel_campaign","delete_campaign","delete_landing_page","unpublish_landing_page","disable_sequence","edit_sequence_graph","cancel_sequence_enrollments","delete_sequence","cancel_team_invitation","delete_webhook"]);function MM(b){let w=LM.has(b),$=BM.has(b);if(w===$)throw Error(`MCP tool "${b}" must be classified as exactly one of read-only or mutating.`);return{readOnlyHint:w,destructiveHint:w?!1:FM.has(b),openWorldHint:KM.has(b)}}function OH(b){return{...b,annotations:{...b.annotations,...MM(b.name)}}}var AQ={status:["is","is_not"],phone:["is_not_empty","is_empty"],smsStatus:["is","is_not"],tag:["contains","not_contains","is_empty","is_not_empty"],email:["contains","not_contains"],emailProvider:["is","is_not","is_empty","is_not_empty"],added:["less_than","more_than"],firstName:["contains","not_contains","is_empty","is_not_empty"],lastName:["contains","not_contains","is_empty","is_not_empty"],list:["is","is_not","is_empty","is_not_empty"],emailSent:["is","is_not","at_least","less_than_count"],emailDelivered:["is","is_not","at_least","less_than_count"],emailOpened:["is","is_not","at_least","less_than_count"],emailClicked:["is","is_not","at_least","less_than_count"],emailBounced:["is","is_temporary_bounce","is_permanent_bounce","is_not","at_least","less_than_count"],emailComplained:["is","is_not","at_least","less_than_count"],attribute:["is","is_not","is_empty","is_not_empty","gte","lte","gt","lt","contains","not_contains"],event:["is","is_not","at_least","less_than_count"],pollResponse:["is"],segment:["is","is_not"],stripeProduct:["is","is_not","at_least","less_than_count"],stripeCurrentProduct:["is","is_not","gte","lte","gt","lt"],stripeTrialProduct:["is","is_not","gte","lte","gt","lt"],commerceProduct:["is","is_not","at_least","less_than_count"]},PM=Object.entries(AQ).map(([b,w])=>`${b}: ${w.join(", ")}`).join("; "),DQ={type:"object",properties:{id:{type:"string",description:"Optional filter ID. Any stable string works; one will be generated if omitted."},field:{type:"string",enum:["status","phone","smsStatus","tag","email","emailProvider","added","firstName","lastName","list","emailSent","emailDelivered","emailOpened","emailClicked","emailBounced","emailComplained","attribute","event","pollResponse","segment","stripeProduct","stripeCurrentProduct","stripeTrialProduct","commerceProduct"],description:`Filter field. Use \`phone\` with is_not_empty/is_empty to check whether a subscriber has a phone number, and \`smsStatus\` (is/is_not one of \`subscribed\`, \`unsubscribed\`, \`not_subscribed\`) for SMS marketing consent. Use \`event\` for custom subscriber events, \`segment\` for saved segment membership, \`stripeProduct\`/\`stripeCurrentProduct\`/\`stripeTrialProduct\` for Stripe product-based segments, and \`commerceProduct\` for products purchased through commerce orders - the value is \`provider:productId\` (provider one of \`shopify\`, \`woocommerce\`, \`api\`; product ids are provider-scoped), optionally with an order-count threshold (\`provider:productId:count\`) for at_least/less_than_count; a bare product id matches the id on any provider. Engagement fields (\`emailSent\`, \`emailDelivered\`, \`emailOpened\`, \`emailClicked\`, \`emailBounced\`, \`emailComplained\`) accept a time range as the value, a specific campaign via \`campaign:<campaign_id>\`, or \`count:timeRange\` (e.g. \`10:30d\`, \`10:all\`) with at_least/less_than_count to segment by number of opens/clicks. ${Ew}`},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: ${PM}.`},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). ${Ew}`}},required:["field","operator","value"],additionalProperties:!1},OQ={type:"object",properties:{kind:{type:"string",enum:["group"]},id:{type:"string",description:"Stable group ID. Any string works; one will be generated if omitted."},joinOperator:{type:"string",enum:["and","or"],description:"How children in this group combine."},children:{type:"array",minItems:1,items:{type:"object",description:'Either a filter leaf (`kind: "filter"`) or another group (`kind: "group"`).'}}},required:["kind","joinOperator","children"],additionalProperties:!0};function x$(b){if(!Array.isArray(b))return b;return b.map((w)=>{if(typeof w!=="object"||w===null)return w;let $=w;if(typeof $.id==="string"&&$.id.trim()!=="")return $;return{...$,id:crypto.randomUUID()}})}function u$(b){if(typeof b!=="object"||b===null)return b;let w=b;if(w.kind==="filter"||"field"in w||"operator"in w||"value"in w){let $=x$([w]);return Array.isArray($)?$[0]:w}if(w.kind!=="group")return b;return{...w,id:typeof w.id==="string"&&w.id.trim()!==""?w.id:crypto.randomUUID(),children:Array.isArray(w.children)?w.children.map(u$):[]}}function ZM(b){let w=b.indexOf(":");return w!==-1&&b.substring(0,w).trim().length>0}function IM(b){let w=b.indexOf(":");return w!==-1&&b.substring(w+1).trim().length>0}function qH(b){if(b==="all")return!0;let w=b.match(/^(\d+)d$/);if(!w?.[1])return!1;let $=Number.parseInt(w[1],10);return Number.isInteger($)&&$>0}function VM(b,w){let $=w.split(":");if(b==="at_least"||b==="less_than_count"){if($.length<3)return'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".';let G=$.slice(0,-2).join(":").trim(),X=$.at(-2),Y=$.at(-1),J=X===void 0?Number.NaN:Number.parseInt(X,10);return G&&Number.isInteger(J)&&J>0&&Y!==void 0&&qH(Y)?null:'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".'}if($.length<2)return'Event filters must use "eventName:timeRange", like "saas.purchase:30d".';let Q=$.slice(0,-1).join(":").trim(),W=$.at(-1);return Q&&W!==void 0&&qH(W)?null:'Event filters must use "eventName:timeRange", like "saas.purchase:30d".'}function jM(b){let w=b.indexOf(":");if(w===-1)return{productId:b,subfilter:null,rawValue:null};let $=b.substring(0,w),Q=b.substring(w+1),W=Q.indexOf(":");if(W===-1)return{productId:$,subfilter:Q,rawValue:null};return{productId:$,subfilter:Q.substring(0,W),rawValue:Q.substring(W+1)}}function NM(b){return b.trim().toLowerCase().replace(/[-\s]+/g,"_")}function EM(b){return["is_canceled","is_cancelled","canceled","cancelled","will_cancel","cancel_at_period_end","is_not_canceled","is_not_cancelled","not_canceled","not_cancelled","will_not_cancel"].includes(b)}function TM(b,w){if(w==="cancels_at"||w==="cancel_at"||w==="cancellation_at")return!0;if(b==="stripeCurrentProduct")return["end_at","ends_at","period_end","period_ends_at","current_period_end"].includes(w);return["start_at","started_at","trial_start","trial_started_at","end_at","ends_at","trial_end","trial_ends_at"].includes(w)}function _M(b){return["is","is_not","gte","lte","gt","lt"].includes(b)}function SM(b,w,$){if(b==="stripeProduct"){if(w!=="at_least"&&w!=="less_than_count")return null;let Y=$.indexOf(":");if(Y===-1)return null;let J=$.substring(0,Y).trim(),z=Number.parseInt($.substring(Y+1).trim(),10);return J&&Number.isInteger(z)&&z>=1?null:'Stripe Product threshold filters must use "productId:count" with a count of at least 1.'}if(b!=="stripeCurrentProduct"&&b!=="stripeTrialProduct")return null;let{productId:Q,subfilter:W,rawValue:G}=jM($);if(!Q.trim())return"Stripe product filters must include a product ID.";if(!W)return w==="is"||w==="is_not"?null:'Stripe current/trial date filters must use "productId:dateField:value".';let X=NM(W);if(EM(X))return w==="is"||w==="is_not"?null:"Stripe cancellation flag filters only support is and is_not operators.";if(!TM(b,X))return`Unsupported Stripe product subfilter "${W}".`;if(!_M(w))return"Stripe date filters only support is, is_not, gte, lte, gt, and lt operators.";return G?.trim()?null:'Stripe date filters must include a value like "productId:end_at:2026-05-26".'}var RM=new Set(["shopify","woocommerce","api"]);function CM(b,w){let $=w.trim(),Q=$.indexOf(":");if(Q!==-1&&RM.has($.substring(0,Q).trim()))$=$.substring(Q+1).trim();if(!$)return'Purchased Product filters must include a product ID, like "shopify:42".';if(b!=="at_least"&&b!=="less_than_count")return null;let W=$.lastIndexOf(":");if(W===-1)return null;let G=$.substring(0,W).trim(),X=Number.parseInt($.substring(W+1).trim(),10);return G&&Number.isInteger(X)&&X>=1?null:'Purchased Product threshold filters must use "provider:productId:count" with a count of at least 1.'}function vM(b){let w;try{w=JSON.parse(b)}catch{return`Poll response filters must use valid JSON. ${Ew}`}if(!y(w)||w.v!==1||typeof w.campaignId!=="string"||!w.campaignId.trim()||typeof w.blockId!=="string"||!w.blockId.trim()||!y(w.match))return`Poll response filter context is invalid. ${Ew}`;let $=w.match;if($.kind==="answer"&&typeof $.value==="string"&&$.value.length>0)return null;if($.kind==="npsBucket"&&($.bucket==="promoters"||$.bucket==="passives"||$.bucket==="detractors"))return null;return`Poll response filter match is invalid. ${Ew}`}function y$(b){if(typeof b!=="object"||b===null)return"Segment filters must be objects.";let w=b,$=w.field,Q=w.operator,W=w.value;if(typeof $!=="string"||!($ in AQ))return`Unsupported segment filter field "${String($)}".`;if(typeof Q!=="string")return`Segment filter "${$}" must include an operator.`;let G=AQ[$];if(!G.includes(Q))return`Operator "${Q}" is not supported for ${$} filters. Use one of: ${G.join(", ")}.`;if(Q!=="is_empty"&&Q!=="is_not_empty"&&(typeof W!=="string"||W.trim().length===0))return`Segment filter "${$}" must include a value.`;if($==="attribute"&&typeof W==="string"){if(!ZM(W))return'Attribute filters must use "attributeName:value" or "attributeName:" for empty checks.';if(Q!=="is_empty"&&Q!=="is_not_empty"&&!IM(W))return'Attribute filters must include a value after "attributeName:".'}if($==="event"&&typeof W==="string"){let X=VM(Q,W);if(X)return X}if($==="pollResponse"&&typeof W==="string"){let X=vM(W);if(X)return X}if(($==="stripeProduct"||$==="stripeCurrentProduct"||$==="stripeTrialProduct")&&typeof W==="string"){let X=SM($,Q,W);if(X)return X}if($==="commerceProduct"&&typeof W==="string"){let X=CM(Q,W);if(X)return X}if($==="tag"&&(Q==="contains"||Q==="not_contains")){if(!(typeof W==="string"&&W.split(",").map((Y)=>Y.trim()).some(Boolean)))return"Tag filters must include at least one tag name."}return null}function h$(b){if(typeof b!=="object"||b===null)return[];let w=b;if(w.kind==="filter"||"field"in w||"operator"in w||"value"in w){let $=y$(w);return $?[$]:[]}if(Array.isArray(w.children))return w.children.flatMap(h$);return[]}function kb(b,w,$){if(w.html!==void 0&&w.blocks!==void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${b}\`, not both.`);if(w.blocks!==void 0&&!Array.isArray(w.blocks))throw Error(`\`blocks\` must be an array when calling \`${b}\`.`);if($?.requireContent&&w.html===void 0&&w.blocks===void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${b}\`.`)}function J1(b,w){if(w.labels===void 0)return;if(!Array.isArray(w.labels))throw Error(`\`labels\` must be an array when calling \`${b}\`.`);if(w.labels.some(($)=>typeof $!=="string"||$.trim().length===0))throw Error(`\`labels\` must contain only non-empty strings when calling \`${b}\`.`)}function BH(b){let w=b.filters!==void 0,$=b.root!==void 0;if(w&&$)throw Error("Provide either `filters` or `root` when calling `create_segment`, not both.");if(!w&&!$)throw Error("Provide either `filters` or `root` when calling `create_segment`.");if(w){if(!Array.isArray(b.filters))throw Error("`filters` must be an array when calling `create_segment`.");if(b.filters.length===0)throw Error("`filters` must include at least one filter when calling `create_segment`.")}if($&&(typeof b.root!=="object"||b.root===null))throw Error("`root` must be an object when calling `create_segment`.");let Q=w?b.filters.flatMap((W)=>{let G=y$(W);return G?[G]:[]}):h$(b.root);if(Q.length>0)throw Error(Q[0]??"Invalid segment filter in `create_segment`.")}function KH(b){let w=b.filters!==void 0,$=b.root!==void 0;if(w&&$)throw Error("Provide either `filters` or `root` when calling `update_segment`, not both.");if(b.name===void 0&&b.filterJoinOperator===void 0&&!w&&!$)throw Error("Provide at least one of `name`, `filters`, `root`, or `filterJoinOperator` when calling `update_segment`.");if(w){if(!Array.isArray(b.filters))throw Error("`filters` must be an array when calling `update_segment`.");if(b.filters.length===0)throw Error("`filters` must include at least one filter when calling `update_segment`.")}if($&&(typeof b.root!=="object"||b.root===null))throw Error("`root` must be an object when calling `update_segment`.");let Q=w?b.filters.flatMap((W)=>{let G=y$(W);return G?[G]:[]}):$?h$(b.root):[];if(Q.length>0)throw Error(Q[0]??"Invalid segment filter in `update_segment`.")}var qQ=["name","description","logoUrl","founderName","primaryColor","brandColors","valueProps","testimonials","toneVoice","companyContext","emailLengthPreference","socialLinks","privacyPolicyUrl","termsUrl","address","language","pricing","fontFamily","emailDirection","fromEmail","fromName","replyTo","replyToName"];function UQ(b,w,$){if(w[$]!==void 0&&!y(w[$]))throw Error(`\`${$}\` must be an object when calling \`${b}\`.`)}function UH(b,w,$){if(w[$]!==void 0&&!Array.isArray(w[$]))throw Error(`\`${$}\` must be an array when calling \`${b}\`.`)}function FH(b){let w=new Set(["companyId",...qQ]),$=Object.keys(b).filter((W)=>!w.has(W));if($.length>0)throw Error(`\`update_company\` accepts only company product-info fields. Unsupported field${$.length===1?"":"s"}: ${$.map((W)=>`\`${W}\``).join(", ")}.`);let Q={};for(let W of qQ)if(b[W]!==void 0)Q[W]=b[W];if(Object.keys(Q).length===0)throw Error(`Provide at least one of ${qQ.map((W)=>`\`${W}\``).join(", ")} when calling \`update_company\`.`);for(let W of["name","description","logoUrl","founderName","primaryColor","toneVoice","companyContext","emailLengthPreference","privacyPolicyUrl","termsUrl","address","language","fontFamily","emailDirection","fromEmail","fromName","replyTo","replyToName"])if(b[W]!==void 0&&typeof b[W]!=="string")throw Error(`\`${W}\` must be a string when calling \`update_company\`.`);if(UQ("update_company",b,"brandColors"),UQ("update_company",b,"socialLinks"),UQ("update_company",b,"pricing"),UH("update_company",b,"valueProps"),UH("update_company",b,"testimonials"),typeof b.primaryColor==="string"&&!/^#[0-9a-f]{6}$/i.test(b.primaryColor.trim()))throw Error("`primaryColor` must be a 6-digit hex color such as #f97316 when calling `update_company`.");for(let W of["fromEmail","replyTo"]){let G=b[W];if(typeof G==="string"&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(G.trim()))throw Error(`\`${W}\` must be a valid email address when calling \`update_company\`.`)}if(b.fromName!==void 0&&b.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `update_company`.");if(b.replyToName!==void 0&&b.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `update_company`.");return Q}var MH=["senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName"];function kM(b){return MH.some((w)=>b[w]!==void 0)}function xM(b){if(typeof b.nodeType==="string")return b.nodeType==="action_email";return b.type===void 0||b.type==="email"}function f$(b,w,$){for(let Q of MH){let W=$[Q];if(W!==void 0&&typeof W!=="string")throw Error(`\`${Q}\` must be a string for ${w} when calling \`${b}\`.`)}if($.senderProfileId!==void 0&&$.fromEmail!==void 0)throw Error(`Provide either \`senderProfileId\` or \`fromEmail\` for ${w} when calling \`${b}\`, not both.`);if($.replyProfileId!==void 0&&$.replyTo!==void 0)throw Error(`Provide either \`replyProfileId\` or \`replyTo\` for ${w} when calling \`${b}\`, not both.`);if($.replyToName!==void 0&&$.replyTo===void 0)throw Error(`\`replyToName\` requires \`replyTo\` for ${w} when calling \`${b}\`.`)}function BQ(b,w,$){if(kM($)&&!xM($))throw Error(`Sender identity fields are only supported for email steps at ${w} when calling \`${b}\`.`);f$(b,w,$)}function LH(b,w,$){if(!Array.isArray($))return;$.forEach((Q,W)=>{if(y(Q))f$(b,`${w}[${W}]`,Q)})}function LQ(b,w,$){if(!Array.isArray($))return;$.forEach((Q,W)=>{if(y(Q))BQ(b,`${w}[${W}]`,Q)})}function uM(b){if(LH("update_sequence","emails",b.emails),LH("update_sequence","steps",b.steps),y(b.insertSteps))LQ("update_sequence","insertSteps.steps",b.insertSteps.steps);if(!y(b.branch))return;if(Array.isArray(b.branch.branches))b.branch.branches.forEach(($,Q)=>{if(y($))LQ("update_sequence",`branch.branches[${Q}].steps`,$.steps)});LQ("update_sequence","branch.elseSteps",b.branch.elseSteps)}function PH(b){if(b.fromEmail!==void 0&&b.senderProfileId!==void 0)throw Error("Provide either `fromEmail` or `senderProfileId` when calling `update_sequence`, not both.");if(b.replyTo!==void 0&&b.replyProfileId!==void 0)throw Error("Provide either `replyTo` or `replyProfileId` when calling `update_sequence`, not both.");if(b.fromName!==void 0&&b.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `update_sequence`.");if(b.replyToName!==void 0&&b.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `update_sequence`.");if(b.clearEnrollmentFieldPath===!0&&b.enrollmentFieldPath!==void 0)throw Error("Provide either `enrollmentFieldPath` or `clearEnrollmentFieldPath` when calling `update_sequence`, not both.");if(b.clearSendingWindow===!0&&b.sendingWindow!==void 0)throw Error("Provide either `sendingWindow` or `clearSendingWindow` when calling `update_sequence`, not both.");if(b.clearBccEmails===!0&&b.bccEmails!==void 0)throw Error("Provide either `bccEmails` or `clearBccEmails` when calling `update_sequence`, not both.");if(b.branch!==void 0&&b.insertSteps!==void 0)throw Error("Provide either `branch` or `insertSteps` when calling `update_sequence`, not both.");uM(b);let w={...b};if(delete w.clearEnrollmentFieldPath,delete w.clearSendingWindow,delete w.clearBccEmails,b.clearEnrollmentFieldPath===!0)w.enrollmentFieldPath=null;if(b.clearSendingWindow===!0)w.sendingWindow=null;if(b.clearBccEmails===!0)w.bccEmails=null;return w}function ZH(b,w,$){let Q=j(b,w,"nodeId");if(!y(w.changes)||Object.keys(w.changes).length===0)throw Error(`\`changes\` must be a non-empty object for ${$} when calling \`${b}\`.`);let W=j(b,w,"expectedUpdatedAt");return{nodeId:Q,changes:w.changes,expectedUpdatedAt:W}}function IH(b){let w=ZH("update_sequence_node",b,"the node update");return{...b.confirmLiveChange!==void 0&&{confirmLiveChange:b.confirmLiveChange},nodeUpdates:[w]}}function VH(b){if(!Array.isArray(b.updates)||b.updates.length===0)throw Error("`updates` must be a non-empty array when calling `update_sequence_nodes`.");let w=new Set,$=b.updates.map((Q,W)=>{if(!y(Q))throw Error(`\`updates[${W}]\` must be an object when calling \`update_sequence_nodes\`.`);let G=ZH("update_sequence_nodes",Q,`updates[${W}]`),X=String(G.nodeId);if(w.has(X))throw Error(`\`updates[${W}]\` targets duplicate nodeId '${X}' when calling \`update_sequence_nodes\`.`);return w.add(X),G});return{...b.confirmLiveChange!==void 0&&{confirmLiveChange:b.confirmLiveChange},nodeUpdates:$}}function jH(b){let w=j("edit_sequence_graph",b,"action"),$=j("edit_sequence_graph",b,"graphRevision");if(!new Set(["move_node","delete_node","duplicate_node","replace_edges"]).has(w))throw Error("`action` must be `move_node`, `delete_node`, `duplicate_node`, or `replace_edges` when calling `edit_sequence_graph`.");let W=M(b,"nodeId"),G=M(b,"afterNodeId"),X=M(b,"beforeNodeId"),Y=b.edges;if(w!=="replace_edges"&&!W)throw Error(`\`nodeId\` is required for ${w} when calling \`edit_sequence_graph\`.`);if(w==="replace_edges"&&W)throw Error("`nodeId` is not used with `replace_edges` when calling `edit_sequence_graph`.");let J=w==="move_node"||w==="duplicate_node";if(J&&(G?1:0)+(X?1:0)!==1)throw Error(`Provide exactly one of \`afterNodeId\` or \`beforeNodeId\` for ${w} when calling \`edit_sequence_graph\`.`);if(!J&&(G||X))throw Error(`\`afterNodeId\` and \`beforeNodeId\` are not used with ${w} when calling \`edit_sequence_graph\`.`);if((w==="replace_edges"||w==="delete_node"&&Y!==void 0)&&(!Array.isArray(Y)||Y.length===0))throw Error(`\`edges\` must contain the complete replacement topology for ${w} when calling \`edit_sequence_graph\`.`);if((w==="move_node"||w==="duplicate_node")&&Y!==void 0)throw Error(`\`edges\` is not used with ${w} when calling \`edit_sequence_graph\`.`);let z=Array.isArray(Y)?Y.map((H,A)=>{if(!y(H))throw Error(`\`edges\` item ${A+1} must be an object when calling \`edit_sequence_graph\`.`);let O=j("edit_sequence_graph",H,"sourceNodeId"),q=j("edit_sequence_graph",H,"targetNodeId");if(H.condition!==void 0&&H.condition!==null&&!y(H.condition))throw Error(`\`edges\` item ${A+1} \`condition\` must be an object when calling \`edit_sequence_graph\`.`);return{sourceNodeId:O,targetNodeId:q,...y(H.condition)?{condition:H.condition}:{}}}):void 0;return{...b.confirmStructuralChange!==void 0&&{confirmStructuralChange:b.confirmStructuralChange},graphEdit:{action:w,expectedRevision:$,...W?{nodeId:W}:{},...G?{afterNodeId:G}:{},...X?{beforeNodeId:X}:{},...z?{edges:z}:{}}}}function NH(b){let w=b.type==="sms",$;if(w){BQ("insert_sequence_step","SMS step",b);let W=M(b,"text"),G=Array.isArray(b.blocks)&&b.blocks.length>0;if(W===void 0&&!G)throw Error("Provide `text` (or `blocks`) when inserting an SMS step with `insert_sequence_step`.");$={type:"sms"};for(let X of["text","blocks","imageUrls","label","name","ineligibleAction","delay","delayMs","waitUntil"])if(b[X]!==void 0)$[X]=b[X]}else{kb("insert_sequence_step",b,{requireContent:!0}),f$("insert_sequence_step","email step",b),$={subject:j("insert_sequence_step",b,"subject")};for(let W of["name","previewText","html","blocks","delay","delayMs","waitUntil","senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName"])if(b[W]!==void 0)$[W]=b[W]}let Q={steps:[$]};if(b.afterNodeId!==void 0)Q.afterNodeId=b.afterNodeId;return{...b.confirmStructuralChange!==void 0&&{confirmStructuralChange:b.confirmStructuralChange},insertSteps:Q}}function EH(b){let w=M(b,"subscriberId"),$=b.fieldValues,Q=$===void 0?void 0:Array.isArray($)?$:void 0;if($!==void 0&&Q===void 0)throw Error("`fieldValues` must be an array when calling `cancel_sequence_enrollments`.");let W=Q?.map((Y)=>typeof Y==="string"?Y.trim():"").filter((Y)=>Y.length>0)??[];if(Q?.some((Y)=>typeof Y!=="string")||Q!==void 0&&W.length===0)throw Error("`fieldValues` must contain at least one non-empty string when calling `cancel_sequence_enrollments`.");if(w!==void 0===W.length>0)throw Error("Provide exactly one target when calling `cancel_sequence_enrollments`: `subscriberId` or `fieldValues`.");let G=M(b,"fieldPath"),X=M(b,"reason");return{...w!==void 0&&{subscriberId:w},...G!==void 0&&{fieldPath:G},...W.length>0&&{fieldValues:W},...typeof b.dryRun==="boolean"&&{dryRun:b.dryRun},...X!==void 0&&{reason:X}}}function TH(b){kb("create_campaign",b),J1("create_campaign",b);let w=M(b,"prompt")!==void 0,$=b.html!==void 0,Q=b.blocks!==void 0,W=b.templateId!==void 0;if(b.prompt!==void 0&&!w)throw Error("`prompt` cannot be empty when calling `create_campaign`.");if(w&&($||Q||W))throw Error("Provide either `prompt`, `html`, `blocks`, or `templateId` when calling `create_campaign`, not multiple content sources.");if(!w&&(b.style!==void 0||b.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_campaign`.");if(!w&&M(b,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_campaign`.")}function _H(b){kb("create_template",b),J1("create_template",b);let w=M(b,"prompt")!==void 0,$=[w,b.html!==void 0,b.blocks!==void 0].filter(Boolean).length;if(b.prompt!==void 0&&!w)throw Error("`prompt` cannot be empty when calling `create_template`.");if($!==1)throw Error("Provide exactly one of `prompt`, `html`, or `blocks` when calling `create_template`.");if(!w&&(b.style!==void 0||b.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_template`.");if(!w&&M(b,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_template`.")}function SH(b){if(M(b,"scheduledAt")===void 0)throw Error("`scheduledAt` is required when calling `schedule_campaign`.");if(b.targetLists!==void 0&&!y(b.targetLists))throw Error("`targetLists` must be an object when calling `schedule_campaign`.");if(b.sendTimeOptimization!==void 0){if(typeof b.sendTimeOptimization!=="boolean")throw Error("`sendTimeOptimization` must be a boolean when calling `schedule_campaign`.")}if(b.spreadOverHours!==void 0){if(typeof b.spreadOverHours!=="number"||!Number.isInteger(b.spreadOverHours)||b.spreadOverHours<1||b.spreadOverHours>72)throw Error("`spreadOverHours` must be an integer between 1 and 72 when calling `schedule_campaign`.")}if(b.recurringInterval!==void 0&&b.recurringInterval!=="weekly"&&b.recurringInterval!=="monthly")throw Error("`recurringInterval` must be 'weekly' or 'monthly' when calling `schedule_campaign`.")}function g$(b,w,$){let Q=new Set(["companyId","landingPageId","name","slug","content"]),W=Object.keys(w).filter((G)=>!Q.has(G));if(W.length>0)throw Error(`\`${b}\` accepts only \`name\`, \`slug\`, and \`content\` update fields. Unsupported field${W.length===1?"":"s"}: ${W.map((G)=>`\`${G}\``).join(", ")}.`);if($.requireUpdate&&w.name===void 0&&w.slug===void 0&&w.content===void 0)throw Error(`Provide at least one of \`name\`, \`slug\`, or \`content\` when calling \`${b}\`.`);return{...w.name!==void 0&&{name:w.name},...w.slug!==void 0&&{slug:w.slug},...w.content!==void 0&&{content:w.content}}}function RH(b){let w=new Set(["companyId","domain","verify"]),$=Object.keys(b).filter((Q)=>!w.has(Q));if($.length>0)throw Error(`\`update_landing_page_domain_settings\` accepts only \`domain\` and \`verify\`. Unsupported field${$.length===1?"":"s"}: ${$.map((Q)=>`\`${Q}\``).join(", ")}.`);if(b.domain===void 0&&b.verify!==!0)throw Error("Provide `domain` or `verify: true` when calling `update_landing_page_domain_settings`.");return{...b.domain!==void 0&&{domain:b.domain},...typeof b.verify==="boolean"&&{verify:b.verify}}}function CH(b){kb("create_transactional_email",b);let w=M(b,"prompt")!==void 0,$=b.html!==void 0,Q=b.blocks!==void 0;if(b.prompt!==void 0&&!w)throw Error("`prompt` cannot be empty when calling `create_transactional_email`.");if(w&&($||Q))throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`, not multiple content sources.");if(!w&&(b.style!==void 0||b.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_transactional_email`.");if(!w&&!$&&!Q)throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`.");if(!w&&M(b,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_transactional_email`.")}var Y0={type:"object",description:"Update Subscriber config. firstName, lastName, and customAttributeUpdates values may use trigger-event merge tags such as {{event.plan}}. Number and boolean values must be a literal or one standalone merge tag and are coerced after resolution.",properties:{label:{type:"string"},firstName:{type:["string","null"],description:"First name literal or merge tag; null clears the field."},lastName:{type:["string","null"],description:"Last name literal or merge tag; null clears the field."},status:{type:"string",enum:["active","unsubscribed","bounced"]},customAttributeUpdates:{type:"array",items:{type:"object",properties:{name:{type:"string"},value:{type:["string","number","boolean","null"],description:"Literal scalar, null to delete, or a standalone merge tag such as {{event.plan}}, {{event.amount}}, or {{event.active}}."},valueType:{type:"string",enum:["text","number","boolean"]}},required:["name","value"]}}},additionalProperties:!0},KQ={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."}},c$={type:"object",description:"A step to create inside a sequence path. Use type:'delay' for a standalone delay, type:'email' for an email, type:'create_discount' for a discount action, or type:'condition' for a condition gate.",properties:{type:{type:"string",enum:["email","delay","create_discount","discount","update_subscriber","condition","webhook"],description:"Sequence path step type. Omit for email steps; use delay for standalone waits or update_subscriber for action_update_attributes."},nodeType:{type:"string",enum:["logic_delay","action_email","action_create_discount","action_add_tag","action_remove_tag","action_add_to_list","action_remove_from_list","action_update_attributes","logic_wait_for_event","logic_condition","action_webhook"],description:"Advanced sequence path node type. Prefer type unless creating a non-email action."},config:{...Y0,description:"Config for advanced nodeType steps. For action_update_attributes, use the documented Update Subscriber fields and trigger-event merge tags; other node types accept their normal config fields.",additionalProperties:!0},subject:{type:"string",description:"Email subject. Required for email steps."},previewText:{type:"string",description:"Email preview text."},blocks:{type:"array",description:Q1,items:{type:"object"}},html:{type:"string",description:"HTML content for email steps. Stored as one raw HTML block. Use this for imported provider HTML."},delay:G1,delayMs:{type:"number",description:"Delay in milliseconds. Useful for standalone type:'delay' steps."},waitUntil:W1,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 vH(b){if(!b||typeof b!=="object")return null;let w=b;if(w.success!==!1)return null;if(typeof w.error==="string")return Error(w.error);if(w.error&&typeof w.error==="object"&&typeof w.error.message==="string")return Error(w.error.message);if(typeof w.message==="string")return Error(w.message);return Error("The tool returned an unsuccessful response.")}function FQ(b){return b.trim().toLowerCase().replace(/\s+/g,"-")}function yM(b){let w=new URLSearchParams;if(typeof b.query==="string"&&b.query.trim()!=="")w.set("query",b.query.trim());if(Array.isArray(b.tags)&&b.tags.length>0)w.set("tags",b.tags.filter(($)=>typeof $==="string"&&$.trim()!=="").join(","));if(typeof b.list==="string"&&b.list.trim()!=="")w.set("list",b.list.trim());if(typeof b.listId==="string"&&b.listId.trim()!=="")w.set("listId",b.listId.trim());if(typeof b.listName==="string"&&b.listName.trim()!=="")w.set("listName",b.listName.trim());if(typeof b.segmentId==="string"&&b.segmentId.trim()!=="")w.set("segmentId",b.segmentId);if(typeof b.status==="string"&&b.status.trim()!=="")w.set("status",b.status.trim());return w.set("page",String(b.page)),w.set("limit",String(b.pageSize)),w}async function xH(b,w){let $=typeof b.limit==="number"&&Number.isFinite(b.limit)?Math.max(1,Math.trunc(b.limit)):void 0,Q=Math.min(100,Math.max(1,$??100)),W=[],G=1,X=0,Y=0,J=0;while(!0){let H=yM({query:b.query,tags:b.tags,list:b.list,listId:b.listId,listName:b.listName,segmentId:b.segmentId,status:b.status,page:G,pageSize:Q}),A=await D("GET",`/api/v1/subscribers?${H.toString()}`,void 0,w);X=A.pagination?.total??A.subscribers.length,Y=A.pagination?.totalPages??1,J+=1,W.push(...A.subscribers??[]);let O=$!==void 0&&W.length>=$,q=A.pagination?G>=A.pagination.totalPages:(A.subscribers??[]).length<Q;if(O||q)break;G+=1}let z=$!==void 0?W.slice(0,$):W;return{success:!0,subscribers:z,pagination:{page:1,limit:Q,total:X,totalPages:Y,fetchedPages:J},returned:z.length,truncated:$!==void 0&&X>0&&z.length<X}}function hM(b){let w=typeof b.email==="string"&&b.email.trim()!==""?b.email.trim():void 0,$=typeof b.externalId==="string"&&b.externalId.trim()!==""?b.externalId.trim():void 0;return{...w?{email:w}:{},...$?{externalId:$}:{}}}function Hw(b,w){let $=hM(w);if(!$.email&&!$.externalId)throw Error(`Provide either \`email\` or \`externalId\` when calling \`${b}\`.`);return $}function m$(b,w){let $=new URLSearchParams;if(w?.includeMachineEngagement)$.set("includeMachineEngagement","true");let Q=$.toString(),W=Q?`?${Q}`:"";if(b.email)return`/api/v1/subscribers/${encodeURIComponent(b.email)}${W}`;return $.set("externalId",String(b.externalId)),`/api/v1/subscribers/external?${$.toString()}`}function MQ(b){if(b.email)return`/api/v1/subscribers/${encodeURIComponent(b.email)}/notes`;let w=new URLSearchParams;return w.set("externalId",String(b.externalId)),`/api/v1/subscribers/external/notes?${w.toString()}`}async function J0(b,w,$){return D("GET",m$(b,$),void 0,w)}function Vb(b,w,$,Q){let W=M(w,$);if(W===void 0)return;if(!Q.includes(W))throw Error(`\`${$}\` must be one of ${Q.join(", ")} when calling \`${b}\`.`);return W}function z0(b,w,$,Q){let W=j(b,w,$);if(!Q.includes(W))throw Error(`\`${$}\` must be one of ${Q.join(", ")} when calling \`${b}\`.`);return W}function zw(b,w,$,Q,W){let G=w[$];if(G===void 0)return;if(typeof G!=="number"||!Number.isInteger(G)||G<Q||G>W)throw Error(`\`${$}\` must be an integer between ${Q} and ${W} when calling \`${b}\`.`);return G}function fM(b,w){let $=[],Q=Vb(b,w,"eventType",C$);if(Q)$.push(Q);if(w.eventTypes!==void 0){if(!Array.isArray(w.eventTypes))throw Error(`\`eventTypes\` must be an array when calling \`${b}\`.`);w.eventTypes.forEach((W,G)=>{if(typeof W!=="string")throw Error(`\`eventTypes\` item ${G+1} must be a string when calling \`${b}\`.`);let X=W.trim();if(!C$.includes(X))throw Error(`\`eventTypes\` item ${G+1} must be one of ${C$.join(", ")} when calling \`${b}\`.`);$.push(X)})}return[...new Set($)]}function PQ(b,w){let $=new URLSearchParams,Q=fM(b,w);if(Q.length>0)$.set("eventTypes",Q.join(","));let W=Vb(b,w,"period",["1h","24h","7d","30d","90d"]);if(W)$.set("period",W);let G=M(w,"start");if(G)$.set("start",G);let X=M(w,"end");if(X)$.set("end",X);let Y=zw(b,w,"page",1,1e6);if(Y!==void 0)$.set("page",String(Y));let J=zw(b,w,"limit",1,500);if(J!==void 0)$.set("limit",String(J));if(w.includeMachineEngagement===!0)$.set("includeMachineEngagement","true");return $}function ZQ(b,w){if(w.events===void 0)return;if(!Array.isArray(w.events))throw Error(`\`events\` must be an array when calling \`${b}\`.`);let $=w.events.map((Q,W)=>{if(typeof Q!=="string"||!Y1.includes(Q))throw Error(`\`events\` item ${W+1} must be one of ${Y1.join(", ")} when calling \`${b}\`.`);return Q});if($.length===0)throw Error(`\`events\` must include at least one event type when calling \`${b}\`.`);return $}function IQ(b,w){if(!Array.isArray(w.emails))throw Error(`\`emails\` must be an array when calling \`${b}\`.`);let $=[];if(w.emails.forEach((Q,W)=>{if(typeof Q!=="string")throw Error(`\`emails\` item ${W+1} must be a string when calling \`${b}\`.`);let G=Q.trim();if(G.length>0)$.push(G)}),$.length===0)throw Error(`\`emails\` must include at least one email address when calling \`${b}\`.`);if($.length>JQ)throw Error(`\`emails\` must include no more than ${JQ} email addresses when calling \`${b}\`. Split larger batches into multiple calls.`);return $}function kH(b,w,$,Q){let W=w[$];if(W===void 0)return;if(!Array.isArray(W))throw Error(`\`${$}\` must be an array when calling \`${b}\`.`);let G=[];if(W.forEach((X,Y)=>{if(typeof X!=="string")throw Error(`\`${$}\` item ${Y+1} must be a string when calling \`${b}\`.`);let J=X.trim();if(J.length>0)G.push(J)}),G.length===0)throw Error(`\`${$}\` must include at least one ${Q} when calling \`${b}\`.`);return G}function uH(b){let $=kH("enroll_subscribers_in_sequence",b,"emails","email address"),Q=kH("enroll_subscribers_in_sequence",b,"subscriberIds","subscriber ID"),W=($?.length??0)+(Q?.length??0);if(W===0)throw Error("Provide `emails` or `subscriberIds` when calling `enroll_subscribers_in_sequence`.");if(W>zQ)throw Error(`\`emails\` and \`subscriberIds\` must include no more than ${zQ} total targets when calling \`enroll_subscribers_in_sequence\`. Split larger batches into multiple calls.`);let G=M(b,"targetNodeId");return{...$!==void 0&&{emails:$},...Q!==void 0&&{subscriberIds:Q},...G!==void 0&&{targetNodeId:G}}}import{readFileSync as gM,statSync as cM}from"node:fs";import{basename as mM}from"node:path";var lM={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 nM(b){let w=b.split(".").pop()?.toLowerCase()??"";return lM[w]??null}var iM=104857600;async function yH(b,w){if(!kQ())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 $=nM(b);if(!$)throw Error("Unsupported file type. Use PDF, ePub, ZIP, image, audio, video, or text files.");let Q=cM(b).size;if(Q>iM)throw Error(`File is too large (${Math.round(Q/1048576)}MB). Delivery files must be 100MB or smaller.`);let W=gM(b),G=await D("POST","/api/v1/products/delivery/upload-url",{filename:mM(b),contentType:$,fileSizeBytes:Q},w),X=await fetch(G.uploadUrl,{method:"PUT",headers:{"Content-Type":$},body:W});if(!X.ok)throw Error(`File upload failed (${X.status})`);return{url:G.publicUrl,fileName:G.fileName,fileSizeBytes:Q,mimeType:$}}async function l$(b){let w=M(b,"companyId");if(w)return w;let $=Dw();if($)return $;try{return(await D("GET","/api/v1/account")).currentCompanyId??void 0}catch{return}}async function hH(b,w){let $=await l$(w);if(!$)throw Error(`A company is required when calling \`${b}\`. Call \`get_account\`, then \`select_company\`, or pass \`companyId\` explicitly.`);return $}function z1(b,w){if(!y(b)||!w)return b;return{...b,url:w}}function fH(b,w){if(!y(b))return b;return{...b,...w.campaign!==void 0&&{url:w.campaign},...w.campaignPreview!==void 0&&{previewUrl:w.campaignPreview}}}function H0(b,w,$){if(!Array.isArray(b)||!w)return b;return b.map((Q)=>{if(!y(Q))return Q;let W=M(Q,"id");if(!W)return Q;let G=Yw({companyId:w,...$==="campaign"&&{campaignId:W},...$==="landingPage"&&{landingPageId:W},...$==="sequence"&&{sequenceId:W},...$==="template"&&{emailId:W},...$==="transactional"&&{transactionalId:W}});if($==="campaign")return fH(Q,G.urls);let X=$==="sequence"?G.urls.sequence:$==="landingPage"?G.urls.landingPage:$==="template"?G.urls.email:G.urls.transactionalEmail;return z1(Q,X)})}function pM(b){if(!Array.isArray(b))return b;return b.map((w)=>{if(!y(w))return w;let $=M(w,"id");if(!$)return w;let Q=Yw({companyId:$});return{...w,url:Q.urls.dashboard,settingsUrl:Q.urls.settings}})}var VQ=new Set(["get_account","select_company","create_company","get_company","update_company","list_campaigns","get_campaign","get_email_send","create_campaign","update_campaign","schedule_campaign","send_test_email","cancel_campaign","pause_campaign","resume_campaign","duplicate_campaign","resend_campaign_to_non_openers","list_landing_pages","get_landing_page","create_landing_page","update_landing_page","publish_landing_page","unpublish_landing_page","delete_landing_page","list_sequences","get_sequence","create_sequence","update_sequence","update_sequence_node","update_sequence_nodes","edit_sequence_graph","insert_sequence_step","enable_sequence","disable_sequence","pause_sequence_enrollments","resume_sequence_enrollments","cancel_sequence_enrollments","list_ab_tests","get_ab_test","get_ab_test_stats","update_ab_test_variant","list_templates","get_template","create_template","update_template","list_transactional_emails","get_transactional_email","create_transactional_email","update_transactional_email"]);async function gH(b,w,$){if(!y($)||!VQ.has(b))return $;let Q=y($.company)?$.company:void 0,G=M($,"selectedCompanyId")??M($,"currentCompanyId")??M($,"companyId")??(Q?M(Q,"id"):void 0)??(Q?M(Q,"companyId"):void 0)??await l$(w);if(!G)return $;let X=y($.campaign)?$.campaign:void 0,Y=y($.sequence)?$.sequence:void 0,J=y($.landingPage)?$.landingPage:void 0,z=y($.template)?$.template:void 0,H=y($.transactional)&&!Array.isArray($.transactional)?$.transactional:void 0,A={companyId:G,campaignId:M(w,"campaignId")??M($,"campaignId")??(X?M(X,"id"):void 0),landingPageId:M(w,"landingPageId")??M($,"landingPageId")??(J?M(J,"id"):void 0),sequenceId:M(w,"sequenceId")??M($,"sequenceId")??(Y?M(Y,"id"):void 0),emailId:M($,"templateId")??(z?M(z,"id"):void 0)??(H?M(H,"emailId"):void 0)??M(w,"templateId"),transactionalId:M(w,"transactionalId")??(H?M(H,"id"):void 0)??M(w,"idOrSlug"),emailSendId:M(w,"emailSendId")??M($,"emailSendId")??(y($.emailSend)?M($.emailSend,"id"):void 0),status:M(w,"status")},O=Yw(A),q=Q?Yw({companyId:G}):void 0;return{...$,...Array.isArray($.companies)&&{companies:pM($.companies)},...Array.isArray($.campaigns)&&{campaigns:H0($.campaigns,G,"campaign")},...Array.isArray($.landingPages)&&{landingPages:H0($.landingPages,G,"landingPage")},...Array.isArray($.sequences)&&{sequences:H0($.sequences,G,"sequence")},...Array.isArray($.templates)&&{templates:H0($.templates,G,"template")},...Array.isArray($.transactional)&&{transactional:H0($.transactional,G,"transactional")},...Q&&q!==void 0&&{company:{...Q,url:q.urls.dashboard,settingsUrl:q.urls.settings}},...X&&O.urls.campaign!==void 0&&{campaign:fH(X,O.urls)},...Y&&O.urls.sequence!==void 0&&{sequence:z1(Y,O.urls.sequence)},...J&&O.urls.landingPage!==void 0&&{landingPage:z1(J,O.urls.landingPage)},...z&&O.urls.email!==void 0&&{template:z1(z,O.urls.email)},...H&&O.urls.transactionalEmail!==void 0&&{transactional:z1(H,O.urls.transactionalEmail)},...y($.emailSend)&&O.urls.emailSend!==void 0&&{emailSend:z1($.emailSend,O.urls.emailSend)},appUrls:O.urls}}var oM={type:"boolean",description:"Whether the Sequenzy operation succeeded."},dM={type:"string",description:"Human-readable status, confirmation, or next-step message."},rM={type:"string",description:"Additional context about the result."};function a(b){return{type:"object",description:b,additionalProperties:!0}}function tM(b){return{type:"array",description:b,items:a("One item in the returned collection.")}}function T(b){return{type:"string",description:b}}function jb(b){return{type:"number",description:b}}function tb(b){return{type:"boolean",description:b}}function F(b){return a(`The ${b} record returned by Sequenzy.`)}function i(b){return tM(`List of ${b} records returned by Sequenzy.`)}var eM={appUrls:a("Dashboard URLs for relevant Sequenzy resources."),url:T("Primary dashboard URL for this result."),settingsUrl:T("Company settings URL when available.")},sM={success:oM,message:dM,note:rM,items:{type:"array",description:"Fallback array wrapper used only when a tool returns a bare array.",items:a("One returned item.")},value:a("Fallback object wrapper used only when a tool returns a non-object value.")},aM={get_account:{account:F("account"),companies:i("company"),apiKeyPermissions:a("Current API key preset and scopes, whether common marketing work is discoverable, any missing marketing read scopes, and the API Keys management URL."),currentCompanyId:T("Company ID selected by the authenticated API key, when available."),selectedCompanyId:T("Company ID selected locally for subsequent MCP calls, when available.")},select_company:{companyId:T("Selected company ID."),companyName:T("Selected company name.")},get_app_urls:{dashboard:T("Company dashboard URL."),settings:T("Company settings URL."),campaign:T("Campaign editor URL."),landingPage:T("Landing page editor URL."),sequence:T("Sequence editor URL."),email:T("Email editor URL."),transactionalEmail:T("Transactional email URL."),emailSend:T("Sent email detail URL."),domain:T("Sending domain settings URL."),urls:a("All generated URLs keyed by resource type.")},create_company:{company:F("company"),autoSelected:tb("Whether the new company was selected for subsequent MCP calls.")},update_company:{company:F("company")},get_company:{company:F("company")},get_sync_rules:{syncRules:{type:"array",description:"Effective sync rules for the company.",items:a("One sync rule.")},isDefault:tb("Whether the company still uses the platform default rules.")},update_sync_rules:{syncRules:{type:"array",description:"Effective sync rules after the update.",items:a("One sync rule.")},isDefault:tb("Whether the company now uses the platform default rules.")},get_shopify_automation_settings:{browseAbandonment:a("Effective browse-abandonment settings (defaults applied)."),priceDrop:a("Effective price-drop settings (defaults applied)."),shopDomain:T("Connected Shopify store domain.")},update_shopify_automation_settings:{browseAbandonment:a("Effective browse-abandonment settings after the update."),priceDrop:a("Effective price-drop settings after the update."),shopDomain:T("Connected Shopify store domain.")},create_api_key:{apiKey:a("Created API key metadata: the newly created secret in `key`, plus `scopes` listing the assigned permission scopes (null when the key has full access)."),key:T("Newly created API key if the API response uses the short key field.")},list_websites:{websites:i("sender website")},add_website:{website:F("Sending domain with the SPF, DKIM, MAIL FROM, and inbound DNS records required for setup.")},add_sending_domain:{website:F("Sending domain with the SPF, DKIM, MAIL FROM, and inbound DNS records required for setup.")},check_website:{website:F("sender website"),ready:tb("Whether the sender website is ready."),status:T("Current processing or verification status.")},verify_sending_domain:{website:F("Sending domain with current aggregate, SPF, DKIM, and MAIL FROM verification details."),verified:tb("Whether the sending domain passed the fresh verification check."),message:T("Verification result summary.")},get_integration_guide:{guide:F("integration guide"),code:T("Generated integration code or example."),steps:{type:"array",description:"Setup steps for the requested integration.",items:a("One setup step.")}},add_subscriber:{subscriber:F("subscriber")},update_subscriber:{subscriber:F("subscriber")},remove_subscriber:{subscriber:F("subscriber"),hardDeleted:tb("Whether the subscriber was permanently deleted.")},get_subscriber:{subscriber:F("subscriber")},list_subscriber_notes:{notes:i("subscriber note")},add_subscriber_note:{note:F("subscriber note")},delete_subscriber_note:{id:T("Deleted subscriber note ID."),deleted:tb("Whether the subscriber note was deleted.")},search_subscribers:{subscribers:i("subscriber"),pagination:a("Pagination metadata."),returned:jb("Number of subscribers returned."),truncated:tb("Whether the result was truncated by the requested limit.")},list_products:{products:i("product")},upsert_products:{products:i("product"),created:jb("Number of products created."),updated:jb("Number of products updated.")},delete_product:{productId:T("Deleted product ID.")},attach_product_file:{product:F("product"),delivery:F("digital delivery file")},remove_product_file:{product:F("product")},sync_products:{job:F("product sync job"),jobId:T("Queued product sync job ID.")},list_tags:{tags:i("tag")},create_tag:{tag:F("tag")},update_tag:{tag:F("tag")},delete_tag:{tagId:T("Deleted tag ID.")},list_lists:{lists:i("list")},create_list:{list:F("list")},update_list:{list:F("list")},delete_list:{listId:T("Deleted list ID.")},add_subscribers_to_list:{list:F("list"),added:jb("Number of subscribers added to the list."),skipped:jb("Number of subscribers skipped.")},remove_subscribers_from_list:{list:F("list"),removed:jb("Number of subscribers removed from the list."),skipped:jb("Number of subscribers skipped.")},list_segments:{segments:i("segment")},create_segment:{segment:F("segment")},update_segment:{segment:F("segment")},delete_segment:{segmentId:T("Deleted segment ID.")},get_segment_count:{count:jb("Number of subscribers matching the segment."),segmentId:T("Segment ID that was counted.")},list_audience_syncs:{audienceSyncs:i("audience sync")},list_ad_accounts:{adAccounts:i("ad account")},create_audience_sync:{audienceSync:F("audience sync")},update_audience_sync:{audienceSync:F("audience sync")},delete_audience_sync:{audienceSyncId:T("Deleted audience sync ID.")},sync_audience_now:{audienceSync:F("audience sync"),job:F("audience sync job"),jobId:T("Queued audience sync job ID.")},list_templates:{templates:i("email template")},get_template:{template:F("email template")},create_template:{template:F("email template")},update_template:{template:F("email template")},delete_template:{templateId:T("Deleted template ID.")},list_ab_tests:{abTests:i("A/B test")},get_ab_test:{abTest:F("A/B test")},get_ab_test_stats:{abTest:F("A/B test"),stats:F("A/B test statistics")},restart_ab_test:{abTest:F("A/B test")},update_ab_test_variant:{abTest:F("A/B test"),variant:F("A/B test variant")},create_ab_test:{abTest:F("A/B test")},add_ab_test_variant:{abTest:F("A/B test"),variant:F("A/B test variant")},delete_ab_test_variant:{abTest:F("A/B test"),variantId:T("Deleted A/B test variant ID.")},delete_ab_test:{abTestId:T("Deleted A/B test ID.")},list_campaigns:{campaigns:i("campaign")},get_campaign:{campaign:F("campaign")},get_email_send:{emailSend:F("email send")},create_campaign:{campaign:F("campaign")},update_campaign:{campaign:F("campaign")},schedule_campaign:{campaign:F("campaign"),scheduledAt:T("Scheduled send timestamp.")},send_test_email:{emailSend:F("test email send"),recipient:T("Test email recipient.")},send_test_sms:{smsSendId:T("Created test SMS send ID."),toPhone:T("Normalized E.164 destination phone.")},cancel_campaign:{campaign:F("campaign")},pause_campaign:{campaign:F("campaign")},resume_campaign:{campaign:F("campaign")},delete_campaign:{campaignId:T("Deleted campaign ID.")},duplicate_campaign:{campaign:F("duplicated campaign")},resend_campaign_to_non_openers:{campaign:F("non-opener resend draft campaign"),estimatedNonOpenerCount:jb("Estimated number of subscribers who haven't opened the original campaign.")},list_landing_pages:{landingPages:i("landing page")},get_landing_page:{landingPage:F("landing page")},create_landing_page:{landingPage:F("landing page")},update_landing_page:{landingPage:F("landing page")},delete_landing_page:{landingPageId:T("Deleted landing page ID.")},publish_landing_page:{landingPage:F("landing page")},unpublish_landing_page:{landingPage:F("landing page")},connect_landing_page_domain:{landingPage:F("landing page"),domain:T("Connected landing page domain.")},update_landing_page_domain_settings:{landingPage:F("landing page"),domain:T("Landing page domain.")},list_sequences:{sequences:i("sequence")},get_sequence:{sequence:F("sequence")},create_sequence:{sequence:F("sequence"),eventTrackingCode:T("Ready-to-adapt code for sending a custom trigger event, including any matching-field property."),eventTracking:a("Custom-event endpoint, payload contract, example payload, documentation URL, and get_integration_guide arguments."),requiredEvents:{type:"array",description:"Event names the application or an integration must send.",items:T("One required event name.")}},update_sequence:{sequence:F("sequence")},update_sequence_node:{sequence:F("sequence")},update_sequence_nodes:{sequence:F("sequence")},edit_sequence_graph:{sequence:F("sequence")},insert_sequence_step:{sequence:F("sequence"),insertedNodeIds:{type:"array",description:"Node IDs created for the inserted step, including any delay node.",items:T("Inserted automation node ID.")},insertedEmailIds:{type:"array",description:"Email template IDs created for the inserted step.",items:T("Inserted email template ID.")},insertedEmailCount:jb("Number of email steps inserted.")},enable_sequence:{sequence:F("sequence")},disable_sequence:{sequence:F("sequence")},pause_sequence_enrollments:{sequenceId:T("Sequence ID."),enrollmentPaused:tb("Whether new sequence enrollments are paused.")},resume_sequence_enrollments:{sequenceId:T("Sequence ID."),enrollmentPaused:tb("Whether new sequence enrollments are paused.")},enroll_subscribers_in_sequence:{sequence:F("sequence"),enrollments:i("sequence enrollment"),enrolled:jb("Number of subscribers enrolled."),skipped:jb("Number of subscribers skipped.")},cancel_sequence_enrollments:{sequence:F("sequence"),cancelled:jb("Number of enrollments cancelled."),skipped:jb("Number of enrollments skipped.")},delete_sequence:{sequenceId:T("Deleted sequence ID.")},list_transactional_emails:{transactional:i("transactional email")},get_transactional_email:{transactional:F("transactional email")},create_transactional_email:{transactional:F("transactional email")},update_transactional_email:{transactional:F("transactional email")},send_email:{emailSend:F("transactional email send"),transactional:F("transactional email")},get_stats:{stats:F("account or company statistics")},get_campaign_stats:{campaign:F("campaign"),stats:F("campaign statistics"),polls:{type:"array",description:`Poll and NPS summaries. Each subscriber counts once per campaign poll block using their latest answer to that block; NPS entries include score, average, and promoter/passive/detractor counts. To list the exact historical respondents behind a count, use the summary blockId and the get_campaign_stats campaignId with create_segment. ${Ew} A summary's attributeKey identifies the subscriber attribute that stores their current/latest response and may be overwritten by a later poll that reuses the key.`,items:a("One poll or NPS results summary.")}},get_sequence_stats:{sequence:F("sequence"),stats:F("sequence statistics")},list_campaign_events:{events:i("campaign email event"),pagination:a("Pagination metadata.")},list_sequence_events:{events:i("sequence email event"),pagination:a("Pagination metadata.")},get_subscriber_activity:{activity:i("subscriber activity event"),subscribers:i("subscriber"),pagination:a("Pagination metadata.")},list_team_members:{members:i("team member"),invitations:i("team invitation")},invite_team_member:{invitation:F("team invitation")},cancel_team_invitation:{invitationId:T("Cancelled invitation ID.")},list_conversations:{conversations:i("inbox conversation"),pagination:a("Pagination metadata.")},get_conversation:{conversation:F("inbox conversation"),messages:i("conversation message")},reply_to_conversation:{conversation:F("inbox conversation"),message:F("conversation message")},update_conversation_status:{conversation:F("inbox conversation")},mark_conversation_read:{conversation:F("inbox conversation")},list_webhooks:{webhooks:i("outbound webhook")},create_webhook:{webhook:F("outbound webhook")},update_webhook:{webhook:F("outbound webhook")},delete_webhook:{webhookId:T("Deleted outbound webhook ID.")},test_webhook:{webhook:F("outbound webhook"),delivery:F("test webhook delivery")},list_webhook_deliveries:{deliveries:i("webhook delivery")},replay_webhook_delivery:{delivery:F("webhook delivery"),job:F("webhook replay job")},generate_email:{email:F("generated email"),html:T("Generated HTML email body."),blocks:{type:"array",description:"Generated Sequenzy email blocks, wrapped with company branding (logo + footer) unless applyBranding was false.",items:a("One generated email block.")},subject:T("Generated subject line."),previewText:T("Generated inbox preview text.")},generate_sequence:{sequence:F("generated sequence"),steps:i("generated sequence step")},generate_subject_lines:{subjectLines:{type:"array",description:"Generated subject line variants.",items:T("One generated subject line.")},variants:i("generated subject line variant")},generate_sms:{prompt:T("The prompt the messages were generated for."),messages:{type:"array",description:"Generated SMS message variants with encoding and segment counts.",items:a("One generated SMS message.")}},get_sms_settings:{sms:a("SMS add-on status: enabled, planEligible, creditsBalance, brandPrefix, numbers, readyToSend (paid plan or credits plus an active number).")},submit_feedback:{}};function bP(b){let w=aM[b];if(w===void 0)throw Error(`MCP tool "${b}" must define outputSchema properties.`);return{type:"object",description:`Structured content returned by the \`${b}\` MCP tool.`,properties:{...sM,...w,...VQ.has(b)?eM:{}},additionalProperties:!0}}function cH(b){return{...b,outputSchema:bP(b.name)}}function mH(b){if(y(b))return b;if(Array.isArray(b))return{items:b};return{value:b}}var lH=[{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:nb},required:["abTestId"]}},{name:"restart_ab_test",description:"Run another sequence A/B test after a winner is selected. By default the winner becomes the new control; pass sourceVariantId to use another variant as the control email.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID to restart"},sourceVariantId:{type:"string",description:"Optional variant ID to use as the new control email. Defaults to the selected winner."},testType:{type:"string",description:"Optional test type: subject or content."},winnerThreshold:{type:"number",description:"Optional number of subscribers before selecting a winner. Must be from 10 to 1000."},variantCount:{type:"number",description:"Optional total variants including the control. Must be from 2 to 4."}},required:["abTestId"],additionalProperties:!1}},{name:"update_ab_test_variant",description:"Update a draft A/B test variant. Provide at least one of subject, previewText, html, or blocks. Use either html or blocks, not both.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"},variantId:{type:"string",description:"A/B test variant ID"},subject:{type:"string",description:"Variant subject line"},previewText:{type:"string",description:"Variant preview text. Pass an empty string to clear it."},html:{type:"string",description:"Replacement HTML body. Mutually exclusive with blocks."},blocks:{type:"array",description:`${Jw} Mutually exclusive with html.`,items:{type:"object"}}},required:["abTestId","variantId"],additionalProperties:!1}},{name:"create_ab_test",description:"Create a campaign A/B test. Control variant A is created automatically from the campaign's current email; optionally provide extra variants. The campaign must be in draft or rejected status, and each campaign can only have one A/B test.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Draft campaign ID to create the A/B test for."},name:{type:"string",description:"Optional A/B test name."},testPercentage:{type:"number",description:"Percentage of the audience used for the test phase, from 5 to 50. Defaults to 20."},testDurationMinutes:{type:"number",description:"Test phase duration in minutes before the winner is selected, from 15 to 1440. Defaults to 240."},winnerCriteria:{type:"string",enum:["open_rate","click_rate"],description:"Winner selection criteria. Defaults to open_rate."},variants:{type:"array",description:"Optional extra variants to create in addition to control variant A.",items:{type:"object",properties:{subject:{type:"string",description:"Variant subject line."},previewText:{type:"string",description:"Variant preview text."},blocks:{type:"array",description:Jw,items:{type:"object"}}},required:["subject"]}}},required:["campaignId"]}},{name:"add_ab_test_variant",description:"Add a variant to a draft campaign A/B test. Variants cannot be added after the test has started.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"},subject:{type:"string",description:"Variant subject line."},previewText:{type:"string",description:"Variant preview text."},blocks:{type:"array",description:Jw,items:{type:"object"}}},required:["abTestId","subject"]}},{name:"delete_ab_test_variant",description:"Permanently delete a variant from a draft campaign A/B test. This cannot be undone. Variant A is the control and cannot be deleted, and the test must keep at least the minimum number of variants. Variants cannot be removed after the test has started.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"},variantId:{type:"string",description:"A/B test variant ID to delete."}},required:["abTestId","variantId"]}},{name:"delete_ab_test",description:"Permanently delete a campaign A/B test and all of its variants. This cannot be undone. Running tests (testing or winner_selected) cannot be deleted, and the linked campaign must be in draft or rejected status.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID to delete."}},required:["abTestId"]}}];var nH=[{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:YH,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:{...XH,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:YH,minItems:1,description:"Replacement segment filters. Same shape and validation rules as create_segment. Mutually exclusive with `root`."},root:{...XH,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:MV},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, editable step content, and graph topology. Each sequence.nodes item includes id, nodeType, current config, updatedAt, and updateHints with its editable/managed fields and ready-to-return expectedUpdatedAt token for update_sequence_node/update_sequence_nodes. The response also includes sequence.edges and graphRevision for safe edit_sequence_graph calls, plus sequence.emails with each email step's nodeId, linked emailId, subject, previewText, and blocks.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"],additionalProperties:!1}},{name:"create_sequence",description:`Create a new email sequence. For net-new natural-language sequence content, provide goal and emailCount so Sequenzy generates it. Use explicit steps only for finished caller-supplied content, exact workflows, or migrations. Explicit steps can include email content, native SMS steps (type: 'sms' with 'text'; check get_sms_settings first and generate copy with generate_sms), and create_discount actions that dynamically create a provider discount/code when each subscriber reaches the step; emails after a discount action can use merge tags such as {{discount.code}} and {{discount.percentOff}}. For AI-generated sequences, the tool polls until emails are generated (typically 30-60 seconds).
|
|
51
|
+
Before implementing, use create_api_key to generate an API key and save it to .env as SEQUENZY_API_KEY.`,inputSchema:{type:"object",properties:{framework:{type:"string",description:"Framework/language (nextjs, express, python, etc.)"},use_case:{type:"string",description:"Use case: 'transactional' (sending emails), 'subscribe_form' (adding subscribers), 'event_tracking' (tracking CUSTOM events only - payment events should come from Stripe/Polar/etc integration), 'ecommerce' (connecting a custom e-commerce platform via the Commerce API)"}}}}];var iH=[{name:"generate_email",description:"Generate email blocks from a prompt. Generated blocks include the company's branding chrome (logo, footer with company name/address/unsubscribe) by default, matching emails created in the dashboard.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},prompt:{type:"string",description:"Description of the email to generate"},style:{type:"string",description:"Style: minimal, branded, promotional"},tone:{type:"string",description:"Tone: professional, casual, friendly"},applyBranding:{type:"boolean",description:"Wrap the generated content with company branding (logo + footer). Defaults to true; set false to get raw content blocks only."},emailType:{type:"string",enum:["marketing","transactional"],description:"Email type. Transactional emails get a footer without the unsubscribe link. Defaults to marketing."}},required:["prompt"]}},{name:"generate_sequence",description:"[DEPRECATED - Use create_sequence instead] Generate a multi-email sequence from a goal. Note: create_sequence now handles AI generation automatically.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},goal:{type:"string",description:"Goal of the sequence (e.g., 'onboard new SaaS trial users')"},emailCount:{type:"number",description:"Number of emails in the sequence (default: 5, max: 10)"},durationDays:{type:"number",description:"Total duration in days (default: 14)"}},required:["goal"]}},{name:"generate_subject_lines",description:"Generate A/B test subject line variants",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},topic:{type:"string",description:"Topic or context for the subject lines"},count:{type:"number",description:"Number of variants to generate (default: 5)"}},required:["topic"]}},{name:"generate_sms",description:"Generate SMS marketing message variants from a prompt. Returns plain-text messages with per-message encoding and segment counts. Use the results as the 'text' of an SMS sequence step (insert_sequence_step with type 'sms' or a create_sequence sms step). Messages exclude opt-out footers and brand prefixes - the platform adds those automatically at send time.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},prompt:{type:"string",description:"Description of the SMS to generate (e.g., 'cart reminder with a free-shipping hook')"},count:{type:"number",description:"Number of message variants to generate (default: 3, max: 10)"}},required:["prompt"]}},{name:"get_sms_settings",description:"Get the company's SMS add-on status: whether SMS is enabled, plan eligibility, credit balance, brand prefix, phone numbers, and whether SMS steps will actually send. Check this before adding SMS steps to sequences so you can warn the user when SMS is not ready.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"send_test_sms",description:"Send a test SMS to a phone number. IMPORTANT: sends a real text message and charges SMS credits - only call when the user explicitly asks for a test send. Requires the SMS add-on with a verified number (check get_sms_settings). Limited to 5 test sends per hour; bypasses quiet hours; excluded from step stats.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},to:{type:"string",description:"Destination phone number in international E.164 format, e.g. +15550100123."},text:{type:"string",description:"Plain-text message body. Merge tags are not resolved for test sends to arbitrary numbers. Provide text or blocks."},imageUrls:{type:"array",items:{type:"string"},description:"Up to 2 publicly reachable image URLs sent as MMS media (US/CA only)."},blocks:{type:"array",items:{type:"object"},description:"SMS content blocks (text + image subset). Provide text or blocks, not both."}},required:["to"]}}];var pH=[{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:nb}}},{name:"get_campaign_stats",description:"Get detailed statistics for a campaign, including attributed conversions, revenue (revenueCents), and any Poll or NPS survey summaries in the top-level polls array",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"},includeMachineEngagement:nb},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:nb},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:nb},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:nb},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:nb},required:[]}}];var oH=[{name:"list_audience_syncs",description:"List Meta custom audience syncs (segment -> ad audience mappings) with their schedule and last sync status. Requires the Meta Ads integration to be connected in the dashboard.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"list_ad_accounts",description:"List the Meta ad accounts available through the connected Meta Ads integration. Use the returned account id as `adAccountId` when creating an audience sync.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"create_audience_sync",description:'Push a segment to a Meta custom audience and keep it synced on a schedule. Provide `segmentId` for an existing segment OR `predefinedSegmentId` for a ready-made template (for example "zero-ltv", "no-purchase-1y", "recent-buyers", "high-spenders-ecom", "non-buyers", "engaged") - the template segment is created automatically on first use. The first upload runs immediately. Note: audiences are add-only; subscribers who later leave the segment stay in the Meta audience.',inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},segmentId:{type:"string",description:"Existing segment ID to sync. Mutually exclusive with `predefinedSegmentId`."},predefinedSegmentId:{type:"string",description:'Predefined segment template ID (for example "zero-ltv", "no-purchase-1y", "recent-buyers"). The segment is created automatically if it does not exist. Mutually exclusive with `segmentId`.'},adAccountId:{type:"string",description:"Meta ad account ID (act_...) from `list_ad_accounts`."},audienceName:{type:"string",description:"Name for the custom audience in Meta Ads Manager."},frequency:{type:"string",enum:["hourly","daily","weekly"],description:"How often to re-upload the segment. Default: daily."}},required:["adAccountId","audienceName"]}},{name:"update_audience_sync",description:"Update an audience sync's frequency or pause/resume it (`isActive`).",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},syncId:{type:"string",description:"Audience sync ID"},frequency:{type:"string",enum:["hourly","daily","weekly"],description:"New sync frequency."},isActive:{type:"boolean",description:"Set false to pause the sync, true to resume it."}},required:["syncId"]}},{name:"delete_audience_sync",description:"Remove an audience sync mapping. The Meta audience itself is kept (running ads are not disrupted) - only future syncs stop.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},syncId:{type:"string",description:"Audience sync ID to remove."}},required:["syncId"]}},{name:"sync_audience_now",description:"Trigger an immediate upload of the segment's subscribers to its Meta custom audience, outside the regular schedule.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},syncId:{type:"string",description:"Audience sync ID to run."}},required:["syncId"]}}];var dH=[{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:Tw,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:Tw,items:{type:"object"}},replyTo:{type:"string",description:"Set reply-to using an existing reply profile email address for this company."},replyProfileId:{type:"string",description:"Set reply-to using a reply profile ID for this company."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo."},fromEmail:{type:"string",description:"Set this campaign's From address. Its domain must be configured and verified."},fromName:{type:"string",description:"Display name for a newly created sender profile. Requires fromEmail."},senderProfileId:{type:"string",description:"Set an existing sender profile. Mutually exclusive with fromEmail."},campaignData:{type:"object",description:"Set campaign-scoped JSON data for repeat blocks and personalization."},computedLists:{type:"array",description:"Set computed list definitions derived from campaignData at send time.",items:{type:"object"}},labels:{type:"array",description:"Replacement label names. Send an empty array to clear labels. Missing labels are created automatically.",items:{type:"string"}}},required:["campaignId"],additionalProperties:!1}},{name:"schedule_campaign",description:"Schedule a draft or already scheduled campaign. Returns dashboard edit and preview URLs.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"},scheduledAt:{type:"string",description:"Future ISO 8601 timestamp for the send, for example 2026-06-01T14:00:00Z."},targetLists:{type:"object",description:"Optional campaign targeting object. Omit to use saved targeting or all active subscribers. Examples: {type:'all'}, {type:'lists', listIds:['list_123']}, {type:'segment', segmentId:'seg_123'}, {type:'filtered', filters:[...], filterJoinOperator:'and'}, or {type:'rules', include:[{type:'lists', listIds:['list_123']}], exclude:[{type:'segments', segmentIds:['seg_123']}]}. Rules audiences require at least one include rule.",additionalProperties:!0},sendTimeOptimization:{type:"boolean",description:"Whether to use send-time optimization."},spreadOverHours:{type:"number",description:"Spread delivery over an integer number of hours from 1 to 72. When set, spread delivery takes precedence over send-time optimization."},recurringInterval:{type:"string",enum:["weekly","monthly"],description:"Repeat this campaign on a cadence starting at scheduledAt. The campaign becomes a recurring template: each run is duplicated and sent automatically, re-evaluating audience membership every time. Omit for a one-shot send; scheduling again without it stops the recurrence."}},required:["campaignId","scheduledAt"],additionalProperties:!1}},{name:"send_test_email",description:"Send a test email to a single address",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to test"},to:{type:"string",description:"Email address to send test to"}},required:["campaignId","to"]}},{name:"cancel_campaign",description:"Cancel a campaign. Stops scheduled and sending campaigns (also works for paused and approval-pending ones). Remaining emails will not be sent and the campaign cannot be restarted - this cannot be undone.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to cancel."}},required:["campaignId"]}},{name:"pause_campaign",description:"Pause a campaign that is currently sending. Only campaigns in sending status can be paused. Use resume_campaign to continue delivery later.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to pause."}},required:["campaignId"]}},{name:"resume_campaign",description:"Resume a paused campaign. Only campaigns in paused status can be resumed. Optionally spread the remaining delivery over a number of hours.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to resume."},spreadOverHours:{type:"number",description:"Spread the remaining delivery over an integer number of hours from 1 to 72."}},required:["campaignId"]}},{name:"delete_campaign",description:"Permanently delete a campaign. This cannot be undone. Sending, scheduled, or paused campaigns must be cancelled with cancel_campaign first.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to delete."}},required:["campaignId"]}},{name:"duplicate_campaign",description:"Duplicate a campaign as a new draft. mode 'campaign' (default) copies the campaign and its email, 'ab_test' also duplicates the campaign's A/B test with all variants, and 'variant' copies a single variant's content as the new campaign email (requires variantId).",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to duplicate."},mode:{type:"string",enum:["campaign","ab_test","variant"],description:"Duplication mode. Defaults to campaign."},variantId:{type:"string",description:"A/B test variant ID whose content becomes the new campaign email. Required when mode is variant."}},required:["campaignId"]}},{name:"resend_campaign_to_non_openers",description:"Create a draft that resends a sent campaign to everyone in the same audience who didn't open it. Copies the campaign email and reuses the original audience with a 'didn't open this campaign' rule added. Only available 6 hours after the campaign finishes sending. The draft must be scheduled or sent separately. Returns the new draft and an estimate of how many subscribers haven't opened the original.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"ID of the sent campaign to resend to non-openers."}},required:["campaignId"]}}];var rH=[{name:"submit_feedback",description:"Send product feedback about Sequenzy itself to the Sequenzy team. IMPORTANT: call this tool whenever the user wanted to accomplish something and Sequenzy did not expose functionality for it - a missing tool or argument, an unsupported workflow, a confusing behavior, or a bug. Briefly tell the user you reported the gap. This feedback goes straight to the team and shapes what gets built next. Do not use it for questions about the user's own account or data, and never include secrets or API keys. Submitting feedback never changes account data.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},message:{type:"string",description:"The feedback itself. Be specific: what was needed, what was missing or wrong, and what you did instead (workaround, gave up, used the dashboard)."},category:{type:"string",enum:["missing_capability","bug","docs","ux","praise","other"],description:"Feedback category. Use missing_capability when the user wanted something these tools do not support (default: other)."},context:{type:"string",description:"Optional: what the user was trying to accomplish, in their words, plus any relevant tool names or arguments you tried."}},required:["message"]}}];var tH=[{name:"list_conversations",description:"List inbox conversations (email replies from subscribers). Filter by status, free-text search, or unread state, with pagination.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},status:{type:"string",enum:["open","closed","all"],description:"Filter by conversation status. Defaults to all."},search:{type:"string",description:"Free-text search across conversation subjects and participants."},unread:{type:"boolean",description:"Set true to only return conversations with unread messages."},page:{type:"number",description:"Page number. Defaults to 1."},limit:{type:"number",description:"Results per page, from 1 to 100. Defaults to 20."}}}},{name:"get_conversation",description:"Get a conversation with its full message history, subscriber details, and context.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},conversationId:{type:"string",description:"Conversation ID."}},required:["conversationId"]}},{name:"reply_to_conversation",description:"Send a reply in a conversation, or add an internal note. type 'outbound' (default) emails the subscriber and requires bodyText or bodyHtml; type 'note' adds a private team-only note. Replying to a closed conversation reopens it.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},conversationId:{type:"string",description:"Conversation ID to reply in."},type:{type:"string",enum:["outbound","note"],description:"Message type: outbound emails the subscriber, note is internal-only. Defaults to outbound."},subject:{type:"string",description:"Optional subject override. Defaults to the conversation subject."},bodyText:{type:"string",description:"Plain-text message body."},bodyHtml:{type:"string",description:"HTML message body."}},required:["conversationId"]}},{name:"update_conversation_status",description:"Open or close a conversation.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},conversationId:{type:"string",description:"Conversation ID."},status:{type:"string",enum:["open","closed"],description:"New conversation status."}},required:["conversationId","status"]}},{name:"mark_conversation_read",description:"Mark all unread inbound messages in a conversation as read.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},conversationId:{type:"string",description:"Conversation ID."}},required:["conversationId"]}}];var eH=[{name:"list_landing_pages",description:"List all landing pages for a company",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list landing pages for. If not provided, uses the currently selected company."}},additionalProperties:!1}},{name:"get_landing_page",description:"Get landing page details, content, metrics, and URLs",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID."}},required:["landingPageId"],additionalProperties:!1}},{name:"create_landing_page",description:"Create a draft landing page. Provide content for an exact page, or a template for generated starter content.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the landing page in. If not provided, uses the currently selected company."},name:{type:"string",description:"Landing page name. Optional; defaults to a template-specific name."},slug:{type:"string",description:"Optional URL slug. It will be normalized and made unique within the company."},template:{type:"string",description:DH},content:{type:"object",description:X0,additionalProperties:!0}},additionalProperties:!1}},{name:"update_landing_page",description:"Edit a landing page's name, slug, or full content. Provide at least one update field.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID."},name:{type:"string",description:"Landing page name."},slug:{type:"string",description:"Landing page URL slug. It will be normalized and made unique within the company."},content:{type:"object",description:X0,additionalProperties:!0}},required:["landingPageId"],additionalProperties:!1}},{name:"delete_landing_page",description:"Delete a landing page",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID."}},required:["landingPageId"],additionalProperties:!1}},{name:"publish_landing_page",description:"Publish a landing page. Optional name, slug, or content updates are saved before publishing.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID."},name:{type:"string",description:"Optional landing page name update."},slug:{type:"string",description:"Optional slug update before publishing."},content:{type:"object",description:X0,additionalProperties:!0}},required:["landingPageId"],additionalProperties:!1}},{name:"unpublish_landing_page",description:"Unpublish a landing page and return it to draft status. Optional name, slug, or content updates are saved first.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID."},name:{type:"string",description:"Optional landing page name update."},slug:{type:"string",description:"Optional slug update before unpublishing."},content:{type:"object",description:X0,additionalProperties:!0}},required:["landingPageId"],additionalProperties:!1}},{name:"connect_landing_page_domain",description:"Connect a custom domain for published landing pages. Returns the DNS target and verification records.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},domain:{type:"string",description:"Custom domain, for example pages.example.com."}},required:["domain"],additionalProperties:!1}},{name:"update_landing_page_domain_settings",description:"Update landing page domain settings. Provide domain to replace the custom domain, verify true to refresh verification, or both.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},domain:{type:"string",description:"Replacement custom domain."},verify:{type:"boolean",description:"Refresh domain verification after any domain update."}},additionalProperties:!1}}];var sH=[{name:"list_products",description:"List synced products (Stripe, Shopify, WooCommerce) including any attached digital delivery file. Useful before attaching a file or building a purchase sequence for a specific product.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list products for. If not provided, uses the currently selected company."},provider:{type:"string",description:"Filter by provider: stripe, shopify, woocommerce, or manual."},search:{type:"string",description:"Filter products by title."}}}},{name:"upsert_products",description:"Create or update products in the catalog (Commerce API, keyed by your productId, stored under the api provider). Use this to add products that are not synced from Stripe/Shopify/WooCommerce, then attach a deliverable file with attach_product_file and build a purchase sequence for them.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},products:{type:"array",description:"Products to create or update (max 100).",items:{type:"object",properties:{productId:{type:"string",description:"Your stable product identifier (used for upserts and order line items)."},title:{type:"string",description:"Product title."},description:{type:"string",description:"Product description."},imageUrl:{type:"string",description:"Product image URL."},url:{type:"string",description:"Product page URL."},priceCents:{type:"number",description:"Price in the smallest currency unit."},currency:{type:"string",description:"ISO currency code, e.g. USD."},inStock:{type:"boolean",description:"Whether the product is in stock."}},required:["productId","title"]}}},required:["products"]}},{name:"delete_product",description:"Delete a product previously pushed via upsert_products (Commerce API products only), identified by your productId.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},productId:{type:"string",description:"Your productId used when upserting the product."}},required:["productId"]}},{name:"attach_product_file",description:"Attach a distributable file to a product, either by public URL or by uploading a local file (filePath, local MCP server only). After a purchase of the product, sequence emails can link to it with {{event.download.url}} and {{event.download.name}}.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},productId:{type:"string",description:"Product ID from list_products, or your own productId for products pushed via upsert_products."},url:{type:"string",description:"Public http(s) URL of the file to deliver. Provide url or filePath, not both."},filePath:{type:"string",description:"Local path of a file to upload and attach (PDF, ePub, ZIP, image, audio, video, or text, up to 100MB). Only available when the MCP server runs locally on this machine."},fileName:{type:"string",description:"Display name for the file (e.g. guide.pdf). Used as {{event.download.name}}."}},required:["productId"]}},{name:"remove_product_file",description:"Remove the attached distributable file from a product.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},productId:{type:"string",description:"Product ID from list_products, or your own productId for products pushed via upsert_products."}},required:["productId"]}},{name:"sync_products",description:"Queue a sync of the Stripe product catalog into the products list. Requires an active Stripe integration.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}}];var aH=[{name:"list_sequences",description:"List all email sequences (automations)",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list sequences for. If not provided, uses the currently selected company."}}}},{name:"get_sequence",description:"Get sequence details, editable step content, and graph topology. Each sequence.nodes item includes id, nodeType, current config, updatedAt, and updateHints with its editable/managed fields and ready-to-return expectedUpdatedAt token for update_sequence_node/update_sequence_nodes. The response also includes sequence.edges and graphRevision for safe edit_sequence_graph calls, plus sequence.emails with each email step's nodeId, linked emailId, subject, previewText, and blocks.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"],additionalProperties:!1}},{name:"create_sequence",description:`Create a new email sequence. For net-new natural-language sequence content, provide goal and emailCount so Sequenzy generates it. Use explicit steps only for finished caller-supplied content, exact workflows, or migrations. Explicit steps can include email content, native SMS steps (type: 'sms' with 'text'; check get_sms_settings first and generate copy with generate_sms), and create_discount actions that dynamically create a provider discount/code when each subscriber reaches the step; emails after a discount action can use merge tags such as {{discount.code}} and {{discount.percentOff}}. For AI-generated sequences, the tool polls until emails are generated (typically 30-60 seconds).
|
|
52
52
|
|
|
53
53
|
MIGRATIONS: When moving sequences or flows from Brevo, Mailchimp, Klaviyo, MailerLite, or another provider, pass the exact provider HTML in each email step's html field and pass fixed waits as delay or delayMs. Use waitUntil when a wait should resolve from the trigger event payload, for example { "field": "renews_at", "direction": "before", "offset": { "days": 1 } }. The API stores provider HTML as raw HTML blocks and creates real logic_delay nodes for waits.
|
|
54
54
|
|
|
@@ -187,7 +187,7 @@ BUILT-IN EVENTS (auto-fired by payment integrations):
|
|
|
187
187
|
|
|
188
188
|
OTHER BUILT-IN EVENTS:
|
|
189
189
|
- email.opened, email.clicked, email.replied, email.bounced, email.unsubscribed
|
|
190
|
-
- contact.subscribed, contact.unsubscribed`,inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the sequence in. If not provided, uses the currently selected company."},fromEmail:{type:"string",description:"From address for all emails in this sequence. Its domain must be configured and verified."},fromName:{type:"string",description:"Display name for a newly created sender profile. Requires fromEmail."},senderProfileId:{type:"string",description:"Existing sender profile ID. Mutually exclusive with fromEmail."},replyTo:{type:"string",description:"Reply-To address for all emails in this sequence. A reply profile is created when needed."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo."},replyProfileId:{type:"string",description:"Existing reply profile ID. Mutually exclusive with replyTo."},name:{type:"string",description:"Sequence name (e.g., 'User Onboarding', 'Welcome Series')"},trigger:{type:"string",enum:["contact_added","tag_added","segment_entered","event_received","inactivity","frequency"],description:"Trigger type: 'contact_added' (when added to a list), 'tag_added' (when tag is applied), 'segment_entered' (when a contact newly enters a saved segment), 'event_received' (when custom event fires), 'inactivity' (when subscriber hasn't performed an event for X days), 'frequency' (when subscriber performs event X times in Y days)"},listId:{type:"string",description:"List ID to trigger on (for contact_added trigger). If not provided, triggers on any list."},tagName:{type:"string",description:"Tag name to trigger on (required for tag_added trigger)"},segmentId:{type:"string",description:"Segment ID to trigger on (required for segment_entered trigger). Use list_segments first to choose a saved segment."},eventName:{type:"string",description:"Event name to trigger on (required for event_received, inactivity, and frequency triggers)"},propertyFilters:{type:"array",description:"Optional event property filters for event_received triggers. The sequence only starts when the triggering event's properties match ALL filters. Use a dot-path into the event properties; use [] to match inside arrays. Examples: scope a purchase sequence to one product with { path: 'lineItems[].providerProductId', operator: 'equals', value: 'prod_123' } (ecommerce.order_placed) or { path: 'productIds', operator: 'equals', value: 'prod_123' } (saas.purchase); to match any of several products use { path: 'lineItems[].providerProductId', operator: 'one_of', value: ['prod_123', 'prod_456'] }. Max 10 filters.",items:{type:"object",properties:{path:{type:"string",description:"Dot-path into the event properties, e.g. 'lineItems[].providerProductId' or 'plan'."},operator:{type:"string",enum:["exists","not_exists","equals","not_equals","one_of","contains","greater_than","less_than"],description:"Comparison operator. one_of matches when the property equals any entry of the value array."},value:{type:["string","number","boolean","array"],items:{type:["string","number"]},maxItems:50,description:"Value to compare against. Required for every operator except exists/not_exists. For one_of, pass an array of strings or numbers (max 50 values); all other operators take a single value."}},required:["path","operator"]}},inactiveDays:{type:"number",description:"Number of days of inactivity (required for inactivity trigger, must be >= 1)"},inactivityBaseline:{type:"string",enum:["sequence_created_at","subscriber_created_at"],description:"When to start counting inactivity for subscribers who never had the event. Defaults to sequence_created_at."},minCount:{type:"number",description:"Minimum event count (required for frequency trigger, must be >= 1)"},timeWindowDays:{type:"number",description:"Time window in days for frequency trigger (required for frequency trigger, must be >= 1)"},emailCount:{type:"number",description:"Number of emails in the sequence (default: 5, max: 10)"},durationDays:{type:"number",description:"Total duration in days used to space AI-generated sequence emails. Only applies when using goal-based AI generation."},goal:{type:"string",description:"What this sequence should accomplish for AI generation. Be specific to the app's actual features and user journey. Avoid generic goals that don't match the app's business model."},enrollmentMode:{type:"string",enum:["unlimited","one_time","matching_field"],description:"Sequence re-entry mode. Use 'matching_field' only for event_received triggers when duplicate active runs should be blocked per event field value."},enrollmentFieldPath:{type:"string",description:"Scalar dot-path event property used by enrollmentMode='matching_field', such as 'order.id' or 'product.providerVariantId'. Array traversal with [] is not supported; use propertyFilters for array matching. Leave omitted for Shopify back-in-stock/replenishment product-variant defaults."},sendingWindow:QH,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:GX,subject:{type:"string",description:"Email subject. Required for email steps."},previewText:{type:"string",description:"Email preview text."},blocks:{type:"array",description:sY,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:QX,delayMs:{type:"number",description:"Delay before this step in milliseconds. Prefer delay for readability; use delayMs when importing provider waits."},waitUntil:eY,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:"Scalar dot-path event property used by enrollmentMode='matching_field', such as 'order.id' or 'product.providerVariantId'. Array traversal with [] is not supported; use propertyFilters for array matching. Omit to leave unchanged. Use clearEnrollmentFieldPath to clear it."},clearEnrollmentFieldPath:{type:"boolean",description:"Set true to clear enrollmentFieldPath without sending a nullable schema value."},sendingWindow:QH,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:oY}},required:["conditionType"]}},elseSteps:{type:"array",description:"Steps to create inside the else fallback path. Required by default so the else arm is usable.",items:oY},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:oY}},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"}},...zH}}},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"}},...zH}}},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:GX},required:["nodeId","config"]}}},required:["sequenceId"]}},{name:"update_sequence_node",description:"Patch one existing sequence node in place. Call get_sequence first, select sequence.nodes[].id, inspect nodeType/config, and pass that node's updatedAt as expectedUpdatedAt. This supports every stored sequence node type, including delays, email/SMS content, actions, conditions, branches without topology changes, webhooks, and trigger settings. Delay example: changes:{ delay:{ days:7 } }. The update is type-aware and preserves fields you omit. It cannot change nodeType, managed linked-resource IDs, or graph topology; use edit_sequence_graph for structural work. On an active sequence, set confirmLiveChange:true only after the user confirms the live behavior change. Existing recipients already waiting keep their scheduled timestamp; the new delay applies when recipients reach the node in the future.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID."},nodeId:pY.properties.nodeId,changes:BH,expectedUpdatedAt:pY.properties.expectedUpdatedAt,confirmLiveChange:{type:"boolean",description:"Set true only after the user explicitly confirms changing a node in an active sequence."}},required:["sequenceId","nodeId","changes","expectedUpdatedAt"],additionalProperties:!1}},{name:"update_sequence_nodes",description:"Atomically patch multiple existing sequence nodes. Call get_sequence first and include each node's id plus its updatedAt as expectedUpdatedAt. Every patch follows update_sequence_node's type-aware rules. Either every node update commits or none do, making this the preferred tool for changes such as replacing all 5-minute delays with 7-day delays. A node may appear only once. It cannot change node types or graph topology. On an active sequence, set confirmLiveChange:true only after the user confirms the live behavior change. Existing recipients already waiting keep their scheduled timestamps.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID."},updates:{type:"array",description:"Non-empty node patches. Each nodeId may appear only once.",items:pY},confirmLiveChange:{type:"boolean",description:"Set true only after the user explicitly confirms changing nodes in an active sequence."}},required:["sequenceId","updates"],additionalProperties:!1}},{name:"edit_sequence_graph",description:"Restructure an existing sequence graph using node IDs, edges, and graphRevision from get_sequence. move_node repositions one non-split step; beforeNodeId can place an A/B test or other step at the shared continuation below a branch. duplicate_node creates an independent copy and deep-copies linked email or A/B test content. delete_node safely splices a linear step; deleting a split node requires the complete replacement edges. replace_edges atomically replaces the complete topology for advanced reconnect or multi-node reorder work. Always call get_sequence immediately before this tool and pass its graphRevision. Active sequences require confirmStructuralChange:true after the user confirms live-flow impact.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID."},action:{type:"string",enum:["move_node","delete_node","duplicate_node","replace_edges"],description:"Graph operation. Use move_node for a single step reorder, duplicate_node for an independent copy, delete_node to remove a step/node, or replace_edges for an atomic reconnect/reorder of the whole topology."},graphRevision:{type:"string",description:"Exact graphRevision returned by the latest get_sequence call. The edit is rejected if the graph changed since then."},nodeId:{type:"string",description:"Existing node to move, duplicate, or delete. Required for those actions and unused by replace_edges."},afterNodeId:{type:"string",description:"For move_node or duplicate_node, insert immediately after this node. The target must have at most one outgoing path. Provide exactly one of afterNodeId or beforeNodeId."},beforeNodeId:{type:"string",description:"For move_node or duplicate_node, insert immediately before this node. All incoming paths converge through the moved/copied node, which is useful for placing a step below a branch. Provide exactly one of beforeNodeId or afterNodeId."},edges:{type:"array",description:"Complete replacement topology from get_sequence.sequence.edges. The returned edge array is already normalized for this input and can be reused directly. Required for replace_edges and when deleting a split node. Preserve each branch edge's condition.branchId. Do not include edges that reference a deleted node.",items:{type:"object",properties:{sourceNodeId:{type:"string"},targetNodeId:{type:"string"},condition:{type:"object",description:"Optional edge routing condition. Preserve condition.branchId on edges leaving logic_branch nodes."}},required:["sourceNodeId","targetNodeId"],additionalProperties:!1}},confirmStructuralChange:{type:"boolean",description:"Set true only after the user explicitly confirms a structural edit to an active sequence."}},required:["sequenceId","action","graphRevision"],additionalProperties:!1}},{name:"insert_sequence_step",description:"Insert one new email or SMS step into an existing sequence. Prefer this over update_sequence.steps/emails when adding a step: it creates the step node (plus an email template for email steps) and, when delay or delayMs is provided, a logic_delay node immediately before it. For SMS steps set type:'sms' and provide 'text' (generate copy with generate_sms; check get_sms_settings first and warn the user if SMS is not enabled). Use get_sequence first, then pass afterNodeId from sequence.nodes or sequence.emails to choose the insertion point. If afterNodeId is omitted, the step is appended only when the sequence has exactly one linear tail. For active sequences, set confirmStructuralChange:true only after the user confirms the live-flow impact.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID."},type:{type:"string",enum:["email","sms"],description:"Step type. Defaults to 'email'. Use 'sms' to insert an SMS step (requires 'text')."},afterNodeId:{type:"string",description:"Existing node ID to insert after. Use a nodeId from get_sequence.sequence.nodes or get_sequence.sequence.emails. Omit only to append to an unambiguous linear tail."},confirmStructuralChange:{type:"boolean",description:"Set true only after the user explicitly confirms a structural edit to an active sequence."},name:{type:"string",description:"Optional email template and step name."},subject:{type:"string",description:"Email subject for the new step. Required for email steps; not used for SMS steps."},previewText:{type:"string",description:"Optional email preview text for the new step."},blocks:{type:"array",description:sY,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:QX,delayMs:{type:"number",description:"Optional wait in milliseconds before the new step. Prefer delay for readability."},waitUntil:eY},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"]}}],VH=bZ.map(wZ).map(jV);async function ZH(Q,Y){try{let X;switch(Q){case"get_account":{let W=await B("GET","/api/v1/account"),$=b1();X={...W,selectedCompanyId:$??W.currentCompanyId};break}case"select_company":{let W=Y.companyId,$=await B("GET","/api/v1/account"),z=$.companies?.find((J)=>J.id===W);if(!z)throw Error(`Company not found. Available companies: ${$.companies?.map((J)=>`${J.name} (${J.id})`).join(", ")??"none"}`);Q6(W),X={success:!0,message:`Switched to company: ${z.name}`,companyId:z.id,companyName:z.name};break}case"get_app_urls":{let W=await UX(Y);X={...Z1({companyId:W,campaignId:N(Y,"campaignId"),landingPageId:N(Y,"landingPageId"),sequenceId:N(Y,"sequenceId"),emailId:N(Y,"emailId")??N(Y,"templateId"),transactionalId:N(Y,"transactionalId"),emailSendId:N(Y,"emailSendId"),domainId:N(Y,"domainId"),status:N(Y,"status"),settingsTab:N(Y,"settingsTab")}),...W===void 0&&{note:"No company ID is selected. Call get_account, select_company, or pass companyId to get concrete dashboard URLs."}};break}case"create_company":{let W=await B("POST","/api/v1/companies",{name:Y.name,domain:Y.domain});if(!W.success)throw Error("Failed to create company");let $=W.company.id,z=6,J=0,H=W.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 W=Y.companyId;X=await B("GET",`/api/v1/companies/${W}`);break}case"update_company":{let W=await KZ("update_company",Y),$=fV(Y);X=await B("PATCH",`/api/v1/companies/${W}`,$);break}case"get_sync_rules":{let W=Y.companyId;X=await B("GET","/api/v1/sync-rules",void 0,W);break}case"update_sync_rules":{let W=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},W);break}case"get_shopify_automation_settings":{let W=Y.companyId;X=await B("GET","/api/v1/shopify/automation-settings",void 0,W);break}case"update_shopify_automation_settings":{let W=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",$,W);break}case"create_api_key":{let W=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",$,W);break}case"list_websites":{let W=Y.companyId;X=await B("GET","/api/v1/websites",void 0,W);break}case"add_sending_domain":case"add_website":{let W=Y.companyId;X=await B("POST","/api/v1/websites",{domain:Y.domain},W);break}case"check_website":{let W=Y.companyId;X=await B("GET",`/api/v1/websites/${encodeURIComponent(String(Y.domain))}`,void 0,W);break}case"verify_sending_domain":{let W=Y.companyId;X=await B("POST",`/api/v1/websites/${encodeURIComponent(String(Y.domain))}/verify`,void 0,W);break}case"get_integration_guide":X=await B("POST","/api/v1/integration-guide",Y);break;case"add_subscriber":{let W=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}},W);break}case"update_subscriber":{let W=Y.companyId,$=v1("update_subscriber",Y),z=await tY($,W),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(JH):[],A=new Set(Array.isArray(Y.removeTags)?Y.removeTags.filter((D)=>typeof D==="string"&&D.trim()!=="").map(JH):[]),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(n(Y.attributes))K.customAttributes={...n(z.subscriber.customAttributes)?z.subscriber.customAttributes:{},...Y.attributes};if(Y.addTags||Y.removeTags)K.tags=U;X=await B("PATCH",$X($),K,W);break}case"remove_subscriber":{let W=Y.companyId,$=v1("remove_subscriber",Y),z=$X($);if(Y.hardDelete===!0)X=await B("DELETE",z,void 0,W);else X=await B("PATCH",z,{status:"unsubscribed"},W);break}case"get_subscriber":{let W=Y.companyId,$=v1("get_subscriber",Y);X=await tY($,W,{includeMachineEngagement:Y.includeMachineEngagement===!0});break}case"list_subscriber_notes":{let W=Y.companyId,$=v1("list_subscriber_notes",Y);X=await B("GET",HH($),void 0,W);break}case"add_subscriber_note":{let W=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",HH($),{body:z},W);break}case"delete_subscriber_note":{let W=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,W);break}case"search_subscribers":{let W=Y.companyId;X=await WZ(Y,W);break}case"list_products":{let W=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,W);break}case"upsert_products":{let W=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},W);break}case"delete_product":{let W=Y.companyId,$=E("delete_product",Y,"productId");X=await B("DELETE",`/api/v1/products/${encodeURIComponent($)}`,void 0,W);break}case"attach_product_file":{let W=Y.companyId,$=E("attach_product_file",Y,"productId"),z=N(Y,"url"),J=N(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 UZ(J,W);H={url:A.url,source:"upload",fileName:N(Y,"fileName")??A.fileName,fileSizeBytes:A.fileSizeBytes,mimeType:A.mimeType}}else{H={url:z};let A=N(Y,"fileName");if(A)H.fileName=A}X=await B("PUT",`/api/v1/products/${encodeURIComponent($)}/delivery`,H,W);break}case"remove_product_file":{let W=Y.companyId,$=E("remove_product_file",Y,"productId");X=await B("DELETE",`/api/v1/products/${encodeURIComponent($)}/delivery`,void 0,W);break}case"sync_products":{let W=Y.companyId;X=await B("POST","/api/v1/products/sync",void 0,W);break}case"list_tags":{let W=Y.companyId;X=await B("GET","/api/v1/tags",void 0,W);break}case"create_tag":{let W=Y.companyId,$=E("create_tag",Y,"name"),z=m0("create_tag",Y,"color",wQ);X=await B("POST","/api/v1/tags",{name:$,...z!==void 0&&{color:z}},W);break}case"update_tag":{let W=Y.companyId,$=E("update_tag",Y,"tagId"),z=aY("update_tag",Y,"color",wQ);X=await B("PATCH",`/api/v1/tags/${encodeURIComponent($)}`,{color:z},W);break}case"delete_tag":{let W=Y.companyId,$=E("delete_tag",Y,"tagId");X=await B("DELETE",`/api/v1/tags/${encodeURIComponent($)}`,void 0,W);break}case"list_lists":{let W=Y.companyId;X=await B("GET","/api/v1/lists",void 0,W);break}case"create_list":{let W=Y.companyId;X=await B("POST","/api/v1/lists",Y,W);break}case"update_list":{let W=Y.companyId,$=E("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&&N(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:N(Y,"name")},...Y.description!==void 0&&{description:Y.description},...Y.isPrivate!==void 0&&{isPrivate:Y.isPrivate}},W);break}case"delete_list":{let W=Y.companyId,$=E("delete_list",Y,"listId");X=await B("DELETE",`/api/v1/lists/${encodeURIComponent($)}`,void 0,W);break}case"add_subscribers_to_list":{let W=Y.companyId,$=E("add_subscribers_to_list",Y,"listId"),z=KH("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},W);break}case"remove_subscribers_from_list":{let W=Y.companyId,$=E("remove_subscribers_from_list",Y,"listId"),z=KH("remove_subscribers_from_list",Y);X=await B("POST",`/api/v1/lists/${encodeURIComponent($)}/subscribers/remove`,{emails:z},W);break}case"list_segments":{let W=Y.companyId;X=await B("GET","/api/v1/segments",void 0,W);break}case"create_segment":{uV(Y);let W=Y.companyId;X=await B("POST","/api/v1/segments",{...Y,...Y.filters!==void 0?{filters:XX(Y.filters)}:{},...Y.root!==void 0?{root:WX(Y.root)}:{}},W);break}case"update_segment":{hV(Y);let W=Y.companyId,$=E("update_segment",Y,"segmentId"),z=N(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:XX(Y.filters)}:{},...Y.root!==void 0?{root:WX(Y.root)}:{}},W);break}case"delete_segment":{let W=Y.companyId,$=E("delete_segment",Y,"segmentId");X=await B("DELETE",`/api/v1/segments/${encodeURIComponent($)}`,void 0,W);break}case"get_segment_count":{let W=Y.companyId;X=await B("GET",`/api/v1/segments/${Y.segmentId}/count`,void 0,W);break}case"list_audience_syncs":{let W=Y.companyId;X=await B("GET","/api/v1/audience-syncs",void 0,W);break}case"list_ad_accounts":{let W=Y.companyId;X=await B("GET","/api/v1/ad-accounts",void 0,W);break}case"create_audience_sync":{let W=Y.companyId,$=N(Y,"segmentId"),z=N(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:E("create_audience_sync",Y,"adAccountId"),audienceName:E("create_audience_sync",Y,"audienceName"),...Y.frequency!==void 0?{frequency:Y.frequency}:{}},W);break}case"update_audience_sync":{let W=Y.companyId,$=E("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}:{}},W);break}case"delete_audience_sync":{let W=Y.companyId,$=E("delete_audience_sync",Y,"syncId");X=await B("DELETE",`/api/v1/audience-syncs/${encodeURIComponent($)}`,void 0,W);break}case"sync_audience_now":{let W=Y.companyId,$=E("sync_audience_now",Y,"syncId");X=await B("POST",`/api/v1/audience-syncs/${encodeURIComponent($)}/sync`,void 0,W);break}case"list_templates":{let W=Y.companyId,$=new URLSearchParams,z=N(Y,"label");if(z)$.set("label",z);X=await B("GET",`/api/v1/templates${$.size>0?`?${$}`:""}`,void 0,W);break}case"get_template":{let W=Y.companyId;X=await B("GET",`/api/v1/templates/${Y.templateId}`,void 0,W);break}case"create_template":{let W=Y.companyId;aV(Y);let $=Object.fromEntries(Object.entries(Y).filter(([z])=>z!=="companyId"));X=await B("POST","/api/v1/templates",$,W);break}case"update_template":{let W=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,W);break}case"delete_template":{let W=Y.companyId;X=await B("DELETE",`/api/v1/templates/${Y.templateId}`,void 0,W);break}case"list_ab_tests":{let W=Y.companyId,$=new URLSearchParams,z=N(Y,"sequenceId");if(z)$.set("sequenceId",z);X=await B("GET",`/api/v1/ab-tests${$.size>0?`?${$}`:""}`,void 0,W);break}case"get_ab_test":{let W=Y.companyId;X=await B("GET",`/api/v1/ab-tests/${Y.abTestId}`,void 0,W);break}case"get_ab_test_stats":{let W=Y.companyId,$=new URLSearchParams,z=N(Y,"period"),J=N(Y,"start"),H=N(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,W);break}case"restart_ab_test":{let W=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=N(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:N(Y,"sourceVariantId"),testType:J,winnerThreshold:H,variantCount:A},W);break}case"update_ab_test_variant":{let W=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,W);break}case"create_ab_test":{let W=Y.companyId,$=E("create_ab_test",Y,"campaignId"),z=N(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(!n(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}},W);break}case"add_ab_test_variant":{let W=Y.companyId,$=E("add_ab_test_variant",Y,"abTestId"),z=E("add_ab_test_variant",Y,"subject"),J=N(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}},W);break}case"delete_ab_test_variant":{let W=Y.companyId,$=E("delete_ab_test_variant",Y,"abTestId"),z=E("delete_ab_test_variant",Y,"variantId");X=await B("DELETE",`/api/v1/ab-tests/${encodeURIComponent($)}/variants/${encodeURIComponent(z)}`,void 0,W);break}case"delete_ab_test":{let W=Y.companyId,$=E("delete_ab_test",Y,"abTestId");X=await B("DELETE",`/api/v1/ab-tests/${encodeURIComponent($)}`,void 0,W);break}case"list_campaigns":{let W=Y.companyId,$=new URLSearchParams;if(Y.status)$.set("status",String(Y.status));let z=N(Y,"label");if(z)$.set("label",z);X=await B("GET",`/api/v1/campaigns?${$}`,void 0,W);break}case"get_campaign":{let W=Y.companyId;X=await B("GET",`/api/v1/campaigns/${Y.campaignId}`,void 0,W);break}case"get_email_send":{let W=Y.companyId;X=await B("GET",`/api/v1/email-sends/${encodeURIComponent(String(Y.emailSendId))}`,void 0,W);break}case"create_campaign":{let W=Y.companyId;if(tV(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",$,W);break}case"update_campaign":{let W=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,W);break}case"schedule_campaign":{let W=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(", ")}.`);sV(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}},W);break}case"send_test_email":{let W=Y.companyId;X=await B("POST",`/api/v1/campaigns/${Y.campaignId}/test`,{to:Y.to},W);break}case"cancel_campaign":{let W=Y.companyId,$=E("cancel_campaign",Y,"campaignId");X=await B("POST",`/api/v1/campaigns/${encodeURIComponent($)}/cancel`,void 0,W);break}case"pause_campaign":{let W=Y.companyId,$=E("pause_campaign",Y,"campaignId");X=await B("POST",`/api/v1/campaigns/${encodeURIComponent($)}/pause`,void 0,W);break}case"resume_campaign":{let W=Y.companyId,$=E("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}},W);break}case"delete_campaign":{let W=Y.companyId,$=E("delete_campaign",Y,"campaignId");X=await B("DELETE",`/api/v1/campaigns/${encodeURIComponent($)}`,void 0,W);break}case"duplicate_campaign":{let W=Y.companyId,$=E("duplicate_campaign",Y,"campaignId"),z=m0("duplicate_campaign",Y,"mode",["campaign","ab_test","variant"]),J=N(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}},W);break}case"resend_campaign_to_non_openers":{let W=Y.companyId,$=E("resend_campaign_to_non_openers",Y,"campaignId");X=await B("POST",`/api/v1/campaigns/${encodeURIComponent($)}/resend-to-non-openers`,void 0,W);break}case"list_landing_pages":{let W=Y.companyId;X=await B("GET","/api/v1/landing-pages",void 0,W);break}case"get_landing_page":{let W=Y.companyId;X=await B("GET",`/api/v1/landing-pages/${Y.landingPageId}`,void 0,W);break}case"create_landing_page":{let W=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}},W);break}case"update_landing_page":{let W=Y.companyId,$=dY("update_landing_page",Y,{requireUpdate:!0});X=await B("PUT",`/api/v1/landing-pages/${Y.landingPageId}`,$,W);break}case"publish_landing_page":{let W=Y.companyId,$=dY("publish_landing_page",Y,{requireUpdate:!1});X=await B("POST",`/api/v1/landing-pages/${Y.landingPageId}/publish`,$,W);break}case"unpublish_landing_page":{let W=Y.companyId,$=dY("unpublish_landing_page",Y,{requireUpdate:!1});X=await B("POST",`/api/v1/landing-pages/${Y.landingPageId}/unpublish`,$,W);break}case"delete_landing_page":{let W=Y.companyId;X=await B("DELETE",`/api/v1/landing-pages/${Y.landingPageId}`,void 0,W);break}case"connect_landing_page_domain":{let W=Y.companyId;X=await B("POST","/api/v1/landing-pages/domain",{domain:Y.domain},W);break}case"update_landing_page_domain_settings":{let W=Y.companyId,$=eV(Y);X=await B("PUT","/api/v1/landing-pages/domain",$,W);break}case"list_sequences":{let W=Y.companyId;X=await B("GET","/api/v1/sequences",void 0,W);break}case"get_sequence":{let W=Y.companyId;X=await B("GET",`/api/v1/sequences/${Y.sequenceId}`,void 0,W);break}case"create_sequence":{let W=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,W);if(!z.success){X=z;break}let J=z.sequence.id;if($){let D=await B("GET",`/api/v1/sequences/${J}`,void 0,W);if(D.success)X={...z,success:!0,sequence:D.sequence,message:`Sequence "${D.sequence.name}" created with explicit steps. Review it before enabling.${z.eventTrackingCode?" Add the custom event feed using eventTrackingCode and eventTracking 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,W);if(D.success)U=D.sequence.enrichmentStatus}let K=await B("GET",`/api/v1/sequences/${J}`,void 0,W);if(K.success)X={...z,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.${z.eventTrackingCode?" Add the custom event feed using eventTrackingCode and eventTracking before enabling.":""}`:`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.${z.eventTrackingCode?" Add the custom event feed using eventTrackingCode and eventTracking before enabling.":""}`};else X=K;break}case"update_sequence":{let W=Y.companyId,$=pV(Y);X=await B("PUT",`/api/v1/sequences/${Y.sequenceId}`,$,W);break}case"update_sequence_node":{let W=Y.companyId,$=E("update_sequence_node",Y,"sequenceId"),z=iV(Y);X=await B("PUT",`/api/v1/sequences/${$}`,z,W);break}case"update_sequence_nodes":{let W=Y.companyId,$=E("update_sequence_nodes",Y,"sequenceId"),z=nV(Y);X=await B("PUT",`/api/v1/sequences/${$}`,z,W);break}case"edit_sequence_graph":{let W=Y.companyId,$=rV(Y);X=await B("PUT",`/api/v1/sequences/${Y.sequenceId}`,$,W);break}case"insert_sequence_step":{let W=Y.companyId,$=dV(Y);X=await B("PUT",`/api/v1/sequences/${Y.sequenceId}`,$,W);break}case"enable_sequence":{let W=Y.companyId;X=await B("POST",`/api/v1/sequences/${Y.sequenceId}/enable`,void 0,W);break}case"disable_sequence":{let W=Y.companyId;X=await B("POST",`/api/v1/sequences/${Y.sequenceId}/disable`,void 0,W);break}case"pause_sequence_enrollments":{let W=Y.companyId;X=await B("POST",`/api/v1/sequences/${Y.sequenceId}/pause-enrollments`,void 0,W);break}case"resume_sequence_enrollments":{let W=Y.companyId;X=await B("POST",`/api/v1/sequences/${Y.sequenceId}/resume-enrollments`,void 0,W);break}case"enroll_subscribers_in_sequence":{let W=Y.companyId,$=E("enroll_subscribers_in_sequence",Y,"sequenceId"),z=zZ(Y);X=await B("POST",`/api/v1/sequences/${encodeURIComponent($)}/enroll`,z,W);break}case"cancel_sequence_enrollments":{let W=Y.companyId,$=oV(Y);X=await B("POST",`/api/v1/sequences/${Y.sequenceId}/enrollments/cancel`,$,W);break}case"delete_sequence":{let W=Y.companyId;X=await B("DELETE",`/api/v1/sequences/${Y.sequenceId}`,void 0,W);break}case"list_transactional_emails":{let W=Y.companyId;X=await B("GET","/api/v1/transactional",void 0,W);break}case"get_transactional_email":{let W=Y.companyId;X=await B("GET",`/api/v1/transactional/${Y.idOrSlug}`,void 0,W);break}case"create_transactional_email":{let W=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(", ")}.`);QZ(Y);let J=Object.fromEntries(Object.entries(Y).filter(([H])=>H!=="companyId"));X=await B("POST","/api/v1/transactional",J,W);break}case"update_transactional_email":{let W=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,W);break}case"send_email":{let W=Y.companyId;X=await B("POST","/api/v1/transactional/send",Y,W);break}case"get_stats":{let W=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,W);break}case"get_campaign_stats":{let W=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,W);break}case"get_sequence_stats":{let W=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,W);break}case"list_campaign_events":{let W=Y.companyId,$=E("list_campaign_events",Y,"campaignId"),J=AH("list_campaign_events",Y).toString();X=await B("GET",`/api/v1/metrics/campaigns/${encodeURIComponent($)}/events${J?`?${J}`:""}`,void 0,W);break}case"list_sequence_events":{let W=Y.companyId,$=E("list_sequence_events",Y,"sequenceId"),J=AH("list_sequence_events",Y).toString();X=await B("GET",`/api/v1/metrics/sequences/${encodeURIComponent($)}/events${J?`?${J}`:""}`,void 0,W);break}case"get_subscriber_activity":{let W=Y.companyId,$=v1("get_subscriber_activity",Y),z=await tY($,W,{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 W=Y.companyId;X=await B("GET","/api/v1/team",void 0,W);break}case"invite_team_member":{let W=Y.companyId,$=E("invite_team_member",Y,"email"),z=aY("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}},W);break}case"cancel_team_invitation":{let W=Y.companyId,$=E("cancel_team_invitation",Y,"invitationId");X=await B("DELETE",`/api/v1/team/invitations/${encodeURIComponent($)}`,void 0,W);break}case"list_conversations":{let W=Y.companyId,$=new URLSearchParams,z=m0("list_conversations",Y,"status",["open","closed","all"]);if(z)$.set("status",z);let J=N(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,W);break}case"get_conversation":{let W=Y.companyId,$=E("get_conversation",Y,"conversationId");X=await B("GET",`/api/v1/conversations/${encodeURIComponent($)}`,void 0,W);break}case"reply_to_conversation":{let W=Y.companyId,$=E("reply_to_conversation",Y,"conversationId"),z=m0("reply_to_conversation",Y,"type",["outbound","note"])??"outbound",J=N(Y,"subject"),H=N(Y,"bodyText"),A=N(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}},W);break}case"update_conversation_status":{let W=Y.companyId,$=E("update_conversation_status",Y,"conversationId"),z=aY("update_conversation_status",Y,"status",["open","closed"]);X=await B("POST",`/api/v1/conversations/${encodeURIComponent($)}/status`,{status:z},W);break}case"mark_conversation_read":{let W=Y.companyId,$=E("mark_conversation_read",Y,"conversationId");X=await B("POST",`/api/v1/conversations/${encodeURIComponent($)}/read`,void 0,W);break}case"list_webhooks":{let W=Y.companyId;X=await B("GET","/api/v1/webhooks",void 0,W);break}case"create_webhook":{let W=Y.companyId,$=E("create_webhook",Y,"name"),z=E("create_webhook",Y,"url"),J=UH("create_webhook",Y);X=await B("POST","/api/v1/webhooks",{name:$,url:z,...J!==void 0&&{events:J}},W);break}case"update_webhook":{let W=Y.companyId,$=E("update_webhook",Y,"webhookId"),z=N(Y,"name"),J=N(Y,"url"),H=UH("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}},W);break}case"delete_webhook":{let W=Y.companyId,$=E("delete_webhook",Y,"webhookId");X=await B("DELETE",`/api/v1/webhooks/${encodeURIComponent($)}`,void 0,W);break}case"test_webhook":{let W=Y.companyId,$=E("test_webhook",Y,"webhookId");X=await B("POST",`/api/v1/webhooks/${encodeURIComponent($)}/test`,void 0,W);break}case"list_webhook_deliveries":{let W=Y.companyId,$=E("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,W);break}case"replay_webhook_delivery":{let W=Y.companyId,$=E("replay_webhook_delivery",Y,"webhookId"),z=E("replay_webhook_delivery",Y,"deliveryId");X=await B("POST",`/api/v1/webhooks/${encodeURIComponent($)}/deliveries/${encodeURIComponent(z)}/replay`,void 0,W);break}case"generate_email":{let W=Y.companyId;X=await B("POST","/api/v1/generate/email",Y,W);break}case"generate_sequence":{let W=Y.companyId;X=await B("POST","/api/v1/generate/sequence",Y,W);break}case"generate_subject_lines":{let W=Y.companyId;X=await B("POST","/api/v1/generate/subjects",Y,W);break}case"generate_sms":{let W=Y.companyId;X=await B("POST","/api/v1/generate/sms",Y,W);break}case"get_sms_settings":{let W=Y.companyId;X=await B("GET","/api/v1/sms/settings",void 0,W);break}case"send_test_sms":{let W=Y.companyId,$={to:E("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",$,W);break}case"submit_feedback":{let W=Y.companyId,$={message:E("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",$,W);break}default:throw Error(`Unknown tool: ${Q}`)}let G=YZ(X);if(G)throw G;return X=await BZ(Q,Y,X),{structuredContent:PZ(X),content:[{type:"text",text:JSON.stringify(X,null,2)}]}}catch(X){return{isError:!0,content:[{type:"text",text:$1(X)}]}}}async function NH(Q,Y,X){let G=Y.getRequestContext?.(Q)??{};try{return await SQ(G,X)}finally{await Y.onRequestContextUpdated?.(G,Q)}}function KX(Q={}){let Y=new lY({name:"sequenzy",version:r5.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
|
|
192
|
-
`);if(
|
|
193
|
-
`}class
|
|
190
|
+
- contact.subscribed, contact.unsubscribed`,inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the sequence in. If not provided, uses the currently selected company."},fromEmail:{type:"string",description:"From address for all emails in this sequence. Its domain must be configured and verified."},fromName:{type:"string",description:"Display name for a newly created sender profile. Requires fromEmail."},senderProfileId:{type:"string",description:"Existing sender profile ID. Mutually exclusive with fromEmail."},replyTo:{type:"string",description:"Reply-To address for all emails in this sequence. A reply profile is created when needed."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo."},replyProfileId:{type:"string",description:"Existing reply profile ID. Mutually exclusive with replyTo."},name:{type:"string",description:"Sequence name (e.g., 'User Onboarding', 'Welcome Series')"},trigger:{type:"string",enum:["contact_added","tag_added","segment_entered","event_received","inactivity","frequency"],description:"Trigger type: 'contact_added' (when added to a list), 'tag_added' (when tag is applied), 'segment_entered' (when a contact newly enters a saved segment), 'event_received' (when custom event fires), 'inactivity' (when subscriber hasn't performed an event for X days), 'frequency' (when subscriber performs event X times in Y days)"},listId:{type:"string",description:"List ID to trigger on (for contact_added trigger). If not provided, triggers on any list."},tagName:{type:"string",description:"Tag name to trigger on (required for tag_added trigger)"},segmentId:{type:"string",description:"Segment ID to trigger on (required for segment_entered trigger). Use list_segments first to choose a saved segment."},eventName:{type:"string",description:"Event name to trigger on (required for event_received, inactivity, and frequency triggers)"},propertyFilters:{type:"array",description:"Optional event property filters for event_received triggers. The sequence only starts when the triggering event's properties match ALL filters. Use a dot-path into the event properties; use [] to match inside arrays. Examples: scope a purchase sequence to one product with { path: 'lineItems[].providerProductId', operator: 'equals', value: 'prod_123' } (ecommerce.order_placed) or { path: 'productIds', operator: 'equals', value: 'prod_123' } (saas.purchase); to match any of several products use { path: 'lineItems[].providerProductId', operator: 'one_of', value: ['prod_123', 'prod_456'] }. Max 10 filters.",items:{type:"object",properties:{path:{type:"string",description:"Dot-path into the event properties, e.g. 'lineItems[].providerProductId' or 'plan'."},operator:{type:"string",enum:["exists","not_exists","equals","not_equals","one_of","contains","greater_than","less_than"],description:"Comparison operator. one_of matches when the property equals any entry of the value array."},value:{type:["string","number","boolean","array"],items:{type:["string","number"]},maxItems:50,description:"Value to compare against. Required for every operator except exists/not_exists. For one_of, pass an array of strings or numbers (max 50 values); all other operators take a single value."}},required:["path","operator"]}},inactiveDays:{type:"number",description:"Number of days of inactivity (required for inactivity trigger, must be >= 1)"},inactivityBaseline:{type:"string",enum:["sequence_created_at","subscriber_created_at"],description:"When to start counting inactivity for subscribers who never had the event. Defaults to sequence_created_at."},minCount:{type:"number",description:"Minimum event count (required for frequency trigger, must be >= 1)"},timeWindowDays:{type:"number",description:"Time window in days for frequency trigger (required for frequency trigger, must be >= 1)"},emailCount:{type:"number",description:"Number of emails in the sequence (default: 5, max: 10)"},durationDays:{type:"number",description:"Total duration in days used to space AI-generated sequence emails. Only applies when using goal-based AI generation."},goal:{type:"string",description:"What this sequence should accomplish for AI generation. Be specific to the app's actual features and user journey. Avoid generic goals that don't match the app's business model."},enrollmentMode:{type:"string",enum:["unlimited","one_time","matching_field"],description:"Sequence re-entry mode. Use 'matching_field' only for event_received triggers when duplicate active runs should be blocked per event field value."},enrollmentFieldPath:{type:"string",description:"Scalar dot-path event property used by enrollmentMode='matching_field', such as 'order.id' or 'product.providerVariantId'. Array traversal with [] is not supported; use propertyFilters for array matching. Leave omitted for Shopify back-in-stock/replenishment product-variant defaults."},sendingWindow:v$,stopCondition:{type:"object",description:"Optional explicit auto-stop condition. Use { type: 'has_tag', value: 'customer' } to end the sequence when a subscriber gets a tag, { type: 'does_not_have_tag', value: 'trial' } when a tag is removed, { type: 'entered_segment', value: 'segment_123' } when they enter a segment, { type: 'field_changed', value: 'plan' } when a subscriber field changes, { type: 'removed_from_list', value: 'list_123' } when they leave a list, { type: 'event_received', value: 'onboarding.completed' } when an event is tracked, or { type: 'none', value: null } for no auto-stop.",properties:{type:{type:"string",enum:["none","has_tag","does_not_have_tag","added_to_list","removed_from_list","entered_segment","field_changed","event_received"],description:"Stop condition type."},value:{type:["string","null"],description:"Tag name, list ID, segment ID, field path, or event name for the stop condition. Use null or omit for type 'none'."}},required:["type"]},steps:{type:"array",description:"Explicit sequence steps. Omit type for email steps, use type: 'sms' for SMS, type: 'create_discount' for a dynamic discount, or type: 'update_subscriber' with nodeType: 'action_update_attributes' and config to copy trigger-event values such as {{event.plan}} into subscriber data.",items:{type:"object",properties:{type:{type:"string",enum:["email","sms","create_discount","discount","update_subscriber"],description:"Step type. Omit or use 'email' for email content. Use 'sms' to send a text message, 'create_discount' to generate a code, or 'update_subscriber' to copy trigger data into the subscriber."},nodeType:{type:"string",enum:["action_email","action_sms","action_create_discount","action_update_attributes"],description:"Internal step type. Use action_update_attributes with config for Update Subscriber steps."},config:Y0,subject:{type:"string",description:"Email subject. Required for email steps."},previewText:{type:"string",description:"Email preview text."},blocks:{type:"array",description:Q1,items:{type:"object"}},html:{type:"string",description:"HTML content for email steps. Stored as one raw HTML block. Use this for imported provider HTML."},text:{type:"string",description:"SMS steps only: plain-text message body. Merge tags like {{FIRST_NAME}} work. Do not include opt-out text or a brand prefix - the platform adds those automatically."},imageUrls:{type:"array",items:{type:"string"},description:"SMS steps only: up to 2 publicly reachable image URLs sent as MMS media."},ineligibleAction:{type:"string",enum:["skip","exit"],description:"SMS steps only: what happens when the contact can't receive SMS (no phone, not opted in, unsupported country). Default 'skip' continues the sequence."},delay:G1,delayMs:{type:"number",description:"Delay before this step in milliseconds. Prefer delay for readability; use delayMs when importing provider waits."},waitUntil:W1,name:{type:"string",description:"Email template name for email steps."},discount:{type:"object",description:"Discount configuration for create_discount steps. Prefer this nested shape for new integrations; legacy top-level discount fields are still accepted.",properties:{label:{type:"string",description:"Builder label for the discount step."},provider:{type:"string",enum:["stripe","shopify"],description:"Discount provider. Use 'stripe' to dynamically create a Stripe coupon plus promotion code, or 'shopify' to dynamically create a Shopify Admin discount code. Defaults to 'stripe' when omitted."},discountType:{type:"string",enum:["percent","amount"],description:"Discount type."},percentOff:{type:"number",description:"Percent discount from 1 to 100. Required when discountType is percent."},amountOff:{type:"number",description:"Fixed amount discount in the smallest currency unit, for example 500 for $5. Required when discountType is amount."},currency:{type:"string",description:"ISO currency for amount discounts. Defaults to usd."},duration:{type:"string",enum:["once","forever","repeating"],description:"Discount duration. Defaults to once."},durationInMonths:{type:"number",description:"Required for repeating discounts."},appliesToAllPlans:{type:"boolean",description:"Whether the discount applies to all plans. Defaults to true."},planIds:{type:"array",description:"Provider product IDs when appliesToAllPlans is false. Stripe uses IDs like prod_abc123; Shopify accepts numeric product IDs or gid://shopify/Product/... IDs.",items:{type:"string"}},codePrefix:{type:"string",description:"Optional prefix for generated dynamic codes. The final code also includes a subscriber/token suffix."},maxRedemptions:{type:"number",description:"Maximum redemptions for each generated code. Use 1 for subscriber-specific codes."},lockToSubscriber:{type:"boolean",description:"Stripe-only. Restrict each generated promotion code to the matched subscriber's Stripe customer."},expiresAt:{type:"string",description:"Optional future expiration date or ISO timestamp."},expiresInHours:{type:"number",description:"Optional relative expiration in hours, resolved when each subscriber's code is created (e.g., 48 for a 48-hour window per subscriber). Takes precedence over expiresAt."},name:{type:"string",description:"Optional display name for each dynamically generated provider discount."}}},label:{type:"string",description:"Legacy top-level discount label. Prefer discount.label."},provider:{type:"string",enum:["stripe","shopify"],description:"Legacy top-level discount provider. Prefer discount.provider. Supports 'stripe' and 'shopify'."},discountType:{type:"string",enum:["percent","amount"],description:"Legacy top-level discount type. Prefer discount.discountType."},percentOff:{type:"number",description:"Percent discount from 1 to 100. Required when discountType is percent."},amountOff:{type:"number",description:"Fixed amount discount in the smallest currency unit, for example 500 for $5. Required when discountType is amount."},currency:{type:"string",description:"ISO currency for amount discounts. Defaults to usd."},duration:{type:"string",enum:["once","forever","repeating"],description:"Discount duration. Defaults to once."},durationInMonths:{type:"number",description:"Required for repeating discounts."},appliesToAllPlans:{type:"boolean",description:"Whether the discount applies to all plans. Defaults to true."},planIds:{type:"array",description:"Provider product IDs when appliesToAllPlans is false. Stripe uses IDs like prod_abc123; Shopify accepts numeric product IDs or gid://shopify/Product/... IDs.",items:{type:"string"}},codePrefix:{type:"string",description:"Optional prefix for generated dynamic codes. The final code also includes a subscriber/token suffix."},maxRedemptions:{type:"number",description:"Maximum redemptions for each generated code. Use 1 for subscriber-specific codes."},lockToSubscriber:{type:"boolean",description:"Legacy top-level Stripe-only flag. Prefer discount.lockToSubscriber."},expiresAt:{type:"string",description:"Optional future expiration date or ISO timestamp."},expiresInHours:{type:"number",description:"Optional relative expiration in hours, resolved when each subscriber's code is created (e.g., 48 for a 48-hour window per subscriber). Takes precedence over expiresAt."}}}}},required:["name","trigger"]}}];var bA=[{name:"update_sequence",description:"Update an existing sequence. To target a specific existing step, use IDs returned by get_sequence. The emails/steps arrays edit email steps, smsSteps edits SMS steps, and subscriberUpdateSteps replaces the config of action_update_attributes steps. To insert new linear steps, use insertSteps with an afterNodeId from get_sequence; omit afterNodeId only to append to an unambiguous linear tail. For active sequences, structural changes such as insertSteps or branch require confirmStructuralChange:true after the user confirms the live-flow impact.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"},name:{type:"string",description:"Sequence name"},fromEmail:{type:"string",description:"Set the From address for all emails in this sequence. Its domain must be configured and verified."},fromName:{type:"string",description:"Display name for a newly created sender profile. Requires fromEmail."},senderProfileId:{type:"string",description:"Set an existing sender profile. Mutually exclusive with fromEmail."},replyTo:{type:"string",description:"Set the Reply-To address for all emails in this sequence."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo."},replyProfileId:{type:"string",description:"Set an existing reply profile. Mutually exclusive with replyTo."},enrollmentPaused:{type:"boolean",description:"Set true to stop new enrollments for an active sequence while current recipients continue. Set false to resume new enrollments. The sequence must already be active."},confirmStructuralChange:{type:"boolean",description:"Set true only after the user explicitly confirms a structural edit to an active sequence. Required for insertSteps or branch when the sequence is active; not needed for content-only email edits."},enrollmentMode:{type:"string",enum:["unlimited","one_time","matching_field"],description:"Updated sequence re-entry mode. 'matching_field' is only valid for event-based sequence triggers."},enrollmentFieldPath:{type:"string",description:"Scalar dot-path event property used by enrollmentMode='matching_field', such as 'order.id' or 'product.providerVariantId'. Array traversal with [] is not supported; use propertyFilters for array matching. Omit to leave unchanged. Use clearEnrollmentFieldPath to clear it."},clearEnrollmentFieldPath:{type:"boolean",description:"Set true to clear enrollmentFieldPath without sending a nullable schema value."},sendingWindow:v$,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:c$}},required:["conditionType"]}},elseSteps:{type:"array",description:"Steps to create inside the else fallback path. Required by default so the else arm is usable.",items:c$},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:c$}},required:["steps"]},emails:{type:"array",description:"Updated existing sequence emails. If you omit emailId/nodeId, items are matched by existing step order. This field does not create new steps; use insertSteps for insertion and include delay on inserted email steps when a timer is needed.",items:{type:"object",properties:{emailId:{type:"string",description:"Optional target linked email template ID for a step. Use the emailId returned in get_sequence.sequence.emails."},nodeId:{type:"string",description:"Optional target action_email node ID for a step. Use the nodeId returned in get_sequence.sequence.emails."},name:{type:"string",description:"Updated step/template name"},subject:{type:"string",description:"Updated email subject"},previewText:{type:"string",description:"Updated preview text"},html:{type:"string",description:"Updated HTML content. Stored as one raw HTML block. Use this to preserve imported provider HTML."},htmlContent:{type:"string",description:"Alias for html. Stored as one raw HTML block. Use this when updating imported provider HTML for a step."},blocks:{type:"array",description:Jw,items:{type:"object"}},...KQ}}},steps:{type:"array",description:"Alias for emails. Supports the same fields and matching rules, and only edits existing email steps. Use insertSteps to create new steps.",items:{type:"object",properties:{emailId:{type:"string",description:"Optional target linked email template ID for a step. Use the emailId returned in get_sequence.sequence.emails."},nodeId:{type:"string",description:"Optional target action_email node ID for a step. Use the nodeId returned in get_sequence.sequence.emails."},name:{type:"string",description:"Updated step/template name"},subject:{type:"string",description:"Updated email subject"},previewText:{type:"string",description:"Updated preview text"},html:{type:"string",description:"Updated HTML content. Stored as one raw HTML block. Use this to preserve imported provider HTML."},htmlContent:{type:"string",description:"Alias for html. Stored as one raw HTML block. Use this when updating HTML content for a step."},blocks:{type:"array",description:Jw,items:{type:"object"}},...KQ}}},smsSteps:{type:"array",description:"Content updates for existing SMS steps, targeted by nodeId (an action_sms node from get_sequence.sequence.nodes). Content-only edits - use insertSteps to create new SMS steps.",items:{type:"object",properties:{nodeId:{type:"string",description:"Target action_sms node ID. Required."},text:{type:"string",description:"Replacement plain-text message body. Merge tags like {{FIRST_NAME}} work. Provide text or blocks, not both."},blocks:{type:"array",items:{type:"object"},description:"Replacement SMS content blocks (text + image subset)."},imageUrls:{type:"array",items:{type:"string"},description:"Up to 2 publicly reachable MMS image URLs. Only valid together with text."},label:{type:"string",description:"Updated display label for the step."},ineligibleAction:{type:"string",enum:["skip","exit"],description:"Updated behavior when the contact can't receive SMS."}},required:["nodeId"]}},subscriberUpdateSteps:{type:"array",description:"Full config replacements for existing Update Subscriber steps, targeted by action_update_attributes nodeId.",items:{type:"object",properties:{nodeId:{type:"string",description:"Target action_update_attributes node ID."},config:Y0},required:["nodeId","config"]}}},required:["sequenceId"]}},{name:"update_sequence_node",description:"Patch one existing sequence node in place. Call get_sequence first, select sequence.nodes[].id, inspect nodeType/config, and pass that node's updatedAt as expectedUpdatedAt. This supports every stored sequence node type, including delays, email/SMS content, actions, conditions, branches without topology changes, webhooks, and trigger settings. Delay example: changes:{ delay:{ days:7 } }. The update is type-aware and preserves fields you omit. It cannot change nodeType, managed linked-resource IDs, or graph topology; use edit_sequence_graph for structural work. On an active sequence, set confirmLiveChange:true only after the user confirms the live behavior change. Existing recipients already waiting keep their scheduled timestamp; the new delay applies when recipients reach the node in the future.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID."},nodeId:k$.properties.nodeId,changes:HQ,expectedUpdatedAt:k$.properties.expectedUpdatedAt,confirmLiveChange:{type:"boolean",description:"Set true only after the user explicitly confirms changing a node in an active sequence."}},required:["sequenceId","nodeId","changes","expectedUpdatedAt"],additionalProperties:!1}},{name:"update_sequence_nodes",description:"Atomically patch multiple existing sequence nodes. Call get_sequence first and include each node's id plus its updatedAt as expectedUpdatedAt. Every patch follows update_sequence_node's type-aware rules. Either every node update commits or none do, making this the preferred tool for changes such as replacing all 5-minute delays with 7-day delays. A node may appear only once. It cannot change node types or graph topology. On an active sequence, set confirmLiveChange:true only after the user confirms the live behavior change. Existing recipients already waiting keep their scheduled timestamps.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID."},updates:{type:"array",description:"Non-empty node patches. Each nodeId may appear only once.",items:k$},confirmLiveChange:{type:"boolean",description:"Set true only after the user explicitly confirms changing nodes in an active sequence."}},required:["sequenceId","updates"],additionalProperties:!1}},{name:"edit_sequence_graph",description:"Restructure an existing sequence graph using node IDs, edges, and graphRevision from get_sequence. move_node repositions one non-split step; beforeNodeId can place an A/B test or other step at the shared continuation below a branch. duplicate_node creates an independent copy and deep-copies linked email or A/B test content. delete_node safely splices a linear step; deleting a split node requires the complete replacement edges. replace_edges atomically replaces the complete topology for advanced reconnect or multi-node reorder work. Always call get_sequence immediately before this tool and pass its graphRevision. Active sequences require confirmStructuralChange:true after the user confirms live-flow impact.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID."},action:{type:"string",enum:["move_node","delete_node","duplicate_node","replace_edges"],description:"Graph operation. Use move_node for a single step reorder, duplicate_node for an independent copy, delete_node to remove a step/node, or replace_edges for an atomic reconnect/reorder of the whole topology."},graphRevision:{type:"string",description:"Exact graphRevision returned by the latest get_sequence call. The edit is rejected if the graph changed since then."},nodeId:{type:"string",description:"Existing node to move, duplicate, or delete. Required for those actions and unused by replace_edges."},afterNodeId:{type:"string",description:"For move_node or duplicate_node, insert immediately after this node. The target must have at most one outgoing path. Provide exactly one of afterNodeId or beforeNodeId."},beforeNodeId:{type:"string",description:"For move_node or duplicate_node, insert immediately before this node. All incoming paths converge through the moved/copied node, which is useful for placing a step below a branch. Provide exactly one of beforeNodeId or afterNodeId."},edges:{type:"array",description:"Complete replacement topology from get_sequence.sequence.edges. The returned edge array is already normalized for this input and can be reused directly. Required for replace_edges and when deleting a split node. Preserve each branch edge's condition.branchId. Do not include edges that reference a deleted node.",items:{type:"object",properties:{sourceNodeId:{type:"string"},targetNodeId:{type:"string"},condition:{type:"object",description:"Optional edge routing condition. Preserve condition.branchId on edges leaving logic_branch nodes."}},required:["sourceNodeId","targetNodeId"],additionalProperties:!1}},confirmStructuralChange:{type:"boolean",description:"Set true only after the user explicitly confirms a structural edit to an active sequence."}},required:["sequenceId","action","graphRevision"],additionalProperties:!1}},{name:"insert_sequence_step",description:"Insert one new email or SMS step into an existing sequence. Prefer this over update_sequence.steps/emails when adding a step: it creates the step node (plus an email template for email steps) and, when delay or delayMs is provided, a logic_delay node immediately before it. For SMS steps set type:'sms' and provide 'text' (generate copy with generate_sms; check get_sms_settings first and warn the user if SMS is not enabled). Use get_sequence first, then pass afterNodeId from sequence.nodes or sequence.emails to choose the insertion point. If afterNodeId is omitted, the step is appended only when the sequence has exactly one linear tail. For active sequences, set confirmStructuralChange:true only after the user confirms the live-flow impact.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID."},type:{type:"string",enum:["email","sms"],description:"Step type. Defaults to 'email'. Use 'sms' to insert an SMS step (requires 'text')."},afterNodeId:{type:"string",description:"Existing node ID to insert after. Use a nodeId from get_sequence.sequence.nodes or get_sequence.sequence.emails. Omit only to append to an unambiguous linear tail."},confirmStructuralChange:{type:"boolean",description:"Set true only after the user explicitly confirms a structural edit to an active sequence."},name:{type:"string",description:"Optional email template and step name."},subject:{type:"string",description:"Email subject for the new step. Required for email steps; not used for SMS steps."},previewText:{type:"string",description:"Optional email preview text for the new step."},blocks:{type:"array",description:Q1,items:{type:"object"}},html:{type:"string",description:"HTML content for the new step. Stored as one raw HTML block. Use this for imported provider HTML. Provide either html or blocks, not both."},senderProfileId:{type:"string",description:"Email steps only: sender profile for the new step. Omit to inherit the effective identity of the nearest sequence email. After a branch merge, only fields shared by every incoming path are inherited; conflicting fields use sequence or company defaults."},fromEmail:{type:"string",description:"Email steps only: From address for the new step. Its domain must be verified. Mutually exclusive with senderProfileId."},fromName:{type:"string",description:"Email steps only: display name override for the new step. With fromEmail, also names a newly created sender profile."},replyProfileId:{type:"string",description:"Email steps only: reply profile for the new step. Omit to inherit the effective Reply-To of the nearest sequence email. After a branch merge, only fields shared by every incoming path are inherited; conflicting fields use sequence or company defaults. Mutually exclusive with replyTo."},replyTo:{type:"string",description:"Email steps only: Reply-To address for the new step. Mutually exclusive with replyProfileId."},replyToName:{type:"string",description:"Email steps only: display name for a newly created reply profile. Requires replyTo."},text:{type:"string",description:"SMS steps only: plain-text message body. Merge tags like {{FIRST_NAME}} work. Do not include opt-out text or a brand prefix - the platform adds those automatically."},imageUrls:{type:"array",items:{type:"string"},description:"SMS steps only: up to 2 publicly reachable image URLs sent as MMS media."},label:{type:"string",description:"SMS steps only: display label for the step."},ineligibleAction:{type:"string",enum:["skip","exit"],description:"SMS steps only: what happens when the contact can't receive SMS (no phone, not opted in, unsupported country). Default 'skip' continues the sequence."},delay:G1,delayMs:{type:"number",description:"Optional wait in milliseconds before the new step. Prefer delay for readability."},waitUntil:W1},required:["sequenceId"],additionalProperties:!1}},{name:"enable_sequence",description:"Enable/activate a sequence. IMPORTANT: Only call this when the user EXPLICITLY asks to enable or activate a sequence. Never enable sequences automatically after creation - the user must review the content first.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}},{name:"disable_sequence",description:"Disable/freeze a sequence. This blocks new enrollments and holds current recipients until the sequence is enabled again. To only stop new enrollments while current recipients continue, use pause_sequence_enrollments.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}},{name:"pause_sequence_enrollments",description:"Stop new enrollments for an active sequence while current recipients continue through the sequence. This matches the dashboard 'Stop new enrollments' control and does not freeze current recipients.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}},{name:"resume_sequence_enrollments",description:"Resume new enrollments for an active sequence whose enrollment gate was paused. Use enable_sequence instead for a fully disabled/frozen sequence.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}},{name:"enroll_subscribers_in_sequence",description:"Manually enroll subscribers in a sequence by email address or subscriber ID. Maximum 500 total targets per call across emails and subscriberIds. Only active subscribers are enrolled: unknown emails are returned in `notFound`, while inactive, unavailable, and already actively enrolled subscribers are counted in `skipped`. By default enrollment starts at the first step after the trigger; pass targetNodeId to start at a specific step.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID to enroll subscribers in."},emails:{type:"array",items:{type:"string"},description:"Email addresses of subscribers to enroll. Combined with subscriberIds, maximum 500 total targets per call."},subscriberIds:{type:"array",items:{type:"string"},description:"Subscriber IDs to enroll. Combined with emails, maximum 500 total targets per call."},targetNodeId:{type:"string",description:"Optional node ID to start enrollment at. Use a non-trigger nodeId from get_sequence. Defaults to the first step after the trigger."}},required:["sequenceId"]}},{name:"cancel_sequence_enrollments",description:"Cancel active/waiting enrollments in one sequence. Provide sequenceId and exactly one target: subscriberId for one subscriber, or fieldValues to match stored entry event properties. For fieldValues, fieldPath is optional when the sequence has enrollmentFieldPath configured; otherwise provide a dot path such as order.id.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID whose enrollments should be cancelled."},subscriberId:{type:"string",description:"Subscriber ID to cancel in this sequence. Provide subscriberId or fieldValues, not both."},fieldPath:{type:"string",description:"Dot-path inside the token's stored entry event properties, such as order.id or event.id. Optional when the sequence has enrollmentFieldPath configured."},fieldValues:{type:"array",items:{type:"string"},description:"Entry field values to match. Cancels all active/waiting enrollments in the sequence whose entry field value is in this list. Provide fieldValues or subscriberId, not both."},dryRun:{type:"boolean",description:"When true, returns matching enrollments without cancelling them. Field-value cancellation defaults to dryRun on the API unless explicitly false."},reason:{type:"string",description:"Optional cancellation reason stored on matched enrollment tokens."}},required:["sequenceId"],additionalProperties:!1}},{name:"delete_sequence",description:"Delete a sequence",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}}];var wA=[{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:nb},required:[]}},{name:"list_subscriber_notes",description:"List internal notes for a subscriber. Provide email or externalId to identify the subscriber.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."}},required:[]}},{name:"add_subscriber_note",description:"Add an internal note to a subscriber. Provide email or externalId to identify the subscriber.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},body:{type:"string",description:"Internal note body, up to 5000 characters."}},required:["body"]}},{name:"delete_subscriber_note",description:"Delete one internal subscriber note by note ID.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},noteId:{type:"string",description:"Subscriber note ID to delete."}},required:["noteId"]}},{name:"search_subscribers",description:"Search subscribers by free-text query, tags, list, or segment. If you omit limit, the tool fetches all pages and returns every match.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},query:{type:"string",description:"Search query (email or name)"},tags:{type:"array",items:{type:"string"},description:"Filter by tags"},list:{type:"string",description:"Filter by subscriber list ID or exact list name. Prefer listId when known."},listId:{type:"string",description:"Filter by subscriber list ID."},listName:{type:"string",description:"Filter by exact subscriber list name when the list ID is not known."},segmentId:{type:"string",description:"Filter by segment ID"},status:{type:"string",description:"Filter by subscriber status: active, unsubscribed, or bounced."},limit:{type:"number",description:"Maximum results to return. If omitted, the tool returns all matches across pages."}}}}];var $A=[{name:"list_tags",description:"List all tags in the account",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list tags for. If not provided, uses the currently selected company."}}}},{name:"create_tag",description:"Create a new tag definition. The name is normalized to lowercase with hyphens (e.g. 'VIP Customer' becomes 'vip-customer'). Color defaults to gray.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},name:{type:"string",description:"Tag name. Normalized to lowercase with hyphens."},color:{type:"string",enum:[...X1],description:"Tag color. Defaults to gray."}},required:["name"]}},{name:"update_tag",description:"Update a tag's color. System tags cannot be updated.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},tagId:{type:"string",description:"Tag ID. Use list_tags to find tag IDs."},color:{type:"string",enum:[...X1],description:"New tag color."}},required:["tagId","color"]}},{name:"delete_tag",description:"Permanently delete a tag and remove it from all subscribers. This cannot be undone. System tags and tags used by sequences cannot be deleted.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},tagId:{type:"string",description:"Tag ID. Use list_tags to find tag IDs."}},required:["tagId"]}},{name:"list_lists",description:"List all subscriber lists",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list lists for. If not provided, uses the currently selected company."}}}},{name:"create_list",description:"Create a new subscriber list",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the list in. If not provided, uses the currently selected company."},name:{type:"string",description:"List name"},description:{type:"string",description:"List description"}},required:["name"]}},{name:"update_list",description:"Update a subscriber list's name, description, or privacy. Only the provided fields are changed.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},listId:{type:"string",description:"Subscriber list ID to update."},name:{type:"string",description:"New list name."},description:{type:["string","null"],description:"New list description. Pass null to clear it."},isPrivate:{type:"boolean",description:"Whether the list is private."}},required:["listId"]}},{name:"delete_list",description:"Permanently delete a subscriber list and remove all of its memberships. Subscribers themselves are kept. This cannot be undone.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},listId:{type:"string",description:"Subscriber list ID to delete."}},required:["listId"]}},{name:"add_subscribers_to_list",description:"Bulk add existing or new subscribers to a subscriber list from an email array. Existing subscribers are added to the list without requiring a per-subscriber update call.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},listId:{type:"string",description:"Subscriber list ID to add subscribers to."},emails:{type:"array",items:{type:"string"},description:"Email addresses to add to the list. Maximum 500 per call."},duplicateStrategy:{type:"string",description:"Duplicate strategy for existing subscribers: skip, merge, or overwrite. Defaults to skip."},enrollInSequences:{type:"boolean",description:"Whether newly created subscribers should enroll in matching sequences. Defaults to false."},optInMode:{type:"string",description:"Consent mode for newly created subscribers: default, confirmed, or double_opt_in. Defaults to default."}},required:["listId","emails"]}},{name:"remove_subscribers_from_list",description:"Remove subscribers from a list by email address. Maximum 500 emails per call. Subscribers stay in the account; only the list membership is removed. Returns the removed count plus a notFound array of emails that did not match a subscriber.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},listId:{type:"string",description:"Subscriber list ID to remove subscribers from."},emails:{type:"array",items:{type:"string"},description:"Email addresses to remove from the list. Maximum 500 per call."}},required:["listId","emails"]}},{name:"list_segments",description:"List all segments",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list segments for. If not provided, uses the currently selected company."}}}},{name:"create_segment",description:'Create a new segment from explicit filter rules. Use `filters` plus `filterJoinOperator` for flat legacy rules, or `root` for nested AND/OR groups such as `{ "kind": "group", "joinOperator": "and", "children": [{ "kind": "filter", "field": "attribute", "operator": "gte", "value": "mrr:50" }, { "kind": "group", "joinOperator": "or", "children": [{ "kind": "filter", "field": "tag", "operator": "contains", "value": "vip" }, { "kind": "filter", "field": "event", "operator": "is_not", "value": "saas.purchase:30d" }] }] }`. Supports `event` and `segment` fields, Stripe product purchase/current/trial/date filters, and campaign-specific engagement filters.',inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the segment in. If not provided, uses the currently selected company."},name:{type:"string",description:"Segment name"},filterJoinOperator:{type:"string",enum:["and","or"],description:'How top-level filters combine. Use `"and"` to require every filter or `"or"` to match any filter.'},filters:{type:"array",items:DQ,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:{...OQ,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:DQ,minItems:1,description:"Replacement segment filters. Same shape and validation rules as create_segment. Mutually exclusive with `root`."},root:{...OQ,description:"Replacement nested filter root. Mutually exclusive with `filters` and `filterJoinOperator`."}},required:["segmentId"]}},{name:"delete_segment",description:"Permanently delete a segment. This cannot be undone. Subscribers are not affected.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},segmentId:{type:"string",description:"Segment ID to delete."}},required:["segmentId"]}},{name:"get_segment_count",description:"Get the number of subscribers in a segment",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},segmentId:{type:"string",description:"Segment ID"}},required:["segmentId"]}}];var QA=[{name:"list_team_members",description:"List team members for the company, including the owner, members with their roles, and pending or expired invitations.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"invite_team_member",description:"Invite a team member by email with role admin, viewer, or restricted. Existing Sequenzy users are added to the team immediately; others receive an email invitation. Billing access (canManageBilling) can only be granted by the company owner and is not available for restricted members.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Email address of the person to invite."},role:{type:"string",enum:["admin","viewer","restricted"],description:"Team role. Admins can manage the workspace; viewers have read-only access; restricted members can open direct campaign links only."},canManageBilling:{type:"boolean",description:"Whether the member can manage billing. Only the company owner can grant billing access. Defaults to false."}},required:["email","role"]}},{name:"cancel_team_invitation",description:"Cancel a pending team invitation. Invitations that have already been accepted cannot be cancelled.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},invitationId:{type:"string",description:"Invitation ID to cancel. Use list_team_members to find pending invitations."}},required:["invitationId"]}}];var WA=[{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:Tw,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:Tw,items:{type:"object"}},labels:{type:"array",description:"Replacement label names. Send an empty array to clear labels. Missing labels are created automatically.",items:{type:"string"}}},required:["templateId"],additionalProperties:!1}},{name:"delete_template",description:"Delete a template",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID"}},required:["templateId"]}}];var GA=[{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:`${Tw} Mutually exclusive with \`html\`.`,items:{type:"object"}},prompt:{type:"string",description:"Generate transactional email blocks from a prompt. Generated blocks include the company's branding (logo and a footer without an unsubscribe link). Mutually exclusive with `html` and `blocks`."},style:{type:"string",description:"Prompt generation style: minimal, branded, promotional. Only used with `prompt`."},tone:{type:"string",description:"Prompt generation tone: professional, casual, friendly. Only used with `prompt`."},enabled:{type:"boolean",description:"Whether this transactional email can be sent immediately. Prompt-created templates default to false; explicit HTML/blocks retain the compatibility default of true."}},required:["name"],additionalProperties:!1}},{name:"update_transactional_email",description:"Update a transactional email by ID or slug. At least one of `name`, `enabled`, `subject`, `previewText`, `html`, or `blocks` is required. Use `html` or `blocks` to replace the linked email body.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},idOrSlug:{type:"string",description:"Transactional email ID or API slug, for example `welcome-email`."},name:{type:"string",description:"Transactional email name."},enabled:{type:"boolean",description:"Whether this transactional email can be sent."},subject:{type:"string",description:"Email subject line."},previewText:{type:["string","null"],description:"Email preview text."},html:{type:"string",description:"Email HTML content. Mutually exclusive with `blocks`. Sequenzy stores it as one raw HTML block."},blocks:{type:"array",description:`${Jw} Mutually exclusive with \`html\`.`,items:{type:"object"}}},required:["idOrSlug"],additionalProperties:!1}},{name:"send_email",description:"Send a transactional email to a single recipient",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},to:{type:"string",description:"Recipient email address"},subject:{type:"string",description:"Email subject (required if not using templateId)"},html:{type:"string",description:"Email HTML content (required if not using templateId)"},templateId:{type:"string",description:"Template ID to use (alternative to html)"},variables:{type:"object",description:"Variables for template personalization. Nested objects and arrays are supported for repeat blocks, for example { items: [...] }."},subscriberExternalId:{type:"string",description:"Customer-owned subscriber ID for attaching analytics/localization on single-recipient sends. Maximum length: 255 characters."}},required:["to"]}}];var XA=[{name:"list_webhooks",description:"List outbound webhook endpoints and their subscribed event types.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"create_webhook",description:"Create an outbound webhook endpoint. IMPORTANT: the response includes a signingSecret that is returned only once - show it to the user immediately so they can store it and verify webhook signatures. If events is omitted, a default set of event types is subscribed.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},name:{type:"string",description:"Webhook endpoint name."},url:{type:"string",description:"HTTPS URL that will receive webhook events."},events:{type:"array",items:{type:"string",enum:[...Y1]},description:"Event types to subscribe to. If omitted, a default set is used."}},required:["name","url"]}},{name:"update_webhook",description:"Update an outbound webhook endpoint's name, URL, subscribed events, or status (enabled/disabled). Providing events replaces the existing event list.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},webhookId:{type:"string",description:"Webhook endpoint ID."},name:{type:"string",description:"New webhook endpoint name."},url:{type:"string",description:"New HTTPS URL that will receive webhook events."},events:{type:"array",items:{type:"string",enum:[...Y1]},description:"Replacement event type subscriptions."},status:{type:"string",enum:["enabled","disabled"],description:"Enable or disable deliveries to this endpoint."}},required:["webhookId"]}},{name:"delete_webhook",description:"Permanently delete an outbound webhook endpoint along with its delivery history. This cannot be undone. To keep the endpoint but stop deliveries, use update_webhook with status disabled instead.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},webhookId:{type:"string",description:"Webhook endpoint ID to delete."}},required:["webhookId"]}},{name:"test_webhook",description:"Send a test event to an outbound webhook endpoint to verify it is reachable and signatures can be validated.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},webhookId:{type:"string",description:"Webhook endpoint ID to test."}},required:["webhookId"]}},{name:"list_webhook_deliveries",description:"List recent delivery attempts for an outbound webhook endpoint, including status and response codes.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},webhookId:{type:"string",description:"Webhook endpoint ID."},limit:{type:"number",description:"Maximum number of deliveries to return, from 1 to 100. Defaults to 20."}},required:["webhookId"]}},{name:"replay_webhook_delivery",description:"Replay a previous webhook delivery, re-sending the same event payload to the endpoint.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},webhookId:{type:"string",description:"Webhook endpoint ID."},deliveryId:{type:"string",description:"Delivery ID to replay. Use list_webhook_deliveries to find delivery IDs."}},required:["webhookId","deliveryId"]}}];var YA=[...nH,...wA,...sH,...$A,...oH,...WA,...lH,...dH,...eH,...aH,...bA,...GA,...pH,...QA,...tH,...XA,...iH,...rH];async function JA(b,w){let $;switch(b){case"get_account":{let Q=await D("GET","/api/v1/account"),W=Dw();$={...Q,selectedCompanyId:W??Q.currentCompanyId};break}case"select_company":{let Q=w.companyId,W=await D("GET","/api/v1/account"),G=W.companies?.find((X)=>X.id===Q);if(!G)throw Error(`Company not found. Available companies: ${W.companies?.map((X)=>`${X.name} (${X.id})`).join(", ")??"none"}`);A0(Q),$={success:!0,message:`Switched to company: ${G.name}`,companyId:G.id,companyName:G.name};break}case"get_app_urls":{let Q=await l$(w);$={...Yw({companyId:Q,campaignId:M(w,"campaignId"),landingPageId:M(w,"landingPageId"),sequenceId:M(w,"sequenceId"),emailId:M(w,"emailId")??M(w,"templateId"),transactionalId:M(w,"transactionalId"),emailSendId:M(w,"emailSendId"),domainId:M(w,"domainId"),status:M(w,"status"),settingsTab:M(w,"settingsTab")}),...Q===void 0&&{note:"No company ID is selected. Call get_account, select_company, or pass companyId to get concrete dashboard URLs."}};break}case"create_company":{let Q=await D("POST","/api/v1/companies",{name:w.name,domain:w.domain});if(!Q.success)throw Error("Failed to create company");let W=Q.company.id,G=6,X=0,Y=Q.company.status;while(Y==="processing"&&X<G){await new Promise((H)=>setTimeout(H,20000)),X++;let z=await D("GET",`/api/v1/companies/${W}`);if(z.success)Y=z.company.status}A0(W);let J=await D("GET",`/api/v1/companies/${W}`);$={success:!0,company:J.company,message:Y==="processing"?"Company created but still processing. You can continue using it while processing completes.":`Company '${J.company.name}' created and ready to use.`,autoSelected:!0};break}case"get_company":{let Q=w.companyId;$=await D("GET",`/api/v1/companies/${Q}`);break}case"update_company":{let Q=await hH("update_company",w),W=FH(w);$=await D("PATCH",`/api/v1/companies/${Q}`,W);break}case"get_sync_rules":{let Q=w.companyId;$=await D("GET","/api/v1/sync-rules",void 0,Q);break}case"update_sync_rules":{let Q=w.companyId;if(w.syncRules!==null&&!Array.isArray(w.syncRules))throw Error("`syncRules` must be an array of rules or null when calling `update_sync_rules`.");$=await D("PUT","/api/v1/sync-rules",{syncRules:w.syncRules},Q);break}case"get_shopify_automation_settings":{let Q=w.companyId;$=await D("GET","/api/v1/shopify/automation-settings",void 0,Q);break}case"update_shopify_automation_settings":{let Q=w.companyId,W={};if(w.browseAbandonment!==void 0)W.browseAbandonment=w.browseAbandonment;if(w.priceDrop!==void 0)W.priceDrop=w.priceDrop;if(Object.keys(W).length===0)throw Error("Provide `browseAbandonment` and/or `priceDrop` when calling `update_shopify_automation_settings`.");$=await D("PUT","/api/v1/shopify/automation-settings",W,Q);break}case"create_api_key":{let Q=w.companyId,W={};if(typeof w.name==="string")W.name=w.name;if(typeof w.preset==="string")W.preset=w.preset;if(Array.isArray(w.scopes))W.scopes=w.scopes;$=await D("POST","/api/v1/api-keys",W,Q);break}case"list_websites":{let Q=w.companyId;$=await D("GET","/api/v1/websites",void 0,Q);break}case"add_sending_domain":case"add_website":{let Q=w.companyId;$=await D("POST","/api/v1/websites",{domain:w.domain},Q);break}case"check_website":{let Q=w.companyId;$=await D("GET",`/api/v1/websites/${encodeURIComponent(String(w.domain))}`,void 0,Q);break}case"verify_sending_domain":{let Q=w.companyId;$=await D("POST",`/api/v1/websites/${encodeURIComponent(String(w.domain))}/verify`,void 0,Q);break}case"get_integration_guide":$=await D("POST","/api/v1/integration-guide",w);break;default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function zA(b,w){let $;switch(b){case"generate_email":{let Q=w.companyId;$=await D("POST","/api/v1/generate/email",w,Q);break}case"generate_sequence":{let Q=w.companyId;$=await D("POST","/api/v1/generate/sequence",w,Q);break}case"generate_subject_lines":{let Q=w.companyId;$=await D("POST","/api/v1/generate/subjects",w,Q);break}case"generate_sms":{let Q=w.companyId;$=await D("POST","/api/v1/generate/sms",w,Q);break}case"get_sms_settings":{let Q=w.companyId;$=await D("GET","/api/v1/sms/settings",void 0,Q);break}case"send_test_sms":{let Q=w.companyId,W={to:j("send_test_sms",w,"to")};for(let G of["text","imageUrls","blocks"])if(w[G]!==void 0)W[G]=w[G];$=await D("POST","/api/v1/sms/test",W,Q);break}case"submit_feedback":{let Q=w.companyId,W={message:j("submit_feedback",w,"message"),source:"mcp"};for(let G of["category","context"])if(w[G]!==void 0)W[G]=w[G];$=await D("POST","/api/v1/feedback",W,Q);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function HA(b,w){let $;switch(b){case"list_transactional_emails":{let Q=w.companyId;$=await D("GET","/api/v1/transactional",void 0,Q);break}case"get_transactional_email":{let Q=w.companyId;$=await D("GET",`/api/v1/transactional/${w.idOrSlug}`,void 0,Q);break}case"create_transactional_email":{let Q=w.companyId,W=new Set(["companyId","name","slug","subject","previewText","html","blocks","prompt","style","tone","enabled"]),G=Object.keys(w).filter((Y)=>!W.has(Y));if(G.length>0)throw Error(`\`create_transactional_email\` accepts only \`name\`, \`slug\`, \`subject\`, \`previewText\`, \`html\`, \`blocks\`, \`prompt\`, \`style\`, \`tone\`, and \`enabled\` fields. Unsupported field${G.length===1?"":"s"}: ${G.map((Y)=>`\`${Y}\``).join(", ")}.`);CH(w);let X=Object.fromEntries(Object.entries(w).filter(([Y])=>Y!=="companyId"));$=await D("POST","/api/v1/transactional",X,Q);break}case"update_transactional_email":{let Q=w.companyId,W=new Set(["companyId","idOrSlug","name","enabled","subject","previewText","html","blocks"]),G=Object.keys(w).filter((Y)=>!W.has(Y));if(G.length>0)throw Error(`\`update_transactional_email\` accepts only \`name\`, \`enabled\`, \`subject\`, \`previewText\`, \`html\`, and \`blocks\` update fields. Unsupported field${G.length===1?"":"s"}: ${G.map((Y)=>`\`${Y}\``).join(", ")}.`);if(kb("update_transactional_email",w),w.name===void 0&&w.enabled===void 0&&w.subject===void 0&&w.previewText===void 0&&w.html===void 0&&w.blocks===void 0)throw Error("Provide at least one of `name`, `enabled`, `subject`, `previewText`, `html`, or `blocks` when calling `update_transactional_email`.");let X=Object.fromEntries(Object.entries(w).filter(([Y])=>Y!=="companyId"&&Y!=="idOrSlug"));$=await D("PATCH",`/api/v1/transactional/${w.idOrSlug}`,X,Q);break}case"send_email":{let Q=w.companyId;$=await D("POST","/api/v1/transactional/send",w,Q);break}case"get_stats":{let Q=w.companyId,W=w.period??"7d",G=new URLSearchParams({period:String(W)});if(w.includeMachineEngagement===!0)G.set("includeMachineEngagement","true");$=await D("GET",`/api/v1/metrics?${G.toString()}`,void 0,Q);break}case"get_campaign_stats":{let Q=w.companyId,W=new URLSearchParams;if(w.includeMachineEngagement===!0)W.set("includeMachineEngagement","true");let G=W.toString();$=await D("GET",`/api/v1/metrics/campaigns/${w.campaignId}${G?`?${G}`:""}`,void 0,Q);break}case"get_sequence_stats":{let Q=w.companyId,W=new URLSearchParams;if(w.includeMachineEngagement===!0)W.set("includeMachineEngagement","true");let G=W.toString();$=await D("GET",`/api/v1/metrics/sequences/${w.sequenceId}${G?`?${G}`:""}`,void 0,Q);break}case"list_campaign_events":{let Q=w.companyId,W=j("list_campaign_events",w,"campaignId"),X=PQ("list_campaign_events",w).toString();$=await D("GET",`/api/v1/metrics/campaigns/${encodeURIComponent(W)}/events${X?`?${X}`:""}`,void 0,Q);break}case"list_sequence_events":{let Q=w.companyId,W=j("list_sequence_events",w,"sequenceId"),X=PQ("list_sequence_events",w).toString();$=await D("GET",`/api/v1/metrics/sequences/${encodeURIComponent(W)}/events${X?`?${X}`:""}`,void 0,Q);break}case"get_subscriber_activity":{let Q=w.companyId,W=Hw("get_subscriber_activity",w),G=await J0(W,Q,{includeMachineEngagement:w.includeMachineEngagement===!0});$={success:G.success,email:G.subscriber.email,emailStats:G.subscriber.emailStats??null,activity:G.subscriber.activity??[],sequenceEnrollments:G.subscriber.sequenceEnrollments??[]};break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function AA(b,w){let $;switch(b){case"list_tags":{let Q=w.companyId;$=await D("GET","/api/v1/tags",void 0,Q);break}case"create_tag":{let Q=w.companyId,W=j("create_tag",w,"name"),G=Vb("create_tag",w,"color",X1);$=await D("POST","/api/v1/tags",{name:W,...G!==void 0&&{color:G}},Q);break}case"update_tag":{let Q=w.companyId,W=j("update_tag",w,"tagId"),G=z0("update_tag",w,"color",X1);$=await D("PATCH",`/api/v1/tags/${encodeURIComponent(W)}`,{color:G},Q);break}case"delete_tag":{let Q=w.companyId,W=j("delete_tag",w,"tagId");$=await D("DELETE",`/api/v1/tags/${encodeURIComponent(W)}`,void 0,Q);break}case"list_lists":{let Q=w.companyId;$=await D("GET","/api/v1/lists",void 0,Q);break}case"create_list":{let Q=w.companyId;$=await D("POST","/api/v1/lists",w,Q);break}case"update_list":{let Q=w.companyId,W=j("update_list",w,"listId");if(w.name===void 0&&w.description===void 0&&w.isPrivate===void 0)throw Error("Provide at least one of `name`, `description`, or `isPrivate` when calling `update_list`.");if(w.name!==void 0&&M(w,"name")===void 0)throw Error("`name` cannot be empty when calling `update_list`.");if(w.description!==void 0&&w.description!==null&&typeof w.description!=="string")throw Error("`description` must be a string or null when calling `update_list`.");if(w.isPrivate!==void 0&&typeof w.isPrivate!=="boolean")throw Error("`isPrivate` must be a boolean when calling `update_list`.");$=await D("PATCH",`/api/v1/lists/${encodeURIComponent(W)}`,{...w.name!==void 0&&{name:M(w,"name")},...w.description!==void 0&&{description:w.description},...w.isPrivate!==void 0&&{isPrivate:w.isPrivate}},Q);break}case"delete_list":{let Q=w.companyId,W=j("delete_list",w,"listId");$=await D("DELETE",`/api/v1/lists/${encodeURIComponent(W)}`,void 0,Q);break}case"add_subscribers_to_list":{let Q=w.companyId,W=j("add_subscribers_to_list",w,"listId"),G=IQ("add_subscribers_to_list",w),X=Vb("add_subscribers_to_list",w,"duplicateStrategy",["skip","merge","overwrite"])??"skip",Y=Vb("add_subscribers_to_list",w,"optInMode",["default","confirmed","double_opt_in"])??"default";$=await D("POST",`/api/v1/lists/${encodeURIComponent(W)}/subscribers`,{emails:G,duplicateStrategy:X,enrollInSequences:w.enrollInSequences===!0,optInMode:Y},Q);break}case"remove_subscribers_from_list":{let Q=w.companyId,W=j("remove_subscribers_from_list",w,"listId"),G=IQ("remove_subscribers_from_list",w);$=await D("POST",`/api/v1/lists/${encodeURIComponent(W)}/subscribers/remove`,{emails:G},Q);break}case"list_segments":{let Q=w.companyId;$=await D("GET","/api/v1/segments",void 0,Q);break}case"create_segment":{BH(w);let Q=w.companyId;$=await D("POST","/api/v1/segments",{...w,...w.filters!==void 0?{filters:x$(w.filters)}:{},...w.root!==void 0?{root:u$(w.root)}:{}},Q);break}case"update_segment":{KH(w);let Q=w.companyId,W=j("update_segment",w,"segmentId"),G=M(w,"name"),X=Vb("update_segment",w,"filterJoinOperator",["and","or"]);$=await D("PATCH",`/api/v1/segments/${encodeURIComponent(W)}`,{...G!==void 0&&{name:G},...X!==void 0&&{filterJoinOperator:X},...w.filters!==void 0?{filters:x$(w.filters)}:{},...w.root!==void 0?{root:u$(w.root)}:{}},Q);break}case"delete_segment":{let Q=w.companyId,W=j("delete_segment",w,"segmentId");$=await D("DELETE",`/api/v1/segments/${encodeURIComponent(W)}`,void 0,Q);break}case"get_segment_count":{let Q=w.companyId;$=await D("GET",`/api/v1/segments/${w.segmentId}/count`,void 0,Q);break}case"list_audience_syncs":{let Q=w.companyId;$=await D("GET","/api/v1/audience-syncs",void 0,Q);break}case"list_ad_accounts":{let Q=w.companyId;$=await D("GET","/api/v1/ad-accounts",void 0,Q);break}case"create_audience_sync":{let Q=w.companyId,W=M(w,"segmentId"),G=M(w,"predefinedSegmentId");if(W&&G)throw Error("Provide either `segmentId` or `predefinedSegmentId` when calling `create_audience_sync`, not both.");if(!W&&!G)throw Error("Provide either `segmentId` or `predefinedSegmentId` when calling `create_audience_sync`.");$=await D("POST","/api/v1/audience-syncs",{segmentId:W,predefinedSegmentId:G,adAccountId:j("create_audience_sync",w,"adAccountId"),audienceName:j("create_audience_sync",w,"audienceName"),...w.frequency!==void 0?{frequency:w.frequency}:{}},Q);break}case"update_audience_sync":{let Q=w.companyId,W=j("update_audience_sync",w,"syncId");$=await D("PATCH",`/api/v1/audience-syncs/${encodeURIComponent(W)}`,{...w.frequency!==void 0?{frequency:w.frequency}:{},...w.isActive!==void 0?{isActive:w.isActive}:{}},Q);break}case"delete_audience_sync":{let Q=w.companyId,W=j("delete_audience_sync",w,"syncId");$=await D("DELETE",`/api/v1/audience-syncs/${encodeURIComponent(W)}`,void 0,Q);break}case"sync_audience_now":{let Q=w.companyId,W=j("sync_audience_now",w,"syncId");$=await D("POST",`/api/v1/audience-syncs/${encodeURIComponent(W)}/sync`,void 0,Q);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function DA(b,w){let $;switch(b){case"list_templates":{let Q=w.companyId,W=new URLSearchParams,G=M(w,"label");if(G)W.set("label",G);$=await D("GET",`/api/v1/templates${W.size>0?`?${W}`:""}`,void 0,Q);break}case"get_template":{let Q=w.companyId;$=await D("GET",`/api/v1/templates/${w.templateId}`,void 0,Q);break}case"create_template":{let Q=w.companyId;_H(w);let W=Object.fromEntries(Object.entries(w).filter(([G])=>G!=="companyId"));$=await D("POST","/api/v1/templates",W,Q);break}case"update_template":{let Q=w.companyId,W=new Set(["companyId","templateId","name","subject","html","blocks","labels"]),G=Object.keys(w).filter((X)=>!W.has(X));if(G.length>0)throw Error(`\`update_template\` accepts only \`name\`, \`subject\`, \`html\`, \`blocks\`, and \`labels\` update fields. Unsupported field${G.length===1?"":"s"}: ${G.map((X)=>`\`${X}\``).join(", ")}.`);if(kb("update_template",w),J1("update_template",w),w.name===void 0&&w.subject===void 0&&w.html===void 0&&w.blocks===void 0&&w.labels===void 0)throw Error("Provide at least one of `name`, `subject`, `html`, `blocks`, or `labels` when calling `update_template`.");$=await D("PUT",`/api/v1/templates/${w.templateId}`,w,Q);break}case"delete_template":{let Q=w.companyId;$=await D("DELETE",`/api/v1/templates/${w.templateId}`,void 0,Q);break}case"list_ab_tests":{let Q=w.companyId,W=new URLSearchParams,G=M(w,"sequenceId");if(G)W.set("sequenceId",G);$=await D("GET",`/api/v1/ab-tests${W.size>0?`?${W}`:""}`,void 0,Q);break}case"get_ab_test":{let Q=w.companyId;$=await D("GET",`/api/v1/ab-tests/${w.abTestId}`,void 0,Q);break}case"get_ab_test_stats":{let Q=w.companyId,W=new URLSearchParams,G=M(w,"period"),X=M(w,"start"),Y=M(w,"end");if(G)W.set("period",G);if(X)W.set("start",X);if(Y)W.set("end",Y);if(w.includeMachineEngagement===!0)W.set("includeMachineEngagement","true");$=await D("GET",`/api/v1/ab-tests/${w.abTestId}/stats${W.size>0?`?${W}`:""}`,void 0,Q);break}case"restart_ab_test":{let Q=w.companyId,W=new Set(["companyId","abTestId","sourceVariantId","testType","winnerThreshold","variantCount"]),G=Object.keys(w).filter((z)=>!W.has(z));if(G.length>0)throw Error(`\`restart_ab_test\` accepts only \`sourceVariantId\`, \`testType\`, \`winnerThreshold\`, and \`variantCount\` option fields. Unsupported field${G.length===1?"":"s"}: ${G.map((z)=>`\`${z}\``).join(", ")}.`);let X=M(w,"testType");if(X!==void 0&&X!=="subject"&&X!=="content")throw Error("`restart_ab_test` testType must be `subject` or `content`.");let Y=w.winnerThreshold===void 0?void 0:Number(w.winnerThreshold);if(Y!==void 0&&(!Number.isInteger(Y)||Y<10||Y>1000))throw Error("`restart_ab_test` winnerThreshold must be an integer from 10 to 1000.");let J=w.variantCount===void 0?void 0:Number(w.variantCount);if(J!==void 0&&(!Number.isInteger(J)||J<2||J>4))throw Error("`restart_ab_test` variantCount must be an integer from 2 to 4.");$=await D("POST",`/api/v1/ab-tests/${w.abTestId}/restart`,{sourceVariantId:M(w,"sourceVariantId"),testType:X,winnerThreshold:Y,variantCount:J},Q);break}case"update_ab_test_variant":{let Q=w.companyId,W=new Set(["companyId","abTestId","variantId","subject","previewText","html","blocks"]),G=Object.keys(w).filter((X)=>!W.has(X));if(G.length>0)throw Error(`\`update_ab_test_variant\` accepts only \`subject\`, \`previewText\`, \`html\`, and \`blocks\` update fields. Unsupported field${G.length===1?"":"s"}: ${G.map((X)=>`\`${X}\``).join(", ")}.`);if(kb("update_ab_test_variant",w),w.subject===void 0&&w.previewText===void 0&&w.html===void 0&&w.blocks===void 0)throw Error("Provide at least one of `subject`, `previewText`, `html`, or `blocks` when calling `update_ab_test_variant`.");$=await D("PATCH",`/api/v1/ab-tests/${w.abTestId}/variants/${w.variantId}`,w,Q);break}case"create_ab_test":{let Q=w.companyId,W=j("create_ab_test",w,"campaignId"),G=M(w,"name"),X=zw("create_ab_test",w,"testPercentage",5,50),Y=zw("create_ab_test",w,"testDurationMinutes",15,1440),J=Vb("create_ab_test",w,"winnerCriteria",["open_rate","click_rate"]);if(w.variants!==void 0){if(!Array.isArray(w.variants))throw Error("`variants` must be an array when calling `create_ab_test`.");w.variants.forEach((z,H)=>{if(!y(z)||typeof z.subject!=="string"||z.subject.trim()==="")throw Error(`\`variants\` item ${H+1} must include a non-empty \`subject\` when calling \`create_ab_test\`.`);if(z.blocks!==void 0&&!Array.isArray(z.blocks))throw Error(`\`variants\` item ${H+1} \`blocks\` must be an array when calling \`create_ab_test\`.`)})}$=await D("POST","/api/v1/ab-tests",{campaignId:W,...G!==void 0&&{name:G},...X!==void 0&&{testPercentage:X},...Y!==void 0&&{testDurationMinutes:Y},...J!==void 0&&{winnerCriteria:J},...w.variants!==void 0&&{variants:w.variants}},Q);break}case"add_ab_test_variant":{let Q=w.companyId,W=j("add_ab_test_variant",w,"abTestId"),G=j("add_ab_test_variant",w,"subject"),X=M(w,"previewText");if(w.blocks!==void 0&&!Array.isArray(w.blocks))throw Error("`blocks` must be an array when calling `add_ab_test_variant`.");$=await D("POST",`/api/v1/ab-tests/${encodeURIComponent(W)}/variants`,{subject:G,...X!==void 0&&{previewText:X},...w.blocks!==void 0&&{blocks:w.blocks}},Q);break}case"delete_ab_test_variant":{let Q=w.companyId,W=j("delete_ab_test_variant",w,"abTestId"),G=j("delete_ab_test_variant",w,"variantId");$=await D("DELETE",`/api/v1/ab-tests/${encodeURIComponent(W)}/variants/${encodeURIComponent(G)}`,void 0,Q);break}case"delete_ab_test":{let Q=w.companyId,W=j("delete_ab_test",w,"abTestId");$=await D("DELETE",`/api/v1/ab-tests/${encodeURIComponent(W)}`,void 0,Q);break}case"list_campaigns":{let Q=w.companyId,W=new URLSearchParams;if(w.status)W.set("status",String(w.status));let G=M(w,"label");if(G)W.set("label",G);$=await D("GET",`/api/v1/campaigns?${W}`,void 0,Q);break}case"get_campaign":{let Q=w.companyId;$=await D("GET",`/api/v1/campaigns/${w.campaignId}`,void 0,Q);break}case"get_email_send":{let Q=w.companyId;$=await D("GET",`/api/v1/email-sends/${encodeURIComponent(String(w.emailSendId))}`,void 0,Q);break}case"create_campaign":{let Q=w.companyId;if(TH(w),w.fromEmail!==void 0&&w.senderProfileId!==void 0)throw Error("Provide either `fromEmail` or `senderProfileId` when calling `create_campaign`, not both.");if(w.replyTo!==void 0&&w.replyProfileId!==void 0)throw Error("Provide either `replyTo` or `replyProfileId` when calling `create_campaign`, not both.");if(w.fromName!==void 0&&w.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `create_campaign`.");if(w.replyToName!==void 0&&w.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `create_campaign`.");let W=Object.fromEntries(Object.entries(w).filter(([G])=>G!=="companyId"));$=await D("POST","/api/v1/campaigns",W,Q);break}case"update_campaign":{let Q=w.companyId,W=new Set(["companyId","campaignId","name","subject","trackingCode","html","blocks","fromEmail","fromName","senderProfileId","replyTo","replyToName","replyProfileId","campaignData","computedLists","labels"]),G=Object.keys(w).filter((X)=>!W.has(X));if(G.length>0)throw Error(`\`update_campaign\` accepts only content, sending identity, campaign data, computed list, and label update fields. Unsupported field${G.length===1?"":"s"}: ${G.map((X)=>`\`${X}\``).join(", ")}.`);if(kb("update_campaign",w),J1("update_campaign",w),w.replyTo!==void 0&&w.replyProfileId!==void 0)throw Error("Provide either `replyTo` or `replyProfileId` when calling `update_campaign`, not both.");if(w.fromEmail!==void 0&&w.senderProfileId!==void 0)throw Error("Provide either `fromEmail` or `senderProfileId` when calling `update_campaign`, not both.");if(w.fromName!==void 0&&w.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `update_campaign`.");if(w.replyToName!==void 0&&w.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `update_campaign`.");if(w.name===void 0&&w.subject===void 0&&w.trackingCode===void 0&&w.html===void 0&&w.blocks===void 0&&w.fromEmail===void 0&&w.senderProfileId===void 0&&w.replyTo===void 0&&w.replyProfileId===void 0&&w.campaignData===void 0&&w.computedLists===void 0&&w.labels===void 0)throw Error("Provide at least one campaign content, sending identity, campaign data, computed list, or label field when calling `update_campaign`.");$=await D("PUT",`/api/v1/campaigns/${w.campaignId}`,w,Q);break}case"schedule_campaign":{let Q=w.companyId,W=new Set(["companyId","campaignId","scheduledAt","targetLists","sendTimeOptimization","spreadOverHours","recurringInterval"]),G=Object.keys(w).filter((X)=>!W.has(X));if(G.length>0)throw Error(`\`schedule_campaign\` accepts only \`campaignId\`, \`scheduledAt\`, \`targetLists\`, \`sendTimeOptimization\`, \`spreadOverHours\`, and \`recurringInterval\`. Unsupported field${G.length===1?"":"s"}: ${G.map((X)=>`\`${X}\``).join(", ")}.`);SH(w),$=await D("POST",`/api/v1/campaigns/${w.campaignId}/schedule`,{scheduledAt:w.scheduledAt,...w.targetLists!==void 0&&{targetLists:w.targetLists},...w.sendTimeOptimization!==void 0&&{sendTimeOptimization:w.sendTimeOptimization},...w.spreadOverHours!==void 0&&{spreadOverHours:w.spreadOverHours},...w.recurringInterval!==void 0&&{recurringInterval:w.recurringInterval}},Q);break}case"send_test_email":{let Q=w.companyId;$=await D("POST",`/api/v1/campaigns/${w.campaignId}/test`,{to:w.to},Q);break}case"cancel_campaign":{let Q=w.companyId,W=j("cancel_campaign",w,"campaignId");$=await D("POST",`/api/v1/campaigns/${encodeURIComponent(W)}/cancel`,void 0,Q);break}case"pause_campaign":{let Q=w.companyId,W=j("pause_campaign",w,"campaignId");$=await D("POST",`/api/v1/campaigns/${encodeURIComponent(W)}/pause`,void 0,Q);break}case"resume_campaign":{let Q=w.companyId,W=j("resume_campaign",w,"campaignId"),G=zw("resume_campaign",w,"spreadOverHours",1,72);$=await D("POST",`/api/v1/campaigns/${encodeURIComponent(W)}/resume`,{...G!==void 0&&{spreadOverHours:G}},Q);break}case"delete_campaign":{let Q=w.companyId,W=j("delete_campaign",w,"campaignId");$=await D("DELETE",`/api/v1/campaigns/${encodeURIComponent(W)}`,void 0,Q);break}case"duplicate_campaign":{let Q=w.companyId,W=j("duplicate_campaign",w,"campaignId"),G=Vb("duplicate_campaign",w,"mode",["campaign","ab_test","variant"]),X=M(w,"variantId");if(G==="variant"&&X===void 0)throw Error("`variantId` is required when calling `duplicate_campaign` with mode `variant`.");$=await D("POST",`/api/v1/campaigns/${encodeURIComponent(W)}/duplicate`,{...G!==void 0&&{mode:G},...X!==void 0&&{variantId:X}},Q);break}case"resend_campaign_to_non_openers":{let Q=w.companyId,W=j("resend_campaign_to_non_openers",w,"campaignId");$=await D("POST",`/api/v1/campaigns/${encodeURIComponent(W)}/resend-to-non-openers`,void 0,Q);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function OA(b,w){let $;switch(b){case"list_landing_pages":{let Q=w.companyId;$=await D("GET","/api/v1/landing-pages",void 0,Q);break}case"get_landing_page":{let Q=w.companyId;$=await D("GET",`/api/v1/landing-pages/${w.landingPageId}`,void 0,Q);break}case"create_landing_page":{let Q=w.companyId,W=new Set(["companyId","name","slug","template","content"]),G=Object.keys(w).filter((X)=>!W.has(X));if(G.length>0)throw Error(`\`create_landing_page\` accepts only \`name\`, \`slug\`, \`template\`, and \`content\` fields. Unsupported field${G.length===1?"":"s"}: ${G.map((X)=>`\`${X}\``).join(", ")}.`);$=await D("POST","/api/v1/landing-pages",{...w.name!==void 0&&{name:w.name},...w.slug!==void 0&&{slug:w.slug},...w.template!==void 0&&{template:w.template},...w.content!==void 0&&{content:w.content}},Q);break}case"update_landing_page":{let Q=w.companyId,W=g$("update_landing_page",w,{requireUpdate:!0});$=await D("PUT",`/api/v1/landing-pages/${w.landingPageId}`,W,Q);break}case"publish_landing_page":{let Q=w.companyId,W=g$("publish_landing_page",w,{requireUpdate:!1});$=await D("POST",`/api/v1/landing-pages/${w.landingPageId}/publish`,W,Q);break}case"unpublish_landing_page":{let Q=w.companyId,W=g$("unpublish_landing_page",w,{requireUpdate:!1});$=await D("POST",`/api/v1/landing-pages/${w.landingPageId}/unpublish`,W,Q);break}case"delete_landing_page":{let Q=w.companyId;$=await D("DELETE",`/api/v1/landing-pages/${w.landingPageId}`,void 0,Q);break}case"connect_landing_page_domain":{let Q=w.companyId;$=await D("POST","/api/v1/landing-pages/domain",{domain:w.domain},Q);break}case"update_landing_page_domain_settings":{let Q=w.companyId,W=RH(w);$=await D("PUT","/api/v1/landing-pages/domain",W,Q);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function qA(b,w){let $;switch(b){case"list_products":{let Q=w.companyId,W=new URLSearchParams;if(typeof w.provider==="string"&&w.provider.trim())W.set("provider",w.provider.trim());if(typeof w.search==="string"&&w.search.trim())W.set("search",w.search.trim());let G=W.size>0?`?${W.toString()}`:"";$=await D("GET",`/api/v1/products${G}`,void 0,Q);break}case"upsert_products":{let Q=w.companyId;if(!Array.isArray(w.products)||w.products.length===0)throw Error("`products` must be a non-empty array when calling `upsert_products`.");$=await D("POST","/api/v1/products",{products:w.products},Q);break}case"delete_product":{let Q=w.companyId,W=j("delete_product",w,"productId");$=await D("DELETE",`/api/v1/products/${encodeURIComponent(W)}`,void 0,Q);break}case"attach_product_file":{let Q=w.companyId,W=j("attach_product_file",w,"productId"),G=M(w,"url"),X=M(w,"filePath");if(G===void 0===(X===void 0))throw Error("Provide either `url` or `filePath` (not both) when calling `attach_product_file`.");let Y;if(X!==void 0){let J=await yH(X,Q);Y={url:J.url,source:"upload",fileName:M(w,"fileName")??J.fileName,fileSizeBytes:J.fileSizeBytes,mimeType:J.mimeType}}else{Y={url:G};let J=M(w,"fileName");if(J)Y.fileName=J}$=await D("PUT",`/api/v1/products/${encodeURIComponent(W)}/delivery`,Y,Q);break}case"remove_product_file":{let Q=w.companyId,W=j("remove_product_file",w,"productId");$=await D("DELETE",`/api/v1/products/${encodeURIComponent(W)}/delivery`,void 0,Q);break}case"sync_products":{let Q=w.companyId;$=await D("POST","/api/v1/products/sync",void 0,Q);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function UA(b,w){let $;switch(b){case"list_sequences":{let Q=w.companyId;$=await D("GET","/api/v1/sequences",void 0,Q);break}case"get_sequence":{let Q=w.companyId;$=await D("GET",`/api/v1/sequences/${w.sequenceId}`,void 0,Q);break}case"create_sequence":{let Q=w.companyId;if(w.fromEmail!==void 0&&w.senderProfileId!==void 0)throw Error("Provide either `fromEmail` or `senderProfileId` when calling `create_sequence`, not both.");if(w.replyTo!==void 0&&w.replyProfileId!==void 0)throw Error("Provide either `replyTo` or `replyProfileId` when calling `create_sequence`, not both.");if(w.fromName!==void 0&&w.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `create_sequence`.");if(w.replyToName!==void 0&&w.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `create_sequence`.");let W=Array.isArray(w.steps)&&w.steps.length>0,G=await D("POST","/api/v1/sequences",w,Q);if(!G.success){$=G;break}let X=G.sequence.id;if(W){let A=await D("GET",`/api/v1/sequences/${X}`,void 0,Q);if(A.success)$={...G,success:!0,sequence:A.sequence,message:`Sequence "${A.sequence.name}" created with explicit steps. Review it before enabling.${G.eventTrackingCode?" Add the custom event feed using eventTrackingCode and eventTracking before enabling.":""}`};else $=A;break}let Y=6,J=0,z="pending";while(z!=="complete"&&J<Y){await new Promise((O)=>setTimeout(O,20000)),J++;let A=await D("GET",`/api/v1/sequences/${X}`,void 0,Q);if(A.success)z=A.sequence.enrichmentStatus}let H=await D("GET",`/api/v1/sequences/${X}`,void 0,Q);if(H.success)$={...G,success:!0,sequence:H.sequence,message:H.sequence.enrichmentStatus==="complete"?`Sequence "${H.sequence.name}" created with ${H.sequence.emailCount} AI-generated emails. The sequence is ready to review and enable.${G.eventTrackingCode?" Add the custom event feed using eventTrackingCode and eventTracking before enabling.":""}`:`Sequence "${H.sequence.name}" created. Email enrichment is still in progress (${H.sequence.enrichedCount}/${H.sequence.emailCount} emails generated). You can check status with get_sequence.${G.eventTrackingCode?" Add the custom event feed using eventTrackingCode and eventTracking before enabling.":""}`};else $=H;break}case"update_sequence":{let Q=w.companyId,W=PH(w);$=await D("PUT",`/api/v1/sequences/${w.sequenceId}`,W,Q);break}case"update_sequence_node":{let Q=w.companyId,W=j("update_sequence_node",w,"sequenceId"),G=IH(w);$=await D("PUT",`/api/v1/sequences/${W}`,G,Q);break}case"update_sequence_nodes":{let Q=w.companyId,W=j("update_sequence_nodes",w,"sequenceId"),G=VH(w);$=await D("PUT",`/api/v1/sequences/${W}`,G,Q);break}case"edit_sequence_graph":{let Q=w.companyId,W=jH(w);$=await D("PUT",`/api/v1/sequences/${w.sequenceId}`,W,Q);break}case"insert_sequence_step":{let Q=w.companyId,W=NH(w);$=await D("PUT",`/api/v1/sequences/${w.sequenceId}`,W,Q);break}case"enable_sequence":{let Q=w.companyId;$=await D("POST",`/api/v1/sequences/${w.sequenceId}/enable`,void 0,Q);break}case"disable_sequence":{let Q=w.companyId;$=await D("POST",`/api/v1/sequences/${w.sequenceId}/disable`,void 0,Q);break}case"pause_sequence_enrollments":{let Q=w.companyId;$=await D("POST",`/api/v1/sequences/${w.sequenceId}/pause-enrollments`,void 0,Q);break}case"resume_sequence_enrollments":{let Q=w.companyId;$=await D("POST",`/api/v1/sequences/${w.sequenceId}/resume-enrollments`,void 0,Q);break}case"enroll_subscribers_in_sequence":{let Q=w.companyId,W=j("enroll_subscribers_in_sequence",w,"sequenceId"),G=uH(w);$=await D("POST",`/api/v1/sequences/${encodeURIComponent(W)}/enroll`,G,Q);break}case"cancel_sequence_enrollments":{let Q=w.companyId,W=EH(w);$=await D("POST",`/api/v1/sequences/${w.sequenceId}/enrollments/cancel`,W,Q);break}case"delete_sequence":{let Q=w.companyId;$=await D("DELETE",`/api/v1/sequences/${w.sequenceId}`,void 0,Q);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function LA(b,w){let $;switch(b){case"add_subscriber":{let Q=w.companyId,W=Hw("add_subscriber",w);$=await D("POST","/api/v1/subscribers",{...W,customAttributes:w.attributes,tags:w.tags,lists:w.listIds,...w.status!==void 0&&{status:w.status},...w.optInMode!==void 0&&{optInMode:w.optInMode}},Q);break}case"update_subscriber":{let Q=w.companyId,W=Hw("update_subscriber",w),G=await J0(W,Q),X=Array.isArray(G.subscriber.tags)?G.subscriber.tags.filter((A)=>typeof A==="string"):[],Y=Array.isArray(w.addTags)?w.addTags.filter((A)=>typeof A==="string"&&A.trim()!=="").map(FQ):[],J=new Set(Array.isArray(w.removeTags)?w.removeTags.filter((A)=>typeof A==="string"&&A.trim()!=="").map(FQ):[]),z=X.filter((A)=>!J.has(A));for(let A of Y)if(!z.includes(A))z.push(A);let H={};if(W.email&&W.externalId)H.externalId=W.externalId;if(y(w.attributes))H.customAttributes={...y(G.subscriber.customAttributes)?G.subscriber.customAttributes:{},...w.attributes};if(w.addTags||w.removeTags)H.tags=z;$=await D("PATCH",m$(W),H,Q);break}case"remove_subscriber":{let Q=w.companyId,W=Hw("remove_subscriber",w),G=m$(W);if(w.hardDelete===!0)$=await D("DELETE",G,void 0,Q);else $=await D("PATCH",G,{status:"unsubscribed"},Q);break}case"get_subscriber":{let Q=w.companyId,W=Hw("get_subscriber",w);$=await J0(W,Q,{includeMachineEngagement:w.includeMachineEngagement===!0});break}case"list_subscriber_notes":{let Q=w.companyId,W=Hw("list_subscriber_notes",w);$=await D("GET",MQ(W),void 0,Q);break}case"add_subscriber_note":{let Q=w.companyId,W=Hw("add_subscriber_note",w),G=typeof w.body==="string"?w.body.trim():void 0;if(!G)throw Error("`body` is required when calling `add_subscriber_note`.");if(G.length>5000)throw Error("`body` must be 5000 characters or fewer when calling `add_subscriber_note`.");$=await D("POST",MQ(W),{body:G},Q);break}case"delete_subscriber_note":{let Q=w.companyId,W=typeof w.noteId==="string"?w.noteId.trim():"";if(!W)throw Error("`noteId` is required when calling `delete_subscriber_note`.");$=await D("DELETE",`/api/v1/subscribers/notes/${encodeURIComponent(W)}`,void 0,Q);break}case"search_subscribers":{let Q=w.companyId;$=await xH(w,Q);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function BA(b,w){let $;switch(b){case"list_team_members":{let Q=w.companyId;$=await D("GET","/api/v1/team",void 0,Q);break}case"invite_team_member":{let Q=w.companyId,W=j("invite_team_member",w,"email"),G=z0("invite_team_member",w,"role",["admin","viewer","restricted"]);if(w.canManageBilling!==void 0&&typeof w.canManageBilling!=="boolean")throw Error("`canManageBilling` must be a boolean when calling `invite_team_member`.");$=await D("POST","/api/v1/team/invitations",{email:W,role:G,...w.canManageBilling!==void 0&&{canManageBilling:w.canManageBilling}},Q);break}case"cancel_team_invitation":{let Q=w.companyId,W=j("cancel_team_invitation",w,"invitationId");$=await D("DELETE",`/api/v1/team/invitations/${encodeURIComponent(W)}`,void 0,Q);break}case"list_conversations":{let Q=w.companyId,W=new URLSearchParams,G=Vb("list_conversations",w,"status",["open","closed","all"]);if(G)W.set("status",G);let X=M(w,"search");if(X)W.set("search",X);if(w.unread!==void 0){if(typeof w.unread!=="boolean")throw Error("`unread` must be a boolean when calling `list_conversations`.");if(w.unread)W.set("unread","true")}if(w.page!==void 0){if(typeof w.page!=="number"||!Number.isInteger(w.page)||w.page<1)throw Error("`page` must be a positive integer when calling `list_conversations`.");W.set("page",String(w.page))}let Y=zw("list_conversations",w,"limit",1,100);if(Y!==void 0)W.set("limit",String(Y));$=await D("GET",`/api/v1/conversations${W.size>0?`?${W}`:""}`,void 0,Q);break}case"get_conversation":{let Q=w.companyId,W=j("get_conversation",w,"conversationId");$=await D("GET",`/api/v1/conversations/${encodeURIComponent(W)}`,void 0,Q);break}case"reply_to_conversation":{let Q=w.companyId,W=j("reply_to_conversation",w,"conversationId"),G=Vb("reply_to_conversation",w,"type",["outbound","note"])??"outbound",X=M(w,"subject"),Y=M(w,"bodyText"),J=M(w,"bodyHtml");if(G==="outbound"&&Y===void 0&&J===void 0)throw Error("Provide `bodyText` or `bodyHtml` when calling `reply_to_conversation` with an outbound message.");$=await D("POST",`/api/v1/conversations/${encodeURIComponent(W)}/messages`,{type:G,...X!==void 0&&{subject:X},...Y!==void 0&&{bodyText:Y},...J!==void 0&&{bodyHtml:J}},Q);break}case"update_conversation_status":{let Q=w.companyId,W=j("update_conversation_status",w,"conversationId"),G=z0("update_conversation_status",w,"status",["open","closed"]);$=await D("POST",`/api/v1/conversations/${encodeURIComponent(W)}/status`,{status:G},Q);break}case"mark_conversation_read":{let Q=w.companyId,W=j("mark_conversation_read",w,"conversationId");$=await D("POST",`/api/v1/conversations/${encodeURIComponent(W)}/read`,void 0,Q);break}case"list_webhooks":{let Q=w.companyId;$=await D("GET","/api/v1/webhooks",void 0,Q);break}case"create_webhook":{let Q=w.companyId,W=j("create_webhook",w,"name"),G=j("create_webhook",w,"url"),X=ZQ("create_webhook",w);$=await D("POST","/api/v1/webhooks",{name:W,url:G,...X!==void 0&&{events:X}},Q);break}case"update_webhook":{let Q=w.companyId,W=j("update_webhook",w,"webhookId"),G=M(w,"name"),X=M(w,"url"),Y=ZQ("update_webhook",w),J=Vb("update_webhook",w,"status",["enabled","disabled"]);if(G===void 0&&X===void 0&&Y===void 0&&J===void 0)throw Error("Provide at least one of `name`, `url`, `events`, or `status` when calling `update_webhook`.");$=await D("PATCH",`/api/v1/webhooks/${encodeURIComponent(W)}`,{...G!==void 0&&{name:G},...X!==void 0&&{url:X},...Y!==void 0&&{events:Y},...J!==void 0&&{status:J}},Q);break}case"delete_webhook":{let Q=w.companyId,W=j("delete_webhook",w,"webhookId");$=await D("DELETE",`/api/v1/webhooks/${encodeURIComponent(W)}`,void 0,Q);break}case"test_webhook":{let Q=w.companyId,W=j("test_webhook",w,"webhookId");$=await D("POST",`/api/v1/webhooks/${encodeURIComponent(W)}/test`,void 0,Q);break}case"list_webhook_deliveries":{let Q=w.companyId,W=j("list_webhook_deliveries",w,"webhookId"),G=zw("list_webhook_deliveries",w,"limit",1,100),X=new URLSearchParams;if(G!==void 0)X.set("limit",String(G));$=await D("GET",`/api/v1/webhooks/${encodeURIComponent(W)}/deliveries${X.size>0?`?${X}`:""}`,void 0,Q);break}case"replay_webhook_delivery":{let Q=w.companyId,W=j("replay_webhook_delivery",w,"webhookId"),G=j("replay_webhook_delivery",w,"deliveryId");$=await D("POST",`/api/v1/webhooks/${encodeURIComponent(W)}/deliveries/${encodeURIComponent(G)}/replay`,void 0,Q);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}var KA=[JA,LA,qA,AA,DA,OA,UA,HA,BA,zA];var FA=YA.map(cH).map(OH);async function MA(b,w){try{let $,Q=!1;for(let G of KA){let X=await G(b,w);if(X.handled){$=X.result,Q=!0;break}}if(!Q)throw Error(`Unknown tool: ${b}`);let W=vH($);if(W)throw W;return $=await gH(b,w,$),{structuredContent:mH($),content:[{type:"text",text:JSON.stringify($,null,2)}]}}catch($){return{isError:!0,content:[{type:"text",text:Aw($)}]}}}async function PA(b,w,$){let Q=w.getRequestContext?.(b)??{};try{return await d$(Q,$)}finally{await w.onRequestContextUpdated?.(Q,b)}}function jQ(b={}){let w=new XQ({name:"sequenzy",version:YH.version},{capabilities:{tools:{},resources:{}},instructions:["Sequenzy email marketing MCP server: manage subscribers, campaigns, sequences, templates, and delivery stats.","If you have access to multiple companies, call get_account and then select_company (or pass companyId per call) before other tools.","IMPORTANT: whenever the user wanted to accomplish something and these tools did not expose functionality for it (missing tool, missing argument, unsupported workflow, or broken behavior), call submit_feedback describing the gap before finishing the task. The Sequenzy team reads every submission and uses it to decide what to build next."].join(`
|
|
191
|
+
`)});return w.setRequestHandler(o6,async()=>{return{tools:FA}}),w.setRequestHandler(k1,async($,Q)=>{let{name:W,arguments:G}=$.params;return PA(Q,b,()=>MA(W,G??{}))}),w.setRequestHandler(g6,async()=>{return{resources:HH}}),w.setRequestHandler(m6,async($,Q)=>{let{uri:W}=$.params;return PA(Q,b,()=>AH(W))}),w}import IA from"node:process";class NQ{append(b){this._buffer=this._buffer?Buffer.concat([this._buffer,b]):b}readMessage(){if(!this._buffer)return null;let b=this._buffer.indexOf(`
|
|
192
|
+
`);if(b===-1)return null;let w=this._buffer.toString("utf8",0,b).replace(/\r$/,"");return this._buffer=this._buffer.subarray(b+1),wP(w)}clear(){this._buffer=void 0}}function wP(b){return LG.parse(JSON.parse(b))}function ZA(b){return JSON.stringify(b)+`
|
|
193
|
+
`}class EQ{constructor(b=IA.stdin,w=IA.stdout){this._stdin=b,this._stdout=w,this._readBuffer=new NQ,this._started=!1,this._ondata=($)=>{this._readBuffer.append($),this.processReadBuffer()},this._onerror=($)=>{this.onerror?.($)}}async start(){if(this._started)throw Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){while(!0)try{let b=this._readBuffer.readMessage();if(b===null)break;this.onmessage?.(b)}catch(b){this.onerror?.(b)}}async close(){if(this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0)this._stdin.pause();this._readBuffer.clear(),this.onclose?.()}send(b){return new Promise((w)=>{let $=ZA(b);if(this._stdout.write($))w();else this._stdout.once("drain",w)})}}async function $P(){yQ(),vQ();let b=jQ(),w=new EQ;await b.connect(w),console.error("Sequenzy MCP server running on stdio")}$P().catch((b)=>{console.error(Aw(b)),process.exit(1)});export{d$ as withMcpRequestContext,A0 as setSelectedCompanyId,Dw as getSelectedCompanyId,jQ as createSequenzyMcpServer,D as apiRequest};
|