nagoc-zerowork 1.1.13 → 1.1.15

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.
Files changed (2) hide show
  1. package/dist/index.js +841 -30
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,53 +1,53 @@
1
1
  #!/usr/bin/env node
2
- var lf=Object.create;var jr=Object.defineProperty;var cf=Object.getOwnPropertyDescriptor;var uf=Object.getOwnPropertyNames;var hf=Object.getPrototypeOf,df=Object.prototype.hasOwnProperty;var k=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Vi=(t,e)=>{for(var n in e)jr(t,n,{get:e[n],enumerable:!0})},pf=(t,e,n,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of uf(e))!df.call(t,r)&&r!==n&&jr(t,r,{get:()=>e[r],enumerable:!(o=cf(e,r))||o.enumerable});return t};var Gi=(t,e,n)=>(n=t!=null?lf(hf(t)):{},pf(e||!t||!t.__esModule?jr(n,"default",{value:t,enumerable:!0}):n,t));var qn=k(Z=>{"use strict";Object.defineProperty(Z,"__esModule",{value:!0});Z.regexpCode=Z.getEsmExportName=Z.getProperty=Z.safeStringify=Z.stringify=Z.strConcat=Z.addCodeArg=Z.str=Z._=Z.nil=Z._Code=Z.Name=Z.IDENTIFIER=Z._CodeOrName=void 0;var jn=class{};Z._CodeOrName=jn;Z.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var kt=class extends jn{constructor(e){if(super(),!Z.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};Z.Name=kt;var Ae=class extends jn{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((n,o)=>`${n}${o}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((n,o)=>(o instanceof kt&&(n[o.str]=(n[o.str]||0)+1),n),{})}};Z._Code=Ae;Z.nil=new Ae("");function cd(t,...e){let n=[t[0]],o=0;for(;o<e.length;)Ya(n,e[o]),n.push(t[++o]);return new Ae(n)}Z._=cd;var Ka=new Ae("+");function ud(t,...e){let n=[Nn(t[0])],o=0;for(;o<e.length;)n.push(Ka),Ya(n,e[o]),n.push(Ka,Nn(t[++o]));return Ry(n),new Ae(n)}Z.str=ud;function Ya(t,e){e instanceof Ae?t.push(...e._items):e instanceof kt?t.push(e):t.push(Oy(e))}Z.addCodeArg=Ya;function Ry(t){let e=1;for(;e<t.length-1;){if(t[e]===Ka){let n=Ay(t[e-1],t[e+1]);if(n!==void 0){t.splice(e-1,3,n);continue}t[e++]="+"}e++}}function Ay(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof kt||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof kt))return`"${t}${e.slice(1)}`}function Dy(t,e){return e.emptyStr()?t:t.emptyStr()?e:ud`${t}${e}`}Z.strConcat=Dy;function Oy(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Nn(Array.isArray(t)?t.join(","):t)}function jy(t){return new Ae(Nn(t))}Z.stringify=jy;function Nn(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}Z.safeStringify=Nn;function Ny(t){return typeof t=="string"&&Z.IDENTIFIER.test(t)?new Ae(`.${t}`):cd`[${t}]`}Z.getProperty=Ny;function qy(t){if(typeof t=="string"&&Z.IDENTIFIER.test(t))return new Ae(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}Z.getEsmExportName=qy;function My(t){return new Ae(t.toString())}Z.regexpCode=My});var es=k(ve=>{"use strict";Object.defineProperty(ve,"__esModule",{value:!0});ve.ValueScope=ve.ValueScopeName=ve.Scope=ve.varKinds=ve.UsedValueState=void 0;var ke=qn(),Xa=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Jo;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Jo||(ve.UsedValueState=Jo={}));ve.varKinds={const:new ke.Name("const"),let:new ke.Name("let"),var:new ke.Name("var")};var Ko=class{constructor({prefixes:e,parent:n}={}){this._names={},this._prefixes=e,this._parent=n}toName(e){return e instanceof ke.Name?e:this.name(e)}name(e){return new ke.Name(this._newName(e))}_newName(e){let n=this._names[e]||this._nameGroup(e);return`${e}${n.index++}`}_nameGroup(e){var n,o;if(!((o=(n=this._parent)===null||n===void 0?void 0:n._prefixes)===null||o===void 0)&&o.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};ve.Scope=Ko;var Yo=class extends ke.Name{constructor(e,n){super(n),this.prefix=e}setValue(e,{property:n,itemIndex:o}){this.value=e,this.scopePath=(0,ke._)`.${new ke.Name(n)}[${o}]`}};ve.ValueScopeName=Yo;var Ly=(0,ke._)`\n`,Qa=class extends Ko{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?Ly:ke.nil}}get(){return this._scope}name(e){return new Yo(e,this._newName(e))}value(e,n){var o;if(n.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let r=this.toName(e),{prefix:a}=r,s=(o=n.key)!==null&&o!==void 0?o:n.ref,i=this._values[a];if(i){let u=i.get(s);if(u)return u}else i=this._values[a]=new Map;i.set(s,r);let l=this._scope[a]||(this._scope[a]=[]),c=l.length;return l[c]=n.ref,r.setValue(n,{property:a,itemIndex:c}),r}getValue(e,n){let o=this._values[e];if(o)return o.get(n)}scopeRefs(e,n=this._values){return this._reduceValues(n,o=>{if(o.scopePath===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return(0,ke._)`${e}${o.scopePath}`})}scopeCode(e=this._values,n,o){return this._reduceValues(e,r=>{if(r.value===void 0)throw new Error(`CodeGen: name "${r}" has no value`);return r.value.code},n,o)}_reduceValues(e,n,o={},r){let a=ke.nil;for(let s in e){let i=e[s];if(!i)continue;let l=o[s]=o[s]||new Map;i.forEach(c=>{if(l.has(c))return;l.set(c,Jo.Started);let u=n(c);if(u){let h=this.opts.es5?ve.varKinds.var:ve.varKinds.const;a=(0,ke._)`${a}${h} ${c} = ${u};${this.opts._n}`}else if(u=r?.(c))a=(0,ke._)`${a}${u}${this.opts._n}`;else throw new Xa(c);l.set(c,Jo.Completed)})}return a}};ve.ValueScope=Qa});var R=k(A=>{"use strict";Object.defineProperty(A,"__esModule",{value:!0});A.or=A.and=A.not=A.CodeGen=A.operators=A.varKinds=A.ValueScopeName=A.ValueScope=A.Scope=A.Name=A.regexpCode=A.stringify=A.getProperty=A.nil=A.strConcat=A.str=A._=void 0;var N=qn(),qe=es(),ut=qn();Object.defineProperty(A,"_",{enumerable:!0,get:function(){return ut._}});Object.defineProperty(A,"str",{enumerable:!0,get:function(){return ut.str}});Object.defineProperty(A,"strConcat",{enumerable:!0,get:function(){return ut.strConcat}});Object.defineProperty(A,"nil",{enumerable:!0,get:function(){return ut.nil}});Object.defineProperty(A,"getProperty",{enumerable:!0,get:function(){return ut.getProperty}});Object.defineProperty(A,"stringify",{enumerable:!0,get:function(){return ut.stringify}});Object.defineProperty(A,"regexpCode",{enumerable:!0,get:function(){return ut.regexpCode}});Object.defineProperty(A,"Name",{enumerable:!0,get:function(){return ut.Name}});var tr=es();Object.defineProperty(A,"Scope",{enumerable:!0,get:function(){return tr.Scope}});Object.defineProperty(A,"ValueScope",{enumerable:!0,get:function(){return tr.ValueScope}});Object.defineProperty(A,"ValueScopeName",{enumerable:!0,get:function(){return tr.ValueScopeName}});Object.defineProperty(A,"varKinds",{enumerable:!0,get:function(){return tr.varKinds}});A.operators={GT:new N._Code(">"),GTE:new N._Code(">="),LT:new N._Code("<"),LTE:new N._Code("<="),EQ:new N._Code("==="),NEQ:new N._Code("!=="),NOT:new N._Code("!"),OR:new N._Code("||"),AND:new N._Code("&&"),ADD:new N._Code("+")};var Qe=class{optimizeNodes(){return this}optimizeNames(e,n){return this}},ts=class extends Qe{constructor(e,n,o){super(),this.varKind=e,this.name=n,this.rhs=o}render({es5:e,_n:n}){let o=e?qe.varKinds.var:this.varKind,r=this.rhs===void 0?"":` = ${this.rhs}`;return`${o} ${this.name}${r};`+n}optimizeNames(e,n){if(e[this.name.str])return this.rhs&&(this.rhs=Ut(this.rhs,e,n)),this}get names(){return this.rhs instanceof N._CodeOrName?this.rhs.names:{}}},Xo=class extends Qe{constructor(e,n,o){super(),this.lhs=e,this.rhs=n,this.sideEffects=o}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof N.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Ut(this.rhs,e,n),this}get names(){let e=this.lhs instanceof N.Name?{}:{...this.lhs.names};return er(e,this.rhs)}},ns=class extends Xo{constructor(e,n,o,r){super(e,o,r),this.op=n}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},os=class extends Qe{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},rs=class extends Qe{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},as=class extends Qe{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},ss=class extends Qe{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,n){return this.code=Ut(this.code,e,n),this}get names(){return this.code instanceof N._CodeOrName?this.code.names:{}}},Mn=class extends Qe{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((n,o)=>n+o.render(e),"")}optimizeNodes(){let{nodes:e}=this,n=e.length;for(;n--;){let o=e[n].optimizeNodes();Array.isArray(o)?e.splice(n,1,...o):o?e[n]=o:e.splice(n,1)}return e.length>0?this:void 0}optimizeNames(e,n){let{nodes:o}=this,r=o.length;for(;r--;){let a=o[r];a.optimizeNames(e,n)||(Zy(e,a.names),o.splice(r,1))}return o.length>0?this:void 0}get names(){return this.nodes.reduce((e,n)=>St(e,n.names),{})}},et=class extends Mn{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},is=class extends Mn{},Bt=class extends et{};Bt.kind="else";var vt=class t extends et{constructor(e,n){super(n),this.condition=e}render(e){let n=`if(${this.condition})`+super.render(e);return this.else&&(n+="else "+this.else.render(e)),n}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let n=this.else;if(n){let o=n.optimizeNodes();n=this.else=Array.isArray(o)?new Bt(o):o}if(n)return e===!1?n instanceof t?n:n.nodes:this.nodes.length?this:new t(hd(e),n instanceof t?[n]:n.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,n){var o;if(this.else=(o=this.else)===null||o===void 0?void 0:o.optimizeNames(e,n),!!(super.optimizeNames(e,n)||this.else))return this.condition=Ut(this.condition,e,n),this}get names(){let e=super.names;return er(e,this.condition),this.else&&St(e,this.else.names),e}};vt.kind="if";var xt=class extends et{};xt.kind="for";var ls=class extends xt{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,n){if(super.optimizeNames(e,n))return this.iteration=Ut(this.iteration,e,n),this}get names(){return St(super.names,this.iteration.names)}},cs=class extends xt{constructor(e,n,o,r){super(),this.varKind=e,this.name=n,this.from=o,this.to=r}render(e){let n=e.es5?qe.varKinds.var:this.varKind,{name:o,from:r,to:a}=this;return`for(${n} ${o}=${r}; ${o}<${a}; ${o}++)`+super.render(e)}get names(){let e=er(super.names,this.from);return er(e,this.to)}},Qo=class extends xt{constructor(e,n,o,r){super(),this.loop=e,this.varKind=n,this.name=o,this.iterable=r}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,n){if(super.optimizeNames(e,n))return this.iterable=Ut(this.iterable,e,n),this}get names(){return St(super.names,this.iterable.names)}},Ln=class extends et{constructor(e,n,o){super(),this.name=e,this.args=n,this.async=o}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};Ln.kind="func";var Zn=class extends Mn{render(e){return"return "+super.render(e)}};Zn.kind="return";var us=class extends et{render(e){let n="try"+super.render(e);return this.catch&&(n+=this.catch.render(e)),this.finally&&(n+=this.finally.render(e)),n}optimizeNodes(){var e,n;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(n=this.finally)===null||n===void 0||n.optimizeNodes(),this}optimizeNames(e,n){var o,r;return super.optimizeNames(e,n),(o=this.catch)===null||o===void 0||o.optimizeNames(e,n),(r=this.finally)===null||r===void 0||r.optimizeNames(e,n),this}get names(){let e=super.names;return this.catch&&St(e,this.catch.names),this.finally&&St(e,this.finally.names),e}},Bn=class extends et{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Bn.kind="catch";var Un=class extends et{render(e){return"finally"+super.render(e)}};Un.kind="finally";var hs=class{constructor(e,n={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...n,_n:n.lines?`
3
- `:""},this._extScope=e,this._scope=new qe.Scope({parent:e}),this._nodes=[new is]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,n){let o=this._extScope.value(e,n);return(this._values[o.prefix]||(this._values[o.prefix]=new Set)).add(o),o}getScopeValue(e,n){return this._extScope.getValue(e,n)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,n,o,r){let a=this._scope.toName(n);return o!==void 0&&r&&(this._constants[a.str]=o),this._leafNode(new ts(e,a,o)),a}const(e,n,o){return this._def(qe.varKinds.const,e,n,o)}let(e,n,o){return this._def(qe.varKinds.let,e,n,o)}var(e,n,o){return this._def(qe.varKinds.var,e,n,o)}assign(e,n,o){return this._leafNode(new Xo(e,n,o))}add(e,n){return this._leafNode(new ns(e,A.operators.ADD,n))}code(e){return typeof e=="function"?e():e!==N.nil&&this._leafNode(new ss(e)),this}object(...e){let n=["{"];for(let[o,r]of e)n.length>1&&n.push(","),n.push(o),(o!==r||this.opts.es5)&&(n.push(":"),(0,N.addCodeArg)(n,r));return n.push("}"),new N._Code(n)}if(e,n,o){if(this._blockNode(new vt(e)),n&&o)this.code(n).else().code(o).endIf();else if(n)this.code(n).endIf();else if(o)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new vt(e))}else(){return this._elseNode(new Bt)}endIf(){return this._endBlockNode(vt,Bt)}_for(e,n){return this._blockNode(e),n&&this.code(n).endFor(),this}for(e,n){return this._for(new ls(e),n)}forRange(e,n,o,r,a=this.opts.es5?qe.varKinds.var:qe.varKinds.let){let s=this._scope.toName(e);return this._for(new cs(a,s,n,o),()=>r(s))}forOf(e,n,o,r=qe.varKinds.const){let a=this._scope.toName(e);if(this.opts.es5){let s=n instanceof N.Name?n:this.var("_arr",n);return this.forRange("_i",0,(0,N._)`${s}.length`,i=>{this.var(a,(0,N._)`${s}[${i}]`),o(a)})}return this._for(new Qo("of",r,a,n),()=>o(a))}forIn(e,n,o,r=this.opts.es5?qe.varKinds.var:qe.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,N._)`Object.keys(${n})`,o);let a=this._scope.toName(e);return this._for(new Qo("in",r,a,n),()=>o(a))}endFor(){return this._endBlockNode(xt)}label(e){return this._leafNode(new os(e))}break(e){return this._leafNode(new rs(e))}return(e){let n=new Zn;if(this._blockNode(n),this.code(e),n.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Zn)}try(e,n,o){if(!n&&!o)throw new Error('CodeGen: "try" without "catch" and "finally"');let r=new us;if(this._blockNode(r),this.code(e),n){let a=this.name("e");this._currNode=r.catch=new Bn(a),n(a)}return o&&(this._currNode=r.finally=new Un,this.code(o)),this._endBlockNode(Bn,Un)}throw(e){return this._leafNode(new as(e))}block(e,n){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(n),this}endBlock(e){let n=this._blockStarts.pop();if(n===void 0)throw new Error("CodeGen: not in self-balancing block");let o=this._nodes.length-n;if(o<0||e!==void 0&&o!==e)throw new Error(`CodeGen: wrong number of nodes: ${o} vs ${e} expected`);return this._nodes.length=n,this}func(e,n=N.nil,o,r){return this._blockNode(new Ln(e,n,o)),r&&this.code(r).endFunc(),this}endFunc(){return this._endBlockNode(Ln)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,n){let o=this._currNode;if(o instanceof e||n&&o instanceof n)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${n?`${e.kind}/${n.kind}`:e.kind}"`)}_elseNode(e){let n=this._currNode;if(!(n instanceof vt))throw new Error('CodeGen: "else" without "if"');return this._currNode=n.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let n=this._nodes;n[n.length-1]=e}};A.CodeGen=hs;function St(t,e){for(let n in e)t[n]=(t[n]||0)+(e[n]||0);return t}function er(t,e){return e instanceof N._CodeOrName?St(t,e.names):t}function Ut(t,e,n){if(t instanceof N.Name)return o(t);if(!r(t))return t;return new N._Code(t._items.reduce((a,s)=>(s instanceof N.Name&&(s=o(s)),s instanceof N._Code?a.push(...s._items):a.push(s),a),[]));function o(a){let s=n[a.str];return s===void 0||e[a.str]!==1?a:(delete e[a.str],s)}function r(a){return a instanceof N._Code&&a._items.some(s=>s instanceof N.Name&&e[s.str]===1&&n[s.str]!==void 0)}}function Zy(t,e){for(let n in e)t[n]=(t[n]||0)-(e[n]||0)}function hd(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,N._)`!${ds(t)}`}A.not=hd;var By=dd(A.operators.AND);function Uy(...t){return t.reduce(By)}A.and=Uy;var Fy=dd(A.operators.OR);function Wy(...t){return t.reduce(Fy)}A.or=Wy;function dd(t){return(e,n)=>e===N.nil?n:n===N.nil?e:(0,N._)`${ds(e)} ${t} ${ds(n)}`}function ds(t){return t instanceof N.Name?t:(0,N._)`(${t})`}});var M=k(D=>{"use strict";Object.defineProperty(D,"__esModule",{value:!0});D.checkStrictMode=D.getErrorPath=D.Type=D.useFunc=D.setEvaluated=D.evaluatedPropsToName=D.mergeEvaluated=D.eachItem=D.unescapeJsonPointer=D.escapeJsonPointer=D.escapeFragment=D.unescapeFragment=D.schemaRefOrVal=D.schemaHasRulesButRef=D.schemaHasRules=D.checkUnknownRules=D.alwaysValidSchema=D.toHash=void 0;var W=R(),Vy=qn();function Gy(t){let e={};for(let n of t)e[n]=!0;return e}D.toHash=Gy;function Hy(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(fd(t,e),!gd(e,t.self.RULES.all))}D.alwaysValidSchema=Hy;function fd(t,e=t.schema){let{opts:n,self:o}=t;if(!n.strictSchema||typeof e=="boolean")return;let r=o.RULES.keywords;for(let a in e)r[a]||bd(t,`unknown keyword: "${a}"`)}D.checkUnknownRules=fd;function gd(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(e[n])return!0;return!1}D.schemaHasRules=gd;function Jy(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(n!=="$ref"&&e.all[n])return!0;return!1}D.schemaHasRulesButRef=Jy;function Ky({topSchemaRef:t,schemaPath:e},n,o,r){if(!r){if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="string")return(0,W._)`${n}`}return(0,W._)`${t}${e}${(0,W.getProperty)(o)}`}D.schemaRefOrVal=Ky;function Yy(t){return wd(decodeURIComponent(t))}D.unescapeFragment=Yy;function Xy(t){return encodeURIComponent(ms(t))}D.escapeFragment=Xy;function ms(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}D.escapeJsonPointer=ms;function wd(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}D.unescapeJsonPointer=wd;function Qy(t,e){if(Array.isArray(t))for(let n of t)e(n);else e(t)}D.eachItem=Qy;function pd({mergeNames:t,mergeToName:e,mergeValues:n,resultToName:o}){return(r,a,s,i)=>{let l=s===void 0?a:s instanceof W.Name?(a instanceof W.Name?t(r,a,s):e(r,a,s),s):a instanceof W.Name?(e(r,s,a),a):n(a,s);return i===W.Name&&!(l instanceof W.Name)?o(r,l):l}}D.mergeEvaluated={props:pd({mergeNames:(t,e,n)=>t.if((0,W._)`${n} !== true && ${e} !== undefined`,()=>{t.if((0,W._)`${e} === true`,()=>t.assign(n,!0),()=>t.assign(n,(0,W._)`${n} || {}`).code((0,W._)`Object.assign(${n}, ${e})`))}),mergeToName:(t,e,n)=>t.if((0,W._)`${n} !== true`,()=>{e===!0?t.assign(n,!0):(t.assign(n,(0,W._)`${n} || {}`),fs(t,n,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:yd}),items:pd({mergeNames:(t,e,n)=>t.if((0,W._)`${n} !== true && ${e} !== undefined`,()=>t.assign(n,(0,W._)`${e} === true ? true : ${n} > ${e} ? ${n} : ${e}`)),mergeToName:(t,e,n)=>t.if((0,W._)`${n} !== true`,()=>t.assign(n,e===!0?!0:(0,W._)`${n} > ${e} ? ${n} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function yd(t,e){if(e===!0)return t.var("props",!0);let n=t.var("props",(0,W._)`{}`);return e!==void 0&&fs(t,n,e),n}D.evaluatedPropsToName=yd;function fs(t,e,n){Object.keys(n).forEach(o=>t.assign((0,W._)`${e}${(0,W.getProperty)(o)}`,!0))}D.setEvaluated=fs;var md={};function eb(t,e){return t.scopeValue("func",{ref:e,code:md[e.code]||(md[e.code]=new Vy._Code(e.code))})}D.useFunc=eb;var ps;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(ps||(D.Type=ps={}));function tb(t,e,n){if(t instanceof W.Name){let o=e===ps.Num;return n?o?(0,W._)`"[" + ${t} + "]"`:(0,W._)`"['" + ${t} + "']"`:o?(0,W._)`"/" + ${t}`:(0,W._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return n?(0,W.getProperty)(t).toString():"/"+ms(t)}D.getErrorPath=tb;function bd(t,e,n=t.opts.strictSchema){if(n){if(e=`strict mode: ${e}`,n===!0)throw new Error(e);t.self.logger.warn(e)}}D.checkStrictMode=bd});var tt=k(gs=>{"use strict";Object.defineProperty(gs,"__esModule",{value:!0});var de=R(),nb={data:new de.Name("data"),valCxt:new de.Name("valCxt"),instancePath:new de.Name("instancePath"),parentData:new de.Name("parentData"),parentDataProperty:new de.Name("parentDataProperty"),rootData:new de.Name("rootData"),dynamicAnchors:new de.Name("dynamicAnchors"),vErrors:new de.Name("vErrors"),errors:new de.Name("errors"),this:new de.Name("this"),self:new de.Name("self"),scope:new de.Name("scope"),json:new de.Name("json"),jsonPos:new de.Name("jsonPos"),jsonLen:new de.Name("jsonLen"),jsonPart:new de.Name("jsonPart")};gs.default=nb});var Fn=k(pe=>{"use strict";Object.defineProperty(pe,"__esModule",{value:!0});pe.extendErrors=pe.resetErrorsCount=pe.reportExtraError=pe.reportError=pe.keyword$DataError=pe.keywordError=void 0;var L=R(),nr=M(),we=tt();pe.keywordError={message:({keyword:t})=>(0,L.str)`must pass "${t}" keyword validation`};pe.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,L.str)`"${t}" keyword must be ${e} ($data)`:(0,L.str)`"${t}" keyword is invalid ($data)`};function ob(t,e=pe.keywordError,n,o){let{it:r}=t,{gen:a,compositeRule:s,allErrors:i}=r,l=xd(t,e,n);o??(s||i)?kd(a,l):vd(r,(0,L._)`[${l}]`)}pe.reportError=ob;function rb(t,e=pe.keywordError,n){let{it:o}=t,{gen:r,compositeRule:a,allErrors:s}=o,i=xd(t,e,n);kd(r,i),a||s||vd(o,we.default.vErrors)}pe.reportExtraError=rb;function ab(t,e){t.assign(we.default.errors,e),t.if((0,L._)`${we.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,L._)`${we.default.vErrors}.length`,e),()=>t.assign(we.default.vErrors,null)))}pe.resetErrorsCount=ab;function sb({gen:t,keyword:e,schemaValue:n,data:o,errsCount:r,it:a}){if(r===void 0)throw new Error("ajv implementation error");let s=t.name("err");t.forRange("i",r,we.default.errors,i=>{t.const(s,(0,L._)`${we.default.vErrors}[${i}]`),t.if((0,L._)`${s}.instancePath === undefined`,()=>t.assign((0,L._)`${s}.instancePath`,(0,L.strConcat)(we.default.instancePath,a.errorPath))),t.assign((0,L._)`${s}.schemaPath`,(0,L.str)`${a.errSchemaPath}/${e}`),a.opts.verbose&&(t.assign((0,L._)`${s}.schema`,n),t.assign((0,L._)`${s}.data`,o))})}pe.extendErrors=sb;function kd(t,e){let n=t.const("err",e);t.if((0,L._)`${we.default.vErrors} === null`,()=>t.assign(we.default.vErrors,(0,L._)`[${n}]`),(0,L._)`${we.default.vErrors}.push(${n})`),t.code((0,L._)`${we.default.errors}++`)}function vd(t,e){let{gen:n,validateName:o,schemaEnv:r}=t;r.$async?n.throw((0,L._)`new ${t.ValidationError}(${e})`):(n.assign((0,L._)`${o}.errors`,e),n.return(!1))}var _t={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 xd(t,e,n){let{createErrors:o}=t.it;return o===!1?(0,L._)`{}`:ib(t,e,n)}function ib(t,e,n={}){let{gen:o,it:r}=t,a=[lb(r,n),cb(t,n)];return ub(t,e,a),o.object(...a)}function lb({errorPath:t},{instancePath:e}){let n=e?(0,L.str)`${t}${(0,nr.getErrorPath)(e,nr.Type.Str)}`:t;return[we.default.instancePath,(0,L.strConcat)(we.default.instancePath,n)]}function cb({keyword:t,it:{errSchemaPath:e}},{schemaPath:n,parentSchema:o}){let r=o?e:(0,L.str)`${e}/${t}`;return n&&(r=(0,L.str)`${r}${(0,nr.getErrorPath)(n,nr.Type.Str)}`),[_t.schemaPath,r]}function ub(t,{params:e,message:n},o){let{keyword:r,data:a,schemaValue:s,it:i}=t,{opts:l,propertyName:c,topSchemaRef:u,schemaPath:h}=i;o.push([_t.keyword,r],[_t.params,typeof e=="function"?e(t):e||(0,L._)`{}`]),l.messages&&o.push([_t.message,typeof n=="function"?n(t):n]),l.verbose&&o.push([_t.schema,s],[_t.parentSchema,(0,L._)`${u}${h}`],[we.default.data,a]),c&&o.push([_t.propertyName,c])}});var _d=k(Ft=>{"use strict";Object.defineProperty(Ft,"__esModule",{value:!0});Ft.boolOrEmptySchema=Ft.topBoolOrEmptySchema=void 0;var hb=Fn(),db=R(),pb=tt(),mb={message:"boolean schema is false"};function fb(t){let{gen:e,schema:n,validateName:o}=t;n===!1?Sd(t,!1):typeof n=="object"&&n.$async===!0?e.return(pb.default.data):(e.assign((0,db._)`${o}.errors`,null),e.return(!0))}Ft.topBoolOrEmptySchema=fb;function gb(t,e){let{gen:n,schema:o}=t;o===!1?(n.var(e,!1),Sd(t)):n.var(e,!0)}Ft.boolOrEmptySchema=gb;function Sd(t,e){let{gen:n,data:o}=t,r={gen:n,keyword:"false schema",data:o,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,hb.reportError)(r,mb,void 0,e)}});var ws=k(Wt=>{"use strict";Object.defineProperty(Wt,"__esModule",{value:!0});Wt.getRules=Wt.isJSONType=void 0;var wb=["string","number","integer","boolean","null","object","array"],yb=new Set(wb);function bb(t){return typeof t=="string"&&yb.has(t)}Wt.isJSONType=bb;function kb(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}Wt.getRules=kb});var ys=k(ht=>{"use strict";Object.defineProperty(ht,"__esModule",{value:!0});ht.shouldUseRule=ht.shouldUseGroup=ht.schemaHasRulesForType=void 0;function vb({schema:t,self:e},n){let o=e.RULES.types[n];return o&&o!==!0&&Id(t,o)}ht.schemaHasRulesForType=vb;function Id(t,e){return e.rules.some(n=>zd(t,n))}ht.shouldUseGroup=Id;function zd(t,e){var n;return t[e.keyword]!==void 0||((n=e.definition.implements)===null||n===void 0?void 0:n.some(o=>t[o]!==void 0))}ht.shouldUseRule=zd});var Wn=k(me=>{"use strict";Object.defineProperty(me,"__esModule",{value:!0});me.reportTypeError=me.checkDataTypes=me.checkDataType=me.coerceAndCheckDataType=me.getJSONTypes=me.getSchemaTypes=me.DataType=void 0;var xb=ws(),Sb=ys(),_b=Fn(),E=R(),Td=M(),Vt;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Vt||(me.DataType=Vt={}));function Ib(t){let e=$d(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}me.getSchemaTypes=Ib;function $d(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(xb.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}me.getJSONTypes=$d;function zb(t,e){let{gen:n,data:o,opts:r}=t,a=Tb(e,r.coerceTypes),s=e.length>0&&!(a.length===0&&e.length===1&&(0,Sb.schemaHasRulesForType)(t,e[0]));if(s){let i=ks(e,o,r.strictNumbers,Vt.Wrong);n.if(i,()=>{a.length?$b(t,e,a):vs(t)})}return s}me.coerceAndCheckDataType=zb;var Cd=new Set(["string","number","integer","boolean","null"]);function Tb(t,e){return e?t.filter(n=>Cd.has(n)||e==="array"&&n==="array"):[]}function $b(t,e,n){let{gen:o,data:r,opts:a}=t,s=o.let("dataType",(0,E._)`typeof ${r}`),i=o.let("coerced",(0,E._)`undefined`);a.coerceTypes==="array"&&o.if((0,E._)`${s} == 'object' && Array.isArray(${r}) && ${r}.length == 1`,()=>o.assign(r,(0,E._)`${r}[0]`).assign(s,(0,E._)`typeof ${r}`).if(ks(e,r,a.strictNumbers),()=>o.assign(i,r))),o.if((0,E._)`${i} !== undefined`);for(let c of n)(Cd.has(c)||c==="array"&&a.coerceTypes==="array")&&l(c);o.else(),vs(t),o.endIf(),o.if((0,E._)`${i} !== undefined`,()=>{o.assign(r,i),Cb(t,i)});function l(c){switch(c){case"string":o.elseIf((0,E._)`${s} == "number" || ${s} == "boolean"`).assign(i,(0,E._)`"" + ${r}`).elseIf((0,E._)`${r} === null`).assign(i,(0,E._)`""`);return;case"number":o.elseIf((0,E._)`${s} == "boolean" || ${r} === null
2
+ var mf=Object.create;var Lr=Object.defineProperty;var ff=Object.getOwnPropertyDescriptor;var gf=Object.getOwnPropertyNames;var wf=Object.getPrototypeOf,yf=Object.prototype.hasOwnProperty;var k=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Yi=(t,e)=>{for(var n in e)Lr(t,n,{get:e[n],enumerable:!0})},bf=(t,e,n,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of gf(e))!yf.call(t,r)&&r!==n&&Lr(t,r,{get:()=>e[r],enumerable:!(o=ff(e,r))||o.enumerable});return t};var Xi=(t,e,n)=>(n=t!=null?mf(wf(t)):{},bf(e||!t||!t.__esModule?Lr(n,"default",{value:t,enumerable:!0}):n,t));var Ln=k(B=>{"use strict";Object.defineProperty(B,"__esModule",{value:!0});B.regexpCode=B.getEsmExportName=B.getProperty=B.safeStringify=B.stringify=B.strConcat=B.addCodeArg=B.str=B._=B.nil=B._Code=B.Name=B.IDENTIFIER=B._CodeOrName=void 0;var qn=class{};B._CodeOrName=qn;B.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var vt=class extends qn{constructor(e){if(super(),!B.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};B.Name=vt;var Ae=class extends qn{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((n,o)=>`${n}${o}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((n,o)=>(o instanceof vt&&(n[o.str]=(n[o.str]||0)+1),n),{})}};B._Code=Ae;B.nil=new Ae("");function md(t,...e){let n=[t[0]],o=0;for(;o<e.length;)ts(n,e[o]),n.push(t[++o]);return new Ae(n)}B._=md;var es=new Ae("+");function fd(t,...e){let n=[Mn(t[0])],o=0;for(;o<e.length;)n.push(es),ts(n,e[o]),n.push(es,Mn(t[++o]));return qy(n),new Ae(n)}B.str=fd;function ts(t,e){e instanceof Ae?t.push(...e._items):e instanceof vt?t.push(e):t.push(By(e))}B.addCodeArg=ts;function qy(t){let e=1;for(;e<t.length-1;){if(t[e]===es){let n=My(t[e-1],t[e+1]);if(n!==void 0){t.splice(e-1,3,n);continue}t[e++]="+"}e++}}function My(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof vt||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof vt))return`"${t}${e.slice(1)}`}function Ly(t,e){return e.emptyStr()?t:t.emptyStr()?e:fd`${t}${e}`}B.strConcat=Ly;function By(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Mn(Array.isArray(t)?t.join(","):t)}function Zy(t){return new Ae(Mn(t))}B.stringify=Zy;function Mn(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}B.safeStringify=Mn;function Fy(t){return typeof t=="string"&&B.IDENTIFIER.test(t)?new Ae(`.${t}`):md`[${t}]`}B.getProperty=Fy;function Uy(t){if(typeof t=="string"&&B.IDENTIFIER.test(t))return new Ae(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}B.getEsmExportName=Uy;function Wy(t){return new Ae(t.toString())}B.regexpCode=Wy});var rs=k(ve=>{"use strict";Object.defineProperty(ve,"__esModule",{value:!0});ve.ValueScope=ve.ValueScopeName=ve.Scope=ve.varKinds=ve.UsedValueState=void 0;var ke=Ln(),ns=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Yo;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Yo||(ve.UsedValueState=Yo={}));ve.varKinds={const:new ke.Name("const"),let:new ke.Name("let"),var:new ke.Name("var")};var Xo=class{constructor({prefixes:e,parent:n}={}){this._names={},this._prefixes=e,this._parent=n}toName(e){return e instanceof ke.Name?e:this.name(e)}name(e){return new ke.Name(this._newName(e))}_newName(e){let n=this._names[e]||this._nameGroup(e);return`${e}${n.index++}`}_nameGroup(e){var n,o;if(!((o=(n=this._parent)===null||n===void 0?void 0:n._prefixes)===null||o===void 0)&&o.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};ve.Scope=Xo;var Qo=class extends ke.Name{constructor(e,n){super(n),this.prefix=e}setValue(e,{property:n,itemIndex:o}){this.value=e,this.scopePath=(0,ke._)`.${new ke.Name(n)}[${o}]`}};ve.ValueScopeName=Qo;var Vy=(0,ke._)`\n`,os=class extends Xo{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?Vy:ke.nil}}get(){return this._scope}name(e){return new Qo(e,this._newName(e))}value(e,n){var o;if(n.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let r=this.toName(e),{prefix:a}=r,s=(o=n.key)!==null&&o!==void 0?o:n.ref,i=this._values[a];if(i){let u=i.get(s);if(u)return u}else i=this._values[a]=new Map;i.set(s,r);let l=this._scope[a]||(this._scope[a]=[]),c=l.length;return l[c]=n.ref,r.setValue(n,{property:a,itemIndex:c}),r}getValue(e,n){let o=this._values[e];if(o)return o.get(n)}scopeRefs(e,n=this._values){return this._reduceValues(n,o=>{if(o.scopePath===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return(0,ke._)`${e}${o.scopePath}`})}scopeCode(e=this._values,n,o){return this._reduceValues(e,r=>{if(r.value===void 0)throw new Error(`CodeGen: name "${r}" has no value`);return r.value.code},n,o)}_reduceValues(e,n,o={},r){let a=ke.nil;for(let s in e){let i=e[s];if(!i)continue;let l=o[s]=o[s]||new Map;i.forEach(c=>{if(l.has(c))return;l.set(c,Yo.Started);let u=n(c);if(u){let h=this.opts.es5?ve.varKinds.var:ve.varKinds.const;a=(0,ke._)`${a}${h} ${c} = ${u};${this.opts._n}`}else if(u=r?.(c))a=(0,ke._)`${a}${u}${this.opts._n}`;else throw new ns(c);l.set(c,Yo.Completed)})}return a}};ve.ValueScope=os});var R=k(A=>{"use strict";Object.defineProperty(A,"__esModule",{value:!0});A.or=A.and=A.not=A.CodeGen=A.operators=A.varKinds=A.ValueScopeName=A.ValueScope=A.Scope=A.Name=A.regexpCode=A.stringify=A.getProperty=A.nil=A.strConcat=A.str=A._=void 0;var N=Ln(),Me=rs(),ht=Ln();Object.defineProperty(A,"_",{enumerable:!0,get:function(){return ht._}});Object.defineProperty(A,"str",{enumerable:!0,get:function(){return ht.str}});Object.defineProperty(A,"strConcat",{enumerable:!0,get:function(){return ht.strConcat}});Object.defineProperty(A,"nil",{enumerable:!0,get:function(){return ht.nil}});Object.defineProperty(A,"getProperty",{enumerable:!0,get:function(){return ht.getProperty}});Object.defineProperty(A,"stringify",{enumerable:!0,get:function(){return ht.stringify}});Object.defineProperty(A,"regexpCode",{enumerable:!0,get:function(){return ht.regexpCode}});Object.defineProperty(A,"Name",{enumerable:!0,get:function(){return ht.Name}});var or=rs();Object.defineProperty(A,"Scope",{enumerable:!0,get:function(){return or.Scope}});Object.defineProperty(A,"ValueScope",{enumerable:!0,get:function(){return or.ValueScope}});Object.defineProperty(A,"ValueScopeName",{enumerable:!0,get:function(){return or.ValueScopeName}});Object.defineProperty(A,"varKinds",{enumerable:!0,get:function(){return or.varKinds}});A.operators={GT:new N._Code(">"),GTE:new N._Code(">="),LT:new N._Code("<"),LTE:new N._Code("<="),EQ:new N._Code("==="),NEQ:new N._Code("!=="),NOT:new N._Code("!"),OR:new N._Code("||"),AND:new N._Code("&&"),ADD:new N._Code("+")};var et=class{optimizeNodes(){return this}optimizeNames(e,n){return this}},as=class extends et{constructor(e,n,o){super(),this.varKind=e,this.name=n,this.rhs=o}render({es5:e,_n:n}){let o=e?Me.varKinds.var:this.varKind,r=this.rhs===void 0?"":` = ${this.rhs}`;return`${o} ${this.name}${r};`+n}optimizeNames(e,n){if(e[this.name.str])return this.rhs&&(this.rhs=Ut(this.rhs,e,n)),this}get names(){return this.rhs instanceof N._CodeOrName?this.rhs.names:{}}},er=class extends et{constructor(e,n,o){super(),this.lhs=e,this.rhs=n,this.sideEffects=o}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof N.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Ut(this.rhs,e,n),this}get names(){let e=this.lhs instanceof N.Name?{}:{...this.lhs.names};return nr(e,this.rhs)}},ss=class extends er{constructor(e,n,o,r){super(e,o,r),this.op=n}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},is=class extends et{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},ls=class extends et{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},cs=class extends et{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},us=class extends et{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,n){return this.code=Ut(this.code,e,n),this}get names(){return this.code instanceof N._CodeOrName?this.code.names:{}}},Bn=class extends et{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((n,o)=>n+o.render(e),"")}optimizeNodes(){let{nodes:e}=this,n=e.length;for(;n--;){let o=e[n].optimizeNodes();Array.isArray(o)?e.splice(n,1,...o):o?e[n]=o:e.splice(n,1)}return e.length>0?this:void 0}optimizeNames(e,n){let{nodes:o}=this,r=o.length;for(;r--;){let a=o[r];a.optimizeNames(e,n)||(Gy(e,a.names),o.splice(r,1))}return o.length>0?this:void 0}get names(){return this.nodes.reduce((e,n)=>_t(e,n.names),{})}},tt=class extends Bn{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},hs=class extends Bn{},Ft=class extends tt{};Ft.kind="else";var xt=class t extends tt{constructor(e,n){super(n),this.condition=e}render(e){let n=`if(${this.condition})`+super.render(e);return this.else&&(n+="else "+this.else.render(e)),n}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let n=this.else;if(n){let o=n.optimizeNodes();n=this.else=Array.isArray(o)?new Ft(o):o}if(n)return e===!1?n instanceof t?n:n.nodes:this.nodes.length?this:new t(gd(e),n instanceof t?[n]:n.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,n){var o;if(this.else=(o=this.else)===null||o===void 0?void 0:o.optimizeNames(e,n),!!(super.optimizeNames(e,n)||this.else))return this.condition=Ut(this.condition,e,n),this}get names(){let e=super.names;return nr(e,this.condition),this.else&&_t(e,this.else.names),e}};xt.kind="if";var St=class extends tt{};St.kind="for";var ds=class extends St{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,n){if(super.optimizeNames(e,n))return this.iteration=Ut(this.iteration,e,n),this}get names(){return _t(super.names,this.iteration.names)}},ps=class extends St{constructor(e,n,o,r){super(),this.varKind=e,this.name=n,this.from=o,this.to=r}render(e){let n=e.es5?Me.varKinds.var:this.varKind,{name:o,from:r,to:a}=this;return`for(${n} ${o}=${r}; ${o}<${a}; ${o}++)`+super.render(e)}get names(){let e=nr(super.names,this.from);return nr(e,this.to)}},tr=class extends St{constructor(e,n,o,r){super(),this.loop=e,this.varKind=n,this.name=o,this.iterable=r}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,n){if(super.optimizeNames(e,n))return this.iterable=Ut(this.iterable,e,n),this}get names(){return _t(super.names,this.iterable.names)}},Zn=class extends tt{constructor(e,n,o){super(),this.name=e,this.args=n,this.async=o}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};Zn.kind="func";var Fn=class extends Bn{render(e){return"return "+super.render(e)}};Fn.kind="return";var ms=class extends tt{render(e){let n="try"+super.render(e);return this.catch&&(n+=this.catch.render(e)),this.finally&&(n+=this.finally.render(e)),n}optimizeNodes(){var e,n;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(n=this.finally)===null||n===void 0||n.optimizeNodes(),this}optimizeNames(e,n){var o,r;return super.optimizeNames(e,n),(o=this.catch)===null||o===void 0||o.optimizeNames(e,n),(r=this.finally)===null||r===void 0||r.optimizeNames(e,n),this}get names(){let e=super.names;return this.catch&&_t(e,this.catch.names),this.finally&&_t(e,this.finally.names),e}},Un=class extends tt{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Un.kind="catch";var Wn=class extends tt{render(e){return"finally"+super.render(e)}};Wn.kind="finally";var fs=class{constructor(e,n={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...n,_n:n.lines?`
3
+ `:""},this._extScope=e,this._scope=new Me.Scope({parent:e}),this._nodes=[new hs]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,n){let o=this._extScope.value(e,n);return(this._values[o.prefix]||(this._values[o.prefix]=new Set)).add(o),o}getScopeValue(e,n){return this._extScope.getValue(e,n)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,n,o,r){let a=this._scope.toName(n);return o!==void 0&&r&&(this._constants[a.str]=o),this._leafNode(new as(e,a,o)),a}const(e,n,o){return this._def(Me.varKinds.const,e,n,o)}let(e,n,o){return this._def(Me.varKinds.let,e,n,o)}var(e,n,o){return this._def(Me.varKinds.var,e,n,o)}assign(e,n,o){return this._leafNode(new er(e,n,o))}add(e,n){return this._leafNode(new ss(e,A.operators.ADD,n))}code(e){return typeof e=="function"?e():e!==N.nil&&this._leafNode(new us(e)),this}object(...e){let n=["{"];for(let[o,r]of e)n.length>1&&n.push(","),n.push(o),(o!==r||this.opts.es5)&&(n.push(":"),(0,N.addCodeArg)(n,r));return n.push("}"),new N._Code(n)}if(e,n,o){if(this._blockNode(new xt(e)),n&&o)this.code(n).else().code(o).endIf();else if(n)this.code(n).endIf();else if(o)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new xt(e))}else(){return this._elseNode(new Ft)}endIf(){return this._endBlockNode(xt,Ft)}_for(e,n){return this._blockNode(e),n&&this.code(n).endFor(),this}for(e,n){return this._for(new ds(e),n)}forRange(e,n,o,r,a=this.opts.es5?Me.varKinds.var:Me.varKinds.let){let s=this._scope.toName(e);return this._for(new ps(a,s,n,o),()=>r(s))}forOf(e,n,o,r=Me.varKinds.const){let a=this._scope.toName(e);if(this.opts.es5){let s=n instanceof N.Name?n:this.var("_arr",n);return this.forRange("_i",0,(0,N._)`${s}.length`,i=>{this.var(a,(0,N._)`${s}[${i}]`),o(a)})}return this._for(new tr("of",r,a,n),()=>o(a))}forIn(e,n,o,r=this.opts.es5?Me.varKinds.var:Me.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,N._)`Object.keys(${n})`,o);let a=this._scope.toName(e);return this._for(new tr("in",r,a,n),()=>o(a))}endFor(){return this._endBlockNode(St)}label(e){return this._leafNode(new is(e))}break(e){return this._leafNode(new ls(e))}return(e){let n=new Fn;if(this._blockNode(n),this.code(e),n.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Fn)}try(e,n,o){if(!n&&!o)throw new Error('CodeGen: "try" without "catch" and "finally"');let r=new ms;if(this._blockNode(r),this.code(e),n){let a=this.name("e");this._currNode=r.catch=new Un(a),n(a)}return o&&(this._currNode=r.finally=new Wn,this.code(o)),this._endBlockNode(Un,Wn)}throw(e){return this._leafNode(new cs(e))}block(e,n){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(n),this}endBlock(e){let n=this._blockStarts.pop();if(n===void 0)throw new Error("CodeGen: not in self-balancing block");let o=this._nodes.length-n;if(o<0||e!==void 0&&o!==e)throw new Error(`CodeGen: wrong number of nodes: ${o} vs ${e} expected`);return this._nodes.length=n,this}func(e,n=N.nil,o,r){return this._blockNode(new Zn(e,n,o)),r&&this.code(r).endFunc(),this}endFunc(){return this._endBlockNode(Zn)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,n){let o=this._currNode;if(o instanceof e||n&&o instanceof n)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${n?`${e.kind}/${n.kind}`:e.kind}"`)}_elseNode(e){let n=this._currNode;if(!(n instanceof xt))throw new Error('CodeGen: "else" without "if"');return this._currNode=n.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let n=this._nodes;n[n.length-1]=e}};A.CodeGen=fs;function _t(t,e){for(let n in e)t[n]=(t[n]||0)+(e[n]||0);return t}function nr(t,e){return e instanceof N._CodeOrName?_t(t,e.names):t}function Ut(t,e,n){if(t instanceof N.Name)return o(t);if(!r(t))return t;return new N._Code(t._items.reduce((a,s)=>(s instanceof N.Name&&(s=o(s)),s instanceof N._Code?a.push(...s._items):a.push(s),a),[]));function o(a){let s=n[a.str];return s===void 0||e[a.str]!==1?a:(delete e[a.str],s)}function r(a){return a instanceof N._Code&&a._items.some(s=>s instanceof N.Name&&e[s.str]===1&&n[s.str]!==void 0)}}function Gy(t,e){for(let n in e)t[n]=(t[n]||0)-(e[n]||0)}function gd(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,N._)`!${gs(t)}`}A.not=gd;var Hy=wd(A.operators.AND);function Jy(...t){return t.reduce(Hy)}A.and=Jy;var Ky=wd(A.operators.OR);function Yy(...t){return t.reduce(Ky)}A.or=Yy;function wd(t){return(e,n)=>e===N.nil?n:n===N.nil?e:(0,N._)`${gs(e)} ${t} ${gs(n)}`}function gs(t){return t instanceof N.Name?t:(0,N._)`(${t})`}});var M=k(j=>{"use strict";Object.defineProperty(j,"__esModule",{value:!0});j.checkStrictMode=j.getErrorPath=j.Type=j.useFunc=j.setEvaluated=j.evaluatedPropsToName=j.mergeEvaluated=j.eachItem=j.unescapeJsonPointer=j.escapeJsonPointer=j.escapeFragment=j.unescapeFragment=j.schemaRefOrVal=j.schemaHasRulesButRef=j.schemaHasRules=j.checkUnknownRules=j.alwaysValidSchema=j.toHash=void 0;var W=R(),Xy=Ln();function Qy(t){let e={};for(let n of t)e[n]=!0;return e}j.toHash=Qy;function eb(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(kd(t,e),!vd(e,t.self.RULES.all))}j.alwaysValidSchema=eb;function kd(t,e=t.schema){let{opts:n,self:o}=t;if(!n.strictSchema||typeof e=="boolean")return;let r=o.RULES.keywords;for(let a in e)r[a]||_d(t,`unknown keyword: "${a}"`)}j.checkUnknownRules=kd;function vd(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(e[n])return!0;return!1}j.schemaHasRules=vd;function tb(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(n!=="$ref"&&e.all[n])return!0;return!1}j.schemaHasRulesButRef=tb;function nb({topSchemaRef:t,schemaPath:e},n,o,r){if(!r){if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="string")return(0,W._)`${n}`}return(0,W._)`${t}${e}${(0,W.getProperty)(o)}`}j.schemaRefOrVal=nb;function ob(t){return xd(decodeURIComponent(t))}j.unescapeFragment=ob;function rb(t){return encodeURIComponent(ys(t))}j.escapeFragment=rb;function ys(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}j.escapeJsonPointer=ys;function xd(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}j.unescapeJsonPointer=xd;function ab(t,e){if(Array.isArray(t))for(let n of t)e(n);else e(t)}j.eachItem=ab;function yd({mergeNames:t,mergeToName:e,mergeValues:n,resultToName:o}){return(r,a,s,i)=>{let l=s===void 0?a:s instanceof W.Name?(a instanceof W.Name?t(r,a,s):e(r,a,s),s):a instanceof W.Name?(e(r,s,a),a):n(a,s);return i===W.Name&&!(l instanceof W.Name)?o(r,l):l}}j.mergeEvaluated={props:yd({mergeNames:(t,e,n)=>t.if((0,W._)`${n} !== true && ${e} !== undefined`,()=>{t.if((0,W._)`${e} === true`,()=>t.assign(n,!0),()=>t.assign(n,(0,W._)`${n} || {}`).code((0,W._)`Object.assign(${n}, ${e})`))}),mergeToName:(t,e,n)=>t.if((0,W._)`${n} !== true`,()=>{e===!0?t.assign(n,!0):(t.assign(n,(0,W._)`${n} || {}`),bs(t,n,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Sd}),items:yd({mergeNames:(t,e,n)=>t.if((0,W._)`${n} !== true && ${e} !== undefined`,()=>t.assign(n,(0,W._)`${e} === true ? true : ${n} > ${e} ? ${n} : ${e}`)),mergeToName:(t,e,n)=>t.if((0,W._)`${n} !== true`,()=>t.assign(n,e===!0?!0:(0,W._)`${n} > ${e} ? ${n} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function Sd(t,e){if(e===!0)return t.var("props",!0);let n=t.var("props",(0,W._)`{}`);return e!==void 0&&bs(t,n,e),n}j.evaluatedPropsToName=Sd;function bs(t,e,n){Object.keys(n).forEach(o=>t.assign((0,W._)`${e}${(0,W.getProperty)(o)}`,!0))}j.setEvaluated=bs;var bd={};function sb(t,e){return t.scopeValue("func",{ref:e,code:bd[e.code]||(bd[e.code]=new Xy._Code(e.code))})}j.useFunc=sb;var ws;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(ws||(j.Type=ws={}));function ib(t,e,n){if(t instanceof W.Name){let o=e===ws.Num;return n?o?(0,W._)`"[" + ${t} + "]"`:(0,W._)`"['" + ${t} + "']"`:o?(0,W._)`"/" + ${t}`:(0,W._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return n?(0,W.getProperty)(t).toString():"/"+ys(t)}j.getErrorPath=ib;function _d(t,e,n=t.opts.strictSchema){if(n){if(e=`strict mode: ${e}`,n===!0)throw new Error(e);t.self.logger.warn(e)}}j.checkStrictMode=_d});var nt=k(ks=>{"use strict";Object.defineProperty(ks,"__esModule",{value:!0});var de=R(),lb={data:new de.Name("data"),valCxt:new de.Name("valCxt"),instancePath:new de.Name("instancePath"),parentData:new de.Name("parentData"),parentDataProperty:new de.Name("parentDataProperty"),rootData:new de.Name("rootData"),dynamicAnchors:new de.Name("dynamicAnchors"),vErrors:new de.Name("vErrors"),errors:new de.Name("errors"),this:new de.Name("this"),self:new de.Name("self"),scope:new de.Name("scope"),json:new de.Name("json"),jsonPos:new de.Name("jsonPos"),jsonLen:new de.Name("jsonLen"),jsonPart:new de.Name("jsonPart")};ks.default=lb});var Vn=k(pe=>{"use strict";Object.defineProperty(pe,"__esModule",{value:!0});pe.extendErrors=pe.resetErrorsCount=pe.reportExtraError=pe.reportError=pe.keyword$DataError=pe.keywordError=void 0;var L=R(),rr=M(),we=nt();pe.keywordError={message:({keyword:t})=>(0,L.str)`must pass "${t}" keyword validation`};pe.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,L.str)`"${t}" keyword must be ${e} ($data)`:(0,L.str)`"${t}" keyword is invalid ($data)`};function cb(t,e=pe.keywordError,n,o){let{it:r}=t,{gen:a,compositeRule:s,allErrors:i}=r,l=Td(t,e,n);o??(s||i)?Id(a,l):zd(r,(0,L._)`[${l}]`)}pe.reportError=cb;function ub(t,e=pe.keywordError,n){let{it:o}=t,{gen:r,compositeRule:a,allErrors:s}=o,i=Td(t,e,n);Id(r,i),a||s||zd(o,we.default.vErrors)}pe.reportExtraError=ub;function hb(t,e){t.assign(we.default.errors,e),t.if((0,L._)`${we.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,L._)`${we.default.vErrors}.length`,e),()=>t.assign(we.default.vErrors,null)))}pe.resetErrorsCount=hb;function db({gen:t,keyword:e,schemaValue:n,data:o,errsCount:r,it:a}){if(r===void 0)throw new Error("ajv implementation error");let s=t.name("err");t.forRange("i",r,we.default.errors,i=>{t.const(s,(0,L._)`${we.default.vErrors}[${i}]`),t.if((0,L._)`${s}.instancePath === undefined`,()=>t.assign((0,L._)`${s}.instancePath`,(0,L.strConcat)(we.default.instancePath,a.errorPath))),t.assign((0,L._)`${s}.schemaPath`,(0,L.str)`${a.errSchemaPath}/${e}`),a.opts.verbose&&(t.assign((0,L._)`${s}.schema`,n),t.assign((0,L._)`${s}.data`,o))})}pe.extendErrors=db;function Id(t,e){let n=t.const("err",e);t.if((0,L._)`${we.default.vErrors} === null`,()=>t.assign(we.default.vErrors,(0,L._)`[${n}]`),(0,L._)`${we.default.vErrors}.push(${n})`),t.code((0,L._)`${we.default.errors}++`)}function zd(t,e){let{gen:n,validateName:o,schemaEnv:r}=t;r.$async?n.throw((0,L._)`new ${t.ValidationError}(${e})`):(n.assign((0,L._)`${o}.errors`,e),n.return(!1))}var It={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 Td(t,e,n){let{createErrors:o}=t.it;return o===!1?(0,L._)`{}`:pb(t,e,n)}function pb(t,e,n={}){let{gen:o,it:r}=t,a=[mb(r,n),fb(t,n)];return gb(t,e,a),o.object(...a)}function mb({errorPath:t},{instancePath:e}){let n=e?(0,L.str)`${t}${(0,rr.getErrorPath)(e,rr.Type.Str)}`:t;return[we.default.instancePath,(0,L.strConcat)(we.default.instancePath,n)]}function fb({keyword:t,it:{errSchemaPath:e}},{schemaPath:n,parentSchema:o}){let r=o?e:(0,L.str)`${e}/${t}`;return n&&(r=(0,L.str)`${r}${(0,rr.getErrorPath)(n,rr.Type.Str)}`),[It.schemaPath,r]}function gb(t,{params:e,message:n},o){let{keyword:r,data:a,schemaValue:s,it:i}=t,{opts:l,propertyName:c,topSchemaRef:u,schemaPath:h}=i;o.push([It.keyword,r],[It.params,typeof e=="function"?e(t):e||(0,L._)`{}`]),l.messages&&o.push([It.message,typeof n=="function"?n(t):n]),l.verbose&&o.push([It.schema,s],[It.parentSchema,(0,L._)`${u}${h}`],[we.default.data,a]),c&&o.push([It.propertyName,c])}});var $d=k(Wt=>{"use strict";Object.defineProperty(Wt,"__esModule",{value:!0});Wt.boolOrEmptySchema=Wt.topBoolOrEmptySchema=void 0;var wb=Vn(),yb=R(),bb=nt(),kb={message:"boolean schema is false"};function vb(t){let{gen:e,schema:n,validateName:o}=t;n===!1?Cd(t,!1):typeof n=="object"&&n.$async===!0?e.return(bb.default.data):(e.assign((0,yb._)`${o}.errors`,null),e.return(!0))}Wt.topBoolOrEmptySchema=vb;function xb(t,e){let{gen:n,schema:o}=t;o===!1?(n.var(e,!1),Cd(t)):n.var(e,!0)}Wt.boolOrEmptySchema=xb;function Cd(t,e){let{gen:n,data:o}=t,r={gen:n,keyword:"false schema",data:o,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,wb.reportError)(r,kb,void 0,e)}});var vs=k(Vt=>{"use strict";Object.defineProperty(Vt,"__esModule",{value:!0});Vt.getRules=Vt.isJSONType=void 0;var Sb=["string","number","integer","boolean","null","object","array"],_b=new Set(Sb);function Ib(t){return typeof t=="string"&&_b.has(t)}Vt.isJSONType=Ib;function zb(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}Vt.getRules=zb});var xs=k(dt=>{"use strict";Object.defineProperty(dt,"__esModule",{value:!0});dt.shouldUseRule=dt.shouldUseGroup=dt.schemaHasRulesForType=void 0;function Tb({schema:t,self:e},n){let o=e.RULES.types[n];return o&&o!==!0&&Pd(t,o)}dt.schemaHasRulesForType=Tb;function Pd(t,e){return e.rules.some(n=>Ed(t,n))}dt.shouldUseGroup=Pd;function Ed(t,e){var n;return t[e.keyword]!==void 0||((n=e.definition.implements)===null||n===void 0?void 0:n.some(o=>t[o]!==void 0))}dt.shouldUseRule=Ed});var Gn=k(me=>{"use strict";Object.defineProperty(me,"__esModule",{value:!0});me.reportTypeError=me.checkDataTypes=me.checkDataType=me.coerceAndCheckDataType=me.getJSONTypes=me.getSchemaTypes=me.DataType=void 0;var Cb=vs(),$b=xs(),Pb=Vn(),E=R(),Rd=M(),Gt;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Gt||(me.DataType=Gt={}));function Eb(t){let e=Ad(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}me.getSchemaTypes=Eb;function Ad(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(Cb.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}me.getJSONTypes=Ad;function Rb(t,e){let{gen:n,data:o,opts:r}=t,a=Ab(e,r.coerceTypes),s=e.length>0&&!(a.length===0&&e.length===1&&(0,$b.schemaHasRulesForType)(t,e[0]));if(s){let i=_s(e,o,r.strictNumbers,Gt.Wrong);n.if(i,()=>{a.length?jb(t,e,a):Is(t)})}return s}me.coerceAndCheckDataType=Rb;var jd=new Set(["string","number","integer","boolean","null"]);function Ab(t,e){return e?t.filter(n=>jd.has(n)||e==="array"&&n==="array"):[]}function jb(t,e,n){let{gen:o,data:r,opts:a}=t,s=o.let("dataType",(0,E._)`typeof ${r}`),i=o.let("coerced",(0,E._)`undefined`);a.coerceTypes==="array"&&o.if((0,E._)`${s} == 'object' && Array.isArray(${r}) && ${r}.length == 1`,()=>o.assign(r,(0,E._)`${r}[0]`).assign(s,(0,E._)`typeof ${r}`).if(_s(e,r,a.strictNumbers),()=>o.assign(i,r))),o.if((0,E._)`${i} !== undefined`);for(let c of n)(jd.has(c)||c==="array"&&a.coerceTypes==="array")&&l(c);o.else(),Is(t),o.endIf(),o.if((0,E._)`${i} !== undefined`,()=>{o.assign(r,i),Db(t,i)});function l(c){switch(c){case"string":o.elseIf((0,E._)`${s} == "number" || ${s} == "boolean"`).assign(i,(0,E._)`"" + ${r}`).elseIf((0,E._)`${r} === null`).assign(i,(0,E._)`""`);return;case"number":o.elseIf((0,E._)`${s} == "boolean" || ${r} === null
4
4
  || (${s} == "string" && ${r} && ${r} == +${r})`).assign(i,(0,E._)`+${r}`);return;case"integer":o.elseIf((0,E._)`${s} === "boolean" || ${r} === null
5
5
  || (${s} === "string" && ${r} && ${r} == +${r} && !(${r} % 1))`).assign(i,(0,E._)`+${r}`);return;case"boolean":o.elseIf((0,E._)`${r} === "false" || ${r} === 0 || ${r} === null`).assign(i,!1).elseIf((0,E._)`${r} === "true" || ${r} === 1`).assign(i,!0);return;case"null":o.elseIf((0,E._)`${r} === "" || ${r} === 0 || ${r} === false`),o.assign(i,null);return;case"array":o.elseIf((0,E._)`${s} === "string" || ${s} === "number"
6
- || ${s} === "boolean" || ${r} === null`).assign(i,(0,E._)`[${r}]`)}}}function Cb({gen:t,parentData:e,parentDataProperty:n},o){t.if((0,E._)`${e} !== undefined`,()=>t.assign((0,E._)`${e}[${n}]`,o))}function bs(t,e,n,o=Vt.Correct){let r=o===Vt.Correct?E.operators.EQ:E.operators.NEQ,a;switch(t){case"null":return(0,E._)`${e} ${r} null`;case"array":a=(0,E._)`Array.isArray(${e})`;break;case"object":a=(0,E._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":a=s((0,E._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":a=s();break;default:return(0,E._)`typeof ${e} ${r} ${t}`}return o===Vt.Correct?a:(0,E.not)(a);function s(i=E.nil){return(0,E.and)((0,E._)`typeof ${e} == "number"`,i,n?(0,E._)`isFinite(${e})`:E.nil)}}me.checkDataType=bs;function ks(t,e,n,o){if(t.length===1)return bs(t[0],e,n,o);let r,a=(0,Td.toHash)(t);if(a.array&&a.object){let s=(0,E._)`typeof ${e} != "object"`;r=a.null?s:(0,E._)`!${e} || ${s}`,delete a.null,delete a.array,delete a.object}else r=E.nil;a.number&&delete a.integer;for(let s in a)r=(0,E.and)(r,bs(s,e,n,o));return r}me.checkDataTypes=ks;var Pb={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,E._)`{type: ${t}}`:(0,E._)`{type: ${e}}`};function vs(t){let e=Eb(t);(0,_b.reportError)(e,Pb)}me.reportTypeError=vs;function Eb(t){let{gen:e,data:n,schema:o}=t,r=(0,Td.schemaRefOrVal)(t,o,"type");return{gen:e,keyword:"type",data:n,schema:o.type,schemaCode:r,schemaValue:r,parentSchema:o,params:{},it:t}}});var Ed=k(or=>{"use strict";Object.defineProperty(or,"__esModule",{value:!0});or.assignDefaults=void 0;var Gt=R(),Rb=M();function Ab(t,e){let{properties:n,items:o}=t.schema;if(e==="object"&&n)for(let r in n)Pd(t,r,n[r].default);else e==="array"&&Array.isArray(o)&&o.forEach((r,a)=>Pd(t,a,r.default))}or.assignDefaults=Ab;function Pd(t,e,n){let{gen:o,compositeRule:r,data:a,opts:s}=t;if(n===void 0)return;let i=(0,Gt._)`${a}${(0,Gt.getProperty)(e)}`;if(r){(0,Rb.checkStrictMode)(t,`default is ignored for: ${i}`);return}let l=(0,Gt._)`${i} === undefined`;s.useDefaults==="empty"&&(l=(0,Gt._)`${l} || ${i} === null || ${i} === ""`),o.if(l,(0,Gt._)`${i} = ${(0,Gt.stringify)(n)}`)}});var De=k(F=>{"use strict";Object.defineProperty(F,"__esModule",{value:!0});F.validateUnion=F.validateArray=F.usePattern=F.callValidateCode=F.schemaProperties=F.allSchemaProperties=F.noPropertyInData=F.propertyInData=F.isOwnProperty=F.hasPropFunc=F.reportMissingProp=F.checkMissingProp=F.checkReportMissingProp=void 0;var K=R(),xs=M(),dt=tt(),Db=M();function Ob(t,e){let{gen:n,data:o,it:r}=t;n.if(_s(n,o,e,r.opts.ownProperties),()=>{t.setParams({missingProperty:(0,K._)`${e}`},!0),t.error()})}F.checkReportMissingProp=Ob;function jb({gen:t,data:e,it:{opts:n}},o,r){return(0,K.or)(...o.map(a=>(0,K.and)(_s(t,e,a,n.ownProperties),(0,K._)`${r} = ${a}`)))}F.checkMissingProp=jb;function Nb(t,e){t.setParams({missingProperty:e},!0),t.error()}F.reportMissingProp=Nb;function Rd(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,K._)`Object.prototype.hasOwnProperty`})}F.hasPropFunc=Rd;function Ss(t,e,n){return(0,K._)`${Rd(t)}.call(${e}, ${n})`}F.isOwnProperty=Ss;function qb(t,e,n,o){let r=(0,K._)`${e}${(0,K.getProperty)(n)} !== undefined`;return o?(0,K._)`${r} && ${Ss(t,e,n)}`:r}F.propertyInData=qb;function _s(t,e,n,o){let r=(0,K._)`${e}${(0,K.getProperty)(n)} === undefined`;return o?(0,K.or)(r,(0,K.not)(Ss(t,e,n))):r}F.noPropertyInData=_s;function Ad(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}F.allSchemaProperties=Ad;function Mb(t,e){return Ad(e).filter(n=>!(0,xs.alwaysValidSchema)(t,e[n]))}F.schemaProperties=Mb;function Lb({schemaCode:t,data:e,it:{gen:n,topSchemaRef:o,schemaPath:r,errorPath:a},it:s},i,l,c){let u=c?(0,K._)`${t}, ${e}, ${o}${r}`:e,h=[[dt.default.instancePath,(0,K.strConcat)(dt.default.instancePath,a)],[dt.default.parentData,s.parentData],[dt.default.parentDataProperty,s.parentDataProperty],[dt.default.rootData,dt.default.rootData]];s.opts.dynamicRef&&h.push([dt.default.dynamicAnchors,dt.default.dynamicAnchors]);let d=(0,K._)`${u}, ${n.object(...h)}`;return l!==K.nil?(0,K._)`${i}.call(${l}, ${d})`:(0,K._)`${i}(${d})`}F.callValidateCode=Lb;var Zb=(0,K._)`new RegExp`;function Bb({gen:t,it:{opts:e}},n){let o=e.unicodeRegExp?"u":"",{regExp:r}=e.code,a=r(n,o);return t.scopeValue("pattern",{key:a.toString(),ref:a,code:(0,K._)`${r.code==="new RegExp"?Zb:(0,Db.useFunc)(t,r)}(${n}, ${o})`})}F.usePattern=Bb;function Ub(t){let{gen:e,data:n,keyword:o,it:r}=t,a=e.name("valid");if(r.allErrors){let i=e.let("valid",!0);return s(()=>e.assign(i,!1)),i}return e.var(a,!0),s(()=>e.break()),a;function s(i){let l=e.const("len",(0,K._)`${n}.length`);e.forRange("i",0,l,c=>{t.subschema({keyword:o,dataProp:c,dataPropType:xs.Type.Num},a),e.if((0,K.not)(a),i)})}}F.validateArray=Ub;function Fb(t){let{gen:e,schema:n,keyword:o,it:r}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");if(n.some(l=>(0,xs.alwaysValidSchema)(r,l))&&!r.opts.unevaluated)return;let s=e.let("valid",!1),i=e.name("_valid");e.block(()=>n.forEach((l,c)=>{let u=t.subschema({keyword:o,schemaProp:c,compositeRule:!0},i);e.assign(s,(0,K._)`${s} || ${i}`),t.mergeValidEvaluated(u,i)||e.if((0,K.not)(s))})),t.result(s,()=>t.reset(),()=>t.error(!0))}F.validateUnion=Fb});var jd=k(Fe=>{"use strict";Object.defineProperty(Fe,"__esModule",{value:!0});Fe.validateKeywordUsage=Fe.validSchemaType=Fe.funcKeywordCode=Fe.macroKeywordCode=void 0;var ye=R(),It=tt(),Wb=De(),Vb=Fn();function Gb(t,e){let{gen:n,keyword:o,schema:r,parentSchema:a,it:s}=t,i=e.macro.call(s.self,r,a,s),l=Od(n,o,i);s.opts.validateSchema!==!1&&s.self.validateSchema(i,!0);let c=n.name("valid");t.subschema({schema:i,schemaPath:ye.nil,errSchemaPath:`${s.errSchemaPath}/${o}`,topSchemaRef:l,compositeRule:!0},c),t.pass(c,()=>t.error(!0))}Fe.macroKeywordCode=Gb;function Hb(t,e){var n;let{gen:o,keyword:r,schema:a,parentSchema:s,$data:i,it:l}=t;Kb(l,e);let c=!i&&e.compile?e.compile.call(l.self,a,s,l):e.validate,u=Od(o,r,c),h=o.let("valid");t.block$data(h,d),t.ok((n=e.valid)!==null&&n!==void 0?n:h);function d(){if(e.errors===!1)w(),e.modifying&&Dd(t),y(()=>t.error());else{let b=e.async?p():m();e.modifying&&Dd(t),y(()=>Jb(t,b))}}function p(){let b=o.let("ruleErrs",null);return o.try(()=>w((0,ye._)`await `),z=>o.assign(h,!1).if((0,ye._)`${z} instanceof ${l.ValidationError}`,()=>o.assign(b,(0,ye._)`${z}.errors`),()=>o.throw(z))),b}function m(){let b=(0,ye._)`${u}.errors`;return o.assign(b,null),w(ye.nil),b}function w(b=e.async?(0,ye._)`await `:ye.nil){let z=l.opts.passContext?It.default.this:It.default.self,S=!("compile"in e&&!i||e.schema===!1);o.assign(h,(0,ye._)`${b}${(0,Wb.callValidateCode)(t,u,z,S)}`,e.modifying)}function y(b){var z;o.if((0,ye.not)((z=e.valid)!==null&&z!==void 0?z:h),b)}}Fe.funcKeywordCode=Hb;function Dd(t){let{gen:e,data:n,it:o}=t;e.if(o.parentData,()=>e.assign(n,(0,ye._)`${o.parentData}[${o.parentDataProperty}]`))}function Jb(t,e){let{gen:n}=t;n.if((0,ye._)`Array.isArray(${e})`,()=>{n.assign(It.default.vErrors,(0,ye._)`${It.default.vErrors} === null ? ${e} : ${It.default.vErrors}.concat(${e})`).assign(It.default.errors,(0,ye._)`${It.default.vErrors}.length`),(0,Vb.extendErrors)(t)},()=>t.error())}function Kb({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Od(t,e,n){if(n===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof n=="function"?{ref:n}:{ref:n,code:(0,ye.stringify)(n)})}function Yb(t,e,n=!1){return!e.length||e.some(o=>o==="array"?Array.isArray(t):o==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==o||n&&typeof t>"u")}Fe.validSchemaType=Yb;function Xb({schema:t,opts:e,self:n,errSchemaPath:o},r,a){if(Array.isArray(r.keyword)?!r.keyword.includes(a):r.keyword!==a)throw new Error("ajv implementation error");let s=r.dependencies;if(s?.some(i=>!Object.prototype.hasOwnProperty.call(t,i)))throw new Error(`parent schema must have dependencies of ${a}: ${s.join(",")}`);if(r.validateSchema&&!r.validateSchema(t[a])){let l=`keyword "${a}" value is invalid at path "${o}": `+n.errorsText(r.validateSchema.errors);if(e.validateSchema==="log")n.logger.error(l);else throw new Error(l)}}Fe.validateKeywordUsage=Xb});var qd=k(pt=>{"use strict";Object.defineProperty(pt,"__esModule",{value:!0});pt.extendSubschemaMode=pt.extendSubschemaData=pt.getSubschema=void 0;var We=R(),Nd=M();function Qb(t,{keyword:e,schemaProp:n,schema:o,schemaPath:r,errSchemaPath:a,topSchemaRef:s}){if(e!==void 0&&o!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let i=t.schema[e];return n===void 0?{schema:i,schemaPath:(0,We._)`${t.schemaPath}${(0,We.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:i[n],schemaPath:(0,We._)`${t.schemaPath}${(0,We.getProperty)(e)}${(0,We.getProperty)(n)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Nd.escapeFragment)(n)}`}}if(o!==void 0){if(r===void 0||a===void 0||s===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:o,schemaPath:r,topSchemaRef:s,errSchemaPath:a}}throw new Error('either "keyword" or "schema" must be passed')}pt.getSubschema=Qb;function ek(t,e,{dataProp:n,dataPropType:o,data:r,dataTypes:a,propertyName:s}){if(r!==void 0&&n!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:i}=e;if(n!==void 0){let{errorPath:c,dataPathArr:u,opts:h}=e,d=i.let("data",(0,We._)`${e.data}${(0,We.getProperty)(n)}`,!0);l(d),t.errorPath=(0,We.str)`${c}${(0,Nd.getErrorPath)(n,o,h.jsPropertySyntax)}`,t.parentDataProperty=(0,We._)`${n}`,t.dataPathArr=[...u,t.parentDataProperty]}if(r!==void 0){let c=r instanceof We.Name?r:i.let("data",r,!0);l(c),s!==void 0&&(t.propertyName=s)}a&&(t.dataTypes=a);function l(c){t.data=c,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,c]}}pt.extendSubschemaData=ek;function tk(t,{jtdDiscriminator:e,jtdMetadata:n,compositeRule:o,createErrors:r,allErrors:a}){o!==void 0&&(t.compositeRule=o),r!==void 0&&(t.createErrors=r),a!==void 0&&(t.allErrors=a),t.jtdDiscriminator=e,t.jtdMetadata=n}pt.extendSubschemaMode=tk});var Is=k((sP,Md)=>{"use strict";Md.exports=function t(e,n){if(e===n)return!0;if(e&&n&&typeof e=="object"&&typeof n=="object"){if(e.constructor!==n.constructor)return!1;var o,r,a;if(Array.isArray(e)){if(o=e.length,o!=n.length)return!1;for(r=o;r--!==0;)if(!t(e[r],n[r]))return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if(a=Object.keys(e),o=a.length,o!==Object.keys(n).length)return!1;for(r=o;r--!==0;)if(!Object.prototype.hasOwnProperty.call(n,a[r]))return!1;for(r=o;r--!==0;){var s=a[r];if(!t(e[s],n[s]))return!1}return!0}return e!==e&&n!==n}});var Zd=k((iP,Ld)=>{"use strict";var mt=Ld.exports=function(t,e,n){typeof e=="function"&&(n=e,e={}),n=e.cb||n;var o=typeof n=="function"?n:n.pre||function(){},r=n.post||function(){};rr(e,o,r,t,"",t)};mt.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};mt.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};mt.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};mt.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 rr(t,e,n,o,r,a,s,i,l,c){if(o&&typeof o=="object"&&!Array.isArray(o)){e(o,r,a,s,i,l,c);for(var u in o){var h=o[u];if(Array.isArray(h)){if(u in mt.arrayKeywords)for(var d=0;d<h.length;d++)rr(t,e,n,h[d],r+"/"+u+"/"+d,a,r,u,o,d)}else if(u in mt.propsKeywords){if(h&&typeof h=="object")for(var p in h)rr(t,e,n,h[p],r+"/"+u+"/"+nk(p),a,r,u,o,p)}else(u in mt.keywords||t.allKeys&&!(u in mt.skipKeywords))&&rr(t,e,n,h,r+"/"+u,a,r,u,o)}n(o,r,a,s,i,l,c)}}function nk(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Vn=k(xe=>{"use strict";Object.defineProperty(xe,"__esModule",{value:!0});xe.getSchemaRefs=xe.resolveUrl=xe.normalizeId=xe._getFullPath=xe.getFullPath=xe.inlineRef=void 0;var ok=M(),rk=Is(),ak=Zd(),sk=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function ik(t,e=!0){return typeof t=="boolean"?!0:e===!0?!zs(t):e?Bd(t)<=e:!1}xe.inlineRef=ik;var lk=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function zs(t){for(let e in t){if(lk.has(e))return!0;let n=t[e];if(Array.isArray(n)&&n.some(zs)||typeof n=="object"&&zs(n))return!0}return!1}function Bd(t){let e=0;for(let n in t){if(n==="$ref")return 1/0;if(e++,!sk.has(n)&&(typeof t[n]=="object"&&(0,ok.eachItem)(t[n],o=>e+=Bd(o)),e===1/0))return 1/0}return e}function Ud(t,e="",n){n!==!1&&(e=Ht(e));let o=t.parse(e);return Fd(t,o)}xe.getFullPath=Ud;function Fd(t,e){return t.serialize(e).split("#")[0]+"#"}xe._getFullPath=Fd;var ck=/#\/?$/;function Ht(t){return t?t.replace(ck,""):""}xe.normalizeId=Ht;function uk(t,e,n){return n=Ht(n),t.resolve(e,n)}xe.resolveUrl=uk;var hk=/^[a-z_][-a-z0-9._]*$/i;function dk(t,e){if(typeof t=="boolean")return{};let{schemaId:n,uriResolver:o}=this.opts,r=Ht(t[n]||e),a={"":r},s=Ud(o,r,!1),i={},l=new Set;return ak(t,{allKeys:!0},(h,d,p,m)=>{if(m===void 0)return;let w=s+d,y=a[m];typeof h[n]=="string"&&(y=b.call(this,h[n])),z.call(this,h.$anchor),z.call(this,h.$dynamicAnchor),a[d]=y;function b(S){let T=this.opts.uriResolver.resolve;if(S=Ht(y?T(y,S):S),l.has(S))throw u(S);l.add(S);let x=this.refs[S];return typeof x=="string"&&(x=this.refs[x]),typeof x=="object"?c(h,x.schema,S):S!==Ht(w)&&(S[0]==="#"?(c(h,i[S],S),i[S]=h):this.refs[S]=w),S}function z(S){if(typeof S=="string"){if(!hk.test(S))throw new Error(`invalid anchor "${S}"`);b.call(this,`#${S}`)}}}),i;function c(h,d,p){if(d!==void 0&&!rk(h,d))throw u(p)}function u(h){return new Error(`reference "${h}" resolves to more than one schema`)}}xe.getSchemaRefs=dk});var Jn=k(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.getData=ft.KeywordCxt=ft.validateFunctionCode=void 0;var Jd=_d(),Wd=Wn(),$s=ys(),ar=Wn(),pk=Ed(),Hn=jd(),Ts=qd(),I=R(),C=tt(),mk=Vn(),nt=M(),Gn=Fn();function fk(t){if(Xd(t)&&(Qd(t),Yd(t))){yk(t);return}Kd(t,()=>(0,Jd.topBoolOrEmptySchema)(t))}ft.validateFunctionCode=fk;function Kd({gen:t,validateName:e,schema:n,schemaEnv:o,opts:r},a){r.code.es5?t.func(e,(0,I._)`${C.default.data}, ${C.default.valCxt}`,o.$async,()=>{t.code((0,I._)`"use strict"; ${Vd(n,r)}`),wk(t,r),t.code(a)}):t.func(e,(0,I._)`${C.default.data}, ${gk(r)}`,o.$async,()=>t.code(Vd(n,r)).code(a))}function gk(t){return(0,I._)`{${C.default.instancePath}="", ${C.default.parentData}, ${C.default.parentDataProperty}, ${C.default.rootData}=${C.default.data}${t.dynamicRef?(0,I._)`, ${C.default.dynamicAnchors}={}`:I.nil}}={}`}function wk(t,e){t.if(C.default.valCxt,()=>{t.var(C.default.instancePath,(0,I._)`${C.default.valCxt}.${C.default.instancePath}`),t.var(C.default.parentData,(0,I._)`${C.default.valCxt}.${C.default.parentData}`),t.var(C.default.parentDataProperty,(0,I._)`${C.default.valCxt}.${C.default.parentDataProperty}`),t.var(C.default.rootData,(0,I._)`${C.default.valCxt}.${C.default.rootData}`),e.dynamicRef&&t.var(C.default.dynamicAnchors,(0,I._)`${C.default.valCxt}.${C.default.dynamicAnchors}`)},()=>{t.var(C.default.instancePath,(0,I._)`""`),t.var(C.default.parentData,(0,I._)`undefined`),t.var(C.default.parentDataProperty,(0,I._)`undefined`),t.var(C.default.rootData,C.default.data),e.dynamicRef&&t.var(C.default.dynamicAnchors,(0,I._)`{}`)})}function yk(t){let{schema:e,opts:n,gen:o}=t;Kd(t,()=>{n.$comment&&e.$comment&&tp(t),Sk(t),o.let(C.default.vErrors,null),o.let(C.default.errors,0),n.unevaluated&&bk(t),ep(t),zk(t)})}function bk(t){let{gen:e,validateName:n}=t;t.evaluated=e.const("evaluated",(0,I._)`${n}.evaluated`),e.if((0,I._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,I._)`${t.evaluated}.props`,(0,I._)`undefined`)),e.if((0,I._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,I._)`${t.evaluated}.items`,(0,I._)`undefined`))}function Vd(t,e){let n=typeof t=="object"&&t[e.schemaId];return n&&(e.code.source||e.code.process)?(0,I._)`/*# sourceURL=${n} */`:I.nil}function kk(t,e){if(Xd(t)&&(Qd(t),Yd(t))){vk(t,e);return}(0,Jd.boolOrEmptySchema)(t,e)}function Yd({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let n in t)if(e.RULES.all[n])return!0;return!1}function Xd(t){return typeof t.schema!="boolean"}function vk(t,e){let{schema:n,gen:o,opts:r}=t;r.$comment&&n.$comment&&tp(t),_k(t),Ik(t);let a=o.const("_errs",C.default.errors);ep(t,a),o.var(e,(0,I._)`${a} === ${C.default.errors}`)}function Qd(t){(0,nt.checkUnknownRules)(t),xk(t)}function ep(t,e){if(t.opts.jtd)return Gd(t,[],!1,e);let n=(0,Wd.getSchemaTypes)(t.schema),o=(0,Wd.coerceAndCheckDataType)(t,n);Gd(t,n,!o,e)}function xk(t){let{schema:e,errSchemaPath:n,opts:o,self:r}=t;e.$ref&&o.ignoreKeywordsWithRef&&(0,nt.schemaHasRulesButRef)(e,r.RULES)&&r.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function Sk(t){let{schema:e,opts:n}=t;e.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,nt.checkStrictMode)(t,"default is ignored in the schema root")}function _k(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,mk.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function Ik(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function tp({gen:t,schemaEnv:e,schema:n,errSchemaPath:o,opts:r}){let a=n.$comment;if(r.$comment===!0)t.code((0,I._)`${C.default.self}.logger.log(${a})`);else if(typeof r.$comment=="function"){let s=(0,I.str)`${o}/$comment`,i=t.scopeValue("root",{ref:e.root});t.code((0,I._)`${C.default.self}.opts.$comment(${a}, ${s}, ${i}.schema)`)}}function zk(t){let{gen:e,schemaEnv:n,validateName:o,ValidationError:r,opts:a}=t;n.$async?e.if((0,I._)`${C.default.errors} === 0`,()=>e.return(C.default.data),()=>e.throw((0,I._)`new ${r}(${C.default.vErrors})`)):(e.assign((0,I._)`${o}.errors`,C.default.vErrors),a.unevaluated&&Tk(t),e.return((0,I._)`${C.default.errors} === 0`))}function Tk({gen:t,evaluated:e,props:n,items:o}){n instanceof I.Name&&t.assign((0,I._)`${e}.props`,n),o instanceof I.Name&&t.assign((0,I._)`${e}.items`,o)}function Gd(t,e,n,o){let{gen:r,schema:a,data:s,allErrors:i,opts:l,self:c}=t,{RULES:u}=c;if(a.$ref&&(l.ignoreKeywordsWithRef||!(0,nt.schemaHasRulesButRef)(a,u))){r.block(()=>op(t,"$ref",u.all.$ref.definition));return}l.jtd||$k(t,e),r.block(()=>{for(let d of u.rules)h(d);h(u.post)});function h(d){(0,$s.shouldUseGroup)(a,d)&&(d.type?(r.if((0,ar.checkDataType)(d.type,s,l.strictNumbers)),Hd(t,d),e.length===1&&e[0]===d.type&&n&&(r.else(),(0,ar.reportTypeError)(t)),r.endIf()):Hd(t,d),i||r.if((0,I._)`${C.default.errors} === ${o||0}`))}}function Hd(t,e){let{gen:n,schema:o,opts:{useDefaults:r}}=t;r&&(0,pk.assignDefaults)(t,e.type),n.block(()=>{for(let a of e.rules)(0,$s.shouldUseRule)(o,a)&&op(t,a.keyword,a.definition,e.type)})}function $k(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(Ck(t,e),t.opts.allowUnionTypes||Pk(t,e),Ek(t,t.dataTypes))}function Ck(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(n=>{np(t.dataTypes,n)||Cs(t,`type "${n}" not allowed by context "${t.dataTypes.join(",")}"`)}),Ak(t,e)}}function Pk(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Cs(t,"use allowUnionTypes to allow union type keyword")}function Ek(t,e){let n=t.self.RULES.all;for(let o in n){let r=n[o];if(typeof r=="object"&&(0,$s.shouldUseRule)(t.schema,r)){let{type:a}=r.definition;a.length&&!a.some(s=>Rk(e,s))&&Cs(t,`missing type "${a.join(",")}" for keyword "${o}"`)}}}function Rk(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function np(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function Ak(t,e){let n=[];for(let o of t.dataTypes)np(e,o)?n.push(o):e.includes("integer")&&o==="number"&&n.push("integer");t.dataTypes=n}function Cs(t,e){let n=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${n}" (strictTypes)`,(0,nt.checkStrictMode)(t,e,t.opts.strictTypes)}var sr=class{constructor(e,n,o){if((0,Hn.validateKeywordUsage)(e,n,o),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=o,this.data=e.data,this.schema=e.schema[o],this.$data=n.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,nt.schemaRefOrVal)(e,this.schema,o,this.$data),this.schemaType=n.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=n,this.$data)this.schemaCode=e.gen.const("vSchema",rp(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Hn.validSchemaType)(this.schema,n.schemaType,n.allowUndefined))throw new Error(`${o} value must be ${JSON.stringify(n.schemaType)}`);("code"in n?n.trackErrors:n.errors!==!1)&&(this.errsCount=e.gen.const("_errs",C.default.errors))}result(e,n,o){this.failResult((0,I.not)(e),n,o)}failResult(e,n,o){this.gen.if(e),o?o():this.error(),n?(this.gen.else(),n(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,n){this.failResult((0,I.not)(e),void 0,n)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:n}=this;this.fail((0,I._)`${n} !== undefined && (${(0,I.or)(this.invalid$data(),e)})`)}error(e,n,o){if(n){this.setParams(n),this._error(e,o),this.setParams({});return}this._error(e,o)}_error(e,n){(e?Gn.reportExtraError:Gn.reportError)(this,this.def.error,n)}$dataError(){(0,Gn.reportError)(this,this.def.$dataError||Gn.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Gn.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,n){n?Object.assign(this.params,e):this.params=e}block$data(e,n,o=I.nil){this.gen.block(()=>{this.check$data(e,o),n()})}check$data(e=I.nil,n=I.nil){if(!this.$data)return;let{gen:o,schemaCode:r,schemaType:a,def:s}=this;o.if((0,I.or)((0,I._)`${r} === undefined`,n)),e!==I.nil&&o.assign(e,!0),(a.length||s.validateSchema)&&(o.elseIf(this.invalid$data()),this.$dataError(),e!==I.nil&&o.assign(e,!1)),o.else()}invalid$data(){let{gen:e,schemaCode:n,schemaType:o,def:r,it:a}=this;return(0,I.or)(s(),i());function s(){if(o.length){if(!(n instanceof I.Name))throw new Error("ajv implementation error");let l=Array.isArray(o)?o:[o];return(0,I._)`${(0,ar.checkDataTypes)(l,n,a.opts.strictNumbers,ar.DataType.Wrong)}`}return I.nil}function i(){if(r.validateSchema){let l=e.scopeValue("validate$data",{ref:r.validateSchema});return(0,I._)`!${l}(${n})`}return I.nil}}subschema(e,n){let o=(0,Ts.getSubschema)(this.it,e);(0,Ts.extendSubschemaData)(o,this.it,e),(0,Ts.extendSubschemaMode)(o,e);let r={...this.it,...o,items:void 0,props:void 0};return kk(r,n),r}mergeEvaluated(e,n){let{it:o,gen:r}=this;o.opts.unevaluated&&(o.props!==!0&&e.props!==void 0&&(o.props=nt.mergeEvaluated.props(r,e.props,o.props,n)),o.items!==!0&&e.items!==void 0&&(o.items=nt.mergeEvaluated.items(r,e.items,o.items,n)))}mergeValidEvaluated(e,n){let{it:o,gen:r}=this;if(o.opts.unevaluated&&(o.props!==!0||o.items!==!0))return r.if(n,()=>this.mergeEvaluated(e,I.Name)),!0}};ft.KeywordCxt=sr;function op(t,e,n,o){let r=new sr(t,n,e);"code"in n?n.code(r,o):r.$data&&n.validate?(0,Hn.funcKeywordCode)(r,n):"macro"in n?(0,Hn.macroKeywordCode)(r,n):(n.compile||n.validate)&&(0,Hn.funcKeywordCode)(r,n)}var Dk=/^\/(?:[^~]|~0|~1)*$/,Ok=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function rp(t,{dataLevel:e,dataNames:n,dataPathArr:o}){let r,a;if(t==="")return C.default.rootData;if(t[0]==="/"){if(!Dk.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);r=t,a=C.default.rootData}else{let c=Ok.exec(t);if(!c)throw new Error(`Invalid JSON-pointer: ${t}`);let u=+c[1];if(r=c[2],r==="#"){if(u>=e)throw new Error(l("property/index",u));return o[e-u]}if(u>e)throw new Error(l("data",u));if(a=n[e-u],!r)return a}let s=a,i=r.split("/");for(let c of i)c&&(a=(0,I._)`${a}${(0,I.getProperty)((0,nt.unescapeJsonPointer)(c))}`,s=(0,I._)`${s} && ${a}`);return s;function l(c,u){return`Cannot access ${c} ${u} levels up, current level is ${e}`}}ft.getData=rp});var ir=k(Es=>{"use strict";Object.defineProperty(Es,"__esModule",{value:!0});var Ps=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Es.default=Ps});var Kn=k(Ds=>{"use strict";Object.defineProperty(Ds,"__esModule",{value:!0});var Rs=Vn(),As=class extends Error{constructor(e,n,o,r){super(r||`can't resolve reference ${o} from id ${n}`),this.missingRef=(0,Rs.resolveUrl)(e,n,o),this.missingSchema=(0,Rs.normalizeId)((0,Rs.getFullPath)(e,this.missingRef))}};Ds.default=As});var cr=k(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.resolveSchema=Oe.getCompilingSchema=Oe.resolveRef=Oe.compileSchema=Oe.SchemaEnv=void 0;var Me=R(),jk=ir(),zt=tt(),Le=Vn(),ap=M(),Nk=Jn(),Jt=class{constructor(e){var n;this.refs={},this.dynamicAnchors={};let o;typeof e.schema=="object"&&(o=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(n=e.baseId)!==null&&n!==void 0?n:(0,Le.normalizeId)(o?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=o?.$async,this.refs={}}};Oe.SchemaEnv=Jt;function js(t){let e=sp.call(this,t);if(e)return e;let n=(0,Le.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:o,lines:r}=this.opts.code,{ownProperties:a}=this.opts,s=new Me.CodeGen(this.scope,{es5:o,lines:r,ownProperties:a}),i;t.$async&&(i=s.scopeValue("Error",{ref:jk.default,code:(0,Me._)`require("ajv/dist/runtime/validation_error").default`}));let l=s.scopeName("validate");t.validateName=l;let c={gen:s,allErrors:this.opts.allErrors,data:zt.default.data,parentData:zt.default.parentData,parentDataProperty:zt.default.parentDataProperty,dataNames:[zt.default.data],dataPathArr:[Me.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,Me.stringify)(t.schema)}:{ref:t.schema}),validateName:l,ValidationError:i,schema:t.schema,schemaEnv:t,rootId:n,baseId:t.baseId||n,schemaPath:Me.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Me._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(t),(0,Nk.validateFunctionCode)(c),s.optimize(this.opts.code.optimize);let h=s.toString();u=`${s.scopeRefs(zt.default.scope)}return ${h}`,this.opts.code.process&&(u=this.opts.code.process(u,t));let p=new Function(`${zt.default.self}`,`${zt.default.scope}`,u)(this,this.scope.get());if(this.scope.value(l,{ref:p}),p.errors=null,p.schema=t.schema,p.schemaEnv=t,t.$async&&(p.$async=!0),this.opts.code.source===!0&&(p.source={validateName:l,validateCode:h,scopeValues:s._values}),this.opts.unevaluated){let{props:m,items:w}=c;p.evaluated={props:m instanceof Me.Name?void 0:m,items:w instanceof Me.Name?void 0:w,dynamicProps:m instanceof Me.Name,dynamicItems:w instanceof Me.Name},p.source&&(p.source.evaluated=(0,Me.stringify)(p.evaluated))}return t.validate=p,t}catch(h){throw delete t.validate,delete t.validateName,u&&this.logger.error("Error compiling schema, function code:",u),h}finally{this._compilations.delete(t)}}Oe.compileSchema=js;function qk(t,e,n){var o;n=(0,Le.resolveUrl)(this.opts.uriResolver,e,n);let r=t.refs[n];if(r)return r;let a=Zk.call(this,t,n);if(a===void 0){let s=(o=t.localRefs)===null||o===void 0?void 0:o[n],{schemaId:i}=this.opts;s&&(a=new Jt({schema:s,schemaId:i,root:t,baseId:e}))}if(a!==void 0)return t.refs[n]=Mk.call(this,a)}Oe.resolveRef=qk;function Mk(t){return(0,Le.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:js.call(this,t)}function sp(t){for(let e of this._compilations)if(Lk(e,t))return e}Oe.getCompilingSchema=sp;function Lk(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function Zk(t,e){let n;for(;typeof(n=this.refs[e])=="string";)e=n;return n||this.schemas[e]||lr.call(this,t,e)}function lr(t,e){let n=this.opts.uriResolver.parse(e),o=(0,Le._getFullPath)(this.opts.uriResolver,n),r=(0,Le.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&o===r)return Os.call(this,n,t);let a=(0,Le.normalizeId)(o),s=this.refs[a]||this.schemas[a];if(typeof s=="string"){let i=lr.call(this,t,s);return typeof i?.schema!="object"?void 0:Os.call(this,n,i)}if(typeof s?.schema=="object"){if(s.validate||js.call(this,s),a===(0,Le.normalizeId)(e)){let{schema:i}=s,{schemaId:l}=this.opts,c=i[l];return c&&(r=(0,Le.resolveUrl)(this.opts.uriResolver,r,c)),new Jt({schema:i,schemaId:l,root:t,baseId:r})}return Os.call(this,n,s)}}Oe.resolveSchema=lr;var Bk=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Os(t,{baseId:e,schema:n,root:o}){var r;if(((r=t.fragment)===null||r===void 0?void 0:r[0])!=="/")return;for(let i of t.fragment.slice(1).split("/")){if(typeof n=="boolean")return;let l=n[(0,ap.unescapeFragment)(i)];if(l===void 0)return;n=l;let c=typeof n=="object"&&n[this.opts.schemaId];!Bk.has(i)&&c&&(e=(0,Le.resolveUrl)(this.opts.uriResolver,e,c))}let a;if(typeof n!="boolean"&&n.$ref&&!(0,ap.schemaHasRulesButRef)(n,this.RULES)){let i=(0,Le.resolveUrl)(this.opts.uriResolver,e,n.$ref);a=lr.call(this,o,i)}let{schemaId:s}=this.opts;if(a=a||new Jt({schema:n,schemaId:s,root:o,baseId:e}),a.schema!==a.root.schema)return a}});var ip=k((pP,Uk)=>{Uk.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 Ms=k((mP,pp)=>{"use strict";var Fk=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),cp=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),Ns=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),up=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),Wk=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function qs(t){let e="",n=0,o=0;for(o=0;o<t.length;o++)if(n=t[o].charCodeAt(0),n!==48){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";e+=t[o];break}for(o+=1;o<t.length;o++){if(n=t[o].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";e+=t[o]}return e}var Vk=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function lp(t){return t.length=0,!0}function Gk(t,e,n){if(t.length){let o=qs(t);if(o!=="")e.push(o);else return n.error=!0,!1;t.length=0}return!0}function Hk(t){let e=0,n={error:!1,address:"",zone:""},o=[],r=[],a=!1,s=!1,i=Gk;for(let l=0;l<t.length;l++){let c=t[l];if(!(c==="["||c==="]"))if(c===":"){if(a===!0&&(s=!0),!i(r,o,n))break;if(++e>7){n.error=!0;break}l>0&&t[l-1]===":"&&(a=!0),o.push(":");continue}else if(c==="%"){if(!i(r,o,n))break;i=lp}else{r.push(c);continue}}return r.length&&(i===lp?n.zone=r.join(""):s?o.push(r.join("")):o.push(qs(r))),n.address=o.join(""),n}function hp(t){if(Jk(t,":")<2)return{host:t,isIPV6:!1};let e=Hk(t);if(e.error)return{host:t,isIPV6:!1};{let n=e.address,o=e.address;return e.zone&&(n+="%"+e.zone,o+="%25"+e.zone),{host:n,isIPV6:!0,escapedHost:o}}}function Jk(t,e){let n=0;for(let o=0;o<t.length;o++)t[o]===e&&n++;return n}function Kk(t){let e=t,n=[],o=-1,r=0;for(;r=e.length;){if(r===1){if(e===".")break;if(e==="/"){n.push("/");break}else{n.push(e);break}}else if(r===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){n.push("/");break}}else if(r===3&&e==="/.."){n.length!==0&&n.pop(),n.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),n.length!==0&&n.pop();continue}}if((o=e.indexOf("/",1))===-1){n.push(e);break}else n.push(e.slice(0,o)),e=e.slice(o)}return n.join("")}var Yk={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},Xk=/[@/?#:]/g,Qk=/[@/?#]/g;function dp(t,e){let n=e?Qk:Xk;return n.lastIndex=0,t.replace(n,o=>Yk[o])}function ev(t,e=!1){if(t.indexOf("%")===-1)return t;let n="";for(let o=0;o<t.length;o++){if(t[o]==="%"&&o+2<t.length){let r=t.slice(o+1,o+3);if(Ns(r)){let a=r.toUpperCase(),s=String.fromCharCode(parseInt(a,16));e&&up(s)?n+=s:n+="%"+a,o+=2;continue}}n+=t[o]}return n}function tv(t){let e="";for(let n=0;n<t.length;n++){if(t[n]==="%"&&n+2<t.length){let o=t.slice(n+1,n+3);if(Ns(o)){let r=o.toUpperCase(),a=String.fromCharCode(parseInt(r,16));a!=="."&&up(a)?e+=a:e+="%"+r,n+=2;continue}}Wk(t[n])?e+=t[n]:e+=escape(t[n])}return e}function nv(t){let e="";for(let n=0;n<t.length;n++){if(t[n]==="%"&&n+2<t.length){let o=t.slice(n+1,n+3);if(Ns(o)){e+="%"+o.toUpperCase(),n+=2;continue}}e+=escape(t[n])}return e}function ov(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let n=unescape(t.host);if(!cp(n)){let o=hp(n);o.isIPV6===!0?n=`[${o.escapedHost}]`:n=dp(n,!1)}e.push(n)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}pp.exports={nonSimpleDomain:Vk,recomposeAuthority:ov,reescapeHostDelimiters:dp,normalizePercentEncoding:ev,normalizePathEncoding:tv,escapePreservingEscapes:nv,removeDotSegments:Kk,isIPv4:cp,isUUID:Fk,normalizeIPv6:hp,stringArrayToHexStripped:qs}});var yp=k((fP,wp)=>{"use strict";var{isUUID:rv}=Ms(),av=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,sv=["http","https","ws","wss","urn","urn:uuid"];function iv(t){return sv.indexOf(t)!==-1}function Ls(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function mp(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function fp(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function lv(t){return t.secure=Ls(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function cv(t){if((t.port===(Ls(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,n]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=n,t.resourceName=void 0}return t.fragment=void 0,t}function uv(t,e){if(!t.path)return t.error="URN can not be parsed",t;let n=t.path.match(av);if(n){let o=e.scheme||t.scheme||"urn";t.nid=n[1].toLowerCase(),t.nss=n[2];let r=`${o}:${e.nid||t.nid}`,a=Zs(r);t.path=void 0,a&&(t=a.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function hv(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let n=e.scheme||t.scheme||"urn",o=t.nid.toLowerCase(),r=`${n}:${e.nid||o}`,a=Zs(r);a&&(t=a.serialize(t,e));let s=t,i=t.nss;return s.path=`${o||e.nid}:${i}`,e.skipEscape=!0,s}function dv(t,e){let n=t;return n.uuid=n.nss,n.nss=void 0,!e.tolerant&&(!n.uuid||!rv(n.uuid))&&(n.error=n.error||"UUID is not valid."),n}function pv(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var gp={scheme:"http",domainHost:!0,parse:mp,serialize:fp},mv={scheme:"https",domainHost:gp.domainHost,parse:mp,serialize:fp},ur={scheme:"ws",domainHost:!0,parse:lv,serialize:cv},fv={scheme:"wss",domainHost:ur.domainHost,parse:ur.parse,serialize:ur.serialize},gv={scheme:"urn",parse:uv,serialize:hv,skipNormalize:!0},wv={scheme:"urn:uuid",parse:dv,serialize:pv,skipNormalize:!0},hr={http:gp,https:mv,ws:ur,wss:fv,urn:gv,"urn:uuid":wv};Object.setPrototypeOf(hr,null);function Zs(t){return t&&(hr[t]||hr[t.toLowerCase()])||void 0}wp.exports={wsIsSecure:Ls,SCHEMES:hr,isValidSchemeName:iv,getSchemeHandler:Zs}});var _p=k((gP,dr)=>{"use strict";var{normalizeIPv6:yv,removeDotSegments:Yn,recomposeAuthority:bv,normalizePercentEncoding:kv,normalizePathEncoding:vv,escapePreservingEscapes:xv,reescapeHostDelimiters:Sv,isIPv4:_v,nonSimpleDomain:Iv}=Ms(),{SCHEMES:zv,getSchemeHandler:kp}=yp();function Tv(t,e){return typeof t=="string"?t=Rv(t,e):typeof t=="object"&&(t=Kt(Tt(t,e),e)),t}function $v(t,e,n){let o=n?Object.assign({scheme:"null"},n):{scheme:"null"},r=vp(Kt(t,o),Kt(e,o),o,!0);return o.skipEscape=!0,Tt(r,o)}function vp(t,e,n,o){let r={};return o||(t=Kt(Tt(t,n),n),e=Kt(Tt(e,n),n)),n=n||{},!n.tolerant&&e.scheme?(r.scheme=e.scheme,r.userinfo=e.userinfo,r.host=e.host,r.port=e.port,r.path=Yn(e.path||""),r.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(r.userinfo=e.userinfo,r.host=e.host,r.port=e.port,r.path=Yn(e.path||""),r.query=e.query):(e.path?(e.path[0]==="/"?r.path=Yn(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?r.path="/"+e.path:t.path?r.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:r.path=e.path,r.path=Yn(r.path)),r.query=e.query):(r.path=t.path,e.query!==void 0?r.query=e.query:r.query=t.query),r.userinfo=t.userinfo,r.host=t.host,r.port=t.port),r.scheme=t.scheme),r.fragment=e.fragment,r}function Cv(t,e,n){let o=bp(t,n),r=bp(e,n);return o!==void 0&&r!==void 0&&o.toLowerCase()===r.toLowerCase()}function Tt(t,e){let n={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},o=Object.assign({},e),r=[],a=kp(o.scheme||n.scheme);a&&a.serialize&&a.serialize(n,o),n.path!==void 0&&(o.skipEscape?n.path=kv(n.path):(n.path=xv(n.path),n.scheme!==void 0&&(n.path=n.path.split("%3A").join(":")))),o.reference!=="suffix"&&n.scheme&&r.push(n.scheme,":");let s=bv(n);if(s!==void 0&&(o.reference!=="suffix"&&r.push("//"),r.push(s),n.path&&n.path[0]!=="/"&&r.push("/")),n.path!==void 0){let i=n.path;!o.absolutePath&&(!a||!a.absolutePath)&&(i=Yn(i)),s===void 0&&i[0]==="/"&&i[1]==="/"&&(i="/%2F"+i.slice(2)),r.push(i)}return n.query!==void 0&&r.push("?",n.query),n.fragment!==void 0&&r.push("#",n.fragment),r.join("")}var Pv=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function Ev(t,e){if(e[2]!==void 0&&t.path&&t.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof t.port=="number"&&(t.port<0||t.port>65535))return"URI port is malformed."}function xp(t,e){let n=Object.assign({},e),o={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},r=!1,a=!1;n.reference==="suffix"&&(n.scheme?t=n.scheme+":"+t:t="//"+t);let s=t.match(Pv);if(s){o.scheme=s[1],o.userinfo=s[3],o.host=s[4],o.port=parseInt(s[5],10),o.path=s[6]||"",o.query=s[7],o.fragment=s[8],isNaN(o.port)&&(o.port=s[5]);let i=Ev(o,s);if(i!==void 0&&(o.error=o.error||i,r=!0),o.host)if(_v(o.host)===!1){let u=yv(o.host);o.host=u.host.toLowerCase(),a=u.isIPV6}else a=!0;o.scheme===void 0&&o.userinfo===void 0&&o.host===void 0&&o.port===void 0&&o.query===void 0&&!o.path?o.reference="same-document":o.scheme===void 0?o.reference="relative":o.fragment===void 0?o.reference="absolute":o.reference="uri",n.reference&&n.reference!=="suffix"&&n.reference!==o.reference&&(o.error=o.error||"URI is not a "+n.reference+" reference.");let l=kp(n.scheme||o.scheme);if(!n.unicodeSupport&&(!l||!l.unicodeSupport)&&o.host&&(n.domainHost||l&&l.domainHost)&&a===!1&&Iv(o.host))try{o.host=URL.domainToASCII(o.host.toLowerCase())}catch(c){o.error=o.error||"Host's domain name can not be converted to ASCII: "+c}if((!l||l&&!l.skipNormalize)&&(t.indexOf("%")!==-1&&(o.scheme!==void 0&&(o.scheme=unescape(o.scheme)),o.host!==void 0&&(o.host=Sv(unescape(o.host),a))),o.path&&(o.path=vv(o.path)),o.fragment))try{o.fragment=encodeURI(decodeURIComponent(o.fragment))}catch{o.error=o.error||"URI malformed"}l&&l.parse&&l.parse(o,n)}else o.error=o.error||"URI can not be parsed.";return{parsed:o,malformedAuthorityOrPort:r}}function Kt(t,e){return xp(t,e).parsed}function Rv(t,e){return Sp(t,e).normalized}function Sp(t,e){let{parsed:n,malformedAuthorityOrPort:o}=xp(t,e);return{normalized:o?t:Tt(n,e),malformedAuthorityOrPort:o}}function bp(t,e){if(typeof t=="string"){let{normalized:n,malformedAuthorityOrPort:o}=Sp(t,e);return o?void 0:n}if(typeof t=="object")return Tt(t,e)}var Bs={SCHEMES:zv,normalize:Tv,resolve:$v,resolveComponent:vp,equal:Cv,serialize:Tt,parse:Kt};dr.exports=Bs;dr.exports.default=Bs;dr.exports.fastUri=Bs});var zp=k(Us=>{"use strict";Object.defineProperty(Us,"__esModule",{value:!0});var Ip=_p();Ip.code='require("ajv/dist/runtime/uri").default';Us.default=Ip});var Dp=k(ue=>{"use strict";Object.defineProperty(ue,"__esModule",{value:!0});ue.CodeGen=ue.Name=ue.nil=ue.stringify=ue.str=ue._=ue.KeywordCxt=void 0;var Av=Jn();Object.defineProperty(ue,"KeywordCxt",{enumerable:!0,get:function(){return Av.KeywordCxt}});var Yt=R();Object.defineProperty(ue,"_",{enumerable:!0,get:function(){return Yt._}});Object.defineProperty(ue,"str",{enumerable:!0,get:function(){return Yt.str}});Object.defineProperty(ue,"stringify",{enumerable:!0,get:function(){return Yt.stringify}});Object.defineProperty(ue,"nil",{enumerable:!0,get:function(){return Yt.nil}});Object.defineProperty(ue,"Name",{enumerable:!0,get:function(){return Yt.Name}});Object.defineProperty(ue,"CodeGen",{enumerable:!0,get:function(){return Yt.CodeGen}});var Dv=ir(),Ep=Kn(),Ov=ws(),Xn=cr(),jv=R(),Qn=Vn(),pr=Wn(),Ws=M(),Tp=ip(),Nv=zp(),Rp=(t,e)=>new RegExp(t,e);Rp.code="new RegExp";var qv=["removeAdditional","useDefaults","coerceTypes"],Mv=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),Lv={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."},Zv={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},$p=200;function Bv(t){var e,n,o,r,a,s,i,l,c,u,h,d,p,m,w,y,b,z,S,T,x,Ie,Ce,sn,Dr;let ln=t.strict,Or=(e=t.code)===null||e===void 0?void 0:e.optimize,Fi=Or===!0||Or===void 0?1:Or||0,Wi=(o=(n=t.code)===null||n===void 0?void 0:n.regExp)!==null&&o!==void 0?o:Rp,sf=(r=t.uriResolver)!==null&&r!==void 0?r:Nv.default;return{strictSchema:(s=(a=t.strictSchema)!==null&&a!==void 0?a:ln)!==null&&s!==void 0?s:!0,strictNumbers:(l=(i=t.strictNumbers)!==null&&i!==void 0?i:ln)!==null&&l!==void 0?l:!0,strictTypes:(u=(c=t.strictTypes)!==null&&c!==void 0?c:ln)!==null&&u!==void 0?u:"log",strictTuples:(d=(h=t.strictTuples)!==null&&h!==void 0?h:ln)!==null&&d!==void 0?d:"log",strictRequired:(m=(p=t.strictRequired)!==null&&p!==void 0?p:ln)!==null&&m!==void 0?m:!1,code:t.code?{...t.code,optimize:Fi,regExp:Wi}:{optimize:Fi,regExp:Wi},loopRequired:(w=t.loopRequired)!==null&&w!==void 0?w:$p,loopEnum:(y=t.loopEnum)!==null&&y!==void 0?y:$p,meta:(b=t.meta)!==null&&b!==void 0?b:!0,messages:(z=t.messages)!==null&&z!==void 0?z:!0,inlineRefs:(S=t.inlineRefs)!==null&&S!==void 0?S:!0,schemaId:(T=t.schemaId)!==null&&T!==void 0?T:"$id",addUsedSchema:(x=t.addUsedSchema)!==null&&x!==void 0?x:!0,validateSchema:(Ie=t.validateSchema)!==null&&Ie!==void 0?Ie:!0,validateFormats:(Ce=t.validateFormats)!==null&&Ce!==void 0?Ce:!0,unicodeRegExp:(sn=t.unicodeRegExp)!==null&&sn!==void 0?sn:!0,int32range:(Dr=t.int32range)!==null&&Dr!==void 0?Dr:!0,uriResolver:sf}}var eo=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...Bv(e)};let{es5:n,lines:o}=this.opts.code;this.scope=new jv.ValueScope({scope:{},prefixes:Mv,es5:n,lines:o}),this.logger=Hv(e.logger);let r=e.validateFormats;e.validateFormats=!1,this.RULES=(0,Ov.getRules)(),Cp.call(this,Lv,e,"NOT SUPPORTED"),Cp.call(this,Zv,e,"DEPRECATED","warn"),this._metaOpts=Vv.call(this),e.formats&&Fv.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&Wv.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),Uv.call(this),e.validateFormats=r}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:n,schemaId:o}=this.opts,r=Tp;o==="id"&&(r={...Tp},r.id=r.$id,delete r.$id),n&&e&&this.addMetaSchema(r,r[o],!1)}defaultMeta(){let{meta:e,schemaId:n}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[n]||e:void 0}validate(e,n){let o;if(typeof e=="string"){if(o=this.getSchema(e),!o)throw new Error(`no schema with key or ref "${e}"`)}else o=this.compile(e);let r=o(n);return"$async"in o||(this.errors=o.errors),r}compile(e,n){let o=this._addSchema(e,n);return o.validate||this._compileSchemaEnv(o)}compileAsync(e,n){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:o}=this.opts;return r.call(this,e,n);async function r(u,h){await a.call(this,u.$schema);let d=this._addSchema(u,h);return d.validate||s.call(this,d)}async function a(u){u&&!this.getSchema(u)&&await r.call(this,{$ref:u},!0)}async function s(u){try{return this._compileSchemaEnv(u)}catch(h){if(!(h instanceof Ep.default))throw h;return i.call(this,h),await l.call(this,h.missingSchema),s.call(this,u)}}function i({missingSchema:u,missingRef:h}){if(this.refs[u])throw new Error(`AnySchema ${u} is loaded but ${h} cannot be resolved`)}async function l(u){let h=await c.call(this,u);this.refs[u]||await a.call(this,h.$schema),this.refs[u]||this.addSchema(h,u,n)}async function c(u){let h=this._loading[u];if(h)return h;try{return await(this._loading[u]=o(u))}finally{delete this._loading[u]}}}addSchema(e,n,o,r=this.opts.validateSchema){if(Array.isArray(e)){for(let s of e)this.addSchema(s,void 0,o,r);return this}let a;if(typeof e=="object"){let{schemaId:s}=this.opts;if(a=e[s],a!==void 0&&typeof a!="string")throw new Error(`schema ${s} must be string`)}return n=(0,Qn.normalizeId)(n||a),this._checkUnique(n),this.schemas[n]=this._addSchema(e,o,n,r,!0),this}addMetaSchema(e,n,o=this.opts.validateSchema){return this.addSchema(e,n,!0,o),this}validateSchema(e,n){if(typeof e=="boolean")return!0;let o;if(o=e.$schema,o!==void 0&&typeof o!="string")throw new Error("$schema must be a string");if(o=o||this.opts.defaultMeta||this.defaultMeta(),!o)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let r=this.validate(o,e);if(!r&&n){let a="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(a);else throw new Error(a)}return r}getSchema(e){let n;for(;typeof(n=Pp.call(this,e))=="string";)e=n;if(n===void 0){let{schemaId:o}=this.opts,r=new Xn.SchemaEnv({schema:{},schemaId:o});if(n=Xn.resolveSchema.call(this,r,e),!n)return;this.refs[e]=n}return n.validate||this._compileSchemaEnv(n)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let n=Pp.call(this,e);return typeof n=="object"&&this._cache.delete(n.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let n=e;this._cache.delete(n);let o=e[this.opts.schemaId];return o&&(o=(0,Qn.normalizeId)(o),delete this.schemas[o],delete this.refs[o]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let n of e)this.addKeyword(n);return this}addKeyword(e,n){let o;if(typeof e=="string")o=e,typeof n=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),n.keyword=o);else if(typeof e=="object"&&n===void 0){if(n=e,o=n.keyword,Array.isArray(o)&&!o.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(Kv.call(this,o,n),!n)return(0,Ws.eachItem)(o,a=>Fs.call(this,a)),this;Xv.call(this,n);let r={...n,type:(0,pr.getJSONTypes)(n.type),schemaType:(0,pr.getJSONTypes)(n.schemaType)};return(0,Ws.eachItem)(o,r.type.length===0?a=>Fs.call(this,a,r):a=>r.type.forEach(s=>Fs.call(this,a,r,s))),this}getKeyword(e){let n=this.RULES.all[e];return typeof n=="object"?n.definition:!!n}removeKeyword(e){let{RULES:n}=this;delete n.keywords[e],delete n.all[e];for(let o of n.rules){let r=o.rules.findIndex(a=>a.keyword===e);r>=0&&o.rules.splice(r,1)}return this}addFormat(e,n){return typeof n=="string"&&(n=new RegExp(n)),this.formats[e]=n,this}errorsText(e=this.errors,{separator:n=", ",dataVar:o="data"}={}){return!e||e.length===0?"No errors":e.map(r=>`${o}${r.instancePath} ${r.message}`).reduce((r,a)=>r+n+a)}$dataMetaSchema(e,n){let o=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let r of n){let a=r.split("/").slice(1),s=e;for(let i of a)s=s[i];for(let i in o){let l=o[i];if(typeof l!="object")continue;let{$data:c}=l.definition,u=s[i];c&&u&&(s[i]=Ap(u))}}return e}_removeAllSchemas(e,n){for(let o in e){let r=e[o];(!n||n.test(o))&&(typeof r=="string"?delete e[o]:r&&!r.meta&&(this._cache.delete(r.schema),delete e[o]))}}_addSchema(e,n,o,r=this.opts.validateSchema,a=this.opts.addUsedSchema){let s,{schemaId:i}=this.opts;if(typeof e=="object")s=e[i];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let l=this._cache.get(e);if(l!==void 0)return l;o=(0,Qn.normalizeId)(s||o);let c=Qn.getSchemaRefs.call(this,e,o);return l=new Xn.SchemaEnv({schema:e,schemaId:i,meta:n,baseId:o,localRefs:c}),this._cache.set(l.schema,l),a&&!o.startsWith("#")&&(o&&this._checkUnique(o),this.refs[o]=l),r&&this.validateSchema(e,!0),l}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):Xn.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let n=this.opts;this.opts=this._metaOpts;try{Xn.compileSchema.call(this,e)}finally{this.opts=n}}};eo.ValidationError=Dv.default;eo.MissingRefError=Ep.default;ue.default=eo;function Cp(t,e,n,o="error"){for(let r in t){let a=r;a in e&&this.logger[o](`${n}: option ${r}. ${t[a]}`)}}function Pp(t){return t=(0,Qn.normalizeId)(t),this.schemas[t]||this.refs[t]}function Uv(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function Fv(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function Wv(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let n=t[e];n.keyword||(n.keyword=e),this.addKeyword(n)}}function Vv(){let t={...this.opts};for(let e of qv)delete t[e];return t}var Gv={log(){},warn(){},error(){}};function Hv(t){if(t===!1)return Gv;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var Jv=/^[a-z_$][a-z0-9_$:-]*$/i;function Kv(t,e){let{RULES:n}=this;if((0,Ws.eachItem)(t,o=>{if(n.keywords[o])throw new Error(`Keyword ${o} is already defined`);if(!Jv.test(o))throw new Error(`Keyword ${o} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function Fs(t,e,n){var o;let r=e?.post;if(n&&r)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:a}=this,s=r?a.post:a.rules.find(({type:l})=>l===n);if(s||(s={type:n,rules:[]},a.rules.push(s)),a.keywords[t]=!0,!e)return;let i={keyword:t,definition:{...e,type:(0,pr.getJSONTypes)(e.type),schemaType:(0,pr.getJSONTypes)(e.schemaType)}};e.before?Yv.call(this,s,i,e.before):s.rules.push(i),a.all[t]=i,(o=e.implements)===null||o===void 0||o.forEach(l=>this.addKeyword(l))}function Yv(t,e,n){let o=t.rules.findIndex(r=>r.keyword===n);o>=0?t.rules.splice(o,0,e):(t.rules.push(e),this.logger.warn(`rule ${n} is not defined`))}function Xv(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=Ap(e)),t.validateSchema=this.compile(e,!0))}var Qv={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Ap(t){return{anyOf:[t,Qv]}}});var Op=k(Vs=>{"use strict";Object.defineProperty(Vs,"__esModule",{value:!0});var ex={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Vs.default=ex});var Mp=k($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.callRef=$t.getValidate=void 0;var tx=Kn(),jp=De(),Se=R(),Xt=tt(),Np=cr(),mr=M(),nx={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:n,it:o}=t,{baseId:r,schemaEnv:a,validateName:s,opts:i,self:l}=o,{root:c}=a;if((n==="#"||n==="#/")&&r===c.baseId)return h();let u=Np.resolveRef.call(l,c,r,n);if(u===void 0)throw new tx.default(o.opts.uriResolver,r,n);if(u instanceof Np.SchemaEnv)return d(u);return p(u);function h(){if(a===c)return fr(t,s,a,a.$async);let m=e.scopeValue("root",{ref:c});return fr(t,(0,Se._)`${m}.validate`,c,c.$async)}function d(m){let w=qp(t,m);fr(t,w,m,m.$async)}function p(m){let w=e.scopeValue("schema",i.code.source===!0?{ref:m,code:(0,Se.stringify)(m)}:{ref:m}),y=e.name("valid"),b=t.subschema({schema:m,dataTypes:[],schemaPath:Se.nil,topSchemaRef:w,errSchemaPath:n},y);t.mergeEvaluated(b),t.ok(y)}}};function qp(t,e){let{gen:n}=t;return e.validate?n.scopeValue("validate",{ref:e.validate}):(0,Se._)`${n.scopeValue("wrapper",{ref:e})}.validate`}$t.getValidate=qp;function fr(t,e,n,o){let{gen:r,it:a}=t,{allErrors:s,schemaEnv:i,opts:l}=a,c=l.passContext?Xt.default.this:Se.nil;o?u():h();function u(){if(!i.$async)throw new Error("async schema referenced by sync schema");let m=r.let("valid");r.try(()=>{r.code((0,Se._)`await ${(0,jp.callValidateCode)(t,e,c)}`),p(e),s||r.assign(m,!0)},w=>{r.if((0,Se._)`!(${w} instanceof ${a.ValidationError})`,()=>r.throw(w)),d(w),s||r.assign(m,!1)}),t.ok(m)}function h(){t.result((0,jp.callValidateCode)(t,e,c),()=>p(e),()=>d(e))}function d(m){let w=(0,Se._)`${m}.errors`;r.assign(Xt.default.vErrors,(0,Se._)`${Xt.default.vErrors} === null ? ${w} : ${Xt.default.vErrors}.concat(${w})`),r.assign(Xt.default.errors,(0,Se._)`${Xt.default.vErrors}.length`)}function p(m){var w;if(!a.opts.unevaluated)return;let y=(w=n?.validate)===null||w===void 0?void 0:w.evaluated;if(a.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(a.props=mr.mergeEvaluated.props(r,y.props,a.props));else{let b=r.var("props",(0,Se._)`${m}.evaluated.props`);a.props=mr.mergeEvaluated.props(r,b,a.props,Se.Name)}if(a.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(a.items=mr.mergeEvaluated.items(r,y.items,a.items));else{let b=r.var("items",(0,Se._)`${m}.evaluated.items`);a.items=mr.mergeEvaluated.items(r,b,a.items,Se.Name)}}}$t.callRef=fr;$t.default=nx});var Lp=k(Gs=>{"use strict";Object.defineProperty(Gs,"__esModule",{value:!0});var ox=Op(),rx=Mp(),ax=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",ox.default,rx.default];Gs.default=ax});var Zp=k(Hs=>{"use strict";Object.defineProperty(Hs,"__esModule",{value:!0});var gr=R(),gt=gr.operators,wr={maximum:{okStr:"<=",ok:gt.LTE,fail:gt.GT},minimum:{okStr:">=",ok:gt.GTE,fail:gt.LT},exclusiveMaximum:{okStr:"<",ok:gt.LT,fail:gt.GTE},exclusiveMinimum:{okStr:">",ok:gt.GT,fail:gt.LTE}},sx={message:({keyword:t,schemaCode:e})=>(0,gr.str)`must be ${wr[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,gr._)`{comparison: ${wr[t].okStr}, limit: ${e}}`},ix={keyword:Object.keys(wr),type:"number",schemaType:"number",$data:!0,error:sx,code(t){let{keyword:e,data:n,schemaCode:o}=t;t.fail$data((0,gr._)`${n} ${wr[e].fail} ${o} || isNaN(${n})`)}};Hs.default=ix});var Bp=k(Js=>{"use strict";Object.defineProperty(Js,"__esModule",{value:!0});var to=R(),lx={message:({schemaCode:t})=>(0,to.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,to._)`{multipleOf: ${t}}`},cx={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:lx,code(t){let{gen:e,data:n,schemaCode:o,it:r}=t,a=r.opts.multipleOfPrecision,s=e.let("res"),i=a?(0,to._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${a}`:(0,to._)`${s} !== parseInt(${s})`;t.fail$data((0,to._)`(${o} === 0 || (${s} = ${n}/${o}, ${i}))`)}};Js.default=cx});var Fp=k(Ks=>{"use strict";Object.defineProperty(Ks,"__esModule",{value:!0});function Up(t){let e=t.length,n=0,o=0,r;for(;o<e;)n++,r=t.charCodeAt(o++),r>=55296&&r<=56319&&o<e&&(r=t.charCodeAt(o),(r&64512)===56320&&o++);return n}Ks.default=Up;Up.code='require("ajv/dist/runtime/ucs2length").default'});var Wp=k(Ys=>{"use strict";Object.defineProperty(Ys,"__esModule",{value:!0});var Ct=R(),ux=M(),hx=Fp(),dx={message({keyword:t,schemaCode:e}){let n=t==="maxLength"?"more":"fewer";return(0,Ct.str)`must NOT have ${n} than ${e} characters`},params:({schemaCode:t})=>(0,Ct._)`{limit: ${t}}`},px={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:dx,code(t){let{keyword:e,data:n,schemaCode:o,it:r}=t,a=e==="maxLength"?Ct.operators.GT:Ct.operators.LT,s=r.opts.unicode===!1?(0,Ct._)`${n}.length`:(0,Ct._)`${(0,ux.useFunc)(t.gen,hx.default)}(${n})`;t.fail$data((0,Ct._)`${s} ${a} ${o}`)}};Ys.default=px});var Vp=k(Xs=>{"use strict";Object.defineProperty(Xs,"__esModule",{value:!0});var mx=De(),fx=M(),Qt=R(),gx={message:({schemaCode:t})=>(0,Qt.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Qt._)`{pattern: ${t}}`},wx={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:gx,code(t){let{gen:e,data:n,$data:o,schema:r,schemaCode:a,it:s}=t,i=s.opts.unicodeRegExp?"u":"";if(o){let{regExp:l}=s.opts.code,c=l.code==="new RegExp"?(0,Qt._)`new RegExp`:(0,fx.useFunc)(e,l),u=e.let("valid");e.try(()=>e.assign(u,(0,Qt._)`${c}(${a}, ${i}).test(${n})`),()=>e.assign(u,!1)),t.fail$data((0,Qt._)`!${u}`)}else{let l=(0,mx.usePattern)(t,r);t.fail$data((0,Qt._)`!${l}.test(${n})`)}}};Xs.default=wx});var Gp=k(Qs=>{"use strict";Object.defineProperty(Qs,"__esModule",{value:!0});var no=R(),yx={message({keyword:t,schemaCode:e}){let n=t==="maxProperties"?"more":"fewer";return(0,no.str)`must NOT have ${n} than ${e} properties`},params:({schemaCode:t})=>(0,no._)`{limit: ${t}}`},bx={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:yx,code(t){let{keyword:e,data:n,schemaCode:o}=t,r=e==="maxProperties"?no.operators.GT:no.operators.LT;t.fail$data((0,no._)`Object.keys(${n}).length ${r} ${o}`)}};Qs.default=bx});var Hp=k(ei=>{"use strict";Object.defineProperty(ei,"__esModule",{value:!0});var oo=De(),ro=R(),kx=M(),vx={message:({params:{missingProperty:t}})=>(0,ro.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,ro._)`{missingProperty: ${t}}`},xx={keyword:"required",type:"object",schemaType:"array",$data:!0,error:vx,code(t){let{gen:e,schema:n,schemaCode:o,data:r,$data:a,it:s}=t,{opts:i}=s;if(!a&&n.length===0)return;let l=n.length>=i.loopRequired;if(s.allErrors?c():u(),i.strictRequired){let p=t.parentSchema.properties,{definedProperties:m}=t.it;for(let w of n)if(p?.[w]===void 0&&!m.has(w)){let y=s.schemaEnv.baseId+s.errSchemaPath,b=`required property "${w}" is not defined at "${y}" (strictRequired)`;(0,kx.checkStrictMode)(s,b,s.opts.strictRequired)}}function c(){if(l||a)t.block$data(ro.nil,h);else for(let p of n)(0,oo.checkReportMissingProp)(t,p)}function u(){let p=e.let("missing");if(l||a){let m=e.let("valid",!0);t.block$data(m,()=>d(p,m)),t.ok(m)}else e.if((0,oo.checkMissingProp)(t,n,p)),(0,oo.reportMissingProp)(t,p),e.else()}function h(){e.forOf("prop",o,p=>{t.setParams({missingProperty:p}),e.if((0,oo.noPropertyInData)(e,r,p,i.ownProperties),()=>t.error())})}function d(p,m){t.setParams({missingProperty:p}),e.forOf(p,o,()=>{e.assign(m,(0,oo.propertyInData)(e,r,p,i.ownProperties)),e.if((0,ro.not)(m),()=>{t.error(),e.break()})},ro.nil)}}};ei.default=xx});var Jp=k(ti=>{"use strict";Object.defineProperty(ti,"__esModule",{value:!0});var ao=R(),Sx={message({keyword:t,schemaCode:e}){let n=t==="maxItems"?"more":"fewer";return(0,ao.str)`must NOT have ${n} than ${e} items`},params:({schemaCode:t})=>(0,ao._)`{limit: ${t}}`},_x={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:Sx,code(t){let{keyword:e,data:n,schemaCode:o}=t,r=e==="maxItems"?ao.operators.GT:ao.operators.LT;t.fail$data((0,ao._)`${n}.length ${r} ${o}`)}};ti.default=_x});var yr=k(ni=>{"use strict";Object.defineProperty(ni,"__esModule",{value:!0});var Kp=Is();Kp.code='require("ajv/dist/runtime/equal").default';ni.default=Kp});var Yp=k(ri=>{"use strict";Object.defineProperty(ri,"__esModule",{value:!0});var oi=Wn(),he=R(),Ix=M(),zx=yr(),Tx={message:({params:{i:t,j:e}})=>(0,he.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,he._)`{i: ${t}, j: ${e}}`},$x={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:Tx,code(t){let{gen:e,data:n,$data:o,schema:r,parentSchema:a,schemaCode:s,it:i}=t;if(!o&&!r)return;let l=e.let("valid"),c=a.items?(0,oi.getSchemaTypes)(a.items):[];t.block$data(l,u,(0,he._)`${s} === false`),t.ok(l);function u(){let m=e.let("i",(0,he._)`${n}.length`),w=e.let("j");t.setParams({i:m,j:w}),e.assign(l,!0),e.if((0,he._)`${m} > 1`,()=>(h()?d:p)(m,w))}function h(){return c.length>0&&!c.some(m=>m==="object"||m==="array")}function d(m,w){let y=e.name("item"),b=(0,oi.checkDataTypes)(c,y,i.opts.strictNumbers,oi.DataType.Wrong),z=e.const("indices",(0,he._)`{}`);e.for((0,he._)`;${m}--;`,()=>{e.let(y,(0,he._)`${n}[${m}]`),e.if(b,(0,he._)`continue`),c.length>1&&e.if((0,he._)`typeof ${y} == "string"`,(0,he._)`${y} += "_"`),e.if((0,he._)`typeof ${z}[${y}] == "number"`,()=>{e.assign(w,(0,he._)`${z}[${y}]`),t.error(),e.assign(l,!1).break()}).code((0,he._)`${z}[${y}] = ${m}`)})}function p(m,w){let y=(0,Ix.useFunc)(e,zx.default),b=e.name("outer");e.label(b).for((0,he._)`;${m}--;`,()=>e.for((0,he._)`${w} = ${m}; ${w}--;`,()=>e.if((0,he._)`${y}(${n}[${m}], ${n}[${w}])`,()=>{t.error(),e.assign(l,!1).break(b)})))}}};ri.default=$x});var Xp=k(si=>{"use strict";Object.defineProperty(si,"__esModule",{value:!0});var ai=R(),Cx=M(),Px=yr(),Ex={message:"must be equal to constant",params:({schemaCode:t})=>(0,ai._)`{allowedValue: ${t}}`},Rx={keyword:"const",$data:!0,error:Ex,code(t){let{gen:e,data:n,$data:o,schemaCode:r,schema:a}=t;o||a&&typeof a=="object"?t.fail$data((0,ai._)`!${(0,Cx.useFunc)(e,Px.default)}(${n}, ${r})`):t.fail((0,ai._)`${a} !== ${n}`)}};si.default=Rx});var Qp=k(ii=>{"use strict";Object.defineProperty(ii,"__esModule",{value:!0});var so=R(),Ax=M(),Dx=yr(),Ox={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,so._)`{allowedValues: ${t}}`},jx={keyword:"enum",schemaType:"array",$data:!0,error:Ox,code(t){let{gen:e,data:n,$data:o,schema:r,schemaCode:a,it:s}=t;if(!o&&r.length===0)throw new Error("enum must have non-empty array");let i=r.length>=s.opts.loopEnum,l,c=()=>l??(l=(0,Ax.useFunc)(e,Dx.default)),u;if(i||o)u=e.let("valid"),t.block$data(u,h);else{if(!Array.isArray(r))throw new Error("ajv implementation error");let p=e.const("vSchema",a);u=(0,so.or)(...r.map((m,w)=>d(p,w)))}t.pass(u);function h(){e.assign(u,!1),e.forOf("v",a,p=>e.if((0,so._)`${c()}(${n}, ${p})`,()=>e.assign(u,!0).break()))}function d(p,m){let w=r[m];return typeof w=="object"&&w!==null?(0,so._)`${c()}(${n}, ${p}[${m}])`:(0,so._)`${n} === ${w}`}}};ii.default=jx});var em=k(li=>{"use strict";Object.defineProperty(li,"__esModule",{value:!0});var Nx=Zp(),qx=Bp(),Mx=Wp(),Lx=Vp(),Zx=Gp(),Bx=Hp(),Ux=Jp(),Fx=Yp(),Wx=Xp(),Vx=Qp(),Gx=[Nx.default,qx.default,Mx.default,Lx.default,Zx.default,Bx.default,Ux.default,Fx.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},Wx.default,Vx.default];li.default=Gx});var ui=k(io=>{"use strict";Object.defineProperty(io,"__esModule",{value:!0});io.validateAdditionalItems=void 0;var Pt=R(),ci=M(),Hx={message:({params:{len:t}})=>(0,Pt.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Pt._)`{limit: ${t}}`},Jx={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:Hx,code(t){let{parentSchema:e,it:n}=t,{items:o}=e;if(!Array.isArray(o)){(0,ci.checkStrictMode)(n,'"additionalItems" is ignored when "items" is not an array of schemas');return}tm(t,o)}};function tm(t,e){let{gen:n,schema:o,data:r,keyword:a,it:s}=t;s.items=!0;let i=n.const("len",(0,Pt._)`${r}.length`);if(o===!1)t.setParams({len:e.length}),t.pass((0,Pt._)`${i} <= ${e.length}`);else if(typeof o=="object"&&!(0,ci.alwaysValidSchema)(s,o)){let c=n.var("valid",(0,Pt._)`${i} <= ${e.length}`);n.if((0,Pt.not)(c),()=>l(c)),t.ok(c)}function l(c){n.forRange("i",e.length,i,u=>{t.subschema({keyword:a,dataProp:u,dataPropType:ci.Type.Num},c),s.allErrors||n.if((0,Pt.not)(c),()=>n.break())})}}io.validateAdditionalItems=tm;io.default=Jx});var hi=k(lo=>{"use strict";Object.defineProperty(lo,"__esModule",{value:!0});lo.validateTuple=void 0;var nm=R(),br=M(),Kx=De(),Yx={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:n}=t;if(Array.isArray(e))return om(t,"additionalItems",e);n.items=!0,!(0,br.alwaysValidSchema)(n,e)&&t.ok((0,Kx.validateArray)(t))}};function om(t,e,n=t.schema){let{gen:o,parentSchema:r,data:a,keyword:s,it:i}=t;u(r),i.opts.unevaluated&&n.length&&i.items!==!0&&(i.items=br.mergeEvaluated.items(o,n.length,i.items));let l=o.name("valid"),c=o.const("len",(0,nm._)`${a}.length`);n.forEach((h,d)=>{(0,br.alwaysValidSchema)(i,h)||(o.if((0,nm._)`${c} > ${d}`,()=>t.subschema({keyword:s,schemaProp:d,dataProp:d},l)),t.ok(l))});function u(h){let{opts:d,errSchemaPath:p}=i,m=n.length,w=m===h.minItems&&(m===h.maxItems||h[e]===!1);if(d.strictTuples&&!w){let y=`"${s}" is ${m}-tuple, but minItems or maxItems/${e} are not specified or different at path "${p}"`;(0,br.checkStrictMode)(i,y,d.strictTuples)}}}lo.validateTuple=om;lo.default=Yx});var rm=k(di=>{"use strict";Object.defineProperty(di,"__esModule",{value:!0});var Xx=hi(),Qx={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,Xx.validateTuple)(t,"items")};di.default=Qx});var sm=k(pi=>{"use strict";Object.defineProperty(pi,"__esModule",{value:!0});var am=R(),eS=M(),tS=De(),nS=ui(),oS={message:({params:{len:t}})=>(0,am.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,am._)`{limit: ${t}}`},rS={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:oS,code(t){let{schema:e,parentSchema:n,it:o}=t,{prefixItems:r}=n;o.items=!0,!(0,eS.alwaysValidSchema)(o,e)&&(r?(0,nS.validateAdditionalItems)(t,r):t.ok((0,tS.validateArray)(t)))}};pi.default=rS});var im=k(mi=>{"use strict";Object.defineProperty(mi,"__esModule",{value:!0});var je=R(),kr=M(),aS={message:({params:{min:t,max:e}})=>e===void 0?(0,je.str)`must contain at least ${t} valid item(s)`:(0,je.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,je._)`{minContains: ${t}}`:(0,je._)`{minContains: ${t}, maxContains: ${e}}`},sS={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:aS,code(t){let{gen:e,schema:n,parentSchema:o,data:r,it:a}=t,s,i,{minContains:l,maxContains:c}=o;a.opts.next?(s=l===void 0?1:l,i=c):s=1;let u=e.const("len",(0,je._)`${r}.length`);if(t.setParams({min:s,max:i}),i===void 0&&s===0){(0,kr.checkStrictMode)(a,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(i!==void 0&&s>i){(0,kr.checkStrictMode)(a,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,kr.alwaysValidSchema)(a,n)){let w=(0,je._)`${u} >= ${s}`;i!==void 0&&(w=(0,je._)`${w} && ${u} <= ${i}`),t.pass(w);return}a.items=!0;let h=e.name("valid");i===void 0&&s===1?p(h,()=>e.if(h,()=>e.break())):s===0?(e.let(h,!0),i!==void 0&&e.if((0,je._)`${r}.length > 0`,d)):(e.let(h,!1),d()),t.result(h,()=>t.reset());function d(){let w=e.name("_valid"),y=e.let("count",0);p(w,()=>e.if(w,()=>m(y)))}function p(w,y){e.forRange("i",0,u,b=>{t.subschema({keyword:"contains",dataProp:b,dataPropType:kr.Type.Num,compositeRule:!0},w),y()})}function m(w){e.code((0,je._)`${w}++`),i===void 0?e.if((0,je._)`${w} >= ${s}`,()=>e.assign(h,!0).break()):(e.if((0,je._)`${w} > ${i}`,()=>e.assign(h,!1).break()),s===1?e.assign(h,!0):e.if((0,je._)`${w} >= ${s}`,()=>e.assign(h,!0)))}}};mi.default=sS});var um=k(Ve=>{"use strict";Object.defineProperty(Ve,"__esModule",{value:!0});Ve.validateSchemaDeps=Ve.validatePropertyDeps=Ve.error=void 0;var fi=R(),iS=M(),co=De();Ve.error={message:({params:{property:t,depsCount:e,deps:n}})=>{let o=e===1?"property":"properties";return(0,fi.str)`must have ${o} ${n} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:n,missingProperty:o}})=>(0,fi._)`{property: ${t},
6
+ || ${s} === "boolean" || ${r} === null`).assign(i,(0,E._)`[${r}]`)}}}function Db({gen:t,parentData:e,parentDataProperty:n},o){t.if((0,E._)`${e} !== undefined`,()=>t.assign((0,E._)`${e}[${n}]`,o))}function Ss(t,e,n,o=Gt.Correct){let r=o===Gt.Correct?E.operators.EQ:E.operators.NEQ,a;switch(t){case"null":return(0,E._)`${e} ${r} null`;case"array":a=(0,E._)`Array.isArray(${e})`;break;case"object":a=(0,E._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":a=s((0,E._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":a=s();break;default:return(0,E._)`typeof ${e} ${r} ${t}`}return o===Gt.Correct?a:(0,E.not)(a);function s(i=E.nil){return(0,E.and)((0,E._)`typeof ${e} == "number"`,i,n?(0,E._)`isFinite(${e})`:E.nil)}}me.checkDataType=Ss;function _s(t,e,n,o){if(t.length===1)return Ss(t[0],e,n,o);let r,a=(0,Rd.toHash)(t);if(a.array&&a.object){let s=(0,E._)`typeof ${e} != "object"`;r=a.null?s:(0,E._)`!${e} || ${s}`,delete a.null,delete a.array,delete a.object}else r=E.nil;a.number&&delete a.integer;for(let s in a)r=(0,E.and)(r,Ss(s,e,n,o));return r}me.checkDataTypes=_s;var Ob={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,E._)`{type: ${t}}`:(0,E._)`{type: ${e}}`};function Is(t){let e=Nb(t);(0,Pb.reportError)(e,Ob)}me.reportTypeError=Is;function Nb(t){let{gen:e,data:n,schema:o}=t,r=(0,Rd.schemaRefOrVal)(t,o,"type");return{gen:e,keyword:"type",data:n,schema:o.type,schemaCode:r,schemaValue:r,parentSchema:o,params:{},it:t}}});var Od=k(ar=>{"use strict";Object.defineProperty(ar,"__esModule",{value:!0});ar.assignDefaults=void 0;var Ht=R(),qb=M();function Mb(t,e){let{properties:n,items:o}=t.schema;if(e==="object"&&n)for(let r in n)Dd(t,r,n[r].default);else e==="array"&&Array.isArray(o)&&o.forEach((r,a)=>Dd(t,a,r.default))}ar.assignDefaults=Mb;function Dd(t,e,n){let{gen:o,compositeRule:r,data:a,opts:s}=t;if(n===void 0)return;let i=(0,Ht._)`${a}${(0,Ht.getProperty)(e)}`;if(r){(0,qb.checkStrictMode)(t,`default is ignored for: ${i}`);return}let l=(0,Ht._)`${i} === undefined`;s.useDefaults==="empty"&&(l=(0,Ht._)`${l} || ${i} === null || ${i} === ""`),o.if(l,(0,Ht._)`${i} = ${(0,Ht.stringify)(n)}`)}});var je=k(U=>{"use strict";Object.defineProperty(U,"__esModule",{value:!0});U.validateUnion=U.validateArray=U.usePattern=U.callValidateCode=U.schemaProperties=U.allSchemaProperties=U.noPropertyInData=U.propertyInData=U.isOwnProperty=U.hasPropFunc=U.reportMissingProp=U.checkMissingProp=U.checkReportMissingProp=void 0;var K=R(),zs=M(),pt=nt(),Lb=M();function Bb(t,e){let{gen:n,data:o,it:r}=t;n.if(Cs(n,o,e,r.opts.ownProperties),()=>{t.setParams({missingProperty:(0,K._)`${e}`},!0),t.error()})}U.checkReportMissingProp=Bb;function Zb({gen:t,data:e,it:{opts:n}},o,r){return(0,K.or)(...o.map(a=>(0,K.and)(Cs(t,e,a,n.ownProperties),(0,K._)`${r} = ${a}`)))}U.checkMissingProp=Zb;function Fb(t,e){t.setParams({missingProperty:e},!0),t.error()}U.reportMissingProp=Fb;function Nd(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,K._)`Object.prototype.hasOwnProperty`})}U.hasPropFunc=Nd;function Ts(t,e,n){return(0,K._)`${Nd(t)}.call(${e}, ${n})`}U.isOwnProperty=Ts;function Ub(t,e,n,o){let r=(0,K._)`${e}${(0,K.getProperty)(n)} !== undefined`;return o?(0,K._)`${r} && ${Ts(t,e,n)}`:r}U.propertyInData=Ub;function Cs(t,e,n,o){let r=(0,K._)`${e}${(0,K.getProperty)(n)} === undefined`;return o?(0,K.or)(r,(0,K.not)(Ts(t,e,n))):r}U.noPropertyInData=Cs;function qd(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}U.allSchemaProperties=qd;function Wb(t,e){return qd(e).filter(n=>!(0,zs.alwaysValidSchema)(t,e[n]))}U.schemaProperties=Wb;function Vb({schemaCode:t,data:e,it:{gen:n,topSchemaRef:o,schemaPath:r,errorPath:a},it:s},i,l,c){let u=c?(0,K._)`${t}, ${e}, ${o}${r}`:e,h=[[pt.default.instancePath,(0,K.strConcat)(pt.default.instancePath,a)],[pt.default.parentData,s.parentData],[pt.default.parentDataProperty,s.parentDataProperty],[pt.default.rootData,pt.default.rootData]];s.opts.dynamicRef&&h.push([pt.default.dynamicAnchors,pt.default.dynamicAnchors]);let d=(0,K._)`${u}, ${n.object(...h)}`;return l!==K.nil?(0,K._)`${i}.call(${l}, ${d})`:(0,K._)`${i}(${d})`}U.callValidateCode=Vb;var Gb=(0,K._)`new RegExp`;function Hb({gen:t,it:{opts:e}},n){let o=e.unicodeRegExp?"u":"",{regExp:r}=e.code,a=r(n,o);return t.scopeValue("pattern",{key:a.toString(),ref:a,code:(0,K._)`${r.code==="new RegExp"?Gb:(0,Lb.useFunc)(t,r)}(${n}, ${o})`})}U.usePattern=Hb;function Jb(t){let{gen:e,data:n,keyword:o,it:r}=t,a=e.name("valid");if(r.allErrors){let i=e.let("valid",!0);return s(()=>e.assign(i,!1)),i}return e.var(a,!0),s(()=>e.break()),a;function s(i){let l=e.const("len",(0,K._)`${n}.length`);e.forRange("i",0,l,c=>{t.subschema({keyword:o,dataProp:c,dataPropType:zs.Type.Num},a),e.if((0,K.not)(a),i)})}}U.validateArray=Jb;function Kb(t){let{gen:e,schema:n,keyword:o,it:r}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");if(n.some(l=>(0,zs.alwaysValidSchema)(r,l))&&!r.opts.unevaluated)return;let s=e.let("valid",!1),i=e.name("_valid");e.block(()=>n.forEach((l,c)=>{let u=t.subschema({keyword:o,schemaProp:c,compositeRule:!0},i);e.assign(s,(0,K._)`${s} || ${i}`),t.mergeValidEvaluated(u,i)||e.if((0,K.not)(s))})),t.result(s,()=>t.reset(),()=>t.error(!0))}U.validateUnion=Kb});var Bd=k(We=>{"use strict";Object.defineProperty(We,"__esModule",{value:!0});We.validateKeywordUsage=We.validSchemaType=We.funcKeywordCode=We.macroKeywordCode=void 0;var ye=R(),zt=nt(),Yb=je(),Xb=Vn();function Qb(t,e){let{gen:n,keyword:o,schema:r,parentSchema:a,it:s}=t,i=e.macro.call(s.self,r,a,s),l=Ld(n,o,i);s.opts.validateSchema!==!1&&s.self.validateSchema(i,!0);let c=n.name("valid");t.subschema({schema:i,schemaPath:ye.nil,errSchemaPath:`${s.errSchemaPath}/${o}`,topSchemaRef:l,compositeRule:!0},c),t.pass(c,()=>t.error(!0))}We.macroKeywordCode=Qb;function ek(t,e){var n;let{gen:o,keyword:r,schema:a,parentSchema:s,$data:i,it:l}=t;nk(l,e);let c=!i&&e.compile?e.compile.call(l.self,a,s,l):e.validate,u=Ld(o,r,c),h=o.let("valid");t.block$data(h,d),t.ok((n=e.valid)!==null&&n!==void 0?n:h);function d(){if(e.errors===!1)w(),e.modifying&&Md(t),y(()=>t.error());else{let b=e.async?p():m();e.modifying&&Md(t),y(()=>tk(t,b))}}function p(){let b=o.let("ruleErrs",null);return o.try(()=>w((0,ye._)`await `),x=>o.assign(h,!1).if((0,ye._)`${x} instanceof ${l.ValidationError}`,()=>o.assign(b,(0,ye._)`${x}.errors`),()=>o.throw(x))),b}function m(){let b=(0,ye._)`${u}.errors`;return o.assign(b,null),w(ye.nil),b}function w(b=e.async?(0,ye._)`await `:ye.nil){let x=l.opts.passContext?zt.default.this:zt.default.self,S=!("compile"in e&&!i||e.schema===!1);o.assign(h,(0,ye._)`${b}${(0,Yb.callValidateCode)(t,u,x,S)}`,e.modifying)}function y(b){var x;o.if((0,ye.not)((x=e.valid)!==null&&x!==void 0?x:h),b)}}We.funcKeywordCode=ek;function Md(t){let{gen:e,data:n,it:o}=t;e.if(o.parentData,()=>e.assign(n,(0,ye._)`${o.parentData}[${o.parentDataProperty}]`))}function tk(t,e){let{gen:n}=t;n.if((0,ye._)`Array.isArray(${e})`,()=>{n.assign(zt.default.vErrors,(0,ye._)`${zt.default.vErrors} === null ? ${e} : ${zt.default.vErrors}.concat(${e})`).assign(zt.default.errors,(0,ye._)`${zt.default.vErrors}.length`),(0,Xb.extendErrors)(t)},()=>t.error())}function nk({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Ld(t,e,n){if(n===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof n=="function"?{ref:n}:{ref:n,code:(0,ye.stringify)(n)})}function ok(t,e,n=!1){return!e.length||e.some(o=>o==="array"?Array.isArray(t):o==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==o||n&&typeof t>"u")}We.validSchemaType=ok;function rk({schema:t,opts:e,self:n,errSchemaPath:o},r,a){if(Array.isArray(r.keyword)?!r.keyword.includes(a):r.keyword!==a)throw new Error("ajv implementation error");let s=r.dependencies;if(s?.some(i=>!Object.prototype.hasOwnProperty.call(t,i)))throw new Error(`parent schema must have dependencies of ${a}: ${s.join(",")}`);if(r.validateSchema&&!r.validateSchema(t[a])){let l=`keyword "${a}" value is invalid at path "${o}": `+n.errorsText(r.validateSchema.errors);if(e.validateSchema==="log")n.logger.error(l);else throw new Error(l)}}We.validateKeywordUsage=rk});var Fd=k(mt=>{"use strict";Object.defineProperty(mt,"__esModule",{value:!0});mt.extendSubschemaMode=mt.extendSubschemaData=mt.getSubschema=void 0;var Ve=R(),Zd=M();function ak(t,{keyword:e,schemaProp:n,schema:o,schemaPath:r,errSchemaPath:a,topSchemaRef:s}){if(e!==void 0&&o!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let i=t.schema[e];return n===void 0?{schema:i,schemaPath:(0,Ve._)`${t.schemaPath}${(0,Ve.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:i[n],schemaPath:(0,Ve._)`${t.schemaPath}${(0,Ve.getProperty)(e)}${(0,Ve.getProperty)(n)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Zd.escapeFragment)(n)}`}}if(o!==void 0){if(r===void 0||a===void 0||s===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:o,schemaPath:r,topSchemaRef:s,errSchemaPath:a}}throw new Error('either "keyword" or "schema" must be passed')}mt.getSubschema=ak;function sk(t,e,{dataProp:n,dataPropType:o,data:r,dataTypes:a,propertyName:s}){if(r!==void 0&&n!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:i}=e;if(n!==void 0){let{errorPath:c,dataPathArr:u,opts:h}=e,d=i.let("data",(0,Ve._)`${e.data}${(0,Ve.getProperty)(n)}`,!0);l(d),t.errorPath=(0,Ve.str)`${c}${(0,Zd.getErrorPath)(n,o,h.jsPropertySyntax)}`,t.parentDataProperty=(0,Ve._)`${n}`,t.dataPathArr=[...u,t.parentDataProperty]}if(r!==void 0){let c=r instanceof Ve.Name?r:i.let("data",r,!0);l(c),s!==void 0&&(t.propertyName=s)}a&&(t.dataTypes=a);function l(c){t.data=c,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,c]}}mt.extendSubschemaData=sk;function ik(t,{jtdDiscriminator:e,jtdMetadata:n,compositeRule:o,createErrors:r,allErrors:a}){o!==void 0&&(t.compositeRule=o),r!==void 0&&(t.createErrors=r),a!==void 0&&(t.allErrors=a),t.jtdDiscriminator=e,t.jtdMetadata=n}mt.extendSubschemaMode=ik});var $s=k((bP,Ud)=>{"use strict";Ud.exports=function t(e,n){if(e===n)return!0;if(e&&n&&typeof e=="object"&&typeof n=="object"){if(e.constructor!==n.constructor)return!1;var o,r,a;if(Array.isArray(e)){if(o=e.length,o!=n.length)return!1;for(r=o;r--!==0;)if(!t(e[r],n[r]))return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if(a=Object.keys(e),o=a.length,o!==Object.keys(n).length)return!1;for(r=o;r--!==0;)if(!Object.prototype.hasOwnProperty.call(n,a[r]))return!1;for(r=o;r--!==0;){var s=a[r];if(!t(e[s],n[s]))return!1}return!0}return e!==e&&n!==n}});var Vd=k((kP,Wd)=>{"use strict";var ft=Wd.exports=function(t,e,n){typeof e=="function"&&(n=e,e={}),n=e.cb||n;var o=typeof n=="function"?n:n.pre||function(){},r=n.post||function(){};sr(e,o,r,t,"",t)};ft.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};ft.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};ft.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};ft.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 sr(t,e,n,o,r,a,s,i,l,c){if(o&&typeof o=="object"&&!Array.isArray(o)){e(o,r,a,s,i,l,c);for(var u in o){var h=o[u];if(Array.isArray(h)){if(u in ft.arrayKeywords)for(var d=0;d<h.length;d++)sr(t,e,n,h[d],r+"/"+u+"/"+d,a,r,u,o,d)}else if(u in ft.propsKeywords){if(h&&typeof h=="object")for(var p in h)sr(t,e,n,h[p],r+"/"+u+"/"+lk(p),a,r,u,o,p)}else(u in ft.keywords||t.allKeys&&!(u in ft.skipKeywords))&&sr(t,e,n,h,r+"/"+u,a,r,u,o)}n(o,r,a,s,i,l,c)}}function lk(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Hn=k(xe=>{"use strict";Object.defineProperty(xe,"__esModule",{value:!0});xe.getSchemaRefs=xe.resolveUrl=xe.normalizeId=xe._getFullPath=xe.getFullPath=xe.inlineRef=void 0;var ck=M(),uk=$s(),hk=Vd(),dk=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function pk(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Ps(t):e?Gd(t)<=e:!1}xe.inlineRef=pk;var mk=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Ps(t){for(let e in t){if(mk.has(e))return!0;let n=t[e];if(Array.isArray(n)&&n.some(Ps)||typeof n=="object"&&Ps(n))return!0}return!1}function Gd(t){let e=0;for(let n in t){if(n==="$ref")return 1/0;if(e++,!dk.has(n)&&(typeof t[n]=="object"&&(0,ck.eachItem)(t[n],o=>e+=Gd(o)),e===1/0))return 1/0}return e}function Hd(t,e="",n){n!==!1&&(e=Jt(e));let o=t.parse(e);return Jd(t,o)}xe.getFullPath=Hd;function Jd(t,e){return t.serialize(e).split("#")[0]+"#"}xe._getFullPath=Jd;var fk=/#\/?$/;function Jt(t){return t?t.replace(fk,""):""}xe.normalizeId=Jt;function gk(t,e,n){return n=Jt(n),t.resolve(e,n)}xe.resolveUrl=gk;var wk=/^[a-z_][-a-z0-9._]*$/i;function yk(t,e){if(typeof t=="boolean")return{};let{schemaId:n,uriResolver:o}=this.opts,r=Jt(t[n]||e),a={"":r},s=Hd(o,r,!1),i={},l=new Set;return hk(t,{allKeys:!0},(h,d,p,m)=>{if(m===void 0)return;let w=s+d,y=a[m];typeof h[n]=="string"&&(y=b.call(this,h[n])),x.call(this,h.$anchor),x.call(this,h.$dynamicAnchor),a[d]=y;function b(S){let T=this.opts.uriResolver.resolve;if(S=Jt(y?T(y,S):S),l.has(S))throw u(S);l.add(S);let _=this.refs[S];return typeof _=="string"&&(_=this.refs[_]),typeof _=="object"?c(h,_.schema,S):S!==Jt(w)&&(S[0]==="#"?(c(h,i[S],S),i[S]=h):this.refs[S]=w),S}function x(S){if(typeof S=="string"){if(!wk.test(S))throw new Error(`invalid anchor "${S}"`);b.call(this,`#${S}`)}}}),i;function c(h,d,p){if(d!==void 0&&!uk(h,d))throw u(p)}function u(h){return new Error(`reference "${h}" resolves to more than one schema`)}}xe.getSchemaRefs=yk});var Yn=k(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});gt.getData=gt.KeywordCxt=gt.validateFunctionCode=void 0;var ep=$d(),Kd=Gn(),Rs=xs(),ir=Gn(),bk=Od(),Kn=Bd(),Es=Fd(),z=R(),$=nt(),kk=Hn(),ot=M(),Jn=Vn();function vk(t){if(op(t)&&(rp(t),np(t))){_k(t);return}tp(t,()=>(0,ep.topBoolOrEmptySchema)(t))}gt.validateFunctionCode=vk;function tp({gen:t,validateName:e,schema:n,schemaEnv:o,opts:r},a){r.code.es5?t.func(e,(0,z._)`${$.default.data}, ${$.default.valCxt}`,o.$async,()=>{t.code((0,z._)`"use strict"; ${Yd(n,r)}`),Sk(t,r),t.code(a)}):t.func(e,(0,z._)`${$.default.data}, ${xk(r)}`,o.$async,()=>t.code(Yd(n,r)).code(a))}function xk(t){return(0,z._)`{${$.default.instancePath}="", ${$.default.parentData}, ${$.default.parentDataProperty}, ${$.default.rootData}=${$.default.data}${t.dynamicRef?(0,z._)`, ${$.default.dynamicAnchors}={}`:z.nil}}={}`}function Sk(t,e){t.if($.default.valCxt,()=>{t.var($.default.instancePath,(0,z._)`${$.default.valCxt}.${$.default.instancePath}`),t.var($.default.parentData,(0,z._)`${$.default.valCxt}.${$.default.parentData}`),t.var($.default.parentDataProperty,(0,z._)`${$.default.valCxt}.${$.default.parentDataProperty}`),t.var($.default.rootData,(0,z._)`${$.default.valCxt}.${$.default.rootData}`),e.dynamicRef&&t.var($.default.dynamicAnchors,(0,z._)`${$.default.valCxt}.${$.default.dynamicAnchors}`)},()=>{t.var($.default.instancePath,(0,z._)`""`),t.var($.default.parentData,(0,z._)`undefined`),t.var($.default.parentDataProperty,(0,z._)`undefined`),t.var($.default.rootData,$.default.data),e.dynamicRef&&t.var($.default.dynamicAnchors,(0,z._)`{}`)})}function _k(t){let{schema:e,opts:n,gen:o}=t;tp(t,()=>{n.$comment&&e.$comment&&sp(t),$k(t),o.let($.default.vErrors,null),o.let($.default.errors,0),n.unevaluated&&Ik(t),ap(t),Rk(t)})}function Ik(t){let{gen:e,validateName:n}=t;t.evaluated=e.const("evaluated",(0,z._)`${n}.evaluated`),e.if((0,z._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,z._)`${t.evaluated}.props`,(0,z._)`undefined`)),e.if((0,z._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,z._)`${t.evaluated}.items`,(0,z._)`undefined`))}function Yd(t,e){let n=typeof t=="object"&&t[e.schemaId];return n&&(e.code.source||e.code.process)?(0,z._)`/*# sourceURL=${n} */`:z.nil}function zk(t,e){if(op(t)&&(rp(t),np(t))){Tk(t,e);return}(0,ep.boolOrEmptySchema)(t,e)}function np({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let n in t)if(e.RULES.all[n])return!0;return!1}function op(t){return typeof t.schema!="boolean"}function Tk(t,e){let{schema:n,gen:o,opts:r}=t;r.$comment&&n.$comment&&sp(t),Pk(t),Ek(t);let a=o.const("_errs",$.default.errors);ap(t,a),o.var(e,(0,z._)`${a} === ${$.default.errors}`)}function rp(t){(0,ot.checkUnknownRules)(t),Ck(t)}function ap(t,e){if(t.opts.jtd)return Xd(t,[],!1,e);let n=(0,Kd.getSchemaTypes)(t.schema),o=(0,Kd.coerceAndCheckDataType)(t,n);Xd(t,n,!o,e)}function Ck(t){let{schema:e,errSchemaPath:n,opts:o,self:r}=t;e.$ref&&o.ignoreKeywordsWithRef&&(0,ot.schemaHasRulesButRef)(e,r.RULES)&&r.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function $k(t){let{schema:e,opts:n}=t;e.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,ot.checkStrictMode)(t,"default is ignored in the schema root")}function Pk(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,kk.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function Ek(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function sp({gen:t,schemaEnv:e,schema:n,errSchemaPath:o,opts:r}){let a=n.$comment;if(r.$comment===!0)t.code((0,z._)`${$.default.self}.logger.log(${a})`);else if(typeof r.$comment=="function"){let s=(0,z.str)`${o}/$comment`,i=t.scopeValue("root",{ref:e.root});t.code((0,z._)`${$.default.self}.opts.$comment(${a}, ${s}, ${i}.schema)`)}}function Rk(t){let{gen:e,schemaEnv:n,validateName:o,ValidationError:r,opts:a}=t;n.$async?e.if((0,z._)`${$.default.errors} === 0`,()=>e.return($.default.data),()=>e.throw((0,z._)`new ${r}(${$.default.vErrors})`)):(e.assign((0,z._)`${o}.errors`,$.default.vErrors),a.unevaluated&&Ak(t),e.return((0,z._)`${$.default.errors} === 0`))}function Ak({gen:t,evaluated:e,props:n,items:o}){n instanceof z.Name&&t.assign((0,z._)`${e}.props`,n),o instanceof z.Name&&t.assign((0,z._)`${e}.items`,o)}function Xd(t,e,n,o){let{gen:r,schema:a,data:s,allErrors:i,opts:l,self:c}=t,{RULES:u}=c;if(a.$ref&&(l.ignoreKeywordsWithRef||!(0,ot.schemaHasRulesButRef)(a,u))){r.block(()=>lp(t,"$ref",u.all.$ref.definition));return}l.jtd||jk(t,e),r.block(()=>{for(let d of u.rules)h(d);h(u.post)});function h(d){(0,Rs.shouldUseGroup)(a,d)&&(d.type?(r.if((0,ir.checkDataType)(d.type,s,l.strictNumbers)),Qd(t,d),e.length===1&&e[0]===d.type&&n&&(r.else(),(0,ir.reportTypeError)(t)),r.endIf()):Qd(t,d),i||r.if((0,z._)`${$.default.errors} === ${o||0}`))}}function Qd(t,e){let{gen:n,schema:o,opts:{useDefaults:r}}=t;r&&(0,bk.assignDefaults)(t,e.type),n.block(()=>{for(let a of e.rules)(0,Rs.shouldUseRule)(o,a)&&lp(t,a.keyword,a.definition,e.type)})}function jk(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(Dk(t,e),t.opts.allowUnionTypes||Ok(t,e),Nk(t,t.dataTypes))}function Dk(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(n=>{ip(t.dataTypes,n)||As(t,`type "${n}" not allowed by context "${t.dataTypes.join(",")}"`)}),Mk(t,e)}}function Ok(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&As(t,"use allowUnionTypes to allow union type keyword")}function Nk(t,e){let n=t.self.RULES.all;for(let o in n){let r=n[o];if(typeof r=="object"&&(0,Rs.shouldUseRule)(t.schema,r)){let{type:a}=r.definition;a.length&&!a.some(s=>qk(e,s))&&As(t,`missing type "${a.join(",")}" for keyword "${o}"`)}}}function qk(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function ip(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function Mk(t,e){let n=[];for(let o of t.dataTypes)ip(e,o)?n.push(o):e.includes("integer")&&o==="number"&&n.push("integer");t.dataTypes=n}function As(t,e){let n=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${n}" (strictTypes)`,(0,ot.checkStrictMode)(t,e,t.opts.strictTypes)}var lr=class{constructor(e,n,o){if((0,Kn.validateKeywordUsage)(e,n,o),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=o,this.data=e.data,this.schema=e.schema[o],this.$data=n.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,ot.schemaRefOrVal)(e,this.schema,o,this.$data),this.schemaType=n.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=n,this.$data)this.schemaCode=e.gen.const("vSchema",cp(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Kn.validSchemaType)(this.schema,n.schemaType,n.allowUndefined))throw new Error(`${o} value must be ${JSON.stringify(n.schemaType)}`);("code"in n?n.trackErrors:n.errors!==!1)&&(this.errsCount=e.gen.const("_errs",$.default.errors))}result(e,n,o){this.failResult((0,z.not)(e),n,o)}failResult(e,n,o){this.gen.if(e),o?o():this.error(),n?(this.gen.else(),n(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,n){this.failResult((0,z.not)(e),void 0,n)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:n}=this;this.fail((0,z._)`${n} !== undefined && (${(0,z.or)(this.invalid$data(),e)})`)}error(e,n,o){if(n){this.setParams(n),this._error(e,o),this.setParams({});return}this._error(e,o)}_error(e,n){(e?Jn.reportExtraError:Jn.reportError)(this,this.def.error,n)}$dataError(){(0,Jn.reportError)(this,this.def.$dataError||Jn.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Jn.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,n){n?Object.assign(this.params,e):this.params=e}block$data(e,n,o=z.nil){this.gen.block(()=>{this.check$data(e,o),n()})}check$data(e=z.nil,n=z.nil){if(!this.$data)return;let{gen:o,schemaCode:r,schemaType:a,def:s}=this;o.if((0,z.or)((0,z._)`${r} === undefined`,n)),e!==z.nil&&o.assign(e,!0),(a.length||s.validateSchema)&&(o.elseIf(this.invalid$data()),this.$dataError(),e!==z.nil&&o.assign(e,!1)),o.else()}invalid$data(){let{gen:e,schemaCode:n,schemaType:o,def:r,it:a}=this;return(0,z.or)(s(),i());function s(){if(o.length){if(!(n instanceof z.Name))throw new Error("ajv implementation error");let l=Array.isArray(o)?o:[o];return(0,z._)`${(0,ir.checkDataTypes)(l,n,a.opts.strictNumbers,ir.DataType.Wrong)}`}return z.nil}function i(){if(r.validateSchema){let l=e.scopeValue("validate$data",{ref:r.validateSchema});return(0,z._)`!${l}(${n})`}return z.nil}}subschema(e,n){let o=(0,Es.getSubschema)(this.it,e);(0,Es.extendSubschemaData)(o,this.it,e),(0,Es.extendSubschemaMode)(o,e);let r={...this.it,...o,items:void 0,props:void 0};return zk(r,n),r}mergeEvaluated(e,n){let{it:o,gen:r}=this;o.opts.unevaluated&&(o.props!==!0&&e.props!==void 0&&(o.props=ot.mergeEvaluated.props(r,e.props,o.props,n)),o.items!==!0&&e.items!==void 0&&(o.items=ot.mergeEvaluated.items(r,e.items,o.items,n)))}mergeValidEvaluated(e,n){let{it:o,gen:r}=this;if(o.opts.unevaluated&&(o.props!==!0||o.items!==!0))return r.if(n,()=>this.mergeEvaluated(e,z.Name)),!0}};gt.KeywordCxt=lr;function lp(t,e,n,o){let r=new lr(t,n,e);"code"in n?n.code(r,o):r.$data&&n.validate?(0,Kn.funcKeywordCode)(r,n):"macro"in n?(0,Kn.macroKeywordCode)(r,n):(n.compile||n.validate)&&(0,Kn.funcKeywordCode)(r,n)}var Lk=/^\/(?:[^~]|~0|~1)*$/,Bk=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function cp(t,{dataLevel:e,dataNames:n,dataPathArr:o}){let r,a;if(t==="")return $.default.rootData;if(t[0]==="/"){if(!Lk.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);r=t,a=$.default.rootData}else{let c=Bk.exec(t);if(!c)throw new Error(`Invalid JSON-pointer: ${t}`);let u=+c[1];if(r=c[2],r==="#"){if(u>=e)throw new Error(l("property/index",u));return o[e-u]}if(u>e)throw new Error(l("data",u));if(a=n[e-u],!r)return a}let s=a,i=r.split("/");for(let c of i)c&&(a=(0,z._)`${a}${(0,z.getProperty)((0,ot.unescapeJsonPointer)(c))}`,s=(0,z._)`${s} && ${a}`);return s;function l(c,u){return`Cannot access ${c} ${u} levels up, current level is ${e}`}}gt.getData=cp});var cr=k(Ds=>{"use strict";Object.defineProperty(Ds,"__esModule",{value:!0});var js=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Ds.default=js});var Xn=k(qs=>{"use strict";Object.defineProperty(qs,"__esModule",{value:!0});var Os=Hn(),Ns=class extends Error{constructor(e,n,o,r){super(r||`can't resolve reference ${o} from id ${n}`),this.missingRef=(0,Os.resolveUrl)(e,n,o),this.missingSchema=(0,Os.normalizeId)((0,Os.getFullPath)(e,this.missingRef))}};qs.default=Ns});var hr=k(De=>{"use strict";Object.defineProperty(De,"__esModule",{value:!0});De.resolveSchema=De.getCompilingSchema=De.resolveRef=De.compileSchema=De.SchemaEnv=void 0;var Le=R(),Zk=cr(),Tt=nt(),Be=Hn(),up=M(),Fk=Yn(),Kt=class{constructor(e){var n;this.refs={},this.dynamicAnchors={};let o;typeof e.schema=="object"&&(o=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(n=e.baseId)!==null&&n!==void 0?n:(0,Be.normalizeId)(o?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=o?.$async,this.refs={}}};De.SchemaEnv=Kt;function Ls(t){let e=hp.call(this,t);if(e)return e;let n=(0,Be.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:o,lines:r}=this.opts.code,{ownProperties:a}=this.opts,s=new Le.CodeGen(this.scope,{es5:o,lines:r,ownProperties:a}),i;t.$async&&(i=s.scopeValue("Error",{ref:Zk.default,code:(0,Le._)`require("ajv/dist/runtime/validation_error").default`}));let l=s.scopeName("validate");t.validateName=l;let c={gen:s,allErrors:this.opts.allErrors,data:Tt.default.data,parentData:Tt.default.parentData,parentDataProperty:Tt.default.parentDataProperty,dataNames:[Tt.default.data],dataPathArr:[Le.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,Le.stringify)(t.schema)}:{ref:t.schema}),validateName:l,ValidationError:i,schema:t.schema,schemaEnv:t,rootId:n,baseId:t.baseId||n,schemaPath:Le.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Le._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(t),(0,Fk.validateFunctionCode)(c),s.optimize(this.opts.code.optimize);let h=s.toString();u=`${s.scopeRefs(Tt.default.scope)}return ${h}`,this.opts.code.process&&(u=this.opts.code.process(u,t));let p=new Function(`${Tt.default.self}`,`${Tt.default.scope}`,u)(this,this.scope.get());if(this.scope.value(l,{ref:p}),p.errors=null,p.schema=t.schema,p.schemaEnv=t,t.$async&&(p.$async=!0),this.opts.code.source===!0&&(p.source={validateName:l,validateCode:h,scopeValues:s._values}),this.opts.unevaluated){let{props:m,items:w}=c;p.evaluated={props:m instanceof Le.Name?void 0:m,items:w instanceof Le.Name?void 0:w,dynamicProps:m instanceof Le.Name,dynamicItems:w instanceof Le.Name},p.source&&(p.source.evaluated=(0,Le.stringify)(p.evaluated))}return t.validate=p,t}catch(h){throw delete t.validate,delete t.validateName,u&&this.logger.error("Error compiling schema, function code:",u),h}finally{this._compilations.delete(t)}}De.compileSchema=Ls;function Uk(t,e,n){var o;n=(0,Be.resolveUrl)(this.opts.uriResolver,e,n);let r=t.refs[n];if(r)return r;let a=Gk.call(this,t,n);if(a===void 0){let s=(o=t.localRefs)===null||o===void 0?void 0:o[n],{schemaId:i}=this.opts;s&&(a=new Kt({schema:s,schemaId:i,root:t,baseId:e}))}if(a!==void 0)return t.refs[n]=Wk.call(this,a)}De.resolveRef=Uk;function Wk(t){return(0,Be.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Ls.call(this,t)}function hp(t){for(let e of this._compilations)if(Vk(e,t))return e}De.getCompilingSchema=hp;function Vk(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function Gk(t,e){let n;for(;typeof(n=this.refs[e])=="string";)e=n;return n||this.schemas[e]||ur.call(this,t,e)}function ur(t,e){let n=this.opts.uriResolver.parse(e),o=(0,Be._getFullPath)(this.opts.uriResolver,n),r=(0,Be.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&o===r)return Ms.call(this,n,t);let a=(0,Be.normalizeId)(o),s=this.refs[a]||this.schemas[a];if(typeof s=="string"){let i=ur.call(this,t,s);return typeof i?.schema!="object"?void 0:Ms.call(this,n,i)}if(typeof s?.schema=="object"){if(s.validate||Ls.call(this,s),a===(0,Be.normalizeId)(e)){let{schema:i}=s,{schemaId:l}=this.opts,c=i[l];return c&&(r=(0,Be.resolveUrl)(this.opts.uriResolver,r,c)),new Kt({schema:i,schemaId:l,root:t,baseId:r})}return Ms.call(this,n,s)}}De.resolveSchema=ur;var Hk=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Ms(t,{baseId:e,schema:n,root:o}){var r;if(((r=t.fragment)===null||r===void 0?void 0:r[0])!=="/")return;for(let i of t.fragment.slice(1).split("/")){if(typeof n=="boolean")return;let l=n[(0,up.unescapeFragment)(i)];if(l===void 0)return;n=l;let c=typeof n=="object"&&n[this.opts.schemaId];!Hk.has(i)&&c&&(e=(0,Be.resolveUrl)(this.opts.uriResolver,e,c))}let a;if(typeof n!="boolean"&&n.$ref&&!(0,up.schemaHasRulesButRef)(n,this.RULES)){let i=(0,Be.resolveUrl)(this.opts.uriResolver,e,n.$ref);a=ur.call(this,o,i)}let{schemaId:s}=this.opts;if(a=a||new Kt({schema:n,schemaId:s,root:o,baseId:e}),a.schema!==a.root.schema)return a}});var dp=k((zP,Jk)=>{Jk.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 Fs=k((TP,yp)=>{"use strict";var Kk=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),mp=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),Bs=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),fp=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),Yk=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Zs(t){let e="",n=0,o=0;for(o=0;o<t.length;o++)if(n=t[o].charCodeAt(0),n!==48){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";e+=t[o];break}for(o+=1;o<t.length;o++){if(n=t[o].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";e+=t[o]}return e}var Xk=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function pp(t){return t.length=0,!0}function Qk(t,e,n){if(t.length){let o=Zs(t);if(o!=="")e.push(o);else return n.error=!0,!1;t.length=0}return!0}function ev(t){let e=0,n={error:!1,address:"",zone:""},o=[],r=[],a=!1,s=!1,i=Qk;for(let l=0;l<t.length;l++){let c=t[l];if(!(c==="["||c==="]"))if(c===":"){if(a===!0&&(s=!0),!i(r,o,n))break;if(++e>7){n.error=!0;break}l>0&&t[l-1]===":"&&(a=!0),o.push(":");continue}else if(c==="%"){if(!i(r,o,n))break;i=pp}else{r.push(c);continue}}return r.length&&(i===pp?n.zone=r.join(""):s?o.push(r.join("")):o.push(Zs(r))),n.address=o.join(""),n}function gp(t){if(tv(t,":")<2)return{host:t,isIPV6:!1};let e=ev(t);if(e.error)return{host:t,isIPV6:!1};{let n=e.address,o=e.address;return e.zone&&(n+="%"+e.zone,o+="%25"+e.zone),{host:n,isIPV6:!0,escapedHost:o}}}function tv(t,e){let n=0;for(let o=0;o<t.length;o++)t[o]===e&&n++;return n}function nv(t){let e=t,n=[],o=-1,r=0;for(;r=e.length;){if(r===1){if(e===".")break;if(e==="/"){n.push("/");break}else{n.push(e);break}}else if(r===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){n.push("/");break}}else if(r===3&&e==="/.."){n.length!==0&&n.pop(),n.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),n.length!==0&&n.pop();continue}}if((o=e.indexOf("/",1))===-1){n.push(e);break}else n.push(e.slice(0,o)),e=e.slice(o)}return n.join("")}var ov={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},rv=/[@/?#:]/g,av=/[@/?#]/g;function wp(t,e){let n=e?av:rv;return n.lastIndex=0,t.replace(n,o=>ov[o])}function sv(t,e=!1){if(t.indexOf("%")===-1)return t;let n="";for(let o=0;o<t.length;o++){if(t[o]==="%"&&o+2<t.length){let r=t.slice(o+1,o+3);if(Bs(r)){let a=r.toUpperCase(),s=String.fromCharCode(parseInt(a,16));e&&fp(s)?n+=s:n+="%"+a,o+=2;continue}}n+=t[o]}return n}function iv(t){let e="";for(let n=0;n<t.length;n++){if(t[n]==="%"&&n+2<t.length){let o=t.slice(n+1,n+3);if(Bs(o)){let r=o.toUpperCase(),a=String.fromCharCode(parseInt(r,16));a!=="."&&fp(a)?e+=a:e+="%"+r,n+=2;continue}}Yk(t[n])?e+=t[n]:e+=escape(t[n])}return e}function lv(t){let e="";for(let n=0;n<t.length;n++){if(t[n]==="%"&&n+2<t.length){let o=t.slice(n+1,n+3);if(Bs(o)){e+="%"+o.toUpperCase(),n+=2;continue}}e+=escape(t[n])}return e}function cv(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let n=unescape(t.host);if(!mp(n)){let o=gp(n);o.isIPV6===!0?n=`[${o.escapedHost}]`:n=wp(n,!1)}e.push(n)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}yp.exports={nonSimpleDomain:Xk,recomposeAuthority:cv,reescapeHostDelimiters:wp,normalizePercentEncoding:sv,normalizePathEncoding:iv,escapePreservingEscapes:lv,removeDotSegments:nv,isIPv4:mp,isUUID:Kk,normalizeIPv6:gp,stringArrayToHexStripped:Zs}});var Sp=k((CP,xp)=>{"use strict";var{isUUID:uv}=Fs(),hv=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,dv=["http","https","ws","wss","urn","urn:uuid"];function pv(t){return dv.indexOf(t)!==-1}function Us(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function bp(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function kp(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function mv(t){return t.secure=Us(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function fv(t){if((t.port===(Us(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,n]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=n,t.resourceName=void 0}return t.fragment=void 0,t}function gv(t,e){if(!t.path)return t.error="URN can not be parsed",t;let n=t.path.match(hv);if(n){let o=e.scheme||t.scheme||"urn";t.nid=n[1].toLowerCase(),t.nss=n[2];let r=`${o}:${e.nid||t.nid}`,a=Ws(r);t.path=void 0,a&&(t=a.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function wv(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let n=e.scheme||t.scheme||"urn",o=t.nid.toLowerCase(),r=`${n}:${e.nid||o}`,a=Ws(r);a&&(t=a.serialize(t,e));let s=t,i=t.nss;return s.path=`${o||e.nid}:${i}`,e.skipEscape=!0,s}function yv(t,e){let n=t;return n.uuid=n.nss,n.nss=void 0,!e.tolerant&&(!n.uuid||!uv(n.uuid))&&(n.error=n.error||"UUID is not valid."),n}function bv(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var vp={scheme:"http",domainHost:!0,parse:bp,serialize:kp},kv={scheme:"https",domainHost:vp.domainHost,parse:bp,serialize:kp},dr={scheme:"ws",domainHost:!0,parse:mv,serialize:fv},vv={scheme:"wss",domainHost:dr.domainHost,parse:dr.parse,serialize:dr.serialize},xv={scheme:"urn",parse:gv,serialize:wv,skipNormalize:!0},Sv={scheme:"urn:uuid",parse:yv,serialize:bv,skipNormalize:!0},pr={http:vp,https:kv,ws:dr,wss:vv,urn:xv,"urn:uuid":Sv};Object.setPrototypeOf(pr,null);function Ws(t){return t&&(pr[t]||pr[t.toLowerCase()])||void 0}xp.exports={wsIsSecure:Us,SCHEMES:pr,isValidSchemeName:pv,getSchemeHandler:Ws}});var $p=k(($P,mr)=>{"use strict";var{normalizeIPv6:_v,removeDotSegments:Qn,recomposeAuthority:Iv,normalizePercentEncoding:zv,normalizePathEncoding:Tv,escapePreservingEscapes:Cv,reescapeHostDelimiters:$v,isIPv4:Pv,nonSimpleDomain:Ev}=Fs(),{SCHEMES:Rv,getSchemeHandler:Ip}=Sp();function Av(t,e){return typeof t=="string"?t=qv(t,e):typeof t=="object"&&(t=Yt(Ct(t,e),e)),t}function jv(t,e,n){let o=n?Object.assign({scheme:"null"},n):{scheme:"null"},r=zp(Yt(t,o),Yt(e,o),o,!0);return o.skipEscape=!0,Ct(r,o)}function zp(t,e,n,o){let r={};return o||(t=Yt(Ct(t,n),n),e=Yt(Ct(e,n),n)),n=n||{},!n.tolerant&&e.scheme?(r.scheme=e.scheme,r.userinfo=e.userinfo,r.host=e.host,r.port=e.port,r.path=Qn(e.path||""),r.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(r.userinfo=e.userinfo,r.host=e.host,r.port=e.port,r.path=Qn(e.path||""),r.query=e.query):(e.path?(e.path[0]==="/"?r.path=Qn(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?r.path="/"+e.path:t.path?r.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:r.path=e.path,r.path=Qn(r.path)),r.query=e.query):(r.path=t.path,e.query!==void 0?r.query=e.query:r.query=t.query),r.userinfo=t.userinfo,r.host=t.host,r.port=t.port),r.scheme=t.scheme),r.fragment=e.fragment,r}function Dv(t,e,n){let o=_p(t,n),r=_p(e,n);return o!==void 0&&r!==void 0&&o.toLowerCase()===r.toLowerCase()}function Ct(t,e){let n={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},o=Object.assign({},e),r=[],a=Ip(o.scheme||n.scheme);a&&a.serialize&&a.serialize(n,o),n.path!==void 0&&(o.skipEscape?n.path=zv(n.path):(n.path=Cv(n.path),n.scheme!==void 0&&(n.path=n.path.split("%3A").join(":")))),o.reference!=="suffix"&&n.scheme&&r.push(n.scheme,":");let s=Iv(n);if(s!==void 0&&(o.reference!=="suffix"&&r.push("//"),r.push(s),n.path&&n.path[0]!=="/"&&r.push("/")),n.path!==void 0){let i=n.path;!o.absolutePath&&(!a||!a.absolutePath)&&(i=Qn(i)),s===void 0&&i[0]==="/"&&i[1]==="/"&&(i="/%2F"+i.slice(2)),r.push(i)}return n.query!==void 0&&r.push("?",n.query),n.fragment!==void 0&&r.push("#",n.fragment),r.join("")}var Ov=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function Nv(t,e){if(e[2]!==void 0&&t.path&&t.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof t.port=="number"&&(t.port<0||t.port>65535))return"URI port is malformed."}function Tp(t,e){let n=Object.assign({},e),o={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},r=!1,a=!1;n.reference==="suffix"&&(n.scheme?t=n.scheme+":"+t:t="//"+t);let s=t.match(Ov);if(s){o.scheme=s[1],o.userinfo=s[3],o.host=s[4],o.port=parseInt(s[5],10),o.path=s[6]||"",o.query=s[7],o.fragment=s[8],isNaN(o.port)&&(o.port=s[5]);let i=Nv(o,s);if(i!==void 0&&(o.error=o.error||i,r=!0),o.host)if(Pv(o.host)===!1){let u=_v(o.host);o.host=u.host.toLowerCase(),a=u.isIPV6}else a=!0;o.scheme===void 0&&o.userinfo===void 0&&o.host===void 0&&o.port===void 0&&o.query===void 0&&!o.path?o.reference="same-document":o.scheme===void 0?o.reference="relative":o.fragment===void 0?o.reference="absolute":o.reference="uri",n.reference&&n.reference!=="suffix"&&n.reference!==o.reference&&(o.error=o.error||"URI is not a "+n.reference+" reference.");let l=Ip(n.scheme||o.scheme);if(!n.unicodeSupport&&(!l||!l.unicodeSupport)&&o.host&&(n.domainHost||l&&l.domainHost)&&a===!1&&Ev(o.host))try{o.host=URL.domainToASCII(o.host.toLowerCase())}catch(c){o.error=o.error||"Host's domain name can not be converted to ASCII: "+c}if((!l||l&&!l.skipNormalize)&&(t.indexOf("%")!==-1&&(o.scheme!==void 0&&(o.scheme=unescape(o.scheme)),o.host!==void 0&&(o.host=$v(unescape(o.host),a))),o.path&&(o.path=Tv(o.path)),o.fragment))try{o.fragment=encodeURI(decodeURIComponent(o.fragment))}catch{o.error=o.error||"URI malformed"}l&&l.parse&&l.parse(o,n)}else o.error=o.error||"URI can not be parsed.";return{parsed:o,malformedAuthorityOrPort:r}}function Yt(t,e){return Tp(t,e).parsed}function qv(t,e){return Cp(t,e).normalized}function Cp(t,e){let{parsed:n,malformedAuthorityOrPort:o}=Tp(t,e);return{normalized:o?t:Ct(n,e),malformedAuthorityOrPort:o}}function _p(t,e){if(typeof t=="string"){let{normalized:n,malformedAuthorityOrPort:o}=Cp(t,e);return o?void 0:n}if(typeof t=="object")return Ct(t,e)}var Vs={SCHEMES:Rv,normalize:Av,resolve:jv,resolveComponent:zp,equal:Dv,serialize:Ct,parse:Yt};mr.exports=Vs;mr.exports.default=Vs;mr.exports.fastUri=Vs});var Ep=k(Gs=>{"use strict";Object.defineProperty(Gs,"__esModule",{value:!0});var Pp=$p();Pp.code='require("ajv/dist/runtime/uri").default';Gs.default=Pp});var Mp=k(ue=>{"use strict";Object.defineProperty(ue,"__esModule",{value:!0});ue.CodeGen=ue.Name=ue.nil=ue.stringify=ue.str=ue._=ue.KeywordCxt=void 0;var Mv=Yn();Object.defineProperty(ue,"KeywordCxt",{enumerable:!0,get:function(){return Mv.KeywordCxt}});var Xt=R();Object.defineProperty(ue,"_",{enumerable:!0,get:function(){return Xt._}});Object.defineProperty(ue,"str",{enumerable:!0,get:function(){return Xt.str}});Object.defineProperty(ue,"stringify",{enumerable:!0,get:function(){return Xt.stringify}});Object.defineProperty(ue,"nil",{enumerable:!0,get:function(){return Xt.nil}});Object.defineProperty(ue,"Name",{enumerable:!0,get:function(){return Xt.Name}});Object.defineProperty(ue,"CodeGen",{enumerable:!0,get:function(){return Xt.CodeGen}});var Lv=cr(),Op=Xn(),Bv=vs(),eo=hr(),Zv=R(),to=Hn(),fr=Gn(),Js=M(),Rp=dp(),Fv=Ep(),Np=(t,e)=>new RegExp(t,e);Np.code="new RegExp";var Uv=["removeAdditional","useDefaults","coerceTypes"],Wv=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),Vv={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."},Gv={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Ap=200;function Hv(t){var e,n,o,r,a,s,i,l,c,u,h,d,p,m,w,y,b,x,S,T,_,Ie,$e,cn,qr;let un=t.strict,Mr=(e=t.code)===null||e===void 0?void 0:e.optimize,Ji=Mr===!0||Mr===void 0?1:Mr||0,Ki=(o=(n=t.code)===null||n===void 0?void 0:n.regExp)!==null&&o!==void 0?o:Np,pf=(r=t.uriResolver)!==null&&r!==void 0?r:Fv.default;return{strictSchema:(s=(a=t.strictSchema)!==null&&a!==void 0?a:un)!==null&&s!==void 0?s:!0,strictNumbers:(l=(i=t.strictNumbers)!==null&&i!==void 0?i:un)!==null&&l!==void 0?l:!0,strictTypes:(u=(c=t.strictTypes)!==null&&c!==void 0?c:un)!==null&&u!==void 0?u:"log",strictTuples:(d=(h=t.strictTuples)!==null&&h!==void 0?h:un)!==null&&d!==void 0?d:"log",strictRequired:(m=(p=t.strictRequired)!==null&&p!==void 0?p:un)!==null&&m!==void 0?m:!1,code:t.code?{...t.code,optimize:Ji,regExp:Ki}:{optimize:Ji,regExp:Ki},loopRequired:(w=t.loopRequired)!==null&&w!==void 0?w:Ap,loopEnum:(y=t.loopEnum)!==null&&y!==void 0?y:Ap,meta:(b=t.meta)!==null&&b!==void 0?b:!0,messages:(x=t.messages)!==null&&x!==void 0?x:!0,inlineRefs:(S=t.inlineRefs)!==null&&S!==void 0?S:!0,schemaId:(T=t.schemaId)!==null&&T!==void 0?T:"$id",addUsedSchema:(_=t.addUsedSchema)!==null&&_!==void 0?_:!0,validateSchema:(Ie=t.validateSchema)!==null&&Ie!==void 0?Ie:!0,validateFormats:($e=t.validateFormats)!==null&&$e!==void 0?$e:!0,unicodeRegExp:(cn=t.unicodeRegExp)!==null&&cn!==void 0?cn:!0,int32range:(qr=t.int32range)!==null&&qr!==void 0?qr:!0,uriResolver:pf}}var no=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...Hv(e)};let{es5:n,lines:o}=this.opts.code;this.scope=new Zv.ValueScope({scope:{},prefixes:Wv,es5:n,lines:o}),this.logger=ex(e.logger);let r=e.validateFormats;e.validateFormats=!1,this.RULES=(0,Bv.getRules)(),jp.call(this,Vv,e,"NOT SUPPORTED"),jp.call(this,Gv,e,"DEPRECATED","warn"),this._metaOpts=Xv.call(this),e.formats&&Kv.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&Yv.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),Jv.call(this),e.validateFormats=r}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:n,schemaId:o}=this.opts,r=Rp;o==="id"&&(r={...Rp},r.id=r.$id,delete r.$id),n&&e&&this.addMetaSchema(r,r[o],!1)}defaultMeta(){let{meta:e,schemaId:n}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[n]||e:void 0}validate(e,n){let o;if(typeof e=="string"){if(o=this.getSchema(e),!o)throw new Error(`no schema with key or ref "${e}"`)}else o=this.compile(e);let r=o(n);return"$async"in o||(this.errors=o.errors),r}compile(e,n){let o=this._addSchema(e,n);return o.validate||this._compileSchemaEnv(o)}compileAsync(e,n){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:o}=this.opts;return r.call(this,e,n);async function r(u,h){await a.call(this,u.$schema);let d=this._addSchema(u,h);return d.validate||s.call(this,d)}async function a(u){u&&!this.getSchema(u)&&await r.call(this,{$ref:u},!0)}async function s(u){try{return this._compileSchemaEnv(u)}catch(h){if(!(h instanceof Op.default))throw h;return i.call(this,h),await l.call(this,h.missingSchema),s.call(this,u)}}function i({missingSchema:u,missingRef:h}){if(this.refs[u])throw new Error(`AnySchema ${u} is loaded but ${h} cannot be resolved`)}async function l(u){let h=await c.call(this,u);this.refs[u]||await a.call(this,h.$schema),this.refs[u]||this.addSchema(h,u,n)}async function c(u){let h=this._loading[u];if(h)return h;try{return await(this._loading[u]=o(u))}finally{delete this._loading[u]}}}addSchema(e,n,o,r=this.opts.validateSchema){if(Array.isArray(e)){for(let s of e)this.addSchema(s,void 0,o,r);return this}let a;if(typeof e=="object"){let{schemaId:s}=this.opts;if(a=e[s],a!==void 0&&typeof a!="string")throw new Error(`schema ${s} must be string`)}return n=(0,to.normalizeId)(n||a),this._checkUnique(n),this.schemas[n]=this._addSchema(e,o,n,r,!0),this}addMetaSchema(e,n,o=this.opts.validateSchema){return this.addSchema(e,n,!0,o),this}validateSchema(e,n){if(typeof e=="boolean")return!0;let o;if(o=e.$schema,o!==void 0&&typeof o!="string")throw new Error("$schema must be a string");if(o=o||this.opts.defaultMeta||this.defaultMeta(),!o)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let r=this.validate(o,e);if(!r&&n){let a="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(a);else throw new Error(a)}return r}getSchema(e){let n;for(;typeof(n=Dp.call(this,e))=="string";)e=n;if(n===void 0){let{schemaId:o}=this.opts,r=new eo.SchemaEnv({schema:{},schemaId:o});if(n=eo.resolveSchema.call(this,r,e),!n)return;this.refs[e]=n}return n.validate||this._compileSchemaEnv(n)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let n=Dp.call(this,e);return typeof n=="object"&&this._cache.delete(n.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let n=e;this._cache.delete(n);let o=e[this.opts.schemaId];return o&&(o=(0,to.normalizeId)(o),delete this.schemas[o],delete this.refs[o]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let n of e)this.addKeyword(n);return this}addKeyword(e,n){let o;if(typeof e=="string")o=e,typeof n=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),n.keyword=o);else if(typeof e=="object"&&n===void 0){if(n=e,o=n.keyword,Array.isArray(o)&&!o.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(nx.call(this,o,n),!n)return(0,Js.eachItem)(o,a=>Hs.call(this,a)),this;rx.call(this,n);let r={...n,type:(0,fr.getJSONTypes)(n.type),schemaType:(0,fr.getJSONTypes)(n.schemaType)};return(0,Js.eachItem)(o,r.type.length===0?a=>Hs.call(this,a,r):a=>r.type.forEach(s=>Hs.call(this,a,r,s))),this}getKeyword(e){let n=this.RULES.all[e];return typeof n=="object"?n.definition:!!n}removeKeyword(e){let{RULES:n}=this;delete n.keywords[e],delete n.all[e];for(let o of n.rules){let r=o.rules.findIndex(a=>a.keyword===e);r>=0&&o.rules.splice(r,1)}return this}addFormat(e,n){return typeof n=="string"&&(n=new RegExp(n)),this.formats[e]=n,this}errorsText(e=this.errors,{separator:n=", ",dataVar:o="data"}={}){return!e||e.length===0?"No errors":e.map(r=>`${o}${r.instancePath} ${r.message}`).reduce((r,a)=>r+n+a)}$dataMetaSchema(e,n){let o=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let r of n){let a=r.split("/").slice(1),s=e;for(let i of a)s=s[i];for(let i in o){let l=o[i];if(typeof l!="object")continue;let{$data:c}=l.definition,u=s[i];c&&u&&(s[i]=qp(u))}}return e}_removeAllSchemas(e,n){for(let o in e){let r=e[o];(!n||n.test(o))&&(typeof r=="string"?delete e[o]:r&&!r.meta&&(this._cache.delete(r.schema),delete e[o]))}}_addSchema(e,n,o,r=this.opts.validateSchema,a=this.opts.addUsedSchema){let s,{schemaId:i}=this.opts;if(typeof e=="object")s=e[i];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let l=this._cache.get(e);if(l!==void 0)return l;o=(0,to.normalizeId)(s||o);let c=to.getSchemaRefs.call(this,e,o);return l=new eo.SchemaEnv({schema:e,schemaId:i,meta:n,baseId:o,localRefs:c}),this._cache.set(l.schema,l),a&&!o.startsWith("#")&&(o&&this._checkUnique(o),this.refs[o]=l),r&&this.validateSchema(e,!0),l}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):eo.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let n=this.opts;this.opts=this._metaOpts;try{eo.compileSchema.call(this,e)}finally{this.opts=n}}};no.ValidationError=Lv.default;no.MissingRefError=Op.default;ue.default=no;function jp(t,e,n,o="error"){for(let r in t){let a=r;a in e&&this.logger[o](`${n}: option ${r}. ${t[a]}`)}}function Dp(t){return t=(0,to.normalizeId)(t),this.schemas[t]||this.refs[t]}function Jv(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function Kv(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function Yv(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let n=t[e];n.keyword||(n.keyword=e),this.addKeyword(n)}}function Xv(){let t={...this.opts};for(let e of Uv)delete t[e];return t}var Qv={log(){},warn(){},error(){}};function ex(t){if(t===!1)return Qv;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var tx=/^[a-z_$][a-z0-9_$:-]*$/i;function nx(t,e){let{RULES:n}=this;if((0,Js.eachItem)(t,o=>{if(n.keywords[o])throw new Error(`Keyword ${o} is already defined`);if(!tx.test(o))throw new Error(`Keyword ${o} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function Hs(t,e,n){var o;let r=e?.post;if(n&&r)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:a}=this,s=r?a.post:a.rules.find(({type:l})=>l===n);if(s||(s={type:n,rules:[]},a.rules.push(s)),a.keywords[t]=!0,!e)return;let i={keyword:t,definition:{...e,type:(0,fr.getJSONTypes)(e.type),schemaType:(0,fr.getJSONTypes)(e.schemaType)}};e.before?ox.call(this,s,i,e.before):s.rules.push(i),a.all[t]=i,(o=e.implements)===null||o===void 0||o.forEach(l=>this.addKeyword(l))}function ox(t,e,n){let o=t.rules.findIndex(r=>r.keyword===n);o>=0?t.rules.splice(o,0,e):(t.rules.push(e),this.logger.warn(`rule ${n} is not defined`))}function rx(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=qp(e)),t.validateSchema=this.compile(e,!0))}var ax={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function qp(t){return{anyOf:[t,ax]}}});var Lp=k(Ks=>{"use strict";Object.defineProperty(Ks,"__esModule",{value:!0});var sx={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Ks.default=sx});var Up=k($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.callRef=$t.getValidate=void 0;var ix=Xn(),Bp=je(),Se=R(),Qt=nt(),Zp=hr(),gr=M(),lx={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:n,it:o}=t,{baseId:r,schemaEnv:a,validateName:s,opts:i,self:l}=o,{root:c}=a;if((n==="#"||n==="#/")&&r===c.baseId)return h();let u=Zp.resolveRef.call(l,c,r,n);if(u===void 0)throw new ix.default(o.opts.uriResolver,r,n);if(u instanceof Zp.SchemaEnv)return d(u);return p(u);function h(){if(a===c)return wr(t,s,a,a.$async);let m=e.scopeValue("root",{ref:c});return wr(t,(0,Se._)`${m}.validate`,c,c.$async)}function d(m){let w=Fp(t,m);wr(t,w,m,m.$async)}function p(m){let w=e.scopeValue("schema",i.code.source===!0?{ref:m,code:(0,Se.stringify)(m)}:{ref:m}),y=e.name("valid"),b=t.subschema({schema:m,dataTypes:[],schemaPath:Se.nil,topSchemaRef:w,errSchemaPath:n},y);t.mergeEvaluated(b),t.ok(y)}}};function Fp(t,e){let{gen:n}=t;return e.validate?n.scopeValue("validate",{ref:e.validate}):(0,Se._)`${n.scopeValue("wrapper",{ref:e})}.validate`}$t.getValidate=Fp;function wr(t,e,n,o){let{gen:r,it:a}=t,{allErrors:s,schemaEnv:i,opts:l}=a,c=l.passContext?Qt.default.this:Se.nil;o?u():h();function u(){if(!i.$async)throw new Error("async schema referenced by sync schema");let m=r.let("valid");r.try(()=>{r.code((0,Se._)`await ${(0,Bp.callValidateCode)(t,e,c)}`),p(e),s||r.assign(m,!0)},w=>{r.if((0,Se._)`!(${w} instanceof ${a.ValidationError})`,()=>r.throw(w)),d(w),s||r.assign(m,!1)}),t.ok(m)}function h(){t.result((0,Bp.callValidateCode)(t,e,c),()=>p(e),()=>d(e))}function d(m){let w=(0,Se._)`${m}.errors`;r.assign(Qt.default.vErrors,(0,Se._)`${Qt.default.vErrors} === null ? ${w} : ${Qt.default.vErrors}.concat(${w})`),r.assign(Qt.default.errors,(0,Se._)`${Qt.default.vErrors}.length`)}function p(m){var w;if(!a.opts.unevaluated)return;let y=(w=n?.validate)===null||w===void 0?void 0:w.evaluated;if(a.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(a.props=gr.mergeEvaluated.props(r,y.props,a.props));else{let b=r.var("props",(0,Se._)`${m}.evaluated.props`);a.props=gr.mergeEvaluated.props(r,b,a.props,Se.Name)}if(a.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(a.items=gr.mergeEvaluated.items(r,y.items,a.items));else{let b=r.var("items",(0,Se._)`${m}.evaluated.items`);a.items=gr.mergeEvaluated.items(r,b,a.items,Se.Name)}}}$t.callRef=wr;$t.default=lx});var Wp=k(Ys=>{"use strict";Object.defineProperty(Ys,"__esModule",{value:!0});var cx=Lp(),ux=Up(),hx=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",cx.default,ux.default];Ys.default=hx});var Vp=k(Xs=>{"use strict";Object.defineProperty(Xs,"__esModule",{value:!0});var yr=R(),wt=yr.operators,br={maximum:{okStr:"<=",ok:wt.LTE,fail:wt.GT},minimum:{okStr:">=",ok:wt.GTE,fail:wt.LT},exclusiveMaximum:{okStr:"<",ok:wt.LT,fail:wt.GTE},exclusiveMinimum:{okStr:">",ok:wt.GT,fail:wt.LTE}},dx={message:({keyword:t,schemaCode:e})=>(0,yr.str)`must be ${br[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,yr._)`{comparison: ${br[t].okStr}, limit: ${e}}`},px={keyword:Object.keys(br),type:"number",schemaType:"number",$data:!0,error:dx,code(t){let{keyword:e,data:n,schemaCode:o}=t;t.fail$data((0,yr._)`${n} ${br[e].fail} ${o} || isNaN(${n})`)}};Xs.default=px});var Gp=k(Qs=>{"use strict";Object.defineProperty(Qs,"__esModule",{value:!0});var oo=R(),mx={message:({schemaCode:t})=>(0,oo.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,oo._)`{multipleOf: ${t}}`},fx={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:mx,code(t){let{gen:e,data:n,schemaCode:o,it:r}=t,a=r.opts.multipleOfPrecision,s=e.let("res"),i=a?(0,oo._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${a}`:(0,oo._)`${s} !== parseInt(${s})`;t.fail$data((0,oo._)`(${o} === 0 || (${s} = ${n}/${o}, ${i}))`)}};Qs.default=fx});var Jp=k(ei=>{"use strict";Object.defineProperty(ei,"__esModule",{value:!0});function Hp(t){let e=t.length,n=0,o=0,r;for(;o<e;)n++,r=t.charCodeAt(o++),r>=55296&&r<=56319&&o<e&&(r=t.charCodeAt(o),(r&64512)===56320&&o++);return n}ei.default=Hp;Hp.code='require("ajv/dist/runtime/ucs2length").default'});var Kp=k(ti=>{"use strict";Object.defineProperty(ti,"__esModule",{value:!0});var Pt=R(),gx=M(),wx=Jp(),yx={message({keyword:t,schemaCode:e}){let n=t==="maxLength"?"more":"fewer";return(0,Pt.str)`must NOT have ${n} than ${e} characters`},params:({schemaCode:t})=>(0,Pt._)`{limit: ${t}}`},bx={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:yx,code(t){let{keyword:e,data:n,schemaCode:o,it:r}=t,a=e==="maxLength"?Pt.operators.GT:Pt.operators.LT,s=r.opts.unicode===!1?(0,Pt._)`${n}.length`:(0,Pt._)`${(0,gx.useFunc)(t.gen,wx.default)}(${n})`;t.fail$data((0,Pt._)`${s} ${a} ${o}`)}};ti.default=bx});var Yp=k(ni=>{"use strict";Object.defineProperty(ni,"__esModule",{value:!0});var kx=je(),vx=M(),en=R(),xx={message:({schemaCode:t})=>(0,en.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,en._)`{pattern: ${t}}`},Sx={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:xx,code(t){let{gen:e,data:n,$data:o,schema:r,schemaCode:a,it:s}=t,i=s.opts.unicodeRegExp?"u":"";if(o){let{regExp:l}=s.opts.code,c=l.code==="new RegExp"?(0,en._)`new RegExp`:(0,vx.useFunc)(e,l),u=e.let("valid");e.try(()=>e.assign(u,(0,en._)`${c}(${a}, ${i}).test(${n})`),()=>e.assign(u,!1)),t.fail$data((0,en._)`!${u}`)}else{let l=(0,kx.usePattern)(t,r);t.fail$data((0,en._)`!${l}.test(${n})`)}}};ni.default=Sx});var Xp=k(oi=>{"use strict";Object.defineProperty(oi,"__esModule",{value:!0});var ro=R(),_x={message({keyword:t,schemaCode:e}){let n=t==="maxProperties"?"more":"fewer";return(0,ro.str)`must NOT have ${n} than ${e} properties`},params:({schemaCode:t})=>(0,ro._)`{limit: ${t}}`},Ix={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:_x,code(t){let{keyword:e,data:n,schemaCode:o}=t,r=e==="maxProperties"?ro.operators.GT:ro.operators.LT;t.fail$data((0,ro._)`Object.keys(${n}).length ${r} ${o}`)}};oi.default=Ix});var Qp=k(ri=>{"use strict";Object.defineProperty(ri,"__esModule",{value:!0});var ao=je(),so=R(),zx=M(),Tx={message:({params:{missingProperty:t}})=>(0,so.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,so._)`{missingProperty: ${t}}`},Cx={keyword:"required",type:"object",schemaType:"array",$data:!0,error:Tx,code(t){let{gen:e,schema:n,schemaCode:o,data:r,$data:a,it:s}=t,{opts:i}=s;if(!a&&n.length===0)return;let l=n.length>=i.loopRequired;if(s.allErrors?c():u(),i.strictRequired){let p=t.parentSchema.properties,{definedProperties:m}=t.it;for(let w of n)if(p?.[w]===void 0&&!m.has(w)){let y=s.schemaEnv.baseId+s.errSchemaPath,b=`required property "${w}" is not defined at "${y}" (strictRequired)`;(0,zx.checkStrictMode)(s,b,s.opts.strictRequired)}}function c(){if(l||a)t.block$data(so.nil,h);else for(let p of n)(0,ao.checkReportMissingProp)(t,p)}function u(){let p=e.let("missing");if(l||a){let m=e.let("valid",!0);t.block$data(m,()=>d(p,m)),t.ok(m)}else e.if((0,ao.checkMissingProp)(t,n,p)),(0,ao.reportMissingProp)(t,p),e.else()}function h(){e.forOf("prop",o,p=>{t.setParams({missingProperty:p}),e.if((0,ao.noPropertyInData)(e,r,p,i.ownProperties),()=>t.error())})}function d(p,m){t.setParams({missingProperty:p}),e.forOf(p,o,()=>{e.assign(m,(0,ao.propertyInData)(e,r,p,i.ownProperties)),e.if((0,so.not)(m),()=>{t.error(),e.break()})},so.nil)}}};ri.default=Cx});var em=k(ai=>{"use strict";Object.defineProperty(ai,"__esModule",{value:!0});var io=R(),$x={message({keyword:t,schemaCode:e}){let n=t==="maxItems"?"more":"fewer";return(0,io.str)`must NOT have ${n} than ${e} items`},params:({schemaCode:t})=>(0,io._)`{limit: ${t}}`},Px={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:$x,code(t){let{keyword:e,data:n,schemaCode:o}=t,r=e==="maxItems"?io.operators.GT:io.operators.LT;t.fail$data((0,io._)`${n}.length ${r} ${o}`)}};ai.default=Px});var kr=k(si=>{"use strict";Object.defineProperty(si,"__esModule",{value:!0});var tm=$s();tm.code='require("ajv/dist/runtime/equal").default';si.default=tm});var nm=k(li=>{"use strict";Object.defineProperty(li,"__esModule",{value:!0});var ii=Gn(),he=R(),Ex=M(),Rx=kr(),Ax={message:({params:{i:t,j:e}})=>(0,he.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,he._)`{i: ${t}, j: ${e}}`},jx={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:Ax,code(t){let{gen:e,data:n,$data:o,schema:r,parentSchema:a,schemaCode:s,it:i}=t;if(!o&&!r)return;let l=e.let("valid"),c=a.items?(0,ii.getSchemaTypes)(a.items):[];t.block$data(l,u,(0,he._)`${s} === false`),t.ok(l);function u(){let m=e.let("i",(0,he._)`${n}.length`),w=e.let("j");t.setParams({i:m,j:w}),e.assign(l,!0),e.if((0,he._)`${m} > 1`,()=>(h()?d:p)(m,w))}function h(){return c.length>0&&!c.some(m=>m==="object"||m==="array")}function d(m,w){let y=e.name("item"),b=(0,ii.checkDataTypes)(c,y,i.opts.strictNumbers,ii.DataType.Wrong),x=e.const("indices",(0,he._)`{}`);e.for((0,he._)`;${m}--;`,()=>{e.let(y,(0,he._)`${n}[${m}]`),e.if(b,(0,he._)`continue`),c.length>1&&e.if((0,he._)`typeof ${y} == "string"`,(0,he._)`${y} += "_"`),e.if((0,he._)`typeof ${x}[${y}] == "number"`,()=>{e.assign(w,(0,he._)`${x}[${y}]`),t.error(),e.assign(l,!1).break()}).code((0,he._)`${x}[${y}] = ${m}`)})}function p(m,w){let y=(0,Ex.useFunc)(e,Rx.default),b=e.name("outer");e.label(b).for((0,he._)`;${m}--;`,()=>e.for((0,he._)`${w} = ${m}; ${w}--;`,()=>e.if((0,he._)`${y}(${n}[${m}], ${n}[${w}])`,()=>{t.error(),e.assign(l,!1).break(b)})))}}};li.default=jx});var om=k(ui=>{"use strict";Object.defineProperty(ui,"__esModule",{value:!0});var ci=R(),Dx=M(),Ox=kr(),Nx={message:"must be equal to constant",params:({schemaCode:t})=>(0,ci._)`{allowedValue: ${t}}`},qx={keyword:"const",$data:!0,error:Nx,code(t){let{gen:e,data:n,$data:o,schemaCode:r,schema:a}=t;o||a&&typeof a=="object"?t.fail$data((0,ci._)`!${(0,Dx.useFunc)(e,Ox.default)}(${n}, ${r})`):t.fail((0,ci._)`${a} !== ${n}`)}};ui.default=qx});var rm=k(hi=>{"use strict";Object.defineProperty(hi,"__esModule",{value:!0});var lo=R(),Mx=M(),Lx=kr(),Bx={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,lo._)`{allowedValues: ${t}}`},Zx={keyword:"enum",schemaType:"array",$data:!0,error:Bx,code(t){let{gen:e,data:n,$data:o,schema:r,schemaCode:a,it:s}=t;if(!o&&r.length===0)throw new Error("enum must have non-empty array");let i=r.length>=s.opts.loopEnum,l,c=()=>l??(l=(0,Mx.useFunc)(e,Lx.default)),u;if(i||o)u=e.let("valid"),t.block$data(u,h);else{if(!Array.isArray(r))throw new Error("ajv implementation error");let p=e.const("vSchema",a);u=(0,lo.or)(...r.map((m,w)=>d(p,w)))}t.pass(u);function h(){e.assign(u,!1),e.forOf("v",a,p=>e.if((0,lo._)`${c()}(${n}, ${p})`,()=>e.assign(u,!0).break()))}function d(p,m){let w=r[m];return typeof w=="object"&&w!==null?(0,lo._)`${c()}(${n}, ${p}[${m}])`:(0,lo._)`${n} === ${w}`}}};hi.default=Zx});var am=k(di=>{"use strict";Object.defineProperty(di,"__esModule",{value:!0});var Fx=Vp(),Ux=Gp(),Wx=Kp(),Vx=Yp(),Gx=Xp(),Hx=Qp(),Jx=em(),Kx=nm(),Yx=om(),Xx=rm(),Qx=[Fx.default,Ux.default,Wx.default,Vx.default,Gx.default,Hx.default,Jx.default,Kx.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},Yx.default,Xx.default];di.default=Qx});var mi=k(co=>{"use strict";Object.defineProperty(co,"__esModule",{value:!0});co.validateAdditionalItems=void 0;var Et=R(),pi=M(),eS={message:({params:{len:t}})=>(0,Et.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Et._)`{limit: ${t}}`},tS={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:eS,code(t){let{parentSchema:e,it:n}=t,{items:o}=e;if(!Array.isArray(o)){(0,pi.checkStrictMode)(n,'"additionalItems" is ignored when "items" is not an array of schemas');return}sm(t,o)}};function sm(t,e){let{gen:n,schema:o,data:r,keyword:a,it:s}=t;s.items=!0;let i=n.const("len",(0,Et._)`${r}.length`);if(o===!1)t.setParams({len:e.length}),t.pass((0,Et._)`${i} <= ${e.length}`);else if(typeof o=="object"&&!(0,pi.alwaysValidSchema)(s,o)){let c=n.var("valid",(0,Et._)`${i} <= ${e.length}`);n.if((0,Et.not)(c),()=>l(c)),t.ok(c)}function l(c){n.forRange("i",e.length,i,u=>{t.subschema({keyword:a,dataProp:u,dataPropType:pi.Type.Num},c),s.allErrors||n.if((0,Et.not)(c),()=>n.break())})}}co.validateAdditionalItems=sm;co.default=tS});var fi=k(uo=>{"use strict";Object.defineProperty(uo,"__esModule",{value:!0});uo.validateTuple=void 0;var im=R(),vr=M(),nS=je(),oS={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:n}=t;if(Array.isArray(e))return lm(t,"additionalItems",e);n.items=!0,!(0,vr.alwaysValidSchema)(n,e)&&t.ok((0,nS.validateArray)(t))}};function lm(t,e,n=t.schema){let{gen:o,parentSchema:r,data:a,keyword:s,it:i}=t;u(r),i.opts.unevaluated&&n.length&&i.items!==!0&&(i.items=vr.mergeEvaluated.items(o,n.length,i.items));let l=o.name("valid"),c=o.const("len",(0,im._)`${a}.length`);n.forEach((h,d)=>{(0,vr.alwaysValidSchema)(i,h)||(o.if((0,im._)`${c} > ${d}`,()=>t.subschema({keyword:s,schemaProp:d,dataProp:d},l)),t.ok(l))});function u(h){let{opts:d,errSchemaPath:p}=i,m=n.length,w=m===h.minItems&&(m===h.maxItems||h[e]===!1);if(d.strictTuples&&!w){let y=`"${s}" is ${m}-tuple, but minItems or maxItems/${e} are not specified or different at path "${p}"`;(0,vr.checkStrictMode)(i,y,d.strictTuples)}}}uo.validateTuple=lm;uo.default=oS});var cm=k(gi=>{"use strict";Object.defineProperty(gi,"__esModule",{value:!0});var rS=fi(),aS={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,rS.validateTuple)(t,"items")};gi.default=aS});var hm=k(wi=>{"use strict";Object.defineProperty(wi,"__esModule",{value:!0});var um=R(),sS=M(),iS=je(),lS=mi(),cS={message:({params:{len:t}})=>(0,um.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,um._)`{limit: ${t}}`},uS={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:cS,code(t){let{schema:e,parentSchema:n,it:o}=t,{prefixItems:r}=n;o.items=!0,!(0,sS.alwaysValidSchema)(o,e)&&(r?(0,lS.validateAdditionalItems)(t,r):t.ok((0,iS.validateArray)(t)))}};wi.default=uS});var dm=k(yi=>{"use strict";Object.defineProperty(yi,"__esModule",{value:!0});var Oe=R(),xr=M(),hS={message:({params:{min:t,max:e}})=>e===void 0?(0,Oe.str)`must contain at least ${t} valid item(s)`:(0,Oe.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Oe._)`{minContains: ${t}}`:(0,Oe._)`{minContains: ${t}, maxContains: ${e}}`},dS={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:hS,code(t){let{gen:e,schema:n,parentSchema:o,data:r,it:a}=t,s,i,{minContains:l,maxContains:c}=o;a.opts.next?(s=l===void 0?1:l,i=c):s=1;let u=e.const("len",(0,Oe._)`${r}.length`);if(t.setParams({min:s,max:i}),i===void 0&&s===0){(0,xr.checkStrictMode)(a,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(i!==void 0&&s>i){(0,xr.checkStrictMode)(a,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,xr.alwaysValidSchema)(a,n)){let w=(0,Oe._)`${u} >= ${s}`;i!==void 0&&(w=(0,Oe._)`${w} && ${u} <= ${i}`),t.pass(w);return}a.items=!0;let h=e.name("valid");i===void 0&&s===1?p(h,()=>e.if(h,()=>e.break())):s===0?(e.let(h,!0),i!==void 0&&e.if((0,Oe._)`${r}.length > 0`,d)):(e.let(h,!1),d()),t.result(h,()=>t.reset());function d(){let w=e.name("_valid"),y=e.let("count",0);p(w,()=>e.if(w,()=>m(y)))}function p(w,y){e.forRange("i",0,u,b=>{t.subschema({keyword:"contains",dataProp:b,dataPropType:xr.Type.Num,compositeRule:!0},w),y()})}function m(w){e.code((0,Oe._)`${w}++`),i===void 0?e.if((0,Oe._)`${w} >= ${s}`,()=>e.assign(h,!0).break()):(e.if((0,Oe._)`${w} > ${i}`,()=>e.assign(h,!1).break()),s===1?e.assign(h,!0):e.if((0,Oe._)`${w} >= ${s}`,()=>e.assign(h,!0)))}}};yi.default=dS});var fm=k(Ge=>{"use strict";Object.defineProperty(Ge,"__esModule",{value:!0});Ge.validateSchemaDeps=Ge.validatePropertyDeps=Ge.error=void 0;var bi=R(),pS=M(),ho=je();Ge.error={message:({params:{property:t,depsCount:e,deps:n}})=>{let o=e===1?"property":"properties";return(0,bi.str)`must have ${o} ${n} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:n,missingProperty:o}})=>(0,bi._)`{property: ${t},
7
7
  missingProperty: ${o},
8
8
  depsCount: ${e},
9
- deps: ${n}}`};var lS={keyword:"dependencies",type:"object",schemaType:"object",error:Ve.error,code(t){let[e,n]=cS(t);lm(t,e),cm(t,n)}};function cS({schema:t}){let e={},n={};for(let o in t){if(o==="__proto__")continue;let r=Array.isArray(t[o])?e:n;r[o]=t[o]}return[e,n]}function lm(t,e=t.schema){let{gen:n,data:o,it:r}=t;if(Object.keys(e).length===0)return;let a=n.let("missing");for(let s in e){let i=e[s];if(i.length===0)continue;let l=(0,co.propertyInData)(n,o,s,r.opts.ownProperties);t.setParams({property:s,depsCount:i.length,deps:i.join(", ")}),r.allErrors?n.if(l,()=>{for(let c of i)(0,co.checkReportMissingProp)(t,c)}):(n.if((0,fi._)`${l} && (${(0,co.checkMissingProp)(t,i,a)})`),(0,co.reportMissingProp)(t,a),n.else())}}Ve.validatePropertyDeps=lm;function cm(t,e=t.schema){let{gen:n,data:o,keyword:r,it:a}=t,s=n.name("valid");for(let i in e)(0,iS.alwaysValidSchema)(a,e[i])||(n.if((0,co.propertyInData)(n,o,i,a.opts.ownProperties),()=>{let l=t.subschema({keyword:r,schemaProp:i},s);t.mergeValidEvaluated(l,s)},()=>n.var(s,!0)),t.ok(s))}Ve.validateSchemaDeps=cm;Ve.default=lS});var dm=k(gi=>{"use strict";Object.defineProperty(gi,"__esModule",{value:!0});var hm=R(),uS=M(),hS={message:"property name must be valid",params:({params:t})=>(0,hm._)`{propertyName: ${t.propertyName}}`},dS={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:hS,code(t){let{gen:e,schema:n,data:o,it:r}=t;if((0,uS.alwaysValidSchema)(r,n))return;let a=e.name("valid");e.forIn("key",o,s=>{t.setParams({propertyName:s}),t.subschema({keyword:"propertyNames",data:s,dataTypes:["string"],propertyName:s,compositeRule:!0},a),e.if((0,hm.not)(a),()=>{t.error(!0),r.allErrors||e.break()})}),t.ok(a)}};gi.default=dS});var yi=k(wi=>{"use strict";Object.defineProperty(wi,"__esModule",{value:!0});var vr=De(),Ze=R(),pS=tt(),xr=M(),mS={message:"must NOT have additional properties",params:({params:t})=>(0,Ze._)`{additionalProperty: ${t.additionalProperty}}`},fS={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:mS,code(t){let{gen:e,schema:n,parentSchema:o,data:r,errsCount:a,it:s}=t;if(!a)throw new Error("ajv implementation error");let{allErrors:i,opts:l}=s;if(s.props=!0,l.removeAdditional!=="all"&&(0,xr.alwaysValidSchema)(s,n))return;let c=(0,vr.allSchemaProperties)(o.properties),u=(0,vr.allSchemaProperties)(o.patternProperties);h(),t.ok((0,Ze._)`${a} === ${pS.default.errors}`);function h(){e.forIn("key",r,y=>{!c.length&&!u.length?m(y):e.if(d(y),()=>m(y))})}function d(y){let b;if(c.length>8){let z=(0,xr.schemaRefOrVal)(s,o.properties,"properties");b=(0,vr.isOwnProperty)(e,z,y)}else c.length?b=(0,Ze.or)(...c.map(z=>(0,Ze._)`${y} === ${z}`)):b=Ze.nil;return u.length&&(b=(0,Ze.or)(b,...u.map(z=>(0,Ze._)`${(0,vr.usePattern)(t,z)}.test(${y})`))),(0,Ze.not)(b)}function p(y){e.code((0,Ze._)`delete ${r}[${y}]`)}function m(y){if(l.removeAdditional==="all"||l.removeAdditional&&n===!1){p(y);return}if(n===!1){t.setParams({additionalProperty:y}),t.error(),i||e.break();return}if(typeof n=="object"&&!(0,xr.alwaysValidSchema)(s,n)){let b=e.name("valid");l.removeAdditional==="failing"?(w(y,b,!1),e.if((0,Ze.not)(b),()=>{t.reset(),p(y)})):(w(y,b),i||e.if((0,Ze.not)(b),()=>e.break()))}}function w(y,b,z){let S={keyword:"additionalProperties",dataProp:y,dataPropType:xr.Type.Str};z===!1&&Object.assign(S,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(S,b)}}};wi.default=fS});var fm=k(ki=>{"use strict";Object.defineProperty(ki,"__esModule",{value:!0});var gS=Jn(),pm=De(),bi=M(),mm=yi(),wS={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:n,parentSchema:o,data:r,it:a}=t;a.opts.removeAdditional==="all"&&o.additionalProperties===void 0&&mm.default.code(new gS.KeywordCxt(a,mm.default,"additionalProperties"));let s=(0,pm.allSchemaProperties)(n);for(let h of s)a.definedProperties.add(h);a.opts.unevaluated&&s.length&&a.props!==!0&&(a.props=bi.mergeEvaluated.props(e,(0,bi.toHash)(s),a.props));let i=s.filter(h=>!(0,bi.alwaysValidSchema)(a,n[h]));if(i.length===0)return;let l=e.name("valid");for(let h of i)c(h)?u(h):(e.if((0,pm.propertyInData)(e,r,h,a.opts.ownProperties)),u(h),a.allErrors||e.else().var(l,!0),e.endIf()),t.it.definedProperties.add(h),t.ok(l);function c(h){return a.opts.useDefaults&&!a.compositeRule&&n[h].default!==void 0}function u(h){t.subschema({keyword:"properties",schemaProp:h,dataProp:h},l)}}};ki.default=wS});var bm=k(vi=>{"use strict";Object.defineProperty(vi,"__esModule",{value:!0});var gm=De(),Sr=R(),wm=M(),ym=M(),yS={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:n,data:o,parentSchema:r,it:a}=t,{opts:s}=a,i=(0,gm.allSchemaProperties)(n),l=i.filter(w=>(0,wm.alwaysValidSchema)(a,n[w]));if(i.length===0||l.length===i.length&&(!a.opts.unevaluated||a.props===!0))return;let c=s.strictSchema&&!s.allowMatchingProperties&&r.properties,u=e.name("valid");a.props!==!0&&!(a.props instanceof Sr.Name)&&(a.props=(0,ym.evaluatedPropsToName)(e,a.props));let{props:h}=a;d();function d(){for(let w of i)c&&p(w),a.allErrors?m(w):(e.var(u,!0),m(w),e.if(u))}function p(w){for(let y in c)new RegExp(w).test(y)&&(0,wm.checkStrictMode)(a,`property ${y} matches pattern ${w} (use allowMatchingProperties)`)}function m(w){e.forIn("key",o,y=>{e.if((0,Sr._)`${(0,gm.usePattern)(t,w)}.test(${y})`,()=>{let b=l.includes(w);b||t.subschema({keyword:"patternProperties",schemaProp:w,dataProp:y,dataPropType:ym.Type.Str},u),a.opts.unevaluated&&h!==!0?e.assign((0,Sr._)`${h}[${y}]`,!0):!b&&!a.allErrors&&e.if((0,Sr.not)(u),()=>e.break())})})}}};vi.default=yS});var km=k(xi=>{"use strict";Object.defineProperty(xi,"__esModule",{value:!0});var bS=M(),kS={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:n,it:o}=t;if((0,bS.alwaysValidSchema)(o,n)){t.fail();return}let r=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},r),t.failResult(r,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};xi.default=kS});var vm=k(Si=>{"use strict";Object.defineProperty(Si,"__esModule",{value:!0});var vS=De(),xS={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:vS.validateUnion,error:{message:"must match a schema in anyOf"}};Si.default=xS});var xm=k(_i=>{"use strict";Object.defineProperty(_i,"__esModule",{value:!0});var _r=R(),SS=M(),_S={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,_r._)`{passingSchemas: ${t.passing}}`},IS={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:_S,code(t){let{gen:e,schema:n,parentSchema:o,it:r}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");if(r.opts.discriminator&&o.discriminator)return;let a=n,s=e.let("valid",!1),i=e.let("passing",null),l=e.name("_valid");t.setParams({passing:i}),e.block(c),t.result(s,()=>t.reset(),()=>t.error(!0));function c(){a.forEach((u,h)=>{let d;(0,SS.alwaysValidSchema)(r,u)?e.var(l,!0):d=t.subschema({keyword:"oneOf",schemaProp:h,compositeRule:!0},l),h>0&&e.if((0,_r._)`${l} && ${s}`).assign(s,!1).assign(i,(0,_r._)`[${i}, ${h}]`).else(),e.if(l,()=>{e.assign(s,!0),e.assign(i,h),d&&t.mergeEvaluated(d,_r.Name)})})}}};_i.default=IS});var Sm=k(Ii=>{"use strict";Object.defineProperty(Ii,"__esModule",{value:!0});var zS=M(),TS={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:n,it:o}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");let r=e.name("valid");n.forEach((a,s)=>{if((0,zS.alwaysValidSchema)(o,a))return;let i=t.subschema({keyword:"allOf",schemaProp:s},r);t.ok(r),t.mergeEvaluated(i)})}};Ii.default=TS});var zm=k(zi=>{"use strict";Object.defineProperty(zi,"__esModule",{value:!0});var Ir=R(),Im=M(),$S={message:({params:t})=>(0,Ir.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Ir._)`{failingKeyword: ${t.ifClause}}`},CS={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:$S,code(t){let{gen:e,parentSchema:n,it:o}=t;n.then===void 0&&n.else===void 0&&(0,Im.checkStrictMode)(o,'"if" without "then" and "else" is ignored');let r=_m(o,"then"),a=_m(o,"else");if(!r&&!a)return;let s=e.let("valid",!0),i=e.name("_valid");if(l(),t.reset(),r&&a){let u=e.let("ifClause");t.setParams({ifClause:u}),e.if(i,c("then",u),c("else",u))}else r?e.if(i,c("then")):e.if((0,Ir.not)(i),c("else"));t.pass(s,()=>t.error(!0));function l(){let u=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},i);t.mergeEvaluated(u)}function c(u,h){return()=>{let d=t.subschema({keyword:u},i);e.assign(s,i),t.mergeValidEvaluated(d,s),h?e.assign(h,(0,Ir._)`${u}`):t.setParams({ifClause:u})}}}};function _m(t,e){let n=t.schema[e];return n!==void 0&&!(0,Im.alwaysValidSchema)(t,n)}zi.default=CS});var Tm=k(Ti=>{"use strict";Object.defineProperty(Ti,"__esModule",{value:!0});var PS=M(),ES={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:n}){e.if===void 0&&(0,PS.checkStrictMode)(n,`"${t}" without "if" is ignored`)}};Ti.default=ES});var $m=k($i=>{"use strict";Object.defineProperty($i,"__esModule",{value:!0});var RS=ui(),AS=rm(),DS=hi(),OS=sm(),jS=im(),NS=um(),qS=dm(),MS=yi(),LS=fm(),ZS=bm(),BS=km(),US=vm(),FS=xm(),WS=Sm(),VS=zm(),GS=Tm();function HS(t=!1){let e=[BS.default,US.default,FS.default,WS.default,VS.default,GS.default,qS.default,MS.default,NS.default,LS.default,ZS.default];return t?e.push(AS.default,OS.default):e.push(RS.default,DS.default),e.push(jS.default),e}$i.default=HS});var Cm=k(Ci=>{"use strict";Object.defineProperty(Ci,"__esModule",{value:!0});var oe=R(),JS={message:({schemaCode:t})=>(0,oe.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,oe._)`{format: ${t}}`},KS={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:JS,code(t,e){let{gen:n,data:o,$data:r,schema:a,schemaCode:s,it:i}=t,{opts:l,errSchemaPath:c,schemaEnv:u,self:h}=i;if(!l.validateFormats)return;r?d():p();function d(){let m=n.scopeValue("formats",{ref:h.formats,code:l.code.formats}),w=n.const("fDef",(0,oe._)`${m}[${s}]`),y=n.let("fType"),b=n.let("format");n.if((0,oe._)`typeof ${w} == "object" && !(${w} instanceof RegExp)`,()=>n.assign(y,(0,oe._)`${w}.type || "string"`).assign(b,(0,oe._)`${w}.validate`),()=>n.assign(y,(0,oe._)`"string"`).assign(b,w)),t.fail$data((0,oe.or)(z(),S()));function z(){return l.strictSchema===!1?oe.nil:(0,oe._)`${s} && !${b}`}function S(){let T=u.$async?(0,oe._)`(${w}.async ? await ${b}(${o}) : ${b}(${o}))`:(0,oe._)`${b}(${o})`,x=(0,oe._)`(typeof ${b} == "function" ? ${T} : ${b}.test(${o}))`;return(0,oe._)`${b} && ${b} !== true && ${y} === ${e} && !${x}`}}function p(){let m=h.formats[a];if(!m){z();return}if(m===!0)return;let[w,y,b]=S(m);w===e&&t.pass(T());function z(){if(l.strictSchema===!1){h.logger.warn(x());return}throw new Error(x());function x(){return`unknown format "${a}" ignored in schema at path "${c}"`}}function S(x){let Ie=x instanceof RegExp?(0,oe.regexpCode)(x):l.code.formats?(0,oe._)`${l.code.formats}${(0,oe.getProperty)(a)}`:void 0,Ce=n.scopeValue("formats",{key:a,ref:x,code:Ie});return typeof x=="object"&&!(x instanceof RegExp)?[x.type||"string",x.validate,(0,oe._)`${Ce}.validate`]:["string",x,Ce]}function T(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!u.$async)throw new Error("async format in sync schema");return(0,oe._)`await ${b}(${o})`}return typeof y=="function"?(0,oe._)`${b}(${o})`:(0,oe._)`${b}.test(${o})`}}}};Ci.default=KS});var Pm=k(Pi=>{"use strict";Object.defineProperty(Pi,"__esModule",{value:!0});var YS=Cm(),XS=[YS.default];Pi.default=XS});var Em=k(en=>{"use strict";Object.defineProperty(en,"__esModule",{value:!0});en.contentVocabulary=en.metadataVocabulary=void 0;en.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];en.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Am=k(Ei=>{"use strict";Object.defineProperty(Ei,"__esModule",{value:!0});var QS=Lp(),e_=em(),t_=$m(),n_=Pm(),Rm=Em(),o_=[QS.default,e_.default,(0,t_.default)(),n_.default,Rm.metadataVocabulary,Rm.contentVocabulary];Ei.default=o_});var Om=k(zr=>{"use strict";Object.defineProperty(zr,"__esModule",{value:!0});zr.DiscrError=void 0;var Dm;(function(t){t.Tag="tag",t.Mapping="mapping"})(Dm||(zr.DiscrError=Dm={}))});var Nm=k(Ai=>{"use strict";Object.defineProperty(Ai,"__esModule",{value:!0});var tn=R(),Ri=Om(),jm=cr(),r_=Kn(),a_=M(),s_={message:({params:{discrError:t,tagName:e}})=>t===Ri.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:n}})=>(0,tn._)`{error: ${t}, tag: ${n}, tagValue: ${e}}`},i_={keyword:"discriminator",type:"object",schemaType:"object",error:s_,code(t){let{gen:e,data:n,schema:o,parentSchema:r,it:a}=t,{oneOf:s}=r;if(!a.opts.discriminator)throw new Error("discriminator: requires discriminator option");let i=o.propertyName;if(typeof i!="string")throw new Error("discriminator: requires propertyName");if(o.mapping)throw new Error("discriminator: mapping is not supported");if(!s)throw new Error("discriminator: requires oneOf keyword");let l=e.let("valid",!1),c=e.const("tag",(0,tn._)`${n}${(0,tn.getProperty)(i)}`);e.if((0,tn._)`typeof ${c} == "string"`,()=>u(),()=>t.error(!1,{discrError:Ri.DiscrError.Tag,tag:c,tagName:i})),t.ok(l);function u(){let p=d();e.if(!1);for(let m in p)e.elseIf((0,tn._)`${c} === ${m}`),e.assign(l,h(p[m]));e.else(),t.error(!1,{discrError:Ri.DiscrError.Mapping,tag:c,tagName:i}),e.endIf()}function h(p){let m=e.name("valid"),w=t.subschema({keyword:"oneOf",schemaProp:p},m);return t.mergeEvaluated(w,tn.Name),m}function d(){var p;let m={},w=b(r),y=!0;for(let T=0;T<s.length;T++){let x=s[T];if(x?.$ref&&!(0,a_.schemaHasRulesButRef)(x,a.self.RULES)){let Ce=x.$ref;if(x=jm.resolveRef.call(a.self,a.schemaEnv.root,a.baseId,Ce),x instanceof jm.SchemaEnv&&(x=x.schema),x===void 0)throw new r_.default(a.opts.uriResolver,a.baseId,Ce)}let Ie=(p=x?.properties)===null||p===void 0?void 0:p[i];if(typeof Ie!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${i}"`);y=y&&(w||b(x)),z(Ie,T)}if(!y)throw new Error(`discriminator: "${i}" must be required`);return m;function b({required:T}){return Array.isArray(T)&&T.includes(i)}function z(T,x){if(T.const)S(T.const,x);else if(T.enum)for(let Ie of T.enum)S(Ie,x);else throw new Error(`discriminator: "properties/${i}" must have "const" or "enum"`)}function S(T,x){if(typeof T!="string"||T in m)throw new Error(`discriminator: "${i}" values must be unique strings`);m[T]=x}}}};Ai.default=i_});var qm=k((rE,l_)=>{l_.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 Oi=k((Y,Di)=>{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.MissingRefError=Y.ValidationError=Y.CodeGen=Y.Name=Y.nil=Y.stringify=Y.str=Y._=Y.KeywordCxt=Y.Ajv=void 0;var c_=Dp(),u_=Am(),h_=Nm(),Mm=qm(),d_=["/properties"],Tr="http://json-schema.org/draft-07/schema",nn=class extends c_.default{_addVocabularies(){super._addVocabularies(),u_.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(h_.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(Mm,d_):Mm;this.addMetaSchema(e,Tr,!1),this.refs["http://json-schema.org/schema"]=Tr}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Tr)?Tr:void 0)}};Y.Ajv=nn;Di.exports=Y=nn;Di.exports.Ajv=nn;Object.defineProperty(Y,"__esModule",{value:!0});Y.default=nn;var p_=Jn();Object.defineProperty(Y,"KeywordCxt",{enumerable:!0,get:function(){return p_.KeywordCxt}});var on=R();Object.defineProperty(Y,"_",{enumerable:!0,get:function(){return on._}});Object.defineProperty(Y,"str",{enumerable:!0,get:function(){return on.str}});Object.defineProperty(Y,"stringify",{enumerable:!0,get:function(){return on.stringify}});Object.defineProperty(Y,"nil",{enumerable:!0,get:function(){return on.nil}});Object.defineProperty(Y,"Name",{enumerable:!0,get:function(){return on.Name}});Object.defineProperty(Y,"CodeGen",{enumerable:!0,get:function(){return on.CodeGen}});var m_=ir();Object.defineProperty(Y,"ValidationError",{enumerable:!0,get:function(){return m_.default}});var f_=Kn();Object.defineProperty(Y,"MissingRefError",{enumerable:!0,get:function(){return f_.default}})});var Gm=k(He=>{"use strict";Object.defineProperty(He,"__esModule",{value:!0});He.formatNames=He.fastFormats=He.fullFormats=void 0;function Ge(t,e){return{validate:t,compare:e}}He.fullFormats={date:Ge(Um,Mi),time:Ge(Ni(!0),Li),"date-time":Ge(Lm(!0),Wm),"iso-time":Ge(Ni(),Fm),"iso-date-time":Ge(Lm(),Vm),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:v_,"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:$_,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:x_,int32:{type:"number",validate:I_},int64:{type:"number",validate:z_},float:{type:"number",validate:Bm},double:{type:"number",validate:Bm},password:!0,binary:!0};He.fastFormats={...He.fullFormats,date:Ge(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Mi),time:Ge(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Li),"date-time":Ge(/^\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,Wm),"iso-time":Ge(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Fm),"iso-date-time":Ge(/^\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,Vm),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};He.formatNames=Object.keys(He.fullFormats);function g_(t){return t%4===0&&(t%100!==0||t%400===0)}var w_=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,y_=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Um(t){let e=w_.exec(t);if(!e)return!1;let n=+e[1],o=+e[2],r=+e[3];return o>=1&&o<=12&&r>=1&&r<=(o===2&&g_(n)?29:y_[o])}function Mi(t,e){if(t&&e)return t>e?1:t<e?-1:0}var ji=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Ni(t){return function(n){let o=ji.exec(n);if(!o)return!1;let r=+o[1],a=+o[2],s=+o[3],i=o[4],l=o[5]==="-"?-1:1,c=+(o[6]||0),u=+(o[7]||0);if(c>23||u>59||t&&!i)return!1;if(r<=23&&a<=59&&s<60)return!0;let h=a-u*l,d=r-c*l-(h<0?1:0);return(d===23||d===-1)&&(h===59||h===-1)&&s<61}}function Li(t,e){if(!(t&&e))return;let n=new Date("2020-01-01T"+t).valueOf(),o=new Date("2020-01-01T"+e).valueOf();if(n&&o)return n-o}function Fm(t,e){if(!(t&&e))return;let n=ji.exec(t),o=ji.exec(e);if(n&&o)return t=n[1]+n[2]+n[3],e=o[1]+o[2]+o[3],t>e?1:t<e?-1:0}var qi=/t|\s/i;function Lm(t){let e=Ni(t);return function(o){let r=o.split(qi);return r.length===2&&Um(r[0])&&e(r[1])}}function Wm(t,e){if(!(t&&e))return;let n=new Date(t).valueOf(),o=new Date(e).valueOf();if(n&&o)return n-o}function Vm(t,e){if(!(t&&e))return;let[n,o]=t.split(qi),[r,a]=e.split(qi),s=Mi(n,r);if(s!==void 0)return s||Li(o,a)}var b_=/\/|:/,k_=/^(?:[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 v_(t){return b_.test(t)&&k_.test(t)}var Zm=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function x_(t){return Zm.lastIndex=0,Zm.test(t)}var S_=-(2**31),__=2**31-1;function I_(t){return Number.isInteger(t)&&t<=__&&t>=S_}function z_(t){return Number.isInteger(t)}function Bm(){return!0}var T_=/[^\\]\\Z/;function $_(t){if(T_.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var Hm=k(rn=>{"use strict";Object.defineProperty(rn,"__esModule",{value:!0});rn.formatLimitDefinition=void 0;var C_=Oi(),Be=R(),wt=Be.operators,$r={formatMaximum:{okStr:"<=",ok:wt.LTE,fail:wt.GT},formatMinimum:{okStr:">=",ok:wt.GTE,fail:wt.LT},formatExclusiveMaximum:{okStr:"<",ok:wt.LT,fail:wt.GTE},formatExclusiveMinimum:{okStr:">",ok:wt.GT,fail:wt.LTE}},P_={message:({keyword:t,schemaCode:e})=>(0,Be.str)`should be ${$r[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Be._)`{comparison: ${$r[t].okStr}, limit: ${e}}`};rn.formatLimitDefinition={keyword:Object.keys($r),type:"string",schemaType:"string",$data:!0,error:P_,code(t){let{gen:e,data:n,schemaCode:o,keyword:r,it:a}=t,{opts:s,self:i}=a;if(!s.validateFormats)return;let l=new C_.KeywordCxt(a,i.RULES.all.format.definition,"format");l.$data?c():u();function c(){let d=e.scopeValue("formats",{ref:i.formats,code:s.code.formats}),p=e.const("fmt",(0,Be._)`${d}[${l.schemaCode}]`);t.fail$data((0,Be.or)((0,Be._)`typeof ${p} != "object"`,(0,Be._)`${p} instanceof RegExp`,(0,Be._)`typeof ${p}.compare != "function"`,h(p)))}function u(){let d=l.schema,p=i.formats[d];if(!p||p===!0)return;if(typeof p!="object"||p instanceof RegExp||typeof p.compare!="function")throw new Error(`"${r}": format "${d}" does not define "compare" function`);let m=e.scopeValue("formats",{key:d,ref:p,code:s.code.formats?(0,Be._)`${s.code.formats}${(0,Be.getProperty)(d)}`:void 0});t.fail$data(h(m))}function h(d){return(0,Be._)`${d}.compare(${n}, ${o}) ${$r[r].fail} 0`}},dependencies:["format"]};var E_=t=>(t.addKeyword(rn.formatLimitDefinition),t);rn.default=E_});var Xm=k((uo,Ym)=>{"use strict";Object.defineProperty(uo,"__esModule",{value:!0});var an=Gm(),R_=Hm(),Zi=R(),Jm=new Zi.Name("fullFormats"),A_=new Zi.Name("fastFormats"),Bi=(t,e={keywords:!0})=>{if(Array.isArray(e))return Km(t,e,an.fullFormats,Jm),t;let[n,o]=e.mode==="fast"?[an.fastFormats,A_]:[an.fullFormats,Jm],r=e.formats||an.formatNames;return Km(t,r,n,o),e.keywords&&(0,R_.default)(t),t};Bi.get=(t,e="full")=>{let o=(e==="fast"?an.fastFormats:an.fullFormats)[t];if(!o)throw new Error(`Unknown format "${t}"`);return o};function Km(t,e,n,o){var r,a;(r=(a=t.opts.code).formats)!==null&&r!==void 0||(a.formats=(0,Zi._)`require("ajv-formats/dist/formats").${o}`);for(let s of e)t.addFormat(s,n[s])}Ym.exports=uo=Bi;Object.defineProperty(uo,"__esModule",{value:!0});uo.default=Bi});var Hi;function g(t,e,n){function o(i,l){if(i._zod||Object.defineProperty(i,"_zod",{value:{def:l,constr:s,traits:new Set},enumerable:!1}),i._zod.traits.has(t))return;i._zod.traits.add(t),e(i,l);let c=s.prototype,u=Object.keys(c);for(let h=0;h<u.length;h++){let d=u[h];d in i||(i[d]=c[d].bind(i))}}let r=n?.Parent??Object;class a extends r{}Object.defineProperty(a,"name",{value:t});function s(i){var l;let c=n?.Parent?new a:this;o(c,i),(l=c._zod).deferred??(l.deferred=[]);for(let u of c._zod.deferred)u();return c}return Object.defineProperty(s,"init",{value:o}),Object.defineProperty(s,Symbol.hasInstance,{value:i=>n?.Parent&&i instanceof n.Parent?!0:i?._zod?.traits?.has(t)}),Object.defineProperty(s,"name",{value:t}),s}var Ue=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Et=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}};(Hi=globalThis).__zod_globalConfig??(Hi.__zod_globalConfig={});var Rt=globalThis.__zod_globalConfig;function ze(t){return t&&Object.assign(Rt,t),Rt}var q={};Vi(q,{BIGINT_FORMAT_RANGES:()=>Xi,Class:()=>qr,NUMBER_FORMAT_RANGES:()=>Fr,aborted:()=>at,allowsEval:()=>Zr,assert:()=>yf,assertEqual:()=>mf,assertIs:()=>gf,assertNever:()=>wf,assertNotEqual:()=>ff,assignProp:()=>ot,base64ToUint8Array:()=>el,base64urlToUint8Array:()=>Of,cached:()=>Dt,captureStackTrace:()=>fo,cleanEnum:()=>Df,cleanRegex:()=>dn,clone:()=>Ne,cloneDef:()=>kf,createTransparentProxy:()=>zf,defineLazy:()=>B,esc:()=>mo,escapeRegex:()=>Ke,explicitlyAborted:()=>Wr,extend:()=>Cf,finalizeIssue:()=>Pe,floatSafeRemainder:()=>Mr,getElementAtPath:()=>vf,getEnumValues:()=>un,getLengthableOrigin:()=>pn,getParsedType:()=>If,getSizableOrigin:()=>Qi,hexToUint8Array:()=>Nf,isObject:()=>yt,isPlainObject:()=>rt,issue:()=>Ot,joinValues:()=>po,jsonStringifyReplacer:()=>At,merge:()=>Ef,mergeDefs:()=>Je,normalizeParams:()=>$,nullish:()=>hn,numKeys:()=>_f,objectClone:()=>bf,omit:()=>$f,optionalKeys:()=>Ur,parsedType:()=>Vr,partial:()=>Rf,pick:()=>Tf,prefixIssues:()=>Ye,primitiveTypes:()=>Yi,promiseAllObject:()=>xf,propertyKeyTypes:()=>Br,randomString:()=>Sf,required:()=>Af,safeExtend:()=>Pf,shallowClone:()=>Ki,slugify:()=>Lr,stringifyPrimitive:()=>go,uint8ArrayToBase64:()=>tl,uint8ArrayToBase64url:()=>jf,uint8ArrayToHex:()=>qf,unwrapMessage:()=>cn});function mf(t){return t}function ff(t){return t}function gf(t){}function wf(t){throw new Error("Unexpected value in exhaustive check")}function yf(t){}function un(t){let e=Object.values(t).filter(o=>typeof o=="number");return Object.entries(t).filter(([o,r])=>e.indexOf(+o)===-1).map(([o,r])=>r)}function po(t,e="|"){return t.map(n=>go(n)).join(e)}function At(t,e){return typeof e=="bigint"?e.toString():e}function Dt(t){return{get value(){{let n=t();return Object.defineProperty(this,"value",{value:n}),n}throw new Error("cached value already set")}}}function hn(t){return t==null}function dn(t){let e=t.startsWith("^")?1:0,n=t.endsWith("$")?t.length-1:t.length;return t.slice(e,n)}function Mr(t,e){let n=t/e,o=Math.round(n),r=Number.EPSILON*Math.max(Math.abs(n),1);return Math.abs(n-o)<r?0:n-o}var Ji=Symbol("evaluating");function B(t,e,n){let o;Object.defineProperty(t,e,{get(){if(o!==Ji)return o===void 0&&(o=Ji,o=n()),o},set(r){Object.defineProperty(t,e,{value:r})},configurable:!0})}function bf(t){return Object.create(Object.getPrototypeOf(t),Object.getOwnPropertyDescriptors(t))}function ot(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Je(...t){let e={};for(let n of t){let o=Object.getOwnPropertyDescriptors(n);Object.assign(e,o)}return Object.defineProperties({},e)}function kf(t){return Je(t._zod.def)}function vf(t,e){return e?e.reduce((n,o)=>n?.[o],t):t}function xf(t){let e=Object.keys(t),n=e.map(o=>t[o]);return Promise.all(n).then(o=>{let r={};for(let a=0;a<e.length;a++)r[e[a]]=o[a];return r})}function Sf(t=10){let e="abcdefghijklmnopqrstuvwxyz",n="";for(let o=0;o<t;o++)n+=e[Math.floor(Math.random()*e.length)];return n}function mo(t){return JSON.stringify(t)}function Lr(t){return t.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var fo="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};function yt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Zr=Dt(()=>{if(Rt.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function rt(t){if(yt(t)===!1)return!1;let e=t.constructor;if(e===void 0||typeof e!="function")return!0;let n=e.prototype;return!(yt(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function Ki(t){return rt(t)?{...t}:Array.isArray(t)?[...t]:t instanceof Map?new Map(t):t instanceof Set?new Set(t):t}function _f(t){let e=0;for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&e++;return e}var If=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},Br=new Set(["string","number","symbol"]),Yi=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Ke(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ne(t,e,n){let o=new t._zod.constr(e??t._zod.def);return(!e||n?.parent)&&(o._zod.parent=t),o}function $(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function zf(t){let e;return new Proxy({},{get(n,o,r){return e??(e=t()),Reflect.get(e,o,r)},set(n,o,r,a){return e??(e=t()),Reflect.set(e,o,r,a)},has(n,o){return e??(e=t()),Reflect.has(e,o)},deleteProperty(n,o){return e??(e=t()),Reflect.deleteProperty(e,o)},ownKeys(n){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(n,o){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,o)},defineProperty(n,o,r){return e??(e=t()),Reflect.defineProperty(e,o,r)}})}function go(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function Ur(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var Fr={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},Xi={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function Tf(t,e){let n=t._zod.def,o=n.checks;if(o&&o.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let a=Je(t._zod.def,{get shape(){let s={};for(let i in e){if(!(i in n.shape))throw new Error(`Unrecognized key: "${i}"`);e[i]&&(s[i]=n.shape[i])}return ot(this,"shape",s),s},checks:[]});return Ne(t,a)}function $f(t,e){let n=t._zod.def,o=n.checks;if(o&&o.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let a=Je(t._zod.def,{get shape(){let s={...t._zod.def.shape};for(let i in e){if(!(i in n.shape))throw new Error(`Unrecognized key: "${i}"`);e[i]&&delete s[i]}return ot(this,"shape",s),s},checks:[]});return Ne(t,a)}function Cf(t,e){if(!rt(e))throw new Error("Invalid input to extend: expected a plain object");let n=t._zod.def.checks;if(n&&n.length>0){let a=t._zod.def.shape;for(let s in e)if(Object.getOwnPropertyDescriptor(a,s)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let r=Je(t._zod.def,{get shape(){let a={...t._zod.def.shape,...e};return ot(this,"shape",a),a}});return Ne(t,r)}function Pf(t,e){if(!rt(e))throw new Error("Invalid input to safeExtend: expected a plain object");let n=Je(t._zod.def,{get shape(){let o={...t._zod.def.shape,...e};return ot(this,"shape",o),o}});return Ne(t,n)}function Ef(t,e){if(t._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let n=Je(t._zod.def,{get shape(){let o={...t._zod.def.shape,...e._zod.def.shape};return ot(this,"shape",o),o},get catchall(){return e._zod.def.catchall},checks:e._zod.def.checks??[]});return Ne(t,n)}function Rf(t,e,n){let r=e._zod.def.checks;if(r&&r.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let s=Je(e._zod.def,{get shape(){let i=e._zod.def.shape,l={...i};if(n)for(let c in n){if(!(c in i))throw new Error(`Unrecognized key: "${c}"`);n[c]&&(l[c]=t?new t({type:"optional",innerType:i[c]}):i[c])}else for(let c in i)l[c]=t?new t({type:"optional",innerType:i[c]}):i[c];return ot(this,"shape",l),l},checks:[]});return Ne(e,s)}function Af(t,e,n){let o=Je(e._zod.def,{get shape(){let r=e._zod.def.shape,a={...r};if(n)for(let s in n){if(!(s in a))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(a[s]=new t({type:"nonoptional",innerType:r[s]}))}else for(let s in r)a[s]=new t({type:"nonoptional",innerType:r[s]});return ot(this,"shape",a),a}});return Ne(e,o)}function at(t,e=0){if(t.aborted===!0)return!0;for(let n=e;n<t.issues.length;n++)if(t.issues[n]?.continue!==!0)return!0;return!1}function Wr(t,e=0){if(t.aborted===!0)return!0;for(let n=e;n<t.issues.length;n++)if(t.issues[n]?.continue===!1)return!0;return!1}function Ye(t,e){return e.map(n=>{var o;return(o=n).path??(o.path=[]),n.path.unshift(t),n})}function cn(t){return typeof t=="string"?t:t?.message}function Pe(t,e,n){let o=t.message?t.message:cn(t.inst?._zod.def?.error?.(t))??cn(e?.error?.(t))??cn(n.customError?.(t))??cn(n.localeError?.(t))??"Invalid input",{inst:r,continue:a,input:s,...i}=t;return i.path??(i.path=[]),i.message=o,e?.reportInput&&(i.input=s),i}function Qi(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function pn(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Vr(t){let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"nan":"number";case"object":{if(t===null)return"null";if(Array.isArray(t))return"array";let n=t;if(n&&Object.getPrototypeOf(n)!==Object.prototype&&"constructor"in n&&n.constructor)return n.constructor.name}}return e}function Ot(...t){let[e,n,o]=t;return typeof e=="string"?{message:e,code:"custom",input:n,inst:o}:{...e}}function Df(t){return Object.entries(t).filter(([e,n])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}function el(t){let e=atob(t),n=new Uint8Array(e.length);for(let o=0;o<e.length;o++)n[o]=e.charCodeAt(o);return n}function tl(t){let e="";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return btoa(e)}function Of(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n="=".repeat((4-e.length%4)%4);return el(e+n)}function jf(t){return tl(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Nf(t){let e=t.replace(/^0x/,"");if(e.length%2!==0)throw new Error("Invalid hex string length");let n=new Uint8Array(e.length/2);for(let o=0;o<e.length;o+=2)n[o/2]=Number.parseInt(e.slice(o,o+2),16);return n}function qf(t){return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}var qr=class{constructor(...e){}};var nl=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),t.message=JSON.stringify(e,At,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},wo=g("$ZodError",nl),Gr=g("$ZodError",nl,{Parent:Error});function ol(t,e=n=>n.message){let n={},o=[];for(let r of t.issues)r.path.length>0?(n[r.path[0]]=n[r.path[0]]||[],n[r.path[0]].push(e(r))):o.push(e(r));return{formErrors:o,fieldErrors:n}}function rl(t,e=n=>n.message){let n={_errors:[]},o=(r,a=[])=>{for(let s of r.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(i=>o({issues:i},[...a,...s.path]));else if(s.code==="invalid_key")o({issues:s.issues},[...a,...s.path]);else if(s.code==="invalid_element")o({issues:s.issues},[...a,...s.path]);else{let i=[...a,...s.path];if(i.length===0)n._errors.push(e(s));else{let l=n,c=0;for(;c<i.length;){let u=i[c];c===i.length-1?(l[u]=l[u]||{_errors:[]},l[u]._errors.push(e(s))):l[u]=l[u]||{_errors:[]},l=l[u],c++}}}};return o(t),n}var yo=t=>(e,n,o,r)=>{let a=o?{...o,async:!1}:{async:!1},s=e._zod.run({value:n,issues:[]},a);if(s instanceof Promise)throw new Ue;if(s.issues.length){let i=new(r?.Err??t)(s.issues.map(l=>Pe(l,a,ze())));throw fo(i,r?.callee),i}return s.value};var bo=t=>async(e,n,o,r)=>{let a=o?{...o,async:!0}:{async:!0},s=e._zod.run({value:n,issues:[]},a);if(s instanceof Promise&&(s=await s),s.issues.length){let i=new(r?.Err??t)(s.issues.map(l=>Pe(l,a,ze())));throw fo(i,r?.callee),i}return s.value};var mn=t=>(e,n,o)=>{let r=o?{...o,async:!1}:{async:!1},a=e._zod.run({value:n,issues:[]},r);if(a instanceof Promise)throw new Ue;return a.issues.length?{success:!1,error:new(t??wo)(a.issues.map(s=>Pe(s,r,ze())))}:{success:!0,data:a.value}},fn=mn(Gr),gn=t=>async(e,n,o)=>{let r=o?{...o,async:!0}:{async:!0},a=e._zod.run({value:n,issues:[]},r);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new t(a.issues.map(s=>Pe(s,r,ze())))}:{success:!0,data:a.value}},ko=gn(Gr),al=t=>(e,n,o)=>{let r=o?{...o,direction:"backward"}:{direction:"backward"};return yo(t)(e,n,r)};var sl=t=>(e,n,o)=>yo(t)(e,n,o);var il=t=>async(e,n,o)=>{let r=o?{...o,direction:"backward"}:{direction:"backward"};return bo(t)(e,n,r)};var ll=t=>async(e,n,o)=>bo(t)(e,n,o);var cl=t=>(e,n,o)=>{let r=o?{...o,direction:"backward"}:{direction:"backward"};return mn(t)(e,n,r)};var ul=t=>(e,n,o)=>mn(t)(e,n,o);var hl=t=>async(e,n,o)=>{let r=o?{...o,direction:"backward"}:{direction:"backward"};return gn(t)(e,n,r)};var dl=t=>async(e,n,o)=>gn(t)(e,n,o);var pl=/^[cC][0-9a-z]{6,}$/,ml=/^[0-9a-z]+$/,fl=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,gl=/^[0-9a-vA-V]{20}$/,wl=/^[A-Za-z0-9]{27}$/,yl=/^[a-zA-Z0-9_-]{21}$/,bl=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var kl=/^([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})$/,Hr=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([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)$/;var vl=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var Lf="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function xl(){return new RegExp(Lf,"u")}var Sl=/^(?:(?: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])$/,_l=/^(([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}|:))$/;var Il=/^((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])$/,zl=/^(([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])$/,Tl=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Jr=/^[A-Za-z0-9_-]*$/;var $l=/^https?$/,Cl=/^\+[1-9]\d{6,14}$/,Pl="(?:(?:\\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])))",El=new RegExp(`^${Pl}$`);function Rl(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Al(t){return new RegExp(`^${Rl(t)}$`)}function Dl(t){let e=Rl({precision:t.precision}),n=["Z"];t.local&&n.push(""),t.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let o=`${e}(?:${n.join("|")})`;return new RegExp(`^${Pl}T(?:${o})$`)}var Ol=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)};var jl=/^-?\d+$/,Kr=/^-?\d+(?:\.\d+)?$/,Nl=/^(?:true|false)$/i,ql=/^null$/i;var Ml=/^[^A-Z]*$/,Ll=/^[^a-z]*$/;var se=g("$ZodCheck",(t,e)=>{var n;t._zod??(t._zod={}),t._zod.def=e,(n=t._zod).onattach??(n.onattach=[])}),Zl={number:"number",bigint:"bigint",object:"date"},Yr=g("$ZodCheckLessThan",(t,e)=>{se.init(t,e);let n=Zl[typeof e.value];t._zod.onattach.push(o=>{let r=o._zod.bag,a=(e.inclusive?r.maximum:r.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<a&&(e.inclusive?r.maximum=e.value:r.exclusiveMaximum=e.value)}),t._zod.check=o=>{(e.inclusive?o.value<=e.value:o.value<e.value)||o.issues.push({origin:n,code:"too_big",maximum:typeof e.value=="object"?e.value.getTime():e.value,input:o.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Xr=g("$ZodCheckGreaterThan",(t,e)=>{se.init(t,e);let n=Zl[typeof e.value];t._zod.onattach.push(o=>{let r=o._zod.bag,a=(e.inclusive?r.minimum:r.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>a&&(e.inclusive?r.minimum=e.value:r.exclusiveMinimum=e.value)}),t._zod.check=o=>{(e.inclusive?o.value>=e.value:o.value>e.value)||o.issues.push({origin:n,code:"too_small",minimum:typeof e.value=="object"?e.value.getTime():e.value,input:o.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Bl=g("$ZodCheckMultipleOf",(t,e)=>{se.init(t,e),t._zod.onattach.push(n=>{var o;(o=n._zod.bag).multipleOf??(o.multipleOf=e.value)}),t._zod.check=n=>{if(typeof n.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%e.value===BigInt(0):Mr(n.value,e.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:e.value,input:n.value,inst:t,continue:!e.abort})}}),Ul=g("$ZodCheckNumberFormat",(t,e)=>{se.init(t,e),e.format=e.format||"float64";let n=e.format?.includes("int"),o=n?"int":"number",[r,a]=Fr[e.format];t._zod.onattach.push(s=>{let i=s._zod.bag;i.format=e.format,i.minimum=r,i.maximum=a,n&&(i.pattern=jl)}),t._zod.check=s=>{let i=s.value;if(n){if(!Number.isInteger(i)){s.issues.push({expected:o,format:e.format,code:"invalid_type",continue:!1,input:i,inst:t});return}if(!Number.isSafeInteger(i)){i>0?s.issues.push({input:i,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:o,inclusive:!0,continue:!e.abort}):s.issues.push({input:i,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:o,inclusive:!0,continue:!e.abort});return}}i<r&&s.issues.push({origin:"number",input:i,code:"too_small",minimum:r,inclusive:!0,inst:t,continue:!e.abort}),i>a&&s.issues.push({origin:"number",input:i,code:"too_big",maximum:a,inclusive:!0,inst:t,continue:!e.abort})}});var Fl=g("$ZodCheckMaxLength",(t,e)=>{var n;se.init(t,e),(n=t._zod.def).when??(n.when=o=>{let r=o.value;return!hn(r)&&r.length!==void 0}),t._zod.onattach.push(o=>{let r=o._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<r&&(o._zod.bag.maximum=e.maximum)}),t._zod.check=o=>{let r=o.value;if(r.length<=e.maximum)return;let s=pn(r);o.issues.push({origin:s,code:"too_big",maximum:e.maximum,inclusive:!0,input:r,inst:t,continue:!e.abort})}}),Wl=g("$ZodCheckMinLength",(t,e)=>{var n;se.init(t,e),(n=t._zod.def).when??(n.when=o=>{let r=o.value;return!hn(r)&&r.length!==void 0}),t._zod.onattach.push(o=>{let r=o._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>r&&(o._zod.bag.minimum=e.minimum)}),t._zod.check=o=>{let r=o.value;if(r.length>=e.minimum)return;let s=pn(r);o.issues.push({origin:s,code:"too_small",minimum:e.minimum,inclusive:!0,input:r,inst:t,continue:!e.abort})}}),Vl=g("$ZodCheckLengthEquals",(t,e)=>{var n;se.init(t,e),(n=t._zod.def).when??(n.when=o=>{let r=o.value;return!hn(r)&&r.length!==void 0}),t._zod.onattach.push(o=>{let r=o._zod.bag;r.minimum=e.length,r.maximum=e.length,r.length=e.length}),t._zod.check=o=>{let r=o.value,a=r.length;if(a===e.length)return;let s=pn(r),i=a>e.length;o.issues.push({origin:s,...i?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:o.value,inst:t,continue:!e.abort})}}),wn=g("$ZodCheckStringFormat",(t,e)=>{var n,o;se.init(t,e),t._zod.onattach.push(r=>{let a=r._zod.bag;a.format=e.format,e.pattern&&(a.patterns??(a.patterns=new Set),a.patterns.add(e.pattern))}),e.pattern?(n=t._zod).check??(n.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:e.format,input:r.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(o=t._zod).check??(o.check=()=>{})}),Gl=g("$ZodCheckRegex",(t,e)=>{wn.init(t,e),t._zod.check=n=>{e.pattern.lastIndex=0,!e.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),Hl=g("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Ml),wn.init(t,e)}),Jl=g("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Ll),wn.init(t,e)}),Kl=g("$ZodCheckIncludes",(t,e)=>{se.init(t,e);let n=Ke(e.includes),o=new RegExp(typeof e.position=="number"?`^.{${e.position}}${n}`:n);e.pattern=o,t._zod.onattach.push(r=>{let a=r._zod.bag;a.patterns??(a.patterns=new Set),a.patterns.add(o)}),t._zod.check=r=>{r.value.includes(e.includes,e.position)||r.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:r.value,inst:t,continue:!e.abort})}}),Yl=g("$ZodCheckStartsWith",(t,e)=>{se.init(t,e);let n=new RegExp(`^${Ke(e.prefix)}.*`);e.pattern??(e.pattern=n),t._zod.onattach.push(o=>{let r=o._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(n)}),t._zod.check=o=>{o.value.startsWith(e.prefix)||o.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:o.value,inst:t,continue:!e.abort})}}),Xl=g("$ZodCheckEndsWith",(t,e)=>{se.init(t,e);let n=new RegExp(`.*${Ke(e.suffix)}$`);e.pattern??(e.pattern=n),t._zod.onattach.push(o=>{let r=o._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(n)}),t._zod.check=o=>{o.value.endsWith(e.suffix)||o.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:o.value,inst:t,continue:!e.abort})}});var Ql=g("$ZodCheckOverwrite",(t,e)=>{se.init(t,e),t._zod.check=n=>{n.value=e.tx(n.value)}});var xo=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let o=e.split(`
9
+ deps: ${n}}`};var mS={keyword:"dependencies",type:"object",schemaType:"object",error:Ge.error,code(t){let[e,n]=fS(t);pm(t,e),mm(t,n)}};function fS({schema:t}){let e={},n={};for(let o in t){if(o==="__proto__")continue;let r=Array.isArray(t[o])?e:n;r[o]=t[o]}return[e,n]}function pm(t,e=t.schema){let{gen:n,data:o,it:r}=t;if(Object.keys(e).length===0)return;let a=n.let("missing");for(let s in e){let i=e[s];if(i.length===0)continue;let l=(0,ho.propertyInData)(n,o,s,r.opts.ownProperties);t.setParams({property:s,depsCount:i.length,deps:i.join(", ")}),r.allErrors?n.if(l,()=>{for(let c of i)(0,ho.checkReportMissingProp)(t,c)}):(n.if((0,bi._)`${l} && (${(0,ho.checkMissingProp)(t,i,a)})`),(0,ho.reportMissingProp)(t,a),n.else())}}Ge.validatePropertyDeps=pm;function mm(t,e=t.schema){let{gen:n,data:o,keyword:r,it:a}=t,s=n.name("valid");for(let i in e)(0,pS.alwaysValidSchema)(a,e[i])||(n.if((0,ho.propertyInData)(n,o,i,a.opts.ownProperties),()=>{let l=t.subschema({keyword:r,schemaProp:i},s);t.mergeValidEvaluated(l,s)},()=>n.var(s,!0)),t.ok(s))}Ge.validateSchemaDeps=mm;Ge.default=mS});var wm=k(ki=>{"use strict";Object.defineProperty(ki,"__esModule",{value:!0});var gm=R(),gS=M(),wS={message:"property name must be valid",params:({params:t})=>(0,gm._)`{propertyName: ${t.propertyName}}`},yS={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:wS,code(t){let{gen:e,schema:n,data:o,it:r}=t;if((0,gS.alwaysValidSchema)(r,n))return;let a=e.name("valid");e.forIn("key",o,s=>{t.setParams({propertyName:s}),t.subschema({keyword:"propertyNames",data:s,dataTypes:["string"],propertyName:s,compositeRule:!0},a),e.if((0,gm.not)(a),()=>{t.error(!0),r.allErrors||e.break()})}),t.ok(a)}};ki.default=yS});var xi=k(vi=>{"use strict";Object.defineProperty(vi,"__esModule",{value:!0});var Sr=je(),Ze=R(),bS=nt(),_r=M(),kS={message:"must NOT have additional properties",params:({params:t})=>(0,Ze._)`{additionalProperty: ${t.additionalProperty}}`},vS={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:kS,code(t){let{gen:e,schema:n,parentSchema:o,data:r,errsCount:a,it:s}=t;if(!a)throw new Error("ajv implementation error");let{allErrors:i,opts:l}=s;if(s.props=!0,l.removeAdditional!=="all"&&(0,_r.alwaysValidSchema)(s,n))return;let c=(0,Sr.allSchemaProperties)(o.properties),u=(0,Sr.allSchemaProperties)(o.patternProperties);h(),t.ok((0,Ze._)`${a} === ${bS.default.errors}`);function h(){e.forIn("key",r,y=>{!c.length&&!u.length?m(y):e.if(d(y),()=>m(y))})}function d(y){let b;if(c.length>8){let x=(0,_r.schemaRefOrVal)(s,o.properties,"properties");b=(0,Sr.isOwnProperty)(e,x,y)}else c.length?b=(0,Ze.or)(...c.map(x=>(0,Ze._)`${y} === ${x}`)):b=Ze.nil;return u.length&&(b=(0,Ze.or)(b,...u.map(x=>(0,Ze._)`${(0,Sr.usePattern)(t,x)}.test(${y})`))),(0,Ze.not)(b)}function p(y){e.code((0,Ze._)`delete ${r}[${y}]`)}function m(y){if(l.removeAdditional==="all"||l.removeAdditional&&n===!1){p(y);return}if(n===!1){t.setParams({additionalProperty:y}),t.error(),i||e.break();return}if(typeof n=="object"&&!(0,_r.alwaysValidSchema)(s,n)){let b=e.name("valid");l.removeAdditional==="failing"?(w(y,b,!1),e.if((0,Ze.not)(b),()=>{t.reset(),p(y)})):(w(y,b),i||e.if((0,Ze.not)(b),()=>e.break()))}}function w(y,b,x){let S={keyword:"additionalProperties",dataProp:y,dataPropType:_r.Type.Str};x===!1&&Object.assign(S,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(S,b)}}};vi.default=vS});var km=k(_i=>{"use strict";Object.defineProperty(_i,"__esModule",{value:!0});var xS=Yn(),ym=je(),Si=M(),bm=xi(),SS={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:n,parentSchema:o,data:r,it:a}=t;a.opts.removeAdditional==="all"&&o.additionalProperties===void 0&&bm.default.code(new xS.KeywordCxt(a,bm.default,"additionalProperties"));let s=(0,ym.allSchemaProperties)(n);for(let h of s)a.definedProperties.add(h);a.opts.unevaluated&&s.length&&a.props!==!0&&(a.props=Si.mergeEvaluated.props(e,(0,Si.toHash)(s),a.props));let i=s.filter(h=>!(0,Si.alwaysValidSchema)(a,n[h]));if(i.length===0)return;let l=e.name("valid");for(let h of i)c(h)?u(h):(e.if((0,ym.propertyInData)(e,r,h,a.opts.ownProperties)),u(h),a.allErrors||e.else().var(l,!0),e.endIf()),t.it.definedProperties.add(h),t.ok(l);function c(h){return a.opts.useDefaults&&!a.compositeRule&&n[h].default!==void 0}function u(h){t.subschema({keyword:"properties",schemaProp:h,dataProp:h},l)}}};_i.default=SS});var _m=k(Ii=>{"use strict";Object.defineProperty(Ii,"__esModule",{value:!0});var vm=je(),Ir=R(),xm=M(),Sm=M(),_S={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:n,data:o,parentSchema:r,it:a}=t,{opts:s}=a,i=(0,vm.allSchemaProperties)(n),l=i.filter(w=>(0,xm.alwaysValidSchema)(a,n[w]));if(i.length===0||l.length===i.length&&(!a.opts.unevaluated||a.props===!0))return;let c=s.strictSchema&&!s.allowMatchingProperties&&r.properties,u=e.name("valid");a.props!==!0&&!(a.props instanceof Ir.Name)&&(a.props=(0,Sm.evaluatedPropsToName)(e,a.props));let{props:h}=a;d();function d(){for(let w of i)c&&p(w),a.allErrors?m(w):(e.var(u,!0),m(w),e.if(u))}function p(w){for(let y in c)new RegExp(w).test(y)&&(0,xm.checkStrictMode)(a,`property ${y} matches pattern ${w} (use allowMatchingProperties)`)}function m(w){e.forIn("key",o,y=>{e.if((0,Ir._)`${(0,vm.usePattern)(t,w)}.test(${y})`,()=>{let b=l.includes(w);b||t.subschema({keyword:"patternProperties",schemaProp:w,dataProp:y,dataPropType:Sm.Type.Str},u),a.opts.unevaluated&&h!==!0?e.assign((0,Ir._)`${h}[${y}]`,!0):!b&&!a.allErrors&&e.if((0,Ir.not)(u),()=>e.break())})})}}};Ii.default=_S});var Im=k(zi=>{"use strict";Object.defineProperty(zi,"__esModule",{value:!0});var IS=M(),zS={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:n,it:o}=t;if((0,IS.alwaysValidSchema)(o,n)){t.fail();return}let r=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},r),t.failResult(r,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};zi.default=zS});var zm=k(Ti=>{"use strict";Object.defineProperty(Ti,"__esModule",{value:!0});var TS=je(),CS={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:TS.validateUnion,error:{message:"must match a schema in anyOf"}};Ti.default=CS});var Tm=k(Ci=>{"use strict";Object.defineProperty(Ci,"__esModule",{value:!0});var zr=R(),$S=M(),PS={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,zr._)`{passingSchemas: ${t.passing}}`},ES={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:PS,code(t){let{gen:e,schema:n,parentSchema:o,it:r}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");if(r.opts.discriminator&&o.discriminator)return;let a=n,s=e.let("valid",!1),i=e.let("passing",null),l=e.name("_valid");t.setParams({passing:i}),e.block(c),t.result(s,()=>t.reset(),()=>t.error(!0));function c(){a.forEach((u,h)=>{let d;(0,$S.alwaysValidSchema)(r,u)?e.var(l,!0):d=t.subschema({keyword:"oneOf",schemaProp:h,compositeRule:!0},l),h>0&&e.if((0,zr._)`${l} && ${s}`).assign(s,!1).assign(i,(0,zr._)`[${i}, ${h}]`).else(),e.if(l,()=>{e.assign(s,!0),e.assign(i,h),d&&t.mergeEvaluated(d,zr.Name)})})}}};Ci.default=ES});var Cm=k($i=>{"use strict";Object.defineProperty($i,"__esModule",{value:!0});var RS=M(),AS={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:n,it:o}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");let r=e.name("valid");n.forEach((a,s)=>{if((0,RS.alwaysValidSchema)(o,a))return;let i=t.subschema({keyword:"allOf",schemaProp:s},r);t.ok(r),t.mergeEvaluated(i)})}};$i.default=AS});var Em=k(Pi=>{"use strict";Object.defineProperty(Pi,"__esModule",{value:!0});var Tr=R(),Pm=M(),jS={message:({params:t})=>(0,Tr.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Tr._)`{failingKeyword: ${t.ifClause}}`},DS={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:jS,code(t){let{gen:e,parentSchema:n,it:o}=t;n.then===void 0&&n.else===void 0&&(0,Pm.checkStrictMode)(o,'"if" without "then" and "else" is ignored');let r=$m(o,"then"),a=$m(o,"else");if(!r&&!a)return;let s=e.let("valid",!0),i=e.name("_valid");if(l(),t.reset(),r&&a){let u=e.let("ifClause");t.setParams({ifClause:u}),e.if(i,c("then",u),c("else",u))}else r?e.if(i,c("then")):e.if((0,Tr.not)(i),c("else"));t.pass(s,()=>t.error(!0));function l(){let u=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},i);t.mergeEvaluated(u)}function c(u,h){return()=>{let d=t.subschema({keyword:u},i);e.assign(s,i),t.mergeValidEvaluated(d,s),h?e.assign(h,(0,Tr._)`${u}`):t.setParams({ifClause:u})}}}};function $m(t,e){let n=t.schema[e];return n!==void 0&&!(0,Pm.alwaysValidSchema)(t,n)}Pi.default=DS});var Rm=k(Ei=>{"use strict";Object.defineProperty(Ei,"__esModule",{value:!0});var OS=M(),NS={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:n}){e.if===void 0&&(0,OS.checkStrictMode)(n,`"${t}" without "if" is ignored`)}};Ei.default=NS});var Am=k(Ri=>{"use strict";Object.defineProperty(Ri,"__esModule",{value:!0});var qS=mi(),MS=cm(),LS=fi(),BS=hm(),ZS=dm(),FS=fm(),US=wm(),WS=xi(),VS=km(),GS=_m(),HS=Im(),JS=zm(),KS=Tm(),YS=Cm(),XS=Em(),QS=Rm();function e_(t=!1){let e=[HS.default,JS.default,KS.default,YS.default,XS.default,QS.default,US.default,WS.default,FS.default,VS.default,GS.default];return t?e.push(MS.default,BS.default):e.push(qS.default,LS.default),e.push(ZS.default),e}Ri.default=e_});var jm=k(Ai=>{"use strict";Object.defineProperty(Ai,"__esModule",{value:!0});var oe=R(),t_={message:({schemaCode:t})=>(0,oe.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,oe._)`{format: ${t}}`},n_={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:t_,code(t,e){let{gen:n,data:o,$data:r,schema:a,schemaCode:s,it:i}=t,{opts:l,errSchemaPath:c,schemaEnv:u,self:h}=i;if(!l.validateFormats)return;r?d():p();function d(){let m=n.scopeValue("formats",{ref:h.formats,code:l.code.formats}),w=n.const("fDef",(0,oe._)`${m}[${s}]`),y=n.let("fType"),b=n.let("format");n.if((0,oe._)`typeof ${w} == "object" && !(${w} instanceof RegExp)`,()=>n.assign(y,(0,oe._)`${w}.type || "string"`).assign(b,(0,oe._)`${w}.validate`),()=>n.assign(y,(0,oe._)`"string"`).assign(b,w)),t.fail$data((0,oe.or)(x(),S()));function x(){return l.strictSchema===!1?oe.nil:(0,oe._)`${s} && !${b}`}function S(){let T=u.$async?(0,oe._)`(${w}.async ? await ${b}(${o}) : ${b}(${o}))`:(0,oe._)`${b}(${o})`,_=(0,oe._)`(typeof ${b} == "function" ? ${T} : ${b}.test(${o}))`;return(0,oe._)`${b} && ${b} !== true && ${y} === ${e} && !${_}`}}function p(){let m=h.formats[a];if(!m){x();return}if(m===!0)return;let[w,y,b]=S(m);w===e&&t.pass(T());function x(){if(l.strictSchema===!1){h.logger.warn(_());return}throw new Error(_());function _(){return`unknown format "${a}" ignored in schema at path "${c}"`}}function S(_){let Ie=_ instanceof RegExp?(0,oe.regexpCode)(_):l.code.formats?(0,oe._)`${l.code.formats}${(0,oe.getProperty)(a)}`:void 0,$e=n.scopeValue("formats",{key:a,ref:_,code:Ie});return typeof _=="object"&&!(_ instanceof RegExp)?[_.type||"string",_.validate,(0,oe._)`${$e}.validate`]:["string",_,$e]}function T(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!u.$async)throw new Error("async format in sync schema");return(0,oe._)`await ${b}(${o})`}return typeof y=="function"?(0,oe._)`${b}(${o})`:(0,oe._)`${b}.test(${o})`}}}};Ai.default=n_});var Dm=k(ji=>{"use strict";Object.defineProperty(ji,"__esModule",{value:!0});var o_=jm(),r_=[o_.default];ji.default=r_});var Om=k(tn=>{"use strict";Object.defineProperty(tn,"__esModule",{value:!0});tn.contentVocabulary=tn.metadataVocabulary=void 0;tn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];tn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var qm=k(Di=>{"use strict";Object.defineProperty(Di,"__esModule",{value:!0});var a_=Wp(),s_=am(),i_=Am(),l_=Dm(),Nm=Om(),c_=[a_.default,s_.default,(0,i_.default)(),l_.default,Nm.metadataVocabulary,Nm.contentVocabulary];Di.default=c_});var Lm=k(Cr=>{"use strict";Object.defineProperty(Cr,"__esModule",{value:!0});Cr.DiscrError=void 0;var Mm;(function(t){t.Tag="tag",t.Mapping="mapping"})(Mm||(Cr.DiscrError=Mm={}))});var Zm=k(Ni=>{"use strict";Object.defineProperty(Ni,"__esModule",{value:!0});var nn=R(),Oi=Lm(),Bm=hr(),u_=Xn(),h_=M(),d_={message:({params:{discrError:t,tagName:e}})=>t===Oi.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:n}})=>(0,nn._)`{error: ${t}, tag: ${n}, tagValue: ${e}}`},p_={keyword:"discriminator",type:"object",schemaType:"object",error:d_,code(t){let{gen:e,data:n,schema:o,parentSchema:r,it:a}=t,{oneOf:s}=r;if(!a.opts.discriminator)throw new Error("discriminator: requires discriminator option");let i=o.propertyName;if(typeof i!="string")throw new Error("discriminator: requires propertyName");if(o.mapping)throw new Error("discriminator: mapping is not supported");if(!s)throw new Error("discriminator: requires oneOf keyword");let l=e.let("valid",!1),c=e.const("tag",(0,nn._)`${n}${(0,nn.getProperty)(i)}`);e.if((0,nn._)`typeof ${c} == "string"`,()=>u(),()=>t.error(!1,{discrError:Oi.DiscrError.Tag,tag:c,tagName:i})),t.ok(l);function u(){let p=d();e.if(!1);for(let m in p)e.elseIf((0,nn._)`${c} === ${m}`),e.assign(l,h(p[m]));e.else(),t.error(!1,{discrError:Oi.DiscrError.Mapping,tag:c,tagName:i}),e.endIf()}function h(p){let m=e.name("valid"),w=t.subschema({keyword:"oneOf",schemaProp:p},m);return t.mergeEvaluated(w,nn.Name),m}function d(){var p;let m={},w=b(r),y=!0;for(let T=0;T<s.length;T++){let _=s[T];if(_?.$ref&&!(0,h_.schemaHasRulesButRef)(_,a.self.RULES)){let $e=_.$ref;if(_=Bm.resolveRef.call(a.self,a.schemaEnv.root,a.baseId,$e),_ instanceof Bm.SchemaEnv&&(_=_.schema),_===void 0)throw new u_.default(a.opts.uriResolver,a.baseId,$e)}let Ie=(p=_?.properties)===null||p===void 0?void 0:p[i];if(typeof Ie!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${i}"`);y=y&&(w||b(_)),x(Ie,T)}if(!y)throw new Error(`discriminator: "${i}" must be required`);return m;function b({required:T}){return Array.isArray(T)&&T.includes(i)}function x(T,_){if(T.const)S(T.const,_);else if(T.enum)for(let Ie of T.enum)S(Ie,_);else throw new Error(`discriminator: "properties/${i}" must have "const" or "enum"`)}function S(T,_){if(typeof T!="string"||T in m)throw new Error(`discriminator: "${i}" values must be unique strings`);m[T]=_}}}};Ni.default=p_});var Fm=k((wE,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 Mi=k((Y,qi)=>{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.MissingRefError=Y.ValidationError=Y.CodeGen=Y.Name=Y.nil=Y.stringify=Y.str=Y._=Y.KeywordCxt=Y.Ajv=void 0;var f_=Mp(),g_=qm(),w_=Zm(),Um=Fm(),y_=["/properties"],$r="http://json-schema.org/draft-07/schema",on=class extends f_.default{_addVocabularies(){super._addVocabularies(),g_.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(w_.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(Um,y_):Um;this.addMetaSchema(e,$r,!1),this.refs["http://json-schema.org/schema"]=$r}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema($r)?$r:void 0)}};Y.Ajv=on;qi.exports=Y=on;qi.exports.Ajv=on;Object.defineProperty(Y,"__esModule",{value:!0});Y.default=on;var b_=Yn();Object.defineProperty(Y,"KeywordCxt",{enumerable:!0,get:function(){return b_.KeywordCxt}});var rn=R();Object.defineProperty(Y,"_",{enumerable:!0,get:function(){return rn._}});Object.defineProperty(Y,"str",{enumerable:!0,get:function(){return rn.str}});Object.defineProperty(Y,"stringify",{enumerable:!0,get:function(){return rn.stringify}});Object.defineProperty(Y,"nil",{enumerable:!0,get:function(){return rn.nil}});Object.defineProperty(Y,"Name",{enumerable:!0,get:function(){return rn.Name}});Object.defineProperty(Y,"CodeGen",{enumerable:!0,get:function(){return rn.CodeGen}});var k_=cr();Object.defineProperty(Y,"ValidationError",{enumerable:!0,get:function(){return k_.default}});var v_=Xn();Object.defineProperty(Y,"MissingRefError",{enumerable:!0,get:function(){return v_.default}})});var Xm=k(Je=>{"use strict";Object.defineProperty(Je,"__esModule",{value:!0});Je.formatNames=Je.fastFormats=Je.fullFormats=void 0;function He(t,e){return{validate:t,compare:e}}Je.fullFormats={date:He(Hm,Fi),time:He(Bi(!0),Ui),"date-time":He(Wm(!0),Km),"iso-time":He(Bi(),Jm),"iso-date-time":He(Wm(),Ym),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:T_,"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:j_,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:C_,int32:{type:"number",validate:E_},int64:{type:"number",validate:R_},float:{type:"number",validate:Gm},double:{type:"number",validate:Gm},password:!0,binary:!0};Je.fastFormats={...Je.fullFormats,date:He(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Fi),time:He(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Ui),"date-time":He(/^\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,Km),"iso-time":He(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Jm),"iso-date-time":He(/^\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,Ym),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};Je.formatNames=Object.keys(Je.fullFormats);function x_(t){return t%4===0&&(t%100!==0||t%400===0)}var S_=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,__=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Hm(t){let e=S_.exec(t);if(!e)return!1;let n=+e[1],o=+e[2],r=+e[3];return o>=1&&o<=12&&r>=1&&r<=(o===2&&x_(n)?29:__[o])}function Fi(t,e){if(t&&e)return t>e?1:t<e?-1:0}var Li=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Bi(t){return function(n){let o=Li.exec(n);if(!o)return!1;let r=+o[1],a=+o[2],s=+o[3],i=o[4],l=o[5]==="-"?-1:1,c=+(o[6]||0),u=+(o[7]||0);if(c>23||u>59||t&&!i)return!1;if(r<=23&&a<=59&&s<60)return!0;let h=a-u*l,d=r-c*l-(h<0?1:0);return(d===23||d===-1)&&(h===59||h===-1)&&s<61}}function Ui(t,e){if(!(t&&e))return;let n=new Date("2020-01-01T"+t).valueOf(),o=new Date("2020-01-01T"+e).valueOf();if(n&&o)return n-o}function Jm(t,e){if(!(t&&e))return;let n=Li.exec(t),o=Li.exec(e);if(n&&o)return t=n[1]+n[2]+n[3],e=o[1]+o[2]+o[3],t>e?1:t<e?-1:0}var Zi=/t|\s/i;function Wm(t){let e=Bi(t);return function(o){let r=o.split(Zi);return r.length===2&&Hm(r[0])&&e(r[1])}}function Km(t,e){if(!(t&&e))return;let n=new Date(t).valueOf(),o=new Date(e).valueOf();if(n&&o)return n-o}function Ym(t,e){if(!(t&&e))return;let[n,o]=t.split(Zi),[r,a]=e.split(Zi),s=Fi(n,r);if(s!==void 0)return s||Ui(o,a)}var I_=/\/|:/,z_=/^(?:[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 T_(t){return I_.test(t)&&z_.test(t)}var Vm=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function C_(t){return Vm.lastIndex=0,Vm.test(t)}var $_=-(2**31),P_=2**31-1;function E_(t){return Number.isInteger(t)&&t<=P_&&t>=$_}function R_(t){return Number.isInteger(t)}function Gm(){return!0}var A_=/[^\\]\\Z/;function j_(t){if(A_.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var Qm=k(an=>{"use strict";Object.defineProperty(an,"__esModule",{value:!0});an.formatLimitDefinition=void 0;var D_=Mi(),Fe=R(),yt=Fe.operators,Pr={formatMaximum:{okStr:"<=",ok:yt.LTE,fail:yt.GT},formatMinimum:{okStr:">=",ok:yt.GTE,fail:yt.LT},formatExclusiveMaximum:{okStr:"<",ok:yt.LT,fail:yt.GTE},formatExclusiveMinimum:{okStr:">",ok:yt.GT,fail:yt.LTE}},O_={message:({keyword:t,schemaCode:e})=>(0,Fe.str)`should be ${Pr[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Fe._)`{comparison: ${Pr[t].okStr}, limit: ${e}}`};an.formatLimitDefinition={keyword:Object.keys(Pr),type:"string",schemaType:"string",$data:!0,error:O_,code(t){let{gen:e,data:n,schemaCode:o,keyword:r,it:a}=t,{opts:s,self:i}=a;if(!s.validateFormats)return;let l=new D_.KeywordCxt(a,i.RULES.all.format.definition,"format");l.$data?c():u();function c(){let d=e.scopeValue("formats",{ref:i.formats,code:s.code.formats}),p=e.const("fmt",(0,Fe._)`${d}[${l.schemaCode}]`);t.fail$data((0,Fe.or)((0,Fe._)`typeof ${p} != "object"`,(0,Fe._)`${p} instanceof RegExp`,(0,Fe._)`typeof ${p}.compare != "function"`,h(p)))}function u(){let d=l.schema,p=i.formats[d];if(!p||p===!0)return;if(typeof p!="object"||p instanceof RegExp||typeof p.compare!="function")throw new Error(`"${r}": format "${d}" does not define "compare" function`);let m=e.scopeValue("formats",{key:d,ref:p,code:s.code.formats?(0,Fe._)`${s.code.formats}${(0,Fe.getProperty)(d)}`:void 0});t.fail$data(h(m))}function h(d){return(0,Fe._)`${d}.compare(${n}, ${o}) ${Pr[r].fail} 0`}},dependencies:["format"]};var N_=t=>(t.addKeyword(an.formatLimitDefinition),t);an.default=N_});var of=k((po,nf)=>{"use strict";Object.defineProperty(po,"__esModule",{value:!0});var sn=Xm(),q_=Qm(),Wi=R(),ef=new Wi.Name("fullFormats"),M_=new Wi.Name("fastFormats"),Vi=(t,e={keywords:!0})=>{if(Array.isArray(e))return tf(t,e,sn.fullFormats,ef),t;let[n,o]=e.mode==="fast"?[sn.fastFormats,M_]:[sn.fullFormats,ef],r=e.formats||sn.formatNames;return tf(t,r,n,o),e.keywords&&(0,q_.default)(t),t};Vi.get=(t,e="full")=>{let o=(e==="fast"?sn.fastFormats:sn.fullFormats)[t];if(!o)throw new Error(`Unknown format "${t}"`);return o};function tf(t,e,n,o){var r,a;(r=(a=t.opts.code).formats)!==null&&r!==void 0||(a.formats=(0,Wi._)`require("ajv-formats/dist/formats").${o}`);for(let s of e)t.addFormat(s,n[s])}nf.exports=po=Vi;Object.defineProperty(po,"__esModule",{value:!0});po.default=Vi});var Qi;function g(t,e,n){function o(i,l){if(i._zod||Object.defineProperty(i,"_zod",{value:{def:l,constr:s,traits:new Set},enumerable:!1}),i._zod.traits.has(t))return;i._zod.traits.add(t),e(i,l);let c=s.prototype,u=Object.keys(c);for(let h=0;h<u.length;h++){let d=u[h];d in i||(i[d]=c[d].bind(i))}}let r=n?.Parent??Object;class a extends r{}Object.defineProperty(a,"name",{value:t});function s(i){var l;let c=n?.Parent?new a:this;o(c,i),(l=c._zod).deferred??(l.deferred=[]);for(let u of c._zod.deferred)u();return c}return Object.defineProperty(s,"init",{value:o}),Object.defineProperty(s,Symbol.hasInstance,{value:i=>n?.Parent&&i instanceof n.Parent?!0:i?._zod?.traits?.has(t)}),Object.defineProperty(s,"name",{value:t}),s}var Ue=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Rt=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}};(Qi=globalThis).__zod_globalConfig??(Qi.__zod_globalConfig={});var At=globalThis.__zod_globalConfig;function ze(t){return t&&Object.assign(At,t),At}var q={};Yi(q,{BIGINT_FORMAT_RANGES:()=>ol,Class:()=>Zr,NUMBER_FORMAT_RANGES:()=>Hr,aborted:()=>st,allowsEval:()=>Wr,assert:()=>_f,assertEqual:()=>kf,assertIs:()=>xf,assertNever:()=>Sf,assertNotEqual:()=>vf,assignProp:()=>rt,base64ToUint8Array:()=>al,base64urlToUint8Array:()=>Bf,cached:()=>Dt,captureStackTrace:()=>wo,cleanEnum:()=>Lf,cleanRegex:()=>mn,clone:()=>qe,cloneDef:()=>zf,createTransparentProxy:()=>Rf,defineLazy:()=>Z,esc:()=>go,escapeRegex:()=>Ye,explicitlyAborted:()=>Jr,extend:()=>Df,finalizeIssue:()=>Pe,floatSafeRemainder:()=>Fr,getElementAtPath:()=>Tf,getEnumValues:()=>dn,getLengthableOrigin:()=>fn,getParsedType:()=>Ef,getSizableOrigin:()=>rl,hexToUint8Array:()=>Ff,isObject:()=>bt,isPlainObject:()=>at,issue:()=>Ot,joinValues:()=>fo,jsonStringifyReplacer:()=>jt,merge:()=>Nf,mergeDefs:()=>Ke,normalizeParams:()=>C,nullish:()=>pn,numKeys:()=>Pf,objectClone:()=>If,omit:()=>jf,optionalKeys:()=>Gr,parsedType:()=>Kr,partial:()=>qf,pick:()=>Af,prefixIssues:()=>Xe,primitiveTypes:()=>nl,promiseAllObject:()=>Cf,propertyKeyTypes:()=>Vr,randomString:()=>$f,required:()=>Mf,safeExtend:()=>Of,shallowClone:()=>tl,slugify:()=>Ur,stringifyPrimitive:()=>yo,uint8ArrayToBase64:()=>sl,uint8ArrayToBase64url:()=>Zf,uint8ArrayToHex:()=>Uf,unwrapMessage:()=>hn});function kf(t){return t}function vf(t){return t}function xf(t){}function Sf(t){throw new Error("Unexpected value in exhaustive check")}function _f(t){}function dn(t){let e=Object.values(t).filter(o=>typeof o=="number");return Object.entries(t).filter(([o,r])=>e.indexOf(+o)===-1).map(([o,r])=>r)}function fo(t,e="|"){return t.map(n=>yo(n)).join(e)}function jt(t,e){return typeof e=="bigint"?e.toString():e}function Dt(t){return{get value(){{let n=t();return Object.defineProperty(this,"value",{value:n}),n}throw new Error("cached value already set")}}}function pn(t){return t==null}function mn(t){let e=t.startsWith("^")?1:0,n=t.endsWith("$")?t.length-1:t.length;return t.slice(e,n)}function Fr(t,e){let n=t/e,o=Math.round(n),r=Number.EPSILON*Math.max(Math.abs(n),1);return Math.abs(n-o)<r?0:n-o}var el=Symbol("evaluating");function Z(t,e,n){let o;Object.defineProperty(t,e,{get(){if(o!==el)return o===void 0&&(o=el,o=n()),o},set(r){Object.defineProperty(t,e,{value:r})},configurable:!0})}function If(t){return Object.create(Object.getPrototypeOf(t),Object.getOwnPropertyDescriptors(t))}function rt(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Ke(...t){let e={};for(let n of t){let o=Object.getOwnPropertyDescriptors(n);Object.assign(e,o)}return Object.defineProperties({},e)}function zf(t){return Ke(t._zod.def)}function Tf(t,e){return e?e.reduce((n,o)=>n?.[o],t):t}function Cf(t){let e=Object.keys(t),n=e.map(o=>t[o]);return Promise.all(n).then(o=>{let r={};for(let a=0;a<e.length;a++)r[e[a]]=o[a];return r})}function $f(t=10){let e="abcdefghijklmnopqrstuvwxyz",n="";for(let o=0;o<t;o++)n+=e[Math.floor(Math.random()*e.length)];return n}function go(t){return JSON.stringify(t)}function Ur(t){return t.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var wo="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};function bt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Wr=Dt(()=>{if(At.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function at(t){if(bt(t)===!1)return!1;let e=t.constructor;if(e===void 0||typeof e!="function")return!0;let n=e.prototype;return!(bt(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function tl(t){return at(t)?{...t}:Array.isArray(t)?[...t]:t instanceof Map?new Map(t):t instanceof Set?new Set(t):t}function Pf(t){let e=0;for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&e++;return e}var Ef=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},Vr=new Set(["string","number","symbol"]),nl=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Ye(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function qe(t,e,n){let o=new t._zod.constr(e??t._zod.def);return(!e||n?.parent)&&(o._zod.parent=t),o}function C(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function Rf(t){let e;return new Proxy({},{get(n,o,r){return e??(e=t()),Reflect.get(e,o,r)},set(n,o,r,a){return e??(e=t()),Reflect.set(e,o,r,a)},has(n,o){return e??(e=t()),Reflect.has(e,o)},deleteProperty(n,o){return e??(e=t()),Reflect.deleteProperty(e,o)},ownKeys(n){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(n,o){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,o)},defineProperty(n,o,r){return e??(e=t()),Reflect.defineProperty(e,o,r)}})}function yo(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function Gr(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var Hr={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},ol={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function Af(t,e){let n=t._zod.def,o=n.checks;if(o&&o.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let a=Ke(t._zod.def,{get shape(){let s={};for(let i in e){if(!(i in n.shape))throw new Error(`Unrecognized key: "${i}"`);e[i]&&(s[i]=n.shape[i])}return rt(this,"shape",s),s},checks:[]});return qe(t,a)}function jf(t,e){let n=t._zod.def,o=n.checks;if(o&&o.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let a=Ke(t._zod.def,{get shape(){let s={...t._zod.def.shape};for(let i in e){if(!(i in n.shape))throw new Error(`Unrecognized key: "${i}"`);e[i]&&delete s[i]}return rt(this,"shape",s),s},checks:[]});return qe(t,a)}function Df(t,e){if(!at(e))throw new Error("Invalid input to extend: expected a plain object");let n=t._zod.def.checks;if(n&&n.length>0){let a=t._zod.def.shape;for(let s in e)if(Object.getOwnPropertyDescriptor(a,s)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let r=Ke(t._zod.def,{get shape(){let a={...t._zod.def.shape,...e};return rt(this,"shape",a),a}});return qe(t,r)}function Of(t,e){if(!at(e))throw new Error("Invalid input to safeExtend: expected a plain object");let n=Ke(t._zod.def,{get shape(){let o={...t._zod.def.shape,...e};return rt(this,"shape",o),o}});return qe(t,n)}function Nf(t,e){if(t._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let n=Ke(t._zod.def,{get shape(){let o={...t._zod.def.shape,...e._zod.def.shape};return rt(this,"shape",o),o},get catchall(){return e._zod.def.catchall},checks:e._zod.def.checks??[]});return qe(t,n)}function qf(t,e,n){let r=e._zod.def.checks;if(r&&r.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let s=Ke(e._zod.def,{get shape(){let i=e._zod.def.shape,l={...i};if(n)for(let c in n){if(!(c in i))throw new Error(`Unrecognized key: "${c}"`);n[c]&&(l[c]=t?new t({type:"optional",innerType:i[c]}):i[c])}else for(let c in i)l[c]=t?new t({type:"optional",innerType:i[c]}):i[c];return rt(this,"shape",l),l},checks:[]});return qe(e,s)}function Mf(t,e,n){let o=Ke(e._zod.def,{get shape(){let r=e._zod.def.shape,a={...r};if(n)for(let s in n){if(!(s in a))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(a[s]=new t({type:"nonoptional",innerType:r[s]}))}else for(let s in r)a[s]=new t({type:"nonoptional",innerType:r[s]});return rt(this,"shape",a),a}});return qe(e,o)}function st(t,e=0){if(t.aborted===!0)return!0;for(let n=e;n<t.issues.length;n++)if(t.issues[n]?.continue!==!0)return!0;return!1}function Jr(t,e=0){if(t.aborted===!0)return!0;for(let n=e;n<t.issues.length;n++)if(t.issues[n]?.continue===!1)return!0;return!1}function Xe(t,e){return e.map(n=>{var o;return(o=n).path??(o.path=[]),n.path.unshift(t),n})}function hn(t){return typeof t=="string"?t:t?.message}function Pe(t,e,n){let o=t.message?t.message:hn(t.inst?._zod.def?.error?.(t))??hn(e?.error?.(t))??hn(n.customError?.(t))??hn(n.localeError?.(t))??"Invalid input",{inst:r,continue:a,input:s,...i}=t;return i.path??(i.path=[]),i.message=o,e?.reportInput&&(i.input=s),i}function rl(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function fn(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Kr(t){let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"nan":"number";case"object":{if(t===null)return"null";if(Array.isArray(t))return"array";let n=t;if(n&&Object.getPrototypeOf(n)!==Object.prototype&&"constructor"in n&&n.constructor)return n.constructor.name}}return e}function Ot(...t){let[e,n,o]=t;return typeof e=="string"?{message:e,code:"custom",input:n,inst:o}:{...e}}function Lf(t){return Object.entries(t).filter(([e,n])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}function al(t){let e=atob(t),n=new Uint8Array(e.length);for(let o=0;o<e.length;o++)n[o]=e.charCodeAt(o);return n}function sl(t){let e="";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return btoa(e)}function Bf(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n="=".repeat((4-e.length%4)%4);return al(e+n)}function Zf(t){return sl(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Ff(t){let e=t.replace(/^0x/,"");if(e.length%2!==0)throw new Error("Invalid hex string length");let n=new Uint8Array(e.length/2);for(let o=0;o<e.length;o+=2)n[o/2]=Number.parseInt(e.slice(o,o+2),16);return n}function Uf(t){return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}var Zr=class{constructor(...e){}};var il=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),t.message=JSON.stringify(e,jt,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},bo=g("$ZodError",il),Yr=g("$ZodError",il,{Parent:Error});function ll(t,e=n=>n.message){let n={},o=[];for(let r of t.issues)r.path.length>0?(n[r.path[0]]=n[r.path[0]]||[],n[r.path[0]].push(e(r))):o.push(e(r));return{formErrors:o,fieldErrors:n}}function cl(t,e=n=>n.message){let n={_errors:[]},o=(r,a=[])=>{for(let s of r.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(i=>o({issues:i},[...a,...s.path]));else if(s.code==="invalid_key")o({issues:s.issues},[...a,...s.path]);else if(s.code==="invalid_element")o({issues:s.issues},[...a,...s.path]);else{let i=[...a,...s.path];if(i.length===0)n._errors.push(e(s));else{let l=n,c=0;for(;c<i.length;){let u=i[c];c===i.length-1?(l[u]=l[u]||{_errors:[]},l[u]._errors.push(e(s))):l[u]=l[u]||{_errors:[]},l=l[u],c++}}}};return o(t),n}var ko=t=>(e,n,o,r)=>{let a=o?{...o,async:!1}:{async:!1},s=e._zod.run({value:n,issues:[]},a);if(s instanceof Promise)throw new Ue;if(s.issues.length){let i=new(r?.Err??t)(s.issues.map(l=>Pe(l,a,ze())));throw wo(i,r?.callee),i}return s.value};var vo=t=>async(e,n,o,r)=>{let a=o?{...o,async:!0}:{async:!0},s=e._zod.run({value:n,issues:[]},a);if(s instanceof Promise&&(s=await s),s.issues.length){let i=new(r?.Err??t)(s.issues.map(l=>Pe(l,a,ze())));throw wo(i,r?.callee),i}return s.value};var gn=t=>(e,n,o)=>{let r=o?{...o,async:!1}:{async:!1},a=e._zod.run({value:n,issues:[]},r);if(a instanceof Promise)throw new Ue;return a.issues.length?{success:!1,error:new(t??bo)(a.issues.map(s=>Pe(s,r,ze())))}:{success:!0,data:a.value}},wn=gn(Yr),yn=t=>async(e,n,o)=>{let r=o?{...o,async:!0}:{async:!0},a=e._zod.run({value:n,issues:[]},r);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new t(a.issues.map(s=>Pe(s,r,ze())))}:{success:!0,data:a.value}},xo=yn(Yr),ul=t=>(e,n,o)=>{let r=o?{...o,direction:"backward"}:{direction:"backward"};return ko(t)(e,n,r)};var hl=t=>(e,n,o)=>ko(t)(e,n,o);var dl=t=>async(e,n,o)=>{let r=o?{...o,direction:"backward"}:{direction:"backward"};return vo(t)(e,n,r)};var pl=t=>async(e,n,o)=>vo(t)(e,n,o);var ml=t=>(e,n,o)=>{let r=o?{...o,direction:"backward"}:{direction:"backward"};return gn(t)(e,n,r)};var fl=t=>(e,n,o)=>gn(t)(e,n,o);var gl=t=>async(e,n,o)=>{let r=o?{...o,direction:"backward"}:{direction:"backward"};return yn(t)(e,n,r)};var wl=t=>async(e,n,o)=>yn(t)(e,n,o);var yl=/^[cC][0-9a-z]{6,}$/,bl=/^[0-9a-z]+$/,kl=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,vl=/^[0-9a-vA-V]{20}$/,xl=/^[A-Za-z0-9]{27}$/,Sl=/^[a-zA-Z0-9_-]{21}$/,_l=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var Il=/^([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})$/,Xr=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([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)$/;var zl=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var Vf="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Tl(){return new RegExp(Vf,"u")}var Cl=/^(?:(?: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])$/,$l=/^(([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}|:))$/;var Pl=/^((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])$/,El=/^(([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])$/,Rl=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Qr=/^[A-Za-z0-9_-]*$/;var Al=/^https?$/,jl=/^\+[1-9]\d{6,14}$/,Dl="(?:(?:\\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])))",Ol=new RegExp(`^${Dl}$`);function Nl(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function ql(t){return new RegExp(`^${Nl(t)}$`)}function Ml(t){let e=Nl({precision:t.precision}),n=["Z"];t.local&&n.push(""),t.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let o=`${e}(?:${n.join("|")})`;return new RegExp(`^${Dl}T(?:${o})$`)}var Ll=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)};var Bl=/^-?\d+$/,ea=/^-?\d+(?:\.\d+)?$/,Zl=/^(?:true|false)$/i,Fl=/^null$/i;var Ul=/^[^A-Z]*$/,Wl=/^[^a-z]*$/;var se=g("$ZodCheck",(t,e)=>{var n;t._zod??(t._zod={}),t._zod.def=e,(n=t._zod).onattach??(n.onattach=[])}),Vl={number:"number",bigint:"bigint",object:"date"},ta=g("$ZodCheckLessThan",(t,e)=>{se.init(t,e);let n=Vl[typeof e.value];t._zod.onattach.push(o=>{let r=o._zod.bag,a=(e.inclusive?r.maximum:r.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<a&&(e.inclusive?r.maximum=e.value:r.exclusiveMaximum=e.value)}),t._zod.check=o=>{(e.inclusive?o.value<=e.value:o.value<e.value)||o.issues.push({origin:n,code:"too_big",maximum:typeof e.value=="object"?e.value.getTime():e.value,input:o.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),na=g("$ZodCheckGreaterThan",(t,e)=>{se.init(t,e);let n=Vl[typeof e.value];t._zod.onattach.push(o=>{let r=o._zod.bag,a=(e.inclusive?r.minimum:r.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>a&&(e.inclusive?r.minimum=e.value:r.exclusiveMinimum=e.value)}),t._zod.check=o=>{(e.inclusive?o.value>=e.value:o.value>e.value)||o.issues.push({origin:n,code:"too_small",minimum:typeof e.value=="object"?e.value.getTime():e.value,input:o.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Gl=g("$ZodCheckMultipleOf",(t,e)=>{se.init(t,e),t._zod.onattach.push(n=>{var o;(o=n._zod.bag).multipleOf??(o.multipleOf=e.value)}),t._zod.check=n=>{if(typeof n.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%e.value===BigInt(0):Fr(n.value,e.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:e.value,input:n.value,inst:t,continue:!e.abort})}}),Hl=g("$ZodCheckNumberFormat",(t,e)=>{se.init(t,e),e.format=e.format||"float64";let n=e.format?.includes("int"),o=n?"int":"number",[r,a]=Hr[e.format];t._zod.onattach.push(s=>{let i=s._zod.bag;i.format=e.format,i.minimum=r,i.maximum=a,n&&(i.pattern=Bl)}),t._zod.check=s=>{let i=s.value;if(n){if(!Number.isInteger(i)){s.issues.push({expected:o,format:e.format,code:"invalid_type",continue:!1,input:i,inst:t});return}if(!Number.isSafeInteger(i)){i>0?s.issues.push({input:i,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:o,inclusive:!0,continue:!e.abort}):s.issues.push({input:i,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:o,inclusive:!0,continue:!e.abort});return}}i<r&&s.issues.push({origin:"number",input:i,code:"too_small",minimum:r,inclusive:!0,inst:t,continue:!e.abort}),i>a&&s.issues.push({origin:"number",input:i,code:"too_big",maximum:a,inclusive:!0,inst:t,continue:!e.abort})}});var Jl=g("$ZodCheckMaxLength",(t,e)=>{var n;se.init(t,e),(n=t._zod.def).when??(n.when=o=>{let r=o.value;return!pn(r)&&r.length!==void 0}),t._zod.onattach.push(o=>{let r=o._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<r&&(o._zod.bag.maximum=e.maximum)}),t._zod.check=o=>{let r=o.value;if(r.length<=e.maximum)return;let s=fn(r);o.issues.push({origin:s,code:"too_big",maximum:e.maximum,inclusive:!0,input:r,inst:t,continue:!e.abort})}}),Kl=g("$ZodCheckMinLength",(t,e)=>{var n;se.init(t,e),(n=t._zod.def).when??(n.when=o=>{let r=o.value;return!pn(r)&&r.length!==void 0}),t._zod.onattach.push(o=>{let r=o._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>r&&(o._zod.bag.minimum=e.minimum)}),t._zod.check=o=>{let r=o.value;if(r.length>=e.minimum)return;let s=fn(r);o.issues.push({origin:s,code:"too_small",minimum:e.minimum,inclusive:!0,input:r,inst:t,continue:!e.abort})}}),Yl=g("$ZodCheckLengthEquals",(t,e)=>{var n;se.init(t,e),(n=t._zod.def).when??(n.when=o=>{let r=o.value;return!pn(r)&&r.length!==void 0}),t._zod.onattach.push(o=>{let r=o._zod.bag;r.minimum=e.length,r.maximum=e.length,r.length=e.length}),t._zod.check=o=>{let r=o.value,a=r.length;if(a===e.length)return;let s=fn(r),i=a>e.length;o.issues.push({origin:s,...i?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:o.value,inst:t,continue:!e.abort})}}),bn=g("$ZodCheckStringFormat",(t,e)=>{var n,o;se.init(t,e),t._zod.onattach.push(r=>{let a=r._zod.bag;a.format=e.format,e.pattern&&(a.patterns??(a.patterns=new Set),a.patterns.add(e.pattern))}),e.pattern?(n=t._zod).check??(n.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:e.format,input:r.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(o=t._zod).check??(o.check=()=>{})}),Xl=g("$ZodCheckRegex",(t,e)=>{bn.init(t,e),t._zod.check=n=>{e.pattern.lastIndex=0,!e.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),Ql=g("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Ul),bn.init(t,e)}),ec=g("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Wl),bn.init(t,e)}),tc=g("$ZodCheckIncludes",(t,e)=>{se.init(t,e);let n=Ye(e.includes),o=new RegExp(typeof e.position=="number"?`^.{${e.position}}${n}`:n);e.pattern=o,t._zod.onattach.push(r=>{let a=r._zod.bag;a.patterns??(a.patterns=new Set),a.patterns.add(o)}),t._zod.check=r=>{r.value.includes(e.includes,e.position)||r.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:r.value,inst:t,continue:!e.abort})}}),nc=g("$ZodCheckStartsWith",(t,e)=>{se.init(t,e);let n=new RegExp(`^${Ye(e.prefix)}.*`);e.pattern??(e.pattern=n),t._zod.onattach.push(o=>{let r=o._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(n)}),t._zod.check=o=>{o.value.startsWith(e.prefix)||o.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:o.value,inst:t,continue:!e.abort})}}),oc=g("$ZodCheckEndsWith",(t,e)=>{se.init(t,e);let n=new RegExp(`.*${Ye(e.suffix)}$`);e.pattern??(e.pattern=n),t._zod.onattach.push(o=>{let r=o._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(n)}),t._zod.check=o=>{o.value.endsWith(e.suffix)||o.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:o.value,inst:t,continue:!e.abort})}});var rc=g("$ZodCheckOverwrite",(t,e)=>{se.init(t,e),t._zod.check=n=>{n.value=e.tx(n.value)}});var _o=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let o=e.split(`
10
10
  `).filter(s=>s),r=Math.min(...o.map(s=>s.length-s.trimStart().length)),a=o.map(s=>s.slice(r)).map(s=>" ".repeat(this.indent*2)+s);for(let s of a)this.content.push(s)}compile(){let e=Function,n=this?.args,r=[...(this?.content??[""]).map(a=>` ${a}`)];return new e(...n,r.join(`
11
- `))}};var tc={major:4,minor:4,patch:3};var G=g("$ZodType",(t,e)=>{var n;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=tc;let o=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&o.unshift(t);for(let r of o)for(let a of r._zod.onattach)a(t);if(o.length===0)(n=t._zod).deferred??(n.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let r=(s,i,l)=>{let c=at(s),u;for(let h of i){if(h._zod.def.when){if(Wr(s)||!h._zod.def.when(s))continue}else if(c)continue;let d=s.issues.length,p=h._zod.check(s);if(p instanceof Promise&&l?.async===!1)throw new Ue;if(u||p instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await p,s.issues.length!==d&&(c||(c=at(s,d)))});else{if(s.issues.length===d)continue;c||(c=at(s,d))}}return u?u.then(()=>s):s},a=(s,i,l)=>{if(at(s))return s.aborted=!0,s;let c=r(i,o,l);if(c instanceof Promise){if(l.async===!1)throw new Ue;return c.then(u=>t._zod.parse(u,l))}return t._zod.parse(c,l)};t._zod.run=(s,i)=>{if(i.skipChecks)return t._zod.parse(s,i);if(i.direction==="backward"){let c=t._zod.parse({value:s.value,issues:[]},{...i,skipChecks:!0});return c instanceof Promise?c.then(u=>a(u,s,i)):a(c,s,i)}let l=t._zod.parse(s,i);if(l instanceof Promise){if(i.async===!1)throw new Ue;return l.then(c=>r(c,o,i))}return r(l,o,i)}}B(t,"~standard",()=>({validate:r=>{try{let a=fn(t,r);return a.success?{value:a.data}:{issues:a.error?.issues}}catch{return ko(t,r).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),Io=g("$ZodString",(t,e)=>{G.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Ol(t._zod.bag),t._zod.parse=(n,o)=>{if(e.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:t}),n}}),H=g("$ZodStringFormat",(t,e)=>{wn.init(t,e),Io.init(t,e)}),uc=g("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=kl),H.init(t,e)}),hc=g("$ZodUUID",(t,e)=>{if(e.version){let o={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(o===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=Hr(o))}else e.pattern??(e.pattern=Hr());H.init(t,e)}),dc=g("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=vl),H.init(t,e)}),pc=g("$ZodURL",(t,e)=>{H.init(t,e),t._zod.check=n=>{try{let o=n.value.trim();if(!e.normalize&&e.protocol?.source===$l.source&&!/^https?:\/\//i.test(o)){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:t,continue:!e.abort});return}let r=new URL(o);e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(r.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:e.hostname.source,input:n.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(r.protocol.endsWith(":")?r.protocol.slice(0,-1):r.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:n.value,inst:t,continue:!e.abort})),e.normalize?n.value=r.href:n.value=o;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:t,continue:!e.abort})}}}),mc=g("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=xl()),H.init(t,e)}),fc=g("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=yl),H.init(t,e)}),gc=g("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=pl),H.init(t,e)}),wc=g("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=ml),H.init(t,e)}),yc=g("$ZodULID",(t,e)=>{e.pattern??(e.pattern=fl),H.init(t,e)}),bc=g("$ZodXID",(t,e)=>{e.pattern??(e.pattern=gl),H.init(t,e)}),kc=g("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=wl),H.init(t,e)}),vc=g("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Dl(e)),H.init(t,e)}),xc=g("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=El),H.init(t,e)}),Sc=g("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Al(e)),H.init(t,e)}),_c=g("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=bl),H.init(t,e)}),Ic=g("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=Sl),H.init(t,e),t._zod.bag.format="ipv4"}),zc=g("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=_l),H.init(t,e),t._zod.bag.format="ipv6",t._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:t,continue:!e.abort})}}});var Tc=g("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=Il),H.init(t,e)}),$c=g("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=zl),H.init(t,e),t._zod.check=n=>{let o=n.value.split("/");try{if(o.length!==2)throw new Error;let[r,a]=o;if(!a)throw new Error;let s=Number(a);if(`${s}`!==a)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${r}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:t,continue:!e.abort})}}});function Cc(t){if(t==="")return!0;if(/\s/.test(t)||t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var Pc=g("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Tl),H.init(t,e),t._zod.bag.contentEncoding="base64",t._zod.check=n=>{Cc(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:t,continue:!e.abort})}});function Uf(t){if(!Jr.test(t))return!1;let e=t.replace(/[-_]/g,o=>o==="-"?"+":"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return Cc(n)}var Ec=g("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Jr),H.init(t,e),t._zod.bag.contentEncoding="base64url",t._zod.check=n=>{Uf(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:t,continue:!e.abort})}}),Rc=g("$ZodE164",(t,e)=>{e.pattern??(e.pattern=Cl),H.init(t,e)});function Ff(t,e=null){try{let n=t.split(".");if(n.length!==3)return!1;let[o]=n;if(!o)return!1;let r=JSON.parse(atob(o));return!("typ"in r&&r?.typ!=="JWT"||!r.alg||e&&(!("alg"in r)||r.alg!==e))}catch{return!1}}var Ac=g("$ZodJWT",(t,e)=>{H.init(t,e),t._zod.check=n=>{Ff(n.value,e.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:t,continue:!e.abort})}});var ea=g("$ZodNumber",(t,e)=>{G.init(t,e),t._zod.pattern=t._zod.bag.pattern??Kr,t._zod.parse=(n,o)=>{if(e.coerce)try{n.value=Number(n.value)}catch{}let r=n.value;if(typeof r=="number"&&!Number.isNaN(r)&&Number.isFinite(r))return n;let a=typeof r=="number"?Number.isNaN(r)?"NaN":Number.isFinite(r)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:r,inst:t,...a?{received:a}:{}}),n}}),Dc=g("$ZodNumberFormat",(t,e)=>{Ul.init(t,e),ea.init(t,e)}),Oc=g("$ZodBoolean",(t,e)=>{G.init(t,e),t._zod.pattern=Nl,t._zod.parse=(n,o)=>{if(e.coerce)try{n.value=!!n.value}catch{}let r=n.value;return typeof r=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:r,inst:t}),n}});var jc=g("$ZodNull",(t,e)=>{G.init(t,e),t._zod.pattern=ql,t._zod.values=new Set([null]),t._zod.parse=(n,o)=>{let r=n.value;return r===null||n.issues.push({expected:"null",code:"invalid_type",input:r,inst:t}),n}});var Nc=g("$ZodUnknown",(t,e)=>{G.init(t,e),t._zod.parse=n=>n}),qc=g("$ZodNever",(t,e)=>{G.init(t,e),t._zod.parse=(n,o)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:t}),n)});function nc(t,e,n){t.issues.length&&e.issues.push(...Ye(n,t.issues)),e.value[n]=t.value}var Mc=g("$ZodArray",(t,e)=>{G.init(t,e),t._zod.parse=(n,o)=>{let r=n.value;if(!Array.isArray(r))return n.issues.push({expected:"array",code:"invalid_type",input:r,inst:t}),n;n.value=Array(r.length);let a=[];for(let s=0;s<r.length;s++){let i=r[s],l=e.element._zod.run({value:i,issues:[]},o);l instanceof Promise?a.push(l.then(c=>nc(c,n,s))):nc(l,n,s)}return a.length?Promise.all(a).then(()=>n):n}});function _o(t,e,n,o,r,a){let s=n in o;if(t.issues.length){if(r&&a&&!s)return;e.issues.push(...Ye(n,t.issues))}if(!s&&!r){t.issues.length||e.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}t.value===void 0?s&&(e.value[n]=void 0):e.value[n]=t.value}function Lc(t){let e=Object.keys(t.shape);for(let o of e)if(!t.shape?.[o]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${o}": expected a Zod schema`);let n=Ur(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(n)}}function Zc(t,e,n,o,r,a){let s=[],i=r.keySet,l=r.catchall._zod,c=l.def.type,u=l.optin==="optional",h=l.optout==="optional";for(let d in e){if(d==="__proto__"||i.has(d))continue;if(c==="never"){s.push(d);continue}let p=l.run({value:e[d],issues:[]},o);p instanceof Promise?t.push(p.then(m=>_o(m,n,d,e,u,h))):_o(p,n,d,e,u,h)}return s.length&&n.issues.push({code:"unrecognized_keys",keys:s,input:e,inst:a}),t.length?Promise.all(t).then(()=>n):n}var Wf=g("$ZodObject",(t,e)=>{if(G.init(t,e),!Object.getOwnPropertyDescriptor(e,"shape")?.get){let i=e.shape;Object.defineProperty(e,"shape",{get:()=>{let l={...i};return Object.defineProperty(e,"shape",{value:l}),l}})}let o=Dt(()=>Lc(e));B(t._zod,"propValues",()=>{let i=e.shape,l={};for(let c in i){let u=i[c]._zod;if(u.values){l[c]??(l[c]=new Set);for(let h of u.values)l[c].add(h)}}return l});let r=yt,a=e.catchall,s;t._zod.parse=(i,l)=>{s??(s=o.value);let c=i.value;if(!r(c))return i.issues.push({expected:"object",code:"invalid_type",input:c,inst:t}),i;i.value={};let u=[],h=s.shape;for(let d of s.keys){let p=h[d],m=p._zod.optin==="optional",w=p._zod.optout==="optional",y=p._zod.run({value:c[d],issues:[]},l);y instanceof Promise?u.push(y.then(b=>_o(b,i,d,c,m,w))):_o(y,i,d,c,m,w)}return a?Zc(u,c,i,l,o.value,t):u.length?Promise.all(u).then(()=>i):i}}),Bc=g("$ZodObjectJIT",(t,e)=>{Wf.init(t,e);let n=t._zod.parse,o=Dt(()=>Lc(e)),r=d=>{let p=new xo(["shape","payload","ctx"]),m=o.value,w=S=>{let T=mo(S);return`shape[${T}]._zod.run({ value: input[${T}], issues: [] }, ctx)`};p.write("const input = payload.value;");let y=Object.create(null),b=0;for(let S of m.keys)y[S]=`key_${b++}`;p.write("const newResult = {};");for(let S of m.keys){let T=y[S],x=mo(S),Ie=d[S],Ce=Ie?._zod?.optin==="optional",sn=Ie?._zod?.optout==="optional";p.write(`const ${T} = ${w(S)};`),Ce&&sn?p.write(`
11
+ `))}};var sc={major:4,minor:4,patch:3};var G=g("$ZodType",(t,e)=>{var n;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=sc;let o=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&o.unshift(t);for(let r of o)for(let a of r._zod.onattach)a(t);if(o.length===0)(n=t._zod).deferred??(n.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let r=(s,i,l)=>{let c=st(s),u;for(let h of i){if(h._zod.def.when){if(Jr(s)||!h._zod.def.when(s))continue}else if(c)continue;let d=s.issues.length,p=h._zod.check(s);if(p instanceof Promise&&l?.async===!1)throw new Ue;if(u||p instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await p,s.issues.length!==d&&(c||(c=st(s,d)))});else{if(s.issues.length===d)continue;c||(c=st(s,d))}}return u?u.then(()=>s):s},a=(s,i,l)=>{if(st(s))return s.aborted=!0,s;let c=r(i,o,l);if(c instanceof Promise){if(l.async===!1)throw new Ue;return c.then(u=>t._zod.parse(u,l))}return t._zod.parse(c,l)};t._zod.run=(s,i)=>{if(i.skipChecks)return t._zod.parse(s,i);if(i.direction==="backward"){let c=t._zod.parse({value:s.value,issues:[]},{...i,skipChecks:!0});return c instanceof Promise?c.then(u=>a(u,s,i)):a(c,s,i)}let l=t._zod.parse(s,i);if(l instanceof Promise){if(i.async===!1)throw new Ue;return l.then(c=>r(c,o,i))}return r(l,o,i)}}Z(t,"~standard",()=>({validate:r=>{try{let a=wn(t,r);return a.success?{value:a.data}:{issues:a.error?.issues}}catch{return xo(t,r).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),To=g("$ZodString",(t,e)=>{G.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Ll(t._zod.bag),t._zod.parse=(n,o)=>{if(e.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:t}),n}}),H=g("$ZodStringFormat",(t,e)=>{bn.init(t,e),To.init(t,e)}),fc=g("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=Il),H.init(t,e)}),gc=g("$ZodUUID",(t,e)=>{if(e.version){let o={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(o===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=Xr(o))}else e.pattern??(e.pattern=Xr());H.init(t,e)}),wc=g("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=zl),H.init(t,e)}),yc=g("$ZodURL",(t,e)=>{H.init(t,e),t._zod.check=n=>{try{let o=n.value.trim();if(!e.normalize&&e.protocol?.source===Al.source&&!/^https?:\/\//i.test(o)){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:t,continue:!e.abort});return}let r=new URL(o);e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(r.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:e.hostname.source,input:n.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(r.protocol.endsWith(":")?r.protocol.slice(0,-1):r.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:n.value,inst:t,continue:!e.abort})),e.normalize?n.value=r.href:n.value=o;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:t,continue:!e.abort})}}}),bc=g("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=Tl()),H.init(t,e)}),kc=g("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=Sl),H.init(t,e)}),vc=g("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=yl),H.init(t,e)}),xc=g("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=bl),H.init(t,e)}),Sc=g("$ZodULID",(t,e)=>{e.pattern??(e.pattern=kl),H.init(t,e)}),_c=g("$ZodXID",(t,e)=>{e.pattern??(e.pattern=vl),H.init(t,e)}),Ic=g("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=xl),H.init(t,e)}),zc=g("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Ml(e)),H.init(t,e)}),Tc=g("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Ol),H.init(t,e)}),Cc=g("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=ql(e)),H.init(t,e)}),$c=g("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=_l),H.init(t,e)}),Pc=g("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=Cl),H.init(t,e),t._zod.bag.format="ipv4"}),Ec=g("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=$l),H.init(t,e),t._zod.bag.format="ipv6",t._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:t,continue:!e.abort})}}});var Rc=g("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=Pl),H.init(t,e)}),Ac=g("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=El),H.init(t,e),t._zod.check=n=>{let o=n.value.split("/");try{if(o.length!==2)throw new Error;let[r,a]=o;if(!a)throw new Error;let s=Number(a);if(`${s}`!==a)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${r}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:t,continue:!e.abort})}}});function jc(t){if(t==="")return!0;if(/\s/.test(t)||t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var Dc=g("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Rl),H.init(t,e),t._zod.bag.contentEncoding="base64",t._zod.check=n=>{jc(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:t,continue:!e.abort})}});function Jf(t){if(!Qr.test(t))return!1;let e=t.replace(/[-_]/g,o=>o==="-"?"+":"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return jc(n)}var Oc=g("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Qr),H.init(t,e),t._zod.bag.contentEncoding="base64url",t._zod.check=n=>{Jf(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:t,continue:!e.abort})}}),Nc=g("$ZodE164",(t,e)=>{e.pattern??(e.pattern=jl),H.init(t,e)});function Kf(t,e=null){try{let n=t.split(".");if(n.length!==3)return!1;let[o]=n;if(!o)return!1;let r=JSON.parse(atob(o));return!("typ"in r&&r?.typ!=="JWT"||!r.alg||e&&(!("alg"in r)||r.alg!==e))}catch{return!1}}var qc=g("$ZodJWT",(t,e)=>{H.init(t,e),t._zod.check=n=>{Kf(n.value,e.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:t,continue:!e.abort})}});var ra=g("$ZodNumber",(t,e)=>{G.init(t,e),t._zod.pattern=t._zod.bag.pattern??ea,t._zod.parse=(n,o)=>{if(e.coerce)try{n.value=Number(n.value)}catch{}let r=n.value;if(typeof r=="number"&&!Number.isNaN(r)&&Number.isFinite(r))return n;let a=typeof r=="number"?Number.isNaN(r)?"NaN":Number.isFinite(r)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:r,inst:t,...a?{received:a}:{}}),n}}),Mc=g("$ZodNumberFormat",(t,e)=>{Hl.init(t,e),ra.init(t,e)}),Lc=g("$ZodBoolean",(t,e)=>{G.init(t,e),t._zod.pattern=Zl,t._zod.parse=(n,o)=>{if(e.coerce)try{n.value=!!n.value}catch{}let r=n.value;return typeof r=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:r,inst:t}),n}});var Bc=g("$ZodNull",(t,e)=>{G.init(t,e),t._zod.pattern=Fl,t._zod.values=new Set([null]),t._zod.parse=(n,o)=>{let r=n.value;return r===null||n.issues.push({expected:"null",code:"invalid_type",input:r,inst:t}),n}});var Zc=g("$ZodUnknown",(t,e)=>{G.init(t,e),t._zod.parse=n=>n}),Fc=g("$ZodNever",(t,e)=>{G.init(t,e),t._zod.parse=(n,o)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:t}),n)});function ic(t,e,n){t.issues.length&&e.issues.push(...Xe(n,t.issues)),e.value[n]=t.value}var Uc=g("$ZodArray",(t,e)=>{G.init(t,e),t._zod.parse=(n,o)=>{let r=n.value;if(!Array.isArray(r))return n.issues.push({expected:"array",code:"invalid_type",input:r,inst:t}),n;n.value=Array(r.length);let a=[];for(let s=0;s<r.length;s++){let i=r[s],l=e.element._zod.run({value:i,issues:[]},o);l instanceof Promise?a.push(l.then(c=>ic(c,n,s))):ic(l,n,s)}return a.length?Promise.all(a).then(()=>n):n}});function zo(t,e,n,o,r,a){let s=n in o;if(t.issues.length){if(r&&a&&!s)return;e.issues.push(...Xe(n,t.issues))}if(!s&&!r){t.issues.length||e.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}t.value===void 0?s&&(e.value[n]=void 0):e.value[n]=t.value}function Wc(t){let e=Object.keys(t.shape);for(let o of e)if(!t.shape?.[o]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${o}": expected a Zod schema`);let n=Gr(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(n)}}function Vc(t,e,n,o,r,a){let s=[],i=r.keySet,l=r.catchall._zod,c=l.def.type,u=l.optin==="optional",h=l.optout==="optional";for(let d in e){if(d==="__proto__"||i.has(d))continue;if(c==="never"){s.push(d);continue}let p=l.run({value:e[d],issues:[]},o);p instanceof Promise?t.push(p.then(m=>zo(m,n,d,e,u,h))):zo(p,n,d,e,u,h)}return s.length&&n.issues.push({code:"unrecognized_keys",keys:s,input:e,inst:a}),t.length?Promise.all(t).then(()=>n):n}var Yf=g("$ZodObject",(t,e)=>{if(G.init(t,e),!Object.getOwnPropertyDescriptor(e,"shape")?.get){let i=e.shape;Object.defineProperty(e,"shape",{get:()=>{let l={...i};return Object.defineProperty(e,"shape",{value:l}),l}})}let o=Dt(()=>Wc(e));Z(t._zod,"propValues",()=>{let i=e.shape,l={};for(let c in i){let u=i[c]._zod;if(u.values){l[c]??(l[c]=new Set);for(let h of u.values)l[c].add(h)}}return l});let r=bt,a=e.catchall,s;t._zod.parse=(i,l)=>{s??(s=o.value);let c=i.value;if(!r(c))return i.issues.push({expected:"object",code:"invalid_type",input:c,inst:t}),i;i.value={};let u=[],h=s.shape;for(let d of s.keys){let p=h[d],m=p._zod.optin==="optional",w=p._zod.optout==="optional",y=p._zod.run({value:c[d],issues:[]},l);y instanceof Promise?u.push(y.then(b=>zo(b,i,d,c,m,w))):zo(y,i,d,c,m,w)}return a?Vc(u,c,i,l,o.value,t):u.length?Promise.all(u).then(()=>i):i}}),Gc=g("$ZodObjectJIT",(t,e)=>{Yf.init(t,e);let n=t._zod.parse,o=Dt(()=>Wc(e)),r=d=>{let p=new _o(["shape","payload","ctx"]),m=o.value,w=S=>{let T=go(S);return`shape[${T}]._zod.run({ value: input[${T}], issues: [] }, ctx)`};p.write("const input = payload.value;");let y=Object.create(null),b=0;for(let S of m.keys)y[S]=`key_${b++}`;p.write("const newResult = {};");for(let S of m.keys){let T=y[S],_=go(S),Ie=d[S],$e=Ie?._zod?.optin==="optional",cn=Ie?._zod?.optout==="optional";p.write(`const ${T} = ${w(S)};`),$e&&cn?p.write(`
12
12
  if (${T}.issues.length) {
13
- if (${x} in input) {
13
+ if (${_} in input) {
14
14
  payload.issues = payload.issues.concat(${T}.issues.map(iss => ({
15
15
  ...iss,
16
- path: iss.path ? [${x}, ...iss.path] : [${x}]
16
+ path: iss.path ? [${_}, ...iss.path] : [${_}]
17
17
  })));
18
18
  }
19
19
  }
20
20
 
21
21
  if (${T}.value === undefined) {
22
- if (${x} in input) {
23
- newResult[${x}] = undefined;
22
+ if (${_} in input) {
23
+ newResult[${_}] = undefined;
24
24
  }
25
25
  } else {
26
- newResult[${x}] = ${T}.value;
26
+ newResult[${_}] = ${T}.value;
27
27
  }
28
28
 
29
- `):Ce?p.write(`
29
+ `):$e?p.write(`
30
30
  if (${T}.issues.length) {
31
31
  payload.issues = payload.issues.concat(${T}.issues.map(iss => ({
32
32
  ...iss,
33
- path: iss.path ? [${x}, ...iss.path] : [${x}]
33
+ path: iss.path ? [${_}, ...iss.path] : [${_}]
34
34
  })));
35
35
  }
36
36
 
37
37
  if (${T}.value === undefined) {
38
- if (${x} in input) {
39
- newResult[${x}] = undefined;
38
+ if (${_} in input) {
39
+ newResult[${_}] = undefined;
40
40
  }
41
41
  } else {
42
- newResult[${x}] = ${T}.value;
42
+ newResult[${_}] = ${T}.value;
43
43
  }
44
44
 
45
45
  `):p.write(`
46
- const ${T}_present = ${x} in input;
46
+ const ${T}_present = ${_} in input;
47
47
  if (${T}.issues.length) {
48
48
  payload.issues = payload.issues.concat(${T}.issues.map(iss => ({
49
49
  ...iss,
50
- path: iss.path ? [${x}, ...iss.path] : [${x}]
50
+ path: iss.path ? [${_}, ...iss.path] : [${_}]
51
51
  })));
52
52
  }
53
53
  if (!${T}_present && !${T}.issues.length) {
@@ -55,23 +55,23 @@ var lf=Object.create;var jr=Object.defineProperty;var cf=Object.getOwnPropertyDe
55
55
  code: "invalid_type",
56
56
  expected: "nonoptional",
57
57
  input: undefined,
58
- path: [${x}]
58
+ path: [${_}]
59
59
  });
60
60
  }
61
61
 
62
62
  if (${T}_present) {
63
63
  if (${T}.value === undefined) {
64
- newResult[${x}] = undefined;
64
+ newResult[${_}] = undefined;
65
65
  } else {
66
- newResult[${x}] = ${T}.value;
66
+ newResult[${_}] = ${T}.value;
67
67
  }
68
68
  }
69
69
 
70
- `)}p.write("payload.value = newResult;"),p.write("return payload;");let z=p.compile();return(S,T)=>z(d,S,T)},a,s=yt,i=!Rt.jitless,c=i&&Zr.value,u=e.catchall,h;t._zod.parse=(d,p)=>{h??(h=o.value);let m=d.value;return s(m)?i&&c&&p?.async===!1&&p.jitless!==!0?(a||(a=r(e.shape)),d=a(d,p),u?Zc([],m,d,p,h,t):d):n(d,p):(d.issues.push({expected:"object",code:"invalid_type",input:m,inst:t}),d)}});function oc(t,e,n,o){for(let a of t)if(a.issues.length===0)return e.value=a.value,e;let r=t.filter(a=>!at(a));return r.length===1?(e.value=r[0].value,r[0]):(e.issues.push({code:"invalid_union",input:e.value,inst:n,errors:t.map(a=>a.issues.map(s=>Pe(s,o,ze())))}),e)}var ta=g("$ZodUnion",(t,e)=>{G.init(t,e),B(t._zod,"optin",()=>e.options.some(o=>o._zod.optin==="optional")?"optional":void 0),B(t._zod,"optout",()=>e.options.some(o=>o._zod.optout==="optional")?"optional":void 0),B(t._zod,"values",()=>{if(e.options.every(o=>o._zod.values))return new Set(e.options.flatMap(o=>Array.from(o._zod.values)))}),B(t._zod,"pattern",()=>{if(e.options.every(o=>o._zod.pattern)){let o=e.options.map(r=>r._zod.pattern);return new RegExp(`^(${o.map(r=>dn(r.source)).join("|")})$`)}});let n=e.options.length===1?e.options[0]._zod.run:null;t._zod.parse=(o,r)=>{if(n)return n(o,r);let a=!1,s=[];for(let i of e.options){let l=i._zod.run({value:o.value,issues:[]},r);if(l instanceof Promise)s.push(l),a=!0;else{if(l.issues.length===0)return l;s.push(l)}}return a?Promise.all(s).then(i=>oc(i,o,t,r)):oc(s,o,t,r)}});var Uc=g("$ZodDiscriminatedUnion",(t,e)=>{e.inclusive=!1,ta.init(t,e);let n=t._zod.parse;B(t._zod,"propValues",()=>{let r={};for(let a of e.options){let s=a._zod.propValues;if(!s||Object.keys(s).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(a)}"`);for(let[i,l]of Object.entries(s)){r[i]||(r[i]=new Set);for(let c of l)r[i].add(c)}}return r});let o=Dt(()=>{let r=e.options,a=new Map;for(let s of r){let i=s._zod.propValues?.[e.discriminator];if(!i||i.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let l of i){if(a.has(l))throw new Error(`Duplicate discriminator value "${String(l)}"`);a.set(l,s)}}return a});t._zod.parse=(r,a)=>{let s=r.value;if(!yt(s))return r.issues.push({code:"invalid_type",expected:"object",input:s,inst:t}),r;let i=o.value.get(s?.[e.discriminator]);return i?i._zod.run(r,a):e.unionFallback||a.direction==="backward"?n(r,a):(r.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:e.discriminator,options:Array.from(o.value.keys()),input:s,path:[e.discriminator],inst:t}),r)}}),Fc=g("$ZodIntersection",(t,e)=>{G.init(t,e),t._zod.parse=(n,o)=>{let r=n.value,a=e.left._zod.run({value:r,issues:[]},o),s=e.right._zod.run({value:r,issues:[]},o);return a instanceof Promise||s instanceof Promise?Promise.all([a,s]).then(([l,c])=>rc(n,l,c)):rc(n,a,s)}});function Qr(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(rt(t)&&rt(e)){let n=Object.keys(e),o=Object.keys(t).filter(a=>n.indexOf(a)!==-1),r={...t,...e};for(let a of o){let s=Qr(t[a],e[a]);if(!s.valid)return{valid:!1,mergeErrorPath:[a,...s.mergeErrorPath]};r[a]=s.data}return{valid:!0,data:r}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let o=0;o<t.length;o++){let r=t[o],a=e[o],s=Qr(r,a);if(!s.valid)return{valid:!1,mergeErrorPath:[o,...s.mergeErrorPath]};n.push(s.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function rc(t,e,n){let o=new Map,r;for(let i of e.issues)if(i.code==="unrecognized_keys"){r??(r=i);for(let l of i.keys)o.has(l)||o.set(l,{}),o.get(l).l=!0}else t.issues.push(i);for(let i of n.issues)if(i.code==="unrecognized_keys")for(let l of i.keys)o.has(l)||o.set(l,{}),o.get(l).r=!0;else t.issues.push(i);let a=[...o].filter(([,i])=>i.l&&i.r).map(([i])=>i);if(a.length&&r&&t.issues.push({...r,keys:a}),at(t))return t;let s=Qr(e.value,n.value);if(!s.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(s.mergeErrorPath)}`);return t.value=s.data,t}var Wc=g("$ZodRecord",(t,e)=>{G.init(t,e),t._zod.parse=(n,o)=>{let r=n.value;if(!rt(r))return n.issues.push({expected:"record",code:"invalid_type",input:r,inst:t}),n;let a=[],s=e.keyType._zod.values;if(s){n.value={};let i=new Set;for(let c of s)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){i.add(typeof c=="number"?c.toString():c);let u=e.keyType._zod.run({value:c,issues:[]},o);if(u instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(u.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:u.issues.map(p=>Pe(p,o,ze())),input:c,path:[c],inst:t});continue}let h=u.value,d=e.valueType._zod.run({value:r[c],issues:[]},o);d instanceof Promise?a.push(d.then(p=>{p.issues.length&&n.issues.push(...Ye(c,p.issues)),n.value[h]=p.value})):(d.issues.length&&n.issues.push(...Ye(c,d.issues)),n.value[h]=d.value)}let l;for(let c in r)i.has(c)||(l=l??[],l.push(c));l&&l.length>0&&n.issues.push({code:"unrecognized_keys",input:r,inst:t,keys:l})}else{n.value={};for(let i of Reflect.ownKeys(r)){if(i==="__proto__"||!Object.prototype.propertyIsEnumerable.call(r,i))continue;let l=e.keyType._zod.run({value:i,issues:[]},o);if(l instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof i=="string"&&Kr.test(i)&&l.issues.length){let h=e.keyType._zod.run({value:Number(i),issues:[]},o);if(h instanceof Promise)throw new Error("Async schemas not supported in object keys currently");h.issues.length===0&&(l=h)}if(l.issues.length){e.mode==="loose"?n.value[i]=r[i]:n.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map(h=>Pe(h,o,ze())),input:i,path:[i],inst:t});continue}let u=e.valueType._zod.run({value:r[i],issues:[]},o);u instanceof Promise?a.push(u.then(h=>{h.issues.length&&n.issues.push(...Ye(i,h.issues)),n.value[l.value]=h.value})):(u.issues.length&&n.issues.push(...Ye(i,u.issues)),n.value[l.value]=u.value)}}return a.length?Promise.all(a).then(()=>n):n}});var Vc=g("$ZodEnum",(t,e)=>{G.init(t,e);let n=un(e.entries),o=new Set(n);t._zod.values=o,t._zod.pattern=new RegExp(`^(${n.filter(r=>Br.has(typeof r)).map(r=>typeof r=="string"?Ke(r):r.toString()).join("|")})$`),t._zod.parse=(r,a)=>{let s=r.value;return o.has(s)||r.issues.push({code:"invalid_value",values:n,input:s,inst:t}),r}}),Gc=g("$ZodLiteral",(t,e)=>{if(G.init(t,e),e.values.length===0)throw new Error("Cannot create literal schema with no valid values");let n=new Set(e.values);t._zod.values=n,t._zod.pattern=new RegExp(`^(${e.values.map(o=>typeof o=="string"?Ke(o):o?Ke(o.toString()):String(o)).join("|")})$`),t._zod.parse=(o,r)=>{let a=o.value;return n.has(a)||o.issues.push({code:"invalid_value",values:e.values,input:a,inst:t}),o}});var Hc=g("$ZodTransform",(t,e)=>{G.init(t,e),t._zod.optin="optional",t._zod.parse=(n,o)=>{if(o.direction==="backward")throw new Et(t.constructor.name);let r=e.transform(n.value,n);if(o.async)return(r instanceof Promise?r:Promise.resolve(r)).then(s=>(n.value=s,n.fallback=!0,n));if(r instanceof Promise)throw new Ue;return n.value=r,n.fallback=!0,n}});function ac(t,e){return e===void 0&&(t.issues.length||t.fallback)?{issues:[],value:void 0}:t}var na=g("$ZodOptional",(t,e)=>{G.init(t,e),t._zod.optin="optional",t._zod.optout="optional",B(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),B(t._zod,"pattern",()=>{let n=e.innerType._zod.pattern;return n?new RegExp(`^(${dn(n.source)})?$`):void 0}),t._zod.parse=(n,o)=>{if(e.innerType._zod.optin==="optional"){let r=n.value,a=e.innerType._zod.run(n,o);return a instanceof Promise?a.then(s=>ac(s,r)):ac(a,r)}return n.value===void 0?n:e.innerType._zod.run(n,o)}}),Jc=g("$ZodExactOptional",(t,e)=>{na.init(t,e),B(t._zod,"values",()=>e.innerType._zod.values),B(t._zod,"pattern",()=>e.innerType._zod.pattern),t._zod.parse=(n,o)=>e.innerType._zod.run(n,o)}),Kc=g("$ZodNullable",(t,e)=>{G.init(t,e),B(t._zod,"optin",()=>e.innerType._zod.optin),B(t._zod,"optout",()=>e.innerType._zod.optout),B(t._zod,"pattern",()=>{let n=e.innerType._zod.pattern;return n?new RegExp(`^(${dn(n.source)}|null)$`):void 0}),B(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(n,o)=>n.value===null?n:e.innerType._zod.run(n,o)}),Yc=g("$ZodDefault",(t,e)=>{G.init(t,e),t._zod.optin="optional",B(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,o)=>{if(o.direction==="backward")return e.innerType._zod.run(n,o);if(n.value===void 0)return n.value=e.defaultValue,n;let r=e.innerType._zod.run(n,o);return r instanceof Promise?r.then(a=>sc(a,e)):sc(r,e)}});function sc(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var Xc=g("$ZodPrefault",(t,e)=>{G.init(t,e),t._zod.optin="optional",B(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,o)=>(o.direction==="backward"||n.value===void 0&&(n.value=e.defaultValue),e.innerType._zod.run(n,o))}),Qc=g("$ZodNonOptional",(t,e)=>{G.init(t,e),B(t._zod,"values",()=>{let n=e.innerType._zod.values;return n?new Set([...n].filter(o=>o!==void 0)):void 0}),t._zod.parse=(n,o)=>{let r=e.innerType._zod.run(n,o);return r instanceof Promise?r.then(a=>ic(a,t)):ic(r,t)}});function ic(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}var eu=g("$ZodCatch",(t,e)=>{G.init(t,e),t._zod.optin="optional",B(t._zod,"optout",()=>e.innerType._zod.optout),B(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,o)=>{if(o.direction==="backward")return e.innerType._zod.run(n,o);let r=e.innerType._zod.run(n,o);return r instanceof Promise?r.then(a=>(n.value=a.value,a.issues.length&&(n.value=e.catchValue({...n,error:{issues:a.issues.map(s=>Pe(s,o,ze()))},input:n.value}),n.issues=[],n.fallback=!0),n)):(n.value=r.value,r.issues.length&&(n.value=e.catchValue({...n,error:{issues:r.issues.map(a=>Pe(a,o,ze()))},input:n.value}),n.issues=[],n.fallback=!0),n)}});var oa=g("$ZodPipe",(t,e)=>{G.init(t,e),B(t._zod,"values",()=>e.in._zod.values),B(t._zod,"optin",()=>e.in._zod.optin),B(t._zod,"optout",()=>e.out._zod.optout),B(t._zod,"propValues",()=>e.in._zod.propValues),t._zod.parse=(n,o)=>{if(o.direction==="backward"){let a=e.out._zod.run(n,o);return a instanceof Promise?a.then(s=>So(s,e.in,o)):So(a,e.in,o)}let r=e.in._zod.run(n,o);return r instanceof Promise?r.then(a=>So(a,e.out,o)):So(r,e.out,o)}});function So(t,e,n){return t.issues.length?(t.aborted=!0,t):e._zod.run({value:t.value,issues:t.issues,fallback:t.fallback},n)}var tu=g("$ZodPreprocess",(t,e)=>{oa.init(t,e)}),nu=g("$ZodReadonly",(t,e)=>{G.init(t,e),B(t._zod,"propValues",()=>e.innerType._zod.propValues),B(t._zod,"values",()=>e.innerType._zod.values),B(t._zod,"optin",()=>e.innerType?._zod?.optin),B(t._zod,"optout",()=>e.innerType?._zod?.optout),t._zod.parse=(n,o)=>{if(o.direction==="backward")return e.innerType._zod.run(n,o);let r=e.innerType._zod.run(n,o);return r instanceof Promise?r.then(lc):lc(r)}});function lc(t){return t.value=Object.freeze(t.value),t}var ou=g("$ZodCustom",(t,e)=>{se.init(t,e),G.init(t,e),t._zod.parse=(n,o)=>n,t._zod.check=n=>{let o=n.value,r=e.fn(o);if(r instanceof Promise)return r.then(a=>cc(a,n,o,t));cc(r,n,o,t)}});function cc(t,e,n,o){if(!t){let r={code:"custom",input:n,inst:o,path:[...o._zod.def.path??[]],continue:!o._zod.def.abort};o._zod.def.params&&(r.params=o._zod.def.params),e.issues.push(Ot(r))}}var Vf=()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function e(r){return t[r]??null}let n={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",mac:"MAC 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"},o={nan:"NaN"};return r=>{switch(r.code){case"invalid_type":{let a=o[r.expected]??r.expected,s=Vr(r.input),i=o[s]??s;return`Invalid input: expected ${a}, received ${i}`}case"invalid_value":return r.values.length===1?`Invalid input: expected ${go(r.values[0])}`:`Invalid option: expected one of ${po(r.values,"|")}`;case"too_big":{let a=r.inclusive?"<=":"<",s=e(r.origin);return s?`Too big: expected ${r.origin??"value"} to have ${a}${r.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${r.origin??"value"} to be ${a}${r.maximum.toString()}`}case"too_small":{let a=r.inclusive?">=":">",s=e(r.origin);return s?`Too small: expected ${r.origin} to have ${a}${r.minimum.toString()} ${s.unit}`:`Too small: expected ${r.origin} to be ${a}${r.minimum.toString()}`}case"invalid_format":{let a=r;return a.format==="starts_with"?`Invalid string: must start with "${a.prefix}"`:a.format==="ends_with"?`Invalid string: must end with "${a.suffix}"`:a.format==="includes"?`Invalid string: must include "${a.includes}"`:a.format==="regex"?`Invalid string: must match pattern ${a.pattern}`:`Invalid ${n[a.format]??r.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${r.divisor}`;case"unrecognized_keys":return`Unrecognized key${r.keys.length>1?"s":""}: ${po(r.keys,", ")}`;case"invalid_key":return`Invalid key in ${r.origin}`;case"invalid_union":return r.options&&Array.isArray(r.options)&&r.options.length>0?`Invalid discriminator value. Expected ${r.options.map(s=>`'${s}'`).join(" | ")}`:"Invalid input";case"invalid_element":return`Invalid value in ${r.origin}`;default:return"Invalid input"}}};function ru(){return{localeError:Vf()}}var au;var ra=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...n){let o=n[0];return this._map.set(e,o),o&&typeof o=="object"&&"id"in o&&this._idmap.set(o.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let n=this._map.get(e);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(e),this}get(e){let n=e._zod.parent;if(n){let o={...this.get(n)??{}};delete o.id;let r={...o,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function Gf(){return new ra}(au=globalThis).__zod_globalRegistry??(au.__zod_globalRegistry=Gf());var bt=globalThis.__zod_globalRegistry;function su(t,e){return new t({type:"string",...$(e)})}function iu(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...$(e)})}function aa(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...$(e)})}function lu(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...$(e)})}function cu(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...$(e)})}function uu(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...$(e)})}function hu(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...$(e)})}function du(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...$(e)})}function pu(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...$(e)})}function mu(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...$(e)})}function fu(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...$(e)})}function gu(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...$(e)})}function wu(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...$(e)})}function yu(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...$(e)})}function bu(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...$(e)})}function ku(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...$(e)})}function vu(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...$(e)})}function xu(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...$(e)})}function Su(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...$(e)})}function _u(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...$(e)})}function Iu(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...$(e)})}function zu(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...$(e)})}function Tu(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...$(e)})}function $u(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...$(e)})}function Cu(t,e){return new t({type:"string",format:"date",check:"string_format",...$(e)})}function Pu(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...$(e)})}function Eu(t,e){return new t({type:"string",format:"duration",check:"string_format",...$(e)})}function Ru(t,e){return new t({type:"number",checks:[],...$(e)})}function Au(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...$(e)})}function Du(t,e){return new t({type:"boolean",...$(e)})}function Ou(t,e){return new t({type:"null",...$(e)})}function ju(t){return new t({type:"unknown"})}function Nu(t,e){return new t({type:"never",...$(e)})}function zo(t,e){return new Yr({check:"less_than",...$(e),value:t,inclusive:!1})}function yn(t,e){return new Yr({check:"less_than",...$(e),value:t,inclusive:!0})}function To(t,e){return new Xr({check:"greater_than",...$(e),value:t,inclusive:!1})}function bn(t,e){return new Xr({check:"greater_than",...$(e),value:t,inclusive:!0})}function $o(t,e){return new Bl({check:"multiple_of",...$(e),value:t})}function Co(t,e){return new Fl({check:"max_length",...$(e),maximum:t})}function jt(t,e){return new Wl({check:"min_length",...$(e),minimum:t})}function Po(t,e){return new Vl({check:"length_equals",...$(e),length:t})}function sa(t,e){return new Gl({check:"string_format",format:"regex",...$(e),pattern:t})}function ia(t){return new Hl({check:"string_format",format:"lowercase",...$(t)})}function la(t){return new Jl({check:"string_format",format:"uppercase",...$(t)})}function ca(t,e){return new Kl({check:"string_format",format:"includes",...$(e),includes:t})}function ua(t,e){return new Yl({check:"string_format",format:"starts_with",...$(e),prefix:t})}function ha(t,e){return new Xl({check:"string_format",format:"ends_with",...$(e),suffix:t})}function st(t){return new Ql({check:"overwrite",tx:t})}function da(t){return st(e=>e.normalize(t))}function pa(){return st(t=>t.trim())}function ma(){return st(t=>t.toLowerCase())}function fa(){return st(t=>t.toUpperCase())}function ga(){return st(t=>Lr(t))}function qu(t,e,n){return new t({type:"array",element:e,...$(n)})}function Mu(t,e,n){let o=$(n);return o.abort??(o.abort=!0),new t({type:"custom",check:"custom",fn:e,...o})}function Lu(t,e,n){return new t({type:"custom",check:"custom",fn:e,...$(n)})}function Zu(t,e){let n=Hf(o=>(o.addIssue=r=>{if(typeof r=="string")o.issues.push(Ot(r,o.value,n._zod.def));else{let a=r;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=o.value),a.inst??(a.inst=n),a.continue??(a.continue=!n._zod.def.abort),o.issues.push(Ot(a))}},t(o.value,o)),e);return n}function Hf(t,e){let n=new se({check:"custom",...$(e)});return n._zod.check=t,n}function wa(t){let e=t?.target??"draft-2020-12";return e==="draft-4"&&(e="draft-04"),e==="draft-7"&&(e="draft-07"),{processors:t.processors??{},metadataRegistry:t?.metadata??bt,target:e,unrepresentable:t?.unrepresentable??"throw",override:t?.override??(()=>{}),io:t?.io??"output",counter:0,seen:new Map,cycles:t?.cycles??"ref",reused:t?.reused??"inline",external:t?.external??void 0}}function ne(t,e,n={path:[],schemaPath:[]}){var o;let r=t._zod.def,a=e.seen.get(t);if(a)return a.count++,n.schemaPath.includes(t)&&(a.cycle=n.path),a.schema;let s={schema:{},count:1,cycle:void 0,path:n.path};e.seen.set(t,s);let i=t._zod.toJSONSchema?.();if(i)s.schema=i;else{let u={...n,schemaPath:[...n.schemaPath,t],path:n.path};if(t._zod.processJSONSchema)t._zod.processJSONSchema(e,s.schema,u);else{let d=s.schema,p=e.processors[r.type];if(!p)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${r.type}`);p(t,e,d,u)}let h=t._zod.parent;h&&(s.ref||(s.ref=h),ne(h,e,u),e.seen.get(h).isParent=!0)}let l=e.metadataRegistry.get(t);return l&&Object.assign(s.schema,l),e.io==="input"&&fe(t)&&(delete s.schema.examples,delete s.schema.default),e.io==="input"&&"_prefault"in s.schema&&((o=s.schema).default??(o.default=s.schema._prefault)),delete s.schema._prefault,e.seen.get(t).schema}function ya(t,e){let n=t.seen.get(e);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=new Map;for(let s of t.seen.entries()){let i=t.metadataRegistry.get(s[0])?.id;if(i){let l=o.get(i);if(l&&l!==s[0])throw new Error(`Duplicate schema id "${i}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);o.set(i,s[0])}}let r=s=>{let i=t.target==="draft-2020-12"?"$defs":"definitions";if(t.external){let h=t.external.registry.get(s[0])?.id,d=t.external.uri??(m=>m);if(h)return{ref:d(h)};let p=s[1].defId??s[1].schema.id??`schema${t.counter++}`;return s[1].defId=p,{defId:p,ref:`${d("__shared")}#/${i}/${p}`}}if(s[1]===n)return{ref:"#"};let c=`#/${i}/`,u=s[1].schema.id??`__schema${t.counter++}`;return{defId:u,ref:c+u}},a=s=>{if(s[1].schema.$ref)return;let i=s[1],{ref:l,defId:c}=r(s);i.def={...i.schema},c&&(i.defId=c);let u=i.schema;for(let h in u)delete u[h];u.$ref=l};if(t.cycles==="throw")for(let s of t.seen.entries()){let i=s[1];if(i.cycle)throw new Error(`Cycle detected: #/${i.cycle?.join("/")}/<root>
70
+ `)}p.write("payload.value = newResult;"),p.write("return payload;");let x=p.compile();return(S,T)=>x(d,S,T)},a,s=bt,i=!At.jitless,c=i&&Wr.value,u=e.catchall,h;t._zod.parse=(d,p)=>{h??(h=o.value);let m=d.value;return s(m)?i&&c&&p?.async===!1&&p.jitless!==!0?(a||(a=r(e.shape)),d=a(d,p),u?Vc([],m,d,p,h,t):d):n(d,p):(d.issues.push({expected:"object",code:"invalid_type",input:m,inst:t}),d)}});function lc(t,e,n,o){for(let a of t)if(a.issues.length===0)return e.value=a.value,e;let r=t.filter(a=>!st(a));return r.length===1?(e.value=r[0].value,r[0]):(e.issues.push({code:"invalid_union",input:e.value,inst:n,errors:t.map(a=>a.issues.map(s=>Pe(s,o,ze())))}),e)}var aa=g("$ZodUnion",(t,e)=>{G.init(t,e),Z(t._zod,"optin",()=>e.options.some(o=>o._zod.optin==="optional")?"optional":void 0),Z(t._zod,"optout",()=>e.options.some(o=>o._zod.optout==="optional")?"optional":void 0),Z(t._zod,"values",()=>{if(e.options.every(o=>o._zod.values))return new Set(e.options.flatMap(o=>Array.from(o._zod.values)))}),Z(t._zod,"pattern",()=>{if(e.options.every(o=>o._zod.pattern)){let o=e.options.map(r=>r._zod.pattern);return new RegExp(`^(${o.map(r=>mn(r.source)).join("|")})$`)}});let n=e.options.length===1?e.options[0]._zod.run:null;t._zod.parse=(o,r)=>{if(n)return n(o,r);let a=!1,s=[];for(let i of e.options){let l=i._zod.run({value:o.value,issues:[]},r);if(l instanceof Promise)s.push(l),a=!0;else{if(l.issues.length===0)return l;s.push(l)}}return a?Promise.all(s).then(i=>lc(i,o,t,r)):lc(s,o,t,r)}});var Hc=g("$ZodDiscriminatedUnion",(t,e)=>{e.inclusive=!1,aa.init(t,e);let n=t._zod.parse;Z(t._zod,"propValues",()=>{let r={};for(let a of e.options){let s=a._zod.propValues;if(!s||Object.keys(s).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(a)}"`);for(let[i,l]of Object.entries(s)){r[i]||(r[i]=new Set);for(let c of l)r[i].add(c)}}return r});let o=Dt(()=>{let r=e.options,a=new Map;for(let s of r){let i=s._zod.propValues?.[e.discriminator];if(!i||i.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let l of i){if(a.has(l))throw new Error(`Duplicate discriminator value "${String(l)}"`);a.set(l,s)}}return a});t._zod.parse=(r,a)=>{let s=r.value;if(!bt(s))return r.issues.push({code:"invalid_type",expected:"object",input:s,inst:t}),r;let i=o.value.get(s?.[e.discriminator]);return i?i._zod.run(r,a):e.unionFallback||a.direction==="backward"?n(r,a):(r.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:e.discriminator,options:Array.from(o.value.keys()),input:s,path:[e.discriminator],inst:t}),r)}}),Jc=g("$ZodIntersection",(t,e)=>{G.init(t,e),t._zod.parse=(n,o)=>{let r=n.value,a=e.left._zod.run({value:r,issues:[]},o),s=e.right._zod.run({value:r,issues:[]},o);return a instanceof Promise||s instanceof Promise?Promise.all([a,s]).then(([l,c])=>cc(n,l,c)):cc(n,a,s)}});function oa(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(at(t)&&at(e)){let n=Object.keys(e),o=Object.keys(t).filter(a=>n.indexOf(a)!==-1),r={...t,...e};for(let a of o){let s=oa(t[a],e[a]);if(!s.valid)return{valid:!1,mergeErrorPath:[a,...s.mergeErrorPath]};r[a]=s.data}return{valid:!0,data:r}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let o=0;o<t.length;o++){let r=t[o],a=e[o],s=oa(r,a);if(!s.valid)return{valid:!1,mergeErrorPath:[o,...s.mergeErrorPath]};n.push(s.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function cc(t,e,n){let o=new Map,r;for(let i of e.issues)if(i.code==="unrecognized_keys"){r??(r=i);for(let l of i.keys)o.has(l)||o.set(l,{}),o.get(l).l=!0}else t.issues.push(i);for(let i of n.issues)if(i.code==="unrecognized_keys")for(let l of i.keys)o.has(l)||o.set(l,{}),o.get(l).r=!0;else t.issues.push(i);let a=[...o].filter(([,i])=>i.l&&i.r).map(([i])=>i);if(a.length&&r&&t.issues.push({...r,keys:a}),st(t))return t;let s=oa(e.value,n.value);if(!s.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(s.mergeErrorPath)}`);return t.value=s.data,t}var Kc=g("$ZodRecord",(t,e)=>{G.init(t,e),t._zod.parse=(n,o)=>{let r=n.value;if(!at(r))return n.issues.push({expected:"record",code:"invalid_type",input:r,inst:t}),n;let a=[],s=e.keyType._zod.values;if(s){n.value={};let i=new Set;for(let c of s)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){i.add(typeof c=="number"?c.toString():c);let u=e.keyType._zod.run({value:c,issues:[]},o);if(u instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(u.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:u.issues.map(p=>Pe(p,o,ze())),input:c,path:[c],inst:t});continue}let h=u.value,d=e.valueType._zod.run({value:r[c],issues:[]},o);d instanceof Promise?a.push(d.then(p=>{p.issues.length&&n.issues.push(...Xe(c,p.issues)),n.value[h]=p.value})):(d.issues.length&&n.issues.push(...Xe(c,d.issues)),n.value[h]=d.value)}let l;for(let c in r)i.has(c)||(l=l??[],l.push(c));l&&l.length>0&&n.issues.push({code:"unrecognized_keys",input:r,inst:t,keys:l})}else{n.value={};for(let i of Reflect.ownKeys(r)){if(i==="__proto__"||!Object.prototype.propertyIsEnumerable.call(r,i))continue;let l=e.keyType._zod.run({value:i,issues:[]},o);if(l instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof i=="string"&&ea.test(i)&&l.issues.length){let h=e.keyType._zod.run({value:Number(i),issues:[]},o);if(h instanceof Promise)throw new Error("Async schemas not supported in object keys currently");h.issues.length===0&&(l=h)}if(l.issues.length){e.mode==="loose"?n.value[i]=r[i]:n.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map(h=>Pe(h,o,ze())),input:i,path:[i],inst:t});continue}let u=e.valueType._zod.run({value:r[i],issues:[]},o);u instanceof Promise?a.push(u.then(h=>{h.issues.length&&n.issues.push(...Xe(i,h.issues)),n.value[l.value]=h.value})):(u.issues.length&&n.issues.push(...Xe(i,u.issues)),n.value[l.value]=u.value)}}return a.length?Promise.all(a).then(()=>n):n}});var Yc=g("$ZodEnum",(t,e)=>{G.init(t,e);let n=dn(e.entries),o=new Set(n);t._zod.values=o,t._zod.pattern=new RegExp(`^(${n.filter(r=>Vr.has(typeof r)).map(r=>typeof r=="string"?Ye(r):r.toString()).join("|")})$`),t._zod.parse=(r,a)=>{let s=r.value;return o.has(s)||r.issues.push({code:"invalid_value",values:n,input:s,inst:t}),r}}),Xc=g("$ZodLiteral",(t,e)=>{if(G.init(t,e),e.values.length===0)throw new Error("Cannot create literal schema with no valid values");let n=new Set(e.values);t._zod.values=n,t._zod.pattern=new RegExp(`^(${e.values.map(o=>typeof o=="string"?Ye(o):o?Ye(o.toString()):String(o)).join("|")})$`),t._zod.parse=(o,r)=>{let a=o.value;return n.has(a)||o.issues.push({code:"invalid_value",values:e.values,input:a,inst:t}),o}});var Qc=g("$ZodTransform",(t,e)=>{G.init(t,e),t._zod.optin="optional",t._zod.parse=(n,o)=>{if(o.direction==="backward")throw new Rt(t.constructor.name);let r=e.transform(n.value,n);if(o.async)return(r instanceof Promise?r:Promise.resolve(r)).then(s=>(n.value=s,n.fallback=!0,n));if(r instanceof Promise)throw new Ue;return n.value=r,n.fallback=!0,n}});function uc(t,e){return e===void 0&&(t.issues.length||t.fallback)?{issues:[],value:void 0}:t}var sa=g("$ZodOptional",(t,e)=>{G.init(t,e),t._zod.optin="optional",t._zod.optout="optional",Z(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),Z(t._zod,"pattern",()=>{let n=e.innerType._zod.pattern;return n?new RegExp(`^(${mn(n.source)})?$`):void 0}),t._zod.parse=(n,o)=>{if(e.innerType._zod.optin==="optional"){let r=n.value,a=e.innerType._zod.run(n,o);return a instanceof Promise?a.then(s=>uc(s,r)):uc(a,r)}return n.value===void 0?n:e.innerType._zod.run(n,o)}}),eu=g("$ZodExactOptional",(t,e)=>{sa.init(t,e),Z(t._zod,"values",()=>e.innerType._zod.values),Z(t._zod,"pattern",()=>e.innerType._zod.pattern),t._zod.parse=(n,o)=>e.innerType._zod.run(n,o)}),tu=g("$ZodNullable",(t,e)=>{G.init(t,e),Z(t._zod,"optin",()=>e.innerType._zod.optin),Z(t._zod,"optout",()=>e.innerType._zod.optout),Z(t._zod,"pattern",()=>{let n=e.innerType._zod.pattern;return n?new RegExp(`^(${mn(n.source)}|null)$`):void 0}),Z(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(n,o)=>n.value===null?n:e.innerType._zod.run(n,o)}),nu=g("$ZodDefault",(t,e)=>{G.init(t,e),t._zod.optin="optional",Z(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,o)=>{if(o.direction==="backward")return e.innerType._zod.run(n,o);if(n.value===void 0)return n.value=e.defaultValue,n;let r=e.innerType._zod.run(n,o);return r instanceof Promise?r.then(a=>hc(a,e)):hc(r,e)}});function hc(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var ou=g("$ZodPrefault",(t,e)=>{G.init(t,e),t._zod.optin="optional",Z(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,o)=>(o.direction==="backward"||n.value===void 0&&(n.value=e.defaultValue),e.innerType._zod.run(n,o))}),ru=g("$ZodNonOptional",(t,e)=>{G.init(t,e),Z(t._zod,"values",()=>{let n=e.innerType._zod.values;return n?new Set([...n].filter(o=>o!==void 0)):void 0}),t._zod.parse=(n,o)=>{let r=e.innerType._zod.run(n,o);return r instanceof Promise?r.then(a=>dc(a,t)):dc(r,t)}});function dc(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}var au=g("$ZodCatch",(t,e)=>{G.init(t,e),t._zod.optin="optional",Z(t._zod,"optout",()=>e.innerType._zod.optout),Z(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,o)=>{if(o.direction==="backward")return e.innerType._zod.run(n,o);let r=e.innerType._zod.run(n,o);return r instanceof Promise?r.then(a=>(n.value=a.value,a.issues.length&&(n.value=e.catchValue({...n,error:{issues:a.issues.map(s=>Pe(s,o,ze()))},input:n.value}),n.issues=[],n.fallback=!0),n)):(n.value=r.value,r.issues.length&&(n.value=e.catchValue({...n,error:{issues:r.issues.map(a=>Pe(a,o,ze()))},input:n.value}),n.issues=[],n.fallback=!0),n)}});var ia=g("$ZodPipe",(t,e)=>{G.init(t,e),Z(t._zod,"values",()=>e.in._zod.values),Z(t._zod,"optin",()=>e.in._zod.optin),Z(t._zod,"optout",()=>e.out._zod.optout),Z(t._zod,"propValues",()=>e.in._zod.propValues),t._zod.parse=(n,o)=>{if(o.direction==="backward"){let a=e.out._zod.run(n,o);return a instanceof Promise?a.then(s=>Io(s,e.in,o)):Io(a,e.in,o)}let r=e.in._zod.run(n,o);return r instanceof Promise?r.then(a=>Io(a,e.out,o)):Io(r,e.out,o)}});function Io(t,e,n){return t.issues.length?(t.aborted=!0,t):e._zod.run({value:t.value,issues:t.issues,fallback:t.fallback},n)}var su=g("$ZodPreprocess",(t,e)=>{ia.init(t,e)}),iu=g("$ZodReadonly",(t,e)=>{G.init(t,e),Z(t._zod,"propValues",()=>e.innerType._zod.propValues),Z(t._zod,"values",()=>e.innerType._zod.values),Z(t._zod,"optin",()=>e.innerType?._zod?.optin),Z(t._zod,"optout",()=>e.innerType?._zod?.optout),t._zod.parse=(n,o)=>{if(o.direction==="backward")return e.innerType._zod.run(n,o);let r=e.innerType._zod.run(n,o);return r instanceof Promise?r.then(pc):pc(r)}});function pc(t){return t.value=Object.freeze(t.value),t}var lu=g("$ZodCustom",(t,e)=>{se.init(t,e),G.init(t,e),t._zod.parse=(n,o)=>n,t._zod.check=n=>{let o=n.value,r=e.fn(o);if(r instanceof Promise)return r.then(a=>mc(a,n,o,t));mc(r,n,o,t)}});function mc(t,e,n,o){if(!t){let r={code:"custom",input:n,inst:o,path:[...o._zod.def.path??[]],continue:!o._zod.def.abort};o._zod.def.params&&(r.params=o._zod.def.params),e.issues.push(Ot(r))}}var Xf=()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function e(r){return t[r]??null}let n={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",mac:"MAC 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"},o={nan:"NaN"};return r=>{switch(r.code){case"invalid_type":{let a=o[r.expected]??r.expected,s=Kr(r.input),i=o[s]??s;return`Invalid input: expected ${a}, received ${i}`}case"invalid_value":return r.values.length===1?`Invalid input: expected ${yo(r.values[0])}`:`Invalid option: expected one of ${fo(r.values,"|")}`;case"too_big":{let a=r.inclusive?"<=":"<",s=e(r.origin);return s?`Too big: expected ${r.origin??"value"} to have ${a}${r.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${r.origin??"value"} to be ${a}${r.maximum.toString()}`}case"too_small":{let a=r.inclusive?">=":">",s=e(r.origin);return s?`Too small: expected ${r.origin} to have ${a}${r.minimum.toString()} ${s.unit}`:`Too small: expected ${r.origin} to be ${a}${r.minimum.toString()}`}case"invalid_format":{let a=r;return a.format==="starts_with"?`Invalid string: must start with "${a.prefix}"`:a.format==="ends_with"?`Invalid string: must end with "${a.suffix}"`:a.format==="includes"?`Invalid string: must include "${a.includes}"`:a.format==="regex"?`Invalid string: must match pattern ${a.pattern}`:`Invalid ${n[a.format]??r.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${r.divisor}`;case"unrecognized_keys":return`Unrecognized key${r.keys.length>1?"s":""}: ${fo(r.keys,", ")}`;case"invalid_key":return`Invalid key in ${r.origin}`;case"invalid_union":return r.options&&Array.isArray(r.options)&&r.options.length>0?`Invalid discriminator value. Expected ${r.options.map(s=>`'${s}'`).join(" | ")}`:"Invalid input";case"invalid_element":return`Invalid value in ${r.origin}`;default:return"Invalid input"}}};function cu(){return{localeError:Xf()}}var uu;var la=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...n){let o=n[0];return this._map.set(e,o),o&&typeof o=="object"&&"id"in o&&this._idmap.set(o.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let n=this._map.get(e);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(e),this}get(e){let n=e._zod.parent;if(n){let o={...this.get(n)??{}};delete o.id;let r={...o,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function Qf(){return new la}(uu=globalThis).__zod_globalRegistry??(uu.__zod_globalRegistry=Qf());var kt=globalThis.__zod_globalRegistry;function hu(t,e){return new t({type:"string",...C(e)})}function du(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...C(e)})}function ca(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...C(e)})}function pu(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...C(e)})}function mu(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...C(e)})}function fu(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...C(e)})}function gu(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...C(e)})}function wu(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...C(e)})}function yu(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...C(e)})}function bu(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...C(e)})}function ku(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...C(e)})}function vu(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...C(e)})}function xu(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...C(e)})}function Su(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...C(e)})}function _u(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...C(e)})}function Iu(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...C(e)})}function zu(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...C(e)})}function Tu(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...C(e)})}function Cu(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...C(e)})}function $u(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...C(e)})}function Pu(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...C(e)})}function Eu(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...C(e)})}function Ru(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...C(e)})}function Au(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...C(e)})}function ju(t,e){return new t({type:"string",format:"date",check:"string_format",...C(e)})}function Du(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...C(e)})}function Ou(t,e){return new t({type:"string",format:"duration",check:"string_format",...C(e)})}function Nu(t,e){return new t({type:"number",checks:[],...C(e)})}function qu(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...C(e)})}function Mu(t,e){return new t({type:"boolean",...C(e)})}function Lu(t,e){return new t({type:"null",...C(e)})}function Bu(t){return new t({type:"unknown"})}function Zu(t,e){return new t({type:"never",...C(e)})}function Co(t,e){return new ta({check:"less_than",...C(e),value:t,inclusive:!1})}function kn(t,e){return new ta({check:"less_than",...C(e),value:t,inclusive:!0})}function $o(t,e){return new na({check:"greater_than",...C(e),value:t,inclusive:!1})}function vn(t,e){return new na({check:"greater_than",...C(e),value:t,inclusive:!0})}function Po(t,e){return new Gl({check:"multiple_of",...C(e),value:t})}function Eo(t,e){return new Jl({check:"max_length",...C(e),maximum:t})}function Nt(t,e){return new Kl({check:"min_length",...C(e),minimum:t})}function Ro(t,e){return new Yl({check:"length_equals",...C(e),length:t})}function ua(t,e){return new Xl({check:"string_format",format:"regex",...C(e),pattern:t})}function ha(t){return new Ql({check:"string_format",format:"lowercase",...C(t)})}function da(t){return new ec({check:"string_format",format:"uppercase",...C(t)})}function pa(t,e){return new tc({check:"string_format",format:"includes",...C(e),includes:t})}function ma(t,e){return new nc({check:"string_format",format:"starts_with",...C(e),prefix:t})}function fa(t,e){return new oc({check:"string_format",format:"ends_with",...C(e),suffix:t})}function it(t){return new rc({check:"overwrite",tx:t})}function ga(t){return it(e=>e.normalize(t))}function wa(){return it(t=>t.trim())}function ya(){return it(t=>t.toLowerCase())}function ba(){return it(t=>t.toUpperCase())}function ka(){return it(t=>Ur(t))}function Fu(t,e,n){return new t({type:"array",element:e,...C(n)})}function Uu(t,e,n){let o=C(n);return o.abort??(o.abort=!0),new t({type:"custom",check:"custom",fn:e,...o})}function Wu(t,e,n){return new t({type:"custom",check:"custom",fn:e,...C(n)})}function Vu(t,e){let n=eg(o=>(o.addIssue=r=>{if(typeof r=="string")o.issues.push(Ot(r,o.value,n._zod.def));else{let a=r;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=o.value),a.inst??(a.inst=n),a.continue??(a.continue=!n._zod.def.abort),o.issues.push(Ot(a))}},t(o.value,o)),e);return n}function eg(t,e){let n=new se({check:"custom",...C(e)});return n._zod.check=t,n}function va(t){let e=t?.target??"draft-2020-12";return e==="draft-4"&&(e="draft-04"),e==="draft-7"&&(e="draft-07"),{processors:t.processors??{},metadataRegistry:t?.metadata??kt,target:e,unrepresentable:t?.unrepresentable??"throw",override:t?.override??(()=>{}),io:t?.io??"output",counter:0,seen:new Map,cycles:t?.cycles??"ref",reused:t?.reused??"inline",external:t?.external??void 0}}function ne(t,e,n={path:[],schemaPath:[]}){var o;let r=t._zod.def,a=e.seen.get(t);if(a)return a.count++,n.schemaPath.includes(t)&&(a.cycle=n.path),a.schema;let s={schema:{},count:1,cycle:void 0,path:n.path};e.seen.set(t,s);let i=t._zod.toJSONSchema?.();if(i)s.schema=i;else{let u={...n,schemaPath:[...n.schemaPath,t],path:n.path};if(t._zod.processJSONSchema)t._zod.processJSONSchema(e,s.schema,u);else{let d=s.schema,p=e.processors[r.type];if(!p)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${r.type}`);p(t,e,d,u)}let h=t._zod.parent;h&&(s.ref||(s.ref=h),ne(h,e,u),e.seen.get(h).isParent=!0)}let l=e.metadataRegistry.get(t);return l&&Object.assign(s.schema,l),e.io==="input"&&fe(t)&&(delete s.schema.examples,delete s.schema.default),e.io==="input"&&"_prefault"in s.schema&&((o=s.schema).default??(o.default=s.schema._prefault)),delete s.schema._prefault,e.seen.get(t).schema}function xa(t,e){let n=t.seen.get(e);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=new Map;for(let s of t.seen.entries()){let i=t.metadataRegistry.get(s[0])?.id;if(i){let l=o.get(i);if(l&&l!==s[0])throw new Error(`Duplicate schema id "${i}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);o.set(i,s[0])}}let r=s=>{let i=t.target==="draft-2020-12"?"$defs":"definitions";if(t.external){let h=t.external.registry.get(s[0])?.id,d=t.external.uri??(m=>m);if(h)return{ref:d(h)};let p=s[1].defId??s[1].schema.id??`schema${t.counter++}`;return s[1].defId=p,{defId:p,ref:`${d("__shared")}#/${i}/${p}`}}if(s[1]===n)return{ref:"#"};let c=`#/${i}/`,u=s[1].schema.id??`__schema${t.counter++}`;return{defId:u,ref:c+u}},a=s=>{if(s[1].schema.$ref)return;let i=s[1],{ref:l,defId:c}=r(s);i.def={...i.schema},c&&(i.defId=c);let u=i.schema;for(let h in u)delete u[h];u.$ref=l};if(t.cycles==="throw")for(let s of t.seen.entries()){let i=s[1];if(i.cycle)throw new Error(`Cycle detected: #/${i.cycle?.join("/")}/<root>
71
71
 
72
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let s of t.seen.entries()){let i=s[1];if(e===s[0]){a(s);continue}if(t.external){let c=t.external.registry.get(s[0])?.id;if(e!==s[0]&&c){a(s);continue}}if(t.metadataRegistry.get(s[0])?.id){a(s);continue}if(i.cycle){a(s);continue}if(i.count>1&&t.reused==="ref"){a(s);continue}}}function ba(t,e){let n=t.seen.get(e);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=i=>{let l=t.seen.get(i);if(l.ref===null)return;let c=l.def??l.schema,u={...c},h=l.ref;if(l.ref=null,h){o(h);let p=t.seen.get(h),m=p.schema;if(m.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(c.allOf=c.allOf??[],c.allOf.push(m)):Object.assign(c,m),Object.assign(c,u),i._zod.parent===h)for(let y in c)y==="$ref"||y==="allOf"||y in u||delete c[y];if(m.$ref&&p.def)for(let y in c)y==="$ref"||y==="allOf"||y in p.def&&JSON.stringify(c[y])===JSON.stringify(p.def[y])&&delete c[y]}let d=i._zod.parent;if(d&&d!==h){o(d);let p=t.seen.get(d);if(p?.schema.$ref&&(c.$ref=p.schema.$ref,p.def))for(let m in c)m==="$ref"||m==="allOf"||m in p.def&&JSON.stringify(c[m])===JSON.stringify(p.def[m])&&delete c[m]}t.override({zodSchema:i,jsonSchema:c,path:l.path??[]})};for(let i of[...t.seen.entries()].reverse())o(i[0]);let r={};if(t.target==="draft-2020-12"?r.$schema="https://json-schema.org/draft/2020-12/schema":t.target==="draft-07"?r.$schema="http://json-schema.org/draft-07/schema#":t.target==="draft-04"?r.$schema="http://json-schema.org/draft-04/schema#":t.target,t.external?.uri){let i=t.external.registry.get(e)?.id;if(!i)throw new Error("Schema is missing an `id` property");r.$id=t.external.uri(i)}Object.assign(r,n.def??n.schema);let a=t.metadataRegistry.get(e)?.id;a!==void 0&&r.id===a&&delete r.id;let s=t.external?.defs??{};for(let i of t.seen.entries()){let l=i[1];l.def&&l.defId&&(l.def.id===l.defId&&delete l.def.id,s[l.defId]=l.def)}t.external||Object.keys(s).length>0&&(t.target==="draft-2020-12"?r.$defs=s:r.definitions=s);try{let i=JSON.parse(JSON.stringify(r));return Object.defineProperty(i,"~standard",{value:{...e["~standard"],jsonSchema:{input:kn(e,"input",t.processors),output:kn(e,"output",t.processors)}},enumerable:!1,writable:!1}),i}catch{throw new Error("Error converting schema to JSON.")}}function fe(t,e){let n=e??{seen:new Set};if(n.seen.has(t))return!1;n.seen.add(t);let o=t._zod.def;if(o.type==="transform")return!0;if(o.type==="array")return fe(o.element,n);if(o.type==="set")return fe(o.valueType,n);if(o.type==="lazy")return fe(o.getter(),n);if(o.type==="promise"||o.type==="optional"||o.type==="nonoptional"||o.type==="nullable"||o.type==="readonly"||o.type==="default"||o.type==="prefault")return fe(o.innerType,n);if(o.type==="intersection")return fe(o.left,n)||fe(o.right,n);if(o.type==="record"||o.type==="map")return fe(o.keyType,n)||fe(o.valueType,n);if(o.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:fe(o.in,n)||fe(o.out,n);if(o.type==="object"){for(let r in o.shape)if(fe(o.shape[r],n))return!0;return!1}if(o.type==="union"){for(let r of o.options)if(fe(r,n))return!0;return!1}if(o.type==="tuple"){for(let r of o.items)if(fe(r,n))return!0;return!!(o.rest&&fe(o.rest,n))}return!1}var Bu=(t,e={})=>n=>{let o=wa({...n,processors:e});return ne(t,o),ya(o,t),ba(o,t)},kn=(t,e,n={})=>o=>{let{libraryOptions:r,target:a}=o??{},s=wa({...r??{},target:a,io:e,processors:n});return ne(t,s),ya(s,t),ba(s,t)};var Jf={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Uu=(t,e,n,o)=>{let r=n;r.type="string";let{minimum:a,maximum:s,format:i,patterns:l,contentEncoding:c}=t._zod.bag;if(typeof a=="number"&&(r.minLength=a),typeof s=="number"&&(r.maxLength=s),i&&(r.format=Jf[i]??i,r.format===""&&delete r.format,i==="time"&&delete r.format),c&&(r.contentEncoding=c),l&&l.size>0){let u=[...l];u.length===1?r.pattern=u[0].source:u.length>1&&(r.allOf=[...u.map(h=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:h.source}))])}},Fu=(t,e,n,o)=>{let r=n,{minimum:a,maximum:s,format:i,multipleOf:l,exclusiveMaximum:c,exclusiveMinimum:u}=t._zod.bag;typeof i=="string"&&i.includes("int")?r.type="integer":r.type="number";let h=typeof u=="number"&&u>=(a??Number.NEGATIVE_INFINITY),d=typeof c=="number"&&c<=(s??Number.POSITIVE_INFINITY),p=e.target==="draft-04"||e.target==="openapi-3.0";h?p?(r.minimum=u,r.exclusiveMinimum=!0):r.exclusiveMinimum=u:typeof a=="number"&&(r.minimum=a),d?p?(r.maximum=c,r.exclusiveMaximum=!0):r.exclusiveMaximum=c:typeof s=="number"&&(r.maximum=s),typeof l=="number"&&(r.multipleOf=l)},Wu=(t,e,n,o)=>{n.type="boolean"};var Vu=(t,e,n,o)=>{e.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"};var Gu=(t,e,n,o)=>{n.not={}};var Hu=(t,e,n,o)=>{};var Ju=(t,e,n,o)=>{let r=t._zod.def,a=un(r.entries);a.every(s=>typeof s=="number")&&(n.type="number"),a.every(s=>typeof s=="string")&&(n.type="string"),n.enum=a},Ku=(t,e,n,o)=>{let r=t._zod.def,a=[];for(let s of r.values)if(s===void 0){if(e.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof s=="bigint"){if(e.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");a.push(Number(s))}else a.push(s);if(a.length!==0)if(a.length===1){let s=a[0];n.type=s===null?"null":typeof s,e.target==="draft-04"||e.target==="openapi-3.0"?n.enum=[s]:n.const=s}else a.every(s=>typeof s=="number")&&(n.type="number"),a.every(s=>typeof s=="string")&&(n.type="string"),a.every(s=>typeof s=="boolean")&&(n.type="boolean"),a.every(s=>s===null)&&(n.type="null"),n.enum=a};var Yu=(t,e,n,o)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")};var Xu=(t,e,n,o)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")};var Qu=(t,e,n,o)=>{let r=n,a=t._zod.def,{minimum:s,maximum:i}=t._zod.bag;typeof s=="number"&&(r.minItems=s),typeof i=="number"&&(r.maxItems=i),r.type="array",r.items=ne(a.element,e,{...o,path:[...o.path,"items"]})},eh=(t,e,n,o)=>{let r=n,a=t._zod.def;r.type="object",r.properties={};let s=a.shape;for(let c in s)r.properties[c]=ne(s[c],e,{...o,path:[...o.path,"properties",c]});let i=new Set(Object.keys(s)),l=new Set([...i].filter(c=>{let u=a.shape[c]._zod;return e.io==="input"?u.optin===void 0:u.optout===void 0}));l.size>0&&(r.required=Array.from(l)),a.catchall?._zod.def.type==="never"?r.additionalProperties=!1:a.catchall?a.catchall&&(r.additionalProperties=ne(a.catchall,e,{...o,path:[...o.path,"additionalProperties"]})):e.io==="output"&&(r.additionalProperties=!1)},th=(t,e,n,o)=>{let r=t._zod.def,a=r.inclusive===!1,s=r.options.map((i,l)=>ne(i,e,{...o,path:[...o.path,a?"oneOf":"anyOf",l]}));a?n.oneOf=s:n.anyOf=s},nh=(t,e,n,o)=>{let r=t._zod.def,a=ne(r.left,e,{...o,path:[...o.path,"allOf",0]}),s=ne(r.right,e,{...o,path:[...o.path,"allOf",1]}),i=c=>"allOf"in c&&Object.keys(c).length===1,l=[...i(a)?a.allOf:[a],...i(s)?s.allOf:[s]];n.allOf=l};var oh=(t,e,n,o)=>{let r=n,a=t._zod.def;r.type="object";let s=a.keyType,l=s._zod.bag?.patterns;if(a.mode==="loose"&&l&&l.size>0){let u=ne(a.valueType,e,{...o,path:[...o.path,"patternProperties","*"]});r.patternProperties={};for(let h of l)r.patternProperties[h.source]=u}else(e.target==="draft-07"||e.target==="draft-2020-12")&&(r.propertyNames=ne(a.keyType,e,{...o,path:[...o.path,"propertyNames"]})),r.additionalProperties=ne(a.valueType,e,{...o,path:[...o.path,"additionalProperties"]});let c=s._zod.values;if(c){let u=[...c].filter(h=>typeof h=="string"||typeof h=="number");u.length>0&&(r.required=u)}},rh=(t,e,n,o)=>{let r=t._zod.def,a=ne(r.innerType,e,o),s=e.seen.get(t);e.target==="openapi-3.0"?(s.ref=r.innerType,n.nullable=!0):n.anyOf=[a,{type:"null"}]},ah=(t,e,n,o)=>{let r=t._zod.def;ne(r.innerType,e,o);let a=e.seen.get(t);a.ref=r.innerType},sh=(t,e,n,o)=>{let r=t._zod.def;ne(r.innerType,e,o);let a=e.seen.get(t);a.ref=r.innerType,n.default=JSON.parse(JSON.stringify(r.defaultValue))},ih=(t,e,n,o)=>{let r=t._zod.def;ne(r.innerType,e,o);let a=e.seen.get(t);a.ref=r.innerType,e.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(r.defaultValue)))},lh=(t,e,n,o)=>{let r=t._zod.def;ne(r.innerType,e,o);let a=e.seen.get(t);a.ref=r.innerType;let s;try{s=r.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=s},ch=(t,e,n,o)=>{let r=t._zod.def,a=r.in._zod.traits.has("$ZodTransform"),s=e.io==="input"?a?r.out:r.in:r.out;ne(s,e,o);let i=e.seen.get(t);i.ref=s},uh=(t,e,n,o)=>{let r=t._zod.def;ne(r.innerType,e,o);let a=e.seen.get(t);a.ref=r.innerType,n.readOnly=!0};var ka=(t,e,n,o)=>{let r=t._zod.def;ne(r.innerType,e,o);let a=e.seen.get(t);a.ref=r.innerType};function Nt(t){return!!t._zod}function it(t,e){return Nt(t)?fn(t,e):t.safeParse(e)}function Eo(t){if(!t)return;let e;if(Nt(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function hh(t){if(Nt(t)){let a=t._zod?.def;if(a){if(a.value!==void 0)return a.value;if(Array.isArray(a.values)&&a.values.length>0)return a.values[0]}}let n=t._def;if(n){if(n.value!==void 0)return n.value;if(Array.isArray(n.values)&&n.values.length>0)return n.values[0]}let o=t.value;if(o!==void 0)return o}var xn={};Vi(xn,{ZodISODate:()=>ph,ZodISODateTime:()=>dh,ZodISODuration:()=>fh,ZodISOTime:()=>mh,date:()=>xa,datetime:()=>va,duration:()=>_a,time:()=>Sa});var dh=g("ZodISODateTime",(t,e)=>{vc.init(t,e),X.init(t,e)});function va(t){return $u(dh,t)}var ph=g("ZodISODate",(t,e)=>{xc.init(t,e),X.init(t,e)});function xa(t){return Cu(ph,t)}var mh=g("ZodISOTime",(t,e)=>{Sc.init(t,e),X.init(t,e)});function Sa(t){return Pu(mh,t)}var fh=g("ZodISODuration",(t,e)=>{_c.init(t,e),X.init(t,e)});function _a(t){return Eu(fh,t)}var rg=(t,e)=>{wo.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>rl(t,n)},flatten:{value:n=>ol(t,n)},addIssue:{value:n=>{t.issues.push(n),t.message=JSON.stringify(t.issues,At,2)}},addIssues:{value:n=>{t.issues.push(...n),t.message=JSON.stringify(t.issues,At,2)}},isEmpty:{get(){return t.issues.length===0}}})};var Te=g("ZodError",rg,{Parent:Error});var gh=yo(Te),wh=bo(Te),yh=mn(Te),bh=gn(Te),kh=al(Te),vh=sl(Te),xh=il(Te),Sh=ll(Te),_h=cl(Te),Ih=ul(Te),zh=hl(Te),Th=dl(Te);var $h=new WeakMap;function Sn(t,e,n){let o=Object.getPrototypeOf(t),r=$h.get(o);if(r||(r=new Set,$h.set(o,r)),!r.has(e)){r.add(e);for(let a in n){let s=n[a];Object.defineProperty(o,a,{configurable:!0,enumerable:!1,get(){let i=s.bind(this);return Object.defineProperty(this,a,{configurable:!0,writable:!0,enumerable:!0,value:i}),i},set(i){Object.defineProperty(this,a,{configurable:!0,writable:!0,enumerable:!0,value:i})}})}}}var te=g("ZodType",(t,e)=>(G.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:kn(t,"input"),output:kn(t,"output")}}),t.toJSONSchema=Bu(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.parse=(n,o)=>gh(t,n,o,{callee:t.parse}),t.safeParse=(n,o)=>yh(t,n,o),t.parseAsync=async(n,o)=>wh(t,n,o,{callee:t.parseAsync}),t.safeParseAsync=async(n,o)=>bh(t,n,o),t.spa=t.safeParseAsync,t.encode=(n,o)=>kh(t,n,o),t.decode=(n,o)=>vh(t,n,o),t.encodeAsync=async(n,o)=>xh(t,n,o),t.decodeAsync=async(n,o)=>Sh(t,n,o),t.safeEncode=(n,o)=>_h(t,n,o),t.safeDecode=(n,o)=>Ih(t,n,o),t.safeEncodeAsync=async(n,o)=>zh(t,n,o),t.safeDecodeAsync=async(n,o)=>Th(t,n,o),Sn(t,"ZodType",{check(...n){let o=this.def;return this.clone(q.mergeDefs(o,{checks:[...o.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,o){return Ne(this,n,o)},brand(){return this},register(n,o){return n.add(this,o),this},refine(n,o){return this.check(Hg(n,o))},superRefine(n,o){return this.check(Jg(n,o))},overwrite(n){return this.check(st(n))},optional(){return ee(this)},exactOptional(){return jg(this)},nullable(){return Rh(this)},nullish(){return ee(Rh(this))},nonoptional(n){return Bg(this,n)},array(){return j(this)},or(n){return J([this,n])},and(n){return Ao(this,n)},transform(n){return Ah(this,Mh(n))},default(n){return Mg(this,n)},prefault(n){return Zg(this,n)},catch(n){return Fg(this,n)},pipe(n){return Ah(this,n)},readonly(){return Gg(this)},describe(n){let o=this.clone();return bt.add(o,{description:n}),o},meta(...n){if(n.length===0)return bt.get(this);let o=this.clone();return bt.add(o,n[0]),o},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(n){return n(this)}}),Object.defineProperty(t,"description",{get(){return bt.get(t)?.description},configurable:!0}),t)),Dh=g("_ZodString",(t,e)=>{Io.init(t,e),te.init(t,e),t._zod.processJSONSchema=(o,r,a)=>Uu(t,o,r,a);let n=t._zod.bag;t.format=n.format??null,t.minLength=n.minimum??null,t.maxLength=n.maximum??null,Sn(t,"_ZodString",{regex(...o){return this.check(sa(...o))},includes(...o){return this.check(ca(...o))},startsWith(...o){return this.check(ua(...o))},endsWith(...o){return this.check(ha(...o))},min(...o){return this.check(jt(...o))},max(...o){return this.check(Co(...o))},length(...o){return this.check(Po(...o))},nonempty(...o){return this.check(jt(1,...o))},lowercase(o){return this.check(ia(o))},uppercase(o){return this.check(la(o))},trim(){return this.check(pa())},normalize(...o){return this.check(da(...o))},toLowerCase(){return this.check(ma())},toUpperCase(){return this.check(fa())},slugify(){return this.check(ga())}})}),sg=g("ZodString",(t,e)=>{Io.init(t,e),Dh.init(t,e),t.email=n=>t.check(iu(ig,n)),t.url=n=>t.check(du(lg,n)),t.jwt=n=>t.check(Tu(Sg,n)),t.emoji=n=>t.check(pu(cg,n)),t.guid=n=>t.check(aa(Ch,n)),t.uuid=n=>t.check(lu(Ro,n)),t.uuidv4=n=>t.check(cu(Ro,n)),t.uuidv6=n=>t.check(uu(Ro,n)),t.uuidv7=n=>t.check(hu(Ro,n)),t.nanoid=n=>t.check(mu(ug,n)),t.guid=n=>t.check(aa(Ch,n)),t.cuid=n=>t.check(fu(hg,n)),t.cuid2=n=>t.check(gu(dg,n)),t.ulid=n=>t.check(wu(pg,n)),t.base64=n=>t.check(_u(kg,n)),t.base64url=n=>t.check(Iu(vg,n)),t.xid=n=>t.check(yu(mg,n)),t.ksuid=n=>t.check(bu(fg,n)),t.ipv4=n=>t.check(ku(gg,n)),t.ipv6=n=>t.check(vu(wg,n)),t.cidrv4=n=>t.check(xu(yg,n)),t.cidrv6=n=>t.check(Su(bg,n)),t.e164=n=>t.check(zu(xg,n)),t.datetime=n=>t.check(va(n)),t.date=n=>t.check(xa(n)),t.time=n=>t.check(Sa(n)),t.duration=n=>t.check(_a(n))});function f(t){return su(sg,t)}var X=g("ZodStringFormat",(t,e)=>{H.init(t,e),Dh.init(t,e)}),ig=g("ZodEmail",(t,e)=>{dc.init(t,e),X.init(t,e)});var Ch=g("ZodGUID",(t,e)=>{uc.init(t,e),X.init(t,e)});var Ro=g("ZodUUID",(t,e)=>{hc.init(t,e),X.init(t,e)});var lg=g("ZodURL",(t,e)=>{pc.init(t,e),X.init(t,e)});var cg=g("ZodEmoji",(t,e)=>{mc.init(t,e),X.init(t,e)});var ug=g("ZodNanoID",(t,e)=>{fc.init(t,e),X.init(t,e)});var hg=g("ZodCUID",(t,e)=>{gc.init(t,e),X.init(t,e)});var dg=g("ZodCUID2",(t,e)=>{wc.init(t,e),X.init(t,e)});var pg=g("ZodULID",(t,e)=>{yc.init(t,e),X.init(t,e)});var mg=g("ZodXID",(t,e)=>{bc.init(t,e),X.init(t,e)});var fg=g("ZodKSUID",(t,e)=>{kc.init(t,e),X.init(t,e)});var gg=g("ZodIPv4",(t,e)=>{Ic.init(t,e),X.init(t,e)});var wg=g("ZodIPv6",(t,e)=>{zc.init(t,e),X.init(t,e)});var yg=g("ZodCIDRv4",(t,e)=>{Tc.init(t,e),X.init(t,e)});var bg=g("ZodCIDRv6",(t,e)=>{$c.init(t,e),X.init(t,e)});var kg=g("ZodBase64",(t,e)=>{Pc.init(t,e),X.init(t,e)});var vg=g("ZodBase64URL",(t,e)=>{Ec.init(t,e),X.init(t,e)});var xg=g("ZodE164",(t,e)=>{Rc.init(t,e),X.init(t,e)});var Sg=g("ZodJWT",(t,e)=>{Ac.init(t,e),X.init(t,e)});var Oh=g("ZodNumber",(t,e)=>{ea.init(t,e),te.init(t,e),t._zod.processJSONSchema=(o,r,a)=>Fu(t,o,r,a),Sn(t,"ZodNumber",{gt(o,r){return this.check(To(o,r))},gte(o,r){return this.check(bn(o,r))},min(o,r){return this.check(bn(o,r))},lt(o,r){return this.check(zo(o,r))},lte(o,r){return this.check(yn(o,r))},max(o,r){return this.check(yn(o,r))},int(o){return this.check(Ph(o))},safe(o){return this.check(Ph(o))},positive(o){return this.check(To(0,o))},nonnegative(o){return this.check(bn(0,o))},negative(o){return this.check(zo(0,o))},nonpositive(o){return this.check(yn(0,o))},multipleOf(o,r){return this.check($o(o,r))},step(o,r){return this.check($o(o,r))},finite(){return this}});let n=t._zod.bag;t.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),t.isFinite=!0,t.format=n.format??null});function U(t){return Ru(Oh,t)}var _g=g("ZodNumberFormat",(t,e)=>{Dc.init(t,e),Oh.init(t,e)});function Ph(t){return Au(_g,t)}var Ig=g("ZodBoolean",(t,e)=>{Oc.init(t,e),te.init(t,e),t._zod.processJSONSchema=(n,o,r)=>Wu(t,n,o,r)});function ae(t){return Du(Ig,t)}var zg=g("ZodNull",(t,e)=>{jc.init(t,e),te.init(t,e),t._zod.processJSONSchema=(n,o,r)=>Vu(t,n,o,r)});function jh(t){return Ou(zg,t)}var Tg=g("ZodUnknown",(t,e)=>{Nc.init(t,e),te.init(t,e),t._zod.processJSONSchema=(n,o,r)=>Hu(t,n,o,r)});function Q(){return ju(Tg)}var $g=g("ZodNever",(t,e)=>{qc.init(t,e),te.init(t,e),t._zod.processJSONSchema=(n,o,r)=>Gu(t,n,o,r)});function Cg(t){return Nu($g,t)}var Pg=g("ZodArray",(t,e)=>{Mc.init(t,e),te.init(t,e),t._zod.processJSONSchema=(n,o,r)=>Qu(t,n,o,r),t.element=e.element,Sn(t,"ZodArray",{min(n,o){return this.check(jt(n,o))},nonempty(n){return this.check(jt(1,n))},max(n,o){return this.check(Co(n,o))},length(n,o){return this.check(Po(n,o))},unwrap(){return this.element}})});function j(t,e){return qu(Pg,t,e)}var Nh=g("ZodObject",(t,e)=>{Bc.init(t,e),te.init(t,e),t._zod.processJSONSchema=(n,o,r)=>eh(t,n,o,r),q.defineLazy(t,"shape",()=>e.shape),Sn(t,"ZodObject",{keyof(){return be(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:Q()})},loose(){return this.clone({...this._zod.def,catchall:Q()})},strict(){return this.clone({...this._zod.def,catchall:Cg()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return q.extend(this,n)},safeExtend(n){return q.safeExtend(this,n)},merge(n){return q.merge(this,n)},pick(n){return q.pick(this,n)},omit(n){return q.omit(this,n)},partial(...n){return q.partial(Lh,this,n[0])},required(...n){return q.required(Zh,this,n[0])}})});function v(t,e){let n={type:"object",shape:t??{},...q.normalizeParams(e)};return new Nh(n)}function ge(t,e){return new Nh({type:"object",shape:t,catchall:Q(),...q.normalizeParams(e)})}var qh=g("ZodUnion",(t,e)=>{ta.init(t,e),te.init(t,e),t._zod.processJSONSchema=(n,o,r)=>th(t,n,o,r),t.options=e.options});function J(t,e){return new qh({type:"union",options:t,...q.normalizeParams(e)})}var Eg=g("ZodDiscriminatedUnion",(t,e)=>{qh.init(t,e),Uc.init(t,e)});function za(t,e,n){return new Eg({type:"union",options:e,discriminator:t,...q.normalizeParams(n)})}var Rg=g("ZodIntersection",(t,e)=>{Fc.init(t,e),te.init(t,e),t._zod.processJSONSchema=(n,o,r)=>nh(t,n,o,r)});function Ao(t,e){return new Rg({type:"intersection",left:t,right:e})}var Eh=g("ZodRecord",(t,e)=>{Wc.init(t,e),te.init(t,e),t._zod.processJSONSchema=(n,o,r)=>oh(t,n,o,r),t.keyType=e.keyType,t.valueType=e.valueType});function V(t,e,n){return!e||!e._zod?new Eh({type:"record",keyType:f(),valueType:t,...q.normalizeParams(e)}):new Eh({type:"record",keyType:t,valueType:e,...q.normalizeParams(n)})}var Ia=g("ZodEnum",(t,e)=>{Vc.init(t,e),te.init(t,e),t._zod.processJSONSchema=(o,r,a)=>Ju(t,o,r,a),t.enum=e.entries,t.options=Object.values(e.entries);let n=new Set(Object.keys(e.entries));t.extract=(o,r)=>{let a={};for(let s of o)if(n.has(s))a[s]=e.entries[s];else throw new Error(`Key ${s} not found in enum`);return new Ia({...e,checks:[],...q.normalizeParams(r),entries:a})},t.exclude=(o,r)=>{let a={...e.entries};for(let s of o)if(n.has(s))delete a[s];else throw new Error(`Key ${s} not found in enum`);return new Ia({...e,checks:[],...q.normalizeParams(r),entries:a})}});function be(t,e){let n=Array.isArray(t)?Object.fromEntries(t.map(o=>[o,o])):t;return new Ia({type:"enum",entries:n,...q.normalizeParams(e)})}var Ag=g("ZodLiteral",(t,e)=>{Gc.init(t,e),te.init(t,e),t._zod.processJSONSchema=(n,o,r)=>Ku(t,n,o,r),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function _(t,e){return new Ag({type:"literal",values:Array.isArray(t)?t:[t],...q.normalizeParams(e)})}var Dg=g("ZodTransform",(t,e)=>{Hc.init(t,e),te.init(t,e),t._zod.processJSONSchema=(n,o,r)=>Xu(t,n,o,r),t._zod.parse=(n,o)=>{if(o.direction==="backward")throw new Et(t.constructor.name);n.addIssue=a=>{if(typeof a=="string")n.issues.push(q.issue(a,n.value,e));else{let s=a;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=t),n.issues.push(q.issue(s))}};let r=e.transform(n.value,n);return r instanceof Promise?r.then(a=>(n.value=a,n.fallback=!0,n)):(n.value=r,n.fallback=!0,n)}});function Mh(t){return new Dg({type:"transform",transform:t})}var Lh=g("ZodOptional",(t,e)=>{na.init(t,e),te.init(t,e),t._zod.processJSONSchema=(n,o,r)=>ka(t,n,o,r),t.unwrap=()=>t._zod.def.innerType});function ee(t){return new Lh({type:"optional",innerType:t})}var Og=g("ZodExactOptional",(t,e)=>{Jc.init(t,e),te.init(t,e),t._zod.processJSONSchema=(n,o,r)=>ka(t,n,o,r),t.unwrap=()=>t._zod.def.innerType});function jg(t){return new Og({type:"optional",innerType:t})}var Ng=g("ZodNullable",(t,e)=>{Kc.init(t,e),te.init(t,e),t._zod.processJSONSchema=(n,o,r)=>rh(t,n,o,r),t.unwrap=()=>t._zod.def.innerType});function Rh(t){return new Ng({type:"nullable",innerType:t})}var qg=g("ZodDefault",(t,e)=>{Yc.init(t,e),te.init(t,e),t._zod.processJSONSchema=(n,o,r)=>sh(t,n,o,r),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function Mg(t,e){return new qg({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():q.shallowClone(e)}})}var Lg=g("ZodPrefault",(t,e)=>{Xc.init(t,e),te.init(t,e),t._zod.processJSONSchema=(n,o,r)=>ih(t,n,o,r),t.unwrap=()=>t._zod.def.innerType});function Zg(t,e){return new Lg({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():q.shallowClone(e)}})}var Zh=g("ZodNonOptional",(t,e)=>{Qc.init(t,e),te.init(t,e),t._zod.processJSONSchema=(n,o,r)=>ah(t,n,o,r),t.unwrap=()=>t._zod.def.innerType});function Bg(t,e){return new Zh({type:"nonoptional",innerType:t,...q.normalizeParams(e)})}var Ug=g("ZodCatch",(t,e)=>{eu.init(t,e),te.init(t,e),t._zod.processJSONSchema=(n,o,r)=>lh(t,n,o,r),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function Fg(t,e){return new Ug({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var Bh=g("ZodPipe",(t,e)=>{oa.init(t,e),te.init(t,e),t._zod.processJSONSchema=(n,o,r)=>ch(t,n,o,r),t.in=e.in,t.out=e.out});function Ah(t,e){return new Bh({type:"pipe",in:t,out:e})}var Wg=g("ZodPreprocess",(t,e)=>{Bh.init(t,e),tu.init(t,e)}),Vg=g("ZodReadonly",(t,e)=>{nu.init(t,e),te.init(t,e),t._zod.processJSONSchema=(n,o,r)=>uh(t,n,o,r),t.unwrap=()=>t._zod.def.innerType});function Gg(t){return new Vg({type:"readonly",innerType:t})}var Uh=g("ZodCustom",(t,e)=>{ou.init(t,e),te.init(t,e),t._zod.processJSONSchema=(n,o,r)=>Yu(t,n,o,r)});function Fh(t,e){return Mu(Uh,t??(()=>!0),e)}function Hg(t,e={}){return Lu(Uh,t,e)}function Jg(t,e){return Zu(t,e)}function Ta(t,e){return new Wg({type:"pipe",in:Mh(t),out:e})}ze(ru());var Ca="2025-11-25";var Wh=[Ca,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],lt="io.modelcontextprotocol/related-task",Oo="2.0",re=Fh(t=>t!==null&&(typeof t=="object"||typeof t=="function")),Vh=J([f(),U().int()]),Gh=f(),rz=ge({ttl:U().optional(),pollInterval:U().optional()}),Kg=v({ttl:U().optional()}),Yg=v({taskId:f()}),Pa=ge({progressToken:Vh.optional(),[lt]:Yg.optional()}),$e=v({_meta:Pa.optional()}),_n=$e.extend({task:Kg.optional()}),Hh=t=>_n.safeParse(t).success,ie=v({method:f(),params:$e.loose().optional()}),Ee=v({_meta:Pa.optional()}),Re=v({method:f(),params:Ee.loose().optional()}),le=ge({_meta:Pa.optional()}),jo=J([f(),U().int()]),Jh=v({jsonrpc:_(Oo),id:jo,...ie.shape}).strict(),Ea=t=>Jh.safeParse(t).success,Kh=v({jsonrpc:_(Oo),...Re.shape}).strict(),Yh=t=>Kh.safeParse(t).success,Ra=v({jsonrpc:_(Oo),id:jo,result:le}).strict(),In=t=>Ra.safeParse(t).success;var O;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(O||(O={}));var Aa=v({jsonrpc:_(Oo),id:jo.optional(),error:v({code:U().int(),message:f(),data:Q().optional()})}).strict();var Xh=t=>Aa.safeParse(t).success;var Qh=J([Jh,Kh,Ra,Aa]),az=J([Ra,Aa]),No=le.strict(),Xg=Ee.extend({requestId:jo.optional(),reason:f().optional()}),qo=Re.extend({method:_("notifications/cancelled"),params:Xg}),Qg=v({src:f(),mimeType:f().optional(),sizes:j(f()).optional(),theme:be(["light","dark"]).optional()}),zn=v({icons:j(Qg).optional()}),qt=v({name:f(),title:f().optional()}),ed=qt.extend({...qt.shape,...zn.shape,version:f(),websiteUrl:f().optional(),description:f().optional()}),ew=Ao(v({applyDefaults:ae().optional()}),V(f(),Q())),tw=Ta(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Ao(v({form:ew.optional(),url:re.optional()}),V(f(),Q()).optional())),nw=ge({list:re.optional(),cancel:re.optional(),requests:ge({sampling:ge({createMessage:re.optional()}).optional(),elicitation:ge({create:re.optional()}).optional()}).optional()}),ow=ge({list:re.optional(),cancel:re.optional(),requests:ge({tools:ge({call:re.optional()}).optional()}).optional()}),rw=v({experimental:V(f(),re).optional(),sampling:v({context:re.optional(),tools:re.optional()}).optional(),elicitation:tw.optional(),roots:v({listChanged:ae().optional()}).optional(),tasks:nw.optional(),extensions:V(f(),re).optional()}),aw=$e.extend({protocolVersion:f(),capabilities:rw,clientInfo:ed}),Da=ie.extend({method:_("initialize"),params:aw});var sw=v({experimental:V(f(),re).optional(),logging:re.optional(),completions:re.optional(),prompts:v({listChanged:ae().optional()}).optional(),resources:v({subscribe:ae().optional(),listChanged:ae().optional()}).optional(),tools:v({listChanged:ae().optional()}).optional(),tasks:ow.optional(),extensions:V(f(),re).optional()}),iw=le.extend({protocolVersion:f(),capabilities:sw,serverInfo:ed,instructions:f().optional()}),Oa=Re.extend({method:_("notifications/initialized"),params:Ee.optional()});var Mo=ie.extend({method:_("ping"),params:$e.optional()}),lw=v({progress:U(),total:ee(U()),message:ee(f())}),cw=v({...Ee.shape,...lw.shape,progressToken:Vh}),Lo=Re.extend({method:_("notifications/progress"),params:cw}),uw=$e.extend({cursor:Gh.optional()}),Tn=ie.extend({params:uw.optional()}),$n=le.extend({nextCursor:Gh.optional()}),hw=be(["working","input_required","completed","failed","cancelled"]),Cn=v({taskId:f(),status:hw,ttl:J([U(),jh()]),createdAt:f(),lastUpdatedAt:f(),pollInterval:ee(U()),statusMessage:ee(f())}),Mt=le.extend({task:Cn}),dw=Ee.merge(Cn),Pn=Re.extend({method:_("notifications/tasks/status"),params:dw}),Zo=ie.extend({method:_("tasks/get"),params:$e.extend({taskId:f()})}),Bo=le.merge(Cn),Uo=ie.extend({method:_("tasks/result"),params:$e.extend({taskId:f()})}),sz=le.loose(),Fo=Tn.extend({method:_("tasks/list")}),Wo=$n.extend({tasks:j(Cn)}),Vo=ie.extend({method:_("tasks/cancel"),params:$e.extend({taskId:f()})}),td=le.merge(Cn),nd=v({uri:f(),mimeType:ee(f()),_meta:V(f(),Q()).optional()}),od=nd.extend({text:f()}),ja=f().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),rd=nd.extend({blob:ja}),En=be(["user","assistant"]),Lt=v({audience:j(En).optional(),priority:U().min(0).max(1).optional(),lastModified:xn.datetime({offset:!0}).optional()}),ad=v({...qt.shape,...zn.shape,uri:f(),description:ee(f()),mimeType:ee(f()),size:ee(U()),annotations:Lt.optional(),_meta:ee(ge({}))}),pw=v({...qt.shape,...zn.shape,uriTemplate:f(),description:ee(f()),mimeType:ee(f()),annotations:Lt.optional(),_meta:ee(ge({}))}),Na=Tn.extend({method:_("resources/list")}),mw=$n.extend({resources:j(ad)}),fw=Tn.extend({method:_("resources/templates/list")}),gw=$n.extend({resourceTemplates:j(pw)}),qa=$e.extend({uri:f()}),ww=qa,Ma=ie.extend({method:_("resources/read"),params:ww}),yw=le.extend({contents:j(J([od,rd]))}),bw=Re.extend({method:_("notifications/resources/list_changed"),params:Ee.optional()}),kw=qa,vw=ie.extend({method:_("resources/subscribe"),params:kw}),xw=qa,Sw=ie.extend({method:_("resources/unsubscribe"),params:xw}),_w=Ee.extend({uri:f()}),Iw=Re.extend({method:_("notifications/resources/updated"),params:_w}),zw=v({name:f(),description:ee(f()),required:ee(ae())}),Tw=v({...qt.shape,...zn.shape,description:ee(f()),arguments:ee(j(zw)),_meta:ee(ge({}))}),$w=Tn.extend({method:_("prompts/list")}),Cw=$n.extend({prompts:j(Tw)}),Pw=$e.extend({name:f(),arguments:V(f(),f()).optional()}),Ew=ie.extend({method:_("prompts/get"),params:Pw}),La=v({type:_("text"),text:f(),annotations:Lt.optional(),_meta:V(f(),Q()).optional()}),Za=v({type:_("image"),data:ja,mimeType:f(),annotations:Lt.optional(),_meta:V(f(),Q()).optional()}),Ba=v({type:_("audio"),data:ja,mimeType:f(),annotations:Lt.optional(),_meta:V(f(),Q()).optional()}),Rw=v({type:_("tool_use"),name:f(),id:f(),input:V(f(),Q()),_meta:V(f(),Q()).optional()}),Aw=v({type:_("resource"),resource:J([od,rd]),annotations:Lt.optional(),_meta:V(f(),Q()).optional()}),Dw=ad.extend({type:_("resource_link")}),Ua=J([La,Za,Ba,Dw,Aw]),Ow=v({role:En,content:Ua}),jw=le.extend({description:f().optional(),messages:j(Ow)}),Nw=Re.extend({method:_("notifications/prompts/list_changed"),params:Ee.optional()}),qw=v({title:f().optional(),readOnlyHint:ae().optional(),destructiveHint:ae().optional(),idempotentHint:ae().optional(),openWorldHint:ae().optional()}),Mw=v({taskSupport:be(["required","optional","forbidden"]).optional()}),sd=v({...qt.shape,...zn.shape,description:f().optional(),inputSchema:v({type:_("object"),properties:V(f(),re).optional(),required:j(f()).optional()}).catchall(Q()),outputSchema:v({type:_("object"),properties:V(f(),re).optional(),required:j(f()).optional()}).catchall(Q()).optional(),annotations:qw.optional(),execution:Mw.optional(),_meta:V(f(),Q()).optional()}),Fa=Tn.extend({method:_("tools/list")}),Lw=$n.extend({tools:j(sd)}),Go=le.extend({content:j(Ua).default([]),structuredContent:V(f(),Q()).optional(),isError:ae().optional()}),iz=Go.or(le.extend({toolResult:Q()})),Zw=_n.extend({name:f(),arguments:V(f(),Q()).optional()}),Rn=ie.extend({method:_("tools/call"),params:Zw}),Bw=Re.extend({method:_("notifications/tools/list_changed"),params:Ee.optional()}),lz=v({autoRefresh:ae().default(!0),debounceMs:U().int().nonnegative().default(300)}),An=be(["debug","info","notice","warning","error","critical","alert","emergency"]),Uw=$e.extend({level:An}),Wa=ie.extend({method:_("logging/setLevel"),params:Uw}),Fw=Ee.extend({level:An,logger:f().optional(),data:Q()}),Ww=Re.extend({method:_("notifications/message"),params:Fw}),Vw=v({name:f().optional()}),Gw=v({hints:j(Vw).optional(),costPriority:U().min(0).max(1).optional(),speedPriority:U().min(0).max(1).optional(),intelligencePriority:U().min(0).max(1).optional()}),Hw=v({mode:be(["auto","required","none"]).optional()}),Jw=v({type:_("tool_result"),toolUseId:f().describe("The unique identifier for the corresponding tool call."),content:j(Ua).default([]),structuredContent:v({}).loose().optional(),isError:ae().optional(),_meta:V(f(),Q()).optional()}),Kw=za("type",[La,Za,Ba]),Do=za("type",[La,Za,Ba,Rw,Jw]),Yw=v({role:En,content:J([Do,j(Do)]),_meta:V(f(),Q()).optional()}),Xw=_n.extend({messages:j(Yw),modelPreferences:Gw.optional(),systemPrompt:f().optional(),includeContext:be(["none","thisServer","allServers"]).optional(),temperature:U().optional(),maxTokens:U().int(),stopSequences:j(f()).optional(),metadata:re.optional(),tools:j(sd).optional(),toolChoice:Hw.optional()}),Qw=ie.extend({method:_("sampling/createMessage"),params:Xw}),Dn=le.extend({model:f(),stopReason:ee(be(["endTurn","stopSequence","maxTokens"]).or(f())),role:En,content:Kw}),Va=le.extend({model:f(),stopReason:ee(be(["endTurn","stopSequence","maxTokens","toolUse"]).or(f())),role:En,content:J([Do,j(Do)])}),ey=v({type:_("boolean"),title:f().optional(),description:f().optional(),default:ae().optional()}),ty=v({type:_("string"),title:f().optional(),description:f().optional(),minLength:U().optional(),maxLength:U().optional(),format:be(["email","uri","date","date-time"]).optional(),default:f().optional()}),ny=v({type:be(["number","integer"]),title:f().optional(),description:f().optional(),minimum:U().optional(),maximum:U().optional(),default:U().optional()}),oy=v({type:_("string"),title:f().optional(),description:f().optional(),enum:j(f()),default:f().optional()}),ry=v({type:_("string"),title:f().optional(),description:f().optional(),oneOf:j(v({const:f(),title:f()})),default:f().optional()}),ay=v({type:_("string"),title:f().optional(),description:f().optional(),enum:j(f()),enumNames:j(f()).optional(),default:f().optional()}),sy=J([oy,ry]),iy=v({type:_("array"),title:f().optional(),description:f().optional(),minItems:U().optional(),maxItems:U().optional(),items:v({type:_("string"),enum:j(f())}),default:j(f()).optional()}),ly=v({type:_("array"),title:f().optional(),description:f().optional(),minItems:U().optional(),maxItems:U().optional(),items:v({anyOf:j(v({const:f(),title:f()}))}),default:j(f()).optional()}),cy=J([iy,ly]),uy=J([ay,sy,cy]),hy=J([uy,ey,ty,ny]),dy=_n.extend({mode:_("form").optional(),message:f(),requestedSchema:v({type:_("object"),properties:V(f(),hy),required:j(f()).optional()})}),py=_n.extend({mode:_("url"),message:f(),elicitationId:f(),url:f().url()}),my=J([dy,py]),fy=ie.extend({method:_("elicitation/create"),params:my}),gy=Ee.extend({elicitationId:f()}),wy=Re.extend({method:_("notifications/elicitation/complete"),params:gy}),Zt=le.extend({action:be(["accept","decline","cancel"]),content:Ta(t=>t===null?void 0:t,V(f(),J([f(),U(),ae(),j(f())])).optional())}),yy=v({type:_("ref/resource"),uri:f()});var by=v({type:_("ref/prompt"),name:f()}),ky=$e.extend({ref:J([by,yy]),argument:v({name:f(),value:f()}),context:v({arguments:V(f(),f()).optional()}).optional()}),vy=ie.extend({method:_("completion/complete"),params:ky});var xy=le.extend({completion:ge({values:j(f()).max(100),total:ee(U().int()),hasMore:ee(ae())})}),Sy=v({uri:f().startsWith("file://"),name:f().optional(),_meta:V(f(),Q()).optional()}),_y=ie.extend({method:_("roots/list"),params:$e.optional()}),Ga=le.extend({roots:j(Sy)}),Iy=Re.extend({method:_("notifications/roots/list_changed"),params:Ee.optional()}),cz=J([Mo,Da,vy,Wa,Ew,$w,Na,fw,Ma,vw,Sw,Rn,Fa,Zo,Uo,Fo,Vo]),uz=J([qo,Lo,Oa,Iy,Pn]),hz=J([No,Dn,Va,Zt,Ga,Bo,Wo,Mt]),dz=J([Mo,Qw,fy,_y,Zo,Uo,Fo,Vo]),pz=J([qo,Lo,Ww,Iw,bw,Bw,Nw,Pn,wy]),mz=J([No,iw,xy,jw,Cw,mw,gw,yw,Go,Lw,Bo,Wo,Mt]),P=class t extends Error{constructor(e,n,o){super(`MCP error ${e}: ${n}`),this.code=e,this.data=o,this.name="McpError"}static fromError(e,n,o){if(e===O.UrlElicitationRequired&&o){let r=o;if(r.elicitations)return new $a(r.elicitations,n)}return new t(e,n,o)}},$a=class extends P{constructor(e,n=`URL elicitation${e.length>1?"s":""} required`){super(O.UrlElicitationRequired,n,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function ct(t){return t==="completed"||t==="failed"||t==="cancelled"}var Gz=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Ha(t){let n=Eo(t)?.method;if(!n)throw new Error("Schema is missing a method literal");let o=hh(n);if(typeof o!="string")throw new Error("Schema method literal must be a string");return o}function Ja(t,e){let n=it(t,e);if(!n.success)throw n.error;return n.data}var Ey=6e4,Ho=class{constructor(e){this._options=e,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(qo,n=>{this._oncancel(n)}),this.setNotificationHandler(Lo,n=>{this._onprogress(n)}),this.setRequestHandler(Mo,n=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Zo,async(n,o)=>{let r=await this._taskStore.getTask(n.params.taskId,o.sessionId);if(!r)throw new P(O.InvalidParams,"Failed to retrieve task: Task not found");return{...r}}),this.setRequestHandler(Uo,async(n,o)=>{let r=async()=>{let a=n.params.taskId;if(this._taskMessageQueue){let i;for(;i=await this._taskMessageQueue.dequeue(a,o.sessionId);){if(i.type==="response"||i.type==="error"){let l=i.message,c=l.id,u=this._requestResolvers.get(c);if(u)if(this._requestResolvers.delete(c),i.type==="response")u(l);else{let h=l,d=new P(h.error.code,h.error.message,h.error.data);u(d)}else{let h=i.type==="response"?"Response":"Error";this._onerror(new Error(`${h} handler missing for request ${c}`))}continue}await this._transport?.send(i.message,{relatedRequestId:o.requestId})}}let s=await this._taskStore.getTask(a,o.sessionId);if(!s)throw new P(O.InvalidParams,`Task not found: ${a}`);if(!ct(s.status))return await this._waitForTaskUpdate(a,o.signal),await r();if(ct(s.status)){let i=await this._taskStore.getTaskResult(a,o.sessionId);return this._clearTaskQueue(a),{...i,_meta:{...i._meta,[lt]:{taskId:a}}}}return await r()};return await r()}),this.setRequestHandler(Fo,async(n,o)=>{try{let{tasks:r,nextCursor:a}=await this._taskStore.listTasks(n.params?.cursor,o.sessionId);return{tasks:r,nextCursor:a,_meta:{}}}catch(r){throw new P(O.InvalidParams,`Failed to list tasks: ${r instanceof Error?r.message:String(r)}`)}}),this.setRequestHandler(Vo,async(n,o)=>{try{let r=await this._taskStore.getTask(n.params.taskId,o.sessionId);if(!r)throw new P(O.InvalidParams,`Task not found: ${n.params.taskId}`);if(ct(r.status))throw new P(O.InvalidParams,`Cannot cancel task in terminal status: ${r.status}`);await this._taskStore.updateTaskStatus(n.params.taskId,"cancelled","Client cancelled task execution.",o.sessionId),this._clearTaskQueue(n.params.taskId);let a=await this._taskStore.getTask(n.params.taskId,o.sessionId);if(!a)throw new P(O.InvalidParams,`Task not found after cancellation: ${n.params.taskId}`);return{_meta:{},...a}}catch(r){throw r instanceof P?r:new P(O.InvalidRequest,`Failed to cancel task: ${r instanceof Error?r.message:String(r)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,n,o,r,a=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(r,n),startTime:Date.now(),timeout:n,maxTotalTimeout:o,resetTimeoutOnProgress:a,onTimeout:r})}_resetTimeout(e){let n=this._timeoutInfo.get(e);if(!n)return!1;let o=Date.now()-n.startTime;if(n.maxTotalTimeout&&o>=n.maxTotalTimeout)throw this._timeoutInfo.delete(e),P.fromError(O.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:n.maxTotalTimeout,totalElapsed:o});return clearTimeout(n.timeoutId),n.timeoutId=setTimeout(n.onTimeout,n.timeout),!0}_cleanupTimeout(e){let n=this._timeoutInfo.get(e);n&&(clearTimeout(n.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let n=this.transport?.onclose;this._transport.onclose=()=>{n?.(),this._onclose()};let o=this.transport?.onerror;this._transport.onerror=a=>{o?.(a),this._onerror(a)};let r=this._transport?.onmessage;this._transport.onmessage=(a,s)=>{r?.(a,s),In(a)||Xh(a)?this._onresponse(a):Ea(a)?this._onrequest(a,s):Yh(a)?this._onnotification(a):this._onerror(new Error(`Unknown message type: ${JSON.stringify(a)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let o of this._timeoutInfo.values())clearTimeout(o.timeoutId);this._timeoutInfo.clear();for(let o of this._requestHandlerAbortControllers.values())o.abort();this._requestHandlerAbortControllers.clear();let n=P.fromError(O.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let o of e.values())o(n)}_onerror(e){this.onerror?.(e)}_onnotification(e){let n=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;n!==void 0&&Promise.resolve().then(()=>n(e)).catch(o=>this._onerror(new Error(`Uncaught error in notification handler: ${o}`)))}_onrequest(e,n){let o=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,r=this._transport,a=e.params?._meta?.[lt]?.taskId;if(o===void 0){let u={jsonrpc:"2.0",id:e.id,error:{code:O.MethodNotFound,message:"Method not found"}};a&&this._taskMessageQueue?this._enqueueTaskMessage(a,{type:"error",message:u,timestamp:Date.now()},r?.sessionId).catch(h=>this._onerror(new Error(`Failed to enqueue error response: ${h}`))):r?.send(u).catch(h=>this._onerror(new Error(`Failed to send an error response: ${h}`)));return}let s=new AbortController;this._requestHandlerAbortControllers.set(e.id,s);let i=Hh(e.params)?e.params.task:void 0,l=this._taskStore?this.requestTaskStore(e,r?.sessionId):void 0,c={signal:s.signal,sessionId:r?.sessionId,_meta:e.params?._meta,sendNotification:async u=>{if(s.signal.aborted)return;let h={relatedRequestId:e.id};a&&(h.relatedTask={taskId:a}),await this.notification(u,h)},sendRequest:async(u,h,d)=>{if(s.signal.aborted)throw new P(O.ConnectionClosed,"Request was cancelled");let p={...d,relatedRequestId:e.id};a&&!p.relatedTask&&(p.relatedTask={taskId:a});let m=p.relatedTask?.taskId??a;return m&&l&&await l.updateTaskStatus(m,"input_required"),await this.request(u,h,p)},authInfo:n?.authInfo,requestId:e.id,requestInfo:n?.requestInfo,taskId:a,taskStore:l,taskRequestedTtl:i?.ttl,closeSSEStream:n?.closeSSEStream,closeStandaloneSSEStream:n?.closeStandaloneSSEStream};Promise.resolve().then(()=>{i&&this.assertTaskHandlerCapability(e.method)}).then(()=>o(e,c)).then(async u=>{if(s.signal.aborted)return;let h={result:u,jsonrpc:"2.0",id:e.id};a&&this._taskMessageQueue?await this._enqueueTaskMessage(a,{type:"response",message:h,timestamp:Date.now()},r?.sessionId):await r?.send(h)},async u=>{if(s.signal.aborted)return;let h={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:O.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};a&&this._taskMessageQueue?await this._enqueueTaskMessage(a,{type:"error",message:h,timestamp:Date.now()},r?.sessionId):await r?.send(h)}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===s&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:n,...o}=e.params,r=Number(n),a=this._progressHandlers.get(r);if(!a){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let s=this._responseHandlers.get(r),i=this._timeoutInfo.get(r);if(i&&s&&i.resetTimeoutOnProgress)try{this._resetTimeout(r)}catch(l){this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),s(l);return}a(o)}_onresponse(e){let n=Number(e.id),o=this._requestResolvers.get(n);if(o){if(this._requestResolvers.delete(n),In(e))o(e);else{let s=new P(e.error.code,e.error.message,e.error.data);o(s)}return}let r=this._responseHandlers.get(n);if(r===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(n),this._cleanupTimeout(n);let a=!1;if(In(e)&&e.result&&typeof e.result=="object"){let s=e.result;if(s.task&&typeof s.task=="object"){let i=s.task;typeof i.taskId=="string"&&(a=!0,this._taskProgressTokens.set(i.taskId,n))}}if(a||this._progressHandlers.delete(n),In(e))r(e);else{let s=P.fromError(e.error.code,e.error.message,e.error.data);r(s)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,n,o){let{task:r}=o??{};if(!r){try{yield{type:"result",result:await this.request(e,n,o)}}catch(s){yield{type:"error",error:s instanceof P?s:new P(O.InternalError,String(s))}}return}let a;try{let s=await this.request(e,Mt,o);if(s.task)a=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new P(O.InternalError,"Task creation did not return a task");for(;;){let i=await this.getTask({taskId:a},o);if(yield{type:"taskStatus",task:i},ct(i.status)){i.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:a},n,o)}:i.status==="failed"?yield{type:"error",error:new P(O.InternalError,`Task ${a} failed`)}:i.status==="cancelled"&&(yield{type:"error",error:new P(O.InternalError,`Task ${a} was cancelled`)});return}if(i.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:a},n,o)};return}let l=i.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(c=>setTimeout(c,l)),o?.signal?.throwIfAborted()}}catch(s){yield{type:"error",error:s instanceof P?s:new P(O.InternalError,String(s))}}}request(e,n,o){let{relatedRequestId:r,resumptionToken:a,onresumptiontoken:s,task:i,relatedTask:l}=o??{};return new Promise((c,u)=>{let h=z=>{u(z)};if(!this._transport){h(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),i&&this.assertTaskCapability(e.method)}catch(z){h(z);return}o?.signal?.throwIfAborted();let d=this._requestMessageId++,p={...e,jsonrpc:"2.0",id:d};o?.onprogress&&(this._progressHandlers.set(d,o.onprogress),p.params={...e.params,_meta:{...e.params?._meta||{},progressToken:d}}),i&&(p.params={...p.params,task:i}),l&&(p.params={...p.params,_meta:{...p.params?._meta||{},[lt]:l}});let m=z=>{this._responseHandlers.delete(d),this._progressHandlers.delete(d),this._cleanupTimeout(d),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:d,reason:String(z)}},{relatedRequestId:r,resumptionToken:a,onresumptiontoken:s}).catch(T=>this._onerror(new Error(`Failed to send cancellation: ${T}`)));let S=z instanceof P?z:new P(O.RequestTimeout,String(z));u(S)};this._responseHandlers.set(d,z=>{if(!o?.signal?.aborted){if(z instanceof Error)return u(z);try{let S=it(n,z.result);S.success?c(S.data):u(S.error)}catch(S){u(S)}}}),o?.signal?.addEventListener("abort",()=>{m(o?.signal?.reason)});let w=o?.timeout??Ey,y=()=>m(P.fromError(O.RequestTimeout,"Request timed out",{timeout:w}));this._setupTimeout(d,w,o?.maxTotalTimeout,y,o?.resetTimeoutOnProgress??!1);let b=l?.taskId;if(b){let z=S=>{let T=this._responseHandlers.get(d);T?T(S):this._onerror(new Error(`Response handler missing for side-channeled request ${d}`))};this._requestResolvers.set(d,z),this._enqueueTaskMessage(b,{type:"request",message:p,timestamp:Date.now()}).catch(S=>{this._cleanupTimeout(d),u(S)})}else this._transport.send(p,{relatedRequestId:r,resumptionToken:a,onresumptiontoken:s}).catch(z=>{this._cleanupTimeout(d),u(z)})})}async getTask(e,n){return this.request({method:"tasks/get",params:e},Bo,n)}async getTaskResult(e,n,o){return this.request({method:"tasks/result",params:e},n,o)}async listTasks(e,n){return this.request({method:"tasks/list",params:e},Wo,n)}async cancelTask(e,n){return this.request({method:"tasks/cancel",params:e},td,n)}async notification(e,n){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let o=n?.relatedTask?.taskId;if(o){let i={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[lt]:n.relatedTask}}};await this._enqueueTaskMessage(o,{type:"notification",message:i,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!n?.relatedRequestId&&!n?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let i={...e,jsonrpc:"2.0"};n?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[lt]:n.relatedTask}}}),this._transport?.send(i,n).catch(l=>this._onerror(l))});return}let s={...e,jsonrpc:"2.0"};n?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[lt]:n.relatedTask}}}),await this._transport.send(s,n)}setRequestHandler(e,n){let o=Ha(e);this.assertRequestHandlerCapability(o),this._requestHandlers.set(o,(r,a)=>{let s=Ja(e,r);return Promise.resolve(n(s,a))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,n){let o=Ha(e);this._notificationHandlers.set(o,r=>{let a=Ja(e,r);return Promise.resolve(n(a))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let n=this._taskProgressTokens.get(e);n!==void 0&&(this._progressHandlers.delete(n),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,n,o){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let r=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,n,o,r)}async _clearTaskQueue(e,n){if(this._taskMessageQueue){let o=await this._taskMessageQueue.dequeueAll(e,n);for(let r of o)if(r.type==="request"&&Ea(r.message)){let a=r.message.id,s=this._requestResolvers.get(a);s?(s(new P(O.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(a)):this._onerror(new Error(`Resolver missing for request ${a} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,n){let o=this._options?.defaultTaskPollInterval??1e3;try{let r=await this._taskStore?.getTask(e);r?.pollInterval&&(o=r.pollInterval)}catch{}return new Promise((r,a)=>{if(n.aborted){a(new P(O.InvalidRequest,"Request cancelled"));return}let s=setTimeout(r,o);n.addEventListener("abort",()=>{clearTimeout(s),a(new P(O.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,n){let o=this._taskStore;if(!o)throw new Error("No task store configured");return{createTask:async r=>{if(!e)throw new Error("No request provided");return await o.createTask(r,e.id,{method:e.method,params:e.params},n)},getTask:async r=>{let a=await o.getTask(r,n);if(!a)throw new P(O.InvalidParams,"Failed to retrieve task: Task not found");return a},storeTaskResult:async(r,a,s)=>{await o.storeTaskResult(r,a,s,n);let i=await o.getTask(r,n);if(i){let l=Pn.parse({method:"notifications/tasks/status",params:i});await this.notification(l),ct(i.status)&&this._cleanupTaskProgressHandler(r)}},getTaskResult:r=>o.getTaskResult(r,n),updateTaskStatus:async(r,a,s)=>{let i=await o.getTask(r,n);if(!i)throw new P(O.InvalidParams,`Task "${r}" not found - it may have been cleaned up`);if(ct(i.status))throw new P(O.InvalidParams,`Cannot update task "${r}" from terminal status "${i.status}" to "${a}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await o.updateTaskStatus(r,a,s,n);let l=await o.getTask(r,n);if(l){let c=Pn.parse({method:"notifications/tasks/status",params:l});await this.notification(c),ct(l.status)&&this._cleanupTaskProgressHandler(r)}},listTasks:r=>o.listTasks(r,n)}}};function id(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function ld(t,e){let n={...t};for(let o in e){let r=o,a=e[r];if(a===void 0)continue;let s=n[r];id(s)&&id(a)?n[r]={...s,...a}:n[r]=a}return n}var Qm=Gi(Oi(),1),ef=Gi(Xm(),1);function D_(){let t=new Qm.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,ef.default)(t),t}var Cr=class{constructor(e){this._ajv=e??D_()}getValidator(e){let n="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return o=>n(o)?{valid:!0,data:o,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(n.errors)}}};var Pr=class{constructor(e){this._server=e}requestStream(e,n,o){return this._server.requestStream(e,n,o)}createMessageStream(e,n){let o=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!o?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let r=e.messages[e.messages.length-1],a=Array.isArray(r.content)?r.content:[r.content],s=a.some(u=>u.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,l=i?Array.isArray(i.content)?i.content:[i.content]:[],c=l.some(u=>u.type==="tool_use");if(s){if(a.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(l.filter(d=>d.type==="tool_use").map(d=>d.id)),h=new Set(a.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(u.size!==h.size||![...u].every(d=>h.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},Dn,n)}elicitInputStream(e,n){let o=this._server.getClientCapabilities(),r=e.mode??"form";switch(r){case"url":{if(!o?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!o?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let a=r==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:a},Zt,n)}async getTask(e,n){return this._server.getTask({taskId:e},n)}async getTaskResult(e,n,o){return this._server.getTaskResult({taskId:e},n,o)}async listTasks(e,n){return this._server.listTasks(e?{cursor:e}:void 0,n)}async cancelTask(e,n){return this._server.cancelTask({taskId:e},n)}};function tf(t,e,n){if(!t)throw new Error(`${n} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${n} does not support task creation for tools/call (required for ${e})`);break;default:break}}function nf(t,e,n){if(!t)throw new Error(`${n} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${n} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${n} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var Er=class extends Ho{constructor(e,n){super(n),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(An.options.map((o,r)=>[o,r])),this.isMessageIgnored=(o,r)=>{let a=this._loggingLevels.get(r);return a?this.LOG_LEVEL_SEVERITY.get(o)<this.LOG_LEVEL_SEVERITY.get(a):!1},this._capabilities=n?.capabilities??{},this._instructions=n?.instructions,this._jsonSchemaValidator=n?.jsonSchemaValidator??new Cr,this.setRequestHandler(Da,o=>this._oninitialize(o)),this.setNotificationHandler(Oa,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Wa,async(o,r)=>{let a=r.sessionId||r.requestInfo?.headers["mcp-session-id"]||void 0,{level:s}=o.params,i=An.safeParse(s);return i.success&&this._loggingLevels.set(a,i.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Pr(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=ld(this._capabilities,e)}setRequestHandler(e,n){let r=Eo(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let a;if(Nt(r)){let i=r;a=i._zod?.def?.value??i.value}else{let i=r;a=i._def?.value??i.value}if(typeof a!="string")throw new Error("Schema method literal must be a string");if(a==="tools/call"){let i=async(l,c)=>{let u=it(Rn,l);if(!u.success){let m=u.error instanceof Error?u.error.message:String(u.error);throw new P(O.InvalidParams,`Invalid tools/call request: ${m}`)}let{params:h}=u.data,d=await Promise.resolve(n(l,c));if(h.task){let m=it(Mt,d);if(!m.success){let w=m.error instanceof Error?m.error.message:String(m.error);throw new P(O.InvalidParams,`Invalid task creation result: ${w}`)}return m.data}let p=it(Go,d);if(!p.success){let m=p.error instanceof Error?p.error.message:String(p.error);throw new P(O.InvalidParams,`Invalid tools/call result: ${m}`)}return p.data};return super.setRequestHandler(e,i)}return super.setRequestHandler(e,n)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){nf(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&tf(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let n=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Wh.includes(n)?n:Ca,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"},No)}async createMessage(e,n){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let o=e.messages[e.messages.length-1],r=Array.isArray(o.content)?o.content:[o.content],a=r.some(c=>c.type==="tool_result"),s=e.messages.length>1?e.messages[e.messages.length-2]:void 0,i=s?Array.isArray(s.content)?s.content:[s.content]:[],l=i.some(c=>c.type==="tool_use");if(a){if(r.some(c=>c.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!l)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(l){let c=new Set(i.filter(h=>h.type==="tool_use").map(h=>h.id)),u=new Set(r.filter(h=>h.type==="tool_result").map(h=>h.toolUseId));if(c.size!==u.size||![...c].every(h=>u.has(h)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},Va,n):this.request({method:"sampling/createMessage",params:e},Dn,n)}async elicitInput(e,n){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let r=e;return this.request({method:"elicitation/create",params:r},Zt,n)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let r=e.mode==="form"?e:{...e,mode:"form"},a=await this.request({method:"elicitation/create",params:r},Zt,n);if(a.action==="accept"&&a.content&&r.requestedSchema)try{let i=this._jsonSchemaValidator.getValidator(r.requestedSchema)(a.content);if(!i.valid)throw new P(O.InvalidParams,`Elicitation response content does not match requested schema: ${i.errorMessage}`)}catch(s){throw s instanceof P?s:new P(O.InternalError,`Error validating elicitation response: ${s instanceof Error?s.message:String(s)}`)}return a}}}createElicitationCompletionNotifier(e,n){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},n)}async listRoots(e,n){return this.request({method:"roots/list",params:e},Ga,n)}async sendLoggingMessage(e,n){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,n))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}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"})}};import rf from"node:process";var Rr=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
73
- `);if(e===-1)return null;let n=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),O_(n)}clear(){this._buffer=void 0}};function O_(t){return Qh.parse(JSON.parse(t))}function of(t){return JSON.stringify(t)+`
74
- `}var Ar=class{constructor(e=rf.stdin,n=rf.stdout){this._stdin=e,this._stdout=n,this._readBuffer=new Rr,this._started=!1,this._ondata=o=>{this._readBuffer.append(o),this.processReadBuffer()},this._onerror=o=>{this.onerror?.(o)}}async start(){if(this._started)throw new 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(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){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(e){return new Promise(n=>{let o=of(e);this._stdout.write(o)?n():this._stdout.once("drain",n)})}};var _e={general:`
72
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let s of t.seen.entries()){let i=s[1];if(e===s[0]){a(s);continue}if(t.external){let c=t.external.registry.get(s[0])?.id;if(e!==s[0]&&c){a(s);continue}}if(t.metadataRegistry.get(s[0])?.id){a(s);continue}if(i.cycle){a(s);continue}if(i.count>1&&t.reused==="ref"){a(s);continue}}}function Sa(t,e){let n=t.seen.get(e);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=i=>{let l=t.seen.get(i);if(l.ref===null)return;let c=l.def??l.schema,u={...c},h=l.ref;if(l.ref=null,h){o(h);let p=t.seen.get(h),m=p.schema;if(m.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(c.allOf=c.allOf??[],c.allOf.push(m)):Object.assign(c,m),Object.assign(c,u),i._zod.parent===h)for(let y in c)y==="$ref"||y==="allOf"||y in u||delete c[y];if(m.$ref&&p.def)for(let y in c)y==="$ref"||y==="allOf"||y in p.def&&JSON.stringify(c[y])===JSON.stringify(p.def[y])&&delete c[y]}let d=i._zod.parent;if(d&&d!==h){o(d);let p=t.seen.get(d);if(p?.schema.$ref&&(c.$ref=p.schema.$ref,p.def))for(let m in c)m==="$ref"||m==="allOf"||m in p.def&&JSON.stringify(c[m])===JSON.stringify(p.def[m])&&delete c[m]}t.override({zodSchema:i,jsonSchema:c,path:l.path??[]})};for(let i of[...t.seen.entries()].reverse())o(i[0]);let r={};if(t.target==="draft-2020-12"?r.$schema="https://json-schema.org/draft/2020-12/schema":t.target==="draft-07"?r.$schema="http://json-schema.org/draft-07/schema#":t.target==="draft-04"?r.$schema="http://json-schema.org/draft-04/schema#":t.target,t.external?.uri){let i=t.external.registry.get(e)?.id;if(!i)throw new Error("Schema is missing an `id` property");r.$id=t.external.uri(i)}Object.assign(r,n.def??n.schema);let a=t.metadataRegistry.get(e)?.id;a!==void 0&&r.id===a&&delete r.id;let s=t.external?.defs??{};for(let i of t.seen.entries()){let l=i[1];l.def&&l.defId&&(l.def.id===l.defId&&delete l.def.id,s[l.defId]=l.def)}t.external||Object.keys(s).length>0&&(t.target==="draft-2020-12"?r.$defs=s:r.definitions=s);try{let i=JSON.parse(JSON.stringify(r));return Object.defineProperty(i,"~standard",{value:{...e["~standard"],jsonSchema:{input:xn(e,"input",t.processors),output:xn(e,"output",t.processors)}},enumerable:!1,writable:!1}),i}catch{throw new Error("Error converting schema to JSON.")}}function fe(t,e){let n=e??{seen:new Set};if(n.seen.has(t))return!1;n.seen.add(t);let o=t._zod.def;if(o.type==="transform")return!0;if(o.type==="array")return fe(o.element,n);if(o.type==="set")return fe(o.valueType,n);if(o.type==="lazy")return fe(o.getter(),n);if(o.type==="promise"||o.type==="optional"||o.type==="nonoptional"||o.type==="nullable"||o.type==="readonly"||o.type==="default"||o.type==="prefault")return fe(o.innerType,n);if(o.type==="intersection")return fe(o.left,n)||fe(o.right,n);if(o.type==="record"||o.type==="map")return fe(o.keyType,n)||fe(o.valueType,n);if(o.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:fe(o.in,n)||fe(o.out,n);if(o.type==="object"){for(let r in o.shape)if(fe(o.shape[r],n))return!0;return!1}if(o.type==="union"){for(let r of o.options)if(fe(r,n))return!0;return!1}if(o.type==="tuple"){for(let r of o.items)if(fe(r,n))return!0;return!!(o.rest&&fe(o.rest,n))}return!1}var Gu=(t,e={})=>n=>{let o=va({...n,processors:e});return ne(t,o),xa(o,t),Sa(o,t)},xn=(t,e,n={})=>o=>{let{libraryOptions:r,target:a}=o??{},s=va({...r??{},target:a,io:e,processors:n});return ne(t,s),xa(s,t),Sa(s,t)};var tg={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Hu=(t,e,n,o)=>{let r=n;r.type="string";let{minimum:a,maximum:s,format:i,patterns:l,contentEncoding:c}=t._zod.bag;if(typeof a=="number"&&(r.minLength=a),typeof s=="number"&&(r.maxLength=s),i&&(r.format=tg[i]??i,r.format===""&&delete r.format,i==="time"&&delete r.format),c&&(r.contentEncoding=c),l&&l.size>0){let u=[...l];u.length===1?r.pattern=u[0].source:u.length>1&&(r.allOf=[...u.map(h=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:h.source}))])}},Ju=(t,e,n,o)=>{let r=n,{minimum:a,maximum:s,format:i,multipleOf:l,exclusiveMaximum:c,exclusiveMinimum:u}=t._zod.bag;typeof i=="string"&&i.includes("int")?r.type="integer":r.type="number";let h=typeof u=="number"&&u>=(a??Number.NEGATIVE_INFINITY),d=typeof c=="number"&&c<=(s??Number.POSITIVE_INFINITY),p=e.target==="draft-04"||e.target==="openapi-3.0";h?p?(r.minimum=u,r.exclusiveMinimum=!0):r.exclusiveMinimum=u:typeof a=="number"&&(r.minimum=a),d?p?(r.maximum=c,r.exclusiveMaximum=!0):r.exclusiveMaximum=c:typeof s=="number"&&(r.maximum=s),typeof l=="number"&&(r.multipleOf=l)},Ku=(t,e,n,o)=>{n.type="boolean"};var Yu=(t,e,n,o)=>{e.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"};var Xu=(t,e,n,o)=>{n.not={}};var Qu=(t,e,n,o)=>{};var eh=(t,e,n,o)=>{let r=t._zod.def,a=dn(r.entries);a.every(s=>typeof s=="number")&&(n.type="number"),a.every(s=>typeof s=="string")&&(n.type="string"),n.enum=a},th=(t,e,n,o)=>{let r=t._zod.def,a=[];for(let s of r.values)if(s===void 0){if(e.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof s=="bigint"){if(e.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");a.push(Number(s))}else a.push(s);if(a.length!==0)if(a.length===1){let s=a[0];n.type=s===null?"null":typeof s,e.target==="draft-04"||e.target==="openapi-3.0"?n.enum=[s]:n.const=s}else a.every(s=>typeof s=="number")&&(n.type="number"),a.every(s=>typeof s=="string")&&(n.type="string"),a.every(s=>typeof s=="boolean")&&(n.type="boolean"),a.every(s=>s===null)&&(n.type="null"),n.enum=a};var nh=(t,e,n,o)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")};var oh=(t,e,n,o)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")};var rh=(t,e,n,o)=>{let r=n,a=t._zod.def,{minimum:s,maximum:i}=t._zod.bag;typeof s=="number"&&(r.minItems=s),typeof i=="number"&&(r.maxItems=i),r.type="array",r.items=ne(a.element,e,{...o,path:[...o.path,"items"]})},ah=(t,e,n,o)=>{let r=n,a=t._zod.def;r.type="object",r.properties={};let s=a.shape;for(let c in s)r.properties[c]=ne(s[c],e,{...o,path:[...o.path,"properties",c]});let i=new Set(Object.keys(s)),l=new Set([...i].filter(c=>{let u=a.shape[c]._zod;return e.io==="input"?u.optin===void 0:u.optout===void 0}));l.size>0&&(r.required=Array.from(l)),a.catchall?._zod.def.type==="never"?r.additionalProperties=!1:a.catchall?a.catchall&&(r.additionalProperties=ne(a.catchall,e,{...o,path:[...o.path,"additionalProperties"]})):e.io==="output"&&(r.additionalProperties=!1)},sh=(t,e,n,o)=>{let r=t._zod.def,a=r.inclusive===!1,s=r.options.map((i,l)=>ne(i,e,{...o,path:[...o.path,a?"oneOf":"anyOf",l]}));a?n.oneOf=s:n.anyOf=s},ih=(t,e,n,o)=>{let r=t._zod.def,a=ne(r.left,e,{...o,path:[...o.path,"allOf",0]}),s=ne(r.right,e,{...o,path:[...o.path,"allOf",1]}),i=c=>"allOf"in c&&Object.keys(c).length===1,l=[...i(a)?a.allOf:[a],...i(s)?s.allOf:[s]];n.allOf=l};var lh=(t,e,n,o)=>{let r=n,a=t._zod.def;r.type="object";let s=a.keyType,l=s._zod.bag?.patterns;if(a.mode==="loose"&&l&&l.size>0){let u=ne(a.valueType,e,{...o,path:[...o.path,"patternProperties","*"]});r.patternProperties={};for(let h of l)r.patternProperties[h.source]=u}else(e.target==="draft-07"||e.target==="draft-2020-12")&&(r.propertyNames=ne(a.keyType,e,{...o,path:[...o.path,"propertyNames"]})),r.additionalProperties=ne(a.valueType,e,{...o,path:[...o.path,"additionalProperties"]});let c=s._zod.values;if(c){let u=[...c].filter(h=>typeof h=="string"||typeof h=="number");u.length>0&&(r.required=u)}},ch=(t,e,n,o)=>{let r=t._zod.def,a=ne(r.innerType,e,o),s=e.seen.get(t);e.target==="openapi-3.0"?(s.ref=r.innerType,n.nullable=!0):n.anyOf=[a,{type:"null"}]},uh=(t,e,n,o)=>{let r=t._zod.def;ne(r.innerType,e,o);let a=e.seen.get(t);a.ref=r.innerType},hh=(t,e,n,o)=>{let r=t._zod.def;ne(r.innerType,e,o);let a=e.seen.get(t);a.ref=r.innerType,n.default=JSON.parse(JSON.stringify(r.defaultValue))},dh=(t,e,n,o)=>{let r=t._zod.def;ne(r.innerType,e,o);let a=e.seen.get(t);a.ref=r.innerType,e.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(r.defaultValue)))},ph=(t,e,n,o)=>{let r=t._zod.def;ne(r.innerType,e,o);let a=e.seen.get(t);a.ref=r.innerType;let s;try{s=r.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=s},mh=(t,e,n,o)=>{let r=t._zod.def,a=r.in._zod.traits.has("$ZodTransform"),s=e.io==="input"?a?r.out:r.in:r.out;ne(s,e,o);let i=e.seen.get(t);i.ref=s},fh=(t,e,n,o)=>{let r=t._zod.def;ne(r.innerType,e,o);let a=e.seen.get(t);a.ref=r.innerType,n.readOnly=!0};var _a=(t,e,n,o)=>{let r=t._zod.def;ne(r.innerType,e,o);let a=e.seen.get(t);a.ref=r.innerType};function qt(t){return!!t._zod}function lt(t,e){return qt(t)?wn(t,e):t.safeParse(e)}function Ao(t){if(!t)return;let e;if(qt(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function gh(t){if(qt(t)){let a=t._zod?.def;if(a){if(a.value!==void 0)return a.value;if(Array.isArray(a.values)&&a.values.length>0)return a.values[0]}}let n=t._def;if(n){if(n.value!==void 0)return n.value;if(Array.isArray(n.values)&&n.values.length>0)return n.values[0]}let o=t.value;if(o!==void 0)return o}var _n={};Yi(_n,{ZodISODate:()=>yh,ZodISODateTime:()=>wh,ZodISODuration:()=>kh,ZodISOTime:()=>bh,date:()=>za,datetime:()=>Ia,duration:()=>Ca,time:()=>Ta});var wh=g("ZodISODateTime",(t,e)=>{zc.init(t,e),X.init(t,e)});function Ia(t){return Au(wh,t)}var yh=g("ZodISODate",(t,e)=>{Tc.init(t,e),X.init(t,e)});function za(t){return ju(yh,t)}var bh=g("ZodISOTime",(t,e)=>{Cc.init(t,e),X.init(t,e)});function Ta(t){return Du(bh,t)}var kh=g("ZodISODuration",(t,e)=>{$c.init(t,e),X.init(t,e)});function Ca(t){return Ou(kh,t)}var ug=(t,e)=>{bo.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>cl(t,n)},flatten:{value:n=>ll(t,n)},addIssue:{value:n=>{t.issues.push(n),t.message=JSON.stringify(t.issues,jt,2)}},addIssues:{value:n=>{t.issues.push(...n),t.message=JSON.stringify(t.issues,jt,2)}},isEmpty:{get(){return t.issues.length===0}}})};var Te=g("ZodError",ug,{Parent:Error});var vh=ko(Te),xh=vo(Te),Sh=gn(Te),_h=yn(Te),Ih=ul(Te),zh=hl(Te),Th=dl(Te),Ch=pl(Te),$h=ml(Te),Ph=fl(Te),Eh=gl(Te),Rh=wl(Te);var Ah=new WeakMap;function In(t,e,n){let o=Object.getPrototypeOf(t),r=Ah.get(o);if(r||(r=new Set,Ah.set(o,r)),!r.has(e)){r.add(e);for(let a in n){let s=n[a];Object.defineProperty(o,a,{configurable:!0,enumerable:!1,get(){let i=s.bind(this);return Object.defineProperty(this,a,{configurable:!0,writable:!0,enumerable:!0,value:i}),i},set(i){Object.defineProperty(this,a,{configurable:!0,writable:!0,enumerable:!0,value:i})}})}}}var te=g("ZodType",(t,e)=>(G.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:xn(t,"input"),output:xn(t,"output")}}),t.toJSONSchema=Gu(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.parse=(n,o)=>vh(t,n,o,{callee:t.parse}),t.safeParse=(n,o)=>Sh(t,n,o),t.parseAsync=async(n,o)=>xh(t,n,o,{callee:t.parseAsync}),t.safeParseAsync=async(n,o)=>_h(t,n,o),t.spa=t.safeParseAsync,t.encode=(n,o)=>Ih(t,n,o),t.decode=(n,o)=>zh(t,n,o),t.encodeAsync=async(n,o)=>Th(t,n,o),t.decodeAsync=async(n,o)=>Ch(t,n,o),t.safeEncode=(n,o)=>$h(t,n,o),t.safeDecode=(n,o)=>Ph(t,n,o),t.safeEncodeAsync=async(n,o)=>Eh(t,n,o),t.safeDecodeAsync=async(n,o)=>Rh(t,n,o),In(t,"ZodType",{check(...n){let o=this.def;return this.clone(q.mergeDefs(o,{checks:[...o.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,o){return qe(this,n,o)},brand(){return this},register(n,o){return n.add(this,o),this},refine(n,o){return this.check(ew(n,o))},superRefine(n,o){return this.check(tw(n,o))},overwrite(n){return this.check(it(n))},optional(){return ee(this)},exactOptional(){return Zg(this)},nullable(){return Nh(this)},nullish(){return ee(Nh(this))},nonoptional(n){return Hg(this,n)},array(){return O(this)},or(n){return J([this,n])},and(n){return Do(this,n)},transform(n){return qh(this,Uh(n))},default(n){return Wg(this,n)},prefault(n){return Gg(this,n)},catch(n){return Kg(this,n)},pipe(n){return qh(this,n)},readonly(){return Qg(this)},describe(n){let o=this.clone();return kt.add(o,{description:n}),o},meta(...n){if(n.length===0)return kt.get(this);let o=this.clone();return kt.add(o,n[0]),o},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(n){return n(this)}}),Object.defineProperty(t,"description",{get(){return kt.get(t)?.description},configurable:!0}),t)),Mh=g("_ZodString",(t,e)=>{To.init(t,e),te.init(t,e),t._zod.processJSONSchema=(o,r,a)=>Hu(t,o,r,a);let n=t._zod.bag;t.format=n.format??null,t.minLength=n.minimum??null,t.maxLength=n.maximum??null,In(t,"_ZodString",{regex(...o){return this.check(ua(...o))},includes(...o){return this.check(pa(...o))},startsWith(...o){return this.check(ma(...o))},endsWith(...o){return this.check(fa(...o))},min(...o){return this.check(Nt(...o))},max(...o){return this.check(Eo(...o))},length(...o){return this.check(Ro(...o))},nonempty(...o){return this.check(Nt(1,...o))},lowercase(o){return this.check(ha(o))},uppercase(o){return this.check(da(o))},trim(){return this.check(wa())},normalize(...o){return this.check(ga(...o))},toLowerCase(){return this.check(ya())},toUpperCase(){return this.check(ba())},slugify(){return this.check(ka())}})}),dg=g("ZodString",(t,e)=>{To.init(t,e),Mh.init(t,e),t.email=n=>t.check(du(pg,n)),t.url=n=>t.check(wu(mg,n)),t.jwt=n=>t.check(Ru($g,n)),t.emoji=n=>t.check(yu(fg,n)),t.guid=n=>t.check(ca(jh,n)),t.uuid=n=>t.check(pu(jo,n)),t.uuidv4=n=>t.check(mu(jo,n)),t.uuidv6=n=>t.check(fu(jo,n)),t.uuidv7=n=>t.check(gu(jo,n)),t.nanoid=n=>t.check(bu(gg,n)),t.guid=n=>t.check(ca(jh,n)),t.cuid=n=>t.check(ku(wg,n)),t.cuid2=n=>t.check(vu(yg,n)),t.ulid=n=>t.check(xu(bg,n)),t.base64=n=>t.check($u(zg,n)),t.base64url=n=>t.check(Pu(Tg,n)),t.xid=n=>t.check(Su(kg,n)),t.ksuid=n=>t.check(_u(vg,n)),t.ipv4=n=>t.check(Iu(xg,n)),t.ipv6=n=>t.check(zu(Sg,n)),t.cidrv4=n=>t.check(Tu(_g,n)),t.cidrv6=n=>t.check(Cu(Ig,n)),t.e164=n=>t.check(Eu(Cg,n)),t.datetime=n=>t.check(Ia(n)),t.date=n=>t.check(za(n)),t.time=n=>t.check(Ta(n)),t.duration=n=>t.check(Ca(n))});function f(t){return hu(dg,t)}var X=g("ZodStringFormat",(t,e)=>{H.init(t,e),Mh.init(t,e)}),pg=g("ZodEmail",(t,e)=>{wc.init(t,e),X.init(t,e)});var jh=g("ZodGUID",(t,e)=>{fc.init(t,e),X.init(t,e)});var jo=g("ZodUUID",(t,e)=>{gc.init(t,e),X.init(t,e)});var mg=g("ZodURL",(t,e)=>{yc.init(t,e),X.init(t,e)});var fg=g("ZodEmoji",(t,e)=>{bc.init(t,e),X.init(t,e)});var gg=g("ZodNanoID",(t,e)=>{kc.init(t,e),X.init(t,e)});var wg=g("ZodCUID",(t,e)=>{vc.init(t,e),X.init(t,e)});var yg=g("ZodCUID2",(t,e)=>{xc.init(t,e),X.init(t,e)});var bg=g("ZodULID",(t,e)=>{Sc.init(t,e),X.init(t,e)});var kg=g("ZodXID",(t,e)=>{_c.init(t,e),X.init(t,e)});var vg=g("ZodKSUID",(t,e)=>{Ic.init(t,e),X.init(t,e)});var xg=g("ZodIPv4",(t,e)=>{Pc.init(t,e),X.init(t,e)});var Sg=g("ZodIPv6",(t,e)=>{Ec.init(t,e),X.init(t,e)});var _g=g("ZodCIDRv4",(t,e)=>{Rc.init(t,e),X.init(t,e)});var Ig=g("ZodCIDRv6",(t,e)=>{Ac.init(t,e),X.init(t,e)});var zg=g("ZodBase64",(t,e)=>{Dc.init(t,e),X.init(t,e)});var Tg=g("ZodBase64URL",(t,e)=>{Oc.init(t,e),X.init(t,e)});var Cg=g("ZodE164",(t,e)=>{Nc.init(t,e),X.init(t,e)});var $g=g("ZodJWT",(t,e)=>{qc.init(t,e),X.init(t,e)});var Lh=g("ZodNumber",(t,e)=>{ra.init(t,e),te.init(t,e),t._zod.processJSONSchema=(o,r,a)=>Ju(t,o,r,a),In(t,"ZodNumber",{gt(o,r){return this.check($o(o,r))},gte(o,r){return this.check(vn(o,r))},min(o,r){return this.check(vn(o,r))},lt(o,r){return this.check(Co(o,r))},lte(o,r){return this.check(kn(o,r))},max(o,r){return this.check(kn(o,r))},int(o){return this.check(Dh(o))},safe(o){return this.check(Dh(o))},positive(o){return this.check($o(0,o))},nonnegative(o){return this.check(vn(0,o))},negative(o){return this.check(Co(0,o))},nonpositive(o){return this.check(kn(0,o))},multipleOf(o,r){return this.check(Po(o,r))},step(o,r){return this.check(Po(o,r))},finite(){return this}});let n=t._zod.bag;t.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),t.isFinite=!0,t.format=n.format??null});function F(t){return Nu(Lh,t)}var Pg=g("ZodNumberFormat",(t,e)=>{Mc.init(t,e),Lh.init(t,e)});function Dh(t){return qu(Pg,t)}var Eg=g("ZodBoolean",(t,e)=>{Lc.init(t,e),te.init(t,e),t._zod.processJSONSchema=(n,o,r)=>Ku(t,n,o,r)});function ae(t){return Mu(Eg,t)}var Rg=g("ZodNull",(t,e)=>{Bc.init(t,e),te.init(t,e),t._zod.processJSONSchema=(n,o,r)=>Yu(t,n,o,r)});function Bh(t){return Lu(Rg,t)}var Ag=g("ZodUnknown",(t,e)=>{Zc.init(t,e),te.init(t,e),t._zod.processJSONSchema=(n,o,r)=>Qu(t,n,o,r)});function Q(){return Bu(Ag)}var jg=g("ZodNever",(t,e)=>{Fc.init(t,e),te.init(t,e),t._zod.processJSONSchema=(n,o,r)=>Xu(t,n,o,r)});function Dg(t){return Zu(jg,t)}var Og=g("ZodArray",(t,e)=>{Uc.init(t,e),te.init(t,e),t._zod.processJSONSchema=(n,o,r)=>rh(t,n,o,r),t.element=e.element,In(t,"ZodArray",{min(n,o){return this.check(Nt(n,o))},nonempty(n){return this.check(Nt(1,n))},max(n,o){return this.check(Eo(n,o))},length(n,o){return this.check(Ro(n,o))},unwrap(){return this.element}})});function O(t,e){return Fu(Og,t,e)}var Zh=g("ZodObject",(t,e)=>{Gc.init(t,e),te.init(t,e),t._zod.processJSONSchema=(n,o,r)=>ah(t,n,o,r),q.defineLazy(t,"shape",()=>e.shape),In(t,"ZodObject",{keyof(){return be(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:Q()})},loose(){return this.clone({...this._zod.def,catchall:Q()})},strict(){return this.clone({...this._zod.def,catchall:Dg()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return q.extend(this,n)},safeExtend(n){return q.safeExtend(this,n)},merge(n){return q.merge(this,n)},pick(n){return q.pick(this,n)},omit(n){return q.omit(this,n)},partial(...n){return q.partial(Wh,this,n[0])},required(...n){return q.required(Vh,this,n[0])}})});function v(t,e){let n={type:"object",shape:t??{},...q.normalizeParams(e)};return new Zh(n)}function ge(t,e){return new Zh({type:"object",shape:t,catchall:Q(),...q.normalizeParams(e)})}var Fh=g("ZodUnion",(t,e)=>{aa.init(t,e),te.init(t,e),t._zod.processJSONSchema=(n,o,r)=>sh(t,n,o,r),t.options=e.options});function J(t,e){return new Fh({type:"union",options:t,...q.normalizeParams(e)})}var Ng=g("ZodDiscriminatedUnion",(t,e)=>{Fh.init(t,e),Hc.init(t,e)});function Pa(t,e,n){return new Ng({type:"union",options:e,discriminator:t,...q.normalizeParams(n)})}var qg=g("ZodIntersection",(t,e)=>{Jc.init(t,e),te.init(t,e),t._zod.processJSONSchema=(n,o,r)=>ih(t,n,o,r)});function Do(t,e){return new qg({type:"intersection",left:t,right:e})}var Oh=g("ZodRecord",(t,e)=>{Kc.init(t,e),te.init(t,e),t._zod.processJSONSchema=(n,o,r)=>lh(t,n,o,r),t.keyType=e.keyType,t.valueType=e.valueType});function V(t,e,n){return!e||!e._zod?new Oh({type:"record",keyType:f(),valueType:t,...q.normalizeParams(e)}):new Oh({type:"record",keyType:t,valueType:e,...q.normalizeParams(n)})}var $a=g("ZodEnum",(t,e)=>{Yc.init(t,e),te.init(t,e),t._zod.processJSONSchema=(o,r,a)=>eh(t,o,r,a),t.enum=e.entries,t.options=Object.values(e.entries);let n=new Set(Object.keys(e.entries));t.extract=(o,r)=>{let a={};for(let s of o)if(n.has(s))a[s]=e.entries[s];else throw new Error(`Key ${s} not found in enum`);return new $a({...e,checks:[],...q.normalizeParams(r),entries:a})},t.exclude=(o,r)=>{let a={...e.entries};for(let s of o)if(n.has(s))delete a[s];else throw new Error(`Key ${s} not found in enum`);return new $a({...e,checks:[],...q.normalizeParams(r),entries:a})}});function be(t,e){let n=Array.isArray(t)?Object.fromEntries(t.map(o=>[o,o])):t;return new $a({type:"enum",entries:n,...q.normalizeParams(e)})}var Mg=g("ZodLiteral",(t,e)=>{Xc.init(t,e),te.init(t,e),t._zod.processJSONSchema=(n,o,r)=>th(t,n,o,r),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function I(t,e){return new Mg({type:"literal",values:Array.isArray(t)?t:[t],...q.normalizeParams(e)})}var Lg=g("ZodTransform",(t,e)=>{Qc.init(t,e),te.init(t,e),t._zod.processJSONSchema=(n,o,r)=>oh(t,n,o,r),t._zod.parse=(n,o)=>{if(o.direction==="backward")throw new Rt(t.constructor.name);n.addIssue=a=>{if(typeof a=="string")n.issues.push(q.issue(a,n.value,e));else{let s=a;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=t),n.issues.push(q.issue(s))}};let r=e.transform(n.value,n);return r instanceof Promise?r.then(a=>(n.value=a,n.fallback=!0,n)):(n.value=r,n.fallback=!0,n)}});function Uh(t){return new Lg({type:"transform",transform:t})}var Wh=g("ZodOptional",(t,e)=>{sa.init(t,e),te.init(t,e),t._zod.processJSONSchema=(n,o,r)=>_a(t,n,o,r),t.unwrap=()=>t._zod.def.innerType});function ee(t){return new Wh({type:"optional",innerType:t})}var Bg=g("ZodExactOptional",(t,e)=>{eu.init(t,e),te.init(t,e),t._zod.processJSONSchema=(n,o,r)=>_a(t,n,o,r),t.unwrap=()=>t._zod.def.innerType});function Zg(t){return new Bg({type:"optional",innerType:t})}var Fg=g("ZodNullable",(t,e)=>{tu.init(t,e),te.init(t,e),t._zod.processJSONSchema=(n,o,r)=>ch(t,n,o,r),t.unwrap=()=>t._zod.def.innerType});function Nh(t){return new Fg({type:"nullable",innerType:t})}var Ug=g("ZodDefault",(t,e)=>{nu.init(t,e),te.init(t,e),t._zod.processJSONSchema=(n,o,r)=>hh(t,n,o,r),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function Wg(t,e){return new Ug({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():q.shallowClone(e)}})}var Vg=g("ZodPrefault",(t,e)=>{ou.init(t,e),te.init(t,e),t._zod.processJSONSchema=(n,o,r)=>dh(t,n,o,r),t.unwrap=()=>t._zod.def.innerType});function Gg(t,e){return new Vg({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():q.shallowClone(e)}})}var Vh=g("ZodNonOptional",(t,e)=>{ru.init(t,e),te.init(t,e),t._zod.processJSONSchema=(n,o,r)=>uh(t,n,o,r),t.unwrap=()=>t._zod.def.innerType});function Hg(t,e){return new Vh({type:"nonoptional",innerType:t,...q.normalizeParams(e)})}var Jg=g("ZodCatch",(t,e)=>{au.init(t,e),te.init(t,e),t._zod.processJSONSchema=(n,o,r)=>ph(t,n,o,r),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function Kg(t,e){return new Jg({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var Gh=g("ZodPipe",(t,e)=>{ia.init(t,e),te.init(t,e),t._zod.processJSONSchema=(n,o,r)=>mh(t,n,o,r),t.in=e.in,t.out=e.out});function qh(t,e){return new Gh({type:"pipe",in:t,out:e})}var Yg=g("ZodPreprocess",(t,e)=>{Gh.init(t,e),su.init(t,e)}),Xg=g("ZodReadonly",(t,e)=>{iu.init(t,e),te.init(t,e),t._zod.processJSONSchema=(n,o,r)=>fh(t,n,o,r),t.unwrap=()=>t._zod.def.innerType});function Qg(t){return new Xg({type:"readonly",innerType:t})}var Hh=g("ZodCustom",(t,e)=>{lu.init(t,e),te.init(t,e),t._zod.processJSONSchema=(n,o,r)=>nh(t,n,o,r)});function Jh(t,e){return Uu(Hh,t??(()=>!0),e)}function ew(t,e={}){return Wu(Hh,t,e)}function tw(t,e){return Vu(t,e)}function Ea(t,e){return new Yg({type:"pipe",in:Uh(t),out:e})}ze(cu());var Aa="2025-11-25";var Kh=[Aa,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],ct="io.modelcontextprotocol/related-task",No="2.0",re=Jh(t=>t!==null&&(typeof t=="object"||typeof t=="function")),Yh=J([f(),F().int()]),Xh=f(),wz=ge({ttl:F().optional(),pollInterval:F().optional()}),nw=v({ttl:F().optional()}),ow=v({taskId:f()}),ja=ge({progressToken:Yh.optional(),[ct]:ow.optional()}),Ce=v({_meta:ja.optional()}),zn=Ce.extend({task:nw.optional()}),Qh=t=>zn.safeParse(t).success,ie=v({method:f(),params:Ce.loose().optional()}),Ee=v({_meta:ja.optional()}),Re=v({method:f(),params:Ee.loose().optional()}),le=ge({_meta:ja.optional()}),qo=J([f(),F().int()]),ed=v({jsonrpc:I(No),id:qo,...ie.shape}).strict(),Da=t=>ed.safeParse(t).success,td=v({jsonrpc:I(No),...Re.shape}).strict(),nd=t=>td.safeParse(t).success,Oa=v({jsonrpc:I(No),id:qo,result:le}).strict(),Tn=t=>Oa.safeParse(t).success;var D;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(D||(D={}));var Na=v({jsonrpc:I(No),id:qo.optional(),error:v({code:F().int(),message:f(),data:Q().optional()})}).strict();var od=t=>Na.safeParse(t).success;var rd=J([ed,td,Oa,Na]),yz=J([Oa,Na]),Mo=le.strict(),rw=Ee.extend({requestId:qo.optional(),reason:f().optional()}),Lo=Re.extend({method:I("notifications/cancelled"),params:rw}),aw=v({src:f(),mimeType:f().optional(),sizes:O(f()).optional(),theme:be(["light","dark"]).optional()}),Cn=v({icons:O(aw).optional()}),Mt=v({name:f(),title:f().optional()}),ad=Mt.extend({...Mt.shape,...Cn.shape,version:f(),websiteUrl:f().optional(),description:f().optional()}),sw=Do(v({applyDefaults:ae().optional()}),V(f(),Q())),iw=Ea(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Do(v({form:sw.optional(),url:re.optional()}),V(f(),Q()).optional())),lw=ge({list:re.optional(),cancel:re.optional(),requests:ge({sampling:ge({createMessage:re.optional()}).optional(),elicitation:ge({create:re.optional()}).optional()}).optional()}),cw=ge({list:re.optional(),cancel:re.optional(),requests:ge({tools:ge({call:re.optional()}).optional()}).optional()}),uw=v({experimental:V(f(),re).optional(),sampling:v({context:re.optional(),tools:re.optional()}).optional(),elicitation:iw.optional(),roots:v({listChanged:ae().optional()}).optional(),tasks:lw.optional(),extensions:V(f(),re).optional()}),hw=Ce.extend({protocolVersion:f(),capabilities:uw,clientInfo:ad}),qa=ie.extend({method:I("initialize"),params:hw});var dw=v({experimental:V(f(),re).optional(),logging:re.optional(),completions:re.optional(),prompts:v({listChanged:ae().optional()}).optional(),resources:v({subscribe:ae().optional(),listChanged:ae().optional()}).optional(),tools:v({listChanged:ae().optional()}).optional(),tasks:cw.optional(),extensions:V(f(),re).optional()}),pw=le.extend({protocolVersion:f(),capabilities:dw,serverInfo:ad,instructions:f().optional()}),Ma=Re.extend({method:I("notifications/initialized"),params:Ee.optional()});var Bo=ie.extend({method:I("ping"),params:Ce.optional()}),mw=v({progress:F(),total:ee(F()),message:ee(f())}),fw=v({...Ee.shape,...mw.shape,progressToken:Yh}),Zo=Re.extend({method:I("notifications/progress"),params:fw}),gw=Ce.extend({cursor:Xh.optional()}),$n=ie.extend({params:gw.optional()}),Pn=le.extend({nextCursor:Xh.optional()}),ww=be(["working","input_required","completed","failed","cancelled"]),En=v({taskId:f(),status:ww,ttl:J([F(),Bh()]),createdAt:f(),lastUpdatedAt:f(),pollInterval:ee(F()),statusMessage:ee(f())}),Lt=le.extend({task:En}),yw=Ee.merge(En),Rn=Re.extend({method:I("notifications/tasks/status"),params:yw}),Fo=ie.extend({method:I("tasks/get"),params:Ce.extend({taskId:f()})}),Uo=le.merge(En),Wo=ie.extend({method:I("tasks/result"),params:Ce.extend({taskId:f()})}),bz=le.loose(),Vo=$n.extend({method:I("tasks/list")}),Go=Pn.extend({tasks:O(En)}),Ho=ie.extend({method:I("tasks/cancel"),params:Ce.extend({taskId:f()})}),sd=le.merge(En),id=v({uri:f(),mimeType:ee(f()),_meta:V(f(),Q()).optional()}),ld=id.extend({text:f()}),La=f().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),cd=id.extend({blob:La}),An=be(["user","assistant"]),Bt=v({audience:O(An).optional(),priority:F().min(0).max(1).optional(),lastModified:_n.datetime({offset:!0}).optional()}),ud=v({...Mt.shape,...Cn.shape,uri:f(),description:ee(f()),mimeType:ee(f()),size:ee(F()),annotations:Bt.optional(),_meta:ee(ge({}))}),bw=v({...Mt.shape,...Cn.shape,uriTemplate:f(),description:ee(f()),mimeType:ee(f()),annotations:Bt.optional(),_meta:ee(ge({}))}),Ba=$n.extend({method:I("resources/list")}),kw=Pn.extend({resources:O(ud)}),vw=$n.extend({method:I("resources/templates/list")}),xw=Pn.extend({resourceTemplates:O(bw)}),Za=Ce.extend({uri:f()}),Sw=Za,Fa=ie.extend({method:I("resources/read"),params:Sw}),_w=le.extend({contents:O(J([ld,cd]))}),Iw=Re.extend({method:I("notifications/resources/list_changed"),params:Ee.optional()}),zw=Za,Tw=ie.extend({method:I("resources/subscribe"),params:zw}),Cw=Za,$w=ie.extend({method:I("resources/unsubscribe"),params:Cw}),Pw=Ee.extend({uri:f()}),Ew=Re.extend({method:I("notifications/resources/updated"),params:Pw}),Rw=v({name:f(),description:ee(f()),required:ee(ae())}),Aw=v({...Mt.shape,...Cn.shape,description:ee(f()),arguments:ee(O(Rw)),_meta:ee(ge({}))}),jw=$n.extend({method:I("prompts/list")}),Dw=Pn.extend({prompts:O(Aw)}),Ow=Ce.extend({name:f(),arguments:V(f(),f()).optional()}),Nw=ie.extend({method:I("prompts/get"),params:Ow}),Ua=v({type:I("text"),text:f(),annotations:Bt.optional(),_meta:V(f(),Q()).optional()}),Wa=v({type:I("image"),data:La,mimeType:f(),annotations:Bt.optional(),_meta:V(f(),Q()).optional()}),Va=v({type:I("audio"),data:La,mimeType:f(),annotations:Bt.optional(),_meta:V(f(),Q()).optional()}),qw=v({type:I("tool_use"),name:f(),id:f(),input:V(f(),Q()),_meta:V(f(),Q()).optional()}),Mw=v({type:I("resource"),resource:J([ld,cd]),annotations:Bt.optional(),_meta:V(f(),Q()).optional()}),Lw=ud.extend({type:I("resource_link")}),Ga=J([Ua,Wa,Va,Lw,Mw]),Bw=v({role:An,content:Ga}),Zw=le.extend({description:f().optional(),messages:O(Bw)}),Fw=Re.extend({method:I("notifications/prompts/list_changed"),params:Ee.optional()}),Uw=v({title:f().optional(),readOnlyHint:ae().optional(),destructiveHint:ae().optional(),idempotentHint:ae().optional(),openWorldHint:ae().optional()}),Ww=v({taskSupport:be(["required","optional","forbidden"]).optional()}),hd=v({...Mt.shape,...Cn.shape,description:f().optional(),inputSchema:v({type:I("object"),properties:V(f(),re).optional(),required:O(f()).optional()}).catchall(Q()),outputSchema:v({type:I("object"),properties:V(f(),re).optional(),required:O(f()).optional()}).catchall(Q()).optional(),annotations:Uw.optional(),execution:Ww.optional(),_meta:V(f(),Q()).optional()}),Ha=$n.extend({method:I("tools/list")}),Vw=Pn.extend({tools:O(hd)}),Jo=le.extend({content:O(Ga).default([]),structuredContent:V(f(),Q()).optional(),isError:ae().optional()}),kz=Jo.or(le.extend({toolResult:Q()})),Gw=zn.extend({name:f(),arguments:V(f(),Q()).optional()}),jn=ie.extend({method:I("tools/call"),params:Gw}),Hw=Re.extend({method:I("notifications/tools/list_changed"),params:Ee.optional()}),vz=v({autoRefresh:ae().default(!0),debounceMs:F().int().nonnegative().default(300)}),Dn=be(["debug","info","notice","warning","error","critical","alert","emergency"]),Jw=Ce.extend({level:Dn}),Ja=ie.extend({method:I("logging/setLevel"),params:Jw}),Kw=Ee.extend({level:Dn,logger:f().optional(),data:Q()}),Yw=Re.extend({method:I("notifications/message"),params:Kw}),Xw=v({name:f().optional()}),Qw=v({hints:O(Xw).optional(),costPriority:F().min(0).max(1).optional(),speedPriority:F().min(0).max(1).optional(),intelligencePriority:F().min(0).max(1).optional()}),ey=v({mode:be(["auto","required","none"]).optional()}),ty=v({type:I("tool_result"),toolUseId:f().describe("The unique identifier for the corresponding tool call."),content:O(Ga).default([]),structuredContent:v({}).loose().optional(),isError:ae().optional(),_meta:V(f(),Q()).optional()}),ny=Pa("type",[Ua,Wa,Va]),Oo=Pa("type",[Ua,Wa,Va,qw,ty]),oy=v({role:An,content:J([Oo,O(Oo)]),_meta:V(f(),Q()).optional()}),ry=zn.extend({messages:O(oy),modelPreferences:Qw.optional(),systemPrompt:f().optional(),includeContext:be(["none","thisServer","allServers"]).optional(),temperature:F().optional(),maxTokens:F().int(),stopSequences:O(f()).optional(),metadata:re.optional(),tools:O(hd).optional(),toolChoice:ey.optional()}),ay=ie.extend({method:I("sampling/createMessage"),params:ry}),On=le.extend({model:f(),stopReason:ee(be(["endTurn","stopSequence","maxTokens"]).or(f())),role:An,content:ny}),Ka=le.extend({model:f(),stopReason:ee(be(["endTurn","stopSequence","maxTokens","toolUse"]).or(f())),role:An,content:J([Oo,O(Oo)])}),sy=v({type:I("boolean"),title:f().optional(),description:f().optional(),default:ae().optional()}),iy=v({type:I("string"),title:f().optional(),description:f().optional(),minLength:F().optional(),maxLength:F().optional(),format:be(["email","uri","date","date-time"]).optional(),default:f().optional()}),ly=v({type:be(["number","integer"]),title:f().optional(),description:f().optional(),minimum:F().optional(),maximum:F().optional(),default:F().optional()}),cy=v({type:I("string"),title:f().optional(),description:f().optional(),enum:O(f()),default:f().optional()}),uy=v({type:I("string"),title:f().optional(),description:f().optional(),oneOf:O(v({const:f(),title:f()})),default:f().optional()}),hy=v({type:I("string"),title:f().optional(),description:f().optional(),enum:O(f()),enumNames:O(f()).optional(),default:f().optional()}),dy=J([cy,uy]),py=v({type:I("array"),title:f().optional(),description:f().optional(),minItems:F().optional(),maxItems:F().optional(),items:v({type:I("string"),enum:O(f())}),default:O(f()).optional()}),my=v({type:I("array"),title:f().optional(),description:f().optional(),minItems:F().optional(),maxItems:F().optional(),items:v({anyOf:O(v({const:f(),title:f()}))}),default:O(f()).optional()}),fy=J([py,my]),gy=J([hy,dy,fy]),wy=J([gy,sy,iy,ly]),yy=zn.extend({mode:I("form").optional(),message:f(),requestedSchema:v({type:I("object"),properties:V(f(),wy),required:O(f()).optional()})}),by=zn.extend({mode:I("url"),message:f(),elicitationId:f(),url:f().url()}),ky=J([yy,by]),vy=ie.extend({method:I("elicitation/create"),params:ky}),xy=Ee.extend({elicitationId:f()}),Sy=Re.extend({method:I("notifications/elicitation/complete"),params:xy}),Zt=le.extend({action:be(["accept","decline","cancel"]),content:Ea(t=>t===null?void 0:t,V(f(),J([f(),F(),ae(),O(f())])).optional())}),_y=v({type:I("ref/resource"),uri:f()});var Iy=v({type:I("ref/prompt"),name:f()}),zy=Ce.extend({ref:J([Iy,_y]),argument:v({name:f(),value:f()}),context:v({arguments:V(f(),f()).optional()}).optional()}),Ty=ie.extend({method:I("completion/complete"),params:zy});var Cy=le.extend({completion:ge({values:O(f()).max(100),total:ee(F().int()),hasMore:ee(ae())})}),$y=v({uri:f().startsWith("file://"),name:f().optional(),_meta:V(f(),Q()).optional()}),Py=ie.extend({method:I("roots/list"),params:Ce.optional()}),Ya=le.extend({roots:O($y)}),Ey=Re.extend({method:I("notifications/roots/list_changed"),params:Ee.optional()}),xz=J([Bo,qa,Ty,Ja,Nw,jw,Ba,vw,Fa,Tw,$w,jn,Ha,Fo,Wo,Vo,Ho]),Sz=J([Lo,Zo,Ma,Ey,Rn]),_z=J([Mo,On,Ka,Zt,Ya,Uo,Go,Lt]),Iz=J([Bo,ay,vy,Py,Fo,Wo,Vo,Ho]),zz=J([Lo,Zo,Yw,Ew,Iw,Hw,Fw,Rn,Sy]),Tz=J([Mo,pw,Cy,Zw,Dw,kw,xw,_w,Jo,Vw,Uo,Go,Lt]),P=class t extends Error{constructor(e,n,o){super(`MCP error ${e}: ${n}`),this.code=e,this.data=o,this.name="McpError"}static fromError(e,n,o){if(e===D.UrlElicitationRequired&&o){let r=o;if(r.elicitations)return new Ra(r.elicitations,n)}return new t(e,n,o)}},Ra=class extends P{constructor(e,n=`URL elicitation${e.length>1?"s":""} required`){super(D.UrlElicitationRequired,n,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function ut(t){return t==="completed"||t==="failed"||t==="cancelled"}var sT=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Xa(t){let n=Ao(t)?.method;if(!n)throw new Error("Schema is missing a method literal");let o=gh(n);if(typeof o!="string")throw new Error("Schema method literal must be a string");return o}function Qa(t,e){let n=lt(t,e);if(!n.success)throw n.error;return n.data}var Ny=6e4,Ko=class{constructor(e){this._options=e,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(Lo,n=>{this._oncancel(n)}),this.setNotificationHandler(Zo,n=>{this._onprogress(n)}),this.setRequestHandler(Bo,n=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Fo,async(n,o)=>{let r=await this._taskStore.getTask(n.params.taskId,o.sessionId);if(!r)throw new P(D.InvalidParams,"Failed to retrieve task: Task not found");return{...r}}),this.setRequestHandler(Wo,async(n,o)=>{let r=async()=>{let a=n.params.taskId;if(this._taskMessageQueue){let i;for(;i=await this._taskMessageQueue.dequeue(a,o.sessionId);){if(i.type==="response"||i.type==="error"){let l=i.message,c=l.id,u=this._requestResolvers.get(c);if(u)if(this._requestResolvers.delete(c),i.type==="response")u(l);else{let h=l,d=new P(h.error.code,h.error.message,h.error.data);u(d)}else{let h=i.type==="response"?"Response":"Error";this._onerror(new Error(`${h} handler missing for request ${c}`))}continue}await this._transport?.send(i.message,{relatedRequestId:o.requestId})}}let s=await this._taskStore.getTask(a,o.sessionId);if(!s)throw new P(D.InvalidParams,`Task not found: ${a}`);if(!ut(s.status))return await this._waitForTaskUpdate(a,o.signal),await r();if(ut(s.status)){let i=await this._taskStore.getTaskResult(a,o.sessionId);return this._clearTaskQueue(a),{...i,_meta:{...i._meta,[ct]:{taskId:a}}}}return await r()};return await r()}),this.setRequestHandler(Vo,async(n,o)=>{try{let{tasks:r,nextCursor:a}=await this._taskStore.listTasks(n.params?.cursor,o.sessionId);return{tasks:r,nextCursor:a,_meta:{}}}catch(r){throw new P(D.InvalidParams,`Failed to list tasks: ${r instanceof Error?r.message:String(r)}`)}}),this.setRequestHandler(Ho,async(n,o)=>{try{let r=await this._taskStore.getTask(n.params.taskId,o.sessionId);if(!r)throw new P(D.InvalidParams,`Task not found: ${n.params.taskId}`);if(ut(r.status))throw new P(D.InvalidParams,`Cannot cancel task in terminal status: ${r.status}`);await this._taskStore.updateTaskStatus(n.params.taskId,"cancelled","Client cancelled task execution.",o.sessionId),this._clearTaskQueue(n.params.taskId);let a=await this._taskStore.getTask(n.params.taskId,o.sessionId);if(!a)throw new P(D.InvalidParams,`Task not found after cancellation: ${n.params.taskId}`);return{_meta:{},...a}}catch(r){throw r instanceof P?r:new P(D.InvalidRequest,`Failed to cancel task: ${r instanceof Error?r.message:String(r)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,n,o,r,a=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(r,n),startTime:Date.now(),timeout:n,maxTotalTimeout:o,resetTimeoutOnProgress:a,onTimeout:r})}_resetTimeout(e){let n=this._timeoutInfo.get(e);if(!n)return!1;let o=Date.now()-n.startTime;if(n.maxTotalTimeout&&o>=n.maxTotalTimeout)throw this._timeoutInfo.delete(e),P.fromError(D.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:n.maxTotalTimeout,totalElapsed:o});return clearTimeout(n.timeoutId),n.timeoutId=setTimeout(n.onTimeout,n.timeout),!0}_cleanupTimeout(e){let n=this._timeoutInfo.get(e);n&&(clearTimeout(n.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let n=this.transport?.onclose;this._transport.onclose=()=>{n?.(),this._onclose()};let o=this.transport?.onerror;this._transport.onerror=a=>{o?.(a),this._onerror(a)};let r=this._transport?.onmessage;this._transport.onmessage=(a,s)=>{r?.(a,s),Tn(a)||od(a)?this._onresponse(a):Da(a)?this._onrequest(a,s):nd(a)?this._onnotification(a):this._onerror(new Error(`Unknown message type: ${JSON.stringify(a)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let o of this._timeoutInfo.values())clearTimeout(o.timeoutId);this._timeoutInfo.clear();for(let o of this._requestHandlerAbortControllers.values())o.abort();this._requestHandlerAbortControllers.clear();let n=P.fromError(D.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let o of e.values())o(n)}_onerror(e){this.onerror?.(e)}_onnotification(e){let n=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;n!==void 0&&Promise.resolve().then(()=>n(e)).catch(o=>this._onerror(new Error(`Uncaught error in notification handler: ${o}`)))}_onrequest(e,n){let o=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,r=this._transport,a=e.params?._meta?.[ct]?.taskId;if(o===void 0){let u={jsonrpc:"2.0",id:e.id,error:{code:D.MethodNotFound,message:"Method not found"}};a&&this._taskMessageQueue?this._enqueueTaskMessage(a,{type:"error",message:u,timestamp:Date.now()},r?.sessionId).catch(h=>this._onerror(new Error(`Failed to enqueue error response: ${h}`))):r?.send(u).catch(h=>this._onerror(new Error(`Failed to send an error response: ${h}`)));return}let s=new AbortController;this._requestHandlerAbortControllers.set(e.id,s);let i=Qh(e.params)?e.params.task:void 0,l=this._taskStore?this.requestTaskStore(e,r?.sessionId):void 0,c={signal:s.signal,sessionId:r?.sessionId,_meta:e.params?._meta,sendNotification:async u=>{if(s.signal.aborted)return;let h={relatedRequestId:e.id};a&&(h.relatedTask={taskId:a}),await this.notification(u,h)},sendRequest:async(u,h,d)=>{if(s.signal.aborted)throw new P(D.ConnectionClosed,"Request was cancelled");let p={...d,relatedRequestId:e.id};a&&!p.relatedTask&&(p.relatedTask={taskId:a});let m=p.relatedTask?.taskId??a;return m&&l&&await l.updateTaskStatus(m,"input_required"),await this.request(u,h,p)},authInfo:n?.authInfo,requestId:e.id,requestInfo:n?.requestInfo,taskId:a,taskStore:l,taskRequestedTtl:i?.ttl,closeSSEStream:n?.closeSSEStream,closeStandaloneSSEStream:n?.closeStandaloneSSEStream};Promise.resolve().then(()=>{i&&this.assertTaskHandlerCapability(e.method)}).then(()=>o(e,c)).then(async u=>{if(s.signal.aborted)return;let h={result:u,jsonrpc:"2.0",id:e.id};a&&this._taskMessageQueue?await this._enqueueTaskMessage(a,{type:"response",message:h,timestamp:Date.now()},r?.sessionId):await r?.send(h)},async u=>{if(s.signal.aborted)return;let h={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:D.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};a&&this._taskMessageQueue?await this._enqueueTaskMessage(a,{type:"error",message:h,timestamp:Date.now()},r?.sessionId):await r?.send(h)}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===s&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:n,...o}=e.params,r=Number(n),a=this._progressHandlers.get(r);if(!a){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let s=this._responseHandlers.get(r),i=this._timeoutInfo.get(r);if(i&&s&&i.resetTimeoutOnProgress)try{this._resetTimeout(r)}catch(l){this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),s(l);return}a(o)}_onresponse(e){let n=Number(e.id),o=this._requestResolvers.get(n);if(o){if(this._requestResolvers.delete(n),Tn(e))o(e);else{let s=new P(e.error.code,e.error.message,e.error.data);o(s)}return}let r=this._responseHandlers.get(n);if(r===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(n),this._cleanupTimeout(n);let a=!1;if(Tn(e)&&e.result&&typeof e.result=="object"){let s=e.result;if(s.task&&typeof s.task=="object"){let i=s.task;typeof i.taskId=="string"&&(a=!0,this._taskProgressTokens.set(i.taskId,n))}}if(a||this._progressHandlers.delete(n),Tn(e))r(e);else{let s=P.fromError(e.error.code,e.error.message,e.error.data);r(s)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,n,o){let{task:r}=o??{};if(!r){try{yield{type:"result",result:await this.request(e,n,o)}}catch(s){yield{type:"error",error:s instanceof P?s:new P(D.InternalError,String(s))}}return}let a;try{let s=await this.request(e,Lt,o);if(s.task)a=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new P(D.InternalError,"Task creation did not return a task");for(;;){let i=await this.getTask({taskId:a},o);if(yield{type:"taskStatus",task:i},ut(i.status)){i.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:a},n,o)}:i.status==="failed"?yield{type:"error",error:new P(D.InternalError,`Task ${a} failed`)}:i.status==="cancelled"&&(yield{type:"error",error:new P(D.InternalError,`Task ${a} was cancelled`)});return}if(i.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:a},n,o)};return}let l=i.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(c=>setTimeout(c,l)),o?.signal?.throwIfAborted()}}catch(s){yield{type:"error",error:s instanceof P?s:new P(D.InternalError,String(s))}}}request(e,n,o){let{relatedRequestId:r,resumptionToken:a,onresumptiontoken:s,task:i,relatedTask:l}=o??{};return new Promise((c,u)=>{let h=x=>{u(x)};if(!this._transport){h(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),i&&this.assertTaskCapability(e.method)}catch(x){h(x);return}o?.signal?.throwIfAborted();let d=this._requestMessageId++,p={...e,jsonrpc:"2.0",id:d};o?.onprogress&&(this._progressHandlers.set(d,o.onprogress),p.params={...e.params,_meta:{...e.params?._meta||{},progressToken:d}}),i&&(p.params={...p.params,task:i}),l&&(p.params={...p.params,_meta:{...p.params?._meta||{},[ct]:l}});let m=x=>{this._responseHandlers.delete(d),this._progressHandlers.delete(d),this._cleanupTimeout(d),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:d,reason:String(x)}},{relatedRequestId:r,resumptionToken:a,onresumptiontoken:s}).catch(T=>this._onerror(new Error(`Failed to send cancellation: ${T}`)));let S=x instanceof P?x:new P(D.RequestTimeout,String(x));u(S)};this._responseHandlers.set(d,x=>{if(!o?.signal?.aborted){if(x instanceof Error)return u(x);try{let S=lt(n,x.result);S.success?c(S.data):u(S.error)}catch(S){u(S)}}}),o?.signal?.addEventListener("abort",()=>{m(o?.signal?.reason)});let w=o?.timeout??Ny,y=()=>m(P.fromError(D.RequestTimeout,"Request timed out",{timeout:w}));this._setupTimeout(d,w,o?.maxTotalTimeout,y,o?.resetTimeoutOnProgress??!1);let b=l?.taskId;if(b){let x=S=>{let T=this._responseHandlers.get(d);T?T(S):this._onerror(new Error(`Response handler missing for side-channeled request ${d}`))};this._requestResolvers.set(d,x),this._enqueueTaskMessage(b,{type:"request",message:p,timestamp:Date.now()}).catch(S=>{this._cleanupTimeout(d),u(S)})}else this._transport.send(p,{relatedRequestId:r,resumptionToken:a,onresumptiontoken:s}).catch(x=>{this._cleanupTimeout(d),u(x)})})}async getTask(e,n){return this.request({method:"tasks/get",params:e},Uo,n)}async getTaskResult(e,n,o){return this.request({method:"tasks/result",params:e},n,o)}async listTasks(e,n){return this.request({method:"tasks/list",params:e},Go,n)}async cancelTask(e,n){return this.request({method:"tasks/cancel",params:e},sd,n)}async notification(e,n){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let o=n?.relatedTask?.taskId;if(o){let i={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[ct]:n.relatedTask}}};await this._enqueueTaskMessage(o,{type:"notification",message:i,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!n?.relatedRequestId&&!n?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let i={...e,jsonrpc:"2.0"};n?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[ct]:n.relatedTask}}}),this._transport?.send(i,n).catch(l=>this._onerror(l))});return}let s={...e,jsonrpc:"2.0"};n?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[ct]:n.relatedTask}}}),await this._transport.send(s,n)}setRequestHandler(e,n){let o=Xa(e);this.assertRequestHandlerCapability(o),this._requestHandlers.set(o,(r,a)=>{let s=Qa(e,r);return Promise.resolve(n(s,a))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,n){let o=Xa(e);this._notificationHandlers.set(o,r=>{let a=Qa(e,r);return Promise.resolve(n(a))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let n=this._taskProgressTokens.get(e);n!==void 0&&(this._progressHandlers.delete(n),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,n,o){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let r=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,n,o,r)}async _clearTaskQueue(e,n){if(this._taskMessageQueue){let o=await this._taskMessageQueue.dequeueAll(e,n);for(let r of o)if(r.type==="request"&&Da(r.message)){let a=r.message.id,s=this._requestResolvers.get(a);s?(s(new P(D.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(a)):this._onerror(new Error(`Resolver missing for request ${a} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,n){let o=this._options?.defaultTaskPollInterval??1e3;try{let r=await this._taskStore?.getTask(e);r?.pollInterval&&(o=r.pollInterval)}catch{}return new Promise((r,a)=>{if(n.aborted){a(new P(D.InvalidRequest,"Request cancelled"));return}let s=setTimeout(r,o);n.addEventListener("abort",()=>{clearTimeout(s),a(new P(D.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,n){let o=this._taskStore;if(!o)throw new Error("No task store configured");return{createTask:async r=>{if(!e)throw new Error("No request provided");return await o.createTask(r,e.id,{method:e.method,params:e.params},n)},getTask:async r=>{let a=await o.getTask(r,n);if(!a)throw new P(D.InvalidParams,"Failed to retrieve task: Task not found");return a},storeTaskResult:async(r,a,s)=>{await o.storeTaskResult(r,a,s,n);let i=await o.getTask(r,n);if(i){let l=Rn.parse({method:"notifications/tasks/status",params:i});await this.notification(l),ut(i.status)&&this._cleanupTaskProgressHandler(r)}},getTaskResult:r=>o.getTaskResult(r,n),updateTaskStatus:async(r,a,s)=>{let i=await o.getTask(r,n);if(!i)throw new P(D.InvalidParams,`Task "${r}" not found - it may have been cleaned up`);if(ut(i.status))throw new P(D.InvalidParams,`Cannot update task "${r}" from terminal status "${i.status}" to "${a}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await o.updateTaskStatus(r,a,s,n);let l=await o.getTask(r,n);if(l){let c=Rn.parse({method:"notifications/tasks/status",params:l});await this.notification(c),ut(l.status)&&this._cleanupTaskProgressHandler(r)}},listTasks:r=>o.listTasks(r,n)}}};function dd(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function pd(t,e){let n={...t};for(let o in e){let r=o,a=e[r];if(a===void 0)continue;let s=n[r];dd(s)&&dd(a)?n[r]={...s,...a}:n[r]=a}return n}var rf=Xi(Mi(),1),af=Xi(of(),1);function L_(){let t=new rf.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,af.default)(t),t}var Er=class{constructor(e){this._ajv=e??L_()}getValidator(e){let n="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return o=>n(o)?{valid:!0,data:o,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(n.errors)}}};var Rr=class{constructor(e){this._server=e}requestStream(e,n,o){return this._server.requestStream(e,n,o)}createMessageStream(e,n){let o=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!o?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let r=e.messages[e.messages.length-1],a=Array.isArray(r.content)?r.content:[r.content],s=a.some(u=>u.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,l=i?Array.isArray(i.content)?i.content:[i.content]:[],c=l.some(u=>u.type==="tool_use");if(s){if(a.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(l.filter(d=>d.type==="tool_use").map(d=>d.id)),h=new Set(a.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(u.size!==h.size||![...u].every(d=>h.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},On,n)}elicitInputStream(e,n){let o=this._server.getClientCapabilities(),r=e.mode??"form";switch(r){case"url":{if(!o?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!o?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let a=r==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:a},Zt,n)}async getTask(e,n){return this._server.getTask({taskId:e},n)}async getTaskResult(e,n,o){return this._server.getTaskResult({taskId:e},n,o)}async listTasks(e,n){return this._server.listTasks(e?{cursor:e}:void 0,n)}async cancelTask(e,n){return this._server.cancelTask({taskId:e},n)}};function sf(t,e,n){if(!t)throw new Error(`${n} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${n} does not support task creation for tools/call (required for ${e})`);break;default:break}}function lf(t,e,n){if(!t)throw new Error(`${n} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${n} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${n} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var Ar=class extends Ko{constructor(e,n){super(n),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Dn.options.map((o,r)=>[o,r])),this.isMessageIgnored=(o,r)=>{let a=this._loggingLevels.get(r);return a?this.LOG_LEVEL_SEVERITY.get(o)<this.LOG_LEVEL_SEVERITY.get(a):!1},this._capabilities=n?.capabilities??{},this._instructions=n?.instructions,this._jsonSchemaValidator=n?.jsonSchemaValidator??new Er,this.setRequestHandler(qa,o=>this._oninitialize(o)),this.setNotificationHandler(Ma,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Ja,async(o,r)=>{let a=r.sessionId||r.requestInfo?.headers["mcp-session-id"]||void 0,{level:s}=o.params,i=Dn.safeParse(s);return i.success&&this._loggingLevels.set(a,i.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Rr(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=pd(this._capabilities,e)}setRequestHandler(e,n){let r=Ao(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let a;if(qt(r)){let i=r;a=i._zod?.def?.value??i.value}else{let i=r;a=i._def?.value??i.value}if(typeof a!="string")throw new Error("Schema method literal must be a string");if(a==="tools/call"){let i=async(l,c)=>{let u=lt(jn,l);if(!u.success){let m=u.error instanceof Error?u.error.message:String(u.error);throw new P(D.InvalidParams,`Invalid tools/call request: ${m}`)}let{params:h}=u.data,d=await Promise.resolve(n(l,c));if(h.task){let m=lt(Lt,d);if(!m.success){let w=m.error instanceof Error?m.error.message:String(m.error);throw new P(D.InvalidParams,`Invalid task creation result: ${w}`)}return m.data}let p=lt(Jo,d);if(!p.success){let m=p.error instanceof Error?p.error.message:String(p.error);throw new P(D.InvalidParams,`Invalid tools/call result: ${m}`)}return p.data};return super.setRequestHandler(e,i)}return super.setRequestHandler(e,n)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){lf(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&sf(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let n=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Kh.includes(n)?n:Aa,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"},Mo)}async createMessage(e,n){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let o=e.messages[e.messages.length-1],r=Array.isArray(o.content)?o.content:[o.content],a=r.some(c=>c.type==="tool_result"),s=e.messages.length>1?e.messages[e.messages.length-2]:void 0,i=s?Array.isArray(s.content)?s.content:[s.content]:[],l=i.some(c=>c.type==="tool_use");if(a){if(r.some(c=>c.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!l)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(l){let c=new Set(i.filter(h=>h.type==="tool_use").map(h=>h.id)),u=new Set(r.filter(h=>h.type==="tool_result").map(h=>h.toolUseId));if(c.size!==u.size||![...c].every(h=>u.has(h)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},Ka,n):this.request({method:"sampling/createMessage",params:e},On,n)}async elicitInput(e,n){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let r=e;return this.request({method:"elicitation/create",params:r},Zt,n)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let r=e.mode==="form"?e:{...e,mode:"form"},a=await this.request({method:"elicitation/create",params:r},Zt,n);if(a.action==="accept"&&a.content&&r.requestedSchema)try{let i=this._jsonSchemaValidator.getValidator(r.requestedSchema)(a.content);if(!i.valid)throw new P(D.InvalidParams,`Elicitation response content does not match requested schema: ${i.errorMessage}`)}catch(s){throw s instanceof P?s:new P(D.InternalError,`Error validating elicitation response: ${s instanceof Error?s.message:String(s)}`)}return a}}}createElicitationCompletionNotifier(e,n){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},n)}async listRoots(e,n){return this.request({method:"roots/list",params:e},Ya,n)}async sendLoggingMessage(e,n){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,n))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}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"})}};import uf from"node:process";var jr=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
73
+ `);if(e===-1)return null;let n=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),B_(n)}clear(){this._buffer=void 0}};function B_(t){return rd.parse(JSON.parse(t))}function cf(t){return JSON.stringify(t)+`
74
+ `}var Dr=class{constructor(e=uf.stdin,n=uf.stdout){this._stdin=e,this._stdout=n,this._readBuffer=new jr,this._started=!1,this._ondata=o=>{this._readBuffer.append(o),this.processReadBuffer()},this._onerror=o=>{this.onerror?.(o)}}async start(){if(this._started)throw new 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(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){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(e){return new Promise(n=>{let o=cf(e);this._stdout.write(o)?n():this._stdout.once("drain",n)})}};var _e={general:`
75
75
  # ZeroWork RPA Architecture
76
76
 
77
77
  ZeroWork is a desktop-based RPA platform to mimic human web interactions.
@@ -309,7 +309,7 @@ SUMMARY:
309
309
  - Code Expression: Single-line JS. Requires Agent >= 1.1.72.
310
310
  - Code Block: Multi-line JS with imports. Requires Agent >= 1.1.72.
311
311
  - Spintax {opt1|opt2|opt3}: Randomizes text. Any agent version.
312
- `,visual_insights:'\n# ZeroWork Visual Insights Master Document\n\nThis document compiles granular UI and configuration insights extracted directly from screenshots of the official ZeroWork documentation.\n\n## Batch 1: Abort Run to Auto Continue\n\n### 1. Abort Run (`Abort Run.png`)\n- **Building Block Name**: `Abort Run`\n- **UI / Icon**: Pink background block with an `(X)` icon inside.\n- **Canvas Branching Example**: Shows a workflow starting with `If a new post...` branching into two paths:\n - Top path: `...exists` -> `Type comment` -> `Post comment`.\n - Bottom path: `...does not exist` -> `Abort Run`.\n- **Function**: Instantly terminates the TaskBot run immediately when reached. Useful for stopping execution when critical data or conditions are missing.\n\n### 2. Actions = & \u2260 (`Actions And.png`)\n- **Condition Type**: `Actions = & \u2260` (Equal / Not Equal).\n- **Context**: Used in `Start Condition and Set Condition` building blocks.\n- **Use Cases**:\n - Break loop on condition that status request is unsuccessful (e.g. check if status response equals or does not equal 200).\n - Set profile visit status to "visited" and avoid visiting the same profile links by checking if status equals "visited".\n - Remove disqualified leads if lead qualification status does not equal "qualified".\n\n### 3. Actions <, \u2264, >, \u2265 (`Actions Less Than Greater Than.png`)\n- **Condition Type**: `Actions <, \u2264, >, \u2265` (Comparison operators).\n- **Context**: Used in `Start Condition and Set Condition`.\n- **Function**: Compares numeric values (e.g., number of followers, prices, degrees, etc.).\n- **Note**: For comparing calendar dates, users should use `Before (Date) & After (Date)`.\n\n### 4. Addressing Siblings (`Addressing Siblings.png`)\n- **Advanced CSS Selector Concept**: Addressing sibling elements in the DOM hierarchy.\n- **Syntax**:\n - Tilde `~`: Loose sibling (matches any following sibling element at that hierarchy level).\n - Plus `+`: Exact sibling (matches the immediately next sibling element at that hierarchy level).\n- **Context**: Used when elements are on the same level in the DOM hierarchy but cannot or should not be addressed as a list (e.g., incremental CSS selectors).\n\n### 5. After Repeat (`After Repeat.png`)\n- **Building Block Name**: `After Repeat`\n- **UI / Canvas Placement**: Must always be placed immediately after a `Start Repeat` building block.\n- **Example 1 (Email Notification)**: `Start Repeat` loops through actions. `After Repeat` is attached right after `Start Repeat`, linking to a `Send Notification` block (`@` icon) to send an email once all loop iterations complete.\n- **Example 2 (Chaining Multiple Loops)**: Creates a "workflow in workflow" effect. Shows two separate loop clusters in the same canvas:\n - Cluster 1: "Collect leads" (`Start Repeat` -> `Save Lists` -> `After Repeat`).\n - Cluster 2: "Iterate over collected leads" (`Start Repeat` -> `Open Link` -> `Enrich Existing Data`).\n - `After Repeat` bridges the end of Cluster 1 directly into the start of Cluster 2.\n\n### 6. APIs: Send HTTP Request (`Apis Send Http Request.png`)\n- **Building Block Name**: `Send HTTP Request`\n- **Modal Configuration UI**:\n - **Request Type Dropdown**: `POST`, `GET`, `PUT`, `PATCH`, `DELETE`.\n - **URL Field**: Input URL (e.g. `https://api.openai.com/v1/completions`). Supports dynamic table references like `{table_name:column_name}`. Note: ensure trailing slashes are correctly handled as required by the specific API.\n - **Tabs**: `HEADERS`, `REQUEST BODY`, `SAVE RESPONSE`.\n - **HEADERS Tab**: Key-value pairs (e.g., `Content-Type`: `application/json`, `Authorization`: `Bearer sk-...`).\n - **REQUEST BODY Tab**: JSON body input area. Supports table/variable references. Note: invalid JSON body errors often occur if double quotes are not escaped or if dynamic data contains unescaped double quotes (recommends using `Replace text` regex to clean data).\n - **SAVE RESPONSE Tab**:\n - `Save response body (optional)`: Dropdown selecting table/variable (e.g. `Variables`).\n - `Nested record path (optional)`: Field to specify dot/bracket notation for nested JSON responses (e.g., `choices[0][\'text\']`).\n - `Save response status code (optional)`: Dropdown to select table/variable (e.g. `Variables`, variable `status`). Allows checking for 200, 400, 500 status codes to handle errors or break loops.\n\n### 7. Apply Regex (`Apply Regex.png`)\n- **Building Block Name**: `Apply Regex`\n- **Modal Configuration UI**:\n - **Enter expression between slashes**: e.g., `/([a-zA-Z0-9-_]+)/g` or `/\\d+/`.\n - **Select method Dropdown**:\n - `Replace text`: Replaces matched regex with a replacement string.\n - `Extract matches`: Extracts matching substrings.\n - `Check if pattern matches`: Returns `true` or `false`.\n - **Text to apply the regex to Field**: Input text or dynamic reference (e.g. `{id: 89197, name: Google Sheets link}`).\n - **Save result to**: Dropdown selecting `Variables` or a table.\n - **Select variable Dropdown**: Selecting the destination variable (e.g. `Google Sheets ID`).\n- **Flags**: Supports `g` (global), `i` (case-insensitive), `m` (multiline). Example: `/pattern/gi`.\n- **Error Handling**: If input text is empty, TaskBot continues running without action. If regex is invalid, TaskBot generates an error report and stops the run/loop.\n\n### 8. Ask ChatGPT (`Ask Chatgpt.png`)\n- **Building Block Name**: `Ask ChatGPT`\n- **Modal Configuration UI**:\n - **Model Dropdown**: e.g., `ChatGPT 3.5`, `ChatGPT 4`.\n - **Enter prompt Field**: Text area for prompt. Supports dynamic references.\n - **Save ChatGPT answer to Dropdown**: Select `Variables` or table.\n - **Select variable Dropdown**: Destination variable (e.g., `Message to send`).\n - **API Key Warning**: If API key is missing, shows a warning banner with an `Add here` link opening Settings -> Integrations tab to enter the OpenAI API key.\n - **Settings Gear Icon (Behavior on error)**:\n - `Stop (loop) run and create error report` (default).\n - `Continue run and record error code`: Dropdown `Save error code to` (e.g. `Variables`, select variable `OpenAI error`).\n- **Error Handling & Token Limits**:\n - Captures 400, 429, etc., or `length` error if token limit is exceeded.\n - Explains truncation issues and recommends using `Format Data` -> `Shorten Content Length` building block to truncate scraped text before sending to ChatGPT to save tokens and prevent `length` errors.\n - Token consumption is logged in TaskBot run reports.\n\n### 9. Auto-Align (`Auto Align.png`)\n- **Feature**: Workflow canvas formatting toolbar.\n- **UI Controls**: Toolbar buttons `[+]`, `[-]`, `[lock]`, `[Align Left-to-Right / Top-to-Bottom icon]`, `[center]`.\n- **Function**: Reorganizes messy, scattered building blocks into a neat, structured layout automatically, either horizontally (left to right) or vertically (top to bottom).\n\n### 10. Auto-Continue from Last Row or Element (`Auto Continue From Last Row Or Element.png`)\n- **Feature**: Resumption capability within `Start Repeat` building blocks.\n- **Modal Configuration UI (`Start Repeat`)**:\n - **Select loop type**: `Standard` (add new rows or repeat actions) vs `Dynamic` (process table rows one by one).\n - **Dynamic Loop UI**:\n - `Table to loop through`: Dropdown selecting table (e.g., `LinkedIn Profiles`).\n - `Newest rows first (reverse order)` checkbox.\n - `Repetition limit (optional)`: e.g., `100`.\n - `Start from (optional)`: row number, e.g., `1`.\n - `Auto-continue from last row` checkbox. Shows badge `Next run starts from 1`.\n - **Standard Loop UI**:\n - `Number of repetitions`: e.g., `100`. `Continue until no element is found` toggle.\n - `Start from (optional)`: element number, e.g., `1`.\n - `Auto-continue from last element` checkbox. Shows badge `Next run starts from 1`.\n- **Execution Logic**:\n - Tracks the last processed row/element across separate bot runs.\n - Example: If repetition limit is 100, Run 1 processes rows 1-100. Run 2 automatically starts at row 101 and processes 101-200. Run 3 starts at 201, etc., until table rows or list elements are exhausted.\n\n## Batch 2: Auto Scroll to Check Web Element Identifies\n\n### 11. Auto-Scroll (`Auto Scroll.png`)\n- **Status**: Documentation page marked as "This page is upcoming. Stay tuned!".\n- **Context**: Navigational links indicate it is related to `Start Repeat` options (`Continue until No Element is Found` and `Auto-Continue from Last Row or Element`).\n\n### 12. Basic Concepts of Selectors (`Basic Concepts Of Selectors.png`)\n- **Core Concept**: Explains the anatomy of CSS Selectors using Wikipedia\'s search button as an example.\n- **Console Inspection**: Right-click element -> Inspect.\n- **Structure**: `tag[attribute=\'value\']` or multiple attributes `tag[attribute1=\'value1\'][attribute2=\'value2\']`.\n- **Example**: `<button class="pure-button pure-button-primary-progressive" type="submit">`\n - **Tag**: `button` (first word, marked purple in DevTools).\n - **Attributes**: `class`, `type` (marked brown).\n - **Values**: `pure-button pure-button-primary-progressive`, `submit` (blue).\n - **Resulting Selector**: `button[class=\'pure-button pure-button-primary-progressive\'][type=\'submit\']`. Note: no spaces between tag and brackets, values wrapped in quotes.\n\n### 13. Before (Date) & After (Date) (`Before Date And After Date.png`)\n- **Condition Type**: `Before (Date) & After (Date)`. Used in `Start Condition and Set Condition`.\n- **Function**: Compares calendar dates (checks if reference date is smaller/earlier or greater/later than comparison date).\n- **Modal Configuration UI**:\n - **Select comparison action Dropdown**: `After calendar date`, `Before calendar date`.\n - **Enter calendar date Field**: e.g., `07/10/2023`.\n - **Enter days shift (optional) Field**: Positive or negative integer (e.g., `3` or `-2`).\n - **Calendar date format Dropdown (Settings gear icon)**: e.g. `MM DD YYYY`, `DD MM YYYY`, `YYYY MM DD`. Essential to keep format consistent between comparison date and reference date to prevent errors.\n- **Days Shift Logic Examples**:\n - Comparison date `07/10/2023`, shift `3`: Effective comparison date becomes `07/13/2023`.\n - `After`: Met if reference date is 14th or later.\n - `Before`: Met if reference date is 12th or earlier.\n - Comparison date `07/10/2023`, shift `-2`: Effective comparison date becomes `07/08/2023`.\n - `After`: Met if reference date is 9th or later.\n - `Before`: Met if reference date is 7th or earlier.\n\n### 14. Break Repeat (`Break Repeat.png`)\n- **Building Block Name**: `Break Repeat`\n- **UI / Icon**: White block with a `[STOP]` octagon icon inside.\n- **Function**: Aborts the current loop iteration and exits the loop immediately when specific conditions are met.\n- **Example 1 (No More Search Results)**: Uses `Check Web Element` to detect text like "There are no search results anymore". If found (checkmark branch), routes to `Break Repeat` (`[STOP]`).\n- **Example 2 (API Error)**: Break loop if status request is unsuccessful (e.g. status != 200).\n- **Example 3 (Daily DM Limit)**: Break loop once a daily DM limit variable is reached.\n\n### 15. Bring Pages to Front (`Bring Pages To Front.png`)\n- **Setting Type**: Run Settings -> `Bring Pages to Front`.\n- **UI**: Accessed via TaskBot Settings gear icon (top right) -> `Run Behavior` section -> `Bring pages to front` toggle switch.\n- **Function**: When enabled, brings each newly active page (new tab or link opened in new tab) to the foreground of the desktop window.\n- **Behavior when Disabled**: TaskBot switches tabs silently in the background without stealing focus. (Note: macOS may still bring Chrome to front once at the very start of the run).\n- **Best Practice / FAQ**: Keep enabled while building or testing TaskBots to easily monitor pages during the run.\n\n### 16. Browser Alert (`Browser Alert.png`)\n- **Building Block Name**: `Browser Alert`\n- **UI / Icon**: Block with a chat bubble / exclamation point icon.\n- **Placement**: Placed immediately after an action (e.g., `Click Web Element`) that triggers a native browser dialog (prompt, confirm, alert, beforeunload).\n- **Modal Configuration UI**:\n - `Enter prompt text (optional)`: Text input area. Used only if the dialog is a `prompt` requiring user input. Ignored for alert, confirm, or beforeunload dialogs.\n- **Run Behavior**:\n - By default, ZeroWork TaskBot automatically dismisses (clicks Cancel on) native browser dialogs. Using `Browser Alert` forces TaskBot to **accept** (click OK on) the alert.\n - If no alert appears, TaskBot takes no action and proceeds seamlessly without interruption.\n\n### 17. Browser Context (`Browser Context.png`)\n- **Core Concept**: Comprehensive reference for `zw.browserContext` API used in `Custom Code` / `Advanced Custom Code` blocks.\n- **Key Methods & Options**:\n - `zw.browserContext.launch(options?: LaunchOptions)`: Launches browser and returns context.\n - `LaunchOptions`: `{ headless?: boolean; stickyProfile?: string | { name: string; isGlobal?: boolean }; maximize?: boolean; bypassDetection?: boolean; cookies?: Cookie[]; scripts?: Script[]; launchOptions?: LaunchOptions; contextOptions?: ContextOptions }`.\n - `headless`: Default `false`. Note: overrides sticky profile settings if explicitly set.\n - `stickyProfile`: Attaches a persistent profile. Can pass profile name or object. `isGlobal: true` shares profile across all TaskBots.\n - `maximize`: Default `true`. Overrides viewport settings.\n - `bypassDetection`: Default `true`. Hardens bot against anti-bot detection. Trade-off: disables some file upload buttons; large uploads (>50MB) and downloads are unsupported.\n - `cookies`: Array of `{ name, value, domain, path, expires, httpOnly, secure, sameSite }`. Tip: avoid adding cookies in code if they supply an active session.\n - `scripts`: Array of `{ path?: string; content?: string }`. Injects JS scripts into every page.\n - `launchOptions` / `contextOptions`: Custom Playwright launch/context configurations (e.g. `args`, `proxy`, `viewport`, `userAgent`, `permissions`).\n - `zw.browserContext.getActivePage()`: Returns active Playwright `Page` object. Note: returns `null` if no active page exists.\n - `zw.browserContext.createPage()`: Creates a new tab/page and returns it.\n - `zw.browserContext.get()`: Returns current main browser context.\n - `zw.browserContext.quit()`: Closes current main browser context and all tabs.\n - `zw.browserContext.clearProfile(name)` / `zw.browserContext.cloneProfile(source, target)`: Manages sticky profiles.\n- **Architectural Rules & Anti-patterns**:\n - Avoid creating Playwright contexts directly via `browser.newContext()` as they lack ZeroWork\'s built-in anti-bot detection evasions and profile management.\n - Never call `zw.browserContext.launch()` inside a loop or multiple times in the same script without quitting first.\n - Avoid changing userAgent, timezone, locale, or geolocation in `contextOptions` if `bypassDetection` is true, as it can break evasion mechanisms.\n\n### 18. Building Block Options (`Building Block Options.png`)\n- **Feature**: Overview of canvas interaction options.\n- **Menu Items**: Lists options available when interacting with building blocks on the canvas: `Deactivate Building Blocks`, `Auto-Align`, `Delay Times between the Building Blocks`, `Shortcuts`, `Sticky Notes`.\n\n### 19. Check if Selector is Correct and Unique (`Check If Selector Is Correct And Unique.png`)\n- **Debugging Methodology**: Verifying custom CSS selectors before running TaskBots.\n- **Console Command**: Open DevTools Console -> enter `document.querySelectorAll("PASTE YOUR SELECTOR HERE")` (e.g., `document.querySelectorAll("button[class*=\'button\'][type=\'submit\']")`).\n- **Evaluating Results**:\n - **Unique**: Returns a NodeList with `length: 1`. Hovering over the result highlights the exact element on the page.\n - **Multiple Matches**: Returns `length > 1`. Means selector is too broad. Need to make it more specific, unless building a selector for a list loop (e.g. profile lists), in which case see Incremental CSS Selectors.\n - **No Matches**: Returns `length: 0` or an error. Indicates a typo, incorrect attribute, or using unescaped/smart quotes.\n- **Note**: `text=` selectors (e.g. `text=Submit`) cannot be tested via `document.querySelectorAll` because `text=` is a Playwright/ZeroWork proprietary engine feature, not native CSS.\n\n### 20. Check Web Element Identifies Selector as Found but Next Action Does Not (`Check Web Element Identifies Selector As Found But Next Action Does Not.png`)\n- **Troubleshooting Scenario**: A `Check Web Element` block successfully finds an element, but the immediately following action block (`Click Web Element`, `Hover Web Element`, `Save Web Element`) fails to find or interact with it.\n- **Root Cause 1 & Solution (Timeout vs Delay)**:\n - Some sites have non-standard JS rendering where the DOM element exists but event listeners (like click) take longer to attach.\n - **Solution**: Increase the `Timeout` setting in `Advanced selector settings` of the failing action block (e.g., from 15 to 30-60 seconds). Note: Timeout is different from delay; timeout is abandoned as soon as the selector is fully ready, so it doesn\'t slow down successful runs.\n- **Root Cause 2 & Solution (Visibility / Scrolling)**:\n - Action blocks (especially click and hover) require the element to be visibly in the viewport, whereas `Check Web Element` only checks if it exists in the DOM.\n - **Diagnosis**: Check `Must be visible on screen` in `Check Web Element`. If it returns false, the element is off-screen.\n - **Solution**: Scroll the element into view. Test manually by adding a 30-second delay to `Check Web Element`, scrolling manually during the delay, and seeing if the next action succeeds. If so, add a `Keyboard Action` block (e.g. Page Down or Arrow Down) before the action block to ensure it scrolls into view automatically.\n\n## Batch 3: Check Web Element to Crash Course\n\n### 21. Check Web Element (`Check Web Element.png`)\n- **Building Block Name**: `Check Web Element`\n- **Function**: Checks if a selector (CSS or XPath) can be found or not on the page.\n- **Workflow Branching**: Creates a conditional fork in the canvas workflow.\n - Green checkmark branch: executes if the selector is found.\n - Red X branch: executes if the selector is not found.\n- **Primary Example**: `Send Notification` if cookies expire in ZeroWork. E.g., checks for the presence of a login button or email/password input field (indicating the user is logged out). If found (checkmark branch), routes to `Send Notification` to alert the user via email. If not found (X branch), continues normal workflow.\n- **Advanced Selector Settings**: Supports `Must be visible on screen` toggle (checking viewport visibility vs DOM presence) and `Timeout` configuration.\n\n### 22. Click Web Element (`Click Web Element.png`)\n- **Building Block Name**: `Click Web Element`\n- **Function**: Clicks on a specified web element (e.g., button, link, dropdown trigger).\n- **Targeting**: Requires providing a CSS or XPath selector for the TaskBot to know which element to target. E.g., `button[type=\'submit\']`.\n- **Modal Configuration UI**:\n - `Enter selector of the element`: Text input area for CSS/XPath.\n - `Advanced selector settings`: Allows configuring custom timeout and delay options before/after clicking.\n- **Best Practices / Context**: Often paired with `Check Web Element` (to verify presence before clicking) or `Browser Alert` (if the click triggers a native browser prompt/confirm dialog).\n\n### 23. Code in Inputs (`Code In Inputs.png`)\n- **Core Feature**: `zScript` expressions and code blocks within dynamic inputs across building blocks.\n- **Syntax 1: `${...}` (Expression)**: Runs a single JavaScript expression and inserts its result directly into the input field.\n - E.g. `${ await zw.deviceStorage.get("password") }` (retrieving locally stored secret).\n - E.g. `${ Math.random() }` (generating random number).\n - E.g. `${ "{id: 1234, name: Country Code}".trim().toUpperCase() }`.\n - **Crucial Warning/Rule**: Table/variable references like `{id: 1234, name: Country Code}` are **not** code; they are replaced with their values by ZeroWork before execution. If you need that value **as a string** inside code, wrap it in quotes (e.g., `"${...}"`), OR read it dynamically using `zw.getRef`: `zw.getRef: ${ (await zw.getRef({ ref_id: 1234, name: "Country Code" })).trim().toUpperCase() }`.\n- **Syntax 2: `$${...}` (Code Block)**: Runs full multi-line JavaScript code. Must include a `return` statement to insert the final value into the input field. All code runs locally on the user\'s device.\n - **Auto-installing NPM Packages**: You can import packages like `axios` directly inside the code block! ZeroWork auto-installs them locally on the fly. E.g.:\n ```javascript\n $${\n import axios from "axios"; // any import auto-installs locally\n const res = await axios.get("https://mydomain.com/my/api/url");\n return res.data;\n }\n ```\n - **Complex Formatting & Logging**: E.g.:\n ```javascript\n $${\n const fullAddress = await zw.getRef({ref_id: 1234, name: "Address" });\n const splitValues = fullAddress.split("country code: ");\n const countryCode = splitValues[1];\n if (!countryCode) {\n await zw.log({ message: "no country code", status: "warning" });\n return "unknown";\n }\n return countryCode.toUpperCase().trim();\n }\n ```\n - **Modal UI Example**: `Update Data` building block where `Set equal to the following value` contains `$${ import axios from "axios"; ... }` and `Data to be updated` selects `Variables` -> `API res`.\n\n### 24. Combine Filters with Standard CSS Logic (`Combine Filters With Standard Css Logic.png`)\n- **Advanced CSS Selector Concept**: Combining ZeroWork\'s proprietary `text=` filter method with standard CSS selector paths using `>>` as a filter separator.\n- **Syntax**: `parent_selector >> filter_selector`. E.g., `div > div[role=\'main\'] > div div >> text="Like"`.\n- **CRITICAL RULE / WARNING**: `>>` can **only** be added **at the end of the selector**.\n - `[checkmark] This will work`: `div > div[role=\'main\'] > div div >> text="Like"`\n - `[X] This will not work`: `div > div[role=\'main\'] > div >> text="Like" > div` (cannot put structural CSS child selectors after `>> text=`).\n- **Example Use Case**: Saving email addresses from Facebook Pages by combining `text=` with standard selector logic to pinpoint the exact container holding the email.\n\n### 25. Common Problems (`Common Problems.png`)\n- **Documentation Section**: Troubleshooting directory listing frequent user issues and their dedicated guide pages:\n - `My TaskBot Does Not Start Run`\n - `When I Use Data from Table, No Data is Being Pulled`\n - `Website is Glitching and Flashing`\n - `No Selector is Found`\n - `My TaskBot Saves Some Data but Not All`\n - `Data Is Saved in Wrong Format`\n - `Website Requires SMS or Email Verification`\n - `Keyboard Action Is Not Working As Expected`\n - `Check Web Element Identifies Selector as Found but Next Action Does Not`\n - `When Using Insert Data Block, First Letters Are Cut Off`\n - `Workflow Has More than One Starting Building Block`\n - `TaskBot Does Not Automatically Scroll`\n\n### 26. Contains & Does Not Contain (`Contains And Does Not Contain.png`)\n- **Condition Type**: `Contains & Does Not Contain`. Used in `Start Condition and Set Condition`.\n- **Function**: Checks if dynamic data (e.g. scraped text, table columns, variables) contains or does not contain certain keywords.\n- **Multiple Keywords**: Separate multiple keywords by comma `,`. E.g., `keyword1, keyword2, keyword3`.\n- **Workflow Example**: Mark leads as qualified if their description contains certain keywords (e.g., "marketing, sales, CEO").\n\n### 27. Continue until No Element Is Found (`Continue Until No Element Is Found.png`)\n- **Loop Option**: Setting within `Start Repeat` building block.\n- **Function**: When enabled, the loop continues running until no matching web element is found on the page. Highly useful for working with lists of unknown or dynamic length, such as social media scroll feeds.\n- **How it works**: If any web action inside the loop (e.g. `Save Web Element`, `Click Web Element`, `Hover Web Element`) returns a "selector not found" error, the loop automatically terminates.\n- **Repetition Limit Recommendation**: Strongly recommends setting a `Repetition limit` (e.g., 100 or 500) even when using this toggle, to prevent infinite loops on truly endless feeds (e.g. infinite scroll feeds) or stuck TaskBots.\n- **WARNING**: If this option is enabled but the loop body does **not** include any web element actions (e.g., it only does API requests or data formatting), the loop will **never end**. Must ensure at least one building block interacts with web elements on the page.\n- **Skipping Selector Not Found Error**: If `Save Web Element` has `Skip if no element is found` enabled, OR if the action is wrapped in a `Start Try-Catch` scope, the error is suppressed/skipped. Therefore, the loop will **not** end when that element is missing. In such cases, the loop only ends when the scrolling area reaches the bottom and no further elements can be identified after several scroll attempts. If `Auto-scroll` is disabled, the loop may run indefinitely because TaskBot cannot detect the end of the scrolling area.\n- **Recommendation**: Leave untoggled if you know exactly how many elements are on the page (e.g., scraping exactly 10 profiles per page).\n\n### 28. Convert Native Table to a Google Sheet (`Convert Native Table To A Google Sheet.png`)\n- **Table Feature**: Option available under `More Actions` (3 dots menu) of native tables in ZeroWork.\n- **UI Menu**: Click 3 dots next to table name (`My Table 4590`) -> select `Convert to a Google Sheet`.\n- **CRITICAL WARNING 1 (Irreversible)**: This action is **not reversible**. Once a native table is converted to a Google Sheet, it cannot be converted back to a native table.\n- **CRITICAL WARNING 2 (Data Deletion)**: All existing rows in the native table will be **permanently deleted** upon conversion. Users are strongly advised to use `Export Data as CSV` before converting to secure their data.\n- **Building Block References Preservation**: Existing table references in building blocks remain intact because the `table id` does not change during conversion.\n- **Column Name Matching & Case Sensitivity**: Users must ensure column names match. Case-sensitivity does **not** matter (e.g., `column one` in native table matches `COLUMN One` in Google Sheet). If column names differ, users must rename them in the Google Sheet or native table **before** converting. Any columns present in building blocks but missing in the Google Sheet will be automatically removed/ignored.\n\n### 29. Cookies (`Cookies.png`)\n- **Core Concept**: Enabling TaskBot to access browser cookie sessions so it doesn\'t have to log in every time it runs in an incognito session.\n- **Step 1: Copy Cookies**:\n - Download free Chrome extension `Cookie-Editor`.\n - Go to the target website (e.g., `linkedin.com`), ensure you are logged in.\n - Click Cookie-Editor plugin icon -> click `Export` button -> select `Export as JSON`. Copies cookies to clipboard.\n- **Step 2: Paste Cookies to ZeroWork**:\n - Open TaskBot builder -> click `TaskBot Settings` gear icon (top right).\n - Paste cookies into the `Cookies` text area.\n- **Session Invalidation Warnings**:\n - If you log out of the website in your own browser after copying cookies, it invalidates the cookie session for the TaskBot as well! If you log out, you must re-copy and re-paste fresh cookies.\n - Cookies expire over time. When they expire, simply re-copy and paste them.\n- **Troubleshooting (TaskBot Cannot Log in with Cookies)**:\n - In rare cases, some websites do not accept cookies to be logged in.\n - Solution 1: Build an automated login flow using `Insert Text or Data` (username/password) and `Click Web Element` (Log in button). Passwords can be encrypted using `Encrypt Content`.\n - Solution 2: Use `run modes` (e.g., non-incognito run mode).\n\n### 30. Crash Course (`Crash Course.png`)\n- **Documentation Section**: Beginner introduction video tutorial series covering the basics of building a first TaskBot. Covers fundamental concepts, UI overview, and basic building block usage.\n\n## Batch 4: Create Columns to Enrich Existing Data\n\n### 31. Create Columns (`Create Columns.png`)\n- **Table Feature**: Adding and managing columns within ZeroWork data tables.\n- **UI Menu**: Accessed via Data Tables view -> click `[+ Add Column]` button.\n- **Configuration**:\n - `Column Name`: Text input for column header.\n - `Column Type`: Select data type (e.g., `Text`, `Number`, `Date`, `Boolean`).\n- **Core Rules & Behavior**:\n - Each column is assigned a unique internal `column id` (e.g., `id: 3862`).\n - Renaming a column does **not** break existing building block references because ZeroWork tracks columns by their underlying ID rather than their display name.\n - Deleting a column permanently removes its data and invalidates any building block input fields referencing that column.\n\n### 32. CSS Selectors Master Class (`Css Selectors Master Class.png`)\n- **Documentation Section**: Advanced video tutorial series and comprehensive guide on mastering CSS selectors for robust web automation.\n- **Key Topics Covered**:\n - `nth-match` and indexing for list elements.\n - `has-text` / `text=` filtering for pinpointing elements containing specific text strings.\n - Addressing parent and ancestor containers.\n - Addressing sibling elements (`+` and `~`).\n - Dynamic attribute matching (e.g., `[class*=\'button\']`, `[id^=\'tab-\']`).\n- **Best Practice**: Essential training for building resilient TaskBots that withstand dynamic UI changes and website updates.\n\n### 33. Data Found and Data Not Found (`Data Found And Data Not Found.png`)\n- **Core Concept**: Workflow branching logic executed by conditional building blocks like `Check Web Element`.\n- **Canvas Visual Representation**:\n - **Green Checkmark Branch (`Found`)**: Followed when the target element, text, or condition successfully evaluates to true (e.g., element exists in the DOM and is visible).\n - **Red X Branch (`Not Found`)**: Followed when the target element or condition evaluates to false (e.g., element is missing after timeout expires).\n- **Common Architectural Patterns**:\n - `Check Web Element` (Login Button) -> `[Found]` -> `Send Notification` (Alert user to log in).\n - `Check Web Element` (Next Page Button) -> `[Found]` -> `Click Web Element`. `[Not Found]` -> `Break Repeat` (End pagination loop).\n\n### 34. Data Is Saved in Wrong Format (`Data Is Saved In Wrong Format.png`)\n- **Troubleshooting Scenario**: Scraped text saved via `Save Web Element` contains unwanted formatting, extra whitespace, line breaks, or garbage characters.\n- **Root Cause**: The raw DOM text inside the targeted HTML element includes formatting tags or spacing used by the website\'s layout engine.\n- **Standard Solution**:\n - Add an `Apply Regex` building block immediately after `Save Web Element`.\n - Configure `Select method` to `Replace text`.\n - Use regex patterns to clean the data (e.g., removing extra line breaks with `/\\n+/g`, stripping leading/trailing whitespace, or extracting specific substring patterns).\n - Save the cleaned result back to the target variable or table column.\n\n### 35. Deactivate Building Blocks (`Deactivate Building Blocks.png`)\n- **Feature**: Disabling specific building blocks on the canvas without deleting them.\n- **UI Interaction**: Right-click any building block on the canvas -> select `Deactivate`.\n- **Visual Indicator**: The deactivated building block turns faded/greyed-out on the canvas.\n- **Run Behavior**: When a TaskBot runs, it completely ignores and skips over any deactivated building blocks, moving seamlessly to the next active block in the sequence.\n- **Primary Use Case**: Highly effective for debugging, testing isolated workflow branches, or temporarily turning off notifications/webhook broadcasts during development.\n\n### 36. Delay Times between the Building Blocks (`Delay Times Between The Building Blocks.png`)\n- **Core Concept**: Managing execution pacing between actions. ZeroWork applies built-in default delays for certain major actions (like `Open Link` or `Insert Text or Data`).\n- **Block-Level Delay Configuration**:\n - Accessed inside action building blocks (e.g., `Keyboard Action`, `Open Link`, `Click Web Element`).\n - Fields: `min sec` and `max sec` (e.g., `min sec: 3`, `max sec: 15`).\n - **CRITICAL RULE / BEHAVIOR**: Block-level delay times entered directly into an action building block **always kick in AFTER the action takes place**. E.g., if you set 3 seconds in `Keyboard Action`, TaskBot presses the keys and then waits 3 seconds before moving to the next block. If you need a delay **before** an action, you must use a separate `Delay` building block placed preceding the action.\n- **Randomize Delay Time Setting**:\n - Global option available in TaskBot settings to automatically randomize delay times between all building blocks.\n - Recommends activating only when mimicking human behavior (e.g. social media automation). Warning: significantly slows down overall run time depending on upper limits.\n\n### 37. Delay (`Delay.png`)\n- **Building Block Name**: `Delay`\n- **Modal Configuration UI**:\n - `Minimum (seconds)`: Shortest possible pause duration (e.g., `4`).\n - `Maximum (seconds)`: Longest possible pause duration (e.g., `10`).\n- **Function & Pacing**: Pauses the TaskBot for a randomized duration between the minimum and maximum values before executing the next building block.\n- **Fixed Delay**: To create a fixed, non-randomized pause, enter the **exact same number** in both minimum and maximum fields (e.g., min `5`, max `5`).\n- **Advanced Dynamic Rules & Edge Cases**:\n - Both fields accept decimal values (e.g., `1.50` for 1.5 seconds).\n - Both fields accept variable and table references (e.g., `{id: 113251, name: min}`).\n - **Invalid Reference**: If a variable/table reference contains an invalid value (e.g., text string instead of a number), the Delay block is **skipped entirely**, and TaskBot moves to the next block immediately without pausing.\n - **Max < Min**: If maximum is less than minimum, TaskBot pauses for the **minimum** duration. E.g., min `10`, max `4` -> pauses for exactly 10 seconds.\n - **Empty Fields**: If either field is left empty, the Delay block is skipped.\n - **Zero Delay**: Setting both values to `0` moves to the next step without pausing.\n\n### 38. Delete Data (`Delete Data.png`)\n- **Building Block Name**: `Delete Data`\n- **Modal Configuration UI**:\n - **Dropdown Options**: `Delete all rows` vs `Delete one row`.\n - `Select variables or data table`: Dropdown selecting target table (e.g., `Profiles`).\n- **Delete All Rows**:\n - Permanently removes all data rows from the selected table.\n - **Best Practice**: Place at the very beginning of a TaskBot workflow (before any loops start) when collecting fresh scraping data on every run and needing to overwrite old runs.\n- **Delete One Row**:\n - Deletes a single row during a loop iteration when specific conditions are met.\n - **Workflow Example (Removing Unqualified Leads)**: `Start Repeat` (Dynamic loop over `Profiles`) -> `Start Condition` (Reference: `Qualification` column) -> `Set Condition` (Filter out `\u2260 Qualified`) -> `Delete Data` (`Delete one row` from `Profiles`). Ensures disqualified leads are purged row by row during the loop.\n\n### 39. Device Storage (`Device Storage.png`)\n- **Core Feature**: `zw.deviceStorage.*` API in Write JS / zScript for persisting key-value data locally on the user\'s device. Survives Desktop Agent restarts, uninstalls, and reinstalls. Data is **never** sent to ZeroWork servers.\n- **API Methods (Always Async / Require `await`)**:\n - `await zw.deviceStorage.get(key: string)`: Returns string value, or `undefined` if not set.\n - `await zw.deviceStorage.set(key: string, value: string)`: Saves string value under the key.\n - `await zw.deviceStorage.remove(key: string)`: Removes key and its value.\n - `await zw.deviceStorage.has(key: string)`: Returns `true` if key exists, `false` otherwise.\n - `await zw.deviceStorage.getAll()`: Returns object of all key-value pairs `{ [key: string]: string }`.\n- **Desktop Agent UI (Adding Secrets)**:\n - Open Desktop Agent -> select `Device storage` from tray menu -> click `Add key` -> enter Key (e.g., `salesforce_password`) and Value -> click `Save`.\n- **Handling Non-String Values**:\n - Device storage only accepts strings. Must use `JSON.stringify()` on write and `JSON.parse()` on read for objects/arrays.\n - E.g.: `await zw.deviceStorage.set("bot_state", JSON.stringify(stateObject));`\n- **Logging Secrets Safely (`zw.logTemp`)**:\n - To log sensitive values (passwords, API tokens) during debugging without leaking them, use `await zw.logTemp(secret);` instead of `zw.log()`. `logTemp` displays the value in live run logs but **never** saves it to persistent TaskBot run reports.\n- **CRITICAL WARNING / SECURITY NOTICE**:\n - Avoid using `zw.deviceStorage.get()` to read secrets via `Code in Inputs` inside standard no-code building blocks if those building blocks auto-log their input values, because auto-logged inputs are saved to persistent TaskBot run reports.\n- **Technical Constraints**: Total device storage limit is ~3,000,000 characters. Exceeding this throws an error.\n\n### 40. Dynamic Inputs (`Dynamic Inputs.png`)\n- **Core Concept**: All building block input fields across ZeroWork accept dynamic inputs, references, code, and spintax.\n- **References to Variables and Tables**:\n - Syntax: `{id: 123, name: "Profile name"}`. Replaced dynamically with the underlying table row or variable value during execution.\n- **Code in Inputs (zScript)**:\n - Requires Desktop Agent v1.1.72+.\n - **`${...}` (Expression)**: Evaluates a single JS expression and inserts the result. E.g., `Password: ${await zw.deviceStorage.get("password")}`.\n - **`$${...}` (Code Block)**: Executes full multi-line JS code. Must include `return`.\n - **Auto-installing NPM Packages**: Any `import` statement inside `$${...}` (e.g., `import axios from "axios";`) automatically installs the NPM package locally on the fly.\n- **Spintax**:\n - Syntax: `{ Hi | Hey | Howdy }! How { are you | are things going }?`.\n - Helph vary text content dynamically to bypass anti-spam filters on social media and email platforms.\n\n### 41. Dynamic Loop (`Dynamic Loop.png`)\n- **Building Block / Mode**: `Start Repeat` -> `Select loop type`: `Dynamic`.\n- **Core Function**: Iterates over existing rows in a selected data table one by one.\n- **Key Characteristics & Behavior**:\n - Iterates over existing rows until it consumes all rows in the table.\n - Automatically tracks progress row by row.\n - If you only want to process a specific subset of rows (e.g., 1 row or 10 rows), enter the desired number into `Repetition limit (optional)`.\n- **Primary Use Cases**:\n - **Enriching Existing Data**: Visiting profile links from a table, scraping additional details (like "About Me" or email), and saving them back to the exact same row.\n - **Performing Actions on Existing Data**: Visiting profile links from a table and auto-sending outreach DMs or emails.\n\n### 42. Enrich Existing Data (`Enrich Existing Data.png`)\n- **Workflow Architecture**: Standard pattern for adding scraped data to existing table records.\n- **Step-by-Step Setup**:\n 1. `Start Repeat`: Configure as `Dynamic` loop selecting the target table (e.g., `LinkedIn Profiles`).\n 2. `Open Link`: Reference the table column containing the URL (e.g., `{id: 3862, name: Profile link}`).\n 3. `Save Web Element` (Job Title): Configure selector, set `Save to` selecting the same table (`LinkedIn Profiles`) and target column (`Current job title`).\n 4. `Save Web Element` (About Me): Configure selector, set `Save to` selecting table (`LinkedIn Profiles`) and target column (`About me section`).\n- **Preventing Duplicate Visits (Visited Status Pattern)**:\n - Create a new column in the table called `Profile visit status`.\n - Add an `Update Data` building block at the end of the loop to set `Profile visit status` equal to `visited`.\n - Add `Start Condition and Set Condition` at the beginning of the loop (right after `Start Repeat`). Configure `Start Condition` to reference `Profile visit status`, and `Set Condition` to filter out rows where status `\u2260 visited` (or check if status equals `visited` and branch away). Ensures TaskBot skips already visited profiles on subsequent runs.\n\n## Batch 5: Exact or Loose Match to Hierarchy\n\n### 43. Exact or Loose Match (`Exact Or Loose Match.png`)\n- **Core CSS Selector Concept**: Attribute matching strategies for targeting web elements.\n- **Exact Match (`=`)**:\n - Syntax: `[attribute=\'value\']`. E.g., `button[class=\'pure-button pure-button-primary-progressive\'][type=\'submit\']`.\n - Behavior: Matches the element only if the attribute string is perfectly identical. Brittle if websites dynamically append utility classes or state classes (like `active` or `focus`).\n- **Loose Match (`*=`)**:\n - Syntax: `[attribute*=\'value\']`. E.g., `button[class*=\'pure-button\'][type=\'submit\']`.\n - Behavior: Matches any element whose attribute contains the specified substring.\n - **Best Practice**: Highly resilient technique for web automation. Allows shortening long, fragile class strings to stable core identifiers (e.g., matching `pure-button` within a changing multi-class string).\n\n### 44. Example: Standardize Different Formats (`Example Standardize Different Formats.png`)\n- **Workflow Architecture**: Multi-step data cleaning pattern for converting human-readable scraped numbers (e.g., "7k" followers) into raw integers (7000) for numeric comparisons.\n- **Step 1: Strip Text Characters (`Format Data`)**:\n - Add `Format Data` building block.\n - Configure `Select format action` to `Remove words`.\n - Enter `k` into `Enter words separated by comma`.\n - Set `Data to be formatted` selecting the target table (`Profiles`) and column (`Number of followers`). E.g., converts "7k" to "7".\n- **Step 2: Mathematical Scaling (`Number Operations`)**:\n - Add `Number Operations` building block immediately following `Format Data`.\n - Configure `Choose a number operation` to `Multiply`.\n - Enter `1000` into `Number to multiply by`.\n - Set `Number to multiply` selecting table (`Profiles`) and column (`Number of followers`). E.g., converts "7" to "7000", enabling accurate use in `Actions <, \u2264, >, \u2265` conditions.\n\n### 45. Export Data as CSV (`Export Data As Csv.png`)\n- **Table Feature**: Exporting ZeroWork data tables to local CSV files.\n- **UI Access Methods**:\n 1. **TaskBot Canvas View**: Click `More Actions` (3 vertical dots icon) next to the table name (`My table 4544`) -> select `Export as CSV`.\n 2. **Data Table Expanded View**: Click the 3 vertical dots icon (top right next to `DELETE DATA`) -> select `Export as CSV`.\n 3. **Global Tables Dashboard**: Navigate to `https://creator.zerowork.io/datagroups` -> click the download icon next to any table.\n- **Google Sheets Export**: Explains how to export attached Google Sheets directly from Google\'s UI via `File` -> `Download` -> `Comma Separated Values (.csv)`.\n\n### 46. Format Data (`Format Data.png`)\n- **Building Block Name**: `Format Data`\n- **Modal Configuration UI & Available Actions**:\n - `Remove word`: Strips specified words/substrings (see Remove Words).\n - `Replace text`: Regex/string replacement. E.g., "Hello world" (replace "world" with "universe") -> "Hello universe".\n - `Shorten content length`: Truncates character count (crucial for ChatGPT token limits).\n - `Convert to lower case`: E.g., "HELLO WORLD" -> "hello world".\n - `Convert to upper case`: E.g., "hello world" -> "HELLO WORLD".\n - `Capitalize first letters`: E.g., "hello world" -> "Hello World".\n - `Normalize URL`: Validates and formats web links. E.g., `www.wikipedia.org` -> `https://www.wikipedia.org/`. Note: If the string is invalid, throws a fatal error `The URL is not a valid URL and cannot be normalized`.\n - `Trim white spaces`: Strips leading/trailing spaces. E.g., `" Hello world "` -> `"Hello World"`.\n - `Remove line breaks`: Strips `\\n` and `\\r`. E.g., multi-line string -> single-line string.\n - `Remove smileys`: Strips emojis and emoticons. E.g., `"Hello world \u{1F30D}"` -> `"Hello World "`.\n- **Run Behavior**: If the input value to be formatted is empty/blank, TaskBot takes no action and seamlessly continues its run.\n\n### 47. General: Run, Schedule, Share, Webhooks (`General Run Schedule Share Webhooks.png`)\n- **Documentation Section**: Overview directory listing core operational and management guides for TaskBots.\n- **Sub-pages Included**:\n - `Run` & `Stop`\n - `Log in to the Agent` & `Run Settings`\n - `TaskBot Sharing Options` & `Cookies`\n - `Scheduler` & `Trigger Run via Webhook`\n - `Proxies` & `Remote (Cloud) Execution`\n - `How to Check and Update Your Agent`\n - `Install ZeroWork Agent on VPS`\n\n### 48. Getting Started (`Getting Started.png`)\n- **Documentation Section**: Initial onboarding guide for new ZeroWork users.\n- **Core Setup Steps**:\n 1. **Install the Desktop Agent**: Download and install the local background runtime agent.\n 2. **Install Google Chrome**: Chrome must be installed on the user\'s OS, even if it is not their primary or default browser. TaskBots execute silently within an automated Chrome instance behind the scenes. E.g., Brave browser users must explicitly whitelist the ZeroWork agent in their strict security shields.\n 3. **Watch the Crash Course**: Recommended video onboarding for building the first bot.\n\n### 49. Getting Support (`Getting Support.png`)\n- **Documentation Section**: Troubleshooting hierarchy and official support channels.\n- **Self-Service Protocol**:\n 1. `Check your agent version`: Verify the Desktop Agent is fully updated to the latest version, as many bugs are resolved by updates.\n 2. `Watch the crash courses`: Review Beginner and Selector crash courses (essential before asking selector questions).\n 3. `Explore the docs`: Search Common Problems, Run Reports, Selectors, Building Blocks, Tables, Variables, Loops.\n- **Escalation Channels**:\n - `Report a Technical Error`: Submit reproducible bug steps via Discord `#report-a-bug` channel or official Bug Report Form.\n - `Business Plan Support`: Priority email support (`billing@zerowork.io` / support form) with up to 2 business days response time.\n - `Community Help`: Fast, free peer support in Discord `#community-help` and `#subflow-library`.\n - `Hire a ZeroWork Expert`: 1-on-1 paid consultation for complex selectors or custom bot architecture.\n\n### 50. Go Back or Forward (`Go Back Or Forward.png`)\n- **Building Block Name**: `Go Back or Forward`\n- **Function**: Navigates the active browser tab\'s history backwards or forwards (mimicking native browser Back/Forward buttons).\n- **Run Behavior & Edge Cases**:\n - If there is no previous or next page in the tab\'s session history to navigate to, the action is entirely non-consequential. TaskBot does not fail or throw an error; it simply continues seamlessly to the next building block.\n\n### 51. Google Sheets (`Google Sheets.png`)\n- **Core Feature**: Comprehensive integration capabilities for linking Google Sheets directly to TaskBot data tables (pull, update, append).\n- **Architectural Rules & FAQ**:\n - `Creating New Columns`: Add columns directly in the Google Sheet, then open TaskBot table view and click `Refetch columns from Google Sheet`.\n - `Renaming or Deleting Columns`: Click `Refetch columns`. Any columns removed from the sheet will be automatically stripped from building block input references. If a column is renamed/deleted in the sheet but was never referenced in any building blocks, no action occurs. E.g., column matching is **case-insensitive** (`column one` matches `Column One`).\n - `Quota & Usage Limits`: To avoid exceeding Google Sheets API rate limits, ZeroWork automatically batches row updates every 50 rows by default. E.g., on a 500-row sheet, TaskBot updates the sheet exactly 10 times. Batch size can be customized in `Start Repeat` additional options. If a rate limit is hit, TaskBot automatically retries 10 times before failing and logging an error in Run Reports.\n - `Deleted Sheet Handling`: TaskBot validates the Google Sheet link and OAuth session at the very start of every run. If invalid or expired, the run aborts immediately with an error report.\n - `Duplicating TaskBots`: Duplicating TaskBot A (linked to Sheet A) creates TaskBot B with a new table ID, but still pointing to Sheet A. Users can keep them sharing the sheet, or link TaskBot B to Sheet B without remapping building block references (because references use table ID, not sheet name).\n - `Re-authentication`: If OAuth tokens expire, go to Google Account Data & Privacy -> Third-party apps -> remove ZeroWork -> return to ZeroWork and re-authenticate.\n\n### 52. Hierarchy (`Hierarchy.png`)\n- **Core CSS Selector Concept**: Structuring selector paths based on DOM element nesting and parent-child relationships. E.g., Wikipedia search button.\n- **Strict Hierarchy (`>`)**:\n - Syntax: `parent > direct_child`. E.g., `body > div > form > fieldset > button`.\n - Behavior: Requires the child element to be an immediate direct descendant of the parent. Fails if intermediate wrapper divs are dynamically inserted.\n- **Loose Hierarchy (` ` space)**:\n - Syntax: `ancestor descendant`. E.g., `body button`.\n - Behavior: Matches the descendant element anywhere inside the ancestor container, regardless of how many intermediate DOM nodes exist between them.\n- **Advanced Combinations & Attribute Injection**:\n - Combine strict and loose: `tag1 tag3 > tag4` (tag3 is anywhere inside tag1, but tag4 is a direct child of tag3).\n - Inject attributes at any level: `tag1[attribute=\'value\'] > tag2[attribute=\'value\']` or `body > div button[class*=\'pure-button\']`.\n\n## Batch 6: Home to Install ZeroWork Agent on VPS\n\n### 53. Home and Welcome (`Home.png`)\n- **Documentation Section**: Home and Welcome (Root Overview)\n- **Target Audience & Core Value**: Dedicated to creators building TaskBots to automate repetitive browser tasks (typing, clicking, copy-pasting data) without requiring any coding skills. TaskBots mimic human interactions on any website to enable limitless automation.\n- **Typical Use Cases**:\n - `Scrape`: Collect LinkedIn profiles, Facebook group members, Instagram followers, Amazon products.\n - `Enrich data`: Collect additional granular data from individual profile/product pages (email, job title, rating, reviews).\n - `Automate actions`: Auto-send DMs, auto-like content, auto-follow profiles, auto-fill forms.\n - `Transform data (calculate, filter, compare)`: Auto-qualify leads based on keywords, geographic location, or activity; auto-format or tag collected data.\n - `Add AI`: Auto-post AI-generated blog posts/comments, auto-reply to messages with AI, auto-send AI-generated prospect/product summaries via email.\n- **Getting Started & Onboarding Links**: Sign Up, Install the Agent, Crash Course, FAQs.\n- **TaskBot Creation Architecture**: Guides divided into Running TaskBots, Using Building Blocks, Using Selectors, Using Tables, Using Variables.\n- **Troubleshooting & Support Hierarchy**: Common Problems, TaskBot Creator Support.\n\n### 54. Hover Web Element (`Hover Web Element.png`)\n- **Building Block Name**: `Hover Web Element`\n- **Function**: Simulates a native mouse hover over a specified web element.\n- **Primary Use Case**: Unlocking elements or tooltips that are only visible in the DOM or UI when hovered. E.g., on Facebook Group posts, the exact timestamp/date is hidden behind a relative time string ("3 March at 04:11"); hovering over it reveals the exact absolute timestamp tooltip (`Sunday, 3 March 2024 at 04:11`).\n- **Workflow Pattern (Hover & Scrape)**:\n - Step 1: Add `Hover Web Element` building block. Configure with the CSS or XPath selector of the trigger element (e.g., `div > span > span > span > span > a > span > span[aria-labelledby]`).\n - Step 2: Add `Save Web Element` building block immediately following the hover block. Configure with the selector of the newly appeared tooltip element to scrape the revealed data.\n- **Modal Configuration UI**:\n - `Enter CSS or XPath selector`: Input field for the target element to hover over. E.g., `div > span > span > span > span > a > span > span[aria-labelledby]`.\n - `min sec` / `max sec`: Configurable randomized delay times executed during the hover action (e.g., min sec `2`, max sec `0`).\n\n### 55. How to Add Tables (`How To Add Tables.png`)\n- **Documentation Section**: How to Add Tables (under `Using Tables`)\n- **Three Methods to Create Data Tables**:\n 1. `ZeroWork native table`: Built directly inside ZeroWork\'s table management UI from scratch (see Native Tables).\n 2. `Google Sheet link`: Synchronizing an external Google Sheet via its sharing link (see Google Sheets).\n 3. `Uploading a CSV file`: Uploading a local CSV file automatically generates table columns and imports all rows based on the CSV headers. E.g., simply upload a CSV file and table columns/rows will be created instantly. Note: Tables created via CSV upload are converted into ZeroWork native tables.\n- **Architectural Decision Guide**: Links to `Using Google Sheet vs. Native Tables` to assist users in selecting the optimal table architecture for their specific automation scale and performance needs.\n\n### 56. How to Build Custom Selectors (`How To Build Custom Selectors.png`)\n- **Documentation Section**: How to Build Custom Selectors (under `Using Selectors`)\n- **Core Philosophy**: When right-click copying selectors from browser dev tools fails to produce reliable results across dynamic web pages, users must learn to build custom, resilient selectors. Relying on auto-copied selectors is often insufficient for modern social media platforms and complex web apps.\n- **Accessibility**: Emphasizes that **no coding skills are required** to master custom selector construction. Includes an embedded video crash course.\n- **Supported Selector Engines**: Fully supports both CSS and XPath selectors. The primary documentation focuses on CSS selectors as they are more approachable for beginner and intermediate builders. (Links to `How to Use XPath in ZeroWork (advanced)` for complex use cases).\n- **Structured Learning Path**:\n - `Basic Concepts of Selectors`: Understanding HTML tags, classes, IDs, and attributes.\n - `One Element Can Have Many Selector Expressions`: Exploring alternative targeting strategies.\n - `Check if Selector Is Correct and Unique`: Validating selectors in the browser console/devtools before bot deployment.\n - `Exact or Loose Match`: Utilizing `= ` vs `*= ` attribute matching.\n - `Hierarchy`: Mastering strict `>` vs loose ` ` descendant combinators.\n - `Combine Filters with Standard CSS Logic`: Chaining multiple attribute conditions.\n - `Lists: Incremental CSS Selectors`: Targeting repeating elements in scraping loops.\n - `Addressing Siblings`: Utilizing `+` (exact) and `~` (loose) sibling combinators.\n\n### 57. How to Check and Update Your Agent (`How To Check And Update Your Agent.png`)\n- **Documentation Section**: How to Check and Update Your Agent (under `General: Run, Schedule, Share, Webhooks`)\n- **Protocol for Checking Agent Status**:\n 1. Open the local Desktop Agent options menu from the OS toolbar/system tray (displays current version e.g., `ZeroWork Version 1.1.46`, Status: Ready, active Account, Scheduler connection status, Logout, Restart, Quit).\n 2. Navigate to the official agent download page (`https://creator.zerowork.io/download-agent`).\n 3. Compare versions: If the latest version displayed on the download page (e.g., Mac OS `1.1.55`, Windows `1.1.55`, Linux `1.1.55 BETA`) is higher than the local installed version, the agent is outdated. Note: First-time downloaders must return to `https://creator.zerowork.io/workflows` to build bots.\n- **Automated Update Protocol**:\n 1. In the agent options menu, click the blue `Check for update` button. Confirm the OS prompt to install the new version.\n 2. Once the update finishes, confirm the prompt to restart the agent.\n- **Manual Fallback Protocol**: If the automated update mechanism fails due to OS firewall or permissions issues, users can safely uninstall their existing agent and manually download/install the latest version from `https://creator.zerowork.io/download-agent`.\n- **Data Preservation Guarantee**: Explicitly assures users that `Uninstalling and reinstalling the agent will not affect any of your scheduled TaskBots or webhooks`.\n\n### 58. How to Use XPath in ZeroWork (advanced) (`How To Use Xpath In Zerowork Advanced.png`)\n- **Documentation Section**: How to Use XPath in ZeroWork (advanced) (under `Using Selectors`)\n- **Context**: While ZeroWork documentation prioritizes CSS selectors for onboarding simplicity, advanced users familiar with XML Path Language can leverage full XPath capabilities.\n- **Automatic Syntax Recognition**: TaskBots automatically detect and parse an XPath selector when the input string begins with a double slash `//`. E.g., `//*[@id=\'js-lang-lists\']/div[1]/ul/li[12]`.\n- **Explicit Declaration Syntax**: Users can also explicitly force XPath evaluation by prefixing the selector string with `xpath=`. E.g., `xpath=//button`.\n- **Dynamic Loop Indexing for XPath Lists**:\n - To iterate over a list of incrementing XPath selectors within a scraping loop, users apply the exact same `loop_index` bracket syntax used for CSS selectors.\n - Example syntax: `//*[@id=\'js-lang-lists\']/div[1]/ul/li[{loop_index,1}]`. During runtime, TaskBot dynamically substitutes `{loop_index,1}` with incrementing integers (`li[1]`, `li[2]`, `li[3]`, etc.) to scrape public lists item by item.\n\n### 59. Import Data from CSV (`Import Data From Csv.png`)\n- **Documentation Section**: Import Data from CSV (under `Using Tables`)\n- **Core Functionality**: Create new native tables from scratch using CSV uploads, or import/merge CSV data into existing native tables.\n- **Creating a New Table from CSV**:\n - Modal Workflow: Click `Add Table` -> Select table type `Import data from CSV` -> Click `UPLOAD CSV` -> Click `ADD TABLE`. Automatically establishes table schema (columns) and populates initial rows from the CSV file.\n- **Updating Existing Native Tables with CSV**:\n - UI Access Locations:\n 1. TaskBot canvas view: Click `More Actions` (3 vertical dots icon) next to the table name (`My table 4544`) -> Select `Import data from CSV`.\n 2. Global tables dashboard (`https://creator.zerowork.io/datagroups`).\n 3. Expanded table view: Click `More Actions` (3 vertical dots icon top right next to `DELETE DATA`) -> Select `Import data from CSV`.\n- **Column Matching & Merging Rules**:\n - `Header Matching`: Ensure CSV column headers match existing table column names.\n - `Non-matching Columns`: If the CSV contains unmapped columns, the table updates successfully but unmapped columns are safely ignored/discarded.\n - `Column Sequence`: The order of columns in the CSV versus the table does not affect import accuracy.\n - `File Name`: The CSV filename does not need to match the table name.\n - `Case Sensitivity`: Column header matching is **case-insensitive** (`fb link` successfully maps to `FB Link`).\n - `Append vs Overwrite`: By default, imported CSV data is appended (merged as new rows below existing data) unless the `overwrite current data` checkbox is explicitly checked.\n- **Checkbox "overwrite current data"**:\n - When checked: Existing table data is permanently purged and replaced entirely by the new CSV payload. Strongly recommends exporting current data as CSV first to prevent accidental data loss.\n - When unchecked: Operates in default append mode.\n- **Google Sheets Import**: For tables linked to external Google Sheets, users must perform CSV imports directly within Google\'s UI via `File` -> `Import`.\n\n### 60. Imports and Package Management (`Imports And Package Management.png`)\n- **Documentation Section**: Imports and Package Management (under `Write Javascript`)\n- **Core Capabilities**: TaskBots support standard JavaScript package imports (e.g., `import dayjs from \'dayjs@1.11.11\'`) or advanced dynamic loading via the `zw.import()` API. ZeroWork automatically resolves, downloads, and installs missing npm packages at runtime. Includes full package lifecycle management via `zw.packages.list()`, `zw.packages.uninstall()`, and `zw.packages.uninstallAll()`.\n- **Local Execution Directive (`#ze-run-locally`)**: Adding the comment `// #ze-run-locally` (or checking the `Run locally` UI checkbox) instructs the engine to execute the JS block in the local Node.js background process rather than the active browser tab context. Essential for utilizing OS-level modules (`child_process`, `fs`, `robotjs`). E.g., shows snippet executing `execSync` to launch Notepad/TextEdit/gedit based on `process.platform` (`win32`, `darwin`, `linux`), waiting via `zw.delay()`, and simulating physical keystrokes via `robot.type()`.\n- **1. Standard Imports**:\n - Supports standard ESM (`import`) or CommonJS (`require`) syntax. Automatically fetches and caches packages. E.g.:\n ```javascript\n // ESM default import\n import dayjs from \'dayjs@1.11.11\';\n await zw.log("now", dayjs().toISOString());\n // ESM subpath import\n import chunk from \'lodash/chunk\';\n await zw.log("chunked result", chunk([1, 2, 3, 4], 2));\n // CommonJS require\n const _ = require("lodash@4.17.21");\n // Git repository import (HTTPS only)\n import lodash from \'git+https://github.com/lodash/lodash.git\';\n ```\n - `Notes`: Installed packages are globally available across TaskBots by default. To isolate dependencies to a single TaskBot, use `zw.import()` with `{ isolate: true }`. Packages unused for 7 days (168 hours) are automatically garbage collected (configurable via `uninstallIfUnusedFor`). Disable auto-import parsing by adding the comment `// #ze-disable-auto-import`.\n- **2. Advanced Imports via `zw.import()` API**:\n - Syntax: `await zw.import(pkg: string | string[] | { [key: string]: string }, options?: ImportOptions)`\n - Options Interface: `{ isolate?: boolean; uninstallIfUnusedFor?: number | null; preferDefault?: boolean; }`\n - `Single package with options`: `const dayjs = await zw.import(\'dayjs@1.11.11\', { isolate: true, uninstallIfUnusedFor: 300 });`\n - `Multiple packages as array`: `const [dayjs, lodash] = await zw.import([\'dayjs@1.11.11\', \'lodash@4.17.21\']);`\n - `Named mapping as object`: `const { time, dash } = await zw.import({ time: \'dayjs@1.11.11\', dash: \'lodash@4.17.21\' });`\n - `Installing from Git`: `const gitLodash = await zw.import(\'git+https://github.com/lodash/lodash.git\');`\n - `Bypassing Garbage Collection`: Pass `{ uninstallIfUnusedFor: null }` to persist the package indefinitely.\n - `Import Option Details`:\n - `uninstallIfUnusedFor` (default: 168). Retention window in hours.\n - `isolate` (default: false). When true, scopes the package installation exclusively to the active TaskBot ID. Crucial when different bots require conflicting package versions. Note: Deleting a TaskBot does not automatically delete isolated packages; manage via `zw.packages.*`.\n - `preferDefault` (default: true). Automatically unwraps `module.default` when present. E.g., `const mysql = await zw.import(\'mysql2@latest/promise\');` vs `const chalk = await zw.import(\'chalk@4\');`.\n - `Input Validation`: Rejects tarball URLs, local file paths, and non-HTTPS Git URLs.\n- **3. Special Package Types**:\n - `Built-in Packages`: Pre-bundled modules that resolve instantly without network installation. Includes Node core modules (`fs`, `os`, `path`), `axios` pinned to `^1.6.6`, and `playwright` pinned to `^1.45.0`. Built-ins do not appear in `zw.packages.list()` and cannot be uninstalled or version-bumped. E.g., `import * as fs from \'fs\';` or `import axios from \'axios\';`.\n - `Pure ESM Packages`: ZeroWork\'s runtime is not pure ESM yet. Importing pure ESM packages throws a fatal error: `This package appears to be pure ESM`. Workarounds: Use a maintained CommonJS/non-ESM fork (e.g., `cacheable-lookup`), pin to an older non-ESM version (e.g., `chalk@4`), or pre-bundle the package using a bundler before pasting into ZeroWork.\n - `Native Packages`: C/C++ native addons (e.g., `robotjs`, `ffi-napi`) require OS-level build tools (Python, Visual Studio C++ build tools, node-gyp) and compatible Node binaries. While advanced users can configure local environments to execute native bindings, they are not guaranteed to work across all machines or cloud runners.\n- **4. Reusing References (Performance Best Practices)**:\n - Importing packages inside scraping loops is an anti-pattern that causes severe execution overhead.\n - Recommended Practice: Declare imports once outside the loop, or store resolved module references in the global state object (`zw.state.cachedResolvedImports`) for micro-optimized access across separate JS building blocks. E.g.:\n ```javascript\n // In an early JS block:\n const cachedDayjs = await zw.import(\'dayjs@1.11.11\');\n zw.state.access().cachedResolvedImports = { dayjs: cachedDayjs };\n // In a later JS block:\n await zw.log(zw.state.access().cachedResolvedImports.dayjs().toISOString());\n ```\n- **5. Package Management APIs**:\n - `zw.packages.list()`: Returns `string[]` of all installed package IDs.\n - `zw.packages.uninstall(id: string)`: Uninstalls a specific package instance.\n - `zw.packages.uninstallAll()`: Purges all user-managed packages from disk (built-in packages remain unaffected).\n - `Package ID Structure`: `<taskbotId>_` prefix (if isolated), lower-cased sanitized package name, `@`, version/commit hash. E.g., `lodash@4.17.21` or `12345_lodash@4.17.21`.\n - `Scripting Examples`: Shows programmatic cleanup scripts filtering `zw.packages.list()` to uninstall specific versions or wipe all packages associated with a specific TaskBot ID (`id.startsWith(`${myTaskBotId}_`)`).\n- **6. Bridging Local Packages to Browser Execution**:\n - Because third-party package management operates strictly in the local Node.js background process, packages cannot be directly imported inside in-browser JS blocks.\n - Bridging Pattern: Import the package in a local JS block (`#ze-run-locally`), inject a wrapper function into the browser page context via `zw.browserContext.setDefaults()` and `context.exposeFunction()`, then call the exposed function inside a subsequent in-browser JS block. E.g.:\n ```javascript\n // Block 1 (Local execution):\n // #ze-run-locally\n import lodash from "lodash";\n await zw.browserContext.setDefaults({\n pageInit: async (page, context) => {\n await context.exposeFunction("exposedChunkFn", (arr) => lodash.chunk(arr, 2));\n }\n });\n ```\n ```javascript\n // Block 2 (Browser execution):\n const result = await exposedChunkFn([1, 2, 3, 4]); // Returns [[1,2], [3,4]]\n await zw.log("exposedChunkFn result", result);\n ```\n - `Critical Asynchronous Rule`: Functions exposed to the browser via `context.exposeFunction()` **always become asynchronous**, even if the underlying local function is synchronous. In-browser code must always invoke exposed functions using `await`.\n\n### 61. Insert Text or Data (`Insert Text Or Data.png`)\n- **Building Block Name**: `Insert Text or Data`\n- **Function**: Injects text strings or dynamic data into web input fields (form inputs, search bars, text areas). E.g., navigating to wikipedia.org and entering search queries.\n- **Modal Configuration UI & Options**:\n - `Dynamic Data References`: Click the `V` (variable) or `T` (table) icon at the top right to insert dynamic tokens. E.g., `Hi {id: 3862, name: Profile name}, let\'s connect!`.\n - `Insert instantly without typing delay`:\n - When enabled (Instant Paste): Bypasses simulated typing entirely, instantly pasting the full text string into the target field. Requires configuring a valid CSS or XPath selector to identify the input element.\n - When disabled (Simulated Typing): Simulates human typing character by character at a configurable typing speed. The selector becomes optional; if omitted, TaskBot types directly into whichever input field currently holds the active OS/browser mouse cursor focus.\n - `Using spintax`: Supports nested spintax variations to randomize outbound messaging and avoid spam filters. E.g., `{Hi|Hello|Hey|Howdy}, {how are you?|what\'s new?|how\'s everything?}`.\n - `Selector Behavior Summary`:\n - When instant paste is enabled: Selector is **mandatory**.\n - When instant paste is disabled: Selector is **optional**. E.g., on search engines like Google, DuckDuckGo, or Wikipedia, the browser automatically focuses the search input on page load, allowing TaskBots to type search queries directly without configuring a CSS selector.\n - `Encrypt Content (Secure Credentials)`: For logging into web portals directly without session cookies, users click the padlock icon to encrypt sensitive passwords. Once encrypted and saved, the password string cannot be viewed, copied, or edited. To update an encrypted password, users must delete the building block entry and re-enter the new password. ZeroWork guarantees no plain text copies of encrypted credentials are ever stored.\n- **Troubleshooting & FAQ**:\n - `Can I use the mouse cursor instead of a selector?`: Yes, but strictly when `Insert instantly without typing delay` is disabled.\n - `When I use a table reference, no data is inserted`: Occurs when the workflow lacks a dynamic loop (`Start Repeat`) configured to iterate over table rows (links to `When I Use Data from Table, No Data is Being Pulled`).\n\n### 62. Install the Agent (`Install The Agent.png`)\n- **Documentation Section**: Install the Agent (under `Getting Started`)\n- **Core Architecture**: The Desktop Agent is a lightweight, headless local background service required to execute TaskBots on the user\'s physical machine. The agent possesses no graphical user interface (GUI); it runs silently in the OS system tray/toolbar. All bot building and workflow orchestration occur via the web application at `https://creator.zerowork.io/workflows`.\n- **Step 1: Download**: Official binaries available for Mac, Windows, and Linux at `https://creator.zerowork.io/download-agent`.\n- **Step 2: OS-Specific Installation**:\n - `Mac OS`: Drag the ZeroWork Agent icon into the system Applications folder.\n - `Windows`: Execute the downloaded `.exe` installer. Confirm UAC elevation prompts and grant firewall access.\n - `Linux`: Choose `.AppImage`, `.deb`, or `.rpm` packages. Use `.deb` for Ubuntu/Linux Mint, `.rpm` for Fedora/RHEL, and `.AppImage` for universal Linux distribution compatibility.\n - `Linux Troubleshooting & Notes`:\n - For `.AppImage`, installing `AppImageLauncher` (`https://github.com/TheAssassin/AppImageLauncher`) is highly recommended for proper desktop integration.\n - If the system tray icon fails to appear after 30 seconds but the background service is verified running (accessible via `http://localhost:9990` in a browser), the desktop environment lacks `appindicator` support. Solved by installing the GNOME "Extension Manager" application and adding the `appindicator` system tray extension. Note: openSUSE distributions are not officially supported.\n- **Step 3: Activation & Background Operation**:\n - Double-click the installed agent application to initialize it. The agent icon appears in the OS tray (top-right on Mac, bottom-right on Windows).\n - Confirm OS security prompts allowing execution of software downloaded from the internet.\n - Emphasizes that the lack of an application window is entirely intentional for headless background automation.\n- **Step 4: Installation Verification**:\n - Build a basic 1-block TaskBot containing `Open Link` pointing to `https://www.wikipedia.org/`. Trigger a run. If an automated Chrome instance launches, navigates to Wikipedia, and terminates successfully, the agent is fully operational.\n - `Windows Focus Note`: On Windows OS, the automated Chrome instance might launch in the background behind active desktop windows. Users should toggle `Stay on Page after Run` in bot settings or minimize active windows to verify browser execution.\n- **Agent Options Access**: Click the tray icon to verify runtime status (`Status: Ready`) and active user account binding.\n\n### 63. Install ZeroWork Agent on VPS (`Install Zerowork Agent On Vps.png`)\n- **Documentation Section**: Install ZeroWork Agent on VPS (under `General: Run, Schedule, Share, Webhooks`)\n- **Core Capability**: Deploying the ZeroWork Desktop Agent onto a Virtual Private Server (VPS) enables 24/7 uninterrupted, automated cloud execution without requiring the user\'s local physical computer to remain powered on.\n- **Community Guide**: Features an embedded step-by-step video tutorial by CodingMenace (`Install ZeroWork Agent on Linux VPS in Minutes! (FREE SCRIPT)`), guiding users through provisioning a Linux VPS, executing an automated installation script, and verifying headless agent connectivity.\n\n\n## Batch 7: Keyboard Actions to My Taskbot Saves Some Data But Not All\n\n### 64. Keyboard Action Is Not Working As Expected (`Keyboard Action Is Not Working As Expected.png`)\n- **Documentation Section**: Common Problems -> Keyboard Action Is Not Working As Expected\n- **Core Problem**: Simulated keystrokes or keyboard shortcuts fail to produce the expected character input or trigger the desired web application event.\n- **Common Causes & Troubleshooting**:\n 1. `Missing DOM Focus`: The target web element (input field, textarea, dropdown) lacks active focus before the keystroke event is fired. Unlike direct text insertion (`Insert Text or Data` with instant paste), simulated keyboard events require the operating system/browser cursor to actively reside within the element. Solution: Add a `Click Web Element` block immediately prior to the `Keyboard Action` block to ensure focus.\n 2. `Character Encoding / Keyboard Layout Mismatches`: Emulated keystrokes rely on keycodes that can conflict with non-standard OS keyboard layouts (e.g., Dvorak, AZERTY, custom language IME). Ensure the OS keyboard layout matches standard expected input mappings during headless execution.\n 3. `Protected Web Inputs / Bot Detection`: Highly secure web portals (banking, advanced anti-bot captchas) employ JavaScript event listeners that detect synthetic `KeyboardEvent` properties (`isTrusted: false`). If synthetic events are blocked, users must utilize local Node execution (`// #ze-run-locally`) paired with OS-level macro automation libraries (e.g., `robotjs`) to simulate physical hardware-level keystrokes.\n\n### 65. Keyboard Action (`Keyboard Action.png`)\n- **Building Block Name**: `Keyboard Action`\n- **Function**: Simulates physical keyboard strokes, key combinations, and modifier shortcuts within the active browser tab.\n- **Modal Configuration UI & Capabilities**:\n - `Simulated Keystrokes`: Supports typing individual characters, strings, or invoking functional keys (`Enter`, `Tab`, `Space`, `Escape`, `Backspace`, `ArrowUp`, `ArrowDown`, `ArrowLeft`, `ArrowRight`).\n - `Modifier Key Support`: Supports chaining modifier keys (`Ctrl`, `Alt`, `Shift`, `Meta` / `Cmd`) with standard keys to execute complex web shortcuts (e.g., `Ctrl+A` to select all, `Ctrl+C` to copy, `Ctrl+V` to paste).\n - `Delay Intervals`: Configurable delay timing between individual keystrokes (measured in milliseconds/seconds) to mimic human typing cadence and bypass basic behavioral bot detection mechanisms.\n- **Workflow Patterns & Best Practices**:\n - `Form Submission`: Chaining `Insert Text or Data` followed by `Keyboard Action` (`Enter`) to submit search forms or login prompts where no explicit submit button exists.\n - `Modal Dismissal`: Sending `Escape` to close intrusive popups, cookie consent banners, or dialog overlays blocking the underlying DOM.\n - `Manual Scrolling`: Executing `Space` or `ArrowDown` inside a scraping loop to force lazy-loaded feeds to fetch new DOM nodes when automated scrolling fails.\n\n### 66. Launch Browser (`Launch Browser.png`)\n- **Building Block Name**: `Launch Browser`\n- **Function**: Explicitly initializes an automated browser instance session with granular environmental configuration. Note: If omitted, TaskBots automatically launch a default Chrome instance on run start.\n- **Modal Configuration UI & Advanced Parameters**:\n - `User-Agent String Overriding`: Allows custom `User-Agent` string configuration to spoof different operating systems, browser versions, or mobile devices (e.g., mimicking an iPhone or Safari on macOS to scrape mobile-optimized DOM structures).\n - `Proxy Configuration Settings`: Input fields to route browser traffic through dedicated proxy servers (`HTTP`, `HTTPS`, `SOCKS5`). Supports authentication credentials (`username:password@ip:port`). Essential for rotating IP addresses during high-frequency scraping runs to prevent IP bans.\n - `Viewport Dimension Controls`: Explicitly sets browser window width and height (e.g., `1920x1080`). Critical for responsive websites where DOM elements (like hamburger menus or pagination bars) change structure or visibility based on viewport resolution.\n - `Headless vs. UI Mode`: Configures whether the browser window executes visibly on the desktop or entirely hidden in the background (headless mode) to conserve CPU/RAM resources during large-scale cloud execution.\n\n### 67. Lists: Incremental CSS Selectors (`Lists Incremental Css Selectors.png`)\n- **Documentation Section**: Using Selectors -> Lists: Incremental CSS Selectors\n- **Core Architectural Concept**: The "List-Loop" paradigm. To scrape or interact with repeating elements (e.g., e-commerce product grids, search result lists, social media feeds) item by item, TaskBots require dynamic selector indexing rather than static selectors.\n- **Dynamic Indexing Syntax (`{loop_index}`)**:\n - Users replace the static integer in a CSS pseudo-class (like `:nth-child()`, `:nth-of-type()`) with the dynamic token `{loop_index}`.\n - E.g., `ul.product-list > li:nth-child({loop_index})`.\n - During runtime execution within a `Start Repeat` loop, the engine dynamically substitutes `{loop_index}` with the current loop iteration integer (`1`, `2`, `3`, `4`, etc.).\n- **Advanced Offset Configuration (`{loop_index, offset}`)**:\n - Syntax: `{loop_index, starting_number}`.\n - E.g., If the first 3 items in a list are sponsored ads and actual organic results begin at index 4, configure the selector as `ul.product-list > li:nth-child({loop_index, 4})`. On loop iteration 1, TaskBot evaluates `li:nth-child(4)`; on iteration 2, `li:nth-child(5)`.\n- **Troubleshooting & Common Mistakes**:\n - `Missing Loop`: Using `{loop_index}` outside of a `Start Repeat` block causes a fatal runtime parsing error.\n - `Brittle Parent Wrappers`: Ensure the parent container selector preceding `:nth-child()` is stable and uniquely identifies the exact list wrapper div.\n\n### 68. Local and Global State (`Local And Global State.png`)\n- **Documentation Section**: Write Javascript -> Local and Global State\n- **Core Architecture**: State management APIs allowing JavaScript building blocks to persist and share data in memory across blocks or across bot runs. All data remains strictly local to the user\'s physical machine/VPS; ZeroWork never transmits state data to cloud servers.\n- **1. Local Per-Run State (`zw.state.*`)**:\n - Scope: Ephemeral scratchpad created on run start and permanently **deleted when the run terminates**.\n - `zw.state.access()`: Returns a live mutable object for local Node context (`// #ze-run-locally`). Can hold any JavaScript type (functions, Maps, Sets, Playwright page/context instances). E.g., `zw.state.access().myHelper = () => { ... };`.\n - `zw.state.clear()`: Purges the entire run state object.\n- **2. Global State (`zw.globalState.*`)**:\n - Scope: Device-level scratchpad shared across all TaskBots running on the same Desktop Agent instance. **Persists across runs** until the Desktop Agent application is explicitly quit or restarted. E.g., caching authentication tokens or tracking cumulative daily run counts across multiple bots.\n - `zw.globalState.access()`: Returns live mutable object for local Node context.\n - `zw.globalState.clear()`: Purges global state.\n - `Persistence Warning`: Global state is NOT durable disk storage. For permanent storage, use Data Tables (`zw.setRef()`) or Device Storage (`zw.deviceStorage.*`).\n- **3. Browser Context State (`zw.state.browser.*` & `zw.globalState.browser.*`)**:\n - Scope: In-browser JS execution blocks cannot directly access the background Node memory (`*.access()`). They must utilize async JSON snapshots.\n - APIs: `await zw.state.browser.getCopy({ key?: string })` and `await zw.state.browser.commit({ state: any, key?: string })`.\n - `Serialization Constraint`: Values passed between browser and local state must be **strictly JSON-safe**. Functions, Maps, Sets, and circular DOM references cannot be serialized.\n - `Payload Size Limit`: Snapshot payloads exceeding **~3,000,000 characters** fail to transfer. Use the `key` parameter to fetch/commit only specific lightweight slices of state.\n - `Asynchronous Requirement`: All `*.browser.*` methods are asynchronous and must be invoked with `await`. E.g., `const state = await zw.state.browser.getCopy();`.\n\n### 69. Log in to the Agent (`Log In To The Agent.png`)\n- **Documentation Section**: General: Run, Schedule, Share, Webhooks -> Log in to the Agent\n- **Core Requirement**: Authentication binding between the local Desktop Agent background service and the user\'s ZeroWork cloud account. Required strictly when utilizing cloud Webhooks or the automated Scheduler. If users only trigger TaskBots manually from the web creator portal, agent login is optional.\n- **Frequency**: Needs to be performed **only once** per machine following initial installation.\n- **Authentication Workflow & UI Status**:\n - Step 1: Click the ZeroWork agent icon in the OS system tray (Mac menu bar top-right, Windows taskbar hidden icons bottom-right).\n - Step 2: Observe initial unauthenticated status: `Account: Click to login` and `Scheduler: disconnected`. Click the account line to open the web OAuth login prompt.\n - Step 3: Following successful authentication, verify active connection status: `Account: user@email.com` and `Scheduler: connected`. (The same connected status applies to Webhooks).\n\n### 70. Log (`Log.png`)\n- **Building Block Name**: `Log`\n- **Function**: Records custom text messages, debugging info, and audit trails during a TaskBot\'s runtime execution.\n- **Display & Storage Locations**:\n 1. `Real-Time Dialog`: Displayed live within the desktop `Running TaskBots` overlay window (e.g., `AGENT: Starting run for TaskBot... Log - building block id 19220: "This is the current counter: 1"`).\n 2. `Run Reports Dashboard`: Permanently archived in the web portal under `TaskBot Run Reports`, providing full historical audit logs with filtering (`Only show warnings and errors`) and CSV export capabilities (`Export csv`).\n- **Block Configuration & Dynamic Variables**:\n - Supports embedding dynamic variable or table tokens directly into the log string. E.g., `Current scraping target: {id: 102, name: Company Name}, iteration {id: 55, name: loop_index}`.\n - `Empty Message Behavior`: If the block is left entirely blank, TaskBot logs a generic warning but execution continues uninterrupted; the run status is NOT marked as failed.\n\n### 71. Metadata (`Metadata.png`)\n- **Documentation Section**: Write Javascript -> Metadata\n- **Core Capability**: Programmatic JavaScript APIs allowing JS building blocks to inspect active runtime environment details, TaskBot configuration, and data schema definitions.\n- **1. `zw.getAgentInfo()`**:\n - Returns synchronous object containing the local Desktop Agent binary version: `{ version: string }` (e.g., `{ version: "1.1.72" }`). Available synchronously across both local Node and browser JS contexts.\n- **2. `zw.getTaskbotInfo()`**:\n - Returns detailed runtime metadata object:\n ```typescript\n {\n id: number,\n name: string, // TaskBot name\n runType: "immediate" | "scheduled" | "webhook",\n currentRunResult: "success" | "warning" | "error" | "man.stopped",\n variables: { ref_id: number, variableNames: string[] },\n tables: Array<{\n ref_id: number,\n type: "G_SHEETS" | "ZW_NATIVE",\n columnNames: string[]\n }>,\n webhookURL: string | null\n }\n ```\n - Context Behavior: `async` (requiring `await`) in browser JS blocks; `sync` in local Node blocks (`// #ze-run-locally`). E.g., `const info = await zw.getTaskbotInfo();`.\n- **Workflow Scripting Examples**:\n - `Branching by Run Type`: `if (info.runType === "scheduled") { await zw.log("Executing unattended scheduled job"); }`.\n - `Filtering Tables by Type`: `const gSheets = info.tables.filter(t => t.type === "G_SHEETS");`.\n - `Dynamic Webhook Chaining`: Extracting `info.webhookURL` and storing it in `zw.globalState.access()` to allow subsequent TaskBots to programmatically trigger this bot via `axios.post(webhookURL)`.\n- **Critical Distinction**: Metadata returns table/variable **schema names** (column headers and variable names), NOT the underlying data values. To retrieve actual data values, scripts must use `zw.getRef()`.\n\n### 72. My TaskBot Does Not Start Run (`My Taskbot Does Not Start Run.png`)\n- **Documentation Section**: Common Problems -> My TaskBot Does Not Start Run\n- **Core Problem**: Clicking the `Run` button in the web creator portal fails to initialize the automation workflow on the local machine.\n- **Comprehensive Root Causes & Solutions**:\n 1. `Outdated Agent Version`: The Desktop Agent binary is deprecated. Verify version in agent tray menu and update via `creator.zerowork.io/download-agent`.\n 2. `Expecting a GUI`: Users mistakenly wait for an agent application window to open. The agent is strictly headless and runs silently in the OS system tray.\n 3. `Hidden Background Windows`: The automated Chrome instance launched successfully but minimized or opened in the background behind active desktop windows. Toggling `Stay on Page after Run` helps verify visual execution.\n 4. `Missing Chrome Installation`: TaskBots rely entirely on the local Google Chrome Chromium engine. Chrome MUST be installed on the OS, regardless of which browser (Safari, Brave, Firefox) is used to access the web creator portal.\n 5. `Browser Shields & Ad Blockers`: The web workflow builder communicates with the local Desktop Agent via local loopback requests (`localhost` / `127.0.0.1`). Strict browser shields (e.g., Brave Shields, advanced ad blockers) intercept and block these local websocket/HTTP connections as "insecure". Solution: Whitelist `creator.zerowork.io` or disable shields.\n 6. `Agent Inactive / Not Installed`: The background daemon is stopped. Double-click the ZeroWork application icon to start the background process.\n 7. `Immediate Workflow Parsing Errors`: The bot actually initialized but aborted instantly due to fatal structural errors (e.g., unconfigured mandatory selectors, invalid loop hierarchies). Inspect Run Reports for stack traces.\n- **OS & Security Level Blockers**:\n - `VPN / Firewall Interference`: Virtual Private Networks or strict firewalls blocking internal loopback ports (`localhost:9990`). Temporarily disable VPN/firewall to isolate.\n - `Antivirus / Windows Smart App Control`: Aggressive AV heuristics or Windows Defender `Reputation-based protection` blocking background automation executables. Solution: Navigate to Windows Security -> App & browser control -> Turn off Reputation-based protection or add an explicit exclusion for the ZeroWork agent binary.\n\n### 73. My TaskBot Saves Some Data but Not All (`My Taskbot Saves Some Data But Not All.png`)\n- **Documentation Section**: Common Problems -> My TaskBot Saves Some Data but Not All\n- **Core Problem**: A scraping workflow successfully captures a subset of target data (e.g., 1 row, or 15 items) but fails to extract the complete dataset across pagination or infinite scrolls.\n- **Root Causes & Architectural Fixes**:\n 1. `Saves Only One Result Per Page (Missing Nested Loops)`: The workflow lacks a proper multi-level loop hierarchy. Scraping paginated lists requires an outer loop (`Start Repeat` for pagination next-button clicks) wrapping an inner loop (`Start Repeat` iterating over `{loop_index}` list items). Refer to `Nested Loops - Handle Pagination`.\n 2. `Saves Only First 10-20 Results (Infinite Scroll / Lazy Loading)`: Modern web applications (LinkedIn, Instagram, e-commerce feeds) do not render the entire DOM on initial page load; new DOM nodes are appended only when the user scrolls near the bottom of the viewport. If ZeroWork\'s built-in auto-scroll fails to trigger the lazy-load event, inject a `Keyboard Action` block (`Space` or `ArrowDown`) inside the scraping loop to force DOM rendering. Refer to `TaskBot Does Not Automatically Scroll`.\n 3. `Saves Data to Just One Row (Missing Loop Entirely)`: The workflow contains `Save Web Element` but completely lacks a `Start Repeat` block. Without a loop, TaskBot executes the save action exactly once, populating only row 1 of the data table.\n\n### 74. Native Tables (`Native Tables.png`)\n- **Documentation Section**: Using Tables -> Native Tables\n- **Core Concept**: ZeroWork\'s built-in tabular data storage system (`ZW_NATIVE`), designed for storing structured scraping results or feeding dynamic input rows into workflows without requiring external Google Sheets integration.\n- **Creation Workflow & UI Elements**:\n - Step 1: Navigate to the `Tables` sidebar panel and click `Add new table`.\n - Step 2: In the `Add Table` modal, select the table type (e.g., `Create ZeroWork table with custom columns`) and input a descriptive `Enter table title`.\n - Step 3: Define schema columns under `COLUMNS` by entering headers (`My column`, `Another column`). Use `ADD ANOTHER COLUMN` to expand schema, then click `ADD TABLE`.\n- **Lifecycle & Refactoring Behaviors**:\n 1. `Automatic Schema Propagation`: Editing a column name in a native table automatically updates all corresponding building block references across the entire workflow. No manual re-mapping is required.\n 2. `Column / Table Deletion Handling`: Deleting a referenced column or removing the table entirely automatically unbinds those references from standard building blocks.\n 3. `JavaScript Block Exception`: In `Write Javascript` building blocks, existing `setRef()` and `getRef()` calls remain in the code body, but the deleted column name argument is automatically renamed/flagged as `"INVALID"` (e.g., `zw.getRef("INVALID")`), alerting developers to update the script.\n 4. `Google Sheets Conversion`: Native tables can be seamlessly converted to external Google Sheets at any point in the project lifecycle (refer to `Convert Native Table to a Google Sheet`).\n\n### 75. Nested Loops - Handle Pagination (`Nested Loops Handle Pagination.png`)\n- **Documentation Section**: Using Building Blocks -> Start Repeat -> Nested Loops - Handle Pagination\n- **Core Concept**: Establishing a multi-level loop hierarchy (an inner loop encapsulated within an outer loop) to systematically execute multi-page scraping workflows (e.g., paginated search results on LinkedIn).\n- **Architectural Setup (Example: 30 Pages x 10 Profiles = 300 Total Results)**:\n 1. `Initial Navigation`: An `Open Link` block navigates to the target search results URL.\n 2. `Outer Loop (Main Loop - Pagination)`: A `Start Repeat` block configured as `Standard` loop type, with `Auto-detect number of available elements` unchecked, and `Enter number of repetitions` set to `30` (representing 30 pages).\n 3. `Inner Loop (Nested Loop - List Items)`: Inside the Main Loop, a second `Start Repeat` block is placed. Configured as `Standard` loop type with `Enter number of repetitions` set to `10` (representing 10 profile items per page). This loop encapsulates the core scraping actions (e.g., `Save Web Element`).\n 4. `Inner Loop Exit Node`: Immediately following the inner loop\'s scraping blocks, an `After Repeat` block is placed. This block serves as the explicit exit boundary of the nested loop.\n 5. `Pagination Transition`: Connected directly to the `After Repeat` block is a `Click Web Element` block targeting the pagination "Next" button.\n- **Workflow Execution Cycle**:\n - The TaskBot enters the Main Loop on Page 1.\n - It enters the Nested Loop, iterating exactly 10 times to harvest 10 profile elements.\n - Upon completing 10 iterations, execution transitions through `After Repeat` to the `Click Web Element` block, clicking "Next" to load Page 2.\n - The Main Loop repeats this entire sequence 30 times, successfully accumulating 300 records.\n\n### 76. No Selector Is Found (`No Selector Is Found.png`)\n- **Documentation Section**: Common Problems -> No Selector is Found\n- **Core Problem**: A building block fails during runtime execution because the configured CSS or XPath selector cannot be located within the active browser DOM.\n- **Comprehensive Root Causes & Troubleshooting**:\n 1. `Asynchronous Rendering / Page Load Latency`: The building block attempts to evaluate the selector before the target web element has fully rendered in the DOM.\n - *Critical Solution Nuance*: Increase the delay interval on the building block that **precedes** the failing block, NOT on the failing block itself. The delay must execute *before* the engine attempts DOM querying.\n 2. `Dynamic / Brittle Selectors`: The copied selector contains auto-generated dynamic class names or IDs that mutate on every page load (frequent in modern SPAs like LinkedIn, Facebook, and Google Maps). Solution: Construct robust custom selectors utilizing stable semantic attributes (e.g., `data-test-id`, `aria-label`, `type`, or partial attribute matching `[class*=\'stable-prefix\']`). Refer to `How to Build Custom Selectors`.\n 3. `Transient DOM State Discrepancy`: If a `Check Web Element` block successfully identifies the selector but the immediately following action block (e.g., `Click Web Element`) fails to find it, the DOM may have re-rendered, detached, or refreshed the node between block executions. Refer to `Check Web Element Identifies Selector As Found but Next Action Does Not`.\n- **Masterclass Resource**: For deep-dive training, developers are referred to Elias Van Laere\'s 2-hour video tutorial (`CSS Selectors for AI Money: ZeroWork 2-Hour Masterclass for Complete Beginners`).\n\n### 77. Number Operations (`Number Operations.png`)\n- **Documentation Section**: Using Building Blocks -> Number Operations\n- **Core Function**: Performs mathematical calculations, numeric formatting, decimal precision adjustments, and string concatenation on workflow variables or table data.\n- **Empty Value Behavior**: If the input value to apply the operation on is empty, the TaskBot gracefully skips the calculation without throwing an error and continues its run.\n- **Supported Operations & Use Cases**:\n 1. `Add`: Combines two numbers (`1 + 1 -> 2`) OR concatenates two strings (`"hello" + " world" -> "hello world"`). Use Case: Maintaining an incremental counter variable to limit the volume of DMs sent per run.\n 2. `Subtract`: Subtracts one number from another (`5 - 3 -> 2`).\n 3. `Multiply`: Multiplies two numbers (`4 * 3 -> 12`). Use Case: Standardizing currency or unit conversions.\n 4. `Divide`: Divides one number by another (`10 / 2 -> 5`).\n 5. `Remainder %`: Performs modulo arithmetic (`13 % 5 -> 3`).\n 6. `Round`: Rounds a float to the nearest whole number (`2.6 -> 3`).\n 7. `Round up`: Mathematical ceiling equivalent (`2.2 -> 3`).\n 8. `Round down`: Mathematical floor equivalent (`2.7 -> 2`).\n 9. `Get random number`: Generates a random floating-point number within a specified min/max range (e.g., Min 1, Max 5 -> `3.45`). Default range if omitted: `0` to `1,000,000,000`.\n 10. `Set decimals`: Truncates or pads a number to a fixed decimal precision (`5 -> 5.00`, `5.5333 -> 5.53`).\n 11. `Remove formatting`: Strips commas or grouping dots from scraped numeric text to produce a clean float. Essential prerequisite before performing arithmetic or logical comparisons (`>`, `<`). E.g., `1.000.000,23` (dot-grouped) -> `1000000.23`; `1,000,000.23` (comma-grouped) -> `1000000.23`. *Error Condition*: If the input has an unrecognized/corrupted format (e.g., `1,000.000.23`), an error report is generated.\n- **Additional Exception Handling**:\n - If the secondary operand (e.g., value to add/subtract) is missing, the operation is skipped without modifying the original value.\n - If the operation requires a valid number (any operation except `Add`) and the input is a non-numeric string, TaskBot generates an error report and halts the run.\n\n### 78. One Element Can Have Many Selector Expressions (`One Element Can Have Many Selector Expressions.png`)\n- **Documentation Section**: Using Selectors -> How to Build Custom Selectors -> One Element Can Have Many Selector Expressions\n- **Core Concept**: A single web element in the DOM can be targeted by multiple valid CSS selector variations. The objective is selecting the most robust, non-brittle expression that withstands future website UI updates.\n- **Example Variations (Wikipedia Search Button)**:\n - `button[class=\'pure-button pure-button-primary-progressive\'][type=\'submit\']` (Valid, but brittle)\n - `button[type=\'submit\']` (Highly robust)\n - `button[class=\'pure-button pure-button-primary-progressive\']` (Brittle)\n - `button[class*=\'button\'][type=\'submit\']` (Highly robust)\n - `button[class*=\'button\']` (Too generic)\n - `button[class][type]` (Too generic)\n- **Selector Best Practices & Robustness Evaluation**:\n 1. `Lean & Short`: Shorter selectors with fewer chained attributes are less prone to breaking when developers modify secondary utility classes. E.g., targeting exact compound classes like `pure-button pure-button-primary-progressive` is overly brittle.\n 2. `Avoid Cryptic / Auto-Generated Strings`: Class names containing random alphanumeric hashes (common in Tailwind, CSS modules, or scoped frameworks) mutate frequently. Rely on stable semantic attributes (`type=\'submit\'`, `aria-label`, `data-test-id`).\n 3. `Avoid Overly Generic Attributes`: Selectors like `button[class*=\'button\']` or `button[class][type]` are too broad and risk matching multiple unintended buttons on the page, failing the TaskBot uniqueness check.\n 4. `Avoid Strict Hierarchy`: Overusing direct child combinators (`div > span > button`) makes the selector highly brittle if a wrapper `div` is added or removed. Prefer descendant combinators (`div button`) or direct attribute targeting.\n\n### 79. Open Link (`Open Link.png`)\n- **Documentation Section**: Using Building Blocks -> Open Link\n- **Core Function**: Opens a specified URL in the active Chromium browser tab. Supports static URLs (e.g., `https://www.linkedin.com/`) or dynamic variable/table tokens (e.g., `{id: 3862, name: link}`).\n- **Modal Configuration UI**:\n - `Enter link`: Input field for the destination URL.\n - `min sec` / `max sec`: Configurable delay range before executing the navigation.\n - `Open in a new tab`: Checkbox option to spawn a new browser tab instead of navigating within the current tab.\n - *Crucial Background Tab Behavior*: When `Open in a new tab` is checked, the new tab spawns in the **background** (physical OS UI focus remains on the original tab). The TaskBot engine automatically switches its internal execution context to the new tab and operates perfectly in the background. If the user wants to visually observe the bot\'s actions in the new tab, they must manually click the tab in the GUI or add a `Switch or Close Tab` building block to bring it to the front.\n- **Website Network Errors & Exception Handling**:\n - If the destination URL cannot be reached (DNS failure, invalid URL, timeout, proxy failure), TaskBot halts the run and generates an error report containing the underlying Chromium network error code (e.g., `ERR_NAME_NOT_RESOLVED`, `ERR_CONNECTION_TIMED_OUT`).\n - Developers are advised to inspect `chrome://network-errors/` or verify local VPN/antivirus/proxy configurations if network errors persist.\n- **Relevant FAQ**:\n 1. `How do I make TaskBot log in to my account when it opens a website?`: Refer to `Cookies` (session cookie injection).\n 2. `When I use a table reference, I get an error that there was no url`: Refer to `When I Use Data from Table, No Data is Being Pulled`.\n\n### 80. Proxies (`Proxies.png`)\n- **Documentation Section**: General: Run, Schedule, Share, Webhooks -> Proxies\n- **Core Capability**: Routing TaskBot browser traffic through dedicated proxy servers to prevent IP rate-limiting, CAPTCHA triggers, or geographic blocking during automated scraping runs.\n- **Step 1: Gathering Proxy Credentials**:\n - Requires obtaining Proxy IP, Port, Username, and Password from a proxy provider dashboard (e.g., HighProxies, IPRoyal). If the proxy uses IP whitelisting without authentication, username and password fields are left blank.\n - **Critical Formatting Rules for Proxy Address**:\n - Must be formatted strictly as `IP:PORT` (separated by a colon).\n - E.g., `194.32.225.238:21261` (Valid).\n - E.g., `194.32.225.238` (Invalid - missing port).\n - E.g., `194.32.225.238.21261` (Invalid - separated by dot instead of colon).\n - **SOCKS5 Proxy Protocol**:\n - SOCKS5 proxies must include the explicit protocol prefix: `socks5://<your_proxy_ip>:<port>` (e.g., `socks5://194.32.225.238:3128`).\n- **Step 2: TaskBot Settings Configuration UI**:\n - Click the `Settings` gear icon in the top right of the TaskBot builder canvas.\n - Scroll down to the `Proxy (Advanced)` section and click `Add proxy`.\n - Populate input fields: `Proxy ip address and port (enter as IP:PORT)`, `Proxy username`, `Proxy password`. Click `SAVE`.\n\n### 81. Quit Browser (`Quit Browser.png`)\n- **Documentation Section**: Using Building Blocks -> Quit Browser\n- **Core Function**: Explicitly closes the active Chromium browser instance utilized by the TaskBot.\n- **Default Lifecycle Context**: By default, TaskBot automatically closes the browser when a run finishes. `Quit Browser` is only necessary if the user wants to terminate the browser mid-run, or if `Stay on page after run` was enabled in `Browser Launch Settings` / `Launch Browser` block.\n- **Configuration Option**:\n - `Force quit` checkbox: When checked, forcefully terminates the browser instance immediately, overriding shared profile rules.\n - *Critical Warning*: If `Force quit` is enabled on a browser instance utilizing a shared "sticky profile" (a persistent user data directory shared across concurrent TaskBots), it will forcefully terminate the browser for ALL TaskBots currently using that sticky profile, not just the current TaskBot!\n- **Behavioral Nuances & Things to Know**:\n 1. `No Browser Context Handling`: If `Quit Browser` executes when no browser is open, it does not throw a fatal error. It logs a warning to the run report and seamlessly continues execution.\n 2. `Sticky Profile Shared Respect (Default)`: If `Force quit` is NOT checked, `Quit Browser` will close the current TaskBot\'s tabs but leave the underlying browser process running if other TaskBots are actively sharing the sticky profile. The browser process fully terminates only when the last TaskBot leaves.\n 3. `Overrides Stay on Page`: `Quit Browser` overrides any `Stay on page after run` configuration.\n 4. `Relaunch Capability`: Placing an `Open Link` or `Launch Browser` block after a `Quit Browser` block will successfully initialize a fresh, clean browser context.\n\n### 82. Raise Error (`Raise Error.png`)\n- **Documentation Section**: Using Building Blocks -> Raise Error\n- **Status**: "This page is upcoming. Stay tuned!"\n- **Workflow Context**: Utilized within advanced logic flows (often paired with `Try-Catch` or conditional validation blocks) to intentionally throw a custom exception, halting execution or triggering designated error recovery pathways.\n\n### 83. Record Date (`Record Date.png`)\n- **Documentation Section**: Using Building Blocks -> Record Date\n- **Core Function**: Generates a dynamic calendar date or timestamp based on user specifications and saves it to a designated data table column or runtime variable.\n- **Example / Use Case (Auto-Follow-Up Campaigns)**:\n - When sending an initial outreach message on LinkedIn, use `Record Date` to log the exact execution date (e.g., `01.01.2023`) into a table column named `Date of 1st message`.\n - On subsequent runs, pair this with `Start Condition and Set Condition` -> `Before (Date) & After (Date)` comparisons to automatically determine if the required wait window (e.g., 3 days) has elapsed before triggering the follow-up message.\n- **Modal UI Configuration**:\n - `Select date format`: E.g., `Whole date`, `Format: DD.MM.YYYY`.\n - `Select date`: E.g., `Today`.\n - `Weekend`: E.g., `Include weekend` (or exclude weekend calculation).\n - `Save to`: E.g., `Select variable or data table` -> `Variables` -> `last run date`.\n\n### 84. References To Variables And Tables (`References To Variables And Tables.png`)\n- **Documentation Section**: Using Building Blocks -> Dynamic Inputs -> References to Variables and Tables\n- **Core Concept**: Injecting dynamic tokens referencing runtime variables or data table columns into building block input fields (e.g., `Send Notification`, `Insert Text or Data`, `Open Link`).\n- **UI Interaction**:\n - Click the `V` icon (for variables) or `T` icon (for tables) located at the top right of the building block modal configuration window.\n - Selecting an item from the dropdown injects a structured token into the input field: `{id: 113251, name: email_subject}`.\n- **Behavioral Nuance**:\n - The token structure contains both an internal numeric `id` and the human-readable `name`. This ensures that if the variable or column is renamed elsewhere in the project, the underlying `id` maintains the binding intact.\n\n### 85. Remote Cloud Execution (`Remote Cloud Execution.png`)\n- **Documentation Section**: General: Run, Schedule, Share, Webhooks -> Remote (Cloud) Execution\n- **Status**: *Upcoming*\n- **Core Concept**: Offloading TaskBot runs from the local Desktop Agent to ZeroWork\'s managed cloud infrastructure.\n- **Pricing & Billing Model**: Billed on a pay-per-cloud-credit cost structure.\n- **Alternative**: Currently, users requiring 24/7 unattended execution without keeping their personal computer online utilize a Virtual Private Server (VPS). Refer to `Install ZeroWork Agent on VPS`.\n\n### 86. Remove Duplicates (`Remove Duplicates.png`)\n- **Documentation Section**: Using Building Blocks -> Remove Duplicates\n- **Core Function**: A batch operation that scans a data table and removes duplicate rows based on a specified column.\n- **Best Practice & Performance Optimization**:\n - Developers should *always* specify a specific column to evaluate for duplicates (e.g., `Profile link` or `Email`), rather than evaluating entire multi-column rows. Specifying a column significantly improves TaskBot execution speed.\n - *Exclusion*: Files stored in `file` columns are automatically ignored when searching for duplicates.\n- **Deduplication Direction & Preservation Logic**:\n - `Default Behavior`: TaskBot removes the newest (latest appended) duplicate rows and preserves the oldest (first scraped) row.\n - `Preserve newest rows` checkbox: Reverses this behavior, deleting older duplicate rows and keeping the latest entry.\n - *Critical Limitation*: The `Preserve newest rows` option is supported **only in native tables (`ZW_NATIVE`)**; it is NOT available for external Google Sheets.\n- **Architectural Placement Warning (`Do Not Place Inside Loops`)**:\n - `Remove Duplicates` is a **batch operation**. It fetches all table rows into memory and deduplicates the entire table at once.\n - Placing this block inside a scraping loop (`Start Repeat`) is highly inefficient and redundant. Furthermore, if placed inside a loop, the engine\'s internal deduplication lock ensures duplicates will only be removed on the *first* iteration of the loop, ignoring subsequent iterations.\n - *Correct Placement*: Place `Remove Duplicates` after the `After Repeat` block (outside the loop entirely) as a post-processing cleanup step.\n\n### 87. Remove Words (`Remove Words.png`)\n- **Documentation Section**: Using Building Blocks -> Format Data -> Remove Words\n- **Core Function**: Strips specified unwanted words or character substrings from scraped text stored in variables or tables.\n- **Configuration & Delimiter**:\n - Multiple target words/strings must be entered separated by a comma.\n - E.g. `Words to remove`: `Ms., Mr., Mrs., PhD, MBA`.\n - Example Transformation:\n - Input: `AI scientist and PhD candidate Ms. Fina Fedora`\n - Output: `AI scientist and candidate Fina Fedora` (successfully stripped `PhD` and `Ms.`).\n- **Critical Limitation (Comma Stripping)**:\n - Because commas `,` are utilized by the engine as the explicit delimiter separating multiple target words in the input field, `Remove Words` **cannot be used to remove commas themselves**.\n - *Workaround*: To strip commas from text (e.g. cleaning formatted numbers or addresses), developers must use the `Replace text` building block, configuring the target as `,` and leaving the replacement value entirely empty.\n\n### 88. Run In Background (`Run In Background.png`)\n- **Documentation Section**: General: Run, Schedule, Share, Webhooks -> Run Settings -> Run in Background\n- **Core Concept**: Headless browser execution toggle. When enabled, TaskBot runs entirely in the background, hiding the automated Chromium browser window from the OS desktop GUI.\n- **Configuration UI**: Click the `Settings` gear icon in the top right of the TaskBot canvas -> under `Run Behavior`, toggle the `Run in background` switch.\n- **Lifecycle & Testing Best Practices**:\n - `During Building / Testing`: Keep `Run in background` **disabled**. Watching the physical browser window execute actions live is essential for debugging selectors, verifying click targets, and ensuring expected page transitions.\n - `Production / Unattended Runs`: Once reliability is verified, enable `Run in background`. Users can monitor background activity via the desktop `Running TaskBots` live log overlay or by reviewing web `Run Reports`.\n - `Multi-Monitor Preference`: Some users with multiple monitors prefer keeping `Run in background` disabled even in production, parking the automated browser window on a secondary display while working on their primary display.\n\n### 89. Run Settings (`Run Settings.png`)\n- **Documentation Section**: General: Run, Schedule, Share, Webhooks -> Run Settings\n- **Core Concept**: Overview index page grouping the three primary runtime behavior toggles available in the TaskBot settings modal:\n 1. `Run in Background` (Headless mode)\n 2. `Stay on Page after Run` (Preserving browser window for post-run inspection)\n 3. `Bring Pages to Front` (Forcing browser window focus over active desktop applications)\n\n### 90. Run (`Run.png`)\n- **Documentation Section**: General: Run, Schedule, Share, Webhooks -> Run\n- **Core Concept**: Initiating TaskBot execution. Clicking `Run` commands the local Desktop Agent to spawn a fresh Chromium browser window and execute the configured automation steps.\n- **Trigger UI Locations**:\n 1. `Inside Workflow Builder`: Clicking the green `Play` icon in the top toolbar.\n 2. `TaskBots Dashboard List`: Clicking the green `Play` button directly on a TaskBot list item row.\n- **Real-Time Display Overlay**:\n - Each time a run initiates, a live status overlay window titled `Running TaskBots` appears in the bottom right of the screen. E.g. displaying real-time logs: `Inserted "Lorem ipsum..."`, `Nov 20, 2023, 4:16:28 PM`, `Loop iteration 2 starts`.\n- **FAQ & Concurrency Limits**:\n - `How many TaskBots can I run in parallel at the same time?`:\n - Users can run multiple TaskBots concurrently as long as local hardware resources (CPU/RAM) permit. On a standard Mac/PC, users typically run between **5 to 20 concurrent TaskBots** simultaneously.\n - `Troubleshooting: TaskBot does not run`: Refer to `My TaskBot Does Not Start Run`.\n\n### 91. Save File (`Save File.png`)\n- **Documentation Section**: Using Building Blocks -> Save File\n- **Core Function**: Downloads binary files (images, PDFs, CSVs) from web pages to the local OS filesystem or stores file URLs/paths in variables/tables.\n- **File Source Options**:\n 1. `From file url`: Used when the developer has a direct static or scraped URL to the file (e.g. `https://wallpaperaccess.com/full/2656.jpg`). Requires providing `Enter file url` and `Save file to folder` (local absolute directory path like `/Users/username/Downloads/`).\n 2. `From download action`: Used when the file download is initiated by clicking a web element (e.g. `Click Web Element` targeting a "Download CSV" button).\n - *Crucial OS Dialog Nuance*: When downloading via a click action, the native OS "Save As" system dialog window is **suppressed / not visible**. The TaskBot engine intercepts the Chromium download stream and handles the file transfer entirely behind the scenes.\n - *Saving Options*:\n - `Save file url to a variable or table`: Captures the underlying download URL into a variable/table.\n - `Save file to local folder`: Writes the binary file to the specified absolute directory path.\n- **File Options (Advanced Preferences)**:\n - `Make file name unique on conflict`: Toggling this switch appends a random numeric ID to the filename if a file with the identical name already exists in the destination folder (e.g. `file_name_6354736148.png`). If untoggled, existing files are overwritten.\n - `File name (optional)`: Allows developers to specify a custom filename (e.g. `my_pic_name.png`).\n - `Save full file path (optional)`: Captures the absolute local OS path of the downloaded file (e.g. `/Users/username/Downloads/my_pic_name.png`) into a variable or table. Essential prerequisite for chaining with `Upload File` blocks later in the workflow.\n- **Critical Data Type Warning (`Note: Save file building block only saves url or path`)**:\n - Developers can only save the file URL or absolute file path to a **standard text column / variable**.\n - They **cannot** save the URL/path to a `file` type column or variable. This is because `file` type columns expect the actual physical binary file object, whereas `Save File` outputs string paths/URLs.\n\n### 92. Save From Clipboard (`Save From Clipboard.png`)\n- **Documentation Section**: Using Building Blocks -> Save from Clipboard\n- **Core Function**: Captures the current content of the OS clipboard and stores it into a specified variable or data table column.\n- **Workflow Example (LinkedIn Post Link Extraction)**:\n 1. Use `Click Web Element` targeting `text="Copy link to post"`. This native web action copies the URL into the OS clipboard.\n 2. Follow immediately with `Save from Clipboard`, configuring the destination table/column (e.g. `Profiles` -> `Profile link`).\n- **Critical Concurrency & Isolation Warning (`Note that there is no clipboard isolation between TaskBots`)**:\n - The OS clipboard is a **global system resource**. There is **no clipboard isolation** between concurrently running TaskBots.\n - While the time between a click copying text and `Save from Clipboard` reading it is typically mere milliseconds, running multiple TaskBots in parallel that all heavily rely on clipboard operations introduces a severe race condition risk.\n - *Risk*: Clipboard contents can get overwritten or mixed up across separate TaskBot instances executing simultaneously.\n - *Best Practice*: For workflows relying on clipboard scraping, limit concurrent execution or utilize direct element scraping (`Save Web Element`) where possible.\n\n### 93. Save Lists (`Save Lists.png`)\n- **Documentation Section**: Using Building Blocks -> Save Web Element -> Save Lists\n- **Core Concept**: Extracting repeating lists of elements (e.g. search results, product feeds) by combining a `Start Repeat` loop with dynamic selector indexing.\n- **Workflow Architecture**: `Open Link` -> `Start Repeat` -> `Save Web Element` -> `After Repeat`.\n- **Loop Index Injection (`{loop_index}`)**:\n - To target each sequential item in a list during iteration, developers must inject `{loop_index}` into the CSS/XPath selector within `Save Web Element`.\n - Example CSS Selector: `#profile-link:nth-child({loop_index:1})`.\n - *Behavior*: On loop iteration 1, it evaluates `#profile-link:nth-child(1)`. On iteration 2, `#profile-link:nth-child(2)`, and so on.\n- **FAQ & Common Patterns**:\n - `Data Overwriting`: Scraped data is *always appended* by default. If a developer wants fresh data to overwrite old data on every run, they must place a `Delete Data` block *before* the loop starts.\n - `Deduplication`: Place `Remove Duplicates` *after* the loop (`After Repeat`) finishes.\n - `Pagination`: Requires `Nested Loops` (outer loop for pages, inner loop for items).\n - `Scrolling`: Built-in auto-scrolling logic handles most dynamic loading. However, if auto-scroll fails on complex infinite-scroll sites, developers must supplement with a `Keyboard Action` block sending `Space` or `Arrow Down` keystrokes.\n\n### 94. Save Page URL (`Save Page Url.png`)\n- **Documentation Section**: Using Building Blocks -> Save Page URL\n- **Core Function**: Captures the active, fully resolved URL of the web page currently loaded in the active browser tab.\n- **Use Case**: Essential for tracking navigation state, logging redirect destinations, or capturing profile URLs after clicking a generic link.\n- **Configuration**: Simply select the destination variable or data table column (e.g. `Variables` -> `Current url`).\n\n### 95. Save Web Element (`Save Web Element.png`)\n- **Documentation Section**: Using Building Blocks -> Save Web Element\n- **Core Function**: Core scraping block used to extract public text, links, or attributes from targeted web elements and save them into data table columns or variables.\n- **Primary Use Case Categories**:\n 1. `Saving Lists`: Extracting repeating arrays of items (e.g. LinkedIn profile search results, Facebook group members, Amazon product feeds). Refer to `Save Lists`.\n 2. `Enriching Existing Data`: Iterating over an existing list of URLs (e.g. visiting individual LinkedIn profile pages or Amazon product detail pages) to extract deeper, granular attributes (e.g. about section, job position, email, price, reviews). Refer to `Enrich Existing Data`.\n\n### 96. Scheduler (`Scheduler.png`)\n- **Documentation Section**: Using ZeroWork -> General: Run, Schedule, Share, Webhooks -> Scheduler\n- **Core Function**: Configures automated, recurring unattended execution of TaskBots at specific time intervals or schedules.\n- **Scheduling Modes**:\n 1. `Frequency`: Fixed periodic intervals (e.g., Every `X` minutes, hours, days, weeks, or months).\n 2. `Cron Expression`: Advanced, granular scheduling using standard Cron syntax (e.g., `0 9 * * 1-5` for 9:00 AM Monday through Friday).\n- **Execution Environment & Cloud Dependencies**:\n - `Desktop Agent Requirement`: For locally hosted runs, the user\'s computer must remain powered on, awake (not in sleep/hibernation mode), and the ZeroWork Desktop Agent must be actively running in the background.\n - `Cloud Runs`: For TaskBots deployed to ZeroWork Cloud Execution, schedules run entirely in the cloud without requiring the local machine or Desktop Agent to be active.\n\n### 97. Select Web Dropdown (`Select Web Dropdown.png`)\n- **Documentation Section**: Using Building Blocks -> Select Web Dropdown\n- **Core Function**: Selects a specific `<option>` within a native HTML `<select>` dropdown menu element.\n- **Critical HTML Tag Requirement & Troubleshooting (`Invalid Dropdown Workaround`)**:\n - `Select Web Dropdown` works **exclusively with native HTML `<select>` elements**. The target element in the DOM must have `<select>` as its tag name, containing child `<option>` tags.\n - `Invalid Dropdown Workaround`: Many modern web applications (e.g., LinkedIn, custom React/Vue UI libraries) implement visual dropdown menus using `<div>`, `<span>`, or `<button>` elements styled to look like dropdowns. `Select Web Dropdown` will **fail** if targeted at these non-`<select>` elements.\n - *Correct Approach for Custom Dropdowns*: To interact with custom `<div>`/`<button>` dropdowns, developers must use a two-step `Click Web Element` sequence:\n 1. `Click Web Element` targeting the outer dropdown trigger button/div to open the menu.\n 2. `Click Web Element` targeting the specific menu item div/span to select the desired option.\n- **UI Configuration**:\n - `Enter dropdown option`: Enter the exact text value of the option to select (e.g., `Badminton`), or inject a dynamic variable/table reference (e.g., `{id: 3607, name: Dropdown option}`).\n - `Enter CSS or XPath selector of the dropdown`: Enter the selector identifying the `<select>` element (e.g., `select[class=\'custom-select\']`).\n\n### 98. Send Notification (`Send Notification.png`)\n- **Documentation Section**: Using Building Blocks -> Send Notification\n- **Core Function**: Dispatches an automated email notification directly to the email address associated with the user\'s ZeroWork account.\n- **Recipient Limitation & Workaround (`IMPORTANT Alert`)**:\n - The email is sent **exclusively to the ZeroWork account owner\'s registered email address**. It cannot be configured to send emails to arbitrary third-party recipients (e.g., clients, scraped leads).\n - *Workaround*: To send emails to external recipients, developers must use the `APIs: Send HTTP Request` building block to integrate with third-party email service APIs (e.g., SendGrid, Mailgun, Make.com webhook).\n- **Configuration Fields**:\n 1. `Subject`: Plaintext email subject line.\n 2. `Email notification content`: The body of the email. Supports plaintext or HTML formatting.\n - *Dynamic Injection*: Both fields support dynamic variable and table references (e.g., `{id: 113251, name: email_subject}`). Both fields are strictly required.\n- **Block Behavior & Technical Nuances**:\n 1. `HTML Support & Minification`: The content field accepts a mix of plaintext and HTML tags. Developers can minify HTML to eliminate extra whitespace in the email body.\n 2. `Rate Limiting`: The block enforces a per-minute sending rate limit to prevent spamming. This rate limit is automatically applied/throttled if the block is placed inside a rapid loop (`Start Repeat`).\n 3. `Sender Address`: Emails originate from `no-reply@notifications.zerowork.io`. Users should whitelist this address in their email client to prevent notifications from landing in spam.\n 4. `Footer`: Delivered emails include a standard ZeroWork footer text.\n- **Common Use Cases / Workflow Patterns**:\n - `Missing Element Alert`: Pair with `Check Web Element` -> on `Not Found` branch, trigger `Send Notification` to alert the user that a required page element changed or failed to load.\n - `Error Monitoring / Uptime Alert`: Pair with `Start Try-Catch` -> on `On Catch Error` branch, trigger `Send Notification` to alert the user that a webpage is down or unreachable.\n\n### 99. Shortcuts (`Shortcuts.png`)\n- **Documentation Section**: Using Building Blocks -> Building Block Options -> Shortcuts\n- **Core Function**: Canvas productivity shortcuts for workflow builders.\n- **Key Shortcut**: `Mouse drag + SHIFT`: Initiates a marquee / bounding box selection to select multiple building blocks simultaneously on the canvas. Selected blocks are highlighted with a distinct border/overlay, allowing bulk operations (moving, deleting, copying).\n\n### 100. Shorten Content Length (`Shorten Content Length.png`)\n- **Documentation Section**: Using Building Blocks -> Format Data -> Shorten Content Length\n- **Core Function**: Truncates a string stored in a variable or table column to a specified maximum character length.\n- **Example Transformation**:\n - Input: `This text needs to be drastically shortened`\n - Max Length: `20`\n - Output: `This text needs to b` (exactly 20 characters, truncating mid-word if necessary).\n- **Primary Use Case / Cost Optimization**:\n - `LLM Token Optimization`: Used heavily before passing scraped text into the `Ask ChatGPT` building block. Truncating massive scraped articles or bios prevents exceeding LLM context window limits and significantly reduces OpenAI API token expenditure.\n\n### 101. Spintax (`Spintax.png`)\n- **Documentation Section**: Using Building Blocks -> Dynamic Inputs -> Spintax\n- **Core Function**: Generates randomized text variations during runtime to bypass anti-spam algorithms and automated bot detection mechanisms on platforms like LinkedIn, Facebook, or email providers.\n- **Syntax Rules**:\n - Enclosed in curly braces `{}` with options separated by vertical pipe `|`.\n - E.g., `{hi|hello|hey|howdy}`.\n - Multi-part Spintax chaining: `{Hi|hello|hey|howdy}, {how are you?|what\'s new?|how\'s everything?}`.\n - *Behavior*: TaskBot randomly selects one option from each bracket set on every loop iteration or run.\n- **Supported Building Blocks & Toggles**:\n 1. `Insert Text or Data`: Spintax is fully supported.\n 2. `Update Data`: Spintax is supported but **disabled by default**. To enable Spintax evaluation when updating table columns or variables, developers must explicitly check the `Use spintax` checkbox in the block\'s configuration modal.\n\n### 102. Split Data (`Split Data.png`)\n- **Documentation Section**: Using Building Blocks -> Split Data\n- **Core Function**: Parses a single string value from a variable or table column into multiple distinct segments based on a specified delimiter, saving each segment into separate columns or variables.\n- **Workflow Example (Splitting Full Name)**:\n - Input Table Column: `Name` (e.g., `Andy Trujillo`).\n - Separator: `(space)`.\n - Save split values to:\n - Position `1` -> Column `First name`.\n - Position `2` -> Column `Last name`.\n - Result: `First name` = `Andy`, `Last name` = `Trujillo`.\n- **Advanced Indexing Rules & Behavioral Nuances**:\n 1. `Positive Indexing (1-Based)`: Indexing starts at `1` (Position 1 = first token, Position 2 = second token).\n - *Critical Warning*: **Position 0 is invalid**. Entering `0` will cause TaskBot to generate a fatal runtime error.\n 2. `Negative Indexing (Reverse Lookup)`: Supported starting from Agent version `1.1.61`. Negative positions count backwards from the end of the split array.\n - E.g., Position `-1` = last token (e.g., last name).\n - E.g., Position `-2` = second-to-last token.\n - *Use Case*: Extremely useful for extracting last names from complex full names containing middle names or prefixes (e.g., `John Robert Smith` -> `-1` correctly captures `Smith`).\n 3. `Missing Position Handling`: If the input string does not contain enough tokens to satisfy a requested position (e.g., requesting Position `3` on `Hello world`), TaskBot does **not** throw an error. It simply saves nothing (leaves the destination empty) and seamlessly continues execution.\n\n### 103. Standard Loop (`Standard Loop.png`)\n- **Documentation Section**: Using Building Blocks -> Start Repeat -> Standard Loop\n- **Core Function**: The primary loop type used to iterate over repeating web elements (e.g., search results, product lists) and append new rows to a data table.\n- **Key Characteristics**:\n 1. `Appends New Rows`: Each loop iteration creates/appends a new row in the target data table.\n 2. `Row Manipulation`: Format Data or Insert Data blocks executed during the loop iteration apply transformations directly to the current to-be-appended row.\n 3. `Ignores Existing Table Data`: Standard Loop is designed for *new data collection*. It ignores pre-existing rows in the table. (To iterate over existing rows, developers must use `Dynamic Loop`).\n 4. `Auto-Scrolling`: Automatically scrolls the web page to load more items in endless scroll containers, unless configured otherwise (refer to `Continue until No Element Is Found`).\n- **Loop Index Injection & Advanced Syntax (`{loop_index}`)**:\n - `Basic Substitution`: Replaces incremental numbers in CSS/XPath selectors. E.g., `li:nth-child(1)` -> `li:nth-child({loop_index})`.\n - `Alternative Filter Syntax (>> nth)`: If the exact structural position of the increment is complex or unknown, developers can append ZeroWork\'s custom filter syntax: `main#main div > span >> nth={loop_index}`.\n- **Advanced Loop Index Parameters**:\n 1. `Custom Starting Point`: `{loop_index,2}` configures the loop to start counting from index `2` (e.g., skipping the first item).\n - *Important CSS vs. Filter Indexing Nuance*:\n - `nth-child()` in CSS is **1-based** (starts at 1).\n - `>> nth=` custom filter syntax is **0-based** (starts at 0). E.g., `>> nth=0` targets the 1st element, `>> nth=1` targets the 2nd element.\n 2. `Custom Step / Skip Interval`: `{loop_index,1,2}` configures the loop to start at index `1` and increment by `2` on each iteration (e.g., evaluating 1, 3, 5, 7...). Useful for skipping ads or secondary rows in alternating table layouts.\n 3. `Parent Loop Referencing (Nested Loops)`: `{loop_index_123}` where `123` is the explicit block ID of an outer `Start Repeat` block. Essential for complex multi-dimensional scraping where inner loop selectors must reference the current iteration index of the outer parent loop.\n\n### 104. Start Condition and Set Condition (`Start Condition And Set Condition.png`)\n- **Documentation Section**: Using Building Blocks -> Start Condition and Set Condition\n- **Core Function**: Introduces conditional branching and dynamic variable manipulation into TaskBot workflows. Enables workflows to execute alternative pathways based on logical evaluations.\n- **Components**:\n 1. `Start Condition`: Evaluates a logical expression. If `True`, execution proceeds along the `True` branch; if `False`, execution proceeds along the `False` branch.\n 2. `Set Condition`: Used to merge or define specific conditional states before or within branching logic.\n- **Comparison Operators & Matching Rules**:\n - `equals` / `does not equal`: Exact string or numeric match.\n - `contains` / `does not contain`: Substring evaluation.\n - `is empty` / `is not empty`: Checks for null, undefined, or zero-length strings.\n - `greater than` / `less than`: Numeric comparisons.\n- **Variable Inspection & Dynamic Evaluation (`{Variable}` Syntax)**:\n - Conditions can inspect runtime variables, table columns, or webhook payloads.\n - *Syntax Requirement*: When referencing a variable in the condition configuration, developers must enclose the variable name in curly braces (e.g., `{status}` equals `active`).\n- **Common Use Cases & Troubleshooting**:\n 1. `Element Existence Check`: Verifying if a scraped field or variable `is not empty` before attempting downstream actions (e.g., checking if `{email}` exists before calling `Send Notification`).\n 2. `Error Recovery Routing`: Inspecting error messages captured from Try-Catch blocks (e.g., `{error_msg}` contains `timeout`).\n 3. `Type Coercion Warnings`: Ensure numeric comparisons use clean numbers without currency symbols or commas, as stringified numbers with formatting may fail `greater than`/`less than` evaluations.\n\n### 105. Start Repeat (`Start Repeat.png`)\n- **Documentation Section**: Using Building Blocks -> Start Repeat\n- **Core Function**: The foundational control block for establishing looping structures in TaskBot workflows. Defines the iteration mechanism, target data source, and exit conditions for repetitive scraping or automation tasks.\n- **Looping Modes & Architecture**:\n 1. `Standard Loop`: Iterates over repeating web elements on a page (e.g., search results lists) and appends new rows to a data table.\n 2. `Dynamic Loop`: Iterates over existing rows of a ZeroWork data table (e.g., visiting a list of URLs previously scraped).\n 3. `Fixed Number Loop`: Executes a sequence of blocks a specific, hardcoded number of times (e.g., clicking a \'Load More\' button exactly 5 times).\n- **Anatomy of a Loop Workflow**:\n - `Start Repeat`: Initiates the loop and defines the iteration parameters.\n - `Loop Body`: The sequence of building blocks executed during each iteration.\n - `After Repeat`: The exit pathway executed once the loop completes all iterations or meets an exit condition.\n- **Advanced Configuration & Exit Conditions**:\n - `Max items`: Puts a hard ceiling on the total number of items to process across all pages/iterations.\n - `Max pages`: Limits pagination loops to a specific number of page transitions.\n - `Continue until No Element Is Found`: Automatically terminates the loop when the target web element selector is no longer present in the DOM.\n- **Troubleshooting (`Loop stops prematurely` or `Infinite loop`)**:\n 1. `Stale Selectors`: If the web page reloads or modifies DOM structures during the loop, `Start Repeat` may fail to find the next item.\n 2. `Missing Pagination`: Ensure the pagination action (`Click Web Element` on \'Next\' button) is correctly configured outside the main item loop but inside the outer pagination loop.\n\n### 106. Stay on Page After Run (`Stay On Page After Run.png`)\n- **Documentation Section**: Using ZeroWork -> Run Settings -> Stay on Page After Run\n- **Core Function**: A debugging and development toggle that prevents the ZeroWork Desktop Agent from automatically closing the browser window upon TaskBot completion or failure.\n- **Access & Configuration**:\n - Located in the `TaskBot Settings` modal (accessed via the gear icon in the builder toolbar) under `Desktop Agent` run settings.\n - Check the box `Stay on page after run` to enable.\n- **Technical Utility & Use Cases**:\n 1. `Post-Mortem DOM Inspection`: When a TaskBot fails due to a missing selector (`No Selector is Found`), keeping the browser open allows developers to open Chrome DevTools (`F12`), inspect the final DOM state, and verify if the website displayed a captcha, pop-up, or dynamic structural change.\n 2. `Session & Cookie Verification`: Allows developers to verify if the bot remained logged in or if a session expired during execution.\n- **Important Behavioral Nuances & Warnings**:\n - `Local Desktop Runs Only`: This setting applies exclusively to local runs executed via the ZeroWork Desktop Agent. It has no effect on Remote (Cloud) Execution or VPS runs.\n - `Memory & Resource Management`: Leaving multiple finished TaskBot browser sessions open consumes significant system RAM. *Best Practice*: Uncheck this setting once workflow debugging is complete and before deploying for production scheduling.\n\n### 107. Sticky Notes (`Sticky Notes.png`)\n- **Documentation Section**: Using ZeroWork -> General -> Sticky Notes\n- **Core Function**: Provides a native documentation and annotation utility directly within the TaskBot builder canvas. Allows creators to embed explanatory text, visual markers, and workflow documentation alongside building blocks.\n- **Features & Capabilities**:\n - `Custom Colors`: Supports various background colors (yellow, blue, green, pink) to categorize notes (e.g., Yellow for general notes, Green for API payloads, Pink for warnings).\n - `Rich Text Formatting`: Supports bold, italic, bulleted lists, and clickable hyperlinks.\n - `Canvas Placement`: Notes can be dragged, resized, and positioned anywhere on the infinite canvas.\n- **Best Practices for Workflow Maintainability**:\n 1. `Complex Selector Documentation`: Documenting the rationale behind complex XPath or regex formulas directly above `Save Web Element` blocks.\n 2. `Team Collaboration & Sharing`: When sharing TaskBots via `Generate sharing link` or `Share with specific user`, sticky notes are fully preserved, making them essential for providing setup instructions to end-users or clients.\n\n### 108. Stop (`Stop.png`)\n- **Documentation Section**: Using Building Blocks -> Stop\n- **Core Function**: Explicitly halts the execution of a TaskBot run at a specific point in the workflow. Acts as a controlled termination point.\n- **Execution Modes / Status Outcomes**:\n 1. `Stop as Success (Completed)`: Halts execution immediately and marks the final run report status as `Success`. Used when a workflow reaches a logical conclusion (e.g., all target leads processed, or a condition verifies no new data is available).\n 2. `Stop as Failure (Failed)`: Halts execution immediately and marks the final run report status as `Failed`. Used when a critical, unrecoverable business logic error occurs (e.g., login failed, API quota exceeded, or required data missing).\n- **Architectural Implementation Patterns**:\n - `Conditional Termination`: Paired with `Start Condition`. E.g., `If {subscription_active} equals \'false\'` -> `Stop (Failed)` with a custom log message.\n - `Try-Catch Fallback`: Placed inside an `On Catch Error` branch to gracefully terminate and log fatal errors without letting the bot crash ungracefully.\n\n### 109. Switch Frame (`Switch Frame.png`)\n- **Documentation Section**: Using Building Blocks -> Switch Frame\n- **Core Function**: Shifts the active browser execution context into or out of an `<iframe>` (inline frame) element to enable interaction with embedded third-party content (e.g., payment gateways, embedded forms, video players, captchas).\n- **Technical Problem (`Isolated Browsing Context`)**:\n - `iframes` act as completely separate, isolated browsing contexts embedded within a parent webpage. Standard DOM queries (`Click Web Element`, `Save Web Element`) executed from the main page cannot see or interact with elements inside an iframe.\n - *Solution*: Developers must explicitly place a `Switch Frame` block before interacting with iframe content.\n- **Modes of Operation**:\n 1. `Switch to iframe`: Select `iframe` from the dropdown and enter the CSS/XPath selector identifying the `<iframe>` tag (e.g., `iframe[id=\'iframeResult\']`). All subsequent building blocks will execute within this iframe\'s DOM.\n 2. `Switch to Main frame`: Select `Main frame` from the dropdown. This exits the iframe context and returns execution to the top-level parent document.\n- **Nested iframes**:\n - If an iframe contains another iframe (e.g., a captcha inside an embedded form), developers must chain multiple `Switch Frame` blocks sequentially to drill down into the nested layers. E.g., `Switch Frame (Outer)` -> `Switch Frame (Inner)`.\n- **Context Auto-Reset Rules (FAQ / Nuances)**:\n - If TaskBot executes an `Open Link`, `Switch Tab`, or `Close Tab` block while inside an iframe, the frame context is **automatically cleared/reset** back to `Main frame` for the newly loaded page/tab (starting from Agent version `1.1.56`).\n- **Troubleshooting (`TaskBot can\'t click/find element in iframe`)**:\n 1. `Wrong Context`: Check if the bot is actually in the correct iframe or if it forgot to switch back to `Main frame`.\n 2. `Nested Frame Miss`: The target element may be inside a second, nested iframe that wasn\'t switched into.\n 3. `Selector Timeout`: Iframe contents often load asynchronously and slower than the parent page. *Tip*: Increase the `selector timeout` in the building block options (`Selector Options`) for actions performed inside iframes.\n\n### 110. Switch or Close Tab (`Switch Or Close Tab.png`)\n- **Documentation Section**: Using Building Blocks -> Switch or Close Tab\n- **Core Function**: Manages browser tab navigation, allowing TaskBots to switch focus between multiple open tabs or close specific tabs during execution.\n- **Actions**:\n 1. `Switch to Tab`: Activates the target tab based on specified criteria.\n 2. `Close Tab`: Closes the target tab based on specified criteria.\n- **Target Selection Options (Criteria)**:\n - `Latest tab`: Targets the rightmost tab opened most recently.\n - `Previous tab`: Targets the tab immediately to the left of the current tab.\n - `Next tab`: Targets the tab immediately to the right of the current tab.\n - `Tab URL matching`: Targets a tab whose URL matches a specific string. Supports:\n - Full URL (e.g., `google.com`).\n - Partial URL (e.g., `/subpage`).\n - Regular Expressions (e.g., `/^https:\\/\\/google\\.com$/i`). *Note*: If regex is invalid, TaskBot treats it as a literal string match without throwing an error.\n - `Tab number`: Targets a tab by its absolute 1-based index from left to right (`Tab number 1` = leftmost tab).\n- **Critical Behavioral Nuances & Warnings (`IMPORTANT Alerts`)**:\n 1. `Tab Indexing vs Visual Order`: TaskBot tracks tab positions based on *creation time*. If a user manually drags and rearranges tabs during an active run, `Tab number`, `Previous tab`, and `Next tab` options may fail or target the wrong tab.\n 2. `Run in Regular Browser Mode Risk`: When running in `Run in my regular browser` mode, the presence of the user\'s personal tabs or parallel TaskBot runs makes positional indexing highly unpredictable. *Best Practice*: Always prefer `Tab URL matching` over positional criteria in regular browser mode.\n 3. `Closing the Active Tab Behavior`: When the currently active tab is closed:\n - The next tab to the right becomes active.\n - If no tab exists on the right, the tab to the left becomes active.\n - If no tabs remain open, the browser window closes.\n 4. `Browser Closure Handling`: If the browser closes because all tabs were closed, TaskBot continues running in the background. However, if the next building block requires a DOM interaction (`Click Web Element`), TaskBot will throw a fatal error. *Fix*: Place an `Open Link` block to relaunch the browser window before attempting DOM actions.\n\n### 111. Take Screenshot (`Take Screenshot.png`)\n- **Documentation Section**: Using Building Blocks -> Take Screenshot\n- **Core Function**: Captures a visual screenshot of the current browser viewport or targeted web element and saves the image file directly to the local filesystem or cloud storage.\n- **Related Documentation Links**:\n - `File Options`: Configuration for naming conventions, dynamic timestamps, and file extension formats.\n - `How do I get folder path?`: Instructions for obtaining absolute directory paths for saving images locally on Windows/macOS.\n\n### 112. TaskBot Does Not Automatically Scroll (`Taskbot Does Not Automatically Scroll.png`)\n- **Documentation Section**: Using ZeroWork -> Common Problems -> TaskBot Does Not Automatically Scroll\n- **Problem Overview**: In certain modern web applications, endless scroll containers or custom virtualized lists use non-standard DOM structures that prevent ZeroWork\'s out-of-the-box auto-scrolling mechanism from detecting the scrollable wrapper.\n- **Architectural Workaround (`Custom Scrolling Logic`)**:\n - Developers must construct custom scrolling logic manually by incorporating a `Keyboard Action` building block into the scraping loop.\n - *Implementation*: Configure `Keyboard Action` to simulate pressing `Arrow Down`, `Page Down`, or `Space` keys to force the container viewport downwards and trigger dynamic element rendering before executing `Save Web Element`.\n\n### 113. TaskBot Sharing Options (`Taskbot Sharing Options.png`)\n- **Documentation Section**: Using ZeroWork -> General: Run, Schedule, Share, Webhooks -> TaskBot Sharing Options\n- **Core Function**: Distributing TaskBot automation workflows to other ZeroWork Creator accounts.\n- **Access**: Click the `Share TaskBot` icon (curved arrow) in the top toolbar of the builder canvas.\n- **Sharing Modes**:\n 1. `Share with specific user`: Enter the target ZeroWork user\'s registered email address. A complete copy of the TaskBot is instantly pushed to their account.\n 2. `Generate sharing link`: Toggle `Activate sharing link` to create a public/shareable URL (`https://zerowork.io/creator/get-taskbot/...`). Anyone with the link can import a duplicate into their workspace. Supports regenerating/resetting the link or deactivating it entirely.\n- **Data Privacy & State Separation (`IMPORTANT Security Rules`)**:\n 1. `Native Table & Variable Data`: Scraped data, table rows, and runtime variable values are **never shared**. The recipient receives the exact table structure (column headers) and variable keys, but all data rows and initial values are entirely empty to protect creator privacy.\n 2. `Run Settings (Cookies, Proxies, Schedules)`: Sensitive execution settings\u2014including authenticated session cookies, proxy credentials, and active scheduler cron jobs\u2014are **stripped entirely**. The recipient\'s copy resets to blank/default run settings.\n 3. `Google Sheets Link Exception`: If the TaskBot uses a `Google Sheets` building block, the configured Google Sheet URL/ID **is preserved and shared**. *Security Warning*: Creators must ensure they restrict access permissions on the Google Sheet or replace the link with a template sheet before sharing.\n- **Live Synchronization (FAQ)**:\n - When sharing via link, the link points dynamically to the creator\'s *current* TaskBot state. Any subsequent building block modifications made by the creator are instantly reflected whenever a new user imports the link.\n- **Troubleshooting (`Recipient did not receive TaskBot`)**:\n - Pushed TaskBots appear in the recipient\'s dashboard within a minute. If missing, instruct the recipient to perform a hard page reload (`F5` / `CMD+R`).\n\n### 114. Trigger Run via Webhook (`Trigger Run Via Webhook.png`)\n- **Documentation Section**: Using ZeroWork -> General: Run, Schedule, Share, Webhooks -> Trigger Run via Webhook\n- **Core Function**: Enables programmatic execution of TaskBots via external HTTP requests (GET or POST), allowing seamless integration with automation platforms (Zapier, Make.com, Pabbly Connect, custom backend servers).\n- **Desktop Agent Prerequisites (`IMPORTANT Red Alert`)**:\n - For local runs triggered via webhook, three strict conditions must be met:\n 1. The user must be actively logged into the ZeroWork Desktop Agent.\n 2. The Desktop Agent process must be actively running in the background.\n 3. The computer must be powered on and configured to prevent sleep/hibernation modes.\n- **Webhook Management**:\n - Generated via `TaskBot Settings` modal -> `Generate Webhook`. E.g., `https://webhook.zerowork.io/webhook/trigger?s=c1416...`.\n - Supports toggling `Webhook is active` to temporarily disable external triggers, or deleting/regenerating the webhook URL to revoke access.\n- **Dynamic Data Ingestion & Variable Mapping (`CRITICAL Capabilities`)**:\n 1. `Built-in Variable (zw_webhook_data)`: The entire raw JSON payload of an incoming POST request (or query parameters of a GET request) is automatically saved into a system-reserved variable named `zw_webhook_data` as a stringified JSON object. E.g., `{"Link": "https://wikipedia.org", "Value": "Some value"}`.\n - *Parsing in JS*: Developers can parse this inside a `Write JavaScript` block using `JSON.parse(await getRef({ref_id: ..., name: "zw_webhook_data"}))`.\n 2. `Direct Top-Level Variable Matching`: If the incoming JSON payload contains top-level keys that exactly match existing TaskBot variable names (case-sensitive), TaskBot automatically populates those variables with the incoming values. E.g., Payload `{"Link": "https://wikipedia.org"}` populates variable `Link`.\n 3. `Advanced JSONPath Matching (Nested Objects & Arrays)`: Developers can map complex nested JSON structures directly to TaskBot variables by defining variable names using JSONPath syntax:\n - E.g., Payload `{"city": {"name": "Berlin"}}` -> Variable name `city.name` captures `Berlin`.\n - E.g., Wildcard Array Extraction: `cities[*].city` extracts an array of city names.\n - E.g., Filter Expressions: `cities[?(@.city==\'Berlin\')]` or `cities[?(@.population>5000000)]`.\n- **Payload & Matching Rules (Notes)**:\n - Variables not included in the webhook payload retain their existing/default values.\n - Matching is strictly case-sensitive (`Link` matches `Link`, not `link` or `LINK`).\n - If a defined JSONPath is invalid or fails to match anything in the payload, TaskBot does **not** throw an error; it simply leaves the variable empty.\n- **TaskBot-to-TaskBot Triggering**:\n - To trigger another TaskBot from within an active TaskBot run, developers can configure an `APIs: Send HTTP Request` building block to make a POST/GET request to the target TaskBot\'s webhook URL.\n\n### 115. Try-Catch (`Try Catch.png`)\n- **Documentation Section**: Using Building Blocks -> Try-Catch\n- **Core Function**: Provides robust error handling and execution recovery by wrapping a block or sequence of building blocks within a monitored execution scope. Prevents unexpected scraping failures from crashing the entire TaskBot run.\n- **Architectural Flow**:\n 1. `Start Try-Catch`: Establishes the beginning of the monitored execution scope. All blocks placed between `Start Try-Catch` and `After Try-Catch` belong to this scope.\n 2. `On Catch Error`: If any building block within the Try-Catch scope fails or throws an error, execution immediately jumps to the `On Catch Error` branch. Developers define fallback/recovery logic here (e.g., logging errors, retrying actions, breaking loops).\n 3. `After Try-Catch`: A convergence junction. Once either the success path completes successfully OR the error recovery path (`On Catch Error`) finishes, execution merges and continues along the `After Try-Catch` pathway.\n- **Advanced Implementation Patterns (Examples)**:\n 1. `Loop Error Isolation`: Wrapping an entire loop sequence inside a Try-Catch. If an error occurs on a specific iteration (e.g., missing element), `On Catch Error` can trigger a `Break Repeat` or log the error, allowing the bot to continue to the `After Repeat` phase without failing the overall run.\n 2. `Granular/Scoped Error Handling`: Chaining multiple separate Try-Catch blocks for distinct high-risk actions. E.g., `Start Try-Catch (Action 1)` -> `On Catch Error (Break)` -> `After Try-Catch` -> `Start Try-Catch (Action 2)` -> `On Catch Error (Retry)` -> `After Try-Catch`.\n 3. `Conditional Error Inspection & Routing`: Combining Try-Catch with conditional branching (`Start Condition`). Developers can record the error message to a variable, then inspect the error string in `On Catch Error`. E.g., `If error contains \'timeout\' -> Retry`, `Else -> Raise Error`.\n- **Critical Limitations (`IMPORTANT Orange Alert`)**:\n - `Fatal Initialization Failures`: If a TaskBot cannot start its run at all, the error **cannot be caught** by a Try-Catch block, even if the entire workflow is wrapped inside one. Common causes for uncatchable fatal errors:\n 1. Outdated Desktop Agent version.\n 2. Invalid TaskBot setup/configuration (e.g., missing required parameters or corrupted builder canvas).\n\n---\n\n## Batch 12 (Items 116 - 131)\n\n### 116. Update Data (`Update Data.png`)\n- **Documentation Section**: Using Building Blocks -> Update Data\n- **Core Function**: Allows TaskBot to update or overwrite existing data in ZeroWork tables or variables during runtime. Essential for updating row statuses, logging scrape timestamps, or modifying counter variables.\n- **Architectural Flow & Configuration**:\n 1. `Target Selection`: Developers select whether to update a Data Table column or a standalone Variable.\n 2. `Value Assignment`: Enter the new value, which can be static text, dynamic spintax, a variable reference, or a formula/code snippet.\n 3. `Scope & Row Mapping`: When updating a table column within a loop (`Start Repeat`), `Update Data` automatically maps to the current active iteration row (`loop_index`), ensuring precise row-level updates without manual row index tracking.\n\n### 117. Upload File (`Upload File.png`)\n- **Documentation Section**: Using Building Blocks -> Upload File\n- **Core Function**: Allows TaskBot to upload files to a webpage from either a direct online file URL or a local folder path on the user\'s computer.\n- **Architectural Flow & Configuration**:\n 1. `Trigger the Upload Action`: Before executing the `Upload File` block, developers must place a building block that initiates the upload action on the target webpage (e.g., a `Click Web Element` targeting the "Upload image" or "Choose file" button).\n - `IMPORTANT Warning`: The native OS file chooser dialog will **not be visible** during TaskBot execution. TaskBot intercepts and handles the file selection behind the scenes directly via the browser API.\n 2. `Select File Source Option`:\n - `From file URL`: Enter a direct online file URL (e.g., `https://example.com/image.jpg`). TaskBot fetches the file directly and uploads it.\n - `From folder path`: Enter the absolute local file path (e.g., `/Users/username/Downloads/pic.png` or `C:\\Users\\username\\Downloads\\pic.png`).\n- **FAQ & Advanced Usage**:\n - `How do I get folder path?`: Explains OS-specific ways to copy absolute paths (Mac: Option + Right Click -> Copy as Pathname; Windows: File Explorer address bar or Shift + Right Click -> Copy as path).\n - `Dynamic Upload via Table Column`: Developers can add a `file column` to a ZeroWork table, upload files directly into the table row, and configure the `Upload File` block to reference that table column.\n\n### 118. Use Element\'s Text (`Use Elements Text.png`)\n- **Documentation Section**: Using Selectors -> Use Element\'s Text\n- **Core Function**: Allows targeting HTML elements directly using their visible text content via two match types: Exact Match and Loose Match.\n- **Selector Syntax Rules**:\n 1. `Exact Match`:\n - **Syntax**: `text="some text"` (inside double quotes).\n - **Behavior**: Case-sensitive exact match. E.g., `text="Start a post"` targets only elements whose text matches exactly.\n 2. `Loose Match`:\n - **Syntax**: `text=some keywords` (without double quotes).\n - **Behavior**: Case-insensitive partial/keyword match. Perfect for dynamic numbers or changing suffixes. E.g., `text=people follow this` targets elements containing "7,898 people follow this" or "1,456 people follow this" by omitting quotes.\n - **Incorrect Syntax**: `text="people follow this"` is a syntax error if looking for dynamic prefix/suffix; it must be without quotes.\n\n### 119. Using Building Blocks (`Using Building Blocks.png`)\n- **Documentation Section**: Using Building Blocks (Overview)\n- **Core Function**: The root entry-point categorizing all available ZeroWork automation building blocks.\n- **Architectural Flow / Block Categories**:\n 1. `Dynamic Inputs`: Explains three types of inputs all building block fields support:\n - *Variables/Tables references*: `Hello {id: 123, name: "Profile name"}`\n - *Code references (stored locally)*: `This is my secret password stored only locally: ${await zw.deviceStorage.get("password")}`\n - *Spintax (randomization)*: `{Hi | Hey | Howdy}! How {are you | are things going}?`\n 2. `Browser`: `Open Link`, `Save Page URL`, `Switch or Close Tab`, `Go Back or Forward`, `Switch Frame`, `Browser Alert`.\n 3. `Web Interaction`: `Click Web Element`, `Check Web Element`, `Save Web Element`, `Insert Text or Data`, `Hover Web Element`, `Select Web Dropdown`, `Keyboard Action`.\n 4. `Logic`: `Start Condition and Set Condition`, `Start Repeat`, `After Repeat`, `Break Repeat`, `Try-Catch`, `Raise Error`, `Abort Run`.\n 5. `Data`: `Update Data`, `Number Operations`, `Format Data`, `Split Data`, `Apply Regex`, `Remove Duplicates`, `Delete Data`.\n 6. `External`: `Ask ChatGPT`, `Send Notification`, `APIs: Send HTTP Request`, `Write JavaScript`.\n 7. `Files`: `Save File`, `Upload File`.\n 8. `Tools`: `Delay`, `Record Date`, `Take Screenshot`, `Save from Clipboard`, `Log`.\n 9. `Building Block Options`: Config options like deactivating, skipping a loop, auto-aligning blocks, and multi-selecting blocks.\n\n### 120. Using Google Sheet vs. Native Tables (`Using Google Sheet Vs. Native Tables.png`)\n- **Documentation Section**: Using Tables -> Using Google Sheet vs. Native Tables\n- **Core Function**: A comparative architectural matrix evaluating trade-offs between ZeroWork Native Tables and Google Sheets integrations for data storage.\n- **Comparison Dimensions**:\n 1. `Reliability`:\n - *Native Tables*: Data handling is seamlessly streamlined with TaskBot runs.\n - *Google Sheets*: External server overload issues are outside ZeroWork control.\n 2. `Editing Column Names`:\n - *Native Tables*: All building block references to edited column names in all TaskBots are **re-mapped automatically**.\n - *Google Sheets*: All building block references in all TaskBots need to be **re-mapped manually** if column names change.\n 3. `Data Sharing`:\n - *Native Tables*: Cannot be shared directly with users outside ZeroWork (requires CSV export).\n - *Google Sheets*: Can share data with anyone instantly.\n 4. `Data Display`:\n - *Native Tables*: Simple paginated view of 50 rows per page.\n - *Google Sheets*: Large variety of filtering, sorting, and data visualization options.\n 5. `Capacity Limits`:\n - *Number of max cells per table/sheet*: Native Tables = 1,500,000 cells; Google Sheets = 10,000,000 cells.\n - *Maximum characters per cell*: Both = 50,000 characters per cell.\n\n### 121. Using Run Reports (`Using Run Reports.png`)\n- **Documentation Section**: Using Run Reports (Overview)\n- **Core Function**: Displays all actions taken during a TaskBot run, essential for troubleshooting failed runs.\n- **Where to Find Run Reports**:\n 1. On the TaskBots list page (icon next to the Play button).\n 2. Inside the TaskBot builder page (icon on the top toolbar).\n- **How Run Reports Are Displayed**: Lists historical runs with timestamps, statuses (Success, Failed, Manually stopped), agent type used, duration, and a `View Logs` / `View Error Details` button.\n- **Tips for Easier Troubleshooting**:\n - `View Logs`: Opens the detailed execution log.\n - `Side View`: Positions logs next to the TaskBot workflow canvas for side-by-side comparison.\n - `View Building Block`: Clicking an error log item highlights/zooms in on the exact building block on the canvas that failed.\n - `Filter`: Toggle "Only show warnings and errors" or search by ID, name, keywords.\n- **Notifications**: Developers can set up automated failure notifications via Email, Slack, or Custom Webhook.\n - `Webhook Payload Structure`: Sends a JSON payload containing `agent_version`, `taskbot_id`, `taskbot_name`, `taskbot_url`, `run_status` (`success`, `fail`, `warning`, `unknown`, `manually_stopped`), `run_type` (`webhook`, `scheduled`, `immediate`), `run_duration`, and an array of `run_errors` (each containing `id`, `timestamp`, `error_message`, `counter`, `screenshot` URL, and `building_block` metadata with `id`, `name`, `type`).\n\n### 122. Using Selectors (`Using Selectors.png`)\n- **Documentation Section**: Using Selectors (Overview)\n- **Core Function**: The root entry-point categorizing all selector features and strategies in ZeroWork.\n- **Architectural Flow / Selector Sections**:\n 1. `What Are Selectors`: Core concept of browser DOM targeting.\n 2. `Use Element\'s Text`: Exact and loose matches on visible text.\n 3. `Copy Selectors`: Methods to copy CSS/XPath selectors from Developer Tools.\n 4. `How to Build Custom Selectors`: Advanced custom attribute-based targeting.\n 5. `How to Use XPath in ZeroWork (advanced)`: Leveraging complex XML path expressions.\n 6. `CSS Selectors Master Class`: In-depth tutorial covering structural, parent-child, and sibling selector strategies.\n\n### 123. Using Tables (`Using Tables.png`)\n- **Documentation Section**: Using Tables (Overview)\n- **Core Function**: The root entry-point categorizing all table management and data storage features in ZeroWork.\n- **Architectural Flow / Table Sections**:\n 1. `How to Add Tables`: Creating new data storage tables within a TaskBot project.\n 2. `Native Tables`: Built-in high-performance ZeroWork data tables.\n 3. `Google Sheets`: External real-time Google Sheets synchronization.\n 4. `Import Data from CSV`: Populating tables from external comma-separated values files.\n 5. `Using Google Sheet vs. Native Tables`: Comparative analysis of reliability, automatic remapping, and sharing trade-offs.\n 6. `Create Columns`: Adding text, number, file, or profile columns.\n 7. `Export Data as CSV`: Extracting scraped or processed data to local files.\n 8. `Convert Native Table to a Google Sheet`: Seamless migration of internal tables to external Google Sheets.\n\n### 124. Using Variables (`Using Variables.png`)\n- **Documentation Section**: Using Variables (Overview)\n- **Core Function**: Variables are used for saving or updating data that you temporarily need during a TaskBot run. Unlike tables, variables do not adhere to any appending or looping logic, making them a powerful and robust way to save/update a single global value dynamically.\n- **When to Use Tables vs. When to Use Variables**:\n - *Tables*: Used when iterating over rows, appending structured datasets, or scraping collections of records.\n - *Variables*: Used for counters, state flags, accumulators, or session-level constants (e.g., total direct messages sent per run).\n- **Comprehensive Flow Example: Limiting DMs to 30 per run**:\n 1. *Step 1*: Setup initial profiles table (`Profile links`).\n 2. *Step 2*: Setup the TaskBot flow: Open LinkedIn -> Loop through profiles -> Insert DM Text -> Click Send.\n 3. *Step 3*: Create a global variable `DM counter` initialized to `0` or left empty.\n 4. *Step 4*: In each iteration, increment `DM counter` by `1` using the `Number Operations` building block.\n 5. *Step 5*: Place a `Start and Set Condition` block *before* sending the DM to check if `DM counter` is less than `30`. If the condition is met, proceed with sending the DM and incrementing. If not, the run bypasses or stops.\n\n### 125. Utilities (`Utilities.png`)\n- **Documentation Section**: Reference & Utilities\n- **Core Function**: Summarizes built-in utility functions and syntax helpers available across all input fields and JavaScript blocks within ZeroWork.\n- **Key Utility Functions**:\n 1. `Device Storage Access`: `zw.deviceStorage.get(key)` / `zw.deviceStorage.set(key, value)` for persisting local key-value data across runs on the same agent machine.\n 2. `Spintax Engine`: `{Option A | Option B | Option C}` for generating randomized variations of text inputs to simulate human variance.\n 3. `Dynamic Variable Interpolation`: `{variable_name}` or `{table_name.column_name}` for injecting runtime data directly into strings.\n\n### 126. Version 1.1.61 (`Version 1.1.61.png`)\n- **Documentation Section**: Release Notes -> Version 1.1.61\n- **Core Overview**: Major release introducing rate limits, strict profile path validations, and selector optimizations.\n- **Key Changes & Features**:\n 1. `Send Notification Rate Limits`: Introduced strict rate limits on `Send Notification` building blocks (max 10 notifications per minute) to prevent external API spamming.\n 2. `Strict Profile Path Validation`: Added explicit file system checks to ensure provided profile paths exist before launching the browser.\n 3. `Selector Optimizations`: Improved background DOM traversal and caching for faster element identification.\n\n### 127. Version 1.1.62 (`Version 1.1.62.png`)\n- **Documentation Section**: Release Notes -> Version 1.1.62\n- **Core Overview**: Hotfix release addressing immediate breaking changes and friction points introduced in 1.1.61.\n- **Key Fixes & Reversions**:\n 1. `Rate Limits Reverted`: Reverted the per-minute rate limits introduced in 1.1.61 for `Send Notification`.\n 2. `Selector Character Limit`: Increased character limit on selectors to **50,000 chars per selector**.\n 3. `Profile Path Validation Disabled`: Disabled the strict profile path check so no error is generated for profile shortcuts (the validation was well-intended but caused breaking changes).\n 4. `Keyboard Action Loop Fix`: Fixed bug where `Keyboard Action` with multiple keys pressed inside a loop errored out.\n 5. `Auto-scroll Selector Indexing Fix`: Fixed unexpected results when enabling auto-scroll but using selectors that do not contain any `loop_index`.\n\n### 128. Version 1.1.63 (`Version 1.1.63.png`)\n- **Documentation Section**: Release Notes -> Version 1.1.63\n- **Core Overview**: Minor release fixing timeouts, timezone bugs, and improving path-following logic for deactivated conditional blocks.\n- **Key Fixes & Improvements**:\n 1. `Insert Text Timeout Fix`: Fixed bug where long texts in `Insert Text or Data` caused timeouts.\n 2. `Timezone Fix`: Fixed dates being recorded in the wrong timezone.\n 3. `Condition Logging`: Improved logging for condition blocks.\n 4. `Deactivated Block Pathing Fix`: Improved path-following logic when `Start Condition` or `Check Web Element` is deactivated. Previously, the chosen fallback path was sometimes suboptimal/unexpected after run flow optimizations, leading to unintended behavior.\n\n### 129. Version 1.1.64 (`Version 1.1.64.png`)\n- **Documentation Section**: Release Notes -> Version 1.1.64\n- **Core Overview**: Patch release fixing tab management, selector compatibility, JavaScript appending, redirect handling, and introducing granular control over human-like clicking.\n- **Key Fixes & Improvements**:\n 1. `Close Tab Fix`: Closing a tab with `Close Tab` no longer prevents new pages from being opened.\n 2. `Select Web Element Fix`: Fixed `Select Web Element` stopping working with certain selectors.\n 3. `Write JS appendIndex Fix`: Fixed bug where custom `appendIndex` values were ignored in `Write JS`.\n 4. `HTTP Redirect Fix`: `Send HTTP Request` now correctly follows redirects (301, 302, 303) automatically.\n 5. `Upload File Redirect Fix`: File URLs in `Upload File` building block with redirects are now followed correctly.\n 6. `Human-Like Clicking Granularity`: Added `Use human-like clicking` option to `Click Web Element` building block. Enabling human-like clicks globally caused issues on certain websites, so it is now configurable per block.\n\n### 130. Version 1.1.65 (`Version 1.1.65.png`)\n- **Documentation Section**: Release Notes -> Version 1.1.65\n- **Core Overview**: Maintenance release addressing background memory leaks and improving stability during long-running scraping loops.\n- **Key Improvements**:\n 1. `Memory Optimization`: Reduced memory footprint during extensive table appending operations.\n 2. `Stability Fixes`: Resolved edge-case crashes when switching between multiple browser tabs rapidly.\n\n### 131. Version 1.1.66 (`Version 1.1.66.png`)\n- **Documentation Section**: Release Notes -> Version 1.1.66\n- **Core Overview**: Security and compatibility patch updating underlying browser driver dependencies.\n- **Key Updates**:\n 1. `Driver Compatibility`: Updated internal Chromium driver hooks to maintain compatibility with modern web standards and anti-bot detection mechanisms.\n 2. `Enhanced Logging`: Added more granular debug traces for network request failures.\n\n### 132. Version 1.1.67 (`Version 1.1.67.png`)\n- **Documentation Section**: Release Notes -> Version 1.1.67\n- **Core Overview**: Patch restoring support for regular browser mode and minor UI improvements.\n- **Key Improvements & Fixes**:\n 1. `Browser Run Fix`: Restores support for "Run in my regular browser" mode, which was broken by recent Chrome updates.\n 2. `Error Messages`: Clarified and improved several error messages.\n 3. `Timeout Extension`: Default timeout for full-page screenshots has been increased.\n\n### 133. Version 1.1.68 (`Version 1.1.68.png`)\n- **Documentation Section**: Release Notes -> Version 1.1.68\n- **Core Overview**: Significant reliability update focusing on background retry mechanisms, concurrency, and UI error reporting.\n- **Key Improvements & Fixes**:\n 1. `Enhancements`: Agent version now included in error reports. File download timeout options added to `Take Screenshot` and `Save File` blocks (default 5 min for file, 2 min for screenshot). Midnight end time allowed in scheduler.\n 2. `Improvements`: Auto retry on 502 errors and aborted response streams. `Open Link` retries on network errors. Scheduler retry mechanism is more robust for syncing scheduled tasks. Copying blocks preserves table references. `Write JS` context cleanup is more forgiving for async code. Notification settings handle duplication better. Parallel webhook triggers handled safely. Improved handling in `Open Link` for rare timing crashes. Improved concurrency for non-incognito browser runs.\n 3. `Fixes`: `Check Web Element` block "Start run from here" activation bug fixed. Awaiting logic fixed for file URL vs download actions. Rare log-out issues and run state display bugs fixed.\n\n### 134. Version 1.1.69 (`Version 1.1.69.png`)\n- **Documentation Section**: Release Notes -> Version 1.1.69\n- **Core Overview**: Major Google Sheets integration update bringing better performance, reliability, and real-time syncing.\n- **Key Improvements & Fixes**:\n 1. `Highlights`: Major Google Sheets performance boost (faster processing, fewer timeouts). Overhauled authentication flow resolving false positive expiration errors. Real-time syncing available for non-native tables in loops.\n 2. `Enhancements`: `Send HTTP Request` supports saving full objects and nested values directly. `Remove Duplicates` can run on every loop iteration when using Google Sheets.\n 3. `Improvements`: Appended rows write into existing empty rows to prevent limit hits. Added retries for taking screenshots and syncing scheduled tasks. Better error messages across blocks. Added handling for unidentified keys in Keyboard Action.\n 4. `Fixes`: Removed conflicting external library for saving clipboard content. Duplicates auto-removed when importing tables. `Send HTTP Request` saving data issues resolved.\n\n### 135. Version 1.1.70 (`Version 1.1.70.png`)\n- **Documentation Section**: Release Notes -> Version 1.1.70\n- **Core Overview**: Stability patch for Google Sheets, navigation timeouts, and HTTP requests.\n- **Key Improvements & Fixes**:\n 1. `Improvements`: Retry handling for critical internal/service-unavailable Google Sheets errors. Reload action integrated into standard page navigation logic. Error details from request responses included if a file URL rejects a download (e.g., status 400).\n 2. `Fixes`: Google Sheets looping error on empty grid rows fixed. `null` values from nested paths in `Send HTTP Request` now correctly save as empty strings/nulls instead of throwing errors. Resolved older Google Sheets authentication issues. HTTP error statuses incorrectly marking run as "unknown" fixed.\n\n### 136. Version 1.1.71 (`Version 1.1.71.png`)\n- **Documentation Section**: Release Notes -> Version 1.1.71\n- **Core Overview**: Minor updates preserving variables on copy, handling null values, and fixing log-out issues.\n- **Key Improvements & Fixes**:\n 1. `Improvements`: Variable/table references preserved when copying specific building blocks to another TaskBot. `null` value behavior in `Send HTTP Request` consistent. Added more retry handling for `Open Link`.\n 2. `Fixes`: Fixed unexpected agent log outs. Fixed issue when two ZeroWork accounts open in different browsers appeared in the same log dialog. Fixed native table row deletion errors.\n\n### 137. Version 1.1.72 (`Version 1.1.72.png`)\n- **Documentation Section**: Release Notes -> Version 1.1.72\n- **Core Overview**: Massive feature update introducing Bypass Detection, Sticky Browser Profiles, Write JS API, Code in No-Code Inputs, and Multi-account automation support.\n- **Key Features & Changes**:\n 1. `Bypass Detection Mode`: TaskBots stay undetectable by Cloudflare and similar strong protections. Runs headless while maintaining detection evasion.\n 2. `Sticky Browser Profiles`: Create dedicated sticky profiles (cookies, storage, fingerprints) per account for multi-account automation. Clone existing regular profiles.\n 3. `Write JS API (zw)`: Native API support for importing npm packages, Local & Global state variables, Device Storage secrets, Utilities (`zw.log()`), Browser Context management, and Metadata retrieval.\n 4. `New Building Blocks`: `Launch Browser` and `Quit Browser` for granular control.\n 5. `Powerful Launch Options`: Inject scripts, use external Chromium browsers (Brave, Chrome), custom launch args, window control, and `Even more options via APIs` for Firefox/add-ons.\n 6. `Code Input in No-Code Blocks`: Template expressions `${...}` and code blocks `${[...]}` allow using code/logic directly in text fields.\n 7. `Device Storage (Secrets)`: Securely store passwords/API keys locally.\n 8. `Breaking Changes`: Legacy Non-incognito mode and "Run in my regular browser" consolidated into profile setup. File upload limit set to 300MB. Spintax disabled by default on inputs to prevent unintended parsing.\n\n### 138. Version 1.1.73 (`Version 1.1.73.png`)\n- **Documentation Section**: Release Notes -> Version 1.1.73\n- **Core Overview**: Stability update focused on browser launch resilience following the massive 1.1.72 release.\n- **Key Improvements & Fixes**:\n 1. `Improvements`: More reliable browser launches. Better browser profile cloning (retries if profile files change mid-copy). Improved error messaging on browser launch failures. Invalid JSON body in `Send HTTP Request` block throws clearer error.\n 2. `Fixes`: Fixed default Chrome args overwriting user-provided args.\n\n### 139. Version 1.1.74 (`Version 1.1.74.png`)\n- **Documentation Section**: Release Notes -> Version 1.1.74\n- **Core Overview**: Introduces Multi-Agent support and White-Label Desktop Agents for enterprise/agency distribution.\n- **Key Features & Changes**:\n 1. `Multi-Agent Support`: Manage multiple Desktop Agents from one ZeroWork account. Trigger runs on specific Agents via webhook using `agent=<AGENT_ID>`.\n 2. `White-Label Desktop Agents`: Brand the Desktop Agent with custom company name and logo for distribution to end customers.\n 3. `Optimizations`: Faster CSV imports into native tables. More reliable webhook connections.\n 4. `Fixes`: Random connection slowdowns, proxy authentication in Bypass Detection Mode, sticky profiles opening as guest, and Remove Duplicates logic fixed.\n\n### 140. Website Is Glitching And Flashing (`Website Is Glitching And Flashing.png`)\n- **Documentation Section**: Common Problems -> Website is Glitching and Flashing\n- **Core Overview**: Addresses UI flashing/looping behavior during execution.\n- **Troubleshooting**: \n - Occurs when the TaskBot cannot find a selector.\n - The agent is continually retrying to find the element, causing visual glitches.\n - Fix by ensuring the selector is valid and uniquely identifiable (refer to "No Selector is Found").\n\n### 141. Website Requires Sms Or Email Verification (`Website Requires Sms Or Email Verification.png`)\n- **Documentation Section**: Common Problems -> Website Requires SMS or Email Verification\n- **Core Overview**: Strategy for handling unexpected 2FA or verification pop-ups.\n- **Implementation Strategy**:\n - Use `Check Web Element` to detect verification pop-ups.\n - For active/attended runs: Add a long delay and manually enter the code while the TaskBot pauses.\n - For background/headless runs: It\'s impossible to interact manually. Terminate the run and use `Send Notification` to alert yourself.\n\n### 142. What Are Selectors (`What Are Selectors.png`)\n- **Documentation Section**: Using Selectors -> What Are Selectors\n- **Core Overview**: Introduction to how elements are identified on a web page using CSS or XPath selectors.\n- **Key Concepts**:\n - Every element on a website can be identified by a unique selector (CSS or XPath).\n - To interact with an element (e.g., click a button), the TaskBot needs to know its selector.\n - ZeroWork supports both CSS and XPath, but the guide focuses on CSS as it is more beginner-friendly. XPath is for advanced users.\n - Getting selectors can be done by: Copying Selectors, Using Element\'s Text, or Building Custom Selectors.\n\n### 143. When I Use Data From Table No Data Is Being Pulled (`When I Use Data From Table No Data Is Being Pulled.png`)\n- **Documentation Section**: Common Problems -> When I Use Data from Table, No Data is Being Pulled\n- **Core Overview**: Explains how to properly reference table data inside and outside of loops.\n- **Implementation Rules**:\n - **With Loops**: To use data from tables, you *must* use the `Start Repeat` building block with the loop type `Dynamic Loop` to iterate over the rows.\n - **Without Loops**: You cannot directly reference a table column in a block (like `Open Link`) if it\'s not inside a loop iterating over that table.\n - **Variables**: Referencing variables (not table columns) works fine without a loop.\n - **First Row Only**: If you only want to use the first row of a table without iterating through all of them, use `Start Repeat` (Dynamic) but set the "Repetition limit (optional)" to `1`.\n\n### 144. When Using Insert Data Block First Letters Are Cut Off (`When Using Insert Data Block First Letters Are Cut Off.png`)\n- **Documentation Section**: Common Problems -> When Using Insert Data Block, First Letters Are Cut Off\n- **Core Overview**: Solves the issue where typed text misses the first few characters.\n- **Troubleshooting**:\n - **Cause**: This happens because the TaskBot starts typing before the input field has fully loaded or gained focus.\n - **Fix**: Add more delay (`min sec` / `max sec`) to the *preceding* building block (e.g., the `Click Web Element` block that clicks the input field before typing) to ensure the field is fully ready.\n\n### 145. Workflow Has More Than One Starting Building Block (`Workflow Has More Than One Starting Building Block.png`)\n- **Documentation Section**: Common Problems -> Workflow Has More than One Starting Building Block\n- **Core Overview**: Resolves the error caused by disconnected or improperly connected blocks in the flow.\n- **Troubleshooting**:\n - **Cause**: Either you have disconnected loose building blocks on the canvas, or blocks are connected backwards (bottom to top, or right to left). Blocks can only be connected top-to-bottom or left-to-right.\n - **Identification Option 1**: Look at the error message for the specific block IDs (e.g., `806460, 809891`). Use the search bar on the canvas to find those specific blocks.\n - **Identification Option 2**: Use the Auto-Align feature. This will align the workflow and bring any floating/loose blocks into view. (Recommendation: duplicate the TaskBot before auto-aligning to preserve your visual layout).\n\n### 146. Write And Read Variables And Tables (`Write And Read Variables And Tables.png`)\n- **Documentation Section**: Using Building Blocks -> Write Javascript -> Write and Read Variables and Tables\n- **Core Overview**: Explains the `zw.getRef()` and `zw.setRef()` API methods for interacting with ZeroWork tables and variables via code.\n- **API Methods**:\n - `await zw.getRef({ ref_id: number, name: string })`: Returns the string value from a variable or table column. (Async)\n - `await zw.setRef({ ref_id: number, name: string, value: string })`: Saves a string value to a variable or table column. (Async/Sync)\n- **Rules & Limitations**:\n - **ref_id**: The numeric ID shown in the left sidebar next to a table or variable.\n - **name**: Identifies the column or variable name. It is **case-sensitive**.\n - **Values**: Values are strictly stored as strings. To store arrays or objects, use `JSON.stringify()` on write, and `JSON.parse()` on read.\n- **Loop Behavior**:\n - Reading existing rows: Place `Start Repeat` (Dynamic) *before* the JS block.\n - Appending new rows: Place `Start Repeat` (Standard) *before* the JS block, OR use the `appendIndex` property inside `setRef()` (e.g., `appendIndex: i`) to manually add rows from a code loop.\n - **Warning**: Do not mix `appendIndex` in code with a built-in `Start Repeat` loop index, as it causes mismatched rows.\n\n### 147. Write Javascript (`Write Javascript.png`)\n- **Documentation Section**: Using Building Blocks -> Write Javascript\n- **Core Overview**: Comprehensive guide to the `Write JavaScript` block and the `zw` API for advanced TaskBot logic.\n- **Capabilities & APIs**:\n - **Imports**: `zw.import(package, options)` or `zw.packages.*` to install npm packages on the fly.\n - **Variables/Tables**: `zw.getRef()` and `zw.setRef()`.\n - **Local/Global State**: `zw.state.*` (per-run state, clears when run ends), `zw.globalState.*` (agent-wide state, stays across runs on the same device).\n - **Device Storage**: `zw.deviceStorage.*` to persist key-value data on the device (survives restarts/reinstalls, never sent to ZeroWork servers).\n - **Utilities**: `zw.delay()`, `zw.log()`, `zw.logTemp()` for logging and waiting.\n - **Browser Context**: `zw.browserContext.*` (launch, quit, manage contexts, custom proxy, geolocation, scripts).\n - **Metadata**: `zw.getTaskbotInfo()`, `zw.getAgentInfo()` to read TaskBot/Agent details.\n- **Execution Modes**:\n - **Local vs Browser**: Code runs locally in the Node.js runtime by default. Check "Run locally" to ensure Node.js APIs/packages work.\n - **Browser limitations**: If running in the browser context, `zw.getRef()`, `zw.deviceStorage.*`, `zw.delay()`, and `zw.getTaskbotInfo()` are available. However, imports, global state, and browser context management are limited or unavailable.\n- **Code in No-Code Blocks**: Use `${...}` for expressions or `${[...]}` for code blocks directly in standard building block inputs.\n\n### 148. Copy Selectors (`Copy Selectors.png`)\n- **Documentation Section**: Using Selectors -> Copy Selectors\n- **Core Overview**: The easiest method to get CSS selectors using a recommended Chrome extension.\n- **Implementation Strategy**:\n - Use the free "Copy CSS Selector" Chrome plugin.\n - Right-click on any element on the website and select "Copy CSS Selector" from the context menu.\n - Wait a few seconds for a dotted frame to appear around the element (confirming it found the selector).\n - Paste the copied selector directly into the ZeroWork building block.\n\n'};var af=[{id:"tutorial_1",title:"Auto-visit links from an existing Google Sheet or data table in ZeroWork",content:`hi I'm Diana founder of zeror in this\r
312
+ `,visual_insights:'\n# ZeroWork Visual Insights Master Document\n\nThis document compiles granular UI and configuration insights extracted directly from screenshots of the official ZeroWork documentation.\n\n## Batch 1: Abort Run to Auto Continue\n\n### 1. Abort Run (`Abort Run.png`)\n- **Building Block Name**: `Abort Run`\n- **UI / Icon**: Pink background block with an `(X)` icon inside.\n- **Canvas Branching Example**: Shows a workflow starting with `If a new post...` branching into two paths:\n - Top path: `...exists` -> `Type comment` -> `Post comment`.\n - Bottom path: `...does not exist` -> `Abort Run`.\n- **Function**: Instantly terminates the TaskBot run immediately when reached. Useful for stopping execution when critical data or conditions are missing.\n\n### 2. Actions = & \u2260 (`Actions And.png`)\n- **Condition Type**: `Actions = & \u2260` (Equal / Not Equal).\n- **Context**: Used in `Start Condition and Set Condition` building blocks.\n- **Use Cases**:\n - Break loop on condition that status request is unsuccessful (e.g. check if status response equals or does not equal 200).\n - Set profile visit status to "visited" and avoid visiting the same profile links by checking if status equals "visited".\n - Remove disqualified leads if lead qualification status does not equal "qualified".\n\n### 3. Actions <, \u2264, >, \u2265 (`Actions Less Than Greater Than.png`)\n- **Condition Type**: `Actions <, \u2264, >, \u2265` (Comparison operators).\n- **Context**: Used in `Start Condition and Set Condition`.\n- **Function**: Compares numeric values (e.g., number of followers, prices, degrees, etc.).\n- **Note**: For comparing calendar dates, users should use `Before (Date) & After (Date)`.\n\n### 4. Addressing Siblings (`Addressing Siblings.png`)\n- **Advanced CSS Selector Concept**: Addressing sibling elements in the DOM hierarchy.\n- **Syntax**:\n - Tilde `~`: Loose sibling (matches any following sibling element at that hierarchy level).\n - Plus `+`: Exact sibling (matches the immediately next sibling element at that hierarchy level).\n- **Context**: Used when elements are on the same level in the DOM hierarchy but cannot or should not be addressed as a list (e.g., incremental CSS selectors).\n\n### 5. After Repeat (`After Repeat.png`)\n- **Building Block Name**: `After Repeat`\n- **UI / Canvas Placement**: Must always be placed immediately after a `Start Repeat` building block.\n- **Example 1 (Email Notification)**: `Start Repeat` loops through actions. `After Repeat` is attached right after `Start Repeat`, linking to a `Send Notification` block (`@` icon) to send an email once all loop iterations complete.\n- **Example 2 (Chaining Multiple Loops)**: Creates a "workflow in workflow" effect. Shows two separate loop clusters in the same canvas:\n - Cluster 1: "Collect leads" (`Start Repeat` -> `Save Lists` -> `After Repeat`).\n - Cluster 2: "Iterate over collected leads" (`Start Repeat` -> `Open Link` -> `Enrich Existing Data`).\n - `After Repeat` bridges the end of Cluster 1 directly into the start of Cluster 2.\n\n### 6. APIs: Send HTTP Request (`Apis Send Http Request.png`)\n- **Building Block Name**: `Send HTTP Request`\n- **Modal Configuration UI**:\n - **Request Type Dropdown**: `POST`, `GET`, `PUT`, `PATCH`, `DELETE`.\n - **URL Field**: Input URL (e.g. `https://api.openai.com/v1/completions`). Supports dynamic table references like `{table_name:column_name}`. Note: ensure trailing slashes are correctly handled as required by the specific API.\n - **Tabs**: `HEADERS`, `REQUEST BODY`, `SAVE RESPONSE`.\n - **HEADERS Tab**: Key-value pairs (e.g., `Content-Type`: `application/json`, `Authorization`: `Bearer sk-...`).\n - **REQUEST BODY Tab**: JSON body input area. Supports table/variable references. Note: invalid JSON body errors often occur if double quotes are not escaped or if dynamic data contains unescaped double quotes (recommends using `Replace text` regex to clean data).\n - **SAVE RESPONSE Tab**:\n - `Save response body (optional)`: Dropdown selecting table/variable (e.g. `Variables`).\n - `Nested record path (optional)`: Field to specify dot/bracket notation for nested JSON responses (e.g., `choices[0][\'text\']`).\n - `Save response status code (optional)`: Dropdown to select table/variable (e.g. `Variables`, variable `status`). Allows checking for 200, 400, 500 status codes to handle errors or break loops.\n\n### 7. Apply Regex (`Apply Regex.png`)\n- **Building Block Name**: `Apply Regex`\n- **Modal Configuration UI**:\n - **Enter expression between slashes**: e.g., `/([a-zA-Z0-9-_]+)/g` or `/\\d+/`.\n - **Select method Dropdown**:\n - `Replace text`: Replaces matched regex with a replacement string.\n - `Extract matches`: Extracts matching substrings.\n - `Check if pattern matches`: Returns `true` or `false`.\n - **Text to apply the regex to Field**: Input text or dynamic reference (e.g. `{id: 89197, name: Google Sheets link}`).\n - **Save result to**: Dropdown selecting `Variables` or a table.\n - **Select variable Dropdown**: Selecting the destination variable (e.g. `Google Sheets ID`).\n- **Flags**: Supports `g` (global), `i` (case-insensitive), `m` (multiline). Example: `/pattern/gi`.\n- **Error Handling**: If input text is empty, TaskBot continues running without action. If regex is invalid, TaskBot generates an error report and stops the run/loop.\n\n### 8. Ask ChatGPT (`Ask Chatgpt.png`)\n- **Building Block Name**: `Ask ChatGPT`\n- **Modal Configuration UI**:\n - **Model Dropdown**: e.g., `ChatGPT 3.5`, `ChatGPT 4`.\n - **Enter prompt Field**: Text area for prompt. Supports dynamic references.\n - **Save ChatGPT answer to Dropdown**: Select `Variables` or table.\n - **Select variable Dropdown**: Destination variable (e.g., `Message to send`).\n - **API Key Warning**: If API key is missing, shows a warning banner with an `Add here` link opening Settings -> Integrations tab to enter the OpenAI API key.\n - **Settings Gear Icon (Behavior on error)**:\n - `Stop (loop) run and create error report` (default).\n - `Continue run and record error code`: Dropdown `Save error code to` (e.g. `Variables`, select variable `OpenAI error`).\n- **Error Handling & Token Limits**:\n - Captures 400, 429, etc., or `length` error if token limit is exceeded.\n - Explains truncation issues and recommends using `Format Data` -> `Shorten Content Length` building block to truncate scraped text before sending to ChatGPT to save tokens and prevent `length` errors.\n - Token consumption is logged in TaskBot run reports.\n\n### 9. Auto-Align (`Auto Align.png`)\n- **Feature**: Workflow canvas formatting toolbar.\n- **UI Controls**: Toolbar buttons `[+]`, `[-]`, `[lock]`, `[Align Left-to-Right / Top-to-Bottom icon]`, `[center]`.\n- **Function**: Reorganizes messy, scattered building blocks into a neat, structured layout automatically, either horizontally (left to right) or vertically (top to bottom).\n\n### 10. Auto-Continue from Last Row or Element (`Auto Continue From Last Row Or Element.png`)\n- **Feature**: Resumption capability within `Start Repeat` building blocks.\n- **Modal Configuration UI (`Start Repeat`)**:\n - **Select loop type**: `Standard` (add new rows or repeat actions) vs `Dynamic` (process table rows one by one).\n - **Dynamic Loop UI**:\n - `Table to loop through`: Dropdown selecting table (e.g., `LinkedIn Profiles`).\n - `Newest rows first (reverse order)` checkbox.\n - `Repetition limit (optional)`: e.g., `100`.\n - `Start from (optional)`: row number, e.g., `1`.\n - `Auto-continue from last row` checkbox. Shows badge `Next run starts from 1`.\n - **Standard Loop UI**:\n - `Number of repetitions`: e.g., `100`. `Continue until no element is found` toggle.\n - `Start from (optional)`: element number, e.g., `1`.\n - `Auto-continue from last element` checkbox. Shows badge `Next run starts from 1`.\n- **Execution Logic**:\n - Tracks the last processed row/element across separate bot runs.\n - Example: If repetition limit is 100, Run 1 processes rows 1-100. Run 2 automatically starts at row 101 and processes 101-200. Run 3 starts at 201, etc., until table rows or list elements are exhausted.\n\n## Batch 2: Auto Scroll to Check Web Element Identifies\n\n### 11. Auto-Scroll (`Auto Scroll.png`)\n- **Status**: Documentation page marked as "This page is upcoming. Stay tuned!".\n- **Context**: Navigational links indicate it is related to `Start Repeat` options (`Continue until No Element is Found` and `Auto-Continue from Last Row or Element`).\n\n### 12. Basic Concepts of Selectors (`Basic Concepts Of Selectors.png`)\n- **Core Concept**: Explains the anatomy of CSS Selectors using Wikipedia\'s search button as an example.\n- **Console Inspection**: Right-click element -> Inspect.\n- **Structure**: `tag[attribute=\'value\']` or multiple attributes `tag[attribute1=\'value1\'][attribute2=\'value2\']`.\n- **Example**: `<button class="pure-button pure-button-primary-progressive" type="submit">`\n - **Tag**: `button` (first word, marked purple in DevTools).\n - **Attributes**: `class`, `type` (marked brown).\n - **Values**: `pure-button pure-button-primary-progressive`, `submit` (blue).\n - **Resulting Selector**: `button[class=\'pure-button pure-button-primary-progressive\'][type=\'submit\']`. Note: no spaces between tag and brackets, values wrapped in quotes.\n\n### 13. Before (Date) & After (Date) (`Before Date And After Date.png`)\n- **Condition Type**: `Before (Date) & After (Date)`. Used in `Start Condition and Set Condition`.\n- **Function**: Compares calendar dates (checks if reference date is smaller/earlier or greater/later than comparison date).\n- **Modal Configuration UI**:\n - **Select comparison action Dropdown**: `After calendar date`, `Before calendar date`.\n - **Enter calendar date Field**: e.g., `07/10/2023`.\n - **Enter days shift (optional) Field**: Positive or negative integer (e.g., `3` or `-2`).\n - **Calendar date format Dropdown (Settings gear icon)**: e.g. `MM DD YYYY`, `DD MM YYYY`, `YYYY MM DD`. Essential to keep format consistent between comparison date and reference date to prevent errors.\n- **Days Shift Logic Examples**:\n - Comparison date `07/10/2023`, shift `3`: Effective comparison date becomes `07/13/2023`.\n - `After`: Met if reference date is 14th or later.\n - `Before`: Met if reference date is 12th or earlier.\n - Comparison date `07/10/2023`, shift `-2`: Effective comparison date becomes `07/08/2023`.\n - `After`: Met if reference date is 9th or later.\n - `Before`: Met if reference date is 7th or earlier.\n\n### 14. Break Repeat (`Break Repeat.png`)\n- **Building Block Name**: `Break Repeat`\n- **UI / Icon**: White block with a `[STOP]` octagon icon inside.\n- **Function**: Aborts the current loop iteration and exits the loop immediately when specific conditions are met.\n- **Example 1 (No More Search Results)**: Uses `Check Web Element` to detect text like "There are no search results anymore". If found (checkmark branch), routes to `Break Repeat` (`[STOP]`).\n- **Example 2 (API Error)**: Break loop if status request is unsuccessful (e.g. status != 200).\n- **Example 3 (Daily DM Limit)**: Break loop once a daily DM limit variable is reached.\n\n### 15. Bring Pages to Front (`Bring Pages To Front.png`)\n- **Setting Type**: Run Settings -> `Bring Pages to Front`.\n- **UI**: Accessed via TaskBot Settings gear icon (top right) -> `Run Behavior` section -> `Bring pages to front` toggle switch.\n- **Function**: When enabled, brings each newly active page (new tab or link opened in new tab) to the foreground of the desktop window.\n- **Behavior when Disabled**: TaskBot switches tabs silently in the background without stealing focus. (Note: macOS may still bring Chrome to front once at the very start of the run).\n- **Best Practice / FAQ**: Keep enabled while building or testing TaskBots to easily monitor pages during the run.\n\n### 16. Browser Alert (`Browser Alert.png`)\n- **Building Block Name**: `Browser Alert`\n- **UI / Icon**: Block with a chat bubble / exclamation point icon.\n- **Placement**: Placed immediately after an action (e.g., `Click Web Element`) that triggers a native browser dialog (prompt, confirm, alert, beforeunload).\n- **Modal Configuration UI**:\n - `Enter prompt text (optional)`: Text input area. Used only if the dialog is a `prompt` requiring user input. Ignored for alert, confirm, or beforeunload dialogs.\n- **Run Behavior**:\n - By default, ZeroWork TaskBot automatically dismisses (clicks Cancel on) native browser dialogs. Using `Browser Alert` forces TaskBot to **accept** (click OK on) the alert.\n - If no alert appears, TaskBot takes no action and proceeds seamlessly without interruption.\n\n### 17. Browser Context (`Browser Context.png`)\n- **Core Concept**: Comprehensive reference for `zw.browserContext` API used in `Custom Code` / `Advanced Custom Code` blocks.\n- **Key Methods & Options**:\n - `zw.browserContext.launch(options?: LaunchOptions)`: Launches browser and returns context.\n - `LaunchOptions`: `{ headless?: boolean; stickyProfile?: string | { name: string; isGlobal?: boolean }; maximize?: boolean; bypassDetection?: boolean; cookies?: Cookie[]; scripts?: Script[]; launchOptions?: LaunchOptions; contextOptions?: ContextOptions }`.\n - `headless`: Default `false`. Note: overrides sticky profile settings if explicitly set.\n - `stickyProfile`: Attaches a persistent profile. Can pass profile name or object. `isGlobal: true` shares profile across all TaskBots.\n - `maximize`: Default `true`. Overrides viewport settings.\n - `bypassDetection`: Default `true`. Hardens bot against anti-bot detection. Trade-off: disables some file upload buttons; large uploads (>50MB) and downloads are unsupported.\n - `cookies`: Array of `{ name, value, domain, path, expires, httpOnly, secure, sameSite }`. Tip: avoid adding cookies in code if they supply an active session.\n - `scripts`: Array of `{ path?: string; content?: string }`. Injects JS scripts into every page.\n - `launchOptions` / `contextOptions`: Custom Playwright launch/context configurations (e.g. `args`, `proxy`, `viewport`, `userAgent`, `permissions`).\n - `zw.browserContext.getActivePage()`: Returns active Playwright `Page` object. Note: returns `null` if no active page exists.\n - `zw.browserContext.createPage()`: Creates a new tab/page and returns it.\n - `zw.browserContext.get()`: Returns current main browser context.\n - `zw.browserContext.quit()`: Closes current main browser context and all tabs.\n - `zw.browserContext.clearProfile(name)` / `zw.browserContext.cloneProfile(source, target)`: Manages sticky profiles.\n- **Architectural Rules & Anti-patterns**:\n - Avoid creating Playwright contexts directly via `browser.newContext()` as they lack ZeroWork\'s built-in anti-bot detection evasions and profile management.\n - Never call `zw.browserContext.launch()` inside a loop or multiple times in the same script without quitting first.\n - Avoid changing userAgent, timezone, locale, or geolocation in `contextOptions` if `bypassDetection` is true, as it can break evasion mechanisms.\n\n### 18. Building Block Options (`Building Block Options.png`)\n- **Feature**: Overview of canvas interaction options.\n- **Menu Items**: Lists options available when interacting with building blocks on the canvas: `Deactivate Building Blocks`, `Auto-Align`, `Delay Times between the Building Blocks`, `Shortcuts`, `Sticky Notes`.\n\n### 19. Check if Selector is Correct and Unique (`Check If Selector Is Correct And Unique.png`)\n- **Debugging Methodology**: Verifying custom CSS selectors before running TaskBots.\n- **Console Command**: Open DevTools Console -> enter `document.querySelectorAll("PASTE YOUR SELECTOR HERE")` (e.g., `document.querySelectorAll("button[class*=\'button\'][type=\'submit\']")`).\n- **Evaluating Results**:\n - **Unique**: Returns a NodeList with `length: 1`. Hovering over the result highlights the exact element on the page.\n - **Multiple Matches**: Returns `length > 1`. Means selector is too broad. Need to make it more specific, unless building a selector for a list loop (e.g. profile lists), in which case see Incremental CSS Selectors.\n - **No Matches**: Returns `length: 0` or an error. Indicates a typo, incorrect attribute, or using unescaped/smart quotes.\n- **Note**: `text=` selectors (e.g. `text=Submit`) cannot be tested via `document.querySelectorAll` because `text=` is a Playwright/ZeroWork proprietary engine feature, not native CSS.\n\n### 20. Check Web Element Identifies Selector as Found but Next Action Does Not (`Check Web Element Identifies Selector As Found But Next Action Does Not.png`)\n- **Troubleshooting Scenario**: A `Check Web Element` block successfully finds an element, but the immediately following action block (`Click Web Element`, `Hover Web Element`, `Save Web Element`) fails to find or interact with it.\n- **Root Cause 1 & Solution (Timeout vs Delay)**:\n - Some sites have non-standard JS rendering where the DOM element exists but event listeners (like click) take longer to attach.\n - **Solution**: Increase the `Timeout` setting in `Advanced selector settings` of the failing action block (e.g., from 15 to 30-60 seconds). Note: Timeout is different from delay; timeout is abandoned as soon as the selector is fully ready, so it doesn\'t slow down successful runs.\n- **Root Cause 2 & Solution (Visibility / Scrolling)**:\n - Action blocks (especially click and hover) require the element to be visibly in the viewport, whereas `Check Web Element` only checks if it exists in the DOM.\n - **Diagnosis**: Check `Must be visible on screen` in `Check Web Element`. If it returns false, the element is off-screen.\n - **Solution**: Scroll the element into view. Test manually by adding a 30-second delay to `Check Web Element`, scrolling manually during the delay, and seeing if the next action succeeds. If so, add a `Keyboard Action` block (e.g. Page Down or Arrow Down) before the action block to ensure it scrolls into view automatically.\n\n## Batch 3: Check Web Element to Crash Course\n\n### 21. Check Web Element (`Check Web Element.png`)\n- **Building Block Name**: `Check Web Element`\n- **Function**: Checks if a selector (CSS or XPath) can be found or not on the page.\n- **Workflow Branching**: Creates a conditional fork in the canvas workflow.\n - Green checkmark branch: executes if the selector is found.\n - Red X branch: executes if the selector is not found.\n- **Primary Example**: `Send Notification` if cookies expire in ZeroWork. E.g., checks for the presence of a login button or email/password input field (indicating the user is logged out). If found (checkmark branch), routes to `Send Notification` to alert the user via email. If not found (X branch), continues normal workflow.\n- **Advanced Selector Settings**: Supports `Must be visible on screen` toggle (checking viewport visibility vs DOM presence) and `Timeout` configuration.\n\n### 22. Click Web Element (`Click Web Element.png`)\n- **Building Block Name**: `Click Web Element`\n- **Function**: Clicks on a specified web element (e.g., button, link, dropdown trigger).\n- **Targeting**: Requires providing a CSS or XPath selector for the TaskBot to know which element to target. E.g., `button[type=\'submit\']`.\n- **Modal Configuration UI**:\n - `Enter selector of the element`: Text input area for CSS/XPath.\n - `Advanced selector settings`: Allows configuring custom timeout and delay options before/after clicking.\n- **Best Practices / Context**: Often paired with `Check Web Element` (to verify presence before clicking) or `Browser Alert` (if the click triggers a native browser prompt/confirm dialog).\n\n### 23. Code in Inputs (`Code In Inputs.png`)\n- **Core Feature**: `zScript` expressions and code blocks within dynamic inputs across building blocks.\n- **Syntax 1: `${...}` (Expression)**: Runs a single JavaScript expression and inserts its result directly into the input field.\n - E.g. `${ await zw.deviceStorage.get("password") }` (retrieving locally stored secret).\n - E.g. `${ Math.random() }` (generating random number).\n - E.g. `${ "{id: 1234, name: Country Code}".trim().toUpperCase() }`.\n - **Crucial Warning/Rule**: Table/variable references like `{id: 1234, name: Country Code}` are **not** code; they are replaced with their values by ZeroWork before execution. If you need that value **as a string** inside code, wrap it in quotes (e.g., `"${...}"`), OR read it dynamically using `zw.getRef`: `zw.getRef: ${ (await zw.getRef({ ref_id: 1234, name: "Country Code" })).trim().toUpperCase() }`.\n- **Syntax 2: `$${...}` (Code Block)**: Runs full multi-line JavaScript code. Must include a `return` statement to insert the final value into the input field. All code runs locally on the user\'s device.\n - **Auto-installing NPM Packages**: You can import packages like `axios` directly inside the code block! ZeroWork auto-installs them locally on the fly. E.g.:\n ```javascript\n $${\n import axios from "axios"; // any import auto-installs locally\n const res = await axios.get("https://mydomain.com/my/api/url");\n return res.data;\n }\n ```\n - **Complex Formatting & Logging**: E.g.:\n ```javascript\n $${\n const fullAddress = await zw.getRef({ref_id: 1234, name: "Address" });\n const splitValues = fullAddress.split("country code: ");\n const countryCode = splitValues[1];\n if (!countryCode) {\n await zw.log({ message: "no country code", status: "warning" });\n return "unknown";\n }\n return countryCode.toUpperCase().trim();\n }\n ```\n - **Modal UI Example**: `Update Data` building block where `Set equal to the following value` contains `$${ import axios from "axios"; ... }` and `Data to be updated` selects `Variables` -> `API res`.\n\n### 24. Combine Filters with Standard CSS Logic (`Combine Filters With Standard Css Logic.png`)\n- **Advanced CSS Selector Concept**: Combining ZeroWork\'s proprietary `text=` filter method with standard CSS selector paths using `>>` as a filter separator.\n- **Syntax**: `parent_selector >> filter_selector`. E.g., `div > div[role=\'main\'] > div div >> text="Like"`.\n- **CRITICAL RULE / WARNING**: `>>` can **only** be added **at the end of the selector**.\n - `[checkmark] This will work`: `div > div[role=\'main\'] > div div >> text="Like"`\n - `[X] This will not work`: `div > div[role=\'main\'] > div >> text="Like" > div` (cannot put structural CSS child selectors after `>> text=`).\n- **Example Use Case**: Saving email addresses from Facebook Pages by combining `text=` with standard selector logic to pinpoint the exact container holding the email.\n\n### 25. Common Problems (`Common Problems.png`)\n- **Documentation Section**: Troubleshooting directory listing frequent user issues and their dedicated guide pages:\n - `My TaskBot Does Not Start Run`\n - `When I Use Data from Table, No Data is Being Pulled`\n - `Website is Glitching and Flashing`\n - `No Selector is Found`\n - `My TaskBot Saves Some Data but Not All`\n - `Data Is Saved in Wrong Format`\n - `Website Requires SMS or Email Verification`\n - `Keyboard Action Is Not Working As Expected`\n - `Check Web Element Identifies Selector as Found but Next Action Does Not`\n - `When Using Insert Data Block, First Letters Are Cut Off`\n - `Workflow Has More than One Starting Building Block`\n - `TaskBot Does Not Automatically Scroll`\n\n### 26. Contains & Does Not Contain (`Contains And Does Not Contain.png`)\n- **Condition Type**: `Contains & Does Not Contain`. Used in `Start Condition and Set Condition`.\n- **Function**: Checks if dynamic data (e.g. scraped text, table columns, variables) contains or does not contain certain keywords.\n- **Multiple Keywords**: Separate multiple keywords by comma `,`. E.g., `keyword1, keyword2, keyword3`.\n- **Workflow Example**: Mark leads as qualified if their description contains certain keywords (e.g., "marketing, sales, CEO").\n\n### 27. Continue until No Element Is Found (`Continue Until No Element Is Found.png`)\n- **Loop Option**: Setting within `Start Repeat` building block.\n- **Function**: When enabled, the loop continues running until no matching web element is found on the page. Highly useful for working with lists of unknown or dynamic length, such as social media scroll feeds.\n- **How it works**: If any web action inside the loop (e.g. `Save Web Element`, `Click Web Element`, `Hover Web Element`) returns a "selector not found" error, the loop automatically terminates.\n- **Repetition Limit Recommendation**: Strongly recommends setting a `Repetition limit` (e.g., 100 or 500) even when using this toggle, to prevent infinite loops on truly endless feeds (e.g. infinite scroll feeds) or stuck TaskBots.\n- **WARNING**: If this option is enabled but the loop body does **not** include any web element actions (e.g., it only does API requests or data formatting), the loop will **never end**. Must ensure at least one building block interacts with web elements on the page.\n- **Skipping Selector Not Found Error**: If `Save Web Element` has `Skip if no element is found` enabled, OR if the action is wrapped in a `Start Try-Catch` scope, the error is suppressed/skipped. Therefore, the loop will **not** end when that element is missing. In such cases, the loop only ends when the scrolling area reaches the bottom and no further elements can be identified after several scroll attempts. If `Auto-scroll` is disabled, the loop may run indefinitely because TaskBot cannot detect the end of the scrolling area.\n- **Recommendation**: Leave untoggled if you know exactly how many elements are on the page (e.g., scraping exactly 10 profiles per page).\n\n### 28. Convert Native Table to a Google Sheet (`Convert Native Table To A Google Sheet.png`)\n- **Table Feature**: Option available under `More Actions` (3 dots menu) of native tables in ZeroWork.\n- **UI Menu**: Click 3 dots next to table name (`My Table 4590`) -> select `Convert to a Google Sheet`.\n- **CRITICAL WARNING 1 (Irreversible)**: This action is **not reversible**. Once a native table is converted to a Google Sheet, it cannot be converted back to a native table.\n- **CRITICAL WARNING 2 (Data Deletion)**: All existing rows in the native table will be **permanently deleted** upon conversion. Users are strongly advised to use `Export Data as CSV` before converting to secure their data.\n- **Building Block References Preservation**: Existing table references in building blocks remain intact because the `table id` does not change during conversion.\n- **Column Name Matching & Case Sensitivity**: Users must ensure column names match. Case-sensitivity does **not** matter (e.g., `column one` in native table matches `COLUMN One` in Google Sheet). If column names differ, users must rename them in the Google Sheet or native table **before** converting. Any columns present in building blocks but missing in the Google Sheet will be automatically removed/ignored.\n\n### 29. Cookies (`Cookies.png`)\n- **Core Concept**: Enabling TaskBot to access browser cookie sessions so it doesn\'t have to log in every time it runs in an incognito session.\n- **Step 1: Copy Cookies**:\n - Download free Chrome extension `Cookie-Editor`.\n - Go to the target website (e.g., `linkedin.com`), ensure you are logged in.\n - Click Cookie-Editor plugin icon -> click `Export` button -> select `Export as JSON`. Copies cookies to clipboard.\n- **Step 2: Paste Cookies to ZeroWork**:\n - Open TaskBot builder -> click `TaskBot Settings` gear icon (top right).\n - Paste cookies into the `Cookies` text area.\n- **Session Invalidation Warnings**:\n - If you log out of the website in your own browser after copying cookies, it invalidates the cookie session for the TaskBot as well! If you log out, you must re-copy and re-paste fresh cookies.\n - Cookies expire over time. When they expire, simply re-copy and paste them.\n- **Troubleshooting (TaskBot Cannot Log in with Cookies)**:\n - In rare cases, some websites do not accept cookies to be logged in.\n - Solution 1: Build an automated login flow using `Insert Text or Data` (username/password) and `Click Web Element` (Log in button). Passwords can be encrypted using `Encrypt Content`.\n - Solution 2: Use `run modes` (e.g., non-incognito run mode).\n\n### 30. Crash Course (`Crash Course.png`)\n- **Documentation Section**: Beginner introduction video tutorial series covering the basics of building a first TaskBot. Covers fundamental concepts, UI overview, and basic building block usage.\n\n## Batch 4: Create Columns to Enrich Existing Data\n\n### 31. Create Columns (`Create Columns.png`)\n- **Table Feature**: Adding and managing columns within ZeroWork data tables.\n- **UI Menu**: Accessed via Data Tables view -> click `[+ Add Column]` button.\n- **Configuration**:\n - `Column Name`: Text input for column header.\n - `Column Type`: Select data type (e.g., `Text`, `Number`, `Date`, `Boolean`).\n- **Core Rules & Behavior**:\n - Each column is assigned a unique internal `column id` (e.g., `id: 3862`).\n - Renaming a column does **not** break existing building block references because ZeroWork tracks columns by their underlying ID rather than their display name.\n - Deleting a column permanently removes its data and invalidates any building block input fields referencing that column.\n\n### 32. CSS Selectors Master Class (`Css Selectors Master Class.png`)\n- **Documentation Section**: Advanced video tutorial series and comprehensive guide on mastering CSS selectors for robust web automation.\n- **Key Topics Covered**:\n - `nth-match` and indexing for list elements.\n - `has-text` / `text=` filtering for pinpointing elements containing specific text strings.\n - Addressing parent and ancestor containers.\n - Addressing sibling elements (`+` and `~`).\n - Dynamic attribute matching (e.g., `[class*=\'button\']`, `[id^=\'tab-\']`).\n- **Best Practice**: Essential training for building resilient TaskBots that withstand dynamic UI changes and website updates.\n\n### 33. Data Found and Data Not Found (`Data Found And Data Not Found.png`)\n- **Core Concept**: Workflow branching logic executed by conditional building blocks like `Check Web Element`.\n- **Canvas Visual Representation**:\n - **Green Checkmark Branch (`Found`)**: Followed when the target element, text, or condition successfully evaluates to true (e.g., element exists in the DOM and is visible).\n - **Red X Branch (`Not Found`)**: Followed when the target element or condition evaluates to false (e.g., element is missing after timeout expires).\n- **Common Architectural Patterns**:\n - `Check Web Element` (Login Button) -> `[Found]` -> `Send Notification` (Alert user to log in).\n - `Check Web Element` (Next Page Button) -> `[Found]` -> `Click Web Element`. `[Not Found]` -> `Break Repeat` (End pagination loop).\n\n### 34. Data Is Saved in Wrong Format (`Data Is Saved In Wrong Format.png`)\n- **Troubleshooting Scenario**: Scraped text saved via `Save Web Element` contains unwanted formatting, extra whitespace, line breaks, or garbage characters.\n- **Root Cause**: The raw DOM text inside the targeted HTML element includes formatting tags or spacing used by the website\'s layout engine.\n- **Standard Solution**:\n - Add an `Apply Regex` building block immediately after `Save Web Element`.\n - Configure `Select method` to `Replace text`.\n - Use regex patterns to clean the data (e.g., removing extra line breaks with `/\\n+/g`, stripping leading/trailing whitespace, or extracting specific substring patterns).\n - Save the cleaned result back to the target variable or table column.\n\n### 35. Deactivate Building Blocks (`Deactivate Building Blocks.png`)\n- **Feature**: Disabling specific building blocks on the canvas without deleting them.\n- **UI Interaction**: Right-click any building block on the canvas -> select `Deactivate`.\n- **Visual Indicator**: The deactivated building block turns faded/greyed-out on the canvas.\n- **Run Behavior**: When a TaskBot runs, it completely ignores and skips over any deactivated building blocks, moving seamlessly to the next active block in the sequence.\n- **Primary Use Case**: Highly effective for debugging, testing isolated workflow branches, or temporarily turning off notifications/webhook broadcasts during development.\n\n### 36. Delay Times between the Building Blocks (`Delay Times Between The Building Blocks.png`)\n- **Core Concept**: Managing execution pacing between actions. ZeroWork applies built-in default delays for certain major actions (like `Open Link` or `Insert Text or Data`).\n- **Block-Level Delay Configuration**:\n - Accessed inside action building blocks (e.g., `Keyboard Action`, `Open Link`, `Click Web Element`).\n - Fields: `min sec` and `max sec` (e.g., `min sec: 3`, `max sec: 15`).\n - **CRITICAL RULE / BEHAVIOR**: Block-level delay times entered directly into an action building block **always kick in AFTER the action takes place**. E.g., if you set 3 seconds in `Keyboard Action`, TaskBot presses the keys and then waits 3 seconds before moving to the next block. If you need a delay **before** an action, you must use a separate `Delay` building block placed preceding the action.\n- **Randomize Delay Time Setting**:\n - Global option available in TaskBot settings to automatically randomize delay times between all building blocks.\n - Recommends activating only when mimicking human behavior (e.g. social media automation). Warning: significantly slows down overall run time depending on upper limits.\n\n### 37. Delay (`Delay.png`)\n- **Building Block Name**: `Delay`\n- **Modal Configuration UI**:\n - `Minimum (seconds)`: Shortest possible pause duration (e.g., `4`).\n - `Maximum (seconds)`: Longest possible pause duration (e.g., `10`).\n- **Function & Pacing**: Pauses the TaskBot for a randomized duration between the minimum and maximum values before executing the next building block.\n- **Fixed Delay**: To create a fixed, non-randomized pause, enter the **exact same number** in both minimum and maximum fields (e.g., min `5`, max `5`).\n- **Advanced Dynamic Rules & Edge Cases**:\n - Both fields accept decimal values (e.g., `1.50` for 1.5 seconds).\n - Both fields accept variable and table references (e.g., `{id: 113251, name: min}`).\n - **Invalid Reference**: If a variable/table reference contains an invalid value (e.g., text string instead of a number), the Delay block is **skipped entirely**, and TaskBot moves to the next block immediately without pausing.\n - **Max < Min**: If maximum is less than minimum, TaskBot pauses for the **minimum** duration. E.g., min `10`, max `4` -> pauses for exactly 10 seconds.\n - **Empty Fields**: If either field is left empty, the Delay block is skipped.\n - **Zero Delay**: Setting both values to `0` moves to the next step without pausing.\n\n### 38. Delete Data (`Delete Data.png`)\n- **Building Block Name**: `Delete Data`\n- **Modal Configuration UI**:\n - **Dropdown Options**: `Delete all rows` vs `Delete one row`.\n - `Select variables or data table`: Dropdown selecting target table (e.g., `Profiles`).\n- **Delete All Rows**:\n - Permanently removes all data rows from the selected table.\n - **Best Practice**: Place at the very beginning of a TaskBot workflow (before any loops start) when collecting fresh scraping data on every run and needing to overwrite old runs.\n- **Delete One Row**:\n - Deletes a single row during a loop iteration when specific conditions are met.\n - **Workflow Example (Removing Unqualified Leads)**: `Start Repeat` (Dynamic loop over `Profiles`) -> `Start Condition` (Reference: `Qualification` column) -> `Set Condition` (Filter out `\u2260 Qualified`) -> `Delete Data` (`Delete one row` from `Profiles`). Ensures disqualified leads are purged row by row during the loop.\n\n### 39. Device Storage (`Device Storage.png`)\n- **Core Feature**: `zw.deviceStorage.*` API in Write JS / zScript for persisting key-value data locally on the user\'s device. Survives Desktop Agent restarts, uninstalls, and reinstalls. Data is **never** sent to ZeroWork servers.\n- **API Methods (Always Async / Require `await`)**:\n - `await zw.deviceStorage.get(key: string)`: Returns string value, or `undefined` if not set.\n - `await zw.deviceStorage.set(key: string, value: string)`: Saves string value under the key.\n - `await zw.deviceStorage.remove(key: string)`: Removes key and its value.\n - `await zw.deviceStorage.has(key: string)`: Returns `true` if key exists, `false` otherwise.\n - `await zw.deviceStorage.getAll()`: Returns object of all key-value pairs `{ [key: string]: string }`.\n- **Desktop Agent UI (Adding Secrets)**:\n - Open Desktop Agent -> select `Device storage` from tray menu -> click `Add key` -> enter Key (e.g., `salesforce_password`) and Value -> click `Save`.\n- **Handling Non-String Values**:\n - Device storage only accepts strings. Must use `JSON.stringify()` on write and `JSON.parse()` on read for objects/arrays.\n - E.g.: `await zw.deviceStorage.set("bot_state", JSON.stringify(stateObject));`\n- **Logging Secrets Safely (`zw.logTemp`)**:\n - To log sensitive values (passwords, API tokens) during debugging without leaking them, use `await zw.logTemp(secret);` instead of `zw.log()`. `logTemp` displays the value in live run logs but **never** saves it to persistent TaskBot run reports.\n- **CRITICAL WARNING / SECURITY NOTICE**:\n - Avoid using `zw.deviceStorage.get()` to read secrets via `Code in Inputs` inside standard no-code building blocks if those building blocks auto-log their input values, because auto-logged inputs are saved to persistent TaskBot run reports.\n- **Technical Constraints**: Total device storage limit is ~3,000,000 characters. Exceeding this throws an error.\n\n### 40. Dynamic Inputs (`Dynamic Inputs.png`)\n- **Core Concept**: All building block input fields across ZeroWork accept dynamic inputs, references, code, and spintax.\n- **References to Variables and Tables**:\n - Syntax: `{id: 123, name: "Profile name"}`. Replaced dynamically with the underlying table row or variable value during execution.\n- **Code in Inputs (zScript)**:\n - Requires Desktop Agent v1.1.72+.\n - **`${...}` (Expression)**: Evaluates a single JS expression and inserts the result. E.g., `Password: ${await zw.deviceStorage.get("password")}`.\n - **`$${...}` (Code Block)**: Executes full multi-line JS code. Must include `return`.\n - **Auto-installing NPM Packages**: Any `import` statement inside `$${...}` (e.g., `import axios from "axios";`) automatically installs the NPM package locally on the fly.\n- **Spintax**:\n - Syntax: `{ Hi | Hey | Howdy }! How { are you | are things going }?`.\n - Helph vary text content dynamically to bypass anti-spam filters on social media and email platforms.\n\n### 41. Dynamic Loop (`Dynamic Loop.png`)\n- **Building Block / Mode**: `Start Repeat` -> `Select loop type`: `Dynamic`.\n- **Core Function**: Iterates over existing rows in a selected data table one by one.\n- **Key Characteristics & Behavior**:\n - Iterates over existing rows until it consumes all rows in the table.\n - Automatically tracks progress row by row.\n - If you only want to process a specific subset of rows (e.g., 1 row or 10 rows), enter the desired number into `Repetition limit (optional)`.\n- **Primary Use Cases**:\n - **Enriching Existing Data**: Visiting profile links from a table, scraping additional details (like "About Me" or email), and saving them back to the exact same row.\n - **Performing Actions on Existing Data**: Visiting profile links from a table and auto-sending outreach DMs or emails.\n\n### 42. Enrich Existing Data (`Enrich Existing Data.png`)\n- **Workflow Architecture**: Standard pattern for adding scraped data to existing table records.\n- **Step-by-Step Setup**:\n 1. `Start Repeat`: Configure as `Dynamic` loop selecting the target table (e.g., `LinkedIn Profiles`).\n 2. `Open Link`: Reference the table column containing the URL (e.g., `{id: 3862, name: Profile link}`).\n 3. `Save Web Element` (Job Title): Configure selector, set `Save to` selecting the same table (`LinkedIn Profiles`) and target column (`Current job title`).\n 4. `Save Web Element` (About Me): Configure selector, set `Save to` selecting table (`LinkedIn Profiles`) and target column (`About me section`).\n- **Preventing Duplicate Visits (Visited Status Pattern)**:\n - Create a new column in the table called `Profile visit status`.\n - Add an `Update Data` building block at the end of the loop to set `Profile visit status` equal to `visited`.\n - Add `Start Condition and Set Condition` at the beginning of the loop (right after `Start Repeat`). Configure `Start Condition` to reference `Profile visit status`, and `Set Condition` to filter out rows where status `\u2260 visited` (or check if status equals `visited` and branch away). Ensures TaskBot skips already visited profiles on subsequent runs.\n\n## Batch 5: Exact or Loose Match to Hierarchy\n\n### 43. Exact or Loose Match (`Exact Or Loose Match.png`)\n- **Core CSS Selector Concept**: Attribute matching strategies for targeting web elements.\n- **Exact Match (`=`)**:\n - Syntax: `[attribute=\'value\']`. E.g., `button[class=\'pure-button pure-button-primary-progressive\'][type=\'submit\']`.\n - Behavior: Matches the element only if the attribute string is perfectly identical. Brittle if websites dynamically append utility classes or state classes (like `active` or `focus`).\n- **Loose Match (`*=`)**:\n - Syntax: `[attribute*=\'value\']`. E.g., `button[class*=\'pure-button\'][type=\'submit\']`.\n - Behavior: Matches any element whose attribute contains the specified substring.\n - **Best Practice**: Highly resilient technique for web automation. Allows shortening long, fragile class strings to stable core identifiers (e.g., matching `pure-button` within a changing multi-class string).\n\n### 44. Example: Standardize Different Formats (`Example Standardize Different Formats.png`)\n- **Workflow Architecture**: Multi-step data cleaning pattern for converting human-readable scraped numbers (e.g., "7k" followers) into raw integers (7000) for numeric comparisons.\n- **Step 1: Strip Text Characters (`Format Data`)**:\n - Add `Format Data` building block.\n - Configure `Select format action` to `Remove words`.\n - Enter `k` into `Enter words separated by comma`.\n - Set `Data to be formatted` selecting the target table (`Profiles`) and column (`Number of followers`). E.g., converts "7k" to "7".\n- **Step 2: Mathematical Scaling (`Number Operations`)**:\n - Add `Number Operations` building block immediately following `Format Data`.\n - Configure `Choose a number operation` to `Multiply`.\n - Enter `1000` into `Number to multiply by`.\n - Set `Number to multiply` selecting table (`Profiles`) and column (`Number of followers`). E.g., converts "7" to "7000", enabling accurate use in `Actions <, \u2264, >, \u2265` conditions.\n\n### 45. Export Data as CSV (`Export Data As Csv.png`)\n- **Table Feature**: Exporting ZeroWork data tables to local CSV files.\n- **UI Access Methods**:\n 1. **TaskBot Canvas View**: Click `More Actions` (3 vertical dots icon) next to the table name (`My table 4544`) -> select `Export as CSV`.\n 2. **Data Table Expanded View**: Click the 3 vertical dots icon (top right next to `DELETE DATA`) -> select `Export as CSV`.\n 3. **Global Tables Dashboard**: Navigate to `https://creator.zerowork.io/datagroups` -> click the download icon next to any table.\n- **Google Sheets Export**: Explains how to export attached Google Sheets directly from Google\'s UI via `File` -> `Download` -> `Comma Separated Values (.csv)`.\n\n### 46. Format Data (`Format Data.png`)\n- **Building Block Name**: `Format Data`\n- **Modal Configuration UI & Available Actions**:\n - `Remove word`: Strips specified words/substrings (see Remove Words).\n - `Replace text`: Regex/string replacement. E.g., "Hello world" (replace "world" with "universe") -> "Hello universe".\n - `Shorten content length`: Truncates character count (crucial for ChatGPT token limits).\n - `Convert to lower case`: E.g., "HELLO WORLD" -> "hello world".\n - `Convert to upper case`: E.g., "hello world" -> "HELLO WORLD".\n - `Capitalize first letters`: E.g., "hello world" -> "Hello World".\n - `Normalize URL`: Validates and formats web links. E.g., `www.wikipedia.org` -> `https://www.wikipedia.org/`. Note: If the string is invalid, throws a fatal error `The URL is not a valid URL and cannot be normalized`.\n - `Trim white spaces`: Strips leading/trailing spaces. E.g., `" Hello world "` -> `"Hello World"`.\n - `Remove line breaks`: Strips `\\n` and `\\r`. E.g., multi-line string -> single-line string.\n - `Remove smileys`: Strips emojis and emoticons. E.g., `"Hello world \u{1F30D}"` -> `"Hello World "`.\n- **Run Behavior**: If the input value to be formatted is empty/blank, TaskBot takes no action and seamlessly continues its run.\n\n### 47. General: Run, Schedule, Share, Webhooks (`General Run Schedule Share Webhooks.png`)\n- **Documentation Section**: Overview directory listing core operational and management guides for TaskBots.\n- **Sub-pages Included**:\n - `Run` & `Stop`\n - `Log in to the Agent` & `Run Settings`\n - `TaskBot Sharing Options` & `Cookies`\n - `Scheduler` & `Trigger Run via Webhook`\n - `Proxies` & `Remote (Cloud) Execution`\n - `How to Check and Update Your Agent`\n - `Install ZeroWork Agent on VPS`\n\n### 48. Getting Started (`Getting Started.png`)\n- **Documentation Section**: Initial onboarding guide for new ZeroWork users.\n- **Core Setup Steps**:\n 1. **Install the Desktop Agent**: Download and install the local background runtime agent.\n 2. **Install Google Chrome**: Chrome must be installed on the user\'s OS, even if it is not their primary or default browser. TaskBots execute silently within an automated Chrome instance behind the scenes. E.g., Brave browser users must explicitly whitelist the ZeroWork agent in their strict security shields.\n 3. **Watch the Crash Course**: Recommended video onboarding for building the first bot.\n\n### 49. Getting Support (`Getting Support.png`)\n- **Documentation Section**: Troubleshooting hierarchy and official support channels.\n- **Self-Service Protocol**:\n 1. `Check your agent version`: Verify the Desktop Agent is fully updated to the latest version, as many bugs are resolved by updates.\n 2. `Watch the crash courses`: Review Beginner and Selector crash courses (essential before asking selector questions).\n 3. `Explore the docs`: Search Common Problems, Run Reports, Selectors, Building Blocks, Tables, Variables, Loops.\n- **Escalation Channels**:\n - `Report a Technical Error`: Submit reproducible bug steps via Discord `#report-a-bug` channel or official Bug Report Form.\n - `Business Plan Support`: Priority email support (`billing@zerowork.io` / support form) with up to 2 business days response time.\n - `Community Help`: Fast, free peer support in Discord `#community-help` and `#subflow-library`.\n - `Hire a ZeroWork Expert`: 1-on-1 paid consultation for complex selectors or custom bot architecture.\n\n### 50. Go Back or Forward (`Go Back Or Forward.png`)\n- **Building Block Name**: `Go Back or Forward`\n- **Function**: Navigates the active browser tab\'s history backwards or forwards (mimicking native browser Back/Forward buttons).\n- **Run Behavior & Edge Cases**:\n - If there is no previous or next page in the tab\'s session history to navigate to, the action is entirely non-consequential. TaskBot does not fail or throw an error; it simply continues seamlessly to the next building block.\n\n### 51. Google Sheets (`Google Sheets.png`)\n- **Core Feature**: Comprehensive integration capabilities for linking Google Sheets directly to TaskBot data tables (pull, update, append).\n- **Architectural Rules & FAQ**:\n - `Creating New Columns`: Add columns directly in the Google Sheet, then open TaskBot table view and click `Refetch columns from Google Sheet`.\n - `Renaming or Deleting Columns`: Click `Refetch columns`. Any columns removed from the sheet will be automatically stripped from building block input references. If a column is renamed/deleted in the sheet but was never referenced in any building blocks, no action occurs. E.g., column matching is **case-insensitive** (`column one` matches `Column One`).\n - `Quota & Usage Limits`: To avoid exceeding Google Sheets API rate limits, ZeroWork automatically batches row updates every 50 rows by default. E.g., on a 500-row sheet, TaskBot updates the sheet exactly 10 times. Batch size can be customized in `Start Repeat` additional options. If a rate limit is hit, TaskBot automatically retries 10 times before failing and logging an error in Run Reports.\n - `Deleted Sheet Handling`: TaskBot validates the Google Sheet link and OAuth session at the very start of every run. If invalid or expired, the run aborts immediately with an error report.\n - `Duplicating TaskBots`: Duplicating TaskBot A (linked to Sheet A) creates TaskBot B with a new table ID, but still pointing to Sheet A. Users can keep them sharing the sheet, or link TaskBot B to Sheet B without remapping building block references (because references use table ID, not sheet name).\n - `Re-authentication`: If OAuth tokens expire, go to Google Account Data & Privacy -> Third-party apps -> remove ZeroWork -> return to ZeroWork and re-authenticate.\n\n### 52. Hierarchy (`Hierarchy.png`)\n- **Core CSS Selector Concept**: Structuring selector paths based on DOM element nesting and parent-child relationships. E.g., Wikipedia search button.\n- **Strict Hierarchy (`>`)**:\n - Syntax: `parent > direct_child`. E.g., `body > div > form > fieldset > button`.\n - Behavior: Requires the child element to be an immediate direct descendant of the parent. Fails if intermediate wrapper divs are dynamically inserted.\n- **Loose Hierarchy (` ` space)**:\n - Syntax: `ancestor descendant`. E.g., `body button`.\n - Behavior: Matches the descendant element anywhere inside the ancestor container, regardless of how many intermediate DOM nodes exist between them.\n- **Advanced Combinations & Attribute Injection**:\n - Combine strict and loose: `tag1 tag3 > tag4` (tag3 is anywhere inside tag1, but tag4 is a direct child of tag3).\n - Inject attributes at any level: `tag1[attribute=\'value\'] > tag2[attribute=\'value\']` or `body > div button[class*=\'pure-button\']`.\n\n## Batch 6: Home to Install ZeroWork Agent on VPS\n\n### 53. Home and Welcome (`Home.png`)\n- **Documentation Section**: Home and Welcome (Root Overview)\n- **Target Audience & Core Value**: Dedicated to creators building TaskBots to automate repetitive browser tasks (typing, clicking, copy-pasting data) without requiring any coding skills. TaskBots mimic human interactions on any website to enable limitless automation.\n- **Typical Use Cases**:\n - `Scrape`: Collect LinkedIn profiles, Facebook group members, Instagram followers, Amazon products.\n - `Enrich data`: Collect additional granular data from individual profile/product pages (email, job title, rating, reviews).\n - `Automate actions`: Auto-send DMs, auto-like content, auto-follow profiles, auto-fill forms.\n - `Transform data (calculate, filter, compare)`: Auto-qualify leads based on keywords, geographic location, or activity; auto-format or tag collected data.\n - `Add AI`: Auto-post AI-generated blog posts/comments, auto-reply to messages with AI, auto-send AI-generated prospect/product summaries via email.\n- **Getting Started & Onboarding Links**: Sign Up, Install the Agent, Crash Course, FAQs.\n- **TaskBot Creation Architecture**: Guides divided into Running TaskBots, Using Building Blocks, Using Selectors, Using Tables, Using Variables.\n- **Troubleshooting & Support Hierarchy**: Common Problems, TaskBot Creator Support.\n\n### 54. Hover Web Element (`Hover Web Element.png`)\n- **Building Block Name**: `Hover Web Element`\n- **Function**: Simulates a native mouse hover over a specified web element.\n- **Primary Use Case**: Unlocking elements or tooltips that are only visible in the DOM or UI when hovered. E.g., on Facebook Group posts, the exact timestamp/date is hidden behind a relative time string ("3 March at 04:11"); hovering over it reveals the exact absolute timestamp tooltip (`Sunday, 3 March 2024 at 04:11`).\n- **Workflow Pattern (Hover & Scrape)**:\n - Step 1: Add `Hover Web Element` building block. Configure with the CSS or XPath selector of the trigger element (e.g., `div > span > span > span > span > a > span > span[aria-labelledby]`).\n - Step 2: Add `Save Web Element` building block immediately following the hover block. Configure with the selector of the newly appeared tooltip element to scrape the revealed data.\n- **Modal Configuration UI**:\n - `Enter CSS or XPath selector`: Input field for the target element to hover over. E.g., `div > span > span > span > span > a > span > span[aria-labelledby]`.\n - `min sec` / `max sec`: Configurable randomized delay times executed during the hover action (e.g., min sec `2`, max sec `0`).\n\n### 55. How to Add Tables (`How To Add Tables.png`)\n- **Documentation Section**: How to Add Tables (under `Using Tables`)\n- **Three Methods to Create Data Tables**:\n 1. `ZeroWork native table`: Built directly inside ZeroWork\'s table management UI from scratch (see Native Tables).\n 2. `Google Sheet link`: Synchronizing an external Google Sheet via its sharing link (see Google Sheets).\n 3. `Uploading a CSV file`: Uploading a local CSV file automatically generates table columns and imports all rows based on the CSV headers. E.g., simply upload a CSV file and table columns/rows will be created instantly. Note: Tables created via CSV upload are converted into ZeroWork native tables.\n- **Architectural Decision Guide**: Links to `Using Google Sheet vs. Native Tables` to assist users in selecting the optimal table architecture for their specific automation scale and performance needs.\n\n### 56. How to Build Custom Selectors (`How To Build Custom Selectors.png`)\n- **Documentation Section**: How to Build Custom Selectors (under `Using Selectors`)\n- **Core Philosophy**: When right-click copying selectors from browser dev tools fails to produce reliable results across dynamic web pages, users must learn to build custom, resilient selectors. Relying on auto-copied selectors is often insufficient for modern social media platforms and complex web apps.\n- **Accessibility**: Emphasizes that **no coding skills are required** to master custom selector construction. Includes an embedded video crash course.\n- **Supported Selector Engines**: Fully supports both CSS and XPath selectors. The primary documentation focuses on CSS selectors as they are more approachable for beginner and intermediate builders. (Links to `How to Use XPath in ZeroWork (advanced)` for complex use cases).\n- **Structured Learning Path**:\n - `Basic Concepts of Selectors`: Understanding HTML tags, classes, IDs, and attributes.\n - `One Element Can Have Many Selector Expressions`: Exploring alternative targeting strategies.\n - `Check if Selector Is Correct and Unique`: Validating selectors in the browser console/devtools before bot deployment.\n - `Exact or Loose Match`: Utilizing `= ` vs `*= ` attribute matching.\n - `Hierarchy`: Mastering strict `>` vs loose ` ` descendant combinators.\n - `Combine Filters with Standard CSS Logic`: Chaining multiple attribute conditions.\n - `Lists: Incremental CSS Selectors`: Targeting repeating elements in scraping loops.\n - `Addressing Siblings`: Utilizing `+` (exact) and `~` (loose) sibling combinators.\n\n### 57. How to Check and Update Your Agent (`How To Check And Update Your Agent.png`)\n- **Documentation Section**: How to Check and Update Your Agent (under `General: Run, Schedule, Share, Webhooks`)\n- **Protocol for Checking Agent Status**:\n 1. Open the local Desktop Agent options menu from the OS toolbar/system tray (displays current version e.g., `ZeroWork Version 1.1.46`, Status: Ready, active Account, Scheduler connection status, Logout, Restart, Quit).\n 2. Navigate to the official agent download page (`https://creator.zerowork.io/download-agent`).\n 3. Compare versions: If the latest version displayed on the download page (e.g., Mac OS `1.1.55`, Windows `1.1.55`, Linux `1.1.55 BETA`) is higher than the local installed version, the agent is outdated. Note: First-time downloaders must return to `https://creator.zerowork.io/workflows` to build bots.\n- **Automated Update Protocol**:\n 1. In the agent options menu, click the blue `Check for update` button. Confirm the OS prompt to install the new version.\n 2. Once the update finishes, confirm the prompt to restart the agent.\n- **Manual Fallback Protocol**: If the automated update mechanism fails due to OS firewall or permissions issues, users can safely uninstall their existing agent and manually download/install the latest version from `https://creator.zerowork.io/download-agent`.\n- **Data Preservation Guarantee**: Explicitly assures users that `Uninstalling and reinstalling the agent will not affect any of your scheduled TaskBots or webhooks`.\n\n### 58. How to Use XPath in ZeroWork (advanced) (`How To Use Xpath In Zerowork Advanced.png`)\n- **Documentation Section**: How to Use XPath in ZeroWork (advanced) (under `Using Selectors`)\n- **Context**: While ZeroWork documentation prioritizes CSS selectors for onboarding simplicity, advanced users familiar with XML Path Language can leverage full XPath capabilities.\n- **Automatic Syntax Recognition**: TaskBots automatically detect and parse an XPath selector when the input string begins with a double slash `//`. E.g., `//*[@id=\'js-lang-lists\']/div[1]/ul/li[12]`.\n- **Explicit Declaration Syntax**: Users can also explicitly force XPath evaluation by prefixing the selector string with `xpath=`. E.g., `xpath=//button`.\n- **Dynamic Loop Indexing for XPath Lists**:\n - To iterate over a list of incrementing XPath selectors within a scraping loop, users apply the exact same `loop_index` bracket syntax used for CSS selectors.\n - Example syntax: `//*[@id=\'js-lang-lists\']/div[1]/ul/li[{loop_index,1}]`. During runtime, TaskBot dynamically substitutes `{loop_index,1}` with incrementing integers (`li[1]`, `li[2]`, `li[3]`, etc.) to scrape public lists item by item.\n\n### 59. Import Data from CSV (`Import Data From Csv.png`)\n- **Documentation Section**: Import Data from CSV (under `Using Tables`)\n- **Core Functionality**: Create new native tables from scratch using CSV uploads, or import/merge CSV data into existing native tables.\n- **Creating a New Table from CSV**:\n - Modal Workflow: Click `Add Table` -> Select table type `Import data from CSV` -> Click `UPLOAD CSV` -> Click `ADD TABLE`. Automatically establishes table schema (columns) and populates initial rows from the CSV file.\n- **Updating Existing Native Tables with CSV**:\n - UI Access Locations:\n 1. TaskBot canvas view: Click `More Actions` (3 vertical dots icon) next to the table name (`My table 4544`) -> Select `Import data from CSV`.\n 2. Global tables dashboard (`https://creator.zerowork.io/datagroups`).\n 3. Expanded table view: Click `More Actions` (3 vertical dots icon top right next to `DELETE DATA`) -> Select `Import data from CSV`.\n- **Column Matching & Merging Rules**:\n - `Header Matching`: Ensure CSV column headers match existing table column names.\n - `Non-matching Columns`: If the CSV contains unmapped columns, the table updates successfully but unmapped columns are safely ignored/discarded.\n - `Column Sequence`: The order of columns in the CSV versus the table does not affect import accuracy.\n - `File Name`: The CSV filename does not need to match the table name.\n - `Case Sensitivity`: Column header matching is **case-insensitive** (`fb link` successfully maps to `FB Link`).\n - `Append vs Overwrite`: By default, imported CSV data is appended (merged as new rows below existing data) unless the `overwrite current data` checkbox is explicitly checked.\n- **Checkbox "overwrite current data"**:\n - When checked: Existing table data is permanently purged and replaced entirely by the new CSV payload. Strongly recommends exporting current data as CSV first to prevent accidental data loss.\n - When unchecked: Operates in default append mode.\n- **Google Sheets Import**: For tables linked to external Google Sheets, users must perform CSV imports directly within Google\'s UI via `File` -> `Import`.\n\n### 60. Imports and Package Management (`Imports And Package Management.png`)\n- **Documentation Section**: Imports and Package Management (under `Write Javascript`)\n- **Core Capabilities**: TaskBots support standard JavaScript package imports (e.g., `import dayjs from \'dayjs@1.11.11\'`) or advanced dynamic loading via the `zw.import()` API. ZeroWork automatically resolves, downloads, and installs missing npm packages at runtime. Includes full package lifecycle management via `zw.packages.list()`, `zw.packages.uninstall()`, and `zw.packages.uninstallAll()`.\n- **Local Execution Directive (`#ze-run-locally`)**: Adding the comment `// #ze-run-locally` (or checking the `Run locally` UI checkbox) instructs the engine to execute the JS block in the local Node.js background process rather than the active browser tab context. Essential for utilizing OS-level modules (`child_process`, `fs`, `robotjs`). E.g., shows snippet executing `execSync` to launch Notepad/TextEdit/gedit based on `process.platform` (`win32`, `darwin`, `linux`), waiting via `zw.delay()`, and simulating physical keystrokes via `robot.type()`.\n- **1. Standard Imports**:\n - Supports standard ESM (`import`) or CommonJS (`require`) syntax. Automatically fetches and caches packages. E.g.:\n ```javascript\n // ESM default import\n import dayjs from \'dayjs@1.11.11\';\n await zw.log("now", dayjs().toISOString());\n // ESM subpath import\n import chunk from \'lodash/chunk\';\n await zw.log("chunked result", chunk([1, 2, 3, 4], 2));\n // CommonJS require\n const _ = require("lodash@4.17.21");\n // Git repository import (HTTPS only)\n import lodash from \'git+https://github.com/lodash/lodash.git\';\n ```\n - `Notes`: Installed packages are globally available across TaskBots by default. To isolate dependencies to a single TaskBot, use `zw.import()` with `{ isolate: true }`. Packages unused for 7 days (168 hours) are automatically garbage collected (configurable via `uninstallIfUnusedFor`). Disable auto-import parsing by adding the comment `// #ze-disable-auto-import`.\n- **2. Advanced Imports via `zw.import()` API**:\n - Syntax: `await zw.import(pkg: string | string[] | { [key: string]: string }, options?: ImportOptions)`\n - Options Interface: `{ isolate?: boolean; uninstallIfUnusedFor?: number | null; preferDefault?: boolean; }`\n - `Single package with options`: `const dayjs = await zw.import(\'dayjs@1.11.11\', { isolate: true, uninstallIfUnusedFor: 300 });`\n - `Multiple packages as array`: `const [dayjs, lodash] = await zw.import([\'dayjs@1.11.11\', \'lodash@4.17.21\']);`\n - `Named mapping as object`: `const { time, dash } = await zw.import({ time: \'dayjs@1.11.11\', dash: \'lodash@4.17.21\' });`\n - `Installing from Git`: `const gitLodash = await zw.import(\'git+https://github.com/lodash/lodash.git\');`\n - `Bypassing Garbage Collection`: Pass `{ uninstallIfUnusedFor: null }` to persist the package indefinitely.\n - `Import Option Details`:\n - `uninstallIfUnusedFor` (default: 168). Retention window in hours.\n - `isolate` (default: false). When true, scopes the package installation exclusively to the active TaskBot ID. Crucial when different bots require conflicting package versions. Note: Deleting a TaskBot does not automatically delete isolated packages; manage via `zw.packages.*`.\n - `preferDefault` (default: true). Automatically unwraps `module.default` when present. E.g., `const mysql = await zw.import(\'mysql2@latest/promise\');` vs `const chalk = await zw.import(\'chalk@4\');`.\n - `Input Validation`: Rejects tarball URLs, local file paths, and non-HTTPS Git URLs.\n- **3. Special Package Types**:\n - `Built-in Packages`: Pre-bundled modules that resolve instantly without network installation. Includes Node core modules (`fs`, `os`, `path`), `axios` pinned to `^1.6.6`, and `playwright` pinned to `^1.45.0`. Built-ins do not appear in `zw.packages.list()` and cannot be uninstalled or version-bumped. E.g., `import * as fs from \'fs\';` or `import axios from \'axios\';`.\n - `Pure ESM Packages`: ZeroWork\'s runtime is not pure ESM yet. Importing pure ESM packages throws a fatal error: `This package appears to be pure ESM`. Workarounds: Use a maintained CommonJS/non-ESM fork (e.g., `cacheable-lookup`), pin to an older non-ESM version (e.g., `chalk@4`), or pre-bundle the package using a bundler before pasting into ZeroWork.\n - `Native Packages`: C/C++ native addons (e.g., `robotjs`, `ffi-napi`) require OS-level build tools (Python, Visual Studio C++ build tools, node-gyp) and compatible Node binaries. While advanced users can configure local environments to execute native bindings, they are not guaranteed to work across all machines or cloud runners.\n- **4. Reusing References (Performance Best Practices)**:\n - Importing packages inside scraping loops is an anti-pattern that causes severe execution overhead.\n - Recommended Practice: Declare imports once outside the loop, or store resolved module references in the global state object (`zw.state.cachedResolvedImports`) for micro-optimized access across separate JS building blocks. E.g.:\n ```javascript\n // In an early JS block:\n const cachedDayjs = await zw.import(\'dayjs@1.11.11\');\n zw.state.access().cachedResolvedImports = { dayjs: cachedDayjs };\n // In a later JS block:\n await zw.log(zw.state.access().cachedResolvedImports.dayjs().toISOString());\n ```\n- **5. Package Management APIs**:\n - `zw.packages.list()`: Returns `string[]` of all installed package IDs.\n - `zw.packages.uninstall(id: string)`: Uninstalls a specific package instance.\n - `zw.packages.uninstallAll()`: Purges all user-managed packages from disk (built-in packages remain unaffected).\n - `Package ID Structure`: `<taskbotId>_` prefix (if isolated), lower-cased sanitized package name, `@`, version/commit hash. E.g., `lodash@4.17.21` or `12345_lodash@4.17.21`.\n - `Scripting Examples`: Shows programmatic cleanup scripts filtering `zw.packages.list()` to uninstall specific versions or wipe all packages associated with a specific TaskBot ID (`id.startsWith(`${myTaskBotId}_`)`).\n- **6. Bridging Local Packages to Browser Execution**:\n - Because third-party package management operates strictly in the local Node.js background process, packages cannot be directly imported inside in-browser JS blocks.\n - Bridging Pattern: Import the package in a local JS block (`#ze-run-locally`), inject a wrapper function into the browser page context via `zw.browserContext.setDefaults()` and `context.exposeFunction()`, then call the exposed function inside a subsequent in-browser JS block. E.g.:\n ```javascript\n // Block 1 (Local execution):\n // #ze-run-locally\n import lodash from "lodash";\n await zw.browserContext.setDefaults({\n pageInit: async (page, context) => {\n await context.exposeFunction("exposedChunkFn", (arr) => lodash.chunk(arr, 2));\n }\n });\n ```\n ```javascript\n // Block 2 (Browser execution):\n const result = await exposedChunkFn([1, 2, 3, 4]); // Returns [[1,2], [3,4]]\n await zw.log("exposedChunkFn result", result);\n ```\n - `Critical Asynchronous Rule`: Functions exposed to the browser via `context.exposeFunction()` **always become asynchronous**, even if the underlying local function is synchronous. In-browser code must always invoke exposed functions using `await`.\n\n### 61. Insert Text or Data (`Insert Text Or Data.png`)\n- **Building Block Name**: `Insert Text or Data`\n- **Function**: Injects text strings or dynamic data into web input fields (form inputs, search bars, text areas). E.g., navigating to wikipedia.org and entering search queries.\n- **Modal Configuration UI & Options**:\n - `Dynamic Data References`: Click the `V` (variable) or `T` (table) icon at the top right to insert dynamic tokens. E.g., `Hi {id: 3862, name: Profile name}, let\'s connect!`.\n - `Insert instantly without typing delay`:\n - When enabled (Instant Paste): Bypasses simulated typing entirely, instantly pasting the full text string into the target field. Requires configuring a valid CSS or XPath selector to identify the input element.\n - When disabled (Simulated Typing): Simulates human typing character by character at a configurable typing speed. The selector becomes optional; if omitted, TaskBot types directly into whichever input field currently holds the active OS/browser mouse cursor focus.\n - `Using spintax`: Supports nested spintax variations to randomize outbound messaging and avoid spam filters. E.g., `{Hi|Hello|Hey|Howdy}, {how are you?|what\'s new?|how\'s everything?}`.\n - `Selector Behavior Summary`:\n - When instant paste is enabled: Selector is **mandatory**.\n - When instant paste is disabled: Selector is **optional**. E.g., on search engines like Google, DuckDuckGo, or Wikipedia, the browser automatically focuses the search input on page load, allowing TaskBots to type search queries directly without configuring a CSS selector.\n - `Encrypt Content (Secure Credentials)`: For logging into web portals directly without session cookies, users click the padlock icon to encrypt sensitive passwords. Once encrypted and saved, the password string cannot be viewed, copied, or edited. To update an encrypted password, users must delete the building block entry and re-enter the new password. ZeroWork guarantees no plain text copies of encrypted credentials are ever stored.\n- **Troubleshooting & FAQ**:\n - `Can I use the mouse cursor instead of a selector?`: Yes, but strictly when `Insert instantly without typing delay` is disabled.\n - `When I use a table reference, no data is inserted`: Occurs when the workflow lacks a dynamic loop (`Start Repeat`) configured to iterate over table rows (links to `When I Use Data from Table, No Data is Being Pulled`).\n\n### 62. Install the Agent (`Install The Agent.png`)\n- **Documentation Section**: Install the Agent (under `Getting Started`)\n- **Core Architecture**: The Desktop Agent is a lightweight, headless local background service required to execute TaskBots on the user\'s physical machine. The agent possesses no graphical user interface (GUI); it runs silently in the OS system tray/toolbar. All bot building and workflow orchestration occur via the web application at `https://creator.zerowork.io/workflows`.\n- **Step 1: Download**: Official binaries available for Mac, Windows, and Linux at `https://creator.zerowork.io/download-agent`.\n- **Step 2: OS-Specific Installation**:\n - `Mac OS`: Drag the ZeroWork Agent icon into the system Applications folder.\n - `Windows`: Execute the downloaded `.exe` installer. Confirm UAC elevation prompts and grant firewall access.\n - `Linux`: Choose `.AppImage`, `.deb`, or `.rpm` packages. Use `.deb` for Ubuntu/Linux Mint, `.rpm` for Fedora/RHEL, and `.AppImage` for universal Linux distribution compatibility.\n - `Linux Troubleshooting & Notes`:\n - For `.AppImage`, installing `AppImageLauncher` (`https://github.com/TheAssassin/AppImageLauncher`) is highly recommended for proper desktop integration.\n - If the system tray icon fails to appear after 30 seconds but the background service is verified running (accessible via `http://localhost:9990` in a browser), the desktop environment lacks `appindicator` support. Solved by installing the GNOME "Extension Manager" application and adding the `appindicator` system tray extension. Note: openSUSE distributions are not officially supported.\n- **Step 3: Activation & Background Operation**:\n - Double-click the installed agent application to initialize it. The agent icon appears in the OS tray (top-right on Mac, bottom-right on Windows).\n - Confirm OS security prompts allowing execution of software downloaded from the internet.\n - Emphasizes that the lack of an application window is entirely intentional for headless background automation.\n- **Step 4: Installation Verification**:\n - Build a basic 1-block TaskBot containing `Open Link` pointing to `https://www.wikipedia.org/`. Trigger a run. If an automated Chrome instance launches, navigates to Wikipedia, and terminates successfully, the agent is fully operational.\n - `Windows Focus Note`: On Windows OS, the automated Chrome instance might launch in the background behind active desktop windows. Users should toggle `Stay on Page after Run` in bot settings or minimize active windows to verify browser execution.\n- **Agent Options Access**: Click the tray icon to verify runtime status (`Status: Ready`) and active user account binding.\n\n### 63. Install ZeroWork Agent on VPS (`Install Zerowork Agent On Vps.png`)\n- **Documentation Section**: Install ZeroWork Agent on VPS (under `General: Run, Schedule, Share, Webhooks`)\n- **Core Capability**: Deploying the ZeroWork Desktop Agent onto a Virtual Private Server (VPS) enables 24/7 uninterrupted, automated cloud execution without requiring the user\'s local physical computer to remain powered on.\n- **Community Guide**: Features an embedded step-by-step video tutorial by CodingMenace (`Install ZeroWork Agent on Linux VPS in Minutes! (FREE SCRIPT)`), guiding users through provisioning a Linux VPS, executing an automated installation script, and verifying headless agent connectivity.\n\n\n## Batch 7: Keyboard Actions to My Taskbot Saves Some Data But Not All\n\n### 64. Keyboard Action Is Not Working As Expected (`Keyboard Action Is Not Working As Expected.png`)\n- **Documentation Section**: Common Problems -> Keyboard Action Is Not Working As Expected\n- **Core Problem**: Simulated keystrokes or keyboard shortcuts fail to produce the expected character input or trigger the desired web application event.\n- **Common Causes & Troubleshooting**:\n 1. `Missing DOM Focus`: The target web element (input field, textarea, dropdown) lacks active focus before the keystroke event is fired. Unlike direct text insertion (`Insert Text or Data` with instant paste), simulated keyboard events require the operating system/browser cursor to actively reside within the element. Solution: Add a `Click Web Element` block immediately prior to the `Keyboard Action` block to ensure focus.\n 2. `Character Encoding / Keyboard Layout Mismatches`: Emulated keystrokes rely on keycodes that can conflict with non-standard OS keyboard layouts (e.g., Dvorak, AZERTY, custom language IME). Ensure the OS keyboard layout matches standard expected input mappings during headless execution.\n 3. `Protected Web Inputs / Bot Detection`: Highly secure web portals (banking, advanced anti-bot captchas) employ JavaScript event listeners that detect synthetic `KeyboardEvent` properties (`isTrusted: false`). If synthetic events are blocked, users must utilize local Node execution (`// #ze-run-locally`) paired with OS-level macro automation libraries (e.g., `robotjs`) to simulate physical hardware-level keystrokes.\n\n### 65. Keyboard Action (`Keyboard Action.png`)\n- **Building Block Name**: `Keyboard Action`\n- **Function**: Simulates physical keyboard strokes, key combinations, and modifier shortcuts within the active browser tab.\n- **Modal Configuration UI & Capabilities**:\n - `Simulated Keystrokes`: Supports typing individual characters, strings, or invoking functional keys (`Enter`, `Tab`, `Space`, `Escape`, `Backspace`, `ArrowUp`, `ArrowDown`, `ArrowLeft`, `ArrowRight`).\n - `Modifier Key Support`: Supports chaining modifier keys (`Ctrl`, `Alt`, `Shift`, `Meta` / `Cmd`) with standard keys to execute complex web shortcuts (e.g., `Ctrl+A` to select all, `Ctrl+C` to copy, `Ctrl+V` to paste).\n - `Delay Intervals`: Configurable delay timing between individual keystrokes (measured in milliseconds/seconds) to mimic human typing cadence and bypass basic behavioral bot detection mechanisms.\n- **Workflow Patterns & Best Practices**:\n - `Form Submission`: Chaining `Insert Text or Data` followed by `Keyboard Action` (`Enter`) to submit search forms or login prompts where no explicit submit button exists.\n - `Modal Dismissal`: Sending `Escape` to close intrusive popups, cookie consent banners, or dialog overlays blocking the underlying DOM.\n - `Manual Scrolling`: Executing `Space` or `ArrowDown` inside a scraping loop to force lazy-loaded feeds to fetch new DOM nodes when automated scrolling fails.\n\n### 66. Launch Browser (`Launch Browser.png`)\n- **Building Block Name**: `Launch Browser`\n- **Function**: Explicitly initializes an automated browser instance session with granular environmental configuration. Note: If omitted, TaskBots automatically launch a default Chrome instance on run start.\n- **Modal Configuration UI & Advanced Parameters**:\n - `User-Agent String Overriding`: Allows custom `User-Agent` string configuration to spoof different operating systems, browser versions, or mobile devices (e.g., mimicking an iPhone or Safari on macOS to scrape mobile-optimized DOM structures).\n - `Proxy Configuration Settings`: Input fields to route browser traffic through dedicated proxy servers (`HTTP`, `HTTPS`, `SOCKS5`). Supports authentication credentials (`username:password@ip:port`). Essential for rotating IP addresses during high-frequency scraping runs to prevent IP bans.\n - `Viewport Dimension Controls`: Explicitly sets browser window width and height (e.g., `1920x1080`). Critical for responsive websites where DOM elements (like hamburger menus or pagination bars) change structure or visibility based on viewport resolution.\n - `Headless vs. UI Mode`: Configures whether the browser window executes visibly on the desktop or entirely hidden in the background (headless mode) to conserve CPU/RAM resources during large-scale cloud execution.\n\n### 67. Lists: Incremental CSS Selectors (`Lists Incremental Css Selectors.png`)\n- **Documentation Section**: Using Selectors -> Lists: Incremental CSS Selectors\n- **Core Architectural Concept**: The "List-Loop" paradigm. To scrape or interact with repeating elements (e.g., e-commerce product grids, search result lists, social media feeds) item by item, TaskBots require dynamic selector indexing rather than static selectors.\n- **Dynamic Indexing Syntax (`{loop_index}`)**:\n - Users replace the static integer in a CSS pseudo-class (like `:nth-child()`, `:nth-of-type()`) with the dynamic token `{loop_index}`.\n - E.g., `ul.product-list > li:nth-child({loop_index})`.\n - During runtime execution within a `Start Repeat` loop, the engine dynamically substitutes `{loop_index}` with the current loop iteration integer (`1`, `2`, `3`, `4`, etc.).\n- **Advanced Offset Configuration (`{loop_index, offset}`)**:\n - Syntax: `{loop_index, starting_number}`.\n - E.g., If the first 3 items in a list are sponsored ads and actual organic results begin at index 4, configure the selector as `ul.product-list > li:nth-child({loop_index, 4})`. On loop iteration 1, TaskBot evaluates `li:nth-child(4)`; on iteration 2, `li:nth-child(5)`.\n- **Troubleshooting & Common Mistakes**:\n - `Missing Loop`: Using `{loop_index}` outside of a `Start Repeat` block causes a fatal runtime parsing error.\n - `Brittle Parent Wrappers`: Ensure the parent container selector preceding `:nth-child()` is stable and uniquely identifies the exact list wrapper div.\n\n### 68. Local and Global State (`Local And Global State.png`)\n- **Documentation Section**: Write Javascript -> Local and Global State\n- **Core Architecture**: State management APIs allowing JavaScript building blocks to persist and share data in memory across blocks or across bot runs. All data remains strictly local to the user\'s physical machine/VPS; ZeroWork never transmits state data to cloud servers.\n- **1. Local Per-Run State (`zw.state.*`)**:\n - Scope: Ephemeral scratchpad created on run start and permanently **deleted when the run terminates**.\n - `zw.state.access()`: Returns a live mutable object for local Node context (`// #ze-run-locally`). Can hold any JavaScript type (functions, Maps, Sets, Playwright page/context instances). E.g., `zw.state.access().myHelper = () => { ... };`.\n - `zw.state.clear()`: Purges the entire run state object.\n- **2. Global State (`zw.globalState.*`)**:\n - Scope: Device-level scratchpad shared across all TaskBots running on the same Desktop Agent instance. **Persists across runs** until the Desktop Agent application is explicitly quit or restarted. E.g., caching authentication tokens or tracking cumulative daily run counts across multiple bots.\n - `zw.globalState.access()`: Returns live mutable object for local Node context.\n - `zw.globalState.clear()`: Purges global state.\n - `Persistence Warning`: Global state is NOT durable disk storage. For permanent storage, use Data Tables (`zw.setRef()`) or Device Storage (`zw.deviceStorage.*`).\n- **3. Browser Context State (`zw.state.browser.*` & `zw.globalState.browser.*`)**:\n - Scope: In-browser JS execution blocks cannot directly access the background Node memory (`*.access()`). They must utilize async JSON snapshots.\n - APIs: `await zw.state.browser.getCopy({ key?: string })` and `await zw.state.browser.commit({ state: any, key?: string })`.\n - `Serialization Constraint`: Values passed between browser and local state must be **strictly JSON-safe**. Functions, Maps, Sets, and circular DOM references cannot be serialized.\n - `Payload Size Limit`: Snapshot payloads exceeding **~3,000,000 characters** fail to transfer. Use the `key` parameter to fetch/commit only specific lightweight slices of state.\n - `Asynchronous Requirement`: All `*.browser.*` methods are asynchronous and must be invoked with `await`. E.g., `const state = await zw.state.browser.getCopy();`.\n\n### 69. Log in to the Agent (`Log In To The Agent.png`)\n- **Documentation Section**: General: Run, Schedule, Share, Webhooks -> Log in to the Agent\n- **Core Requirement**: Authentication binding between the local Desktop Agent background service and the user\'s ZeroWork cloud account. Required strictly when utilizing cloud Webhooks or the automated Scheduler. If users only trigger TaskBots manually from the web creator portal, agent login is optional.\n- **Frequency**: Needs to be performed **only once** per machine following initial installation.\n- **Authentication Workflow & UI Status**:\n - Step 1: Click the ZeroWork agent icon in the OS system tray (Mac menu bar top-right, Windows taskbar hidden icons bottom-right).\n - Step 2: Observe initial unauthenticated status: `Account: Click to login` and `Scheduler: disconnected`. Click the account line to open the web OAuth login prompt.\n - Step 3: Following successful authentication, verify active connection status: `Account: user@email.com` and `Scheduler: connected`. (The same connected status applies to Webhooks).\n\n### 70. Log (`Log.png`)\n- **Building Block Name**: `Log`\n- **Function**: Records custom text messages, debugging info, and audit trails during a TaskBot\'s runtime execution.\n- **Display & Storage Locations**:\n 1. `Real-Time Dialog`: Displayed live within the desktop `Running TaskBots` overlay window (e.g., `AGENT: Starting run for TaskBot... Log - building block id 19220: "This is the current counter: 1"`).\n 2. `Run Reports Dashboard`: Permanently archived in the web portal under `TaskBot Run Reports`, providing full historical audit logs with filtering (`Only show warnings and errors`) and CSV export capabilities (`Export csv`).\n- **Block Configuration & Dynamic Variables**:\n - Supports embedding dynamic variable or table tokens directly into the log string. E.g., `Current scraping target: {id: 102, name: Company Name}, iteration {id: 55, name: loop_index}`.\n - `Empty Message Behavior`: If the block is left entirely blank, TaskBot logs a generic warning but execution continues uninterrupted; the run status is NOT marked as failed.\n\n### 71. Metadata (`Metadata.png`)\n- **Documentation Section**: Write Javascript -> Metadata\n- **Core Capability**: Programmatic JavaScript APIs allowing JS building blocks to inspect active runtime environment details, TaskBot configuration, and data schema definitions.\n- **1. `zw.getAgentInfo()`**:\n - Returns synchronous object containing the local Desktop Agent binary version: `{ version: string }` (e.g., `{ version: "1.1.72" }`). Available synchronously across both local Node and browser JS contexts.\n- **2. `zw.getTaskbotInfo()`**:\n - Returns detailed runtime metadata object:\n ```typescript\n {\n id: number,\n name: string, // TaskBot name\n runType: "immediate" | "scheduled" | "webhook",\n currentRunResult: "success" | "warning" | "error" | "man.stopped",\n variables: { ref_id: number, variableNames: string[] },\n tables: Array<{\n ref_id: number,\n type: "G_SHEETS" | "ZW_NATIVE",\n columnNames: string[]\n }>,\n webhookURL: string | null\n }\n ```\n - Context Behavior: `async` (requiring `await`) in browser JS blocks; `sync` in local Node blocks (`// #ze-run-locally`). E.g., `const info = await zw.getTaskbotInfo();`.\n- **Workflow Scripting Examples**:\n - `Branching by Run Type`: `if (info.runType === "scheduled") { await zw.log("Executing unattended scheduled job"); }`.\n - `Filtering Tables by Type`: `const gSheets = info.tables.filter(t => t.type === "G_SHEETS");`.\n - `Dynamic Webhook Chaining`: Extracting `info.webhookURL` and storing it in `zw.globalState.access()` to allow subsequent TaskBots to programmatically trigger this bot via `axios.post(webhookURL)`.\n- **Critical Distinction**: Metadata returns table/variable **schema names** (column headers and variable names), NOT the underlying data values. To retrieve actual data values, scripts must use `zw.getRef()`.\n\n### 72. My TaskBot Does Not Start Run (`My Taskbot Does Not Start Run.png`)\n- **Documentation Section**: Common Problems -> My TaskBot Does Not Start Run\n- **Core Problem**: Clicking the `Run` button in the web creator portal fails to initialize the automation workflow on the local machine.\n- **Comprehensive Root Causes & Solutions**:\n 1. `Outdated Agent Version`: The Desktop Agent binary is deprecated. Verify version in agent tray menu and update via `creator.zerowork.io/download-agent`.\n 2. `Expecting a GUI`: Users mistakenly wait for an agent application window to open. The agent is strictly headless and runs silently in the OS system tray.\n 3. `Hidden Background Windows`: The automated Chrome instance launched successfully but minimized or opened in the background behind active desktop windows. Toggling `Stay on Page after Run` helps verify visual execution.\n 4. `Missing Chrome Installation`: TaskBots rely entirely on the local Google Chrome Chromium engine. Chrome MUST be installed on the OS, regardless of which browser (Safari, Brave, Firefox) is used to access the web creator portal.\n 5. `Browser Shields & Ad Blockers`: The web workflow builder communicates with the local Desktop Agent via local loopback requests (`localhost` / `127.0.0.1`). Strict browser shields (e.g., Brave Shields, advanced ad blockers) intercept and block these local websocket/HTTP connections as "insecure". Solution: Whitelist `creator.zerowork.io` or disable shields.\n 6. `Agent Inactive / Not Installed`: The background daemon is stopped. Double-click the ZeroWork application icon to start the background process.\n 7. `Immediate Workflow Parsing Errors`: The bot actually initialized but aborted instantly due to fatal structural errors (e.g., unconfigured mandatory selectors, invalid loop hierarchies). Inspect Run Reports for stack traces.\n- **OS & Security Level Blockers**:\n - `VPN / Firewall Interference`: Virtual Private Networks or strict firewalls blocking internal loopback ports (`localhost:9990`). Temporarily disable VPN/firewall to isolate.\n - `Antivirus / Windows Smart App Control`: Aggressive AV heuristics or Windows Defender `Reputation-based protection` blocking background automation executables. Solution: Navigate to Windows Security -> App & browser control -> Turn off Reputation-based protection or add an explicit exclusion for the ZeroWork agent binary.\n\n### 73. My TaskBot Saves Some Data but Not All (`My Taskbot Saves Some Data But Not All.png`)\n- **Documentation Section**: Common Problems -> My TaskBot Saves Some Data but Not All\n- **Core Problem**: A scraping workflow successfully captures a subset of target data (e.g., 1 row, or 15 items) but fails to extract the complete dataset across pagination or infinite scrolls.\n- **Root Causes & Architectural Fixes**:\n 1. `Saves Only One Result Per Page (Missing Nested Loops)`: The workflow lacks a proper multi-level loop hierarchy. Scraping paginated lists requires an outer loop (`Start Repeat` for pagination next-button clicks) wrapping an inner loop (`Start Repeat` iterating over `{loop_index}` list items). Refer to `Nested Loops - Handle Pagination`.\n 2. `Saves Only First 10-20 Results (Infinite Scroll / Lazy Loading)`: Modern web applications (LinkedIn, Instagram, e-commerce feeds) do not render the entire DOM on initial page load; new DOM nodes are appended only when the user scrolls near the bottom of the viewport. If ZeroWork\'s built-in auto-scroll fails to trigger the lazy-load event, inject a `Keyboard Action` block (`Space` or `ArrowDown`) inside the scraping loop to force DOM rendering. Refer to `TaskBot Does Not Automatically Scroll`.\n 3. `Saves Data to Just One Row (Missing Loop Entirely)`: The workflow contains `Save Web Element` but completely lacks a `Start Repeat` block. Without a loop, TaskBot executes the save action exactly once, populating only row 1 of the data table.\n\n### 74. Native Tables (`Native Tables.png`)\n- **Documentation Section**: Using Tables -> Native Tables\n- **Core Concept**: ZeroWork\'s built-in tabular data storage system (`ZW_NATIVE`), designed for storing structured scraping results or feeding dynamic input rows into workflows without requiring external Google Sheets integration.\n- **Creation Workflow & UI Elements**:\n - Step 1: Navigate to the `Tables` sidebar panel and click `Add new table`.\n - Step 2: In the `Add Table` modal, select the table type (e.g., `Create ZeroWork table with custom columns`) and input a descriptive `Enter table title`.\n - Step 3: Define schema columns under `COLUMNS` by entering headers (`My column`, `Another column`). Use `ADD ANOTHER COLUMN` to expand schema, then click `ADD TABLE`.\n- **Lifecycle & Refactoring Behaviors**:\n 1. `Automatic Schema Propagation`: Editing a column name in a native table automatically updates all corresponding building block references across the entire workflow. No manual re-mapping is required.\n 2. `Column / Table Deletion Handling`: Deleting a referenced column or removing the table entirely automatically unbinds those references from standard building blocks.\n 3. `JavaScript Block Exception`: In `Write Javascript` building blocks, existing `setRef()` and `getRef()` calls remain in the code body, but the deleted column name argument is automatically renamed/flagged as `"INVALID"` (e.g., `zw.getRef("INVALID")`), alerting developers to update the script.\n 4. `Google Sheets Conversion`: Native tables can be seamlessly converted to external Google Sheets at any point in the project lifecycle (refer to `Convert Native Table to a Google Sheet`).\n\n### 75. Nested Loops - Handle Pagination (`Nested Loops Handle Pagination.png`)\n- **Documentation Section**: Using Building Blocks -> Start Repeat -> Nested Loops - Handle Pagination\n- **Core Concept**: Establishing a multi-level loop hierarchy (an inner loop encapsulated within an outer loop) to systematically execute multi-page scraping workflows (e.g., paginated search results on LinkedIn).\n- **Architectural Setup (Example: 30 Pages x 10 Profiles = 300 Total Results)**:\n 1. `Initial Navigation`: An `Open Link` block navigates to the target search results URL.\n 2. `Outer Loop (Main Loop - Pagination)`: A `Start Repeat` block configured as `Standard` loop type, with `Auto-detect number of available elements` unchecked, and `Enter number of repetitions` set to `30` (representing 30 pages).\n 3. `Inner Loop (Nested Loop - List Items)`: Inside the Main Loop, a second `Start Repeat` block is placed. Configured as `Standard` loop type with `Enter number of repetitions` set to `10` (representing 10 profile items per page). This loop encapsulates the core scraping actions (e.g., `Save Web Element`).\n 4. `Inner Loop Exit Node`: Immediately following the inner loop\'s scraping blocks, an `After Repeat` block is placed. This block serves as the explicit exit boundary of the nested loop.\n 5. `Pagination Transition`: Connected directly to the `After Repeat` block is a `Click Web Element` block targeting the pagination "Next" button.\n- **Workflow Execution Cycle**:\n - The TaskBot enters the Main Loop on Page 1.\n - It enters the Nested Loop, iterating exactly 10 times to harvest 10 profile elements.\n - Upon completing 10 iterations, execution transitions through `After Repeat` to the `Click Web Element` block, clicking "Next" to load Page 2.\n - The Main Loop repeats this entire sequence 30 times, successfully accumulating 300 records.\n\n### 76. No Selector Is Found (`No Selector Is Found.png`)\n- **Documentation Section**: Common Problems -> No Selector is Found\n- **Core Problem**: A building block fails during runtime execution because the configured CSS or XPath selector cannot be located within the active browser DOM.\n- **Comprehensive Root Causes & Troubleshooting**:\n 1. `Asynchronous Rendering / Page Load Latency`: The building block attempts to evaluate the selector before the target web element has fully rendered in the DOM.\n - *Critical Solution Nuance*: Increase the delay interval on the building block that **precedes** the failing block, NOT on the failing block itself. The delay must execute *before* the engine attempts DOM querying.\n 2. `Dynamic / Brittle Selectors`: The copied selector contains auto-generated dynamic class names or IDs that mutate on every page load (frequent in modern SPAs like LinkedIn, Facebook, and Google Maps). Solution: Construct robust custom selectors utilizing stable semantic attributes (e.g., `data-test-id`, `aria-label`, `type`, or partial attribute matching `[class*=\'stable-prefix\']`). Refer to `How to Build Custom Selectors`.\n 3. `Transient DOM State Discrepancy`: If a `Check Web Element` block successfully identifies the selector but the immediately following action block (e.g., `Click Web Element`) fails to find it, the DOM may have re-rendered, detached, or refreshed the node between block executions. Refer to `Check Web Element Identifies Selector As Found but Next Action Does Not`.\n- **Masterclass Resource**: For deep-dive training, developers are referred to Elias Van Laere\'s 2-hour video tutorial (`CSS Selectors for AI Money: ZeroWork 2-Hour Masterclass for Complete Beginners`).\n\n### 77. Number Operations (`Number Operations.png`)\n- **Documentation Section**: Using Building Blocks -> Number Operations\n- **Core Function**: Performs mathematical calculations, numeric formatting, decimal precision adjustments, and string concatenation on workflow variables or table data.\n- **Empty Value Behavior**: If the input value to apply the operation on is empty, the TaskBot gracefully skips the calculation without throwing an error and continues its run.\n- **Supported Operations & Use Cases**:\n 1. `Add`: Combines two numbers (`1 + 1 -> 2`) OR concatenates two strings (`"hello" + " world" -> "hello world"`). Use Case: Maintaining an incremental counter variable to limit the volume of DMs sent per run.\n 2. `Subtract`: Subtracts one number from another (`5 - 3 -> 2`).\n 3. `Multiply`: Multiplies two numbers (`4 * 3 -> 12`). Use Case: Standardizing currency or unit conversions.\n 4. `Divide`: Divides one number by another (`10 / 2 -> 5`).\n 5. `Remainder %`: Performs modulo arithmetic (`13 % 5 -> 3`).\n 6. `Round`: Rounds a float to the nearest whole number (`2.6 -> 3`).\n 7. `Round up`: Mathematical ceiling equivalent (`2.2 -> 3`).\n 8. `Round down`: Mathematical floor equivalent (`2.7 -> 2`).\n 9. `Get random number`: Generates a random floating-point number within a specified min/max range (e.g., Min 1, Max 5 -> `3.45`). Default range if omitted: `0` to `1,000,000,000`.\n 10. `Set decimals`: Truncates or pads a number to a fixed decimal precision (`5 -> 5.00`, `5.5333 -> 5.53`).\n 11. `Remove formatting`: Strips commas or grouping dots from scraped numeric text to produce a clean float. Essential prerequisite before performing arithmetic or logical comparisons (`>`, `<`). E.g., `1.000.000,23` (dot-grouped) -> `1000000.23`; `1,000,000.23` (comma-grouped) -> `1000000.23`. *Error Condition*: If the input has an unrecognized/corrupted format (e.g., `1,000.000.23`), an error report is generated.\n- **Additional Exception Handling**:\n - If the secondary operand (e.g., value to add/subtract) is missing, the operation is skipped without modifying the original value.\n - If the operation requires a valid number (any operation except `Add`) and the input is a non-numeric string, TaskBot generates an error report and halts the run.\n\n### 78. One Element Can Have Many Selector Expressions (`One Element Can Have Many Selector Expressions.png`)\n- **Documentation Section**: Using Selectors -> How to Build Custom Selectors -> One Element Can Have Many Selector Expressions\n- **Core Concept**: A single web element in the DOM can be targeted by multiple valid CSS selector variations. The objective is selecting the most robust, non-brittle expression that withstands future website UI updates.\n- **Example Variations (Wikipedia Search Button)**:\n - `button[class=\'pure-button pure-button-primary-progressive\'][type=\'submit\']` (Valid, but brittle)\n - `button[type=\'submit\']` (Highly robust)\n - `button[class=\'pure-button pure-button-primary-progressive\']` (Brittle)\n - `button[class*=\'button\'][type=\'submit\']` (Highly robust)\n - `button[class*=\'button\']` (Too generic)\n - `button[class][type]` (Too generic)\n- **Selector Best Practices & Robustness Evaluation**:\n 1. `Lean & Short`: Shorter selectors with fewer chained attributes are less prone to breaking when developers modify secondary utility classes. E.g., targeting exact compound classes like `pure-button pure-button-primary-progressive` is overly brittle.\n 2. `Avoid Cryptic / Auto-Generated Strings`: Class names containing random alphanumeric hashes (common in Tailwind, CSS modules, or scoped frameworks) mutate frequently. Rely on stable semantic attributes (`type=\'submit\'`, `aria-label`, `data-test-id`).\n 3. `Avoid Overly Generic Attributes`: Selectors like `button[class*=\'button\']` or `button[class][type]` are too broad and risk matching multiple unintended buttons on the page, failing the TaskBot uniqueness check.\n 4. `Avoid Strict Hierarchy`: Overusing direct child combinators (`div > span > button`) makes the selector highly brittle if a wrapper `div` is added or removed. Prefer descendant combinators (`div button`) or direct attribute targeting.\n\n### 79. Open Link (`Open Link.png`)\n- **Documentation Section**: Using Building Blocks -> Open Link\n- **Core Function**: Opens a specified URL in the active Chromium browser tab. Supports static URLs (e.g., `https://www.linkedin.com/`) or dynamic variable/table tokens (e.g., `{id: 3862, name: link}`).\n- **Modal Configuration UI**:\n - `Enter link`: Input field for the destination URL.\n - `min sec` / `max sec`: Configurable delay range before executing the navigation.\n - `Open in a new tab`: Checkbox option to spawn a new browser tab instead of navigating within the current tab.\n - *Crucial Background Tab Behavior*: When `Open in a new tab` is checked, the new tab spawns in the **background** (physical OS UI focus remains on the original tab). The TaskBot engine automatically switches its internal execution context to the new tab and operates perfectly in the background. If the user wants to visually observe the bot\'s actions in the new tab, they must manually click the tab in the GUI or add a `Switch or Close Tab` building block to bring it to the front.\n- **Website Network Errors & Exception Handling**:\n - If the destination URL cannot be reached (DNS failure, invalid URL, timeout, proxy failure), TaskBot halts the run and generates an error report containing the underlying Chromium network error code (e.g., `ERR_NAME_NOT_RESOLVED`, `ERR_CONNECTION_TIMED_OUT`).\n - Developers are advised to inspect `chrome://network-errors/` or verify local VPN/antivirus/proxy configurations if network errors persist.\n- **Relevant FAQ**:\n 1. `How do I make TaskBot log in to my account when it opens a website?`: Refer to `Cookies` (session cookie injection).\n 2. `When I use a table reference, I get an error that there was no url`: Refer to `When I Use Data from Table, No Data is Being Pulled`.\n\n### 80. Proxies (`Proxies.png`)\n- **Documentation Section**: General: Run, Schedule, Share, Webhooks -> Proxies\n- **Core Capability**: Routing TaskBot browser traffic through dedicated proxy servers to prevent IP rate-limiting, CAPTCHA triggers, or geographic blocking during automated scraping runs.\n- **Step 1: Gathering Proxy Credentials**:\n - Requires obtaining Proxy IP, Port, Username, and Password from a proxy provider dashboard (e.g., HighProxies, IPRoyal). If the proxy uses IP whitelisting without authentication, username and password fields are left blank.\n - **Critical Formatting Rules for Proxy Address**:\n - Must be formatted strictly as `IP:PORT` (separated by a colon).\n - E.g., `194.32.225.238:21261` (Valid).\n - E.g., `194.32.225.238` (Invalid - missing port).\n - E.g., `194.32.225.238.21261` (Invalid - separated by dot instead of colon).\n - **SOCKS5 Proxy Protocol**:\n - SOCKS5 proxies must include the explicit protocol prefix: `socks5://<your_proxy_ip>:<port>` (e.g., `socks5://194.32.225.238:3128`).\n- **Step 2: TaskBot Settings Configuration UI**:\n - Click the `Settings` gear icon in the top right of the TaskBot builder canvas.\n - Scroll down to the `Proxy (Advanced)` section and click `Add proxy`.\n - Populate input fields: `Proxy ip address and port (enter as IP:PORT)`, `Proxy username`, `Proxy password`. Click `SAVE`.\n\n### 81. Quit Browser (`Quit Browser.png`)\n- **Documentation Section**: Using Building Blocks -> Quit Browser\n- **Core Function**: Explicitly closes the active Chromium browser instance utilized by the TaskBot.\n- **Default Lifecycle Context**: By default, TaskBot automatically closes the browser when a run finishes. `Quit Browser` is only necessary if the user wants to terminate the browser mid-run, or if `Stay on page after run` was enabled in `Browser Launch Settings` / `Launch Browser` block.\n- **Configuration Option**:\n - `Force quit` checkbox: When checked, forcefully terminates the browser instance immediately, overriding shared profile rules.\n - *Critical Warning*: If `Force quit` is enabled on a browser instance utilizing a shared "sticky profile" (a persistent user data directory shared across concurrent TaskBots), it will forcefully terminate the browser for ALL TaskBots currently using that sticky profile, not just the current TaskBot!\n- **Behavioral Nuances & Things to Know**:\n 1. `No Browser Context Handling`: If `Quit Browser` executes when no browser is open, it does not throw a fatal error. It logs a warning to the run report and seamlessly continues execution.\n 2. `Sticky Profile Shared Respect (Default)`: If `Force quit` is NOT checked, `Quit Browser` will close the current TaskBot\'s tabs but leave the underlying browser process running if other TaskBots are actively sharing the sticky profile. The browser process fully terminates only when the last TaskBot leaves.\n 3. `Overrides Stay on Page`: `Quit Browser` overrides any `Stay on page after run` configuration.\n 4. `Relaunch Capability`: Placing an `Open Link` or `Launch Browser` block after a `Quit Browser` block will successfully initialize a fresh, clean browser context.\n\n### 82. Raise Error (`Raise Error.png`)\n- **Documentation Section**: Using Building Blocks -> Raise Error\n- **Status**: "This page is upcoming. Stay tuned!"\n- **Workflow Context**: Utilized within advanced logic flows (often paired with `Try-Catch` or conditional validation blocks) to intentionally throw a custom exception, halting execution or triggering designated error recovery pathways.\n\n### 83. Record Date (`Record Date.png`)\n- **Documentation Section**: Using Building Blocks -> Record Date\n- **Core Function**: Generates a dynamic calendar date or timestamp based on user specifications and saves it to a designated data table column or runtime variable.\n- **Example / Use Case (Auto-Follow-Up Campaigns)**:\n - When sending an initial outreach message on LinkedIn, use `Record Date` to log the exact execution date (e.g., `01.01.2023`) into a table column named `Date of 1st message`.\n - On subsequent runs, pair this with `Start Condition and Set Condition` -> `Before (Date) & After (Date)` comparisons to automatically determine if the required wait window (e.g., 3 days) has elapsed before triggering the follow-up message.\n- **Modal UI Configuration**:\n - `Select date format`: E.g., `Whole date`, `Format: DD.MM.YYYY`.\n - `Select date`: E.g., `Today`.\n - `Weekend`: E.g., `Include weekend` (or exclude weekend calculation).\n - `Save to`: E.g., `Select variable or data table` -> `Variables` -> `last run date`.\n\n### 84. References To Variables And Tables (`References To Variables And Tables.png`)\n- **Documentation Section**: Using Building Blocks -> Dynamic Inputs -> References to Variables and Tables\n- **Core Concept**: Injecting dynamic tokens referencing runtime variables or data table columns into building block input fields (e.g., `Send Notification`, `Insert Text or Data`, `Open Link`).\n- **UI Interaction**:\n - Click the `V` icon (for variables) or `T` icon (for tables) located at the top right of the building block modal configuration window.\n - Selecting an item from the dropdown injects a structured token into the input field: `{id: 113251, name: email_subject}`.\n- **Behavioral Nuance**:\n - The token structure contains both an internal numeric `id` and the human-readable `name`. This ensures that if the variable or column is renamed elsewhere in the project, the underlying `id` maintains the binding intact.\n\n### 85. Remote Cloud Execution (`Remote Cloud Execution.png`)\n- **Documentation Section**: General: Run, Schedule, Share, Webhooks -> Remote (Cloud) Execution\n- **Status**: *Upcoming*\n- **Core Concept**: Offloading TaskBot runs from the local Desktop Agent to ZeroWork\'s managed cloud infrastructure.\n- **Pricing & Billing Model**: Billed on a pay-per-cloud-credit cost structure.\n- **Alternative**: Currently, users requiring 24/7 unattended execution without keeping their personal computer online utilize a Virtual Private Server (VPS). Refer to `Install ZeroWork Agent on VPS`.\n\n### 86. Remove Duplicates (`Remove Duplicates.png`)\n- **Documentation Section**: Using Building Blocks -> Remove Duplicates\n- **Core Function**: A batch operation that scans a data table and removes duplicate rows based on a specified column.\n- **Best Practice & Performance Optimization**:\n - Developers should *always* specify a specific column to evaluate for duplicates (e.g., `Profile link` or `Email`), rather than evaluating entire multi-column rows. Specifying a column significantly improves TaskBot execution speed.\n - *Exclusion*: Files stored in `file` columns are automatically ignored when searching for duplicates.\n- **Deduplication Direction & Preservation Logic**:\n - `Default Behavior`: TaskBot removes the newest (latest appended) duplicate rows and preserves the oldest (first scraped) row.\n - `Preserve newest rows` checkbox: Reverses this behavior, deleting older duplicate rows and keeping the latest entry.\n - *Critical Limitation*: The `Preserve newest rows` option is supported **only in native tables (`ZW_NATIVE`)**; it is NOT available for external Google Sheets.\n- **Architectural Placement Warning (`Do Not Place Inside Loops`)**:\n - `Remove Duplicates` is a **batch operation**. It fetches all table rows into memory and deduplicates the entire table at once.\n - Placing this block inside a scraping loop (`Start Repeat`) is highly inefficient and redundant. Furthermore, if placed inside a loop, the engine\'s internal deduplication lock ensures duplicates will only be removed on the *first* iteration of the loop, ignoring subsequent iterations.\n - *Correct Placement*: Place `Remove Duplicates` after the `After Repeat` block (outside the loop entirely) as a post-processing cleanup step.\n\n### 87. Remove Words (`Remove Words.png`)\n- **Documentation Section**: Using Building Blocks -> Format Data -> Remove Words\n- **Core Function**: Strips specified unwanted words or character substrings from scraped text stored in variables or tables.\n- **Configuration & Delimiter**:\n - Multiple target words/strings must be entered separated by a comma.\n - E.g. `Words to remove`: `Ms., Mr., Mrs., PhD, MBA`.\n - Example Transformation:\n - Input: `AI scientist and PhD candidate Ms. Fina Fedora`\n - Output: `AI scientist and candidate Fina Fedora` (successfully stripped `PhD` and `Ms.`).\n- **Critical Limitation (Comma Stripping)**:\n - Because commas `,` are utilized by the engine as the explicit delimiter separating multiple target words in the input field, `Remove Words` **cannot be used to remove commas themselves**.\n - *Workaround*: To strip commas from text (e.g. cleaning formatted numbers or addresses), developers must use the `Replace text` building block, configuring the target as `,` and leaving the replacement value entirely empty.\n\n### 88. Run In Background (`Run In Background.png`)\n- **Documentation Section**: General: Run, Schedule, Share, Webhooks -> Run Settings -> Run in Background\n- **Core Concept**: Headless browser execution toggle. When enabled, TaskBot runs entirely in the background, hiding the automated Chromium browser window from the OS desktop GUI.\n- **Configuration UI**: Click the `Settings` gear icon in the top right of the TaskBot canvas -> under `Run Behavior`, toggle the `Run in background` switch.\n- **Lifecycle & Testing Best Practices**:\n - `During Building / Testing`: Keep `Run in background` **disabled**. Watching the physical browser window execute actions live is essential for debugging selectors, verifying click targets, and ensuring expected page transitions.\n - `Production / Unattended Runs`: Once reliability is verified, enable `Run in background`. Users can monitor background activity via the desktop `Running TaskBots` live log overlay or by reviewing web `Run Reports`.\n - `Multi-Monitor Preference`: Some users with multiple monitors prefer keeping `Run in background` disabled even in production, parking the automated browser window on a secondary display while working on their primary display.\n\n### 89. Run Settings (`Run Settings.png`)\n- **Documentation Section**: General: Run, Schedule, Share, Webhooks -> Run Settings\n- **Core Concept**: Overview index page grouping the three primary runtime behavior toggles available in the TaskBot settings modal:\n 1. `Run in Background` (Headless mode)\n 2. `Stay on Page after Run` (Preserving browser window for post-run inspection)\n 3. `Bring Pages to Front` (Forcing browser window focus over active desktop applications)\n\n### 90. Run (`Run.png`)\n- **Documentation Section**: General: Run, Schedule, Share, Webhooks -> Run\n- **Core Concept**: Initiating TaskBot execution. Clicking `Run` commands the local Desktop Agent to spawn a fresh Chromium browser window and execute the configured automation steps.\n- **Trigger UI Locations**:\n 1. `Inside Workflow Builder`: Clicking the green `Play` icon in the top toolbar.\n 2. `TaskBots Dashboard List`: Clicking the green `Play` button directly on a TaskBot list item row.\n- **Real-Time Display Overlay**:\n - Each time a run initiates, a live status overlay window titled `Running TaskBots` appears in the bottom right of the screen. E.g. displaying real-time logs: `Inserted "Lorem ipsum..."`, `Nov 20, 2023, 4:16:28 PM`, `Loop iteration 2 starts`.\n- **FAQ & Concurrency Limits**:\n - `How many TaskBots can I run in parallel at the same time?`:\n - Users can run multiple TaskBots concurrently as long as local hardware resources (CPU/RAM) permit. On a standard Mac/PC, users typically run between **5 to 20 concurrent TaskBots** simultaneously.\n - `Troubleshooting: TaskBot does not run`: Refer to `My TaskBot Does Not Start Run`.\n\n### 91. Save File (`Save File.png`)\n- **Documentation Section**: Using Building Blocks -> Save File\n- **Core Function**: Downloads binary files (images, PDFs, CSVs) from web pages to the local OS filesystem or stores file URLs/paths in variables/tables.\n- **File Source Options**:\n 1. `From file url`: Used when the developer has a direct static or scraped URL to the file (e.g. `https://wallpaperaccess.com/full/2656.jpg`). Requires providing `Enter file url` and `Save file to folder` (local absolute directory path like `/Users/username/Downloads/`).\n 2. `From download action`: Used when the file download is initiated by clicking a web element (e.g. `Click Web Element` targeting a "Download CSV" button).\n - *Crucial OS Dialog Nuance*: When downloading via a click action, the native OS "Save As" system dialog window is **suppressed / not visible**. The TaskBot engine intercepts the Chromium download stream and handles the file transfer entirely behind the scenes.\n - *Saving Options*:\n - `Save file url to a variable or table`: Captures the underlying download URL into a variable/table.\n - `Save file to local folder`: Writes the binary file to the specified absolute directory path.\n- **File Options (Advanced Preferences)**:\n - `Make file name unique on conflict`: Toggling this switch appends a random numeric ID to the filename if a file with the identical name already exists in the destination folder (e.g. `file_name_6354736148.png`). If untoggled, existing files are overwritten.\n - `File name (optional)`: Allows developers to specify a custom filename (e.g. `my_pic_name.png`).\n - `Save full file path (optional)`: Captures the absolute local OS path of the downloaded file (e.g. `/Users/username/Downloads/my_pic_name.png`) into a variable or table. Essential prerequisite for chaining with `Upload File` blocks later in the workflow.\n- **Critical Data Type Warning (`Note: Save file building block only saves url or path`)**:\n - Developers can only save the file URL or absolute file path to a **standard text column / variable**.\n - They **cannot** save the URL/path to a `file` type column or variable. This is because `file` type columns expect the actual physical binary file object, whereas `Save File` outputs string paths/URLs.\n\n### 92. Save From Clipboard (`Save From Clipboard.png`)\n- **Documentation Section**: Using Building Blocks -> Save from Clipboard\n- **Core Function**: Captures the current content of the OS clipboard and stores it into a specified variable or data table column.\n- **Workflow Example (LinkedIn Post Link Extraction)**:\n 1. Use `Click Web Element` targeting `text="Copy link to post"`. This native web action copies the URL into the OS clipboard.\n 2. Follow immediately with `Save from Clipboard`, configuring the destination table/column (e.g. `Profiles` -> `Profile link`).\n- **Critical Concurrency & Isolation Warning (`Note that there is no clipboard isolation between TaskBots`)**:\n - The OS clipboard is a **global system resource**. There is **no clipboard isolation** between concurrently running TaskBots.\n - While the time between a click copying text and `Save from Clipboard` reading it is typically mere milliseconds, running multiple TaskBots in parallel that all heavily rely on clipboard operations introduces a severe race condition risk.\n - *Risk*: Clipboard contents can get overwritten or mixed up across separate TaskBot instances executing simultaneously.\n - *Best Practice*: For workflows relying on clipboard scraping, limit concurrent execution or utilize direct element scraping (`Save Web Element`) where possible.\n\n### 93. Save Lists (`Save Lists.png`)\n- **Documentation Section**: Using Building Blocks -> Save Web Element -> Save Lists\n- **Core Concept**: Extracting repeating lists of elements (e.g. search results, product feeds) by combining a `Start Repeat` loop with dynamic selector indexing.\n- **Workflow Architecture**: `Open Link` -> `Start Repeat` -> `Save Web Element` -> `After Repeat`.\n- **Loop Index Injection (`{loop_index}`)**:\n - To target each sequential item in a list during iteration, developers must inject `{loop_index}` into the CSS/XPath selector within `Save Web Element`.\n - Example CSS Selector: `#profile-link:nth-child({loop_index:1})`.\n - *Behavior*: On loop iteration 1, it evaluates `#profile-link:nth-child(1)`. On iteration 2, `#profile-link:nth-child(2)`, and so on.\n- **FAQ & Common Patterns**:\n - `Data Overwriting`: Scraped data is *always appended* by default. If a developer wants fresh data to overwrite old data on every run, they must place a `Delete Data` block *before* the loop starts.\n - `Deduplication`: Place `Remove Duplicates` *after* the loop (`After Repeat`) finishes.\n - `Pagination`: Requires `Nested Loops` (outer loop for pages, inner loop for items).\n - `Scrolling`: Built-in auto-scrolling logic handles most dynamic loading. However, if auto-scroll fails on complex infinite-scroll sites, developers must supplement with a `Keyboard Action` block sending `Space` or `Arrow Down` keystrokes.\n\n### 94. Save Page URL (`Save Page Url.png`)\n- **Documentation Section**: Using Building Blocks -> Save Page URL\n- **Core Function**: Captures the active, fully resolved URL of the web page currently loaded in the active browser tab.\n- **Use Case**: Essential for tracking navigation state, logging redirect destinations, or capturing profile URLs after clicking a generic link.\n- **Configuration**: Simply select the destination variable or data table column (e.g. `Variables` -> `Current url`).\n\n### 95. Save Web Element (`Save Web Element.png`)\n- **Documentation Section**: Using Building Blocks -> Save Web Element\n- **Core Function**: Core scraping block used to extract public text, links, or attributes from targeted web elements and save them into data table columns or variables.\n- **Primary Use Case Categories**:\n 1. `Saving Lists`: Extracting repeating arrays of items (e.g. LinkedIn profile search results, Facebook group members, Amazon product feeds). Refer to `Save Lists`.\n 2. `Enriching Existing Data`: Iterating over an existing list of URLs (e.g. visiting individual LinkedIn profile pages or Amazon product detail pages) to extract deeper, granular attributes (e.g. about section, job position, email, price, reviews). Refer to `Enrich Existing Data`.\n\n### 96. Scheduler (`Scheduler.png`)\n- **Documentation Section**: Using ZeroWork -> General: Run, Schedule, Share, Webhooks -> Scheduler\n- **Core Function**: Configures automated, recurring unattended execution of TaskBots at specific time intervals or schedules.\n- **Scheduling Modes**:\n 1. `Frequency`: Fixed periodic intervals (e.g., Every `X` minutes, hours, days, weeks, or months).\n 2. `Cron Expression`: Advanced, granular scheduling using standard Cron syntax (e.g., `0 9 * * 1-5` for 9:00 AM Monday through Friday).\n- **Execution Environment & Cloud Dependencies**:\n - `Desktop Agent Requirement`: For locally hosted runs, the user\'s computer must remain powered on, awake (not in sleep/hibernation mode), and the ZeroWork Desktop Agent must be actively running in the background.\n - `Cloud Runs`: For TaskBots deployed to ZeroWork Cloud Execution, schedules run entirely in the cloud without requiring the local machine or Desktop Agent to be active.\n\n### 97. Select Web Dropdown (`Select Web Dropdown.png`)\n- **Documentation Section**: Using Building Blocks -> Select Web Dropdown\n- **Core Function**: Selects a specific `<option>` within a native HTML `<select>` dropdown menu element.\n- **Critical HTML Tag Requirement & Troubleshooting (`Invalid Dropdown Workaround`)**:\n - `Select Web Dropdown` works **exclusively with native HTML `<select>` elements**. The target element in the DOM must have `<select>` as its tag name, containing child `<option>` tags.\n - `Invalid Dropdown Workaround`: Many modern web applications (e.g., LinkedIn, custom React/Vue UI libraries) implement visual dropdown menus using `<div>`, `<span>`, or `<button>` elements styled to look like dropdowns. `Select Web Dropdown` will **fail** if targeted at these non-`<select>` elements.\n - *Correct Approach for Custom Dropdowns*: To interact with custom `<div>`/`<button>` dropdowns, developers must use a two-step `Click Web Element` sequence:\n 1. `Click Web Element` targeting the outer dropdown trigger button/div to open the menu.\n 2. `Click Web Element` targeting the specific menu item div/span to select the desired option.\n- **UI Configuration**:\n - `Enter dropdown option`: Enter the exact text value of the option to select (e.g., `Badminton`), or inject a dynamic variable/table reference (e.g., `{id: 3607, name: Dropdown option}`).\n - `Enter CSS or XPath selector of the dropdown`: Enter the selector identifying the `<select>` element (e.g., `select[class=\'custom-select\']`).\n\n### 98. Send Notification (`Send Notification.png`)\n- **Documentation Section**: Using Building Blocks -> Send Notification\n- **Core Function**: Dispatches an automated email notification directly to the email address associated with the user\'s ZeroWork account.\n- **Recipient Limitation & Workaround (`IMPORTANT Alert`)**:\n - The email is sent **exclusively to the ZeroWork account owner\'s registered email address**. It cannot be configured to send emails to arbitrary third-party recipients (e.g., clients, scraped leads).\n - *Workaround*: To send emails to external recipients, developers must use the `APIs: Send HTTP Request` building block to integrate with third-party email service APIs (e.g., SendGrid, Mailgun, Make.com webhook).\n- **Configuration Fields**:\n 1. `Subject`: Plaintext email subject line.\n 2. `Email notification content`: The body of the email. Supports plaintext or HTML formatting.\n - *Dynamic Injection*: Both fields support dynamic variable and table references (e.g., `{id: 113251, name: email_subject}`). Both fields are strictly required.\n- **Block Behavior & Technical Nuances**:\n 1. `HTML Support & Minification`: The content field accepts a mix of plaintext and HTML tags. Developers can minify HTML to eliminate extra whitespace in the email body.\n 2. `Rate Limiting`: The block enforces a per-minute sending rate limit to prevent spamming. This rate limit is automatically applied/throttled if the block is placed inside a rapid loop (`Start Repeat`).\n 3. `Sender Address`: Emails originate from `no-reply@notifications.zerowork.io`. Users should whitelist this address in their email client to prevent notifications from landing in spam.\n 4. `Footer`: Delivered emails include a standard ZeroWork footer text.\n- **Common Use Cases / Workflow Patterns**:\n - `Missing Element Alert`: Pair with `Check Web Element` -> on `Not Found` branch, trigger `Send Notification` to alert the user that a required page element changed or failed to load.\n - `Error Monitoring / Uptime Alert`: Pair with `Start Try-Catch` -> on `On Catch Error` branch, trigger `Send Notification` to alert the user that a webpage is down or unreachable.\n\n### 99. Shortcuts (`Shortcuts.png`)\n- **Documentation Section**: Using Building Blocks -> Building Block Options -> Shortcuts\n- **Core Function**: Canvas productivity shortcuts for workflow builders.\n- **Key Shortcut**: `Mouse drag + SHIFT`: Initiates a marquee / bounding box selection to select multiple building blocks simultaneously on the canvas. Selected blocks are highlighted with a distinct border/overlay, allowing bulk operations (moving, deleting, copying).\n\n### 100. Shorten Content Length (`Shorten Content Length.png`)\n- **Documentation Section**: Using Building Blocks -> Format Data -> Shorten Content Length\n- **Core Function**: Truncates a string stored in a variable or table column to a specified maximum character length.\n- **Example Transformation**:\n - Input: `This text needs to be drastically shortened`\n - Max Length: `20`\n - Output: `This text needs to b` (exactly 20 characters, truncating mid-word if necessary).\n- **Primary Use Case / Cost Optimization**:\n - `LLM Token Optimization`: Used heavily before passing scraped text into the `Ask ChatGPT` building block. Truncating massive scraped articles or bios prevents exceeding LLM context window limits and significantly reduces OpenAI API token expenditure.\n\n### 101. Spintax (`Spintax.png`)\n- **Documentation Section**: Using Building Blocks -> Dynamic Inputs -> Spintax\n- **Core Function**: Generates randomized text variations during runtime to bypass anti-spam algorithms and automated bot detection mechanisms on platforms like LinkedIn, Facebook, or email providers.\n- **Syntax Rules**:\n - Enclosed in curly braces `{}` with options separated by vertical pipe `|`.\n - E.g., `{hi|hello|hey|howdy}`.\n - Multi-part Spintax chaining: `{Hi|hello|hey|howdy}, {how are you?|what\'s new?|how\'s everything?}`.\n - *Behavior*: TaskBot randomly selects one option from each bracket set on every loop iteration or run.\n- **Supported Building Blocks & Toggles**:\n 1. `Insert Text or Data`: Spintax is fully supported.\n 2. `Update Data`: Spintax is supported but **disabled by default**. To enable Spintax evaluation when updating table columns or variables, developers must explicitly check the `Use spintax` checkbox in the block\'s configuration modal.\n\n### 102. Split Data (`Split Data.png`)\n- **Documentation Section**: Using Building Blocks -> Split Data\n- **Core Function**: Parses a single string value from a variable or table column into multiple distinct segments based on a specified delimiter, saving each segment into separate columns or variables.\n- **Workflow Example (Splitting Full Name)**:\n - Input Table Column: `Name` (e.g., `Andy Trujillo`).\n - Separator: `(space)`.\n - Save split values to:\n - Position `1` -> Column `First name`.\n - Position `2` -> Column `Last name`.\n - Result: `First name` = `Andy`, `Last name` = `Trujillo`.\n- **Advanced Indexing Rules & Behavioral Nuances**:\n 1. `Positive Indexing (1-Based)`: Indexing starts at `1` (Position 1 = first token, Position 2 = second token).\n - *Critical Warning*: **Position 0 is invalid**. Entering `0` will cause TaskBot to generate a fatal runtime error.\n 2. `Negative Indexing (Reverse Lookup)`: Supported starting from Agent version `1.1.61`. Negative positions count backwards from the end of the split array.\n - E.g., Position `-1` = last token (e.g., last name).\n - E.g., Position `-2` = second-to-last token.\n - *Use Case*: Extremely useful for extracting last names from complex full names containing middle names or prefixes (e.g., `John Robert Smith` -> `-1` correctly captures `Smith`).\n 3. `Missing Position Handling`: If the input string does not contain enough tokens to satisfy a requested position (e.g., requesting Position `3` on `Hello world`), TaskBot does **not** throw an error. It simply saves nothing (leaves the destination empty) and seamlessly continues execution.\n\n### 103. Standard Loop (`Standard Loop.png`)\n- **Documentation Section**: Using Building Blocks -> Start Repeat -> Standard Loop\n- **Core Function**: The primary loop type used to iterate over repeating web elements (e.g., search results, product lists) and append new rows to a data table.\n- **Key Characteristics**:\n 1. `Appends New Rows`: Each loop iteration creates/appends a new row in the target data table.\n 2. `Row Manipulation`: Format Data or Insert Data blocks executed during the loop iteration apply transformations directly to the current to-be-appended row.\n 3. `Ignores Existing Table Data`: Standard Loop is designed for *new data collection*. It ignores pre-existing rows in the table. (To iterate over existing rows, developers must use `Dynamic Loop`).\n 4. `Auto-Scrolling`: Automatically scrolls the web page to load more items in endless scroll containers, unless configured otherwise (refer to `Continue until No Element Is Found`).\n- **Loop Index Injection & Advanced Syntax (`{loop_index}`)**:\n - `Basic Substitution`: Replaces incremental numbers in CSS/XPath selectors. E.g., `li:nth-child(1)` -> `li:nth-child({loop_index})`.\n - `Alternative Filter Syntax (>> nth)`: If the exact structural position of the increment is complex or unknown, developers can append ZeroWork\'s custom filter syntax: `main#main div > span >> nth={loop_index}`.\n- **Advanced Loop Index Parameters**:\n 1. `Custom Starting Point`: `{loop_index,2}` configures the loop to start counting from index `2` (e.g., skipping the first item).\n - *Important CSS vs. Filter Indexing Nuance*:\n - `nth-child()` in CSS is **1-based** (starts at 1).\n - `>> nth=` custom filter syntax is **0-based** (starts at 0). E.g., `>> nth=0` targets the 1st element, `>> nth=1` targets the 2nd element.\n 2. `Custom Step / Skip Interval`: `{loop_index,1,2}` configures the loop to start at index `1` and increment by `2` on each iteration (e.g., evaluating 1, 3, 5, 7...). Useful for skipping ads or secondary rows in alternating table layouts.\n 3. `Parent Loop Referencing (Nested Loops)`: `{loop_index_123}` where `123` is the explicit block ID of an outer `Start Repeat` block. Essential for complex multi-dimensional scraping where inner loop selectors must reference the current iteration index of the outer parent loop.\n\n### 104. Start Condition and Set Condition (`Start Condition And Set Condition.png`)\n- **Documentation Section**: Using Building Blocks -> Start Condition and Set Condition\n- **Core Function**: Introduces conditional branching and dynamic variable manipulation into TaskBot workflows. Enables workflows to execute alternative pathways based on logical evaluations.\n- **Components**:\n 1. `Start Condition`: Evaluates a logical expression. If `True`, execution proceeds along the `True` branch; if `False`, execution proceeds along the `False` branch.\n 2. `Set Condition`: Used to merge or define specific conditional states before or within branching logic.\n- **Comparison Operators & Matching Rules**:\n - `equals` / `does not equal`: Exact string or numeric match.\n - `contains` / `does not contain`: Substring evaluation.\n - `is empty` / `is not empty`: Checks for null, undefined, or zero-length strings.\n - `greater than` / `less than`: Numeric comparisons.\n- **Variable Inspection & Dynamic Evaluation (`{Variable}` Syntax)**:\n - Conditions can inspect runtime variables, table columns, or webhook payloads.\n - *Syntax Requirement*: When referencing a variable in the condition configuration, developers must enclose the variable name in curly braces (e.g., `{status}` equals `active`).\n- **Common Use Cases & Troubleshooting**:\n 1. `Element Existence Check`: Verifying if a scraped field or variable `is not empty` before attempting downstream actions (e.g., checking if `{email}` exists before calling `Send Notification`).\n 2. `Error Recovery Routing`: Inspecting error messages captured from Try-Catch blocks (e.g., `{error_msg}` contains `timeout`).\n 3. `Type Coercion Warnings`: Ensure numeric comparisons use clean numbers without currency symbols or commas, as stringified numbers with formatting may fail `greater than`/`less than` evaluations.\n\n### 105. Start Repeat (`Start Repeat.png`)\n- **Documentation Section**: Using Building Blocks -> Start Repeat\n- **Core Function**: The foundational control block for establishing looping structures in TaskBot workflows. Defines the iteration mechanism, target data source, and exit conditions for repetitive scraping or automation tasks.\n- **Looping Modes & Architecture**:\n 1. `Standard Loop`: Iterates over repeating web elements on a page (e.g., search results lists) and appends new rows to a data table.\n 2. `Dynamic Loop`: Iterates over existing rows of a ZeroWork data table (e.g., visiting a list of URLs previously scraped).\n 3. `Fixed Number Loop`: Executes a sequence of blocks a specific, hardcoded number of times (e.g., clicking a \'Load More\' button exactly 5 times).\n- **Anatomy of a Loop Workflow**:\n - `Start Repeat`: Initiates the loop and defines the iteration parameters.\n - `Loop Body`: The sequence of building blocks executed during each iteration.\n - `After Repeat`: The exit pathway executed once the loop completes all iterations or meets an exit condition.\n- **Advanced Configuration & Exit Conditions**:\n - `Max items`: Puts a hard ceiling on the total number of items to process across all pages/iterations.\n - `Max pages`: Limits pagination loops to a specific number of page transitions.\n - `Continue until No Element Is Found`: Automatically terminates the loop when the target web element selector is no longer present in the DOM.\n- **Troubleshooting (`Loop stops prematurely` or `Infinite loop`)**:\n 1. `Stale Selectors`: If the web page reloads or modifies DOM structures during the loop, `Start Repeat` may fail to find the next item.\n 2. `Missing Pagination`: Ensure the pagination action (`Click Web Element` on \'Next\' button) is correctly configured outside the main item loop but inside the outer pagination loop.\n\n### 106. Stay on Page After Run (`Stay On Page After Run.png`)\n- **Documentation Section**: Using ZeroWork -> Run Settings -> Stay on Page After Run\n- **Core Function**: A debugging and development toggle that prevents the ZeroWork Desktop Agent from automatically closing the browser window upon TaskBot completion or failure.\n- **Access & Configuration**:\n - Located in the `TaskBot Settings` modal (accessed via the gear icon in the builder toolbar) under `Desktop Agent` run settings.\n - Check the box `Stay on page after run` to enable.\n- **Technical Utility & Use Cases**:\n 1. `Post-Mortem DOM Inspection`: When a TaskBot fails due to a missing selector (`No Selector is Found`), keeping the browser open allows developers to open Chrome DevTools (`F12`), inspect the final DOM state, and verify if the website displayed a captcha, pop-up, or dynamic structural change.\n 2. `Session & Cookie Verification`: Allows developers to verify if the bot remained logged in or if a session expired during execution.\n- **Important Behavioral Nuances & Warnings**:\n - `Local Desktop Runs Only`: This setting applies exclusively to local runs executed via the ZeroWork Desktop Agent. It has no effect on Remote (Cloud) Execution or VPS runs.\n - `Memory & Resource Management`: Leaving multiple finished TaskBot browser sessions open consumes significant system RAM. *Best Practice*: Uncheck this setting once workflow debugging is complete and before deploying for production scheduling.\n\n### 107. Sticky Notes (`Sticky Notes.png`)\n- **Documentation Section**: Using ZeroWork -> General -> Sticky Notes\n- **Core Function**: Provides a native documentation and annotation utility directly within the TaskBot builder canvas. Allows creators to embed explanatory text, visual markers, and workflow documentation alongside building blocks.\n- **Features & Capabilities**:\n - `Custom Colors`: Supports various background colors (yellow, blue, green, pink) to categorize notes (e.g., Yellow for general notes, Green for API payloads, Pink for warnings).\n - `Rich Text Formatting`: Supports bold, italic, bulleted lists, and clickable hyperlinks.\n - `Canvas Placement`: Notes can be dragged, resized, and positioned anywhere on the infinite canvas.\n- **Best Practices for Workflow Maintainability**:\n 1. `Complex Selector Documentation`: Documenting the rationale behind complex XPath or regex formulas directly above `Save Web Element` blocks.\n 2. `Team Collaboration & Sharing`: When sharing TaskBots via `Generate sharing link` or `Share with specific user`, sticky notes are fully preserved, making them essential for providing setup instructions to end-users or clients.\n\n### 108. Stop (`Stop.png`)\n- **Documentation Section**: Using Building Blocks -> Stop\n- **Core Function**: Explicitly halts the execution of a TaskBot run at a specific point in the workflow. Acts as a controlled termination point.\n- **Execution Modes / Status Outcomes**:\n 1. `Stop as Success (Completed)`: Halts execution immediately and marks the final run report status as `Success`. Used when a workflow reaches a logical conclusion (e.g., all target leads processed, or a condition verifies no new data is available).\n 2. `Stop as Failure (Failed)`: Halts execution immediately and marks the final run report status as `Failed`. Used when a critical, unrecoverable business logic error occurs (e.g., login failed, API quota exceeded, or required data missing).\n- **Architectural Implementation Patterns**:\n - `Conditional Termination`: Paired with `Start Condition`. E.g., `If {subscription_active} equals \'false\'` -> `Stop (Failed)` with a custom log message.\n - `Try-Catch Fallback`: Placed inside an `On Catch Error` branch to gracefully terminate and log fatal errors without letting the bot crash ungracefully.\n\n### 109. Switch Frame (`Switch Frame.png`)\n- **Documentation Section**: Using Building Blocks -> Switch Frame\n- **Core Function**: Shifts the active browser execution context into or out of an `<iframe>` (inline frame) element to enable interaction with embedded third-party content (e.g., payment gateways, embedded forms, video players, captchas).\n- **Technical Problem (`Isolated Browsing Context`)**:\n - `iframes` act as completely separate, isolated browsing contexts embedded within a parent webpage. Standard DOM queries (`Click Web Element`, `Save Web Element`) executed from the main page cannot see or interact with elements inside an iframe.\n - *Solution*: Developers must explicitly place a `Switch Frame` block before interacting with iframe content.\n- **Modes of Operation**:\n 1. `Switch to iframe`: Select `iframe` from the dropdown and enter the CSS/XPath selector identifying the `<iframe>` tag (e.g., `iframe[id=\'iframeResult\']`). All subsequent building blocks will execute within this iframe\'s DOM.\n 2. `Switch to Main frame`: Select `Main frame` from the dropdown. This exits the iframe context and returns execution to the top-level parent document.\n- **Nested iframes**:\n - If an iframe contains another iframe (e.g., a captcha inside an embedded form), developers must chain multiple `Switch Frame` blocks sequentially to drill down into the nested layers. E.g., `Switch Frame (Outer)` -> `Switch Frame (Inner)`.\n- **Context Auto-Reset Rules (FAQ / Nuances)**:\n - If TaskBot executes an `Open Link`, `Switch Tab`, or `Close Tab` block while inside an iframe, the frame context is **automatically cleared/reset** back to `Main frame` for the newly loaded page/tab (starting from Agent version `1.1.56`).\n- **Troubleshooting (`TaskBot can\'t click/find element in iframe`)**:\n 1. `Wrong Context`: Check if the bot is actually in the correct iframe or if it forgot to switch back to `Main frame`.\n 2. `Nested Frame Miss`: The target element may be inside a second, nested iframe that wasn\'t switched into.\n 3. `Selector Timeout`: Iframe contents often load asynchronously and slower than the parent page. *Tip*: Increase the `selector timeout` in the building block options (`Selector Options`) for actions performed inside iframes.\n\n### 110. Switch or Close Tab (`Switch Or Close Tab.png`)\n- **Documentation Section**: Using Building Blocks -> Switch or Close Tab\n- **Core Function**: Manages browser tab navigation, allowing TaskBots to switch focus between multiple open tabs or close specific tabs during execution.\n- **Actions**:\n 1. `Switch to Tab`: Activates the target tab based on specified criteria.\n 2. `Close Tab`: Closes the target tab based on specified criteria.\n- **Target Selection Options (Criteria)**:\n - `Latest tab`: Targets the rightmost tab opened most recently.\n - `Previous tab`: Targets the tab immediately to the left of the current tab.\n - `Next tab`: Targets the tab immediately to the right of the current tab.\n - `Tab URL matching`: Targets a tab whose URL matches a specific string. Supports:\n - Full URL (e.g., `google.com`).\n - Partial URL (e.g., `/subpage`).\n - Regular Expressions (e.g., `/^https:\\/\\/google\\.com$/i`). *Note*: If regex is invalid, TaskBot treats it as a literal string match without throwing an error.\n - `Tab number`: Targets a tab by its absolute 1-based index from left to right (`Tab number 1` = leftmost tab).\n- **Critical Behavioral Nuances & Warnings (`IMPORTANT Alerts`)**:\n 1. `Tab Indexing vs Visual Order`: TaskBot tracks tab positions based on *creation time*. If a user manually drags and rearranges tabs during an active run, `Tab number`, `Previous tab`, and `Next tab` options may fail or target the wrong tab.\n 2. `Run in Regular Browser Mode Risk`: When running in `Run in my regular browser` mode, the presence of the user\'s personal tabs or parallel TaskBot runs makes positional indexing highly unpredictable. *Best Practice*: Always prefer `Tab URL matching` over positional criteria in regular browser mode.\n 3. `Closing the Active Tab Behavior`: When the currently active tab is closed:\n - The next tab to the right becomes active.\n - If no tab exists on the right, the tab to the left becomes active.\n - If no tabs remain open, the browser window closes.\n 4. `Browser Closure Handling`: If the browser closes because all tabs were closed, TaskBot continues running in the background. However, if the next building block requires a DOM interaction (`Click Web Element`), TaskBot will throw a fatal error. *Fix*: Place an `Open Link` block to relaunch the browser window before attempting DOM actions.\n\n### 111. Take Screenshot (`Take Screenshot.png`)\n- **Documentation Section**: Using Building Blocks -> Take Screenshot\n- **Core Function**: Captures a visual screenshot of the current browser viewport or targeted web element and saves the image file directly to the local filesystem or cloud storage.\n- **Related Documentation Links**:\n - `File Options`: Configuration for naming conventions, dynamic timestamps, and file extension formats.\n - `How do I get folder path?`: Instructions for obtaining absolute directory paths for saving images locally on Windows/macOS.\n\n### 112. TaskBot Does Not Automatically Scroll (`Taskbot Does Not Automatically Scroll.png`)\n- **Documentation Section**: Using ZeroWork -> Common Problems -> TaskBot Does Not Automatically Scroll\n- **Problem Overview**: In certain modern web applications, endless scroll containers or custom virtualized lists use non-standard DOM structures that prevent ZeroWork\'s out-of-the-box auto-scrolling mechanism from detecting the scrollable wrapper.\n- **Architectural Workaround (`Custom Scrolling Logic`)**:\n - Developers must construct custom scrolling logic manually by incorporating a `Keyboard Action` building block into the scraping loop.\n - *Implementation*: Configure `Keyboard Action` to simulate pressing `Arrow Down`, `Page Down`, or `Space` keys to force the container viewport downwards and trigger dynamic element rendering before executing `Save Web Element`.\n\n### 113. TaskBot Sharing Options (`Taskbot Sharing Options.png`)\n- **Documentation Section**: Using ZeroWork -> General: Run, Schedule, Share, Webhooks -> TaskBot Sharing Options\n- **Core Function**: Distributing TaskBot automation workflows to other ZeroWork Creator accounts.\n- **Access**: Click the `Share TaskBot` icon (curved arrow) in the top toolbar of the builder canvas.\n- **Sharing Modes**:\n 1. `Share with specific user`: Enter the target ZeroWork user\'s registered email address. A complete copy of the TaskBot is instantly pushed to their account.\n 2. `Generate sharing link`: Toggle `Activate sharing link` to create a public/shareable URL (`https://zerowork.io/creator/get-taskbot/...`). Anyone with the link can import a duplicate into their workspace. Supports regenerating/resetting the link or deactivating it entirely.\n- **Data Privacy & State Separation (`IMPORTANT Security Rules`)**:\n 1. `Native Table & Variable Data`: Scraped data, table rows, and runtime variable values are **never shared**. The recipient receives the exact table structure (column headers) and variable keys, but all data rows and initial values are entirely empty to protect creator privacy.\n 2. `Run Settings (Cookies, Proxies, Schedules)`: Sensitive execution settings\u2014including authenticated session cookies, proxy credentials, and active scheduler cron jobs\u2014are **stripped entirely**. The recipient\'s copy resets to blank/default run settings.\n 3. `Google Sheets Link Exception`: If the TaskBot uses a `Google Sheets` building block, the configured Google Sheet URL/ID **is preserved and shared**. *Security Warning*: Creators must ensure they restrict access permissions on the Google Sheet or replace the link with a template sheet before sharing.\n- **Live Synchronization (FAQ)**:\n - When sharing via link, the link points dynamically to the creator\'s *current* TaskBot state. Any subsequent building block modifications made by the creator are instantly reflected whenever a new user imports the link.\n- **Troubleshooting (`Recipient did not receive TaskBot`)**:\n - Pushed TaskBots appear in the recipient\'s dashboard within a minute. If missing, instruct the recipient to perform a hard page reload (`F5` / `CMD+R`).\n\n### 114. Trigger Run via Webhook (`Trigger Run Via Webhook.png`)\n- **Documentation Section**: Using ZeroWork -> General: Run, Schedule, Share, Webhooks -> Trigger Run via Webhook\n- **Core Function**: Enables programmatic execution of TaskBots via external HTTP requests (GET or POST), allowing seamless integration with automation platforms (Zapier, Make.com, Pabbly Connect, custom backend servers).\n- **Desktop Agent Prerequisites (`IMPORTANT Red Alert`)**:\n - For local runs triggered via webhook, three strict conditions must be met:\n 1. The user must be actively logged into the ZeroWork Desktop Agent.\n 2. The Desktop Agent process must be actively running in the background.\n 3. The computer must be powered on and configured to prevent sleep/hibernation modes.\n- **Webhook Management**:\n - Generated via `TaskBot Settings` modal -> `Generate Webhook`. E.g., `https://webhook.zerowork.io/webhook/trigger?s=c1416...`.\n - Supports toggling `Webhook is active` to temporarily disable external triggers, or deleting/regenerating the webhook URL to revoke access.\n- **Dynamic Data Ingestion & Variable Mapping (`CRITICAL Capabilities`)**:\n 1. `Built-in Variable (zw_webhook_data)`: The entire raw JSON payload of an incoming POST request (or query parameters of a GET request) is automatically saved into a system-reserved variable named `zw_webhook_data` as a stringified JSON object. E.g., `{"Link": "https://wikipedia.org", "Value": "Some value"}`.\n - *Parsing in JS*: Developers can parse this inside a `Write JavaScript` block using `JSON.parse(await getRef({ref_id: ..., name: "zw_webhook_data"}))`.\n 2. `Direct Top-Level Variable Matching`: If the incoming JSON payload contains top-level keys that exactly match existing TaskBot variable names (case-sensitive), TaskBot automatically populates those variables with the incoming values. E.g., Payload `{"Link": "https://wikipedia.org"}` populates variable `Link`.\n 3. `Advanced JSONPath Matching (Nested Objects & Arrays)`: Developers can map complex nested JSON structures directly to TaskBot variables by defining variable names using JSONPath syntax:\n - E.g., Payload `{"city": {"name": "Berlin"}}` -> Variable name `city.name` captures `Berlin`.\n - E.g., Wildcard Array Extraction: `cities[*].city` extracts an array of city names.\n - E.g., Filter Expressions: `cities[?(@.city==\'Berlin\')]` or `cities[?(@.population>5000000)]`.\n- **Payload & Matching Rules (Notes)**:\n - Variables not included in the webhook payload retain their existing/default values.\n - Matching is strictly case-sensitive (`Link` matches `Link`, not `link` or `LINK`).\n - If a defined JSONPath is invalid or fails to match anything in the payload, TaskBot does **not** throw an error; it simply leaves the variable empty.\n- **TaskBot-to-TaskBot Triggering**:\n - To trigger another TaskBot from within an active TaskBot run, developers can configure an `APIs: Send HTTP Request` building block to make a POST/GET request to the target TaskBot\'s webhook URL.\n\n### 115. Try-Catch (`Try Catch.png`)\n- **Documentation Section**: Using Building Blocks -> Try-Catch\n- **Core Function**: Provides robust error handling and execution recovery by wrapping a block or sequence of building blocks within a monitored execution scope. Prevents unexpected scraping failures from crashing the entire TaskBot run.\n- **Architectural Flow**:\n 1. `Start Try-Catch`: Establishes the beginning of the monitored execution scope. All blocks placed between `Start Try-Catch` and `After Try-Catch` belong to this scope.\n 2. `On Catch Error`: If any building block within the Try-Catch scope fails or throws an error, execution immediately jumps to the `On Catch Error` branch. Developers define fallback/recovery logic here (e.g., logging errors, retrying actions, breaking loops).\n 3. `After Try-Catch`: A convergence junction. Once either the success path completes successfully OR the error recovery path (`On Catch Error`) finishes, execution merges and continues along the `After Try-Catch` pathway.\n- **Advanced Implementation Patterns (Examples)**:\n 1. `Loop Error Isolation`: Wrapping an entire loop sequence inside a Try-Catch. If an error occurs on a specific iteration (e.g., missing element), `On Catch Error` can trigger a `Break Repeat` or log the error, allowing the bot to continue to the `After Repeat` phase without failing the overall run.\n 2. `Granular/Scoped Error Handling`: Chaining multiple separate Try-Catch blocks for distinct high-risk actions. E.g., `Start Try-Catch (Action 1)` -> `On Catch Error (Break)` -> `After Try-Catch` -> `Start Try-Catch (Action 2)` -> `On Catch Error (Retry)` -> `After Try-Catch`.\n 3. `Conditional Error Inspection & Routing`: Combining Try-Catch with conditional branching (`Start Condition`). Developers can record the error message to a variable, then inspect the error string in `On Catch Error`. E.g., `If error contains \'timeout\' -> Retry`, `Else -> Raise Error`.\n- **Critical Limitations (`IMPORTANT Orange Alert`)**:\n - `Fatal Initialization Failures`: If a TaskBot cannot start its run at all, the error **cannot be caught** by a Try-Catch block, even if the entire workflow is wrapped inside one. Common causes for uncatchable fatal errors:\n 1. Outdated Desktop Agent version.\n 2. Invalid TaskBot setup/configuration (e.g., missing required parameters or corrupted builder canvas).\n\n---\n\n## Batch 12 (Items 116 - 131)\n\n### 116. Update Data (`Update Data.png`)\n- **Documentation Section**: Using Building Blocks -> Update Data\n- **Core Function**: Allows TaskBot to update or overwrite existing data in ZeroWork tables or variables during runtime. Essential for updating row statuses, logging scrape timestamps, or modifying counter variables.\n- **Architectural Flow & Configuration**:\n 1. `Target Selection`: Developers select whether to update a Data Table column or a standalone Variable.\n 2. `Value Assignment`: Enter the new value, which can be static text, dynamic spintax, a variable reference, or a formula/code snippet.\n 3. `Scope & Row Mapping`: When updating a table column within a loop (`Start Repeat`), `Update Data` automatically maps to the current active iteration row (`loop_index`), ensuring precise row-level updates without manual row index tracking.\n\n### 117. Upload File (`Upload File.png`)\n- **Documentation Section**: Using Building Blocks -> Upload File\n- **Core Function**: Allows TaskBot to upload files to a webpage from either a direct online file URL or a local folder path on the user\'s computer.\n- **Architectural Flow & Configuration**:\n 1. `Trigger the Upload Action`: Before executing the `Upload File` block, developers must place a building block that initiates the upload action on the target webpage (e.g., a `Click Web Element` targeting the "Upload image" or "Choose file" button).\n - `IMPORTANT Warning`: The native OS file chooser dialog will **not be visible** during TaskBot execution. TaskBot intercepts and handles the file selection behind the scenes directly via the browser API.\n 2. `Select File Source Option`:\n - `From file URL`: Enter a direct online file URL (e.g., `https://example.com/image.jpg`). TaskBot fetches the file directly and uploads it.\n - `From folder path`: Enter the absolute local file path (e.g., `/Users/username/Downloads/pic.png` or `C:\\Users\\username\\Downloads\\pic.png`).\n- **FAQ & Advanced Usage**:\n - `How do I get folder path?`: Explains OS-specific ways to copy absolute paths (Mac: Option + Right Click -> Copy as Pathname; Windows: File Explorer address bar or Shift + Right Click -> Copy as path).\n - `Dynamic Upload via Table Column`: Developers can add a `file column` to a ZeroWork table, upload files directly into the table row, and configure the `Upload File` block to reference that table column.\n\n### 118. Use Element\'s Text (`Use Elements Text.png`)\n- **Documentation Section**: Using Selectors -> Use Element\'s Text\n- **Core Function**: Allows targeting HTML elements directly using their visible text content via two match types: Exact Match and Loose Match.\n- **Selector Syntax Rules**:\n 1. `Exact Match`:\n - **Syntax**: `text="some text"` (inside double quotes).\n - **Behavior**: Case-sensitive exact match. E.g., `text="Start a post"` targets only elements whose text matches exactly.\n 2. `Loose Match`:\n - **Syntax**: `text=some keywords` (without double quotes).\n - **Behavior**: Case-insensitive partial/keyword match. Perfect for dynamic numbers or changing suffixes. E.g., `text=people follow this` targets elements containing "7,898 people follow this" or "1,456 people follow this" by omitting quotes.\n - **Incorrect Syntax**: `text="people follow this"` is a syntax error if looking for dynamic prefix/suffix; it must be without quotes.\n\n### 119. Using Building Blocks (`Using Building Blocks.png`)\n- **Documentation Section**: Using Building Blocks (Overview)\n- **Core Function**: The root entry-point categorizing all available ZeroWork automation building blocks.\n- **Architectural Flow / Block Categories**:\n 1. `Dynamic Inputs`: Explains three types of inputs all building block fields support:\n - *Variables/Tables references*: `Hello {id: 123, name: "Profile name"}`\n - *Code references (stored locally)*: `This is my secret password stored only locally: ${await zw.deviceStorage.get("password")}`\n - *Spintax (randomization)*: `{Hi | Hey | Howdy}! How {are you | are things going}?`\n 2. `Browser`: `Open Link`, `Save Page URL`, `Switch or Close Tab`, `Go Back or Forward`, `Switch Frame`, `Browser Alert`.\n 3. `Web Interaction`: `Click Web Element`, `Check Web Element`, `Save Web Element`, `Insert Text or Data`, `Hover Web Element`, `Select Web Dropdown`, `Keyboard Action`.\n 4. `Logic`: `Start Condition and Set Condition`, `Start Repeat`, `After Repeat`, `Break Repeat`, `Try-Catch`, `Raise Error`, `Abort Run`.\n 5. `Data`: `Update Data`, `Number Operations`, `Format Data`, `Split Data`, `Apply Regex`, `Remove Duplicates`, `Delete Data`.\n 6. `External`: `Ask ChatGPT`, `Send Notification`, `APIs: Send HTTP Request`, `Write JavaScript`.\n 7. `Files`: `Save File`, `Upload File`.\n 8. `Tools`: `Delay`, `Record Date`, `Take Screenshot`, `Save from Clipboard`, `Log`.\n 9. `Building Block Options`: Config options like deactivating, skipping a loop, auto-aligning blocks, and multi-selecting blocks.\n\n### 120. Using Google Sheet vs. Native Tables (`Using Google Sheet Vs. Native Tables.png`)\n- **Documentation Section**: Using Tables -> Using Google Sheet vs. Native Tables\n- **Core Function**: A comparative architectural matrix evaluating trade-offs between ZeroWork Native Tables and Google Sheets integrations for data storage.\n- **Comparison Dimensions**:\n 1. `Reliability`:\n - *Native Tables*: Data handling is seamlessly streamlined with TaskBot runs.\n - *Google Sheets*: External server overload issues are outside ZeroWork control.\n 2. `Editing Column Names`:\n - *Native Tables*: All building block references to edited column names in all TaskBots are **re-mapped automatically**.\n - *Google Sheets*: All building block references in all TaskBots need to be **re-mapped manually** if column names change.\n 3. `Data Sharing`:\n - *Native Tables*: Cannot be shared directly with users outside ZeroWork (requires CSV export).\n - *Google Sheets*: Can share data with anyone instantly.\n 4. `Data Display`:\n - *Native Tables*: Simple paginated view of 50 rows per page.\n - *Google Sheets*: Large variety of filtering, sorting, and data visualization options.\n 5. `Capacity Limits`:\n - *Number of max cells per table/sheet*: Native Tables = 1,500,000 cells; Google Sheets = 10,000,000 cells.\n - *Maximum characters per cell*: Both = 50,000 characters per cell.\n\n### 121. Using Run Reports (`Using Run Reports.png`)\n- **Documentation Section**: Using Run Reports (Overview)\n- **Core Function**: Displays all actions taken during a TaskBot run, essential for troubleshooting failed runs.\n- **Where to Find Run Reports**:\n 1. On the TaskBots list page (icon next to the Play button).\n 2. Inside the TaskBot builder page (icon on the top toolbar).\n- **How Run Reports Are Displayed**: Lists historical runs with timestamps, statuses (Success, Failed, Manually stopped), agent type used, duration, and a `View Logs` / `View Error Details` button.\n- **Tips for Easier Troubleshooting**:\n - `View Logs`: Opens the detailed execution log.\n - `Side View`: Positions logs next to the TaskBot workflow canvas for side-by-side comparison.\n - `View Building Block`: Clicking an error log item highlights/zooms in on the exact building block on the canvas that failed.\n - `Filter`: Toggle "Only show warnings and errors" or search by ID, name, keywords.\n- **Notifications**: Developers can set up automated failure notifications via Email, Slack, or Custom Webhook.\n - `Webhook Payload Structure`: Sends a JSON payload containing `agent_version`, `taskbot_id`, `taskbot_name`, `taskbot_url`, `run_status` (`success`, `fail`, `warning`, `unknown`, `manually_stopped`), `run_type` (`webhook`, `scheduled`, `immediate`), `run_duration`, and an array of `run_errors` (each containing `id`, `timestamp`, `error_message`, `counter`, `screenshot` URL, and `building_block` metadata with `id`, `name`, `type`).\n\n### 122. Using Selectors (`Using Selectors.png`)\n- **Documentation Section**: Using Selectors (Overview)\n- **Core Function**: The root entry-point categorizing all selector features and strategies in ZeroWork.\n- **Architectural Flow / Selector Sections**:\n 1. `What Are Selectors`: Core concept of browser DOM targeting.\n 2. `Use Element\'s Text`: Exact and loose matches on visible text.\n 3. `Copy Selectors`: Methods to copy CSS/XPath selectors from Developer Tools.\n 4. `How to Build Custom Selectors`: Advanced custom attribute-based targeting.\n 5. `How to Use XPath in ZeroWork (advanced)`: Leveraging complex XML path expressions.\n 6. `CSS Selectors Master Class`: In-depth tutorial covering structural, parent-child, and sibling selector strategies.\n\n### 123. Using Tables (`Using Tables.png`)\n- **Documentation Section**: Using Tables (Overview)\n- **Core Function**: The root entry-point categorizing all table management and data storage features in ZeroWork.\n- **Architectural Flow / Table Sections**:\n 1. `How to Add Tables`: Creating new data storage tables within a TaskBot project.\n 2. `Native Tables`: Built-in high-performance ZeroWork data tables.\n 3. `Google Sheets`: External real-time Google Sheets synchronization.\n 4. `Import Data from CSV`: Populating tables from external comma-separated values files.\n 5. `Using Google Sheet vs. Native Tables`: Comparative analysis of reliability, automatic remapping, and sharing trade-offs.\n 6. `Create Columns`: Adding text, number, file, or profile columns.\n 7. `Export Data as CSV`: Extracting scraped or processed data to local files.\n 8. `Convert Native Table to a Google Sheet`: Seamless migration of internal tables to external Google Sheets.\n\n### 124. Using Variables (`Using Variables.png`)\n- **Documentation Section**: Using Variables (Overview)\n- **Core Function**: Variables are used for saving or updating data that you temporarily need during a TaskBot run. Unlike tables, variables do not adhere to any appending or looping logic, making them a powerful and robust way to save/update a single global value dynamically.\n- **When to Use Tables vs. When to Use Variables**:\n - *Tables*: Used when iterating over rows, appending structured datasets, or scraping collections of records.\n - *Variables*: Used for counters, state flags, accumulators, or session-level constants (e.g., total direct messages sent per run).\n- **Comprehensive Flow Example: Limiting DMs to 30 per run**:\n 1. *Step 1*: Setup initial profiles table (`Profile links`).\n 2. *Step 2*: Setup the TaskBot flow: Open LinkedIn -> Loop through profiles -> Insert DM Text -> Click Send.\n 3. *Step 3*: Create a global variable `DM counter` initialized to `0` or left empty.\n 4. *Step 4*: In each iteration, increment `DM counter` by `1` using the `Number Operations` building block.\n 5. *Step 5*: Place a `Start and Set Condition` block *before* sending the DM to check if `DM counter` is less than `30`. If the condition is met, proceed with sending the DM and incrementing. If not, the run bypasses or stops.\n\n### 125. Utilities (`Utilities.png`)\n- **Documentation Section**: Reference & Utilities\n- **Core Function**: Summarizes built-in utility functions and syntax helpers available across all input fields and JavaScript blocks within ZeroWork.\n- **Key Utility Functions**:\n 1. `Device Storage Access`: `zw.deviceStorage.get(key)` / `zw.deviceStorage.set(key, value)` for persisting local key-value data across runs on the same agent machine.\n 2. `Spintax Engine`: `{Option A | Option B | Option C}` for generating randomized variations of text inputs to simulate human variance.\n 3. `Dynamic Variable Interpolation`: `{variable_name}` or `{table_name.column_name}` for injecting runtime data directly into strings.\n\n### 126. Version 1.1.61 (`Version 1.1.61.png`)\n- **Documentation Section**: Release Notes -> Version 1.1.61\n- **Core Overview**: Major release introducing rate limits, strict profile path validations, and selector optimizations.\n- **Key Changes & Features**:\n 1. `Send Notification Rate Limits`: Introduced strict rate limits on `Send Notification` building blocks (max 10 notifications per minute) to prevent external API spamming.\n 2. `Strict Profile Path Validation`: Added explicit file system checks to ensure provided profile paths exist before launching the browser.\n 3. `Selector Optimizations`: Improved background DOM traversal and caching for faster element identification.\n\n### 127. Version 1.1.62 (`Version 1.1.62.png`)\n- **Documentation Section**: Release Notes -> Version 1.1.62\n- **Core Overview**: Hotfix release addressing immediate breaking changes and friction points introduced in 1.1.61.\n- **Key Fixes & Reversions**:\n 1. `Rate Limits Reverted`: Reverted the per-minute rate limits introduced in 1.1.61 for `Send Notification`.\n 2. `Selector Character Limit`: Increased character limit on selectors to **50,000 chars per selector**.\n 3. `Profile Path Validation Disabled`: Disabled the strict profile path check so no error is generated for profile shortcuts (the validation was well-intended but caused breaking changes).\n 4. `Keyboard Action Loop Fix`: Fixed bug where `Keyboard Action` with multiple keys pressed inside a loop errored out.\n 5. `Auto-scroll Selector Indexing Fix`: Fixed unexpected results when enabling auto-scroll but using selectors that do not contain any `loop_index`.\n\n### 128. Version 1.1.63 (`Version 1.1.63.png`)\n- **Documentation Section**: Release Notes -> Version 1.1.63\n- **Core Overview**: Minor release fixing timeouts, timezone bugs, and improving path-following logic for deactivated conditional blocks.\n- **Key Fixes & Improvements**:\n 1. `Insert Text Timeout Fix`: Fixed bug where long texts in `Insert Text or Data` caused timeouts.\n 2. `Timezone Fix`: Fixed dates being recorded in the wrong timezone.\n 3. `Condition Logging`: Improved logging for condition blocks.\n 4. `Deactivated Block Pathing Fix`: Improved path-following logic when `Start Condition` or `Check Web Element` is deactivated. Previously, the chosen fallback path was sometimes suboptimal/unexpected after run flow optimizations, leading to unintended behavior.\n\n### 129. Version 1.1.64 (`Version 1.1.64.png`)\n- **Documentation Section**: Release Notes -> Version 1.1.64\n- **Core Overview**: Patch release fixing tab management, selector compatibility, JavaScript appending, redirect handling, and introducing granular control over human-like clicking.\n- **Key Fixes & Improvements**:\n 1. `Close Tab Fix`: Closing a tab with `Close Tab` no longer prevents new pages from being opened.\n 2. `Select Web Element Fix`: Fixed `Select Web Element` stopping working with certain selectors.\n 3. `Write JS appendIndex Fix`: Fixed bug where custom `appendIndex` values were ignored in `Write JS`.\n 4. `HTTP Redirect Fix`: `Send HTTP Request` now correctly follows redirects (301, 302, 303) automatically.\n 5. `Upload File Redirect Fix`: File URLs in `Upload File` building block with redirects are now followed correctly.\n 6. `Human-Like Clicking Granularity`: Added `Use human-like clicking` option to `Click Web Element` building block. Enabling human-like clicks globally caused issues on certain websites, so it is now configurable per block.\n\n### 130. Version 1.1.65 (`Version 1.1.65.png`)\n- **Documentation Section**: Release Notes -> Version 1.1.65\n- **Core Overview**: Maintenance release addressing background memory leaks and improving stability during long-running scraping loops.\n- **Key Improvements**:\n 1. `Memory Optimization`: Reduced memory footprint during extensive table appending operations.\n 2. `Stability Fixes`: Resolved edge-case crashes when switching between multiple browser tabs rapidly.\n\n### 131. Version 1.1.66 (`Version 1.1.66.png`)\n- **Documentation Section**: Release Notes -> Version 1.1.66\n- **Core Overview**: Security and compatibility patch updating underlying browser driver dependencies.\n- **Key Updates**:\n 1. `Driver Compatibility`: Updated internal Chromium driver hooks to maintain compatibility with modern web standards and anti-bot detection mechanisms.\n 2. `Enhanced Logging`: Added more granular debug traces for network request failures.\n\n### 132. Version 1.1.67 (`Version 1.1.67.png`)\n- **Documentation Section**: Release Notes -> Version 1.1.67\n- **Core Overview**: Patch restoring support for regular browser mode and minor UI improvements.\n- **Key Improvements & Fixes**:\n 1. `Browser Run Fix`: Restores support for "Run in my regular browser" mode, which was broken by recent Chrome updates.\n 2. `Error Messages`: Clarified and improved several error messages.\n 3. `Timeout Extension`: Default timeout for full-page screenshots has been increased.\n\n### 133. Version 1.1.68 (`Version 1.1.68.png`)\n- **Documentation Section**: Release Notes -> Version 1.1.68\n- **Core Overview**: Significant reliability update focusing on background retry mechanisms, concurrency, and UI error reporting.\n- **Key Improvements & Fixes**:\n 1. `Enhancements`: Agent version now included in error reports. File download timeout options added to `Take Screenshot` and `Save File` blocks (default 5 min for file, 2 min for screenshot). Midnight end time allowed in scheduler.\n 2. `Improvements`: Auto retry on 502 errors and aborted response streams. `Open Link` retries on network errors. Scheduler retry mechanism is more robust for syncing scheduled tasks. Copying blocks preserves table references. `Write JS` context cleanup is more forgiving for async code. Notification settings handle duplication better. Parallel webhook triggers handled safely. Improved handling in `Open Link` for rare timing crashes. Improved concurrency for non-incognito browser runs.\n 3. `Fixes`: `Check Web Element` block "Start run from here" activation bug fixed. Awaiting logic fixed for file URL vs download actions. Rare log-out issues and run state display bugs fixed.\n\n### 134. Version 1.1.69 (`Version 1.1.69.png`)\n- **Documentation Section**: Release Notes -> Version 1.1.69\n- **Core Overview**: Major Google Sheets integration update bringing better performance, reliability, and real-time syncing.\n- **Key Improvements & Fixes**:\n 1. `Highlights`: Major Google Sheets performance boost (faster processing, fewer timeouts). Overhauled authentication flow resolving false positive expiration errors. Real-time syncing available for non-native tables in loops.\n 2. `Enhancements`: `Send HTTP Request` supports saving full objects and nested values directly. `Remove Duplicates` can run on every loop iteration when using Google Sheets.\n 3. `Improvements`: Appended rows write into existing empty rows to prevent limit hits. Added retries for taking screenshots and syncing scheduled tasks. Better error messages across blocks. Added handling for unidentified keys in Keyboard Action.\n 4. `Fixes`: Removed conflicting external library for saving clipboard content. Duplicates auto-removed when importing tables. `Send HTTP Request` saving data issues resolved.\n\n### 135. Version 1.1.70 (`Version 1.1.70.png`)\n- **Documentation Section**: Release Notes -> Version 1.1.70\n- **Core Overview**: Stability patch for Google Sheets, navigation timeouts, and HTTP requests.\n- **Key Improvements & Fixes**:\n 1. `Improvements`: Retry handling for critical internal/service-unavailable Google Sheets errors. Reload action integrated into standard page navigation logic. Error details from request responses included if a file URL rejects a download (e.g., status 400).\n 2. `Fixes`: Google Sheets looping error on empty grid rows fixed. `null` values from nested paths in `Send HTTP Request` now correctly save as empty strings/nulls instead of throwing errors. Resolved older Google Sheets authentication issues. HTTP error statuses incorrectly marking run as "unknown" fixed.\n\n### 136. Version 1.1.71 (`Version 1.1.71.png`)\n- **Documentation Section**: Release Notes -> Version 1.1.71\n- **Core Overview**: Minor updates preserving variables on copy, handling null values, and fixing log-out issues.\n- **Key Improvements & Fixes**:\n 1. `Improvements`: Variable/table references preserved when copying specific building blocks to another TaskBot. `null` value behavior in `Send HTTP Request` consistent. Added more retry handling for `Open Link`.\n 2. `Fixes`: Fixed unexpected agent log outs. Fixed issue when two ZeroWork accounts open in different browsers appeared in the same log dialog. Fixed native table row deletion errors.\n\n### 137. Version 1.1.72 (`Version 1.1.72.png`)\n- **Documentation Section**: Release Notes -> Version 1.1.72\n- **Core Overview**: Massive feature update introducing Bypass Detection, Sticky Browser Profiles, Write JS API, Code in No-Code Inputs, and Multi-account automation support.\n- **Key Features & Changes**:\n 1. `Bypass Detection Mode`: TaskBots stay undetectable by Cloudflare and similar strong protections. Runs headless while maintaining detection evasion.\n 2. `Sticky Browser Profiles`: Create dedicated sticky profiles (cookies, storage, fingerprints) per account for multi-account automation. Clone existing regular profiles.\n 3. `Write JS API (zw)`: Native API support for importing npm packages, Local & Global state variables, Device Storage secrets, Utilities (`zw.log()`), Browser Context management, and Metadata retrieval.\n 4. `New Building Blocks`: `Launch Browser` and `Quit Browser` for granular control.\n 5. `Powerful Launch Options`: Inject scripts, use external Chromium browsers (Brave, Chrome), custom launch args, window control, and `Even more options via APIs` for Firefox/add-ons.\n 6. `Code Input in No-Code Blocks`: Template expressions `${...}` and code blocks `${[...]}` allow using code/logic directly in text fields.\n 7. `Device Storage (Secrets)`: Securely store passwords/API keys locally.\n 8. `Breaking Changes`: Legacy Non-incognito mode and "Run in my regular browser" consolidated into profile setup. File upload limit set to 300MB. Spintax disabled by default on inputs to prevent unintended parsing.\n\n### 138. Version 1.1.73 (`Version 1.1.73.png`)\n- **Documentation Section**: Release Notes -> Version 1.1.73\n- **Core Overview**: Stability update focused on browser launch resilience following the massive 1.1.72 release.\n- **Key Improvements & Fixes**:\n 1. `Improvements`: More reliable browser launches. Better browser profile cloning (retries if profile files change mid-copy). Improved error messaging on browser launch failures. Invalid JSON body in `Send HTTP Request` block throws clearer error.\n 2. `Fixes`: Fixed default Chrome args overwriting user-provided args.\n\n### 139. Version 1.1.74 (`Version 1.1.74.png`)\n- **Documentation Section**: Release Notes -> Version 1.1.74\n- **Core Overview**: Introduces Multi-Agent support and White-Label Desktop Agents for enterprise/agency distribution.\n- **Key Features & Changes**:\n 1. `Multi-Agent Support`: Manage multiple Desktop Agents from one ZeroWork account. Trigger runs on specific Agents via webhook using `agent=<AGENT_ID>`.\n 2. `White-Label Desktop Agents`: Brand the Desktop Agent with custom company name and logo for distribution to end customers.\n 3. `Optimizations`: Faster CSV imports into native tables. More reliable webhook connections.\n 4. `Fixes`: Random connection slowdowns, proxy authentication in Bypass Detection Mode, sticky profiles opening as guest, and Remove Duplicates logic fixed.\n\n### 140. Website Is Glitching And Flashing (`Website Is Glitching And Flashing.png`)\n- **Documentation Section**: Common Problems -> Website is Glitching and Flashing\n- **Core Overview**: Addresses UI flashing/looping behavior during execution.\n- **Troubleshooting**: \n - Occurs when the TaskBot cannot find a selector.\n - The agent is continually retrying to find the element, causing visual glitches.\n - Fix by ensuring the selector is valid and uniquely identifiable (refer to "No Selector is Found").\n\n### 141. Website Requires Sms Or Email Verification (`Website Requires Sms Or Email Verification.png`)\n- **Documentation Section**: Common Problems -> Website Requires SMS or Email Verification\n- **Core Overview**: Strategy for handling unexpected 2FA or verification pop-ups.\n- **Implementation Strategy**:\n - Use `Check Web Element` to detect verification pop-ups.\n - For active/attended runs: Add a long delay and manually enter the code while the TaskBot pauses.\n - For background/headless runs: It\'s impossible to interact manually. Terminate the run and use `Send Notification` to alert yourself.\n\n### 142. What Are Selectors (`What Are Selectors.png`)\n- **Documentation Section**: Using Selectors -> What Are Selectors\n- **Core Overview**: Introduction to how elements are identified on a web page using CSS or XPath selectors.\n- **Key Concepts**:\n - Every element on a website can be identified by a unique selector (CSS or XPath).\n - To interact with an element (e.g., click a button), the TaskBot needs to know its selector.\n - ZeroWork supports both CSS and XPath, but the guide focuses on CSS as it is more beginner-friendly. XPath is for advanced users.\n - Getting selectors can be done by: Copying Selectors, Using Element\'s Text, or Building Custom Selectors.\n\n### 143. When I Use Data From Table No Data Is Being Pulled (`When I Use Data From Table No Data Is Being Pulled.png`)\n- **Documentation Section**: Common Problems -> When I Use Data from Table, No Data is Being Pulled\n- **Core Overview**: Explains how to properly reference table data inside and outside of loops.\n- **Implementation Rules**:\n - **With Loops**: To use data from tables, you *must* use the `Start Repeat` building block with the loop type `Dynamic Loop` to iterate over the rows.\n - **Without Loops**: You cannot directly reference a table column in a block (like `Open Link`) if it\'s not inside a loop iterating over that table.\n - **Variables**: Referencing variables (not table columns) works fine without a loop.\n - **First Row Only**: If you only want to use the first row of a table without iterating through all of them, use `Start Repeat` (Dynamic) but set the "Repetition limit (optional)" to `1`.\n\n### 144. When Using Insert Data Block First Letters Are Cut Off (`When Using Insert Data Block First Letters Are Cut Off.png`)\n- **Documentation Section**: Common Problems -> When Using Insert Data Block, First Letters Are Cut Off\n- **Core Overview**: Solves the issue where typed text misses the first few characters.\n- **Troubleshooting**:\n - **Cause**: This happens because the TaskBot starts typing before the input field has fully loaded or gained focus.\n - **Fix**: Add more delay (`min sec` / `max sec`) to the *preceding* building block (e.g., the `Click Web Element` block that clicks the input field before typing) to ensure the field is fully ready.\n\n### 145. Workflow Has More Than One Starting Building Block (`Workflow Has More Than One Starting Building Block.png`)\n- **Documentation Section**: Common Problems -> Workflow Has More than One Starting Building Block\n- **Core Overview**: Resolves the error caused by disconnected or improperly connected blocks in the flow.\n- **Troubleshooting**:\n - **Cause**: Either you have disconnected loose building blocks on the canvas, or blocks are connected backwards (bottom to top, or right to left). Blocks can only be connected top-to-bottom or left-to-right.\n - **Identification Option 1**: Look at the error message for the specific block IDs (e.g., `806460, 809891`). Use the search bar on the canvas to find those specific blocks.\n - **Identification Option 2**: Use the Auto-Align feature. This will align the workflow and bring any floating/loose blocks into view. (Recommendation: duplicate the TaskBot before auto-aligning to preserve your visual layout).\n\n### 146. Write And Read Variables And Tables (`Write And Read Variables And Tables.png`)\n- **Documentation Section**: Using Building Blocks -> Write Javascript -> Write and Read Variables and Tables\n- **Core Overview**: Explains the `zw.getRef()` and `zw.setRef()` API methods for interacting with ZeroWork tables and variables via code.\n- **API Methods**:\n - `await zw.getRef({ ref_id: number, name: string })`: Returns the string value from a variable or table column. (Async)\n - `await zw.setRef({ ref_id: number, name: string, value: string })`: Saves a string value to a variable or table column. (Async/Sync)\n- **Rules & Limitations**:\n - **ref_id**: The numeric ID shown in the left sidebar next to a table or variable.\n - **name**: Identifies the column or variable name. It is **case-sensitive**.\n - **Values**: Values are strictly stored as strings. To store arrays or objects, use `JSON.stringify()` on write, and `JSON.parse()` on read.\n- **Loop Behavior**:\n - Reading existing rows: Place `Start Repeat` (Dynamic) *before* the JS block.\n - Appending new rows: Place `Start Repeat` (Standard) *before* the JS block, OR use the `appendIndex` property inside `setRef()` (e.g., `appendIndex: i`) to manually add rows from a code loop.\n - **Warning**: Do not mix `appendIndex` in code with a built-in `Start Repeat` loop index, as it causes mismatched rows.\n\n### 147. Write Javascript (`Write Javascript.png`)\n- **Documentation Section**: Using Building Blocks -> Write Javascript\n- **Core Overview**: Comprehensive guide to the `Write JavaScript` block and the `zw` API for advanced TaskBot logic.\n- **Capabilities & APIs**:\n - **Imports**: `zw.import(package, options)` or `zw.packages.*` to install npm packages on the fly.\n - **Variables/Tables**: `zw.getRef()` and `zw.setRef()`.\n - **Local/Global State**: `zw.state.*` (per-run state, clears when run ends), `zw.globalState.*` (agent-wide state, stays across runs on the same device).\n - **Device Storage**: `zw.deviceStorage.*` to persist key-value data on the device (survives restarts/reinstalls, never sent to ZeroWork servers).\n - **Utilities**: `zw.delay()`, `zw.log()`, `zw.logTemp()` for logging and waiting.\n - **Browser Context**: `zw.browserContext.*` (launch, quit, manage contexts, custom proxy, geolocation, scripts).\n - **Metadata**: `zw.getTaskbotInfo()`, `zw.getAgentInfo()` to read TaskBot/Agent details.\n- **Execution Modes**:\n - **Local vs Browser**: Code runs locally in the Node.js runtime by default. Check "Run locally" to ensure Node.js APIs/packages work.\n - **Browser limitations**: If running in the browser context, `zw.getRef()`, `zw.deviceStorage.*`, `zw.delay()`, and `zw.getTaskbotInfo()` are available. However, imports, global state, and browser context management are limited or unavailable.\n- **Code in No-Code Blocks**: Use `${...}` for expressions or `${[...]}` for code blocks directly in standard building block inputs.\n\n### 148. Copy Selectors (`Copy Selectors.png`)\n- **Documentation Section**: Using Selectors -> Copy Selectors\n- **Core Overview**: The easiest method to get CSS selectors using a recommended Chrome extension.\n- **Implementation Strategy**:\n - Use the free "Copy CSS Selector" Chrome plugin.\n - Right-click on any element on the website and select "Copy CSS Selector" from the context menu.\n - Wait a few seconds for a dotted frame to appear around the element (confirming it found the selector).\n - Paste the copied selector directly into the ZeroWork building block.\n\n'};var hf=[{id:"tutorial_1",title:"Auto-visit links from an existing Google Sheet or data table in ZeroWork",content:`hi I'm Diana founder of zeror in this\r
313
313
  video I'm going to show you how to\r
314
314
  create a taskboard that iterates over\r
315
315
  your existing Google sheet or data table\r
@@ -9304,9 +9304,818 @@ It should open WhatsApp automatically, send all the messages. You can just sit b
9304
9304
 
9305
9305
  Speaker 1
9306
9306
  04:29 - 04:41
9307
- Like this, you can just run it, you can schedule it to run as much as you like. I hope you enjoyed this video. Please like and subscribe and good luck automating. Bye bye!`}];var j_=()=>{let t=process.env.ZEROWORK_BOTS;if(!t)return{};try{return JSON.parse(t)}catch{return console.error("Failed to parse ZEROWORK_BOTS environment variable. Must be valid JSON."),{}}},ho=new Er({name:"nagoc-zerowork",version:"1.1.13"},{capabilities:{tools:{},resources:{}}});function Ui(){return af}ho.setRequestHandler(Na,async()=>{let e=Ui().map(n=>({uri:`resource://zerowork/tutorials/${n.id}`,name:`ZeroWork Video Tutorial: ${n.title}`,mimeType:"text/plain",description:`Official video masterclass transcript for: ${n.title}`}));return{resources:[{uri:"resource://zerowork/general",name:"ZeroWork General Knowledge",mimeType:"text/plain",description:"General concepts about ZeroWork RPA, TaskBots, and Architecture"},{uri:"resource://zerowork/webhooks",name:"ZeroWork Webhooks Guide",mimeType:"text/plain",description:"How to trigger ZeroWork bots and pass dynamic data via webhooks"},{uri:"resource://zerowork/variables",name:"ZeroWork Variables Guide",mimeType:"text/plain",description:"How variables work in ZeroWork"},{uri:"resource://zerowork/tables",name:"ZeroWork Tables Guide",mimeType:"text/plain",description:"How data tables work in ZeroWork"},{uri:"resource://zerowork/selectors",name:"ZeroWork Selectors Guide",mimeType:"text/plain",description:"How CSS and XPath selectors work in ZeroWork"},{uri:"resource://zerowork/loops",name:"ZeroWork Loops Guide",mimeType:"text/plain",description:"How loops and repeats work in ZeroWork"},{uri:"resource://zerowork/chatgpt",name:"ZeroWork ChatGPT Guide",mimeType:"text/plain",description:"How to integrate ChatGPT via Ask ChatGPT block"},{uri:"resource://zerowork/anti_bot",name:"ZeroWork Anti-Bot Guide",mimeType:"text/plain",description:"Best practices to avoid bot detection and handle dynamic states"},{uri:"resource://zerowork/troubleshooting",name:"ZeroWork Troubleshooting Guide",mimeType:"text/plain",description:"Common problems and troubleshooting steps"},{uri:"resource://zerowork/building_blocks",name:"ZeroWork Building Blocks Guide",mimeType:"text/plain",description:"Comprehensive catalog of all ZeroWork building blocks and their options"},{uri:"resource://zerowork/dynamic_inputs",name:"ZeroWork Dynamic Inputs Guide",mimeType:"text/plain",description:"How to use dynamic inputs: variable/table references, code expressions, code blocks, and spintax in ZeroWork building blocks"},{uri:"resource://zerowork/visual_insights",name:"ZeroWork Visual Insights and Troubleshooting",mimeType:"text/plain",description:"Comprehensive visual documentation and troubleshooting guide for ZeroWork covering over 140 common scenarios."},...e]}});ho.setRequestHandler(Ma,async t=>{let e=t.params.uri,n="";if(e.startsWith("resource://zerowork/tutorials/")){let o=e.replace("resource://zerowork/tutorials/",""),a=Ui().find(s=>s.id===o);if(!a)throw new Error(`Tutorial resource not found: ${e}`);n=`=== ${a.title} ===
9307
+ Like this, you can just run it, you can schedule it to run as much as you like. I hope you enjoyed this video. Please like and subscribe and good luck automating. Bye bye!`}];import*as ln from"fs";import*as Nr from"path";function Or(){return'<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="5" x2="12" y2="19"></line><polyline points="19 12 12 19 5 12"></polyline></svg>'}function Z_(){return'<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"></polyline></svg>'}function F_(){return'<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="16" x2="12" y2="12"></line><line x1="12" y1="8" x2="12.01" y2="8"></line></svg>'}function U_(){return'<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="16" x2="12" y2="12"></line><line x1="12" y1="8" x2="12.01" y2="8"></line></svg>'}function W_(t){let e=t.toLowerCase();return e==="launch browser"||e==="quit browser"?{badgeClass:"badge-dark",color:"#64748b"}:e==="write javascript"?{badgeClass:"badge-orange",color:"#f97316"}:e==="start condition"||e==="check web element"||e.includes("condition")?{badgeClass:"badge-blue",color:"#3b82f6"}:e==="start repeat"||e==="after repeat"||e==="break repeat"||e.includes("repeat")?{badgeClass:"badge-purple",color:"#8b5cf6"}:e==="update data"||e==="number operations"||e==="format data"||e==="save web element"||e.includes("data")||e.includes("save")?{badgeClass:"badge-green",color:"#10b981"}:e==="send notification"||e.includes("notification")?{badgeClass:"badge-yellow",color:"#eab308"}:e==="abort run"||e==="raise error"||e==="abort"||e.includes("error")?{badgeClass:"badge-red",color:"#ef4444"}:{badgeClass:"badge-gray",color:"#94a3b8"}}function V_(t){return!t||t.length===0?"":`
9308
+ <table class="compact-inputs-table">
9309
+ <thead>
9310
+ <tr><th>Field</th><th>Value</th></tr>
9311
+ </thead>
9312
+ <tbody>
9313
+ ${t.map(n=>{let r=n.value.includes("{")||n.value.includes("}")||n.value.includes("await")||n.value.includes("zw.")?`<code>${Ne(n.value)}</code>`:Ne(n.value);return`<tr><td>${Ne(n.name)}</td><td>${r}</td></tr>`}).join(`
9314
+ `)}
9315
+ </tbody>
9316
+ </table>
9317
+ `}function Ne(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}function G_(t,e){let{badgeClass:n}=W_(t.name),r=["launch browser","start repeat","open link","check web element","insert text or data","write javascript","ask chatgpt","send http request"].includes(t.name.toLowerCase())?"pulse-btn":"",a=`<span class="badge ${n}">${Ne(t.name)}</span>`;return t.name.toLowerCase()==="write javascript"&&t.jsMode&&(a+=` <span class="badge badge-orange-light">${t.jsMode}</span>`),e==="Compact"?`
9318
+ <div class="block-card compact-card" data-block="${t.id}">
9319
+ <div class="block-info-left">
9320
+ <div class="block-badges-row">${a}</div>
9321
+ <span class="block-name">${Ne(t.description)}</span>
9322
+ </div>
9323
+ <div class="compact-details">
9324
+ ${V_(t.inputs)}
9325
+ ${t.jsCode?`
9326
+ <div class="compact-js-code">
9327
+ <pre><code>${Ne(t.jsCode)}</code></pre>
9328
+ </div>
9329
+ `:""}
9330
+ ${t.note?`
9331
+ <div class="compact-note-box">
9332
+ <strong>Important Remark:</strong>
9333
+ <span>${Ne(t.note)}</span>
9334
+ </div>
9335
+ `:""}
9336
+ </div>
9337
+ </div>
9338
+ `:`
9339
+ <div class="block-card ${e==="JS-heavy"&&t.name.toLowerCase()==="write javascript"?"js-heavy-card":""}" data-block="${t.id}" onclick="showBlockInfo('${t.id}')">
9340
+ <div class="block-info-left">
9341
+ <div class="block-badges-row">${a}</div>
9342
+ <span class="block-name">${Ne(t.description)}</span>
9343
+ </div>
9344
+ <button class="info-btn ${r}" aria-label="Info">
9345
+ ${U_()}
9346
+ </button>
9347
+ </div>
9348
+ `}function Gi(t,e,n,o){let r="";for(let a=0;a<t.length;a++){let s=t[a];if(n.has(s))continue;n.add(s);let i=e[s];if(!i)continue;r+=G_(i,o);let l=i.branches&&i.branches.length>0&&i.branchMapping,c=a===t.length-1;if(l){r+=`<div class="flow-arrow">${Or()}</div>`,r+='<div class="split-container">';for(let u of i.branches||[]){let h=i.branchMapping?.[u]||[];h.forEach(y=>n.add(y));let d=Gi(h,e,new Set,o),p=u.toLowerCase().includes("found")||u.toLowerCase().includes("yes")||u.toLowerCase().includes("success"),m=p?"label-success":"label-warning",w=p?Z_():F_();r+=`
9349
+ <div class="split-column">
9350
+ <div class="split-label-container ${m}">
9351
+ ${w}
9352
+ <span>${u}</span>
9353
+ </div>
9354
+ ${d}
9355
+ </div>
9356
+ `}r+="</div>",c||(r+=`<div class="flow-arrow">${Or()}</div>`)}else c||(r+=`<div class="flow-arrow">${Or()}</div>`)}return r}function df(t){let{style:e="Full interactive",workflowTitle:n,workflowDescription:o="",blocks:r,outputPath:a}=t,s=a||Nr.join(process.cwd(),"outputs","zerowork-diagram.html"),i=Nr.dirname(s);ln.existsSync(i)||ln.mkdirSync(i,{recursive:!0});let l={};r.forEach(w=>{l[w.id]=w});let c=new Set;r.forEach(w=>{w.branchMapping&&Object.values(w.branchMapping).forEach(y=>{y.forEach(b=>c.add(b))})});let u=r.map(w=>w.id).filter(w=>!c.has(w)),h="",d=new Set;if(e==="Collapsed phases"){let w={},y=[];r.forEach(b=>{let x=b.phase||"General Process";w[x]||(w[x]=[],y.push(x)),c.has(b.id)||w[x].push(b.id)}),y.forEach((b,x)=>{let S=w[b],T=Gi(S,l,d,e);h+=`
9357
+ <details class="phase-details" ${x===0?"open":""}>
9358
+ <summary class="phase-summary">
9359
+ <span class="phase-title">${Ne(b)}</span>
9360
+ <span class="phase-toggle-icon">
9361
+ <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="6 9 12 15 18 9"></polyline></svg>
9362
+ </span>
9363
+ </summary>
9364
+ <div class="phase-content">
9365
+ ${T}
9366
+ </div>
9367
+ </details>
9368
+ `,x<y.length-1&&(h+=`<div class="flow-arrow">${Or()}</div>`)})}else h=Gi(u,l,d,e);let p=Object.keys(l).length;console.error(`Verified ${p} ZeroWork building blocks for diagram.`);let m=H_(e,n,o,h,l);return ln.writeFileSync(s,m,"utf8"),s}function H_(t,e,n,o,r){let a=t==="Compact",s=a?"grid-template-columns: 1fr;":"";return`<!DOCTYPE html>
9369
+ <html lang="en">
9370
+ <head>
9371
+ <meta charset="UTF-8">
9372
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
9373
+ <title>ZeroWork TaskBot Workflow: ${Ne(e)}</title>
9374
+ <style>
9375
+ :root {
9376
+ --bg-main: #0b0f19;
9377
+ --bg-card: #161e2f;
9378
+ --bg-card-hover: #1e293b;
9379
+ --bg-sidebar: #0f172a;
9380
+ --border-color: rgba(255, 255, 255, 0.06);
9381
+ --border-hover: #3b82f6;
9382
+ --text-main: #f8fafc;
9383
+ --text-muted: #94a3b8;
9384
+
9385
+ /* ZeroWork block theme colors */
9386
+ --color-purple: #8b5cf6;
9387
+ --color-purple-bg: rgba(139, 92, 246, 0.1);
9388
+ --color-blue: #3b82f6;
9389
+ --color-blue-bg: rgba(59, 130, 246, 0.1);
9390
+ --color-yellow: #eab308;
9391
+ --color-yellow-bg: rgba(234, 179, 8, 0.1);
9392
+ --color-red: #ef4444;
9393
+ --color-red-bg: rgba(239, 68, 68, 0.1);
9394
+ --color-green: #10b981;
9395
+ --color-green-bg: rgba(16, 185, 129, 0.1);
9396
+ --color-orange: #f97316;
9397
+ --color-orange-bg: rgba(249, 115, 22, 0.1);
9398
+ --color-gray: #64748b;
9399
+ --color-gray-bg: rgba(100, 116, 139, 0.1);
9400
+ --color-dark: #334155;
9401
+ --color-dark-bg: rgba(51, 65, 85, 0.2);
9402
+ }
9308
9403
 
9309
- ${a.content}`}else if(e==="resource://zerowork/general")n=_e.general;else if(e==="resource://zerowork/webhooks")n=_e.webhooks;else if(e==="resource://zerowork/variables")n=_e.variables;else if(e==="resource://zerowork/tables")n=_e.tables;else if(e==="resource://zerowork/selectors")n=_e.selectors;else if(e==="resource://zerowork/loops")n=_e.loops;else if(e==="resource://zerowork/chatgpt")n=_e.chatgpt;else if(e==="resource://zerowork/anti_bot")n=_e.anti_bot;else if(e==="resource://zerowork/troubleshooting")n=_e.troubleshooting;else if(e==="resource://zerowork/building_blocks")n=_e.building_blocks;else if(e==="resource://zerowork/dynamic_inputs")n=_e.dynamic_inputs;else if(e==="resource://zerowork/visual_insights")n=_e.visual_insights;else throw new Error(`Resource not found: ${e}`);return{contents:[{uri:e,mimeType:"text/plain",text:n}]}});ho.setRequestHandler(Fa,async()=>({tools:[{name:"list_taskbots",description:"Lists all configured TaskBots and their names that are available to trigger.",inputSchema:{type:"object",properties:{}}},{name:"trigger_taskbot",description:"Triggers a specific ZeroWork TaskBot by its configured name. Does not send data.",inputSchema:{type:"object",properties:{botName:{type:"string",description:"The name of the TaskBot to trigger (must be one from list_taskbots)"}},required:["botName"]}},{name:"trigger_taskbot_with_data",description:"Triggers a specific ZeroWork TaskBot and sends dynamic JSON data to its zw_webhook_data variable.",inputSchema:{type:"object",properties:{botName:{type:"string",description:"The name of the TaskBot to trigger"},payload:{type:"object",description:"The JSON object payload to send to the bot"}},required:["botName","payload"]}},{name:"trigger_webhook_url",description:"Triggers an arbitrary ZeroWork webhook URL directly.",inputSchema:{type:"object",properties:{url:{type:"string",description:"The full ZeroWork webhook URL"},payload:{type:"object",description:"Optional JSON object payload to send to the bot"}},required:["url"]}},{name:"generate_robust_selector",description:"Analyzes an HTML snippet and target requirements to generate robust, non-brittle CSS and XPath selectors tailored for ZeroWork TaskBots.",inputSchema:{type:"object",properties:{htmlSnippet:{type:"string",description:"The raw HTML snippet containing the target element and its surrounding container hierarchy."},targetText:{type:"string",description:"Optional exact or partial visible text of the target element (e.g., 'Connect', 'Follow')."},description:{type:"string",description:"Optional description of what the element is or its context (e.g., 'The experience list container on LinkedIn', 'Submit button on a dynamic form')."}},required:["htmlSnippet"]}},{name:"get_mcp_version",description:"Returns the version of this MCP server package currently running.",inputSchema:{type:"object",properties:{}}},{name:"search_zerowork_docs",description:"Search and query the ENTIRE ZeroWork official documentation at docs.zerowork.io. Use this tool for ANY question about ZeroWork including features, building blocks, dynamic inputs, TaskBots, spintax, variables, code in inputs, agents, triggers, actions, conditions, loops, integrations, webhooks, selectors, device storage, or any how-to guides. ALWAYS use this tool before answering any ZeroWork-related questions. IMPORTANT: If the user is asking about specific automation workflows, step-by-step use cases (e.g. WhatsApp, LinkedIn, cold outreach), or advanced selector strategies, you MUST ALSO call search_zerowork_tutorials to check the expert video masterclass knowledge base!",inputSchema:{type:"object",properties:{question:{type:"string",description:"The natural language question to search the docs for"}},required:["question"]}},{name:"search_zerowork_tutorials",description:"Search and query the complete library of official ZeroWork video masterclasses, tutorial transcripts, and expert automation guides. ALWAYS call this tool when the user asks about specific automation workflows, step-by-step use cases (e.g., WhatsApp, LinkedIn, cold outreach, lead generation), advanced CSS selector walkthroughs, or dynamic loop setups, EVEN IF the user does not explicitly mention the words 'tutorials', 'videos', or 'guides'.",inputSchema:{type:"object",properties:{query:{type:"string",description:"The natural language search query or keywords to find in the video tutorials"}},required:["query"]}}]}));ho.setRequestHandler(Rn,async t=>{let{name:e,arguments:n}=t.params,o=j_();try{if(e==="list_taskbots"){let r=Object.keys(o);return r.length===0?{content:[{type:"text",text:'No TaskBots are configured. Please set the ZEROWORK_BOTS environment variable in your Claude config (e.g., {"myBot": "https://hook.zerowork.io/..."}).'}]}:{content:[{type:"text",text:`Configured TaskBots:
9404
+ * {
9405
+ box-sizing: border-box;
9406
+ margin: 0;
9407
+ padding: 0;
9408
+ }
9409
+
9410
+ body {
9411
+ font-family: 'Inter', system-ui, -apple-system, sans-serif;
9412
+ background-color: var(--bg-main);
9413
+ color: var(--text-main);
9414
+ display: grid;
9415
+ grid-template-columns: 1fr 420px;
9416
+ ${s}
9417
+ min-height: 100vh;
9418
+ overflow-x: hidden;
9419
+ }
9420
+
9421
+ /* Layout */
9422
+ .diagram-container {
9423
+ padding: 2.5rem;
9424
+ overflow-y: auto;
9425
+ height: 100vh;
9426
+ display: flex;
9427
+ flex-direction: column;
9428
+ align-items: center;
9429
+ }
9430
+
9431
+ .sidebar-container {
9432
+ background-color: var(--bg-sidebar);
9433
+ border-left: 1px solid var(--border-color);
9434
+ padding: 2.5rem 2rem;
9435
+ overflow-y: auto;
9436
+ height: 100vh;
9437
+ position: sticky;
9438
+ top: 0;
9439
+ display: flex;
9440
+ flex-direction: column;
9441
+ gap: 1.5rem;
9442
+ }
9443
+
9444
+ .header {
9445
+ width: 100%;
9446
+ max-width: 800px;
9447
+ margin-bottom: 2rem;
9448
+ text-align: center;
9449
+ }
9450
+
9451
+ .header h1 {
9452
+ font-size: 2rem;
9453
+ font-weight: 800;
9454
+ margin-bottom: 0.6rem;
9455
+ background: linear-gradient(to right, #60a5fa, #a78bfa);
9456
+ -webkit-background-clip: text;
9457
+ -webkit-text-fill-color: transparent;
9458
+ }
9459
+
9460
+ .header p {
9461
+ color: var(--text-muted);
9462
+ font-size: 1rem;
9463
+ line-height: 1.5;
9464
+ }
9465
+
9466
+ .legend {
9467
+ display: flex;
9468
+ flex-wrap: wrap;
9469
+ gap: 0.8rem;
9470
+ justify-content: center;
9471
+ margin-bottom: 2.5rem;
9472
+ padding: 0.8rem 1.2rem;
9473
+ background: rgba(255, 255, 255, 0.02);
9474
+ border-radius: 10px;
9475
+ border: 1px solid var(--border-color);
9476
+ max-width: 800px;
9477
+ }
9478
+
9479
+ .legend-item {
9480
+ display: flex;
9481
+ align-items: center;
9482
+ gap: 0.5rem;
9483
+ font-size: 0.8rem;
9484
+ color: var(--text-muted);
9485
+ }
9486
+
9487
+ .legend-color {
9488
+ width: 12px;
9489
+ height: 12px;
9490
+ border-radius: 3px;
9491
+ }
9492
+
9493
+ .workflow {
9494
+ display: flex;
9495
+ flex-direction: column;
9496
+ align-items: center;
9497
+ width: 100%;
9498
+ max-width: 800px;
9499
+ }
9500
+
9501
+ .loop-box {
9502
+ border: 2px dashed var(--color-purple);
9503
+ background: rgba(139, 92, 246, 0.01);
9504
+ border-radius: 16px;
9505
+ padding: 2rem 1.5rem;
9506
+ margin: 1.5rem 0;
9507
+ width: 100%;
9508
+ display: flex;
9509
+ flex-direction: column;
9510
+ align-items: center;
9511
+ position: relative;
9512
+ }
9513
+
9514
+ .loop-badge {
9515
+ position: absolute;
9516
+ top: -12px;
9517
+ left: 24px;
9518
+ background-color: var(--color-purple);
9519
+ color: white;
9520
+ padding: 0.2rem 0.75rem;
9521
+ border-radius: 20px;
9522
+ font-size: 0.75rem;
9523
+ font-weight: 700;
9524
+ box-shadow: 0 4px 6px rgba(0,0,0,0.1);
9525
+ }
9526
+
9527
+ /* Cards */
9528
+ .block-card {
9529
+ background-color: var(--bg-card);
9530
+ border: 1px solid var(--border-color);
9531
+ border-radius: 12px;
9532
+ width: 340px;
9533
+ padding: 1.1rem;
9534
+ display: flex;
9535
+ align-items: center;
9536
+ justify-content: space-between;
9537
+ cursor: pointer;
9538
+ transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
9539
+ box-shadow: 0 4px 6px rgba(0, 0, 0, 0.2);
9540
+ }
9541
+
9542
+ .block-card:hover {
9543
+ background-color: var(--bg-card-hover);
9544
+ border-color: var(--border-hover);
9545
+ transform: translateY(-2px);
9546
+ box-shadow: 0 10px 15px -3px rgba(59, 130, 246, 0.25);
9547
+ }
9548
+
9549
+ .block-card.active {
9550
+ border-color: #3b82f6;
9551
+ box-shadow: 0 0 12px rgba(59, 130, 246, 0.35);
9552
+ }
9553
+
9554
+ .block-card.js-heavy-card {
9555
+ border-color: var(--color-orange);
9556
+ box-shadow: 0 0 10px rgba(249, 115, 22, 0.25);
9557
+ }
9558
+
9559
+ .block-info-left {
9560
+ display: flex;
9561
+ flex-direction: column;
9562
+ gap: 0.5rem;
9563
+ flex: 1;
9564
+ }
9565
+
9566
+ .block-badges-row {
9567
+ display: flex;
9568
+ flex-wrap: wrap;
9569
+ gap: 0.4rem;
9570
+ }
9571
+
9572
+ .block-name {
9573
+ font-size: 0.95rem;
9574
+ font-weight: 600;
9575
+ line-height: 1.4;
9576
+ }
9577
+
9578
+ /* Badges */
9579
+ .badge {
9580
+ display: inline-block;
9581
+ padding: 0.15rem 0.5rem;
9582
+ border-radius: 4px;
9583
+ font-size: 0.7rem;
9584
+ font-weight: 800;
9585
+ text-transform: uppercase;
9586
+ letter-spacing: 0.05em;
9587
+ }
9588
+
9589
+ .badge-purple { background-color: var(--color-purple-bg); color: var(--color-purple); }
9590
+ .badge-blue { background-color: var(--color-blue-bg); color: var(--color-blue); }
9591
+ .badge-yellow { background-color: var(--color-yellow-bg); color: var(--color-yellow); }
9592
+ .badge-red { background-color: var(--color-red-bg); color: var(--color-red); }
9593
+ .badge-green { background-color: var(--color-green-bg); color: var(--color-green); }
9594
+ .badge-orange { background-color: var(--color-orange-bg); color: var(--color-orange); }
9595
+ .badge-orange-light { background-color: rgba(249, 115, 22, 0.05); color: var(--color-orange); border: 1px solid rgba(249, 115, 22, 0.2); }
9596
+ .badge-gray { background-color: var(--color-gray-bg); color: var(--color-gray); }
9597
+ .badge-dark { background-color: var(--color-dark-bg); color: var(--text-main); border: 1px solid var(--border-color); }
9598
+
9599
+ .info-btn {
9600
+ background: none;
9601
+ border: none;
9602
+ color: var(--text-muted);
9603
+ cursor: pointer;
9604
+ padding: 0.3rem;
9605
+ display: flex;
9606
+ align-items: center;
9607
+ justify-content: center;
9608
+ transition: color 0.15s ease, transform 0.15s ease;
9609
+ margin-left: 0.5rem;
9610
+ }
9611
+
9612
+ .info-btn:hover {
9613
+ color: var(--text-main);
9614
+ transform: scale(1.1);
9615
+ }
9616
+
9617
+ /* Pulsing Animation */
9618
+ .pulse-btn {
9619
+ animation: pulse-glow 2s infinite;
9620
+ color: var(--border-hover);
9621
+ border-radius: 50%;
9622
+ }
9623
+
9624
+ @keyframes pulse-glow {
9625
+ 0% { box-shadow: 0 0 0 0 rgba(59, 130, 246, 0.5); }
9626
+ 70% { box-shadow: 0 0 0 8px rgba(59, 130, 246, 0); }
9627
+ 100% { box-shadow: 0 0 0 0 rgba(59, 130, 246, 0); }
9628
+ }
9629
+
9630
+ .flow-arrow {
9631
+ height: 36px;
9632
+ display: flex;
9633
+ align-items: center;
9634
+ justify-content: center;
9635
+ color: var(--text-muted);
9636
+ opacity: 0.4;
9637
+ }
9638
+
9639
+ /* Branching Layout */
9640
+ .split-container {
9641
+ display: flex;
9642
+ gap: 2.5rem;
9643
+ width: 100%;
9644
+ margin: 1.5rem 0;
9645
+ justify-content: center;
9646
+ }
9647
+
9648
+ .split-column {
9649
+ flex: 1;
9650
+ display: flex;
9651
+ flex-direction: column;
9652
+ align-items: center;
9653
+ background: rgba(22, 30, 47, 0.3);
9654
+ border: 1px dashed var(--border-color);
9655
+ border-radius: 14px;
9656
+ padding: 1.5rem;
9657
+ }
9658
+
9659
+ .split-label-container {
9660
+ display: flex;
9661
+ align-items: center;
9662
+ justify-content: center;
9663
+ width: 100%;
9664
+ margin-bottom: 1.25rem;
9665
+ font-size: 0.85rem;
9666
+ font-weight: 700;
9667
+ gap: 0.4rem;
9668
+ }
9669
+
9670
+ .label-success { color: var(--color-green); }
9671
+ .label-warning { color: var(--color-yellow); }
9672
+
9673
+ /* Collapsed Phases */
9674
+ .phase-details {
9675
+ width: 100%;
9676
+ background: rgba(255, 255, 255, 0.01);
9677
+ border: 1px solid var(--border-color);
9678
+ border-radius: 12px;
9679
+ margin-bottom: 0.5rem;
9680
+ overflow: hidden;
9681
+ }
9682
+
9683
+ .phase-summary {
9684
+ padding: 1.1rem 1.5rem;
9685
+ display: flex;
9686
+ justify-content: space-between;
9687
+ align-items: center;
9688
+ cursor: pointer;
9689
+ user-select: none;
9690
+ font-weight: 700;
9691
+ font-size: 1rem;
9692
+ color: #60a5fa;
9693
+ background: rgba(255, 255, 255, 0.02);
9694
+ list-style: none;
9695
+ }
9696
+
9697
+ .phase-summary::-webkit-details-marker {
9698
+ display: none;
9699
+ }
9700
+
9701
+ .phase-toggle-icon {
9702
+ transition: transform 0.2s ease;
9703
+ color: var(--text-muted);
9704
+ }
9705
+
9706
+ .phase-details[open] .phase-toggle-icon {
9707
+ transform: rotate(180deg);
9708
+ }
9709
+
9710
+ .phase-content {
9711
+ padding: 2rem 1.5rem;
9712
+ display: flex;
9713
+ flex-direction: column;
9714
+ align-items: center;
9715
+ border-top: 1px solid var(--border-color);
9716
+ }
9717
+
9718
+ /* Compact Style Card Extensions */
9719
+ .compact-card {
9720
+ width: 100%;
9721
+ max-width: 500px;
9722
+ flex-direction: column;
9723
+ align-items: flex-start;
9724
+ gap: 1rem;
9725
+ cursor: default;
9726
+ }
9727
+
9728
+ .compact-card:hover {
9729
+ transform: none;
9730
+ box-shadow: 0 4px 6px rgba(0, 0, 0, 0.2);
9731
+ border-color: var(--border-color);
9732
+ }
9733
+
9734
+ .compact-details {
9735
+ width: 100%;
9736
+ display: flex;
9737
+ flex-direction: column;
9738
+ gap: 0.8rem;
9739
+ }
9740
+
9741
+ .compact-desc {
9742
+ font-size: 0.85rem;
9743
+ color: var(--text-muted);
9744
+ line-height: 1.4;
9745
+ }
9746
+
9747
+ .compact-inputs-table {
9748
+ width: 100%;
9749
+ border-collapse: collapse;
9750
+ font-size: 0.8rem;
9751
+ border: 1px solid var(--border-color);
9752
+ border-radius: 6px;
9753
+ overflow: hidden;
9754
+ }
9755
+
9756
+ .compact-inputs-table th, .compact-inputs-table td {
9757
+ padding: 0.5rem 0.75rem;
9758
+ text-align: left;
9759
+ border-bottom: 1px solid var(--border-color);
9760
+ }
9761
+
9762
+ .compact-inputs-table th {
9763
+ background-color: rgba(255,255,255,0.02);
9764
+ color: var(--text-muted);
9765
+ font-weight: 600;
9766
+ }
9767
+
9768
+ .compact-inputs-table td code {
9769
+ font-family: monospace;
9770
+ background: rgba(255,255,255,0.06);
9771
+ padding: 0.1rem 0.3rem;
9772
+ border-radius: 4px;
9773
+ color: #60a5fa;
9774
+ }
9775
+
9776
+ .compact-note-box {
9777
+ background-color: rgba(234, 179, 8, 0.05);
9778
+ border-left: 3px solid var(--color-yellow);
9779
+ padding: 0.6rem 0.8rem;
9780
+ border-radius: 4px;
9781
+ font-size: 0.8rem;
9782
+ color: #fef08a;
9783
+ }
9784
+
9785
+ .compact-js-code pre {
9786
+ background-color: #080c14;
9787
+ padding: 0.75rem;
9788
+ border-radius: 6px;
9789
+ overflow-x: auto;
9790
+ border: 1px solid var(--border-color);
9791
+ }
9792
+
9793
+ .compact-js-code code {
9794
+ font-family: monospace;
9795
+ font-size: 0.8rem;
9796
+ color: #fb923c;
9797
+ }
9798
+
9799
+ /* Sidebar Details Panel */
9800
+ .panel-empty {
9801
+ display: flex;
9802
+ flex-direction: column;
9803
+ align-items: center;
9804
+ justify-content: center;
9805
+ height: 100%;
9806
+ color: var(--text-muted);
9807
+ text-align: center;
9808
+ gap: 1.25rem;
9809
+ }
9810
+
9811
+ .panel-empty svg {
9812
+ opacity: 0.25;
9813
+ }
9814
+
9815
+ .panel-content h2 {
9816
+ font-size: 1.5rem;
9817
+ font-weight: 800;
9818
+ margin-bottom: 0.3rem;
9819
+ line-height: 1.3;
9820
+ }
9821
+
9822
+ .panel-category {
9823
+ margin-bottom: 1.5rem;
9824
+ }
9825
+
9826
+ .panel-desc {
9827
+ color: var(--text-muted);
9828
+ font-size: 0.95rem;
9829
+ line-height: 1.6;
9830
+ margin-bottom: 1.8rem;
9831
+ padding-bottom: 1.2rem;
9832
+ border-bottom: 1px solid var(--border-color);
9833
+ }
9834
+
9835
+ .inputs-table {
9836
+ width: 100%;
9837
+ border-collapse: collapse;
9838
+ margin-bottom: 1.8rem;
9839
+ }
9840
+
9841
+ .inputs-table th, .inputs-table td {
9842
+ text-align: left;
9843
+ padding: 0.7rem 0.8rem;
9844
+ font-size: 0.85rem;
9845
+ border-bottom: 1px solid var(--border-color);
9846
+ }
9847
+
9848
+ .inputs-table th {
9849
+ color: var(--text-muted);
9850
+ font-weight: 700;
9851
+ text-transform: uppercase;
9852
+ font-size: 0.75rem;
9853
+ letter-spacing: 0.05em;
9854
+ }
9855
+
9856
+ .inputs-table td code {
9857
+ background: rgba(255, 255, 255, 0.05);
9858
+ padding: 0.2rem 0.4rem;
9859
+ border-radius: 4px;
9860
+ font-family: monospace;
9861
+ color: #60a5fa;
9862
+ word-break: break-all;
9863
+ }
9864
+
9865
+ .note-box {
9866
+ background-color: var(--color-yellow-bg);
9867
+ border-left: 4px solid var(--color-yellow);
9868
+ border-radius: 6px;
9869
+ padding: 1.2rem;
9870
+ font-size: 0.85rem;
9871
+ line-height: 1.5;
9872
+ color: #fef08a;
9873
+ margin-bottom: 1.5rem;
9874
+ }
9875
+
9876
+ .note-box strong {
9877
+ display: block;
9878
+ margin-bottom: 0.3rem;
9879
+ color: var(--color-yellow);
9880
+ }
9881
+
9882
+ .js-code-box {
9883
+ margin-top: 1.5rem;
9884
+ display: flex;
9885
+ flex-direction: column;
9886
+ gap: 0.5rem;
9887
+ }
9888
+
9889
+ .js-code-header {
9890
+ display: flex;
9891
+ justify-content: space-between;
9892
+ align-items: center;
9893
+ font-size: 0.8rem;
9894
+ color: var(--text-muted);
9895
+ }
9896
+
9897
+ .copy-btn {
9898
+ background: rgba(255,255,255,0.05);
9899
+ border: 1px solid var(--border-color);
9900
+ color: var(--text-main);
9901
+ padding: 0.3rem 0.75rem;
9902
+ border-radius: 4px;
9903
+ cursor: pointer;
9904
+ font-size: 0.75rem;
9905
+ transition: background 0.15s ease;
9906
+ }
9907
+
9908
+ .copy-btn:hover {
9909
+ background: rgba(255,255,255,0.12);
9910
+ }
9911
+
9912
+ .js-code-box pre {
9913
+ background-color: #06090f;
9914
+ border: 1px solid var(--border-color);
9915
+ border-radius: 8px;
9916
+ padding: 1rem;
9917
+ overflow-x: auto;
9918
+ }
9919
+
9920
+ .js-code-box code {
9921
+ font-family: monospace;
9922
+ color: #f97316;
9923
+ font-size: 0.85rem;
9924
+ }
9925
+
9926
+ /* Responsive */
9927
+ @media (max-width: 950px) {
9928
+ body {
9929
+ grid-template-columns: 1fr;
9930
+ height: auto;
9931
+ }
9932
+ .diagram-container, .sidebar-container {
9933
+ height: auto;
9934
+ }
9935
+ .sidebar-container {
9936
+ position: static;
9937
+ border-left: none;
9938
+ border-top: 1px solid var(--border-color);
9939
+ }
9940
+ }
9941
+ </style>
9942
+ </head>
9943
+ <body>
9944
+
9945
+ <div class="diagram-container">
9946
+ <div class="header">
9947
+ <h1>${Ne(e)}</h1>
9948
+ <p>${Ne(n)}</p>
9949
+ </div>
9950
+
9951
+
9952
+ <div class="legend">
9953
+ <div class="legend-item"><div class="legend-color" style="background-color: #64748b;"></div><span>Terminals</span></div>
9954
+ <div class="legend-item"><div class="legend-color" style="background-color: #8b5cf6;"></div><span>Loops</span></div>
9955
+ <div class="legend-item"><div class="legend-color" style="background-color: #3b82f6;"></div><span>Decisions</span></div>
9956
+ <div class="legend-item"><div class="legend-color" style="background-color: #10b981;"></div><span>Data Saves</span></div>
9957
+ <div class="legend-item"><div class="legend-color" style="background-color: #eab308;"></div><span>Notifications</span></div>
9958
+ <div class="legend-item"><div class="legend-color" style="background-color: #ef4444;"></div><span>Errors</span></div>
9959
+ <div class="legend-item"><div class="legend-color" style="background-color: #94a3b8;"></div><span>Generic Actions</span></div>
9960
+ </div>
9961
+
9962
+
9963
+ <div class="workflow">
9964
+ ${o}
9965
+ </div>
9966
+ </div>
9967
+
9968
+ ${a?"":`
9969
+ <div class="sidebar-container" id="sidebar">
9970
+ <div class="panel-empty" id="panel-empty">
9971
+ <svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect><line x1="9" y1="3" x2="9" y2="21"></line></svg>
9972
+ <p>Select any building block from the workflow on the left to view its detailed settings and properties.</p>
9973
+ </div>
9974
+
9975
+ <div class="panel-content" id="panel-content" style="display: none;">
9976
+ <h2 id="p-name">Block Name</h2>
9977
+ <div class="panel-category">
9978
+ <span class="badge" id="p-badge">Category</span>
9979
+ <span class="badge" id="p-jsmode" style="display: none;">PAGE</span>
9980
+ </div>
9981
+ <p class="panel-desc" id="p-desc">Description</p>
9982
+
9983
+ <table class="inputs-table" id="p-inputs-table">
9984
+ <thead>
9985
+ <tr>
9986
+ <th>Input Field</th>
9987
+ <th>Value/Setting</th>
9988
+ </tr>
9989
+ </thead>
9990
+ <tbody id="p-inputs-body">
9991
+ <!-- Dynamically populated -->
9992
+ </tbody>
9993
+ </table>
9994
+
9995
+ <div class="note-box" id="p-note-box" style="display: none;">
9996
+ <strong>Important Remark</strong>
9997
+ <span id="p-note-text">Gotchas.</span>
9998
+ </div>
9999
+
10000
+ <div class="js-code-box" id="p-js-code-box" style="display: none;">
10001
+ <div class="js-code-header">
10002
+ <span>JavaScript Code Content</span>
10003
+ <button class="copy-btn" id="copy-btn" onclick="copyJsCode()">Copy Code</button>
10004
+ </div>
10005
+ <pre><code id="p-js-code">code</code></pre>
10006
+ </div>
10007
+ </div>
10008
+ </div>
10009
+ `}
10010
+
10011
+ <script>
10012
+ const BLOCKS = ${JSON.stringify(r)};
10013
+
10014
+ function showBlockInfo(blockId) {
10015
+ // Toggle active states on cards
10016
+ document.querySelectorAll('.block-card').forEach(card => card.classList.remove('active'));
10017
+ const activeCard = document.querySelector(\`.block-card[data-block="\${blockId}"]\`);
10018
+ if (activeCard) activeCard.classList.add('active');
10019
+
10020
+ const data = BLOCKS[blockId];
10021
+ if (!data) return;
10022
+
10023
+ const emptyEl = document.getElementById('panel-empty');
10024
+ if (emptyEl) emptyEl.style.display = 'none';
10025
+
10026
+ const contentEl = document.getElementById('panel-content');
10027
+ if (contentEl) contentEl.style.display = 'block';
10028
+
10029
+ document.getElementById('p-name').textContent = data.name;
10030
+
10031
+ // Update badge class dynamically
10032
+ const badge = document.getElementById('p-badge');
10033
+ badge.textContent = data.category;
10034
+
10035
+ const badgeClass = getBadgeClass(data.name);
10036
+ badge.className = 'badge ' + badgeClass;
10037
+
10038
+ // Handle JS details
10039
+ const jsmode = document.getElementById('p-jsmode');
10040
+ const jscodebox = document.getElementById('p-js-code-box');
10041
+ if (data.name.toLowerCase() === 'write javascript') {
10042
+ jsmode.style.display = 'inline-block';
10043
+ jsmode.textContent = data.jsMode || 'PAGE';
10044
+ jscodebox.style.display = 'flex';
10045
+ document.getElementById('p-js-code').textContent = data.jsCode || '';
10046
+ } else {
10047
+ jsmode.style.display = 'none';
10048
+ jscodebox.style.display = 'none';
10049
+ }
10050
+
10051
+ document.getElementById('p-desc').textContent = data.description;
10052
+
10053
+ const body = document.getElementById('p-inputs-body');
10054
+ body.innerHTML = '';
10055
+
10056
+ const tableEl = document.getElementById('p-inputs-table');
10057
+ if (!data.inputs || data.inputs.length === 0) {
10058
+ tableEl.style.display = 'none';
10059
+ } else {
10060
+ tableEl.style.display = 'table';
10061
+ data.inputs.forEach(input => {
10062
+ const row = document.createElement('tr');
10063
+ const nameTd = document.createElement('td');
10064
+ nameTd.textContent = input.name;
10065
+ const valTd = document.createElement('td');
10066
+
10067
+ if (input.value.includes('{') || input.value.includes('}') || input.value.includes('await') || input.value.includes('zw.')) {
10068
+ const codeEl = document.createElement('code');
10069
+ codeEl.textContent = input.value;
10070
+ valTd.appendChild(codeEl);
10071
+ } else {
10072
+ valTd.textContent = input.value;
10073
+ }
10074
+
10075
+ row.appendChild(nameTd);
10076
+ row.appendChild(valTd);
10077
+ body.appendChild(row);
10078
+ });
10079
+ }
10080
+
10081
+ const noteBox = document.getElementById('p-note-box');
10082
+ if (data.note) {
10083
+ noteBox.style.display = 'block';
10084
+ document.getElementById('p-note-text').textContent = data.note;
10085
+ } else {
10086
+ noteBox.style.display = 'none';
10087
+ }
10088
+ }
10089
+
10090
+ function getBadgeClass(name) {
10091
+ const n = name.toLowerCase();
10092
+ if (n === 'launch browser' || n === 'quit browser') return 'badge-dark';
10093
+ if (n === 'write javascript') return 'badge-orange';
10094
+ if (n === 'start condition' || n === 'check web element' || n.includes('condition')) return 'badge-blue';
10095
+ if (n === 'start repeat' || n === 'after repeat' || n === 'break repeat' || n.includes('repeat')) return 'badge-purple';
10096
+ if (n === 'update data' || n === 'number operations' || n === 'format data' || n === 'save web element' || n.includes('data') || n.includes('save')) return 'badge-green';
10097
+ if (n === 'send notification' || n.includes('notification')) return 'badge-yellow';
10098
+ if (n === 'abort run' || n === 'raise error' || n === 'abort' || n.includes('error')) return 'badge-red';
10099
+ return 'badge-gray';
10100
+ }
10101
+
10102
+ function copyJsCode() {
10103
+ const code = document.getElementById('p-js-code').textContent;
10104
+ navigator.clipboard.writeText(code).then(() => {
10105
+ const btn = document.getElementById('copy-btn');
10106
+ const origText = btn.textContent;
10107
+ btn.textContent = 'Copied!';
10108
+ setTimeout(() => {
10109
+ btn.textContent = origText;
10110
+ }, 1500);
10111
+ });
10112
+ }
10113
+ </script>
10114
+ </body>
10115
+ </html>
10116
+ `}var J_=()=>{let t=process.env.ZEROWORK_BOTS;if(!t)return{};try{return JSON.parse(t)}catch{return console.error("Failed to parse ZEROWORK_BOTS environment variable. Must be valid JSON."),{}}},mo=new Ar({name:"nagoc-zerowork",version:"1.1.15"},{capabilities:{tools:{},resources:{}}});function Hi(){return hf}mo.setRequestHandler(Ba,async()=>{let e=Hi().map(n=>({uri:`resource://zerowork/tutorials/${n.id}`,name:`ZeroWork Video Tutorial: ${n.title}`,mimeType:"text/plain",description:`Official video masterclass transcript for: ${n.title}`}));return{resources:[{uri:"resource://zerowork/general",name:"ZeroWork General Knowledge",mimeType:"text/plain",description:"General concepts about ZeroWork RPA, TaskBots, and Architecture"},{uri:"resource://zerowork/webhooks",name:"ZeroWork Webhooks Guide",mimeType:"text/plain",description:"How to trigger ZeroWork bots and pass dynamic data via webhooks"},{uri:"resource://zerowork/variables",name:"ZeroWork Variables Guide",mimeType:"text/plain",description:"How variables work in ZeroWork"},{uri:"resource://zerowork/tables",name:"ZeroWork Tables Guide",mimeType:"text/plain",description:"How data tables work in ZeroWork"},{uri:"resource://zerowork/selectors",name:"ZeroWork Selectors Guide",mimeType:"text/plain",description:"How CSS and XPath selectors work in ZeroWork"},{uri:"resource://zerowork/loops",name:"ZeroWork Loops Guide",mimeType:"text/plain",description:"How loops and repeats work in ZeroWork"},{uri:"resource://zerowork/chatgpt",name:"ZeroWork ChatGPT Guide",mimeType:"text/plain",description:"How to integrate ChatGPT via Ask ChatGPT block"},{uri:"resource://zerowork/anti_bot",name:"ZeroWork Anti-Bot Guide",mimeType:"text/plain",description:"Best practices to avoid bot detection and handle dynamic states"},{uri:"resource://zerowork/troubleshooting",name:"ZeroWork Troubleshooting Guide",mimeType:"text/plain",description:"Common problems and troubleshooting steps"},{uri:"resource://zerowork/building_blocks",name:"ZeroWork Building Blocks Guide",mimeType:"text/plain",description:"Comprehensive catalog of all ZeroWork building blocks and their options"},{uri:"resource://zerowork/dynamic_inputs",name:"ZeroWork Dynamic Inputs Guide",mimeType:"text/plain",description:"How to use dynamic inputs: variable/table references, code expressions, code blocks, and spintax in ZeroWork building blocks"},{uri:"resource://zerowork/visual_insights",name:"ZeroWork Visual Insights and Troubleshooting",mimeType:"text/plain",description:"Comprehensive visual documentation and troubleshooting guide for ZeroWork covering over 140 common scenarios."},...e]}});mo.setRequestHandler(Fa,async t=>{let e=t.params.uri,n="";if(e.startsWith("resource://zerowork/tutorials/")){let o=e.replace("resource://zerowork/tutorials/",""),a=Hi().find(s=>s.id===o);if(!a)throw new Error(`Tutorial resource not found: ${e}`);n=`=== ${a.title} ===
10117
+
10118
+ ${a.content}`}else if(e==="resource://zerowork/general")n=_e.general;else if(e==="resource://zerowork/webhooks")n=_e.webhooks;else if(e==="resource://zerowork/variables")n=_e.variables;else if(e==="resource://zerowork/tables")n=_e.tables;else if(e==="resource://zerowork/selectors")n=_e.selectors;else if(e==="resource://zerowork/loops")n=_e.loops;else if(e==="resource://zerowork/chatgpt")n=_e.chatgpt;else if(e==="resource://zerowork/anti_bot")n=_e.anti_bot;else if(e==="resource://zerowork/troubleshooting")n=_e.troubleshooting;else if(e==="resource://zerowork/building_blocks")n=_e.building_blocks;else if(e==="resource://zerowork/dynamic_inputs")n=_e.dynamic_inputs;else if(e==="resource://zerowork/visual_insights")n=_e.visual_insights;else throw new Error(`Resource not found: ${e}`);return{contents:[{uri:e,mimeType:"text/plain",text:n}]}});mo.setRequestHandler(Ha,async()=>({tools:[{name:"list_taskbots",description:"Lists all configured TaskBots and their names that are available to trigger.",inputSchema:{type:"object",properties:{}}},{name:"trigger_taskbot",description:"Triggers a specific ZeroWork TaskBot by its configured name. Does not send data.",inputSchema:{type:"object",properties:{botName:{type:"string",description:"The name of the TaskBot to trigger (must be one from list_taskbots)"}},required:["botName"]}},{name:"trigger_taskbot_with_data",description:"Triggers a specific ZeroWork TaskBot and sends dynamic JSON data to its zw_webhook_data variable.",inputSchema:{type:"object",properties:{botName:{type:"string",description:"The name of the TaskBot to trigger"},payload:{type:"object",description:"The JSON object payload to send to the bot"}},required:["botName","payload"]}},{name:"trigger_webhook_url",description:"Triggers an arbitrary ZeroWork webhook URL directly.",inputSchema:{type:"object",properties:{url:{type:"string",description:"The full ZeroWork webhook URL"},payload:{type:"object",description:"Optional JSON object payload to send to the bot"}},required:["url"]}},{name:"generate_robust_selector",description:"Analyzes an HTML snippet and target requirements to generate robust, non-brittle CSS and XPath selectors tailored for ZeroWork TaskBots.",inputSchema:{type:"object",properties:{htmlSnippet:{type:"string",description:"The raw HTML snippet containing the target element and its surrounding container hierarchy."},targetText:{type:"string",description:"Optional exact or partial visible text of the target element (e.g., 'Connect', 'Follow')."},description:{type:"string",description:"Optional description of what the element is or its context (e.g., 'The experience list container on LinkedIn', 'Submit button on a dynamic form')."}},required:["htmlSnippet"]}},{name:"get_mcp_version",description:"Returns the version of this MCP server package currently running.",inputSchema:{type:"object",properties:{}}},{name:"search_zerowork_docs",description:"Search and query the ENTIRE ZeroWork official documentation at docs.zerowork.io. Use this tool for ANY question about ZeroWork including features, building blocks, dynamic inputs, TaskBots, spintax, variables, code in inputs, agents, triggers, actions, conditions, loops, integrations, webhooks, selectors, device storage, or any how-to guides. ALWAYS use this tool before answering any ZeroWork-related questions. IMPORTANT: If the user is asking about specific automation workflows, step-by-step use cases (e.g. WhatsApp, LinkedIn, cold outreach), or advanced selector strategies, you MUST ALSO call search_zerowork_tutorials to check the expert video masterclass knowledge base!",inputSchema:{type:"object",properties:{question:{type:"string",description:"The natural language question to search the docs for"}},required:["question"]}},{name:"search_zerowork_tutorials",description:"Search and query the complete library of official ZeroWork video masterclasses, tutorial transcripts, and expert automation guides. ALWAYS call this tool when the user asks about specific automation workflows, step-by-step use cases (e.g., WhatsApp, LinkedIn, cold outreach, lead generation), advanced CSS selector walkthroughs, or dynamic loop setups, EVEN IF the user does not explicitly mention the words 'tutorials', 'videos', or 'guides'.",inputSchema:{type:"object",properties:{query:{type:"string",description:"The natural language search query or keywords to find in the video tutorials"}},required:["query"]}},{name:"generate_diagram",description:"Generates a premium, interactive, self-contained HTML flowchart/diagram for a ZeroWork TaskBot workflow and saves it to the local filesystem.",inputSchema:{type:"object",properties:{workflowTitle:{type:"string",description:"Title of the workflow (e.g., 'Instagram DM Campaign')"},workflowDescription:{type:"string",description:"A high-level description of what the TaskBot does."},outputPath:{type:"string",description:"Optional absolute file path to save the HTML diagram. If not specified, saves to outputs/zerowork-diagram.html in the current working directory."},blocks:{type:"array",description:"An ordered list of ZeroWork building blocks representing the workflow sequence.",items:{type:"object",properties:{id:{type:"string",description:"Unique ID (e.g., 'block-1')"},name:{type:"string",description:"EXACT ZeroWork block name (e.g. 'Launch Browser', 'Start Repeat')"},category:{type:"string",description:"The block category (e.g. 'Browser Operations')"},description:{type:"string",description:"Description of what this block does in this workflow"},inputs:{type:"array",items:{type:"object",properties:{name:{type:"string"},value:{type:"string"}},required:["name","value"]}},note:{type:"string",description:"Optional warning/gotcha for this block"},jsMode:{type:"string",enum:["PAGE","LOCAL"],description:"For Write JavaScript blocks: PAGE (in browser) or LOCAL (locally in app)"},jsCode:{type:"string",description:"For Write JavaScript blocks: code content"},jsOutputVar:{type:"string",description:"For Write JavaScript blocks: output variable name"},branches:{type:"array",items:{type:"string"},description:"For decision nodes: list of branch names (e.g., ['Found', 'Not Found'])"},branchMapping:{type:"object",description:"Mapping from branch names to arrays of block IDs that execute in that branch (e.g., {'Found': ['block-6', 'block-7'], 'Not Found': ['block-12']})"},phase:{type:"string",description:"Optional grouping phase for 'Collapsed phases' style"}},required:["id","name","category","description"]}}},required:["workflowTitle","blocks"]}}]}));mo.setRequestHandler(jn,async t=>{let{name:e,arguments:n}=t.params,o=J_();try{if(e==="list_taskbots"){let r=Object.keys(o);return r.length===0?{content:[{type:"text",text:'No TaskBots are configured. Please set the ZEROWORK_BOTS environment variable in your Claude config (e.g., {"myBot": "https://hook.zerowork.io/..."}).'}]}:{content:[{type:"text",text:`Configured TaskBots:
9310
10119
  ${r.map(a=>`- ${a}`).join(`
9311
10120
  `)}`}]}}if(e==="trigger_taskbot"||e==="trigger_taskbot_with_data"){let r=String(n?.botName),a=o[r];if(!a)throw new Error(`Bot '${r}' not found in configuration. Use list_taskbots to see available bots.`);let s=e==="trigger_taskbot_with_data",i=s?n?.payload:null,l={method:s?"POST":"GET",headers:s?{"Content-Type":"application/json"}:void 0,body:s?JSON.stringify(i):void 0,signal:AbortSignal.timeout(15e3)},c=await fetch(a,l),u=await c.text();return{content:[{type:"text",text:`Successfully triggered ${r}.
9312
10121
  Status: ${c.status}
@@ -9345,7 +10154,7 @@ ${r.slice(0,500)}${r.length>500?`
9345
10154
  ... (truncated)`:""}
9346
10155
  \`\`\`
9347
10156
 
9348
- `,i+="*Guidance*: Use the strategies above to construct your selector in ZeroWork. Test the selector in your browser console using `document.querySelectorAll('your-selector')` to verify uniqueness before adding it to your TaskBot.",{content:[{type:"text",text:i}]}}if(e==="get_mcp_version")return{content:[{type:"text",text:"nagoc-zerowork version 1.1.13"}]};if(e==="search_zerowork_tutorials"){let r=String(n?.query||"");if(!r)throw new Error("The 'query' parameter is required.");let a=Ui();if(a.length===0)return{content:[{type:"text",text:"No video tutorial subtitles found. Please check that subtitle files are bundled correctly."}]};let s=r.toLowerCase(),i=s.split(/\s+/).filter(h=>h.length>1),l=a.map(h=>{let d=0,p=h.title.toLowerCase(),m=h.content.toLowerCase();return p.includes(s)&&(d+=10),m.includes(s)&&(d+=5),i.forEach(w=>{p.includes(w)&&(d+=3);let y=m.match(new RegExp(w,"g"));y&&(d+=y.length)}),{tutorial:h,score:d}}).filter(h=>h.score>0).sort((h,d)=>d.score-h.score);if(l.length===0)return{content:[{type:"text",text:`No tutorial subtitles matched the query "${r}". Try searching with different keywords or use search_zerowork_docs for official written documentation.`}]};let c=l.slice(0,5),u=`### \u{1F3AC} ZeroWork Video Tutorial Search Results
10157
+ `,i+="*Guidance*: Use the strategies above to construct your selector in ZeroWork. Test the selector in your browser console using `document.querySelectorAll('your-selector')` to verify uniqueness before adding it to your TaskBot.",{content:[{type:"text",text:i}]}}if(e==="get_mcp_version")return{content:[{type:"text",text:"nagoc-zerowork version 1.1.15"}]};if(e==="search_zerowork_tutorials"){let r=String(n?.query||"");if(!r)throw new Error("The 'query' parameter is required.");let a=Hi();if(a.length===0)return{content:[{type:"text",text:"No video tutorial subtitles found. Please check that subtitle files are bundled correctly."}]};let s=r.toLowerCase(),i=s.split(/\s+/).filter(h=>h.length>1),l=a.map(h=>{let d=0,p=h.title.toLowerCase(),m=h.content.toLowerCase();return p.includes(s)&&(d+=10),m.includes(s)&&(d+=5),i.forEach(w=>{p.includes(w)&&(d+=3);let y=m.match(new RegExp(w,"g"));y&&(d+=y.length)}),{tutorial:h,score:d}}).filter(h=>h.score>0).sort((h,d)=>d.score-h.score);if(l.length===0)return{content:[{type:"text",text:`No tutorial subtitles matched the query "${r}". Try searching with different keywords or use search_zerowork_docs for official written documentation.`}]};let c=l.slice(0,5),u=`### \u{1F3AC} ZeroWork Video Tutorial Search Results
9349
10158
 
9350
10159
  *Crawled from official video masterclasses and automation guides*
9351
10160
 
@@ -9355,7 +10164,7 @@ ${r.slice(0,500)}${r.length>500?`
9355
10164
  `,u+=`*Resource URI*: \`resource://zerowork/tutorials/${h.id}\` (Relevance Score: ${d})
9356
10165
 
9357
10166
  `;let y=h.content.split(`
9358
- `).filter(b=>i.some(z=>b.toLowerCase().includes(z))).slice(0,4).map(b=>`> "... ${b.trim()} ..."`).join(`
10167
+ `).filter(b=>i.some(x=>b.toLowerCase().includes(x))).slice(0,4).map(b=>`> "... ${b.trim()} ..."`).join(`
9359
10168
  `);y?u+=`**Matching Excerpts**:
9360
10169
  ${y}
9361
10170
 
@@ -9380,4 +10189,6 @@ ${s}`;else{let l=r.toLowerCase(),c=[];(l.includes("webhook")||l.includes("trigge
9380
10189
 
9381
10190
  ${h}
9382
10191
 
9383
- *Note: Total crawled pages indexed: ${a.length>0?a.length:35}. Use the exact details above to answer the user's question comprehensively.*`}return{content:[{type:"text",text:i}]}}throw new Error(`Unknown tool: ${e}`)}catch(r){return{content:[{type:"text",text:`Error executing tool ${e}: ${r.message}`}],isError:!0}}});async function N_(){let t=new Ar;await ho.connect(t),console.error("ZeroWork MCP Server running on stdio")}N_().catch(t=>{console.error("Fatal error in main():",t),process.exit(1)});
10192
+ *Note: Total crawled pages indexed: ${a.length>0?a.length:35}. Use the exact details above to answer the user's question comprehensively.*`}return{content:[{type:"text",text:i}]}}if(e==="generate_diagram"){let r=String(n?.workflowTitle||""),a=n?.workflowDescription?String(n.workflowDescription):void 0,s=n?.outputPath?String(n.outputPath):void 0,i=n?.blocks;if(!r||!i)throw new Error("Missing required fields: 'workflowTitle' and 'blocks' are required.");return{content:[{type:"text",text:`Successfully generated ZeroWork workflow diagram!
10193
+ Output Path: ${df({workflowTitle:r,workflowDescription:a,outputPath:s,blocks:i})}
10194
+ Total Blocks Verified: ${i.length}`}]}}throw new Error(`Unknown tool: ${e}`)}catch(r){return{content:[{type:"text",text:`Error executing tool ${e}: ${r.message}`}],isError:!0}}});async function K_(){let t=new Dr;await mo.connect(t),console.error("ZeroWork MCP Server running on stdio")}K_().catch(t=>{console.error("Fatal error in main():",t),process.exit(1)});