@crewpilot/agent 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +107 -0
- package/dist-npm/cli.js +25 -0
- package/dist-npm/index.js +481 -0
- package/package.json +69 -0
- package/prompts/agent.md +266 -0
- package/prompts/catalyst.config.json +72 -0
- package/prompts/copilot-instructions.md +36 -0
- package/prompts/skills/assure-code-quality/SKILL.md +112 -0
- package/prompts/skills/assure-pr-intelligence/SKILL.md +148 -0
- package/prompts/skills/assure-vulnerability-scan/SKILL.md +146 -0
- package/prompts/skills/autopilot-meeting/SKILL.md +407 -0
- package/prompts/skills/autopilot-worker/SKILL.md +623 -0
- package/prompts/skills/daily-digest/SKILL.md +167 -0
- package/prompts/skills/deliver-change-management/SKILL.md +132 -0
- package/prompts/skills/deliver-deploy-guard/SKILL.md +144 -0
- package/prompts/skills/deliver-doc-governance/SKILL.md +130 -0
- package/prompts/skills/engineer-feature-builder/SKILL.md +270 -0
- package/prompts/skills/engineer-root-cause-analysis/SKILL.md +150 -0
- package/prompts/skills/engineer-test-first/SKILL.md +148 -0
- package/prompts/skills/insights-knowledge-base/SKILL.md +181 -0
- package/prompts/skills/insights-pattern-detection/SKILL.md +142 -0
- package/prompts/skills/strategize-architecture-planner/SKILL.md +141 -0
- package/prompts/skills/strategize-solution-design/SKILL.md +118 -0
- package/scripts/postinstall.js +108 -0
|
@@ -0,0 +1,481 @@
|
|
|
1
|
+
var Rb=Object.create;var ba=Object.defineProperty;var Cb=Object.getOwnPropertyDescriptor;var Ib=Object.getOwnPropertyNames;var Ab=Object.getPrototypeOf,Ob=Object.prototype.hasOwnProperty;var N=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var _=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),wa=(r,e)=>{for(var t in e)ba(r,t,{get:e[t],enumerable:!0})},Nb=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Ib(e))!Ob.call(r,i)&&i!==t&&ba(r,i,{get:()=>e[i],enumerable:!(n=Cb(e,i))||n.enumerable});return r};var ka=(r,e,t)=>(t=r!=null?Rb(Ab(r)):{},Nb(e||!r||!r.__esModule?ba(t,"default",{value:r,enumerable:!0}):t,r));var zi=_(ee=>{"use strict";Object.defineProperty(ee,"__esModule",{value:!0});ee.regexpCode=ee.getEsmExportName=ee.getProperty=ee.safeStringify=ee.stringify=ee.strConcat=ee.addCodeArg=ee.str=ee._=ee.nil=ee._Code=ee.Name=ee.IDENTIFIER=ee._CodeOrName=void 0;var $i=class{};ee._CodeOrName=$i;ee.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Wr=class extends $i{constructor(e){if(super(),!ee.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}}};ee.Name=Wr;var at=class extends $i{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((t,n)=>`${t}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((t,n)=>(n instanceof Wr&&(t[n.str]=(t[n.str]||0)+1),t),{})}};ee._Code=at;ee.nil=new at("");function ug(r,...e){let t=[r[0]],n=0;for(;n<e.length;)ou(t,e[n]),t.push(r[++n]);return new at(t)}ee._=ug;var iu=new at("+");function pg(r,...e){let t=[Ti(r[0])],n=0;for(;n<e.length;)t.push(iu),ou(t,e[n]),t.push(iu,Ti(r[++n]));return NE(t),new at(t)}ee.str=pg;function ou(r,e){e instanceof at?r.push(...e._items):e instanceof Wr?r.push(e):r.push(LE(e))}ee.addCodeArg=ou;function NE(r){let e=1;for(;e<r.length-1;){if(r[e]===iu){let t=jE(r[e-1],r[e+1]);if(t!==void 0){r.splice(e-1,3,t);continue}r[e++]="+"}e++}}function jE(r,e){if(e==='""')return r;if(r==='""')return e;if(typeof r=="string")return e instanceof Wr||r[r.length-1]!=='"'?void 0:typeof e!="string"?`${r.slice(0,-1)}${e}"`:e[0]==='"'?r.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(r instanceof Wr))return`"${r}${e.slice(1)}`}function ME(r,e){return e.emptyStr()?r:r.emptyStr()?e:pg`${r}${e}`}ee.strConcat=ME;function LE(r){return typeof r=="number"||typeof r=="boolean"||r===null?r:Ti(Array.isArray(r)?r.join(","):r)}function DE(r){return new at(Ti(r))}ee.stringify=DE;function Ti(r){return JSON.stringify(r).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}ee.safeStringify=Ti;function qE(r){return typeof r=="string"&&ee.IDENTIFIER.test(r)?new at(`.${r}`):ug`[${r}]`}ee.getProperty=qE;function ZE(r){if(typeof r=="string"&&ee.IDENTIFIER.test(r))return new at(`${r}`);throw new Error(`CodeGen: invalid export name: ${r}, use explicit $id name mapping`)}ee.getEsmExportName=ZE;function UE(r){return new at(r.toString())}ee.regexpCode=UE});var cu=_(Ve=>{"use strict";Object.defineProperty(Ve,"__esModule",{value:!0});Ve.ValueScope=Ve.ValueScopeName=Ve.Scope=Ve.varKinds=Ve.UsedValueState=void 0;var Be=zi(),su=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},gs;(function(r){r[r.Started=0]="Started",r[r.Completed=1]="Completed"})(gs||(Ve.UsedValueState=gs={}));Ve.varKinds={const:new Be.Name("const"),let:new Be.Name("let"),var:new Be.Name("var")};var vs=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof Be.Name?e:this.name(e)}name(e){return new Be.Name(this._newName(e))}_newName(e){let t=this._names[e]||this._nameGroup(e);return`${e}${t.index++}`}_nameGroup(e){var t,n;if(!((n=(t=this._parent)===null||t===void 0?void 0:t._prefixes)===null||n===void 0)&&n.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=vs;var xs=class extends Be.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:t,itemIndex:n}){this.value=e,this.scopePath=(0,Be._)`.${new Be.Name(t)}[${n}]`}};Ve.ValueScopeName=xs;var FE=(0,Be._)`\n`,au=class extends vs{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?FE:Be.nil}}get(){return this._scope}name(e){return new xs(e,this._newName(e))}value(e,t){var n;if(t.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let i=this.toName(e),{prefix:o}=i,s=(n=t.key)!==null&&n!==void 0?n:t.ref,a=this._values[o];if(a){let u=a.get(s);if(u)return u}else a=this._values[o]=new Map;a.set(s,i);let c=this._scope[o]||(this._scope[o]=[]),l=c.length;return c[l]=t.ref,i.setValue(t,{property:o,itemIndex:l}),i}getValue(e,t){let n=this._values[e];if(n)return n.get(t)}scopeRefs(e,t=this._values){return this._reduceValues(t,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,Be._)`${e}${n.scopePath}`})}scopeCode(e=this._values,t,n){return this._reduceValues(e,i=>{if(i.value===void 0)throw new Error(`CodeGen: name "${i}" has no value`);return i.value.code},t,n)}_reduceValues(e,t,n={},i){let o=Be.nil;for(let s in e){let a=e[s];if(!a)continue;let c=n[s]=n[s]||new Map;a.forEach(l=>{if(c.has(l))return;c.set(l,gs.Started);let u=t(l);if(u){let p=this.opts.es5?Ve.varKinds.var:Ve.varKinds.const;o=(0,Be._)`${o}${p} ${l} = ${u};${this.opts._n}`}else if(u=i?.(l))o=(0,Be._)`${o}${u}${this.opts._n}`;else throw new su(l);c.set(l,gs.Completed)})}return o}};Ve.ValueScope=au});var H=_(B=>{"use strict";Object.defineProperty(B,"__esModule",{value:!0});B.or=B.and=B.not=B.CodeGen=B.operators=B.varKinds=B.ValueScopeName=B.ValueScope=B.Scope=B.Name=B.regexpCode=B.stringify=B.getProperty=B.nil=B.strConcat=B.str=B._=void 0;var X=zi(),vt=cu(),pr=zi();Object.defineProperty(B,"_",{enumerable:!0,get:function(){return pr._}});Object.defineProperty(B,"str",{enumerable:!0,get:function(){return pr.str}});Object.defineProperty(B,"strConcat",{enumerable:!0,get:function(){return pr.strConcat}});Object.defineProperty(B,"nil",{enumerable:!0,get:function(){return pr.nil}});Object.defineProperty(B,"getProperty",{enumerable:!0,get:function(){return pr.getProperty}});Object.defineProperty(B,"stringify",{enumerable:!0,get:function(){return pr.stringify}});Object.defineProperty(B,"regexpCode",{enumerable:!0,get:function(){return pr.regexpCode}});Object.defineProperty(B,"Name",{enumerable:!0,get:function(){return pr.Name}});var ws=cu();Object.defineProperty(B,"Scope",{enumerable:!0,get:function(){return ws.Scope}});Object.defineProperty(B,"ValueScope",{enumerable:!0,get:function(){return ws.ValueScope}});Object.defineProperty(B,"ValueScopeName",{enumerable:!0,get:function(){return ws.ValueScopeName}});Object.defineProperty(B,"varKinds",{enumerable:!0,get:function(){return ws.varKinds}});B.operators={GT:new X._Code(">"),GTE:new X._Code(">="),LT:new X._Code("<"),LTE:new X._Code("<="),EQ:new X._Code("==="),NEQ:new X._Code("!=="),NOT:new X._Code("!"),OR:new X._Code("||"),AND:new X._Code("&&"),ADD:new X._Code("+")};var Wt=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},lu=class extends Wt{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){let n=e?vt.varKinds.var:this.varKind,i=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${i};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&(this.rhs=Cn(this.rhs,e,t)),this}get names(){return this.rhs instanceof X._CodeOrName?this.rhs.names:{}}},ys=class extends Wt{constructor(e,t,n){super(),this.lhs=e,this.rhs=t,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,t){if(!(this.lhs instanceof X.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Cn(this.rhs,e,t),this}get names(){let e=this.lhs instanceof X.Name?{}:{...this.lhs.names};return bs(e,this.rhs)}},uu=class extends ys{constructor(e,t,n,i){super(e,n,i),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},pu=class extends Wt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},du=class extends Wt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},mu=class extends Wt{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},fu=class extends Wt{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=Cn(this.code,e,t),this}get names(){return this.code instanceof X._CodeOrName?this.code.names:{}}},Pi=class extends Wt{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,n)=>t+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,t=e.length;for(;t--;){let n=e[t].optimizeNodes();Array.isArray(n)?e.splice(t,1,...n):n?e[t]=n:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:n}=this,i=n.length;for(;i--;){let o=n[i];o.optimizeNames(e,t)||(HE(e,o.names),n.splice(i,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>Jr(e,t.names),{})}},Gt=class extends Pi{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},hu=class extends Pi{},Rn=class extends Gt{};Rn.kind="else";var Gr=class r extends Gt{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+="else "+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let t=this.else;if(t){let n=t.optimizeNodes();t=this.else=Array.isArray(n)?new Rn(n):n}if(t)return e===!1?t instanceof r?t:t.nodes:this.nodes.length?this:new r(dg(e),t instanceof r?[t]:t.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,t){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,t),!!(super.optimizeNames(e,t)||this.else))return this.condition=Cn(this.condition,e,t),this}get names(){let e=super.names;return bs(e,this.condition),this.else&&Jr(e,this.else.names),e}};Gr.kind="if";var Kr=class extends Gt{};Kr.kind="for";var gu=class extends Kr{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=Cn(this.iteration,e,t),this}get names(){return Jr(super.names,this.iteration.names)}},vu=class extends Kr{constructor(e,t,n,i){super(),this.varKind=e,this.name=t,this.from=n,this.to=i}render(e){let t=e.es5?vt.varKinds.var:this.varKind,{name:n,from:i,to:o}=this;return`for(${t} ${n}=${i}; ${n}<${o}; ${n}++)`+super.render(e)}get names(){let e=bs(super.names,this.from);return bs(e,this.to)}},_s=class extends Kr{constructor(e,t,n,i){super(),this.loop=e,this.varKind=t,this.name=n,this.iterable=i}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=Cn(this.iterable,e,t),this}get names(){return Jr(super.names,this.iterable.names)}},Ri=class extends Gt{constructor(e,t,n){super(),this.name=e,this.args=t,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};Ri.kind="func";var Ci=class extends Pi{render(e){return"return "+super.render(e)}};Ci.kind="return";var xu=class extends Gt{render(e){let t="try"+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(t=this.finally)===null||t===void 0||t.optimizeNodes(),this}optimizeNames(e,t){var n,i;return super.optimizeNames(e,t),(n=this.catch)===null||n===void 0||n.optimizeNames(e,t),(i=this.finally)===null||i===void 0||i.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&Jr(e,this.catch.names),this.finally&&Jr(e,this.finally.names),e}},Ii=class extends Gt{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Ii.kind="catch";var Ai=class extends Gt{render(e){return"finally"+super.render(e)}};Ai.kind="finally";var yu=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
|
|
2
|
+
`:""},this._extScope=e,this._scope=new vt.Scope({parent:e}),this._nodes=[new hu]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){let n=this._extScope.value(e,t);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,n,i){let o=this._scope.toName(t);return n!==void 0&&i&&(this._constants[o.str]=n),this._leafNode(new lu(e,o,n)),o}const(e,t,n){return this._def(vt.varKinds.const,e,t,n)}let(e,t,n){return this._def(vt.varKinds.let,e,t,n)}var(e,t,n){return this._def(vt.varKinds.var,e,t,n)}assign(e,t,n){return this._leafNode(new ys(e,t,n))}add(e,t){return this._leafNode(new uu(e,B.operators.ADD,t))}code(e){return typeof e=="function"?e():e!==X.nil&&this._leafNode(new fu(e)),this}object(...e){let t=["{"];for(let[n,i]of e)t.length>1&&t.push(","),t.push(n),(n!==i||this.opts.es5)&&(t.push(":"),(0,X.addCodeArg)(t,i));return t.push("}"),new X._Code(t)}if(e,t,n){if(this._blockNode(new Gr(e)),t&&n)this.code(t).else().code(n).endIf();else if(t)this.code(t).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new Gr(e))}else(){return this._elseNode(new Rn)}endIf(){return this._endBlockNode(Gr,Rn)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new gu(e),t)}forRange(e,t,n,i,o=this.opts.es5?vt.varKinds.var:vt.varKinds.let){let s=this._scope.toName(e);return this._for(new vu(o,s,t,n),()=>i(s))}forOf(e,t,n,i=vt.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let s=t instanceof X.Name?t:this.var("_arr",t);return this.forRange("_i",0,(0,X._)`${s}.length`,a=>{this.var(o,(0,X._)`${s}[${a}]`),n(o)})}return this._for(new _s("of",i,o,t),()=>n(o))}forIn(e,t,n,i=this.opts.es5?vt.varKinds.var:vt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,X._)`Object.keys(${t})`,n);let o=this._scope.toName(e);return this._for(new _s("in",i,o,t),()=>n(o))}endFor(){return this._endBlockNode(Kr)}label(e){return this._leafNode(new pu(e))}break(e){return this._leafNode(new du(e))}return(e){let t=new Ci;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Ci)}try(e,t,n){if(!t&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let i=new xu;if(this._blockNode(i),this.code(e),t){let o=this.name("e");this._currNode=i.catch=new Ii(o),t(o)}return n&&(this._currNode=i.finally=new Ai,this.code(n)),this._endBlockNode(Ii,Ai)}throw(e){return this._leafNode(new mu(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){let t=this._blockStarts.pop();if(t===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-t;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=t,this}func(e,t=X.nil,n,i){return this._blockNode(new Ri(e,t,n)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(Ri)}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,t){let n=this._currNode;if(n instanceof e||t&&n instanceof t)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){let t=this._currNode;if(!(t instanceof Gr))throw new Error('CodeGen: "else" without "if"');return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let t=this._nodes;t[t.length-1]=e}};B.CodeGen=yu;function Jr(r,e){for(let t in e)r[t]=(r[t]||0)+(e[t]||0);return r}function bs(r,e){return e instanceof X._CodeOrName?Jr(r,e.names):r}function Cn(r,e,t){if(r instanceof X.Name)return n(r);if(!i(r))return r;return new X._Code(r._items.reduce((o,s)=>(s instanceof X.Name&&(s=n(s)),s instanceof X._Code?o.push(...s._items):o.push(s),o),[]));function n(o){let s=t[o.str];return s===void 0||e[o.str]!==1?o:(delete e[o.str],s)}function i(o){return o instanceof X._Code&&o._items.some(s=>s instanceof X.Name&&e[s.str]===1&&t[s.str]!==void 0)}}function HE(r,e){for(let t in e)r[t]=(r[t]||0)-(e[t]||0)}function dg(r){return typeof r=="boolean"||typeof r=="number"||r===null?!r:(0,X._)`!${_u(r)}`}B.not=dg;var BE=mg(B.operators.AND);function VE(...r){return r.reduce(BE)}B.and=VE;var WE=mg(B.operators.OR);function GE(...r){return r.reduce(WE)}B.or=GE;function mg(r){return(e,t)=>e===X.nil?t:t===X.nil?e:(0,X._)`${_u(e)} ${r} ${_u(t)}`}function _u(r){return r instanceof X.Name?r:(0,X._)`(${r})`}});var Q=_(V=>{"use strict";Object.defineProperty(V,"__esModule",{value:!0});V.checkStrictMode=V.getErrorPath=V.Type=V.useFunc=V.setEvaluated=V.evaluatedPropsToName=V.mergeEvaluated=V.eachItem=V.unescapeJsonPointer=V.escapeJsonPointer=V.escapeFragment=V.unescapeFragment=V.schemaRefOrVal=V.schemaHasRulesButRef=V.schemaHasRules=V.checkUnknownRules=V.alwaysValidSchema=V.toHash=void 0;var ae=H(),KE=zi();function JE(r){let e={};for(let t of r)e[t]=!0;return e}V.toHash=JE;function XE(r,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(gg(r,e),!vg(e,r.self.RULES.all))}V.alwaysValidSchema=XE;function gg(r,e=r.schema){let{opts:t,self:n}=r;if(!t.strictSchema||typeof e=="boolean")return;let i=n.RULES.keywords;for(let o in e)i[o]||_g(r,`unknown keyword: "${o}"`)}V.checkUnknownRules=gg;function vg(r,e){if(typeof r=="boolean")return!r;for(let t in r)if(e[t])return!0;return!1}V.schemaHasRules=vg;function QE(r,e){if(typeof r=="boolean")return!r;for(let t in r)if(t!=="$ref"&&e.all[t])return!0;return!1}V.schemaHasRulesButRef=QE;function YE({topSchemaRef:r,schemaPath:e},t,n,i){if(!i){if(typeof t=="number"||typeof t=="boolean")return t;if(typeof t=="string")return(0,ae._)`${t}`}return(0,ae._)`${r}${e}${(0,ae.getProperty)(n)}`}V.schemaRefOrVal=YE;function e$(r){return xg(decodeURIComponent(r))}V.unescapeFragment=e$;function t$(r){return encodeURIComponent(wu(r))}V.escapeFragment=t$;function wu(r){return typeof r=="number"?`${r}`:r.replace(/~/g,"~0").replace(/\//g,"~1")}V.escapeJsonPointer=wu;function xg(r){return r.replace(/~1/g,"/").replace(/~0/g,"~")}V.unescapeJsonPointer=xg;function r$(r,e){if(Array.isArray(r))for(let t of r)e(t);else e(r)}V.eachItem=r$;function fg({mergeNames:r,mergeToName:e,mergeValues:t,resultToName:n}){return(i,o,s,a)=>{let c=s===void 0?o:s instanceof ae.Name?(o instanceof ae.Name?r(i,o,s):e(i,o,s),s):o instanceof ae.Name?(e(i,s,o),o):t(o,s);return a===ae.Name&&!(c instanceof ae.Name)?n(i,c):c}}V.mergeEvaluated={props:fg({mergeNames:(r,e,t)=>r.if((0,ae._)`${t} !== true && ${e} !== undefined`,()=>{r.if((0,ae._)`${e} === true`,()=>r.assign(t,!0),()=>r.assign(t,(0,ae._)`${t} || {}`).code((0,ae._)`Object.assign(${t}, ${e})`))}),mergeToName:(r,e,t)=>r.if((0,ae._)`${t} !== true`,()=>{e===!0?r.assign(t,!0):(r.assign(t,(0,ae._)`${t} || {}`),ku(r,t,e))}),mergeValues:(r,e)=>r===!0?!0:{...r,...e},resultToName:yg}),items:fg({mergeNames:(r,e,t)=>r.if((0,ae._)`${t} !== true && ${e} !== undefined`,()=>r.assign(t,(0,ae._)`${e} === true ? true : ${t} > ${e} ? ${t} : ${e}`)),mergeToName:(r,e,t)=>r.if((0,ae._)`${t} !== true`,()=>r.assign(t,e===!0?!0:(0,ae._)`${t} > ${e} ? ${t} : ${e}`)),mergeValues:(r,e)=>r===!0?!0:Math.max(r,e),resultToName:(r,e)=>r.var("items",e)})};function yg(r,e){if(e===!0)return r.var("props",!0);let t=r.var("props",(0,ae._)`{}`);return e!==void 0&&ku(r,t,e),t}V.evaluatedPropsToName=yg;function ku(r,e,t){Object.keys(t).forEach(n=>r.assign((0,ae._)`${e}${(0,ae.getProperty)(n)}`,!0))}V.setEvaluated=ku;var hg={};function n$(r,e){return r.scopeValue("func",{ref:e,code:hg[e.code]||(hg[e.code]=new KE._Code(e.code))})}V.useFunc=n$;var bu;(function(r){r[r.Num=0]="Num",r[r.Str=1]="Str"})(bu||(V.Type=bu={}));function i$(r,e,t){if(r instanceof ae.Name){let n=e===bu.Num;return t?n?(0,ae._)`"[" + ${r} + "]"`:(0,ae._)`"['" + ${r} + "']"`:n?(0,ae._)`"/" + ${r}`:(0,ae._)`"/" + ${r}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return t?(0,ae.getProperty)(r).toString():"/"+wu(r)}V.getErrorPath=i$;function _g(r,e,t=r.opts.strictSchema){if(t){if(e=`strict mode: ${e}`,t===!0)throw new Error(e);r.self.logger.warn(e)}}V.checkStrictMode=_g});var Kt=_(Su=>{"use strict";Object.defineProperty(Su,"__esModule",{value:!0});var Ie=H(),o$={data:new Ie.Name("data"),valCxt:new Ie.Name("valCxt"),instancePath:new Ie.Name("instancePath"),parentData:new Ie.Name("parentData"),parentDataProperty:new Ie.Name("parentDataProperty"),rootData:new Ie.Name("rootData"),dynamicAnchors:new Ie.Name("dynamicAnchors"),vErrors:new Ie.Name("vErrors"),errors:new Ie.Name("errors"),this:new Ie.Name("this"),self:new Ie.Name("self"),scope:new Ie.Name("scope"),json:new Ie.Name("json"),jsonPos:new Ie.Name("jsonPos"),jsonLen:new Ie.Name("jsonLen"),jsonPart:new Ie.Name("jsonPart")};Su.default=o$});var Oi=_(Ae=>{"use strict";Object.defineProperty(Ae,"__esModule",{value:!0});Ae.extendErrors=Ae.resetErrorsCount=Ae.reportExtraError=Ae.reportError=Ae.keyword$DataError=Ae.keywordError=void 0;var Y=H(),ks=Q(),Le=Kt();Ae.keywordError={message:({keyword:r})=>(0,Y.str)`must pass "${r}" keyword validation`};Ae.keyword$DataError={message:({keyword:r,schemaType:e})=>e?(0,Y.str)`"${r}" keyword must be ${e} ($data)`:(0,Y.str)`"${r}" keyword is invalid ($data)`};function s$(r,e=Ae.keywordError,t,n){let{it:i}=r,{gen:o,compositeRule:s,allErrors:a}=i,c=kg(r,e,t);n??(s||a)?bg(o,c):wg(i,(0,Y._)`[${c}]`)}Ae.reportError=s$;function a$(r,e=Ae.keywordError,t){let{it:n}=r,{gen:i,compositeRule:o,allErrors:s}=n,a=kg(r,e,t);bg(i,a),o||s||wg(n,Le.default.vErrors)}Ae.reportExtraError=a$;function c$(r,e){r.assign(Le.default.errors,e),r.if((0,Y._)`${Le.default.vErrors} !== null`,()=>r.if(e,()=>r.assign((0,Y._)`${Le.default.vErrors}.length`,e),()=>r.assign(Le.default.vErrors,null)))}Ae.resetErrorsCount=c$;function l$({gen:r,keyword:e,schemaValue:t,data:n,errsCount:i,it:o}){if(i===void 0)throw new Error("ajv implementation error");let s=r.name("err");r.forRange("i",i,Le.default.errors,a=>{r.const(s,(0,Y._)`${Le.default.vErrors}[${a}]`),r.if((0,Y._)`${s}.instancePath === undefined`,()=>r.assign((0,Y._)`${s}.instancePath`,(0,Y.strConcat)(Le.default.instancePath,o.errorPath))),r.assign((0,Y._)`${s}.schemaPath`,(0,Y.str)`${o.errSchemaPath}/${e}`),o.opts.verbose&&(r.assign((0,Y._)`${s}.schema`,t),r.assign((0,Y._)`${s}.data`,n))})}Ae.extendErrors=l$;function bg(r,e){let t=r.const("err",e);r.if((0,Y._)`${Le.default.vErrors} === null`,()=>r.assign(Le.default.vErrors,(0,Y._)`[${t}]`),(0,Y._)`${Le.default.vErrors}.push(${t})`),r.code((0,Y._)`${Le.default.errors}++`)}function wg(r,e){let{gen:t,validateName:n,schemaEnv:i}=r;i.$async?t.throw((0,Y._)`new ${r.ValidationError}(${e})`):(t.assign((0,Y._)`${n}.errors`,e),t.return(!1))}var Xr={keyword:new Y.Name("keyword"),schemaPath:new Y.Name("schemaPath"),params:new Y.Name("params"),propertyName:new Y.Name("propertyName"),message:new Y.Name("message"),schema:new Y.Name("schema"),parentSchema:new Y.Name("parentSchema")};function kg(r,e,t){let{createErrors:n}=r.it;return n===!1?(0,Y._)`{}`:u$(r,e,t)}function u$(r,e,t={}){let{gen:n,it:i}=r,o=[p$(i,t),d$(r,t)];return m$(r,e,o),n.object(...o)}function p$({errorPath:r},{instancePath:e}){let t=e?(0,Y.str)`${r}${(0,ks.getErrorPath)(e,ks.Type.Str)}`:r;return[Le.default.instancePath,(0,Y.strConcat)(Le.default.instancePath,t)]}function d$({keyword:r,it:{errSchemaPath:e}},{schemaPath:t,parentSchema:n}){let i=n?e:(0,Y.str)`${e}/${r}`;return t&&(i=(0,Y.str)`${i}${(0,ks.getErrorPath)(t,ks.Type.Str)}`),[Xr.schemaPath,i]}function m$(r,{params:e,message:t},n){let{keyword:i,data:o,schemaValue:s,it:a}=r,{opts:c,propertyName:l,topSchemaRef:u,schemaPath:p}=a;n.push([Xr.keyword,i],[Xr.params,typeof e=="function"?e(r):e||(0,Y._)`{}`]),c.messages&&n.push([Xr.message,typeof t=="function"?t(r):t]),c.verbose&&n.push([Xr.schema,s],[Xr.parentSchema,(0,Y._)`${u}${p}`],[Le.default.data,o]),l&&n.push([Xr.propertyName,l])}});var Eg=_(In=>{"use strict";Object.defineProperty(In,"__esModule",{value:!0});In.boolOrEmptySchema=In.topBoolOrEmptySchema=void 0;var f$=Oi(),h$=H(),g$=Kt(),v$={message:"boolean schema is false"};function x$(r){let{gen:e,schema:t,validateName:n}=r;t===!1?Sg(r,!1):typeof t=="object"&&t.$async===!0?e.return(g$.default.data):(e.assign((0,h$._)`${n}.errors`,null),e.return(!0))}In.topBoolOrEmptySchema=x$;function y$(r,e){let{gen:t,schema:n}=r;n===!1?(t.var(e,!1),Sg(r)):t.var(e,!0)}In.boolOrEmptySchema=y$;function Sg(r,e){let{gen:t,data:n}=r,i={gen:t,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:r};(0,f$.reportError)(i,v$,void 0,e)}});var Eu=_(An=>{"use strict";Object.defineProperty(An,"__esModule",{value:!0});An.getRules=An.isJSONType=void 0;var _$=["string","number","integer","boolean","null","object","array"],b$=new Set(_$);function w$(r){return typeof r=="string"&&b$.has(r)}An.isJSONType=w$;function k$(){let r={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...r,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},r.number,r.string,r.array,r.object],post:{rules:[]},all:{},keywords:{}}}An.getRules=k$});var $u=_(dr=>{"use strict";Object.defineProperty(dr,"__esModule",{value:!0});dr.shouldUseRule=dr.shouldUseGroup=dr.schemaHasRulesForType=void 0;function S$({schema:r,self:e},t){let n=e.RULES.types[t];return n&&n!==!0&&$g(r,n)}dr.schemaHasRulesForType=S$;function $g(r,e){return e.rules.some(t=>Tg(r,t))}dr.shouldUseGroup=$g;function Tg(r,e){var t;return r[e.keyword]!==void 0||((t=e.definition.implements)===null||t===void 0?void 0:t.some(n=>r[n]!==void 0))}dr.shouldUseRule=Tg});var Ni=_(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.reportTypeError=Oe.checkDataTypes=Oe.checkDataType=Oe.coerceAndCheckDataType=Oe.getJSONTypes=Oe.getSchemaTypes=Oe.DataType=void 0;var E$=Eu(),$$=$u(),T$=Oi(),U=H(),zg=Q(),On;(function(r){r[r.Correct=0]="Correct",r[r.Wrong=1]="Wrong"})(On||(Oe.DataType=On={}));function z$(r){let e=Pg(r.type);if(e.includes("null")){if(r.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&r.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');r.nullable===!0&&e.push("null")}return e}Oe.getSchemaTypes=z$;function Pg(r){let e=Array.isArray(r)?r:r?[r]:[];if(e.every(E$.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Oe.getJSONTypes=Pg;function P$(r,e){let{gen:t,data:n,opts:i}=r,o=R$(e,i.coerceTypes),s=e.length>0&&!(o.length===0&&e.length===1&&(0,$$.schemaHasRulesForType)(r,e[0]));if(s){let a=zu(e,n,i.strictNumbers,On.Wrong);t.if(a,()=>{o.length?C$(r,e,o):Pu(r)})}return s}Oe.coerceAndCheckDataType=P$;var Rg=new Set(["string","number","integer","boolean","null"]);function R$(r,e){return e?r.filter(t=>Rg.has(t)||e==="array"&&t==="array"):[]}function C$(r,e,t){let{gen:n,data:i,opts:o}=r,s=n.let("dataType",(0,U._)`typeof ${i}`),a=n.let("coerced",(0,U._)`undefined`);o.coerceTypes==="array"&&n.if((0,U._)`${s} == 'object' && Array.isArray(${i}) && ${i}.length == 1`,()=>n.assign(i,(0,U._)`${i}[0]`).assign(s,(0,U._)`typeof ${i}`).if(zu(e,i,o.strictNumbers),()=>n.assign(a,i))),n.if((0,U._)`${a} !== undefined`);for(let l of t)(Rg.has(l)||l==="array"&&o.coerceTypes==="array")&&c(l);n.else(),Pu(r),n.endIf(),n.if((0,U._)`${a} !== undefined`,()=>{n.assign(i,a),I$(r,a)});function c(l){switch(l){case"string":n.elseIf((0,U._)`${s} == "number" || ${s} == "boolean"`).assign(a,(0,U._)`"" + ${i}`).elseIf((0,U._)`${i} === null`).assign(a,(0,U._)`""`);return;case"number":n.elseIf((0,U._)`${s} == "boolean" || ${i} === null
|
|
3
|
+
|| (${s} == "string" && ${i} && ${i} == +${i})`).assign(a,(0,U._)`+${i}`);return;case"integer":n.elseIf((0,U._)`${s} === "boolean" || ${i} === null
|
|
4
|
+
|| (${s} === "string" && ${i} && ${i} == +${i} && !(${i} % 1))`).assign(a,(0,U._)`+${i}`);return;case"boolean":n.elseIf((0,U._)`${i} === "false" || ${i} === 0 || ${i} === null`).assign(a,!1).elseIf((0,U._)`${i} === "true" || ${i} === 1`).assign(a,!0);return;case"null":n.elseIf((0,U._)`${i} === "" || ${i} === 0 || ${i} === false`),n.assign(a,null);return;case"array":n.elseIf((0,U._)`${s} === "string" || ${s} === "number"
|
|
5
|
+
|| ${s} === "boolean" || ${i} === null`).assign(a,(0,U._)`[${i}]`)}}}function I$({gen:r,parentData:e,parentDataProperty:t},n){r.if((0,U._)`${e} !== undefined`,()=>r.assign((0,U._)`${e}[${t}]`,n))}function Tu(r,e,t,n=On.Correct){let i=n===On.Correct?U.operators.EQ:U.operators.NEQ,o;switch(r){case"null":return(0,U._)`${e} ${i} null`;case"array":o=(0,U._)`Array.isArray(${e})`;break;case"object":o=(0,U._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":o=s((0,U._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":o=s();break;default:return(0,U._)`typeof ${e} ${i} ${r}`}return n===On.Correct?o:(0,U.not)(o);function s(a=U.nil){return(0,U.and)((0,U._)`typeof ${e} == "number"`,a,t?(0,U._)`isFinite(${e})`:U.nil)}}Oe.checkDataType=Tu;function zu(r,e,t,n){if(r.length===1)return Tu(r[0],e,t,n);let i,o=(0,zg.toHash)(r);if(o.array&&o.object){let s=(0,U._)`typeof ${e} != "object"`;i=o.null?s:(0,U._)`!${e} || ${s}`,delete o.null,delete o.array,delete o.object}else i=U.nil;o.number&&delete o.integer;for(let s in o)i=(0,U.and)(i,Tu(s,e,t,n));return i}Oe.checkDataTypes=zu;var A$={message:({schema:r})=>`must be ${r}`,params:({schema:r,schemaValue:e})=>typeof r=="string"?(0,U._)`{type: ${r}}`:(0,U._)`{type: ${e}}`};function Pu(r){let e=O$(r);(0,T$.reportError)(e,A$)}Oe.reportTypeError=Pu;function O$(r){let{gen:e,data:t,schema:n}=r,i=(0,zg.schemaRefOrVal)(r,n,"type");return{gen:e,keyword:"type",data:t,schema:n.type,schemaCode:i,schemaValue:i,parentSchema:n,params:{},it:r}}});var Ig=_(Ss=>{"use strict";Object.defineProperty(Ss,"__esModule",{value:!0});Ss.assignDefaults=void 0;var Nn=H(),N$=Q();function j$(r,e){let{properties:t,items:n}=r.schema;if(e==="object"&&t)for(let i in t)Cg(r,i,t[i].default);else e==="array"&&Array.isArray(n)&&n.forEach((i,o)=>Cg(r,o,i.default))}Ss.assignDefaults=j$;function Cg(r,e,t){let{gen:n,compositeRule:i,data:o,opts:s}=r;if(t===void 0)return;let a=(0,Nn._)`${o}${(0,Nn.getProperty)(e)}`;if(i){(0,N$.checkStrictMode)(r,`default is ignored for: ${a}`);return}let c=(0,Nn._)`${a} === undefined`;s.useDefaults==="empty"&&(c=(0,Nn._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Nn._)`${a} = ${(0,Nn.stringify)(t)}`)}});var ct=_(ie=>{"use strict";Object.defineProperty(ie,"__esModule",{value:!0});ie.validateUnion=ie.validateArray=ie.usePattern=ie.callValidateCode=ie.schemaProperties=ie.allSchemaProperties=ie.noPropertyInData=ie.propertyInData=ie.isOwnProperty=ie.hasPropFunc=ie.reportMissingProp=ie.checkMissingProp=ie.checkReportMissingProp=void 0;var de=H(),Ru=Q(),mr=Kt(),M$=Q();function L$(r,e){let{gen:t,data:n,it:i}=r;t.if(Iu(t,n,e,i.opts.ownProperties),()=>{r.setParams({missingProperty:(0,de._)`${e}`},!0),r.error()})}ie.checkReportMissingProp=L$;function D$({gen:r,data:e,it:{opts:t}},n,i){return(0,de.or)(...n.map(o=>(0,de.and)(Iu(r,e,o,t.ownProperties),(0,de._)`${i} = ${o}`)))}ie.checkMissingProp=D$;function q$(r,e){r.setParams({missingProperty:e},!0),r.error()}ie.reportMissingProp=q$;function Ag(r){return r.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,de._)`Object.prototype.hasOwnProperty`})}ie.hasPropFunc=Ag;function Cu(r,e,t){return(0,de._)`${Ag(r)}.call(${e}, ${t})`}ie.isOwnProperty=Cu;function Z$(r,e,t,n){let i=(0,de._)`${e}${(0,de.getProperty)(t)} !== undefined`;return n?(0,de._)`${i} && ${Cu(r,e,t)}`:i}ie.propertyInData=Z$;function Iu(r,e,t,n){let i=(0,de._)`${e}${(0,de.getProperty)(t)} === undefined`;return n?(0,de.or)(i,(0,de.not)(Cu(r,e,t))):i}ie.noPropertyInData=Iu;function Og(r){return r?Object.keys(r).filter(e=>e!=="__proto__"):[]}ie.allSchemaProperties=Og;function U$(r,e){return Og(e).filter(t=>!(0,Ru.alwaysValidSchema)(r,e[t]))}ie.schemaProperties=U$;function F$({schemaCode:r,data:e,it:{gen:t,topSchemaRef:n,schemaPath:i,errorPath:o},it:s},a,c,l){let u=l?(0,de._)`${r}, ${e}, ${n}${i}`:e,p=[[mr.default.instancePath,(0,de.strConcat)(mr.default.instancePath,o)],[mr.default.parentData,s.parentData],[mr.default.parentDataProperty,s.parentDataProperty],[mr.default.rootData,mr.default.rootData]];s.opts.dynamicRef&&p.push([mr.default.dynamicAnchors,mr.default.dynamicAnchors]);let d=(0,de._)`${u}, ${t.object(...p)}`;return c!==de.nil?(0,de._)`${a}.call(${c}, ${d})`:(0,de._)`${a}(${d})`}ie.callValidateCode=F$;var H$=(0,de._)`new RegExp`;function B$({gen:r,it:{opts:e}},t){let n=e.unicodeRegExp?"u":"",{regExp:i}=e.code,o=i(t,n);return r.scopeValue("pattern",{key:o.toString(),ref:o,code:(0,de._)`${i.code==="new RegExp"?H$:(0,M$.useFunc)(r,i)}(${t}, ${n})`})}ie.usePattern=B$;function V$(r){let{gen:e,data:t,keyword:n,it:i}=r,o=e.name("valid");if(i.allErrors){let a=e.let("valid",!0);return s(()=>e.assign(a,!1)),a}return e.var(o,!0),s(()=>e.break()),o;function s(a){let c=e.const("len",(0,de._)`${t}.length`);e.forRange("i",0,c,l=>{r.subschema({keyword:n,dataProp:l,dataPropType:Ru.Type.Num},o),e.if((0,de.not)(o),a)})}}ie.validateArray=V$;function W$(r){let{gen:e,schema:t,keyword:n,it:i}=r;if(!Array.isArray(t))throw new Error("ajv implementation error");if(t.some(c=>(0,Ru.alwaysValidSchema)(i,c))&&!i.opts.unevaluated)return;let s=e.let("valid",!1),a=e.name("_valid");e.block(()=>t.forEach((c,l)=>{let u=r.subschema({keyword:n,schemaProp:l,compositeRule:!0},a);e.assign(s,(0,de._)`${s} || ${a}`),r.mergeValidEvaluated(u,a)||e.if((0,de.not)(s))})),r.result(s,()=>r.reset(),()=>r.error(!0))}ie.validateUnion=W$});var Mg=_(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.validateKeywordUsage=Pt.validSchemaType=Pt.funcKeywordCode=Pt.macroKeywordCode=void 0;var De=H(),Qr=Kt(),G$=ct(),K$=Oi();function J$(r,e){let{gen:t,keyword:n,schema:i,parentSchema:o,it:s}=r,a=e.macro.call(s.self,i,o,s),c=jg(t,n,a);s.opts.validateSchema!==!1&&s.self.validateSchema(a,!0);let l=t.name("valid");r.subschema({schema:a,schemaPath:De.nil,errSchemaPath:`${s.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),r.pass(l,()=>r.error(!0))}Pt.macroKeywordCode=J$;function X$(r,e){var t;let{gen:n,keyword:i,schema:o,parentSchema:s,$data:a,it:c}=r;Y$(c,e);let l=!a&&e.compile?e.compile.call(c.self,o,s,c):e.validate,u=jg(n,i,l),p=n.let("valid");r.block$data(p,d),r.ok((t=e.valid)!==null&&t!==void 0?t:p);function d(){if(e.errors===!1)h(),e.modifying&&Ng(r),v(()=>r.error());else{let b=e.async?f():m();e.modifying&&Ng(r),v(()=>Q$(r,b))}}function f(){let b=n.let("ruleErrs",null);return n.try(()=>h((0,De._)`await `),w=>n.assign(p,!1).if((0,De._)`${w} instanceof ${c.ValidationError}`,()=>n.assign(b,(0,De._)`${w}.errors`),()=>n.throw(w))),b}function m(){let b=(0,De._)`${u}.errors`;return n.assign(b,null),h(De.nil),b}function h(b=e.async?(0,De._)`await `:De.nil){let w=c.opts.passContext?Qr.default.this:Qr.default.self,E=!("compile"in e&&!a||e.schema===!1);n.assign(p,(0,De._)`${b}${(0,G$.callValidateCode)(r,u,w,E)}`,e.modifying)}function v(b){var w;n.if((0,De.not)((w=e.valid)!==null&&w!==void 0?w:p),b)}}Pt.funcKeywordCode=X$;function Ng(r){let{gen:e,data:t,it:n}=r;e.if(n.parentData,()=>e.assign(t,(0,De._)`${n.parentData}[${n.parentDataProperty}]`))}function Q$(r,e){let{gen:t}=r;t.if((0,De._)`Array.isArray(${e})`,()=>{t.assign(Qr.default.vErrors,(0,De._)`${Qr.default.vErrors} === null ? ${e} : ${Qr.default.vErrors}.concat(${e})`).assign(Qr.default.errors,(0,De._)`${Qr.default.vErrors}.length`),(0,K$.extendErrors)(r)},()=>r.error())}function Y$({schemaEnv:r},e){if(e.async&&!r.$async)throw new Error("async keyword in sync schema")}function jg(r,e,t){if(t===void 0)throw new Error(`keyword "${e}" failed to compile`);return r.scopeValue("keyword",typeof t=="function"?{ref:t}:{ref:t,code:(0,De.stringify)(t)})}function eT(r,e,t=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(r):n==="object"?r&&typeof r=="object"&&!Array.isArray(r):typeof r==n||t&&typeof r>"u")}Pt.validSchemaType=eT;function tT({schema:r,opts:e,self:t,errSchemaPath:n},i,o){if(Array.isArray(i.keyword)?!i.keyword.includes(o):i.keyword!==o)throw new Error("ajv implementation error");let s=i.dependencies;if(s?.some(a=>!Object.prototype.hasOwnProperty.call(r,a)))throw new Error(`parent schema must have dependencies of ${o}: ${s.join(",")}`);if(i.validateSchema&&!i.validateSchema(r[o])){let c=`keyword "${o}" value is invalid at path "${n}": `+t.errorsText(i.validateSchema.errors);if(e.validateSchema==="log")t.logger.error(c);else throw new Error(c)}}Pt.validateKeywordUsage=tT});var Dg=_(fr=>{"use strict";Object.defineProperty(fr,"__esModule",{value:!0});fr.extendSubschemaMode=fr.extendSubschemaData=fr.getSubschema=void 0;var Rt=H(),Lg=Q();function rT(r,{keyword:e,schemaProp:t,schema:n,schemaPath:i,errSchemaPath:o,topSchemaRef:s}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=r.schema[e];return t===void 0?{schema:a,schemaPath:(0,Rt._)`${r.schemaPath}${(0,Rt.getProperty)(e)}`,errSchemaPath:`${r.errSchemaPath}/${e}`}:{schema:a[t],schemaPath:(0,Rt._)`${r.schemaPath}${(0,Rt.getProperty)(e)}${(0,Rt.getProperty)(t)}`,errSchemaPath:`${r.errSchemaPath}/${e}/${(0,Lg.escapeFragment)(t)}`}}if(n!==void 0){if(i===void 0||o===void 0||s===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:i,topSchemaRef:s,errSchemaPath:o}}throw new Error('either "keyword" or "schema" must be passed')}fr.getSubschema=rT;function nT(r,e,{dataProp:t,dataPropType:n,data:i,dataTypes:o,propertyName:s}){if(i!==void 0&&t!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(t!==void 0){let{errorPath:l,dataPathArr:u,opts:p}=e,d=a.let("data",(0,Rt._)`${e.data}${(0,Rt.getProperty)(t)}`,!0);c(d),r.errorPath=(0,Rt.str)`${l}${(0,Lg.getErrorPath)(t,n,p.jsPropertySyntax)}`,r.parentDataProperty=(0,Rt._)`${t}`,r.dataPathArr=[...u,r.parentDataProperty]}if(i!==void 0){let l=i instanceof Rt.Name?i:a.let("data",i,!0);c(l),s!==void 0&&(r.propertyName=s)}o&&(r.dataTypes=o);function c(l){r.data=l,r.dataLevel=e.dataLevel+1,r.dataTypes=[],e.definedProperties=new Set,r.parentData=e.data,r.dataNames=[...e.dataNames,l]}}fr.extendSubschemaData=nT;function iT(r,{jtdDiscriminator:e,jtdMetadata:t,compositeRule:n,createErrors:i,allErrors:o}){n!==void 0&&(r.compositeRule=n),i!==void 0&&(r.createErrors=i),o!==void 0&&(r.allErrors=o),r.jtdDiscriminator=e,r.jtdMetadata=t}fr.extendSubschemaMode=iT});var Au=_((KL,qg)=>{"use strict";qg.exports=function r(e,t){if(e===t)return!0;if(e&&t&&typeof e=="object"&&typeof t=="object"){if(e.constructor!==t.constructor)return!1;var n,i,o;if(Array.isArray(e)){if(n=e.length,n!=t.length)return!1;for(i=n;i--!==0;)if(!r(e[i],t[i]))return!1;return!0}if(e.constructor===RegExp)return e.source===t.source&&e.flags===t.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===t.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===t.toString();if(o=Object.keys(e),n=o.length,n!==Object.keys(t).length)return!1;for(i=n;i--!==0;)if(!Object.prototype.hasOwnProperty.call(t,o[i]))return!1;for(i=n;i--!==0;){var s=o[i];if(!r(e[s],t[s]))return!1}return!0}return e!==e&&t!==t}});var Ug=_((JL,Zg)=>{"use strict";var hr=Zg.exports=function(r,e,t){typeof e=="function"&&(t=e,e={}),t=e.cb||t;var n=typeof t=="function"?t:t.pre||function(){},i=t.post||function(){};Es(e,n,i,r,"",r)};hr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};hr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};hr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};hr.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 Es(r,e,t,n,i,o,s,a,c,l){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,i,o,s,a,c,l);for(var u in n){var p=n[u];if(Array.isArray(p)){if(u in hr.arrayKeywords)for(var d=0;d<p.length;d++)Es(r,e,t,p[d],i+"/"+u+"/"+d,o,i,u,n,d)}else if(u in hr.propsKeywords){if(p&&typeof p=="object")for(var f in p)Es(r,e,t,p[f],i+"/"+u+"/"+oT(f),o,i,u,n,f)}else(u in hr.keywords||r.allKeys&&!(u in hr.skipKeywords))&&Es(r,e,t,p,i+"/"+u,o,i,u,n)}t(n,i,o,s,a,c,l)}}function oT(r){return r.replace(/~/g,"~0").replace(/\//g,"~1")}});var ji=_(We=>{"use strict";Object.defineProperty(We,"__esModule",{value:!0});We.getSchemaRefs=We.resolveUrl=We.normalizeId=We._getFullPath=We.getFullPath=We.inlineRef=void 0;var sT=Q(),aT=Au(),cT=Ug(),lT=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function uT(r,e=!0){return typeof r=="boolean"?!0:e===!0?!Ou(r):e?Fg(r)<=e:!1}We.inlineRef=uT;var pT=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Ou(r){for(let e in r){if(pT.has(e))return!0;let t=r[e];if(Array.isArray(t)&&t.some(Ou)||typeof t=="object"&&Ou(t))return!0}return!1}function Fg(r){let e=0;for(let t in r){if(t==="$ref")return 1/0;if(e++,!lT.has(t)&&(typeof r[t]=="object"&&(0,sT.eachItem)(r[t],n=>e+=Fg(n)),e===1/0))return 1/0}return e}function Hg(r,e="",t){t!==!1&&(e=jn(e));let n=r.parse(e);return Bg(r,n)}We.getFullPath=Hg;function Bg(r,e){return r.serialize(e).split("#")[0]+"#"}We._getFullPath=Bg;var dT=/#\/?$/;function jn(r){return r?r.replace(dT,""):""}We.normalizeId=jn;function mT(r,e,t){return t=jn(t),r.resolve(e,t)}We.resolveUrl=mT;var fT=/^[a-z_][-a-z0-9._]*$/i;function hT(r,e){if(typeof r=="boolean")return{};let{schemaId:t,uriResolver:n}=this.opts,i=jn(r[t]||e),o={"":i},s=Hg(n,i,!1),a={},c=new Set;return cT(r,{allKeys:!0},(p,d,f,m)=>{if(m===void 0)return;let h=s+d,v=o[m];typeof p[t]=="string"&&(v=b.call(this,p[t])),w.call(this,p.$anchor),w.call(this,p.$dynamicAnchor),o[d]=v;function b(E){let P=this.opts.uriResolver.resolve;if(E=jn(v?P(v,E):E),c.has(E))throw u(E);c.add(E);let j=this.refs[E];return typeof j=="string"&&(j=this.refs[j]),typeof j=="object"?l(p,j.schema,E):E!==jn(h)&&(E[0]==="#"?(l(p,a[E],E),a[E]=p):this.refs[E]=h),E}function w(E){if(typeof E=="string"){if(!fT.test(E))throw new Error(`invalid anchor "${E}"`);b.call(this,`#${E}`)}}}),a;function l(p,d,f){if(d!==void 0&&!aT(p,d))throw u(f)}function u(p){return new Error(`reference "${p}" resolves to more than one schema`)}}We.getSchemaRefs=hT});var Di=_(gr=>{"use strict";Object.defineProperty(gr,"__esModule",{value:!0});gr.getData=gr.KeywordCxt=gr.validateFunctionCode=void 0;var Jg=Eg(),Vg=Ni(),ju=$u(),$s=Ni(),gT=Ig(),Li=Mg(),Nu=Dg(),A=H(),q=Kt(),vT=ji(),Jt=Q(),Mi=Oi();function xT(r){if(Yg(r)&&(ev(r),Qg(r))){bT(r);return}Xg(r,()=>(0,Jg.topBoolOrEmptySchema)(r))}gr.validateFunctionCode=xT;function Xg({gen:r,validateName:e,schema:t,schemaEnv:n,opts:i},o){i.code.es5?r.func(e,(0,A._)`${q.default.data}, ${q.default.valCxt}`,n.$async,()=>{r.code((0,A._)`"use strict"; ${Wg(t,i)}`),_T(r,i),r.code(o)}):r.func(e,(0,A._)`${q.default.data}, ${yT(i)}`,n.$async,()=>r.code(Wg(t,i)).code(o))}function yT(r){return(0,A._)`{${q.default.instancePath}="", ${q.default.parentData}, ${q.default.parentDataProperty}, ${q.default.rootData}=${q.default.data}${r.dynamicRef?(0,A._)`, ${q.default.dynamicAnchors}={}`:A.nil}}={}`}function _T(r,e){r.if(q.default.valCxt,()=>{r.var(q.default.instancePath,(0,A._)`${q.default.valCxt}.${q.default.instancePath}`),r.var(q.default.parentData,(0,A._)`${q.default.valCxt}.${q.default.parentData}`),r.var(q.default.parentDataProperty,(0,A._)`${q.default.valCxt}.${q.default.parentDataProperty}`),r.var(q.default.rootData,(0,A._)`${q.default.valCxt}.${q.default.rootData}`),e.dynamicRef&&r.var(q.default.dynamicAnchors,(0,A._)`${q.default.valCxt}.${q.default.dynamicAnchors}`)},()=>{r.var(q.default.instancePath,(0,A._)`""`),r.var(q.default.parentData,(0,A._)`undefined`),r.var(q.default.parentDataProperty,(0,A._)`undefined`),r.var(q.default.rootData,q.default.data),e.dynamicRef&&r.var(q.default.dynamicAnchors,(0,A._)`{}`)})}function bT(r){let{schema:e,opts:t,gen:n}=r;Xg(r,()=>{t.$comment&&e.$comment&&rv(r),$T(r),n.let(q.default.vErrors,null),n.let(q.default.errors,0),t.unevaluated&&wT(r),tv(r),PT(r)})}function wT(r){let{gen:e,validateName:t}=r;r.evaluated=e.const("evaluated",(0,A._)`${t}.evaluated`),e.if((0,A._)`${r.evaluated}.dynamicProps`,()=>e.assign((0,A._)`${r.evaluated}.props`,(0,A._)`undefined`)),e.if((0,A._)`${r.evaluated}.dynamicItems`,()=>e.assign((0,A._)`${r.evaluated}.items`,(0,A._)`undefined`))}function Wg(r,e){let t=typeof r=="object"&&r[e.schemaId];return t&&(e.code.source||e.code.process)?(0,A._)`/*# sourceURL=${t} */`:A.nil}function kT(r,e){if(Yg(r)&&(ev(r),Qg(r))){ST(r,e);return}(0,Jg.boolOrEmptySchema)(r,e)}function Qg({schema:r,self:e}){if(typeof r=="boolean")return!r;for(let t in r)if(e.RULES.all[t])return!0;return!1}function Yg(r){return typeof r.schema!="boolean"}function ST(r,e){let{schema:t,gen:n,opts:i}=r;i.$comment&&t.$comment&&rv(r),TT(r),zT(r);let o=n.const("_errs",q.default.errors);tv(r,o),n.var(e,(0,A._)`${o} === ${q.default.errors}`)}function ev(r){(0,Jt.checkUnknownRules)(r),ET(r)}function tv(r,e){if(r.opts.jtd)return Gg(r,[],!1,e);let t=(0,Vg.getSchemaTypes)(r.schema),n=(0,Vg.coerceAndCheckDataType)(r,t);Gg(r,t,!n,e)}function ET(r){let{schema:e,errSchemaPath:t,opts:n,self:i}=r;e.$ref&&n.ignoreKeywordsWithRef&&(0,Jt.schemaHasRulesButRef)(e,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${t}"`)}function $T(r){let{schema:e,opts:t}=r;e.default!==void 0&&t.useDefaults&&t.strictSchema&&(0,Jt.checkStrictMode)(r,"default is ignored in the schema root")}function TT(r){let e=r.schema[r.opts.schemaId];e&&(r.baseId=(0,vT.resolveUrl)(r.opts.uriResolver,r.baseId,e))}function zT(r){if(r.schema.$async&&!r.schemaEnv.$async)throw new Error("async schema in sync schema")}function rv({gen:r,schemaEnv:e,schema:t,errSchemaPath:n,opts:i}){let o=t.$comment;if(i.$comment===!0)r.code((0,A._)`${q.default.self}.logger.log(${o})`);else if(typeof i.$comment=="function"){let s=(0,A.str)`${n}/$comment`,a=r.scopeValue("root",{ref:e.root});r.code((0,A._)`${q.default.self}.opts.$comment(${o}, ${s}, ${a}.schema)`)}}function PT(r){let{gen:e,schemaEnv:t,validateName:n,ValidationError:i,opts:o}=r;t.$async?e.if((0,A._)`${q.default.errors} === 0`,()=>e.return(q.default.data),()=>e.throw((0,A._)`new ${i}(${q.default.vErrors})`)):(e.assign((0,A._)`${n}.errors`,q.default.vErrors),o.unevaluated&&RT(r),e.return((0,A._)`${q.default.errors} === 0`))}function RT({gen:r,evaluated:e,props:t,items:n}){t instanceof A.Name&&r.assign((0,A._)`${e}.props`,t),n instanceof A.Name&&r.assign((0,A._)`${e}.items`,n)}function Gg(r,e,t,n){let{gen:i,schema:o,data:s,allErrors:a,opts:c,self:l}=r,{RULES:u}=l;if(o.$ref&&(c.ignoreKeywordsWithRef||!(0,Jt.schemaHasRulesButRef)(o,u))){i.block(()=>iv(r,"$ref",u.all.$ref.definition));return}c.jtd||CT(r,e),i.block(()=>{for(let d of u.rules)p(d);p(u.post)});function p(d){(0,ju.shouldUseGroup)(o,d)&&(d.type?(i.if((0,$s.checkDataType)(d.type,s,c.strictNumbers)),Kg(r,d),e.length===1&&e[0]===d.type&&t&&(i.else(),(0,$s.reportTypeError)(r)),i.endIf()):Kg(r,d),a||i.if((0,A._)`${q.default.errors} === ${n||0}`))}}function Kg(r,e){let{gen:t,schema:n,opts:{useDefaults:i}}=r;i&&(0,gT.assignDefaults)(r,e.type),t.block(()=>{for(let o of e.rules)(0,ju.shouldUseRule)(n,o)&&iv(r,o.keyword,o.definition,e.type)})}function CT(r,e){r.schemaEnv.meta||!r.opts.strictTypes||(IT(r,e),r.opts.allowUnionTypes||AT(r,e),OT(r,r.dataTypes))}function IT(r,e){if(e.length){if(!r.dataTypes.length){r.dataTypes=e;return}e.forEach(t=>{nv(r.dataTypes,t)||Mu(r,`type "${t}" not allowed by context "${r.dataTypes.join(",")}"`)}),jT(r,e)}}function AT(r,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Mu(r,"use allowUnionTypes to allow union type keyword")}function OT(r,e){let t=r.self.RULES.all;for(let n in t){let i=t[n];if(typeof i=="object"&&(0,ju.shouldUseRule)(r.schema,i)){let{type:o}=i.definition;o.length&&!o.some(s=>NT(e,s))&&Mu(r,`missing type "${o.join(",")}" for keyword "${n}"`)}}}function NT(r,e){return r.includes(e)||e==="number"&&r.includes("integer")}function nv(r,e){return r.includes(e)||e==="integer"&&r.includes("number")}function jT(r,e){let t=[];for(let n of r.dataTypes)nv(e,n)?t.push(n):e.includes("integer")&&n==="number"&&t.push("integer");r.dataTypes=t}function Mu(r,e){let t=r.schemaEnv.baseId+r.errSchemaPath;e+=` at "${t}" (strictTypes)`,(0,Jt.checkStrictMode)(r,e,r.opts.strictTypes)}var Ts=class{constructor(e,t,n){if((0,Li.validateKeywordUsage)(e,t,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Jt.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const("vSchema",ov(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Li.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(t.schemaType)}`);("code"in t?t.trackErrors:t.errors!==!1)&&(this.errsCount=e.gen.const("_errs",q.default.errors))}result(e,t,n){this.failResult((0,A.not)(e),t,n)}failResult(e,t,n){this.gen.if(e),n?n():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,A.not)(e),void 0,t)}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:t}=this;this.fail((0,A._)`${t} !== undefined && (${(0,A.or)(this.invalid$data(),e)})`)}error(e,t,n){if(t){this.setParams(t),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,t){(e?Mi.reportExtraError:Mi.reportError)(this,this.def.error,t)}$dataError(){(0,Mi.reportError)(this,this.def.$dataError||Mi.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Mi.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,n=A.nil){this.gen.block(()=>{this.check$data(e,n),t()})}check$data(e=A.nil,t=A.nil){if(!this.$data)return;let{gen:n,schemaCode:i,schemaType:o,def:s}=this;n.if((0,A.or)((0,A._)`${i} === undefined`,t)),e!==A.nil&&n.assign(e,!0),(o.length||s.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==A.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:n,def:i,it:o}=this;return(0,A.or)(s(),a());function s(){if(n.length){if(!(t instanceof A.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,A._)`${(0,$s.checkDataTypes)(c,t,o.opts.strictNumbers,$s.DataType.Wrong)}`}return A.nil}function a(){if(i.validateSchema){let c=e.scopeValue("validate$data",{ref:i.validateSchema});return(0,A._)`!${c}(${t})`}return A.nil}}subschema(e,t){let n=(0,Nu.getSubschema)(this.it,e);(0,Nu.extendSubschemaData)(n,this.it,e),(0,Nu.extendSubschemaMode)(n,e);let i={...this.it,...n,items:void 0,props:void 0};return kT(i,t),i}mergeEvaluated(e,t){let{it:n,gen:i}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Jt.mergeEvaluated.props(i,e.props,n.props,t)),n.items!==!0&&e.items!==void 0&&(n.items=Jt.mergeEvaluated.items(i,e.items,n.items,t)))}mergeValidEvaluated(e,t){let{it:n,gen:i}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return i.if(t,()=>this.mergeEvaluated(e,A.Name)),!0}};gr.KeywordCxt=Ts;function iv(r,e,t,n){let i=new Ts(r,t,e);"code"in t?t.code(i,n):i.$data&&t.validate?(0,Li.funcKeywordCode)(i,t):"macro"in t?(0,Li.macroKeywordCode)(i,t):(t.compile||t.validate)&&(0,Li.funcKeywordCode)(i,t)}var MT=/^\/(?:[^~]|~0|~1)*$/,LT=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function ov(r,{dataLevel:e,dataNames:t,dataPathArr:n}){let i,o;if(r==="")return q.default.rootData;if(r[0]==="/"){if(!MT.test(r))throw new Error(`Invalid JSON-pointer: ${r}`);i=r,o=q.default.rootData}else{let l=LT.exec(r);if(!l)throw new Error(`Invalid JSON-pointer: ${r}`);let u=+l[1];if(i=l[2],i==="#"){if(u>=e)throw new Error(c("property/index",u));return n[e-u]}if(u>e)throw new Error(c("data",u));if(o=t[e-u],!i)return o}let s=o,a=i.split("/");for(let l of a)l&&(o=(0,A._)`${o}${(0,A.getProperty)((0,Jt.unescapeJsonPointer)(l))}`,s=(0,A._)`${s} && ${o}`);return s;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${e}`}}gr.getData=ov});var zs=_(Du=>{"use strict";Object.defineProperty(Du,"__esModule",{value:!0});var Lu=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Du.default=Lu});var qi=_(Uu=>{"use strict";Object.defineProperty(Uu,"__esModule",{value:!0});var qu=ji(),Zu=class extends Error{constructor(e,t,n,i){super(i||`can't resolve reference ${n} from id ${t}`),this.missingRef=(0,qu.resolveUrl)(e,t,n),this.missingSchema=(0,qu.normalizeId)((0,qu.getFullPath)(e,this.missingRef))}};Uu.default=Zu});var Rs=_(lt=>{"use strict";Object.defineProperty(lt,"__esModule",{value:!0});lt.resolveSchema=lt.getCompilingSchema=lt.resolveRef=lt.compileSchema=lt.SchemaEnv=void 0;var xt=H(),DT=zs(),Yr=Kt(),yt=ji(),sv=Q(),qT=Di(),Mn=class{constructor(e){var t;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(t=e.baseId)!==null&&t!==void 0?t:(0,yt.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};lt.SchemaEnv=Mn;function Hu(r){let e=av.call(this,r);if(e)return e;let t=(0,yt.getFullPath)(this.opts.uriResolver,r.root.baseId),{es5:n,lines:i}=this.opts.code,{ownProperties:o}=this.opts,s=new xt.CodeGen(this.scope,{es5:n,lines:i,ownProperties:o}),a;r.$async&&(a=s.scopeValue("Error",{ref:DT.default,code:(0,xt._)`require("ajv/dist/runtime/validation_error").default`}));let c=s.scopeName("validate");r.validateName=c;let l={gen:s,allErrors:this.opts.allErrors,data:Yr.default.data,parentData:Yr.default.parentData,parentDataProperty:Yr.default.parentDataProperty,dataNames:[Yr.default.data],dataPathArr:[xt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===!0?{ref:r.schema,code:(0,xt.stringify)(r.schema)}:{ref:r.schema}),validateName:c,ValidationError:a,schema:r.schema,schemaEnv:r,rootId:t,baseId:r.baseId||t,schemaPath:xt.nil,errSchemaPath:r.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,xt._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(r),(0,qT.validateFunctionCode)(l),s.optimize(this.opts.code.optimize);let p=s.toString();u=`${s.scopeRefs(Yr.default.scope)}return ${p}`,this.opts.code.process&&(u=this.opts.code.process(u,r));let f=new Function(`${Yr.default.self}`,`${Yr.default.scope}`,u)(this,this.scope.get());if(this.scope.value(c,{ref:f}),f.errors=null,f.schema=r.schema,f.schemaEnv=r,r.$async&&(f.$async=!0),this.opts.code.source===!0&&(f.source={validateName:c,validateCode:p,scopeValues:s._values}),this.opts.unevaluated){let{props:m,items:h}=l;f.evaluated={props:m instanceof xt.Name?void 0:m,items:h instanceof xt.Name?void 0:h,dynamicProps:m instanceof xt.Name,dynamicItems:h instanceof xt.Name},f.source&&(f.source.evaluated=(0,xt.stringify)(f.evaluated))}return r.validate=f,r}catch(p){throw delete r.validate,delete r.validateName,u&&this.logger.error("Error compiling schema, function code:",u),p}finally{this._compilations.delete(r)}}lt.compileSchema=Hu;function ZT(r,e,t){var n;t=(0,yt.resolveUrl)(this.opts.uriResolver,e,t);let i=r.refs[t];if(i)return i;let o=HT.call(this,r,t);if(o===void 0){let s=(n=r.localRefs)===null||n===void 0?void 0:n[t],{schemaId:a}=this.opts;s&&(o=new Mn({schema:s,schemaId:a,root:r,baseId:e}))}if(o!==void 0)return r.refs[t]=UT.call(this,o)}lt.resolveRef=ZT;function UT(r){return(0,yt.inlineRef)(r.schema,this.opts.inlineRefs)?r.schema:r.validate?r:Hu.call(this,r)}function av(r){for(let e of this._compilations)if(FT(e,r))return e}lt.getCompilingSchema=av;function FT(r,e){return r.schema===e.schema&&r.root===e.root&&r.baseId===e.baseId}function HT(r,e){let t;for(;typeof(t=this.refs[e])=="string";)e=t;return t||this.schemas[e]||Ps.call(this,r,e)}function Ps(r,e){let t=this.opts.uriResolver.parse(e),n=(0,yt._getFullPath)(this.opts.uriResolver,t),i=(0,yt.getFullPath)(this.opts.uriResolver,r.baseId,void 0);if(Object.keys(r.schema).length>0&&n===i)return Fu.call(this,t,r);let o=(0,yt.normalizeId)(n),s=this.refs[o]||this.schemas[o];if(typeof s=="string"){let a=Ps.call(this,r,s);return typeof a?.schema!="object"?void 0:Fu.call(this,t,a)}if(typeof s?.schema=="object"){if(s.validate||Hu.call(this,s),o===(0,yt.normalizeId)(e)){let{schema:a}=s,{schemaId:c}=this.opts,l=a[c];return l&&(i=(0,yt.resolveUrl)(this.opts.uriResolver,i,l)),new Mn({schema:a,schemaId:c,root:r,baseId:i})}return Fu.call(this,t,s)}}lt.resolveSchema=Ps;var BT=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Fu(r,{baseId:e,schema:t,root:n}){var i;if(((i=r.fragment)===null||i===void 0?void 0:i[0])!=="/")return;for(let a of r.fragment.slice(1).split("/")){if(typeof t=="boolean")return;let c=t[(0,sv.unescapeFragment)(a)];if(c===void 0)return;t=c;let l=typeof t=="object"&&t[this.opts.schemaId];!BT.has(a)&&l&&(e=(0,yt.resolveUrl)(this.opts.uriResolver,e,l))}let o;if(typeof t!="boolean"&&t.$ref&&!(0,sv.schemaHasRulesButRef)(t,this.RULES)){let a=(0,yt.resolveUrl)(this.opts.uriResolver,e,t.$ref);o=Ps.call(this,n,a)}let{schemaId:s}=this.opts;if(o=o||new Mn({schema:t,schemaId:s,root:n,baseId:e}),o.schema!==o.root.schema)return o}});var cv=_((rD,VT)=>{VT.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 Vu=_((nD,dv)=>{"use strict";var WT=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),uv=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function Bu(r){let e="",t=0,n=0;for(n=0;n<r.length;n++)if(t=r[n].charCodeAt(0),t!==48){if(!(t>=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102))return"";e+=r[n];break}for(n+=1;n<r.length;n++){if(t=r[n].charCodeAt(0),!(t>=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102))return"";e+=r[n]}return e}var GT=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function lv(r){return r.length=0,!0}function KT(r,e,t){if(r.length){let n=Bu(r);if(n!=="")e.push(n);else return t.error=!0,!1;r.length=0}return!0}function JT(r){let e=0,t={error:!1,address:"",zone:""},n=[],i=[],o=!1,s=!1,a=KT;for(let c=0;c<r.length;c++){let l=r[c];if(!(l==="["||l==="]"))if(l===":"){if(o===!0&&(s=!0),!a(i,n,t))break;if(++e>7){t.error=!0;break}c>0&&r[c-1]===":"&&(o=!0),n.push(":");continue}else if(l==="%"){if(!a(i,n,t))break;a=lv}else{i.push(l);continue}}return i.length&&(a===lv?t.zone=i.join(""):s?n.push(i.join("")):n.push(Bu(i))),t.address=n.join(""),t}function pv(r){if(XT(r,":")<2)return{host:r,isIPV6:!1};let e=JT(r);if(e.error)return{host:r,isIPV6:!1};{let t=e.address,n=e.address;return e.zone&&(t+="%"+e.zone,n+="%25"+e.zone),{host:t,isIPV6:!0,escapedHost:n}}}function XT(r,e){let t=0;for(let n=0;n<r.length;n++)r[n]===e&&t++;return t}function QT(r){let e=r,t=[],n=-1,i=0;for(;i=e.length;){if(i===1){if(e===".")break;if(e==="/"){t.push("/");break}else{t.push(e);break}}else if(i===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){t.push("/");break}}else if(i===3&&e==="/.."){t.length!==0&&t.pop(),t.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),t.length!==0&&t.pop();continue}}if((n=e.indexOf("/",1))===-1){t.push(e);break}else t.push(e.slice(0,n)),e=e.slice(n)}return t.join("")}function YT(r,e){let t=e!==!0?escape:unescape;return r.scheme!==void 0&&(r.scheme=t(r.scheme)),r.userinfo!==void 0&&(r.userinfo=t(r.userinfo)),r.host!==void 0&&(r.host=t(r.host)),r.path!==void 0&&(r.path=t(r.path)),r.query!==void 0&&(r.query=t(r.query)),r.fragment!==void 0&&(r.fragment=t(r.fragment)),r}function ez(r){let e=[];if(r.userinfo!==void 0&&(e.push(r.userinfo),e.push("@")),r.host!==void 0){let t=unescape(r.host);if(!uv(t)){let n=pv(t);n.isIPV6===!0?t=`[${n.escapedHost}]`:t=r.host}e.push(t)}return(typeof r.port=="number"||typeof r.port=="string")&&(e.push(":"),e.push(String(r.port))),e.length?e.join(""):void 0}dv.exports={nonSimpleDomain:GT,recomposeAuthority:ez,normalizeComponentEncoding:YT,removeDotSegments:QT,isIPv4:uv,isUUID:WT,normalizeIPv6:pv,stringArrayToHexStripped:Bu}});var vv=_((iD,gv)=>{"use strict";var{isUUID:tz}=Vu(),rz=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,nz=["http","https","ws","wss","urn","urn:uuid"];function iz(r){return nz.indexOf(r)!==-1}function Wu(r){return r.secure===!0?!0:r.secure===!1?!1:r.scheme?r.scheme.length===3&&(r.scheme[0]==="w"||r.scheme[0]==="W")&&(r.scheme[1]==="s"||r.scheme[1]==="S")&&(r.scheme[2]==="s"||r.scheme[2]==="S"):!1}function mv(r){return r.host||(r.error=r.error||"HTTP URIs must have a host."),r}function fv(r){let e=String(r.scheme).toLowerCase()==="https";return(r.port===(e?443:80)||r.port==="")&&(r.port=void 0),r.path||(r.path="/"),r}function oz(r){return r.secure=Wu(r),r.resourceName=(r.path||"/")+(r.query?"?"+r.query:""),r.path=void 0,r.query=void 0,r}function sz(r){if((r.port===(Wu(r)?443:80)||r.port==="")&&(r.port=void 0),typeof r.secure=="boolean"&&(r.scheme=r.secure?"wss":"ws",r.secure=void 0),r.resourceName){let[e,t]=r.resourceName.split("?");r.path=e&&e!=="/"?e:void 0,r.query=t,r.resourceName=void 0}return r.fragment=void 0,r}function az(r,e){if(!r.path)return r.error="URN can not be parsed",r;let t=r.path.match(rz);if(t){let n=e.scheme||r.scheme||"urn";r.nid=t[1].toLowerCase(),r.nss=t[2];let i=`${n}:${e.nid||r.nid}`,o=Gu(i);r.path=void 0,o&&(r=o.parse(r,e))}else r.error=r.error||"URN can not be parsed.";return r}function cz(r,e){if(r.nid===void 0)throw new Error("URN without nid cannot be serialized");let t=e.scheme||r.scheme||"urn",n=r.nid.toLowerCase(),i=`${t}:${e.nid||n}`,o=Gu(i);o&&(r=o.serialize(r,e));let s=r,a=r.nss;return s.path=`${n||e.nid}:${a}`,e.skipEscape=!0,s}function lz(r,e){let t=r;return t.uuid=t.nss,t.nss=void 0,!e.tolerant&&(!t.uuid||!tz(t.uuid))&&(t.error=t.error||"UUID is not valid."),t}function uz(r){let e=r;return e.nss=(r.uuid||"").toLowerCase(),e}var hv={scheme:"http",domainHost:!0,parse:mv,serialize:fv},pz={scheme:"https",domainHost:hv.domainHost,parse:mv,serialize:fv},Cs={scheme:"ws",domainHost:!0,parse:oz,serialize:sz},dz={scheme:"wss",domainHost:Cs.domainHost,parse:Cs.parse,serialize:Cs.serialize},mz={scheme:"urn",parse:az,serialize:cz,skipNormalize:!0},fz={scheme:"urn:uuid",parse:lz,serialize:uz,skipNormalize:!0},Is={http:hv,https:pz,ws:Cs,wss:dz,urn:mz,"urn:uuid":fz};Object.setPrototypeOf(Is,null);function Gu(r){return r&&(Is[r]||Is[r.toLowerCase()])||void 0}gv.exports={wsIsSecure:Wu,SCHEMES:Is,isValidSchemeName:iz,getSchemeHandler:Gu}});var _v=_((oD,Os)=>{"use strict";var{normalizeIPv6:hz,removeDotSegments:Zi,recomposeAuthority:gz,normalizeComponentEncoding:As,isIPv4:vz,nonSimpleDomain:xz}=Vu(),{SCHEMES:yz,getSchemeHandler:xv}=vv();function _z(r,e){return typeof r=="string"?r=Ct(Xt(r,e),e):typeof r=="object"&&(r=Xt(Ct(r,e),e)),r}function bz(r,e,t){let n=t?Object.assign({scheme:"null"},t):{scheme:"null"},i=yv(Xt(r,n),Xt(e,n),n,!0);return n.skipEscape=!0,Ct(i,n)}function yv(r,e,t,n){let i={};return n||(r=Xt(Ct(r,t),t),e=Xt(Ct(e,t),t)),t=t||{},!t.tolerant&&e.scheme?(i.scheme=e.scheme,i.userinfo=e.userinfo,i.host=e.host,i.port=e.port,i.path=Zi(e.path||""),i.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(i.userinfo=e.userinfo,i.host=e.host,i.port=e.port,i.path=Zi(e.path||""),i.query=e.query):(e.path?(e.path[0]==="/"?i.path=Zi(e.path):((r.userinfo!==void 0||r.host!==void 0||r.port!==void 0)&&!r.path?i.path="/"+e.path:r.path?i.path=r.path.slice(0,r.path.lastIndexOf("/")+1)+e.path:i.path=e.path,i.path=Zi(i.path)),i.query=e.query):(i.path=r.path,e.query!==void 0?i.query=e.query:i.query=r.query),i.userinfo=r.userinfo,i.host=r.host,i.port=r.port),i.scheme=r.scheme),i.fragment=e.fragment,i}function wz(r,e,t){return typeof r=="string"?(r=unescape(r),r=Ct(As(Xt(r,t),!0),{...t,skipEscape:!0})):typeof r=="object"&&(r=Ct(As(r,!0),{...t,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=Ct(As(Xt(e,t),!0),{...t,skipEscape:!0})):typeof e=="object"&&(e=Ct(As(e,!0),{...t,skipEscape:!0})),r.toLowerCase()===e.toLowerCase()}function Ct(r,e){let t={host:r.host,scheme:r.scheme,userinfo:r.userinfo,port:r.port,path:r.path,query:r.query,nid:r.nid,nss:r.nss,uuid:r.uuid,fragment:r.fragment,reference:r.reference,resourceName:r.resourceName,secure:r.secure,error:""},n=Object.assign({},e),i=[],o=xv(n.scheme||t.scheme);o&&o.serialize&&o.serialize(t,n),t.path!==void 0&&(n.skipEscape?t.path=unescape(t.path):(t.path=escape(t.path),t.scheme!==void 0&&(t.path=t.path.split("%3A").join(":")))),n.reference!=="suffix"&&t.scheme&&i.push(t.scheme,":");let s=gz(t);if(s!==void 0&&(n.reference!=="suffix"&&i.push("//"),i.push(s),t.path&&t.path[0]!=="/"&&i.push("/")),t.path!==void 0){let a=t.path;!n.absolutePath&&(!o||!o.absolutePath)&&(a=Zi(a)),s===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),i.push(a)}return t.query!==void 0&&i.push("?",t.query),t.fragment!==void 0&&i.push("#",t.fragment),i.join("")}var kz=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function Xt(r,e){let t=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},i=!1;t.reference==="suffix"&&(t.scheme?r=t.scheme+":"+r:r="//"+r);let o=r.match(kz);if(o){if(n.scheme=o[1],n.userinfo=o[3],n.host=o[4],n.port=parseInt(o[5],10),n.path=o[6]||"",n.query=o[7],n.fragment=o[8],isNaN(n.port)&&(n.port=o[5]),n.host)if(vz(n.host)===!1){let c=hz(n.host);n.host=c.host.toLowerCase(),i=c.isIPV6}else i=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",t.reference&&t.reference!=="suffix"&&t.reference!==n.reference&&(n.error=n.error||"URI is not a "+t.reference+" reference.");let s=xv(t.scheme||n.scheme);if(!t.unicodeSupport&&(!s||!s.unicodeSupport)&&n.host&&(t.domainHost||s&&s.domainHost)&&i===!1&&xz(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(a){n.error=n.error||"Host's domain name can not be converted to ASCII: "+a}(!s||s&&!s.skipNormalize)&&(r.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=unescape(n.host))),n.path&&(n.path=escape(unescape(n.path))),n.fragment&&(n.fragment=encodeURI(decodeURIComponent(n.fragment)))),s&&s.parse&&s.parse(n,t)}else n.error=n.error||"URI can not be parsed.";return n}var Ku={SCHEMES:yz,normalize:_z,resolve:bz,resolveComponent:yv,equal:wz,serialize:Ct,parse:Xt};Os.exports=Ku;Os.exports.default=Ku;Os.exports.fastUri=Ku});var wv=_(Ju=>{"use strict";Object.defineProperty(Ju,"__esModule",{value:!0});var bv=_v();bv.code='require("ajv/dist/runtime/uri").default';Ju.default=bv});var Rv=_(Pe=>{"use strict";Object.defineProperty(Pe,"__esModule",{value:!0});Pe.CodeGen=Pe.Name=Pe.nil=Pe.stringify=Pe.str=Pe._=Pe.KeywordCxt=void 0;var Sz=Di();Object.defineProperty(Pe,"KeywordCxt",{enumerable:!0,get:function(){return Sz.KeywordCxt}});var Ln=H();Object.defineProperty(Pe,"_",{enumerable:!0,get:function(){return Ln._}});Object.defineProperty(Pe,"str",{enumerable:!0,get:function(){return Ln.str}});Object.defineProperty(Pe,"stringify",{enumerable:!0,get:function(){return Ln.stringify}});Object.defineProperty(Pe,"nil",{enumerable:!0,get:function(){return Ln.nil}});Object.defineProperty(Pe,"Name",{enumerable:!0,get:function(){return Ln.Name}});Object.defineProperty(Pe,"CodeGen",{enumerable:!0,get:function(){return Ln.CodeGen}});var Ez=zs(),Tv=qi(),$z=Eu(),Ui=Rs(),Tz=H(),Fi=ji(),Ns=Ni(),Qu=Q(),kv=cv(),zz=wv(),zv=(r,e)=>new RegExp(r,e);zv.code="new RegExp";var Pz=["removeAdditional","useDefaults","coerceTypes"],Rz=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),Cz={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."},Iz={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Sv=200;function Az(r){var e,t,n,i,o,s,a,c,l,u,p,d,f,m,h,v,b,w,E,P,j,Ne,tt,dn,ya;let Xn=r.strict,_a=(e=r.code)===null||e===void 0?void 0:e.optimize,dm=_a===!0||_a===void 0?1:_a||0,mm=(n=(t=r.code)===null||t===void 0?void 0:t.regExp)!==null&&n!==void 0?n:zv,Pb=(i=r.uriResolver)!==null&&i!==void 0?i:zz.default;return{strictSchema:(s=(o=r.strictSchema)!==null&&o!==void 0?o:Xn)!==null&&s!==void 0?s:!0,strictNumbers:(c=(a=r.strictNumbers)!==null&&a!==void 0?a:Xn)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=r.strictTypes)!==null&&l!==void 0?l:Xn)!==null&&u!==void 0?u:"log",strictTuples:(d=(p=r.strictTuples)!==null&&p!==void 0?p:Xn)!==null&&d!==void 0?d:"log",strictRequired:(m=(f=r.strictRequired)!==null&&f!==void 0?f:Xn)!==null&&m!==void 0?m:!1,code:r.code?{...r.code,optimize:dm,regExp:mm}:{optimize:dm,regExp:mm},loopRequired:(h=r.loopRequired)!==null&&h!==void 0?h:Sv,loopEnum:(v=r.loopEnum)!==null&&v!==void 0?v:Sv,meta:(b=r.meta)!==null&&b!==void 0?b:!0,messages:(w=r.messages)!==null&&w!==void 0?w:!0,inlineRefs:(E=r.inlineRefs)!==null&&E!==void 0?E:!0,schemaId:(P=r.schemaId)!==null&&P!==void 0?P:"$id",addUsedSchema:(j=r.addUsedSchema)!==null&&j!==void 0?j:!0,validateSchema:(Ne=r.validateSchema)!==null&&Ne!==void 0?Ne:!0,validateFormats:(tt=r.validateFormats)!==null&&tt!==void 0?tt:!0,unicodeRegExp:(dn=r.unicodeRegExp)!==null&&dn!==void 0?dn:!0,int32range:(ya=r.int32range)!==null&&ya!==void 0?ya:!0,uriResolver:Pb}}var Hi=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...Az(e)};let{es5:t,lines:n}=this.opts.code;this.scope=new Tz.ValueScope({scope:{},prefixes:Rz,es5:t,lines:n}),this.logger=Dz(e.logger);let i=e.validateFormats;e.validateFormats=!1,this.RULES=(0,$z.getRules)(),Ev.call(this,Cz,e,"NOT SUPPORTED"),Ev.call(this,Iz,e,"DEPRECATED","warn"),this._metaOpts=Mz.call(this),e.formats&&Nz.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&jz.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),Oz.call(this),e.validateFormats=i}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:n}=this.opts,i=kv;n==="id"&&(i={...kv},i.id=i.$id,delete i.$id),t&&e&&this.addMetaSchema(i,i[n],!1)}defaultMeta(){let{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[t]||e:void 0}validate(e,t){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let i=n(t);return"$async"in n||(this.errors=n.errors),i}compile(e,t){let n=this._addSchema(e,t);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,t){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return i.call(this,e,t);async function i(u,p){await o.call(this,u.$schema);let d=this._addSchema(u,p);return d.validate||s.call(this,d)}async function o(u){u&&!this.getSchema(u)&&await i.call(this,{$ref:u},!0)}async function s(u){try{return this._compileSchemaEnv(u)}catch(p){if(!(p instanceof Tv.default))throw p;return a.call(this,p),await c.call(this,p.missingSchema),s.call(this,u)}}function a({missingSchema:u,missingRef:p}){if(this.refs[u])throw new Error(`AnySchema ${u} is loaded but ${p} cannot be resolved`)}async function c(u){let p=await l.call(this,u);this.refs[u]||await o.call(this,p.$schema),this.refs[u]||this.addSchema(p,u,t)}async function l(u){let p=this._loading[u];if(p)return p;try{return await(this._loading[u]=n(u))}finally{delete this._loading[u]}}}addSchema(e,t,n,i=this.opts.validateSchema){if(Array.isArray(e)){for(let s of e)this.addSchema(s,void 0,n,i);return this}let o;if(typeof e=="object"){let{schemaId:s}=this.opts;if(o=e[s],o!==void 0&&typeof o!="string")throw new Error(`schema ${s} must be string`)}return t=(0,Fi.normalizeId)(t||o),this._checkUnique(t),this.schemas[t]=this._addSchema(e,n,t,i,!0),this}addMetaSchema(e,t,n=this.opts.validateSchema){return this.addSchema(e,t,!0,n),this}validateSchema(e,t){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let i=this.validate(n,e);if(!i&&t){let o="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(o);else throw new Error(o)}return i}getSchema(e){let t;for(;typeof(t=$v.call(this,e))=="string";)e=t;if(t===void 0){let{schemaId:n}=this.opts,i=new Ui.SchemaEnv({schema:{},schemaId:n});if(t=Ui.resolveSchema.call(this,i,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}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 t=$v.call(this,e);return typeof t=="object"&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let t=e;this._cache.delete(t);let n=e[this.opts.schemaId];return n&&(n=(0,Fi.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let n;if(typeof e=="string")n=e,typeof t=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),t.keyword=n);else if(typeof e=="object"&&t===void 0){if(t=e,n=t.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(Zz.call(this,n,t),!t)return(0,Qu.eachItem)(n,o=>Xu.call(this,o)),this;Fz.call(this,t);let i={...t,type:(0,Ns.getJSONTypes)(t.type),schemaType:(0,Ns.getJSONTypes)(t.schemaType)};return(0,Qu.eachItem)(n,i.type.length===0?o=>Xu.call(this,o,i):o=>i.type.forEach(s=>Xu.call(this,o,i,s))),this}getKeyword(e){let t=this.RULES.all[e];return typeof t=="object"?t.definition:!!t}removeKeyword(e){let{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(let n of t.rules){let i=n.rules.findIndex(o=>o.keyword===e);i>=0&&n.rules.splice(i,1)}return this}addFormat(e,t){return typeof t=="string"&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(i=>`${n}${i.instancePath} ${i.message}`).reduce((i,o)=>i+t+o)}$dataMetaSchema(e,t){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let i of t){let o=i.split("/").slice(1),s=e;for(let a of o)s=s[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:l}=c.definition,u=s[a];l&&u&&(s[a]=Pv(u))}}return e}_removeAllSchemas(e,t){for(let n in e){let i=e[n];(!t||t.test(n))&&(typeof i=="string"?delete e[n]:i&&!i.meta&&(this._cache.delete(i.schema),delete e[n]))}}_addSchema(e,t,n,i=this.opts.validateSchema,o=this.opts.addUsedSchema){let s,{schemaId:a}=this.opts;if(typeof e=="object")s=e[a];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 c=this._cache.get(e);if(c!==void 0)return c;n=(0,Fi.normalizeId)(s||n);let l=Fi.getSchemaRefs.call(this,e,n);return c=new Ui.SchemaEnv({schema:e,schemaId:a,meta:t,baseId:n,localRefs:l}),this._cache.set(c.schema,c),o&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),i&&this.validateSchema(e,!0),c}_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):Ui.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let t=this.opts;this.opts=this._metaOpts;try{Ui.compileSchema.call(this,e)}finally{this.opts=t}}};Hi.ValidationError=Ez.default;Hi.MissingRefError=Tv.default;Pe.default=Hi;function Ev(r,e,t,n="error"){for(let i in r){let o=i;o in e&&this.logger[n](`${t}: option ${i}. ${r[o]}`)}}function $v(r){return r=(0,Fi.normalizeId)(r),this.schemas[r]||this.refs[r]}function Oz(){let r=this.opts.schemas;if(r)if(Array.isArray(r))this.addSchema(r);else for(let e in r)this.addSchema(r[e],e)}function Nz(){for(let r in this.opts.formats){let e=this.opts.formats[r];e&&this.addFormat(r,e)}}function jz(r){if(Array.isArray(r)){this.addVocabulary(r);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in r){let t=r[e];t.keyword||(t.keyword=e),this.addKeyword(t)}}function Mz(){let r={...this.opts};for(let e of Pz)delete r[e];return r}var Lz={log(){},warn(){},error(){}};function Dz(r){if(r===!1)return Lz;if(r===void 0)return console;if(r.log&&r.warn&&r.error)return r;throw new Error("logger must implement log, warn and error methods")}var qz=/^[a-z_$][a-z0-9_$:-]*$/i;function Zz(r,e){let{RULES:t}=this;if((0,Qu.eachItem)(r,n=>{if(t.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!qz.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function Xu(r,e,t){var n;let i=e?.post;if(t&&i)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:o}=this,s=i?o.post:o.rules.find(({type:c})=>c===t);if(s||(s={type:t,rules:[]},o.rules.push(s)),o.keywords[r]=!0,!e)return;let a={keyword:r,definition:{...e,type:(0,Ns.getJSONTypes)(e.type),schemaType:(0,Ns.getJSONTypes)(e.schemaType)}};e.before?Uz.call(this,s,a,e.before):s.rules.push(a),o.all[r]=a,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function Uz(r,e,t){let n=r.rules.findIndex(i=>i.keyword===t);n>=0?r.rules.splice(n,0,e):(r.rules.push(e),this.logger.warn(`rule ${t} is not defined`))}function Fz(r){let{metaSchema:e}=r;e!==void 0&&(r.$data&&this.opts.$data&&(e=Pv(e)),r.validateSchema=this.compile(e,!0))}var Hz={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Pv(r){return{anyOf:[r,Hz]}}});var Cv=_(Yu=>{"use strict";Object.defineProperty(Yu,"__esModule",{value:!0});var Bz={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Yu.default=Bz});var Nv=_(en=>{"use strict";Object.defineProperty(en,"__esModule",{value:!0});en.callRef=en.getValidate=void 0;var Vz=qi(),Iv=ct(),Ge=H(),Dn=Kt(),Av=Rs(),js=Q(),Wz={keyword:"$ref",schemaType:"string",code(r){let{gen:e,schema:t,it:n}=r,{baseId:i,schemaEnv:o,validateName:s,opts:a,self:c}=n,{root:l}=o;if((t==="#"||t==="#/")&&i===l.baseId)return p();let u=Av.resolveRef.call(c,l,i,t);if(u===void 0)throw new Vz.default(n.opts.uriResolver,i,t);if(u instanceof Av.SchemaEnv)return d(u);return f(u);function p(){if(o===l)return Ms(r,s,o,o.$async);let m=e.scopeValue("root",{ref:l});return Ms(r,(0,Ge._)`${m}.validate`,l,l.$async)}function d(m){let h=Ov(r,m);Ms(r,h,m,m.$async)}function f(m){let h=e.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,Ge.stringify)(m)}:{ref:m}),v=e.name("valid"),b=r.subschema({schema:m,dataTypes:[],schemaPath:Ge.nil,topSchemaRef:h,errSchemaPath:t},v);r.mergeEvaluated(b),r.ok(v)}}};function Ov(r,e){let{gen:t}=r;return e.validate?t.scopeValue("validate",{ref:e.validate}):(0,Ge._)`${t.scopeValue("wrapper",{ref:e})}.validate`}en.getValidate=Ov;function Ms(r,e,t,n){let{gen:i,it:o}=r,{allErrors:s,schemaEnv:a,opts:c}=o,l=c.passContext?Dn.default.this:Ge.nil;n?u():p();function u(){if(!a.$async)throw new Error("async schema referenced by sync schema");let m=i.let("valid");i.try(()=>{i.code((0,Ge._)`await ${(0,Iv.callValidateCode)(r,e,l)}`),f(e),s||i.assign(m,!0)},h=>{i.if((0,Ge._)`!(${h} instanceof ${o.ValidationError})`,()=>i.throw(h)),d(h),s||i.assign(m,!1)}),r.ok(m)}function p(){r.result((0,Iv.callValidateCode)(r,e,l),()=>f(e),()=>d(e))}function d(m){let h=(0,Ge._)`${m}.errors`;i.assign(Dn.default.vErrors,(0,Ge._)`${Dn.default.vErrors} === null ? ${h} : ${Dn.default.vErrors}.concat(${h})`),i.assign(Dn.default.errors,(0,Ge._)`${Dn.default.vErrors}.length`)}function f(m){var h;if(!o.opts.unevaluated)return;let v=(h=t?.validate)===null||h===void 0?void 0:h.evaluated;if(o.props!==!0)if(v&&!v.dynamicProps)v.props!==void 0&&(o.props=js.mergeEvaluated.props(i,v.props,o.props));else{let b=i.var("props",(0,Ge._)`${m}.evaluated.props`);o.props=js.mergeEvaluated.props(i,b,o.props,Ge.Name)}if(o.items!==!0)if(v&&!v.dynamicItems)v.items!==void 0&&(o.items=js.mergeEvaluated.items(i,v.items,o.items));else{let b=i.var("items",(0,Ge._)`${m}.evaluated.items`);o.items=js.mergeEvaluated.items(i,b,o.items,Ge.Name)}}}en.callRef=Ms;en.default=Wz});var jv=_(ep=>{"use strict";Object.defineProperty(ep,"__esModule",{value:!0});var Gz=Cv(),Kz=Nv(),Jz=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",Gz.default,Kz.default];ep.default=Jz});var Mv=_(tp=>{"use strict";Object.defineProperty(tp,"__esModule",{value:!0});var Ls=H(),vr=Ls.operators,Ds={maximum:{okStr:"<=",ok:vr.LTE,fail:vr.GT},minimum:{okStr:">=",ok:vr.GTE,fail:vr.LT},exclusiveMaximum:{okStr:"<",ok:vr.LT,fail:vr.GTE},exclusiveMinimum:{okStr:">",ok:vr.GT,fail:vr.LTE}},Xz={message:({keyword:r,schemaCode:e})=>(0,Ls.str)`must be ${Ds[r].okStr} ${e}`,params:({keyword:r,schemaCode:e})=>(0,Ls._)`{comparison: ${Ds[r].okStr}, limit: ${e}}`},Qz={keyword:Object.keys(Ds),type:"number",schemaType:"number",$data:!0,error:Xz,code(r){let{keyword:e,data:t,schemaCode:n}=r;r.fail$data((0,Ls._)`${t} ${Ds[e].fail} ${n} || isNaN(${t})`)}};tp.default=Qz});var Lv=_(rp=>{"use strict";Object.defineProperty(rp,"__esModule",{value:!0});var Bi=H(),Yz={message:({schemaCode:r})=>(0,Bi.str)`must be multiple of ${r}`,params:({schemaCode:r})=>(0,Bi._)`{multipleOf: ${r}}`},eP={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:Yz,code(r){let{gen:e,data:t,schemaCode:n,it:i}=r,o=i.opts.multipleOfPrecision,s=e.let("res"),a=o?(0,Bi._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${o}`:(0,Bi._)`${s} !== parseInt(${s})`;r.fail$data((0,Bi._)`(${n} === 0 || (${s} = ${t}/${n}, ${a}))`)}};rp.default=eP});var qv=_(np=>{"use strict";Object.defineProperty(np,"__esModule",{value:!0});function Dv(r){let e=r.length,t=0,n=0,i;for(;n<e;)t++,i=r.charCodeAt(n++),i>=55296&&i<=56319&&n<e&&(i=r.charCodeAt(n),(i&64512)===56320&&n++);return t}np.default=Dv;Dv.code='require("ajv/dist/runtime/ucs2length").default'});var Zv=_(ip=>{"use strict";Object.defineProperty(ip,"__esModule",{value:!0});var tn=H(),tP=Q(),rP=qv(),nP={message({keyword:r,schemaCode:e}){let t=r==="maxLength"?"more":"fewer";return(0,tn.str)`must NOT have ${t} than ${e} characters`},params:({schemaCode:r})=>(0,tn._)`{limit: ${r}}`},iP={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:nP,code(r){let{keyword:e,data:t,schemaCode:n,it:i}=r,o=e==="maxLength"?tn.operators.GT:tn.operators.LT,s=i.opts.unicode===!1?(0,tn._)`${t}.length`:(0,tn._)`${(0,tP.useFunc)(r.gen,rP.default)}(${t})`;r.fail$data((0,tn._)`${s} ${o} ${n}`)}};ip.default=iP});var Uv=_(op=>{"use strict";Object.defineProperty(op,"__esModule",{value:!0});var oP=ct(),sP=Q(),qn=H(),aP={message:({schemaCode:r})=>(0,qn.str)`must match pattern "${r}"`,params:({schemaCode:r})=>(0,qn._)`{pattern: ${r}}`},cP={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:aP,code(r){let{gen:e,data:t,$data:n,schema:i,schemaCode:o,it:s}=r,a=s.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=s.opts.code,l=c.code==="new RegExp"?(0,qn._)`new RegExp`:(0,sP.useFunc)(e,c),u=e.let("valid");e.try(()=>e.assign(u,(0,qn._)`${l}(${o}, ${a}).test(${t})`),()=>e.assign(u,!1)),r.fail$data((0,qn._)`!${u}`)}else{let c=(0,oP.usePattern)(r,i);r.fail$data((0,qn._)`!${c}.test(${t})`)}}};op.default=cP});var Fv=_(sp=>{"use strict";Object.defineProperty(sp,"__esModule",{value:!0});var Vi=H(),lP={message({keyword:r,schemaCode:e}){let t=r==="maxProperties"?"more":"fewer";return(0,Vi.str)`must NOT have ${t} than ${e} properties`},params:({schemaCode:r})=>(0,Vi._)`{limit: ${r}}`},uP={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:lP,code(r){let{keyword:e,data:t,schemaCode:n}=r,i=e==="maxProperties"?Vi.operators.GT:Vi.operators.LT;r.fail$data((0,Vi._)`Object.keys(${t}).length ${i} ${n}`)}};sp.default=uP});var Hv=_(ap=>{"use strict";Object.defineProperty(ap,"__esModule",{value:!0});var Wi=ct(),Gi=H(),pP=Q(),dP={message:({params:{missingProperty:r}})=>(0,Gi.str)`must have required property '${r}'`,params:({params:{missingProperty:r}})=>(0,Gi._)`{missingProperty: ${r}}`},mP={keyword:"required",type:"object",schemaType:"array",$data:!0,error:dP,code(r){let{gen:e,schema:t,schemaCode:n,data:i,$data:o,it:s}=r,{opts:a}=s;if(!o&&t.length===0)return;let c=t.length>=a.loopRequired;if(s.allErrors?l():u(),a.strictRequired){let f=r.parentSchema.properties,{definedProperties:m}=r.it;for(let h of t)if(f?.[h]===void 0&&!m.has(h)){let v=s.schemaEnv.baseId+s.errSchemaPath,b=`required property "${h}" is not defined at "${v}" (strictRequired)`;(0,pP.checkStrictMode)(s,b,s.opts.strictRequired)}}function l(){if(c||o)r.block$data(Gi.nil,p);else for(let f of t)(0,Wi.checkReportMissingProp)(r,f)}function u(){let f=e.let("missing");if(c||o){let m=e.let("valid",!0);r.block$data(m,()=>d(f,m)),r.ok(m)}else e.if((0,Wi.checkMissingProp)(r,t,f)),(0,Wi.reportMissingProp)(r,f),e.else()}function p(){e.forOf("prop",n,f=>{r.setParams({missingProperty:f}),e.if((0,Wi.noPropertyInData)(e,i,f,a.ownProperties),()=>r.error())})}function d(f,m){r.setParams({missingProperty:f}),e.forOf(f,n,()=>{e.assign(m,(0,Wi.propertyInData)(e,i,f,a.ownProperties)),e.if((0,Gi.not)(m),()=>{r.error(),e.break()})},Gi.nil)}}};ap.default=mP});var Bv=_(cp=>{"use strict";Object.defineProperty(cp,"__esModule",{value:!0});var Ki=H(),fP={message({keyword:r,schemaCode:e}){let t=r==="maxItems"?"more":"fewer";return(0,Ki.str)`must NOT have ${t} than ${e} items`},params:({schemaCode:r})=>(0,Ki._)`{limit: ${r}}`},hP={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:fP,code(r){let{keyword:e,data:t,schemaCode:n}=r,i=e==="maxItems"?Ki.operators.GT:Ki.operators.LT;r.fail$data((0,Ki._)`${t}.length ${i} ${n}`)}};cp.default=hP});var qs=_(lp=>{"use strict";Object.defineProperty(lp,"__esModule",{value:!0});var Vv=Au();Vv.code='require("ajv/dist/runtime/equal").default';lp.default=Vv});var Wv=_(pp=>{"use strict";Object.defineProperty(pp,"__esModule",{value:!0});var up=Ni(),Re=H(),gP=Q(),vP=qs(),xP={message:({params:{i:r,j:e}})=>(0,Re.str)`must NOT have duplicate items (items ## ${e} and ${r} are identical)`,params:({params:{i:r,j:e}})=>(0,Re._)`{i: ${r}, j: ${e}}`},yP={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:xP,code(r){let{gen:e,data:t,$data:n,schema:i,parentSchema:o,schemaCode:s,it:a}=r;if(!n&&!i)return;let c=e.let("valid"),l=o.items?(0,up.getSchemaTypes)(o.items):[];r.block$data(c,u,(0,Re._)`${s} === false`),r.ok(c);function u(){let m=e.let("i",(0,Re._)`${t}.length`),h=e.let("j");r.setParams({i:m,j:h}),e.assign(c,!0),e.if((0,Re._)`${m} > 1`,()=>(p()?d:f)(m,h))}function p(){return l.length>0&&!l.some(m=>m==="object"||m==="array")}function d(m,h){let v=e.name("item"),b=(0,up.checkDataTypes)(l,v,a.opts.strictNumbers,up.DataType.Wrong),w=e.const("indices",(0,Re._)`{}`);e.for((0,Re._)`;${m}--;`,()=>{e.let(v,(0,Re._)`${t}[${m}]`),e.if(b,(0,Re._)`continue`),l.length>1&&e.if((0,Re._)`typeof ${v} == "string"`,(0,Re._)`${v} += "_"`),e.if((0,Re._)`typeof ${w}[${v}] == "number"`,()=>{e.assign(h,(0,Re._)`${w}[${v}]`),r.error(),e.assign(c,!1).break()}).code((0,Re._)`${w}[${v}] = ${m}`)})}function f(m,h){let v=(0,gP.useFunc)(e,vP.default),b=e.name("outer");e.label(b).for((0,Re._)`;${m}--;`,()=>e.for((0,Re._)`${h} = ${m}; ${h}--;`,()=>e.if((0,Re._)`${v}(${t}[${m}], ${t}[${h}])`,()=>{r.error(),e.assign(c,!1).break(b)})))}}};pp.default=yP});var Gv=_(mp=>{"use strict";Object.defineProperty(mp,"__esModule",{value:!0});var dp=H(),_P=Q(),bP=qs(),wP={message:"must be equal to constant",params:({schemaCode:r})=>(0,dp._)`{allowedValue: ${r}}`},kP={keyword:"const",$data:!0,error:wP,code(r){let{gen:e,data:t,$data:n,schemaCode:i,schema:o}=r;n||o&&typeof o=="object"?r.fail$data((0,dp._)`!${(0,_P.useFunc)(e,bP.default)}(${t}, ${i})`):r.fail((0,dp._)`${o} !== ${t}`)}};mp.default=kP});var Kv=_(fp=>{"use strict";Object.defineProperty(fp,"__esModule",{value:!0});var Ji=H(),SP=Q(),EP=qs(),$P={message:"must be equal to one of the allowed values",params:({schemaCode:r})=>(0,Ji._)`{allowedValues: ${r}}`},TP={keyword:"enum",schemaType:"array",$data:!0,error:$P,code(r){let{gen:e,data:t,$data:n,schema:i,schemaCode:o,it:s}=r;if(!n&&i.length===0)throw new Error("enum must have non-empty array");let a=i.length>=s.opts.loopEnum,c,l=()=>c??(c=(0,SP.useFunc)(e,EP.default)),u;if(a||n)u=e.let("valid"),r.block$data(u,p);else{if(!Array.isArray(i))throw new Error("ajv implementation error");let f=e.const("vSchema",o);u=(0,Ji.or)(...i.map((m,h)=>d(f,h)))}r.pass(u);function p(){e.assign(u,!1),e.forOf("v",o,f=>e.if((0,Ji._)`${l()}(${t}, ${f})`,()=>e.assign(u,!0).break()))}function d(f,m){let h=i[m];return typeof h=="object"&&h!==null?(0,Ji._)`${l()}(${t}, ${f}[${m}])`:(0,Ji._)`${t} === ${h}`}}};fp.default=TP});var Jv=_(hp=>{"use strict";Object.defineProperty(hp,"__esModule",{value:!0});var zP=Mv(),PP=Lv(),RP=Zv(),CP=Uv(),IP=Fv(),AP=Hv(),OP=Bv(),NP=Wv(),jP=Gv(),MP=Kv(),LP=[zP.default,PP.default,RP.default,CP.default,IP.default,AP.default,OP.default,NP.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},jP.default,MP.default];hp.default=LP});var vp=_(Xi=>{"use strict";Object.defineProperty(Xi,"__esModule",{value:!0});Xi.validateAdditionalItems=void 0;var rn=H(),gp=Q(),DP={message:({params:{len:r}})=>(0,rn.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,rn._)`{limit: ${r}}`},qP={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:DP,code(r){let{parentSchema:e,it:t}=r,{items:n}=e;if(!Array.isArray(n)){(0,gp.checkStrictMode)(t,'"additionalItems" is ignored when "items" is not an array of schemas');return}Xv(r,n)}};function Xv(r,e){let{gen:t,schema:n,data:i,keyword:o,it:s}=r;s.items=!0;let a=t.const("len",(0,rn._)`${i}.length`);if(n===!1)r.setParams({len:e.length}),r.pass((0,rn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,gp.alwaysValidSchema)(s,n)){let l=t.var("valid",(0,rn._)`${a} <= ${e.length}`);t.if((0,rn.not)(l),()=>c(l)),r.ok(l)}function c(l){t.forRange("i",e.length,a,u=>{r.subschema({keyword:o,dataProp:u,dataPropType:gp.Type.Num},l),s.allErrors||t.if((0,rn.not)(l),()=>t.break())})}}Xi.validateAdditionalItems=Xv;Xi.default=qP});var xp=_(Qi=>{"use strict";Object.defineProperty(Qi,"__esModule",{value:!0});Qi.validateTuple=void 0;var Qv=H(),Zs=Q(),ZP=ct(),UP={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(r){let{schema:e,it:t}=r;if(Array.isArray(e))return Yv(r,"additionalItems",e);t.items=!0,!(0,Zs.alwaysValidSchema)(t,e)&&r.ok((0,ZP.validateArray)(r))}};function Yv(r,e,t=r.schema){let{gen:n,parentSchema:i,data:o,keyword:s,it:a}=r;u(i),a.opts.unevaluated&&t.length&&a.items!==!0&&(a.items=Zs.mergeEvaluated.items(n,t.length,a.items));let c=n.name("valid"),l=n.const("len",(0,Qv._)`${o}.length`);t.forEach((p,d)=>{(0,Zs.alwaysValidSchema)(a,p)||(n.if((0,Qv._)`${l} > ${d}`,()=>r.subschema({keyword:s,schemaProp:d,dataProp:d},c)),r.ok(c))});function u(p){let{opts:d,errSchemaPath:f}=a,m=t.length,h=m===p.minItems&&(m===p.maxItems||p[e]===!1);if(d.strictTuples&&!h){let v=`"${s}" is ${m}-tuple, but minItems or maxItems/${e} are not specified or different at path "${f}"`;(0,Zs.checkStrictMode)(a,v,d.strictTuples)}}}Qi.validateTuple=Yv;Qi.default=UP});var ex=_(yp=>{"use strict";Object.defineProperty(yp,"__esModule",{value:!0});var FP=xp(),HP={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:r=>(0,FP.validateTuple)(r,"items")};yp.default=HP});var rx=_(_p=>{"use strict";Object.defineProperty(_p,"__esModule",{value:!0});var tx=H(),BP=Q(),VP=ct(),WP=vp(),GP={message:({params:{len:r}})=>(0,tx.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,tx._)`{limit: ${r}}`},KP={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:GP,code(r){let{schema:e,parentSchema:t,it:n}=r,{prefixItems:i}=t;n.items=!0,!(0,BP.alwaysValidSchema)(n,e)&&(i?(0,WP.validateAdditionalItems)(r,i):r.ok((0,VP.validateArray)(r)))}};_p.default=KP});var nx=_(bp=>{"use strict";Object.defineProperty(bp,"__esModule",{value:!0});var ut=H(),Us=Q(),JP={message:({params:{min:r,max:e}})=>e===void 0?(0,ut.str)`must contain at least ${r} valid item(s)`:(0,ut.str)`must contain at least ${r} and no more than ${e} valid item(s)`,params:({params:{min:r,max:e}})=>e===void 0?(0,ut._)`{minContains: ${r}}`:(0,ut._)`{minContains: ${r}, maxContains: ${e}}`},XP={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:JP,code(r){let{gen:e,schema:t,parentSchema:n,data:i,it:o}=r,s,a,{minContains:c,maxContains:l}=n;o.opts.next?(s=c===void 0?1:c,a=l):s=1;let u=e.const("len",(0,ut._)`${i}.length`);if(r.setParams({min:s,max:a}),a===void 0&&s===0){(0,Us.checkStrictMode)(o,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&s>a){(0,Us.checkStrictMode)(o,'"minContains" > "maxContains" is always invalid'),r.fail();return}if((0,Us.alwaysValidSchema)(o,t)){let h=(0,ut._)`${u} >= ${s}`;a!==void 0&&(h=(0,ut._)`${h} && ${u} <= ${a}`),r.pass(h);return}o.items=!0;let p=e.name("valid");a===void 0&&s===1?f(p,()=>e.if(p,()=>e.break())):s===0?(e.let(p,!0),a!==void 0&&e.if((0,ut._)`${i}.length > 0`,d)):(e.let(p,!1),d()),r.result(p,()=>r.reset());function d(){let h=e.name("_valid"),v=e.let("count",0);f(h,()=>e.if(h,()=>m(v)))}function f(h,v){e.forRange("i",0,u,b=>{r.subschema({keyword:"contains",dataProp:b,dataPropType:Us.Type.Num,compositeRule:!0},h),v()})}function m(h){e.code((0,ut._)`${h}++`),a===void 0?e.if((0,ut._)`${h} >= ${s}`,()=>e.assign(p,!0).break()):(e.if((0,ut._)`${h} > ${a}`,()=>e.assign(p,!1).break()),s===1?e.assign(p,!0):e.if((0,ut._)`${h} >= ${s}`,()=>e.assign(p,!0)))}}};bp.default=XP});var sx=_(It=>{"use strict";Object.defineProperty(It,"__esModule",{value:!0});It.validateSchemaDeps=It.validatePropertyDeps=It.error=void 0;var wp=H(),QP=Q(),Yi=ct();It.error={message:({params:{property:r,depsCount:e,deps:t}})=>{let n=e===1?"property":"properties";return(0,wp.str)`must have ${n} ${t} when property ${r} is present`},params:({params:{property:r,depsCount:e,deps:t,missingProperty:n}})=>(0,wp._)`{property: ${r},
|
|
6
|
+
missingProperty: ${n},
|
|
7
|
+
depsCount: ${e},
|
|
8
|
+
deps: ${t}}`};var YP={keyword:"dependencies",type:"object",schemaType:"object",error:It.error,code(r){let[e,t]=eR(r);ix(r,e),ox(r,t)}};function eR({schema:r}){let e={},t={};for(let n in r){if(n==="__proto__")continue;let i=Array.isArray(r[n])?e:t;i[n]=r[n]}return[e,t]}function ix(r,e=r.schema){let{gen:t,data:n,it:i}=r;if(Object.keys(e).length===0)return;let o=t.let("missing");for(let s in e){let a=e[s];if(a.length===0)continue;let c=(0,Yi.propertyInData)(t,n,s,i.opts.ownProperties);r.setParams({property:s,depsCount:a.length,deps:a.join(", ")}),i.allErrors?t.if(c,()=>{for(let l of a)(0,Yi.checkReportMissingProp)(r,l)}):(t.if((0,wp._)`${c} && (${(0,Yi.checkMissingProp)(r,a,o)})`),(0,Yi.reportMissingProp)(r,o),t.else())}}It.validatePropertyDeps=ix;function ox(r,e=r.schema){let{gen:t,data:n,keyword:i,it:o}=r,s=t.name("valid");for(let a in e)(0,QP.alwaysValidSchema)(o,e[a])||(t.if((0,Yi.propertyInData)(t,n,a,o.opts.ownProperties),()=>{let c=r.subschema({keyword:i,schemaProp:a},s);r.mergeValidEvaluated(c,s)},()=>t.var(s,!0)),r.ok(s))}It.validateSchemaDeps=ox;It.default=YP});var cx=_(kp=>{"use strict";Object.defineProperty(kp,"__esModule",{value:!0});var ax=H(),tR=Q(),rR={message:"property name must be valid",params:({params:r})=>(0,ax._)`{propertyName: ${r.propertyName}}`},nR={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:rR,code(r){let{gen:e,schema:t,data:n,it:i}=r;if((0,tR.alwaysValidSchema)(i,t))return;let o=e.name("valid");e.forIn("key",n,s=>{r.setParams({propertyName:s}),r.subschema({keyword:"propertyNames",data:s,dataTypes:["string"],propertyName:s,compositeRule:!0},o),e.if((0,ax.not)(o),()=>{r.error(!0),i.allErrors||e.break()})}),r.ok(o)}};kp.default=nR});var Ep=_(Sp=>{"use strict";Object.defineProperty(Sp,"__esModule",{value:!0});var Fs=ct(),_t=H(),iR=Kt(),Hs=Q(),oR={message:"must NOT have additional properties",params:({params:r})=>(0,_t._)`{additionalProperty: ${r.additionalProperty}}`},sR={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:oR,code(r){let{gen:e,schema:t,parentSchema:n,data:i,errsCount:o,it:s}=r;if(!o)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=s;if(s.props=!0,c.removeAdditional!=="all"&&(0,Hs.alwaysValidSchema)(s,t))return;let l=(0,Fs.allSchemaProperties)(n.properties),u=(0,Fs.allSchemaProperties)(n.patternProperties);p(),r.ok((0,_t._)`${o} === ${iR.default.errors}`);function p(){e.forIn("key",i,v=>{!l.length&&!u.length?m(v):e.if(d(v),()=>m(v))})}function d(v){let b;if(l.length>8){let w=(0,Hs.schemaRefOrVal)(s,n.properties,"properties");b=(0,Fs.isOwnProperty)(e,w,v)}else l.length?b=(0,_t.or)(...l.map(w=>(0,_t._)`${v} === ${w}`)):b=_t.nil;return u.length&&(b=(0,_t.or)(b,...u.map(w=>(0,_t._)`${(0,Fs.usePattern)(r,w)}.test(${v})`))),(0,_t.not)(b)}function f(v){e.code((0,_t._)`delete ${i}[${v}]`)}function m(v){if(c.removeAdditional==="all"||c.removeAdditional&&t===!1){f(v);return}if(t===!1){r.setParams({additionalProperty:v}),r.error(),a||e.break();return}if(typeof t=="object"&&!(0,Hs.alwaysValidSchema)(s,t)){let b=e.name("valid");c.removeAdditional==="failing"?(h(v,b,!1),e.if((0,_t.not)(b),()=>{r.reset(),f(v)})):(h(v,b),a||e.if((0,_t.not)(b),()=>e.break()))}}function h(v,b,w){let E={keyword:"additionalProperties",dataProp:v,dataPropType:Hs.Type.Str};w===!1&&Object.assign(E,{compositeRule:!0,createErrors:!1,allErrors:!1}),r.subschema(E,b)}}};Sp.default=sR});var px=_(Tp=>{"use strict";Object.defineProperty(Tp,"__esModule",{value:!0});var aR=Di(),lx=ct(),$p=Q(),ux=Ep(),cR={keyword:"properties",type:"object",schemaType:"object",code(r){let{gen:e,schema:t,parentSchema:n,data:i,it:o}=r;o.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&ux.default.code(new aR.KeywordCxt(o,ux.default,"additionalProperties"));let s=(0,lx.allSchemaProperties)(t);for(let p of s)o.definedProperties.add(p);o.opts.unevaluated&&s.length&&o.props!==!0&&(o.props=$p.mergeEvaluated.props(e,(0,$p.toHash)(s),o.props));let a=s.filter(p=>!(0,$p.alwaysValidSchema)(o,t[p]));if(a.length===0)return;let c=e.name("valid");for(let p of a)l(p)?u(p):(e.if((0,lx.propertyInData)(e,i,p,o.opts.ownProperties)),u(p),o.allErrors||e.else().var(c,!0),e.endIf()),r.it.definedProperties.add(p),r.ok(c);function l(p){return o.opts.useDefaults&&!o.compositeRule&&t[p].default!==void 0}function u(p){r.subschema({keyword:"properties",schemaProp:p,dataProp:p},c)}}};Tp.default=cR});var hx=_(zp=>{"use strict";Object.defineProperty(zp,"__esModule",{value:!0});var dx=ct(),Bs=H(),mx=Q(),fx=Q(),lR={keyword:"patternProperties",type:"object",schemaType:"object",code(r){let{gen:e,schema:t,data:n,parentSchema:i,it:o}=r,{opts:s}=o,a=(0,dx.allSchemaProperties)(t),c=a.filter(h=>(0,mx.alwaysValidSchema)(o,t[h]));if(a.length===0||c.length===a.length&&(!o.opts.unevaluated||o.props===!0))return;let l=s.strictSchema&&!s.allowMatchingProperties&&i.properties,u=e.name("valid");o.props!==!0&&!(o.props instanceof Bs.Name)&&(o.props=(0,fx.evaluatedPropsToName)(e,o.props));let{props:p}=o;d();function d(){for(let h of a)l&&f(h),o.allErrors?m(h):(e.var(u,!0),m(h),e.if(u))}function f(h){for(let v in l)new RegExp(h).test(v)&&(0,mx.checkStrictMode)(o,`property ${v} matches pattern ${h} (use allowMatchingProperties)`)}function m(h){e.forIn("key",n,v=>{e.if((0,Bs._)`${(0,dx.usePattern)(r,h)}.test(${v})`,()=>{let b=c.includes(h);b||r.subschema({keyword:"patternProperties",schemaProp:h,dataProp:v,dataPropType:fx.Type.Str},u),o.opts.unevaluated&&p!==!0?e.assign((0,Bs._)`${p}[${v}]`,!0):!b&&!o.allErrors&&e.if((0,Bs.not)(u),()=>e.break())})})}}};zp.default=lR});var gx=_(Pp=>{"use strict";Object.defineProperty(Pp,"__esModule",{value:!0});var uR=Q(),pR={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(r){let{gen:e,schema:t,it:n}=r;if((0,uR.alwaysValidSchema)(n,t)){r.fail();return}let i=e.name("valid");r.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},i),r.failResult(i,()=>r.reset(),()=>r.error())},error:{message:"must NOT be valid"}};Pp.default=pR});var vx=_(Rp=>{"use strict";Object.defineProperty(Rp,"__esModule",{value:!0});var dR=ct(),mR={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:dR.validateUnion,error:{message:"must match a schema in anyOf"}};Rp.default=mR});var xx=_(Cp=>{"use strict";Object.defineProperty(Cp,"__esModule",{value:!0});var Vs=H(),fR=Q(),hR={message:"must match exactly one schema in oneOf",params:({params:r})=>(0,Vs._)`{passingSchemas: ${r.passing}}`},gR={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:hR,code(r){let{gen:e,schema:t,parentSchema:n,it:i}=r;if(!Array.isArray(t))throw new Error("ajv implementation error");if(i.opts.discriminator&&n.discriminator)return;let o=t,s=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");r.setParams({passing:a}),e.block(l),r.result(s,()=>r.reset(),()=>r.error(!0));function l(){o.forEach((u,p)=>{let d;(0,fR.alwaysValidSchema)(i,u)?e.var(c,!0):d=r.subschema({keyword:"oneOf",schemaProp:p,compositeRule:!0},c),p>0&&e.if((0,Vs._)`${c} && ${s}`).assign(s,!1).assign(a,(0,Vs._)`[${a}, ${p}]`).else(),e.if(c,()=>{e.assign(s,!0),e.assign(a,p),d&&r.mergeEvaluated(d,Vs.Name)})})}}};Cp.default=gR});var yx=_(Ip=>{"use strict";Object.defineProperty(Ip,"__esModule",{value:!0});var vR=Q(),xR={keyword:"allOf",schemaType:"array",code(r){let{gen:e,schema:t,it:n}=r;if(!Array.isArray(t))throw new Error("ajv implementation error");let i=e.name("valid");t.forEach((o,s)=>{if((0,vR.alwaysValidSchema)(n,o))return;let a=r.subschema({keyword:"allOf",schemaProp:s},i);r.ok(i),r.mergeEvaluated(a)})}};Ip.default=xR});var wx=_(Ap=>{"use strict";Object.defineProperty(Ap,"__esModule",{value:!0});var Ws=H(),bx=Q(),yR={message:({params:r})=>(0,Ws.str)`must match "${r.ifClause}" schema`,params:({params:r})=>(0,Ws._)`{failingKeyword: ${r.ifClause}}`},_R={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:yR,code(r){let{gen:e,parentSchema:t,it:n}=r;t.then===void 0&&t.else===void 0&&(0,bx.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let i=_x(n,"then"),o=_x(n,"else");if(!i&&!o)return;let s=e.let("valid",!0),a=e.name("_valid");if(c(),r.reset(),i&&o){let u=e.let("ifClause");r.setParams({ifClause:u}),e.if(a,l("then",u),l("else",u))}else i?e.if(a,l("then")):e.if((0,Ws.not)(a),l("else"));r.pass(s,()=>r.error(!0));function c(){let u=r.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);r.mergeEvaluated(u)}function l(u,p){return()=>{let d=r.subschema({keyword:u},a);e.assign(s,a),r.mergeValidEvaluated(d,s),p?e.assign(p,(0,Ws._)`${u}`):r.setParams({ifClause:u})}}}};function _x(r,e){let t=r.schema[e];return t!==void 0&&!(0,bx.alwaysValidSchema)(r,t)}Ap.default=_R});var kx=_(Op=>{"use strict";Object.defineProperty(Op,"__esModule",{value:!0});var bR=Q(),wR={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:r,parentSchema:e,it:t}){e.if===void 0&&(0,bR.checkStrictMode)(t,`"${r}" without "if" is ignored`)}};Op.default=wR});var Sx=_(Np=>{"use strict";Object.defineProperty(Np,"__esModule",{value:!0});var kR=vp(),SR=ex(),ER=xp(),$R=rx(),TR=nx(),zR=sx(),PR=cx(),RR=Ep(),CR=px(),IR=hx(),AR=gx(),OR=vx(),NR=xx(),jR=yx(),MR=wx(),LR=kx();function DR(r=!1){let e=[AR.default,OR.default,NR.default,jR.default,MR.default,LR.default,PR.default,RR.default,zR.default,CR.default,IR.default];return r?e.push(SR.default,$R.default):e.push(kR.default,ER.default),e.push(TR.default),e}Np.default=DR});var Ex=_(jp=>{"use strict";Object.defineProperty(jp,"__esModule",{value:!0});var ye=H(),qR={message:({schemaCode:r})=>(0,ye.str)`must match format "${r}"`,params:({schemaCode:r})=>(0,ye._)`{format: ${r}}`},ZR={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:qR,code(r,e){let{gen:t,data:n,$data:i,schema:o,schemaCode:s,it:a}=r,{opts:c,errSchemaPath:l,schemaEnv:u,self:p}=a;if(!c.validateFormats)return;i?d():f();function d(){let m=t.scopeValue("formats",{ref:p.formats,code:c.code.formats}),h=t.const("fDef",(0,ye._)`${m}[${s}]`),v=t.let("fType"),b=t.let("format");t.if((0,ye._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>t.assign(v,(0,ye._)`${h}.type || "string"`).assign(b,(0,ye._)`${h}.validate`),()=>t.assign(v,(0,ye._)`"string"`).assign(b,h)),r.fail$data((0,ye.or)(w(),E()));function w(){return c.strictSchema===!1?ye.nil:(0,ye._)`${s} && !${b}`}function E(){let P=u.$async?(0,ye._)`(${h}.async ? await ${b}(${n}) : ${b}(${n}))`:(0,ye._)`${b}(${n})`,j=(0,ye._)`(typeof ${b} == "function" ? ${P} : ${b}.test(${n}))`;return(0,ye._)`${b} && ${b} !== true && ${v} === ${e} && !${j}`}}function f(){let m=p.formats[o];if(!m){w();return}if(m===!0)return;let[h,v,b]=E(m);h===e&&r.pass(P());function w(){if(c.strictSchema===!1){p.logger.warn(j());return}throw new Error(j());function j(){return`unknown format "${o}" ignored in schema at path "${l}"`}}function E(j){let Ne=j instanceof RegExp?(0,ye.regexpCode)(j):c.code.formats?(0,ye._)`${c.code.formats}${(0,ye.getProperty)(o)}`:void 0,tt=t.scopeValue("formats",{key:o,ref:j,code:Ne});return typeof j=="object"&&!(j instanceof RegExp)?[j.type||"string",j.validate,(0,ye._)`${tt}.validate`]:["string",j,tt]}function P(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!u.$async)throw new Error("async format in sync schema");return(0,ye._)`await ${b}(${n})`}return typeof v=="function"?(0,ye._)`${b}(${n})`:(0,ye._)`${b}.test(${n})`}}}};jp.default=ZR});var $x=_(Mp=>{"use strict";Object.defineProperty(Mp,"__esModule",{value:!0});var UR=Ex(),FR=[UR.default];Mp.default=FR});var Tx=_(Zn=>{"use strict";Object.defineProperty(Zn,"__esModule",{value:!0});Zn.contentVocabulary=Zn.metadataVocabulary=void 0;Zn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Zn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Px=_(Lp=>{"use strict";Object.defineProperty(Lp,"__esModule",{value:!0});var HR=jv(),BR=Jv(),VR=Sx(),WR=$x(),zx=Tx(),GR=[HR.default,BR.default,(0,VR.default)(),WR.default,zx.metadataVocabulary,zx.contentVocabulary];Lp.default=GR});var Cx=_(Gs=>{"use strict";Object.defineProperty(Gs,"__esModule",{value:!0});Gs.DiscrError=void 0;var Rx;(function(r){r.Tag="tag",r.Mapping="mapping"})(Rx||(Gs.DiscrError=Rx={}))});var Ax=_(qp=>{"use strict";Object.defineProperty(qp,"__esModule",{value:!0});var Un=H(),Dp=Cx(),Ix=Rs(),KR=qi(),JR=Q(),XR={message:({params:{discrError:r,tagName:e}})=>r===Dp.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:r,tag:e,tagName:t}})=>(0,Un._)`{error: ${r}, tag: ${t}, tagValue: ${e}}`},QR={keyword:"discriminator",type:"object",schemaType:"object",error:XR,code(r){let{gen:e,data:t,schema:n,parentSchema:i,it:o}=r,{oneOf:s}=i;if(!o.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!s)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),l=e.const("tag",(0,Un._)`${t}${(0,Un.getProperty)(a)}`);e.if((0,Un._)`typeof ${l} == "string"`,()=>u(),()=>r.error(!1,{discrError:Dp.DiscrError.Tag,tag:l,tagName:a})),r.ok(c);function u(){let f=d();e.if(!1);for(let m in f)e.elseIf((0,Un._)`${l} === ${m}`),e.assign(c,p(f[m]));e.else(),r.error(!1,{discrError:Dp.DiscrError.Mapping,tag:l,tagName:a}),e.endIf()}function p(f){let m=e.name("valid"),h=r.subschema({keyword:"oneOf",schemaProp:f},m);return r.mergeEvaluated(h,Un.Name),m}function d(){var f;let m={},h=b(i),v=!0;for(let P=0;P<s.length;P++){let j=s[P];if(j?.$ref&&!(0,JR.schemaHasRulesButRef)(j,o.self.RULES)){let tt=j.$ref;if(j=Ix.resolveRef.call(o.self,o.schemaEnv.root,o.baseId,tt),j instanceof Ix.SchemaEnv&&(j=j.schema),j===void 0)throw new KR.default(o.opts.uriResolver,o.baseId,tt)}let Ne=(f=j?.properties)===null||f===void 0?void 0:f[a];if(typeof Ne!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);v=v&&(h||b(j)),w(Ne,P)}if(!v)throw new Error(`discriminator: "${a}" must be required`);return m;function b({required:P}){return Array.isArray(P)&&P.includes(a)}function w(P,j){if(P.const)E(P.const,j);else if(P.enum)for(let Ne of P.enum)E(Ne,j);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function E(P,j){if(typeof P!="string"||P in m)throw new Error(`discriminator: "${a}" values must be unique strings`);m[P]=j}}}};qp.default=QR});var Ox=_((WD,YR)=>{YR.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 Up=_((me,Zp)=>{"use strict";Object.defineProperty(me,"__esModule",{value:!0});me.MissingRefError=me.ValidationError=me.CodeGen=me.Name=me.nil=me.stringify=me.str=me._=me.KeywordCxt=me.Ajv=void 0;var eC=Rv(),tC=Px(),rC=Ax(),Nx=Ox(),nC=["/properties"],Ks="http://json-schema.org/draft-07/schema",Fn=class extends eC.default{_addVocabularies(){super._addVocabularies(),tC.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(rC.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(Nx,nC):Nx;this.addMetaSchema(e,Ks,!1),this.refs["http://json-schema.org/schema"]=Ks}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Ks)?Ks:void 0)}};me.Ajv=Fn;Zp.exports=me=Fn;Zp.exports.Ajv=Fn;Object.defineProperty(me,"__esModule",{value:!0});me.default=Fn;var iC=Di();Object.defineProperty(me,"KeywordCxt",{enumerable:!0,get:function(){return iC.KeywordCxt}});var Hn=H();Object.defineProperty(me,"_",{enumerable:!0,get:function(){return Hn._}});Object.defineProperty(me,"str",{enumerable:!0,get:function(){return Hn.str}});Object.defineProperty(me,"stringify",{enumerable:!0,get:function(){return Hn.stringify}});Object.defineProperty(me,"nil",{enumerable:!0,get:function(){return Hn.nil}});Object.defineProperty(me,"Name",{enumerable:!0,get:function(){return Hn.Name}});Object.defineProperty(me,"CodeGen",{enumerable:!0,get:function(){return Hn.CodeGen}});var oC=zs();Object.defineProperty(me,"ValidationError",{enumerable:!0,get:function(){return oC.default}});var sC=qi();Object.defineProperty(me,"MissingRefError",{enumerable:!0,get:function(){return sC.default}})});var Fx=_(Ot=>{"use strict";Object.defineProperty(Ot,"__esModule",{value:!0});Ot.formatNames=Ot.fastFormats=Ot.fullFormats=void 0;function At(r,e){return{validate:r,compare:e}}Ot.fullFormats={date:At(Dx,Vp),time:At(Hp(!0),Wp),"date-time":At(jx(!0),Zx),"iso-time":At(Hp(),qx),"iso-date-time":At(jx(),Ux),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:dC,"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:yC,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:mC,int32:{type:"number",validate:gC},int64:{type:"number",validate:vC},float:{type:"number",validate:Lx},double:{type:"number",validate:Lx},password:!0,binary:!0};Ot.fastFormats={...Ot.fullFormats,date:At(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Vp),time:At(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Wp),"date-time":At(/^\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,Zx),"iso-time":At(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,qx),"iso-date-time":At(/^\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,Ux),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};Ot.formatNames=Object.keys(Ot.fullFormats);function aC(r){return r%4===0&&(r%100!==0||r%400===0)}var cC=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,lC=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Dx(r){let e=cC.exec(r);if(!e)return!1;let t=+e[1],n=+e[2],i=+e[3];return n>=1&&n<=12&&i>=1&&i<=(n===2&&aC(t)?29:lC[n])}function Vp(r,e){if(r&&e)return r>e?1:r<e?-1:0}var Fp=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Hp(r){return function(t){let n=Fp.exec(t);if(!n)return!1;let i=+n[1],o=+n[2],s=+n[3],a=n[4],c=n[5]==="-"?-1:1,l=+(n[6]||0),u=+(n[7]||0);if(l>23||u>59||r&&!a)return!1;if(i<=23&&o<=59&&s<60)return!0;let p=o-u*c,d=i-l*c-(p<0?1:0);return(d===23||d===-1)&&(p===59||p===-1)&&s<61}}function Wp(r,e){if(!(r&&e))return;let t=new Date("2020-01-01T"+r).valueOf(),n=new Date("2020-01-01T"+e).valueOf();if(t&&n)return t-n}function qx(r,e){if(!(r&&e))return;let t=Fp.exec(r),n=Fp.exec(e);if(t&&n)return r=t[1]+t[2]+t[3],e=n[1]+n[2]+n[3],r>e?1:r<e?-1:0}var Bp=/t|\s/i;function jx(r){let e=Hp(r);return function(n){let i=n.split(Bp);return i.length===2&&Dx(i[0])&&e(i[1])}}function Zx(r,e){if(!(r&&e))return;let t=new Date(r).valueOf(),n=new Date(e).valueOf();if(t&&n)return t-n}function Ux(r,e){if(!(r&&e))return;let[t,n]=r.split(Bp),[i,o]=e.split(Bp),s=Vp(t,i);if(s!==void 0)return s||Wp(n,o)}var uC=/\/|:/,pC=/^(?:[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 dC(r){return uC.test(r)&&pC.test(r)}var Mx=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function mC(r){return Mx.lastIndex=0,Mx.test(r)}var fC=-(2**31),hC=2**31-1;function gC(r){return Number.isInteger(r)&&r<=hC&&r>=fC}function vC(r){return Number.isInteger(r)}function Lx(){return!0}var xC=/[^\\]\\Z/;function yC(r){if(xC.test(r))return!1;try{return new RegExp(r),!0}catch{return!1}}});var Hx=_(Bn=>{"use strict";Object.defineProperty(Bn,"__esModule",{value:!0});Bn.formatLimitDefinition=void 0;var _C=Up(),bt=H(),xr=bt.operators,Js={formatMaximum:{okStr:"<=",ok:xr.LTE,fail:xr.GT},formatMinimum:{okStr:">=",ok:xr.GTE,fail:xr.LT},formatExclusiveMaximum:{okStr:"<",ok:xr.LT,fail:xr.GTE},formatExclusiveMinimum:{okStr:">",ok:xr.GT,fail:xr.LTE}},bC={message:({keyword:r,schemaCode:e})=>(0,bt.str)`should be ${Js[r].okStr} ${e}`,params:({keyword:r,schemaCode:e})=>(0,bt._)`{comparison: ${Js[r].okStr}, limit: ${e}}`};Bn.formatLimitDefinition={keyword:Object.keys(Js),type:"string",schemaType:"string",$data:!0,error:bC,code(r){let{gen:e,data:t,schemaCode:n,keyword:i,it:o}=r,{opts:s,self:a}=o;if(!s.validateFormats)return;let c=new _C.KeywordCxt(o,a.RULES.all.format.definition,"format");c.$data?l():u();function l(){let d=e.scopeValue("formats",{ref:a.formats,code:s.code.formats}),f=e.const("fmt",(0,bt._)`${d}[${c.schemaCode}]`);r.fail$data((0,bt.or)((0,bt._)`typeof ${f} != "object"`,(0,bt._)`${f} instanceof RegExp`,(0,bt._)`typeof ${f}.compare != "function"`,p(f)))}function u(){let d=c.schema,f=a.formats[d];if(!f||f===!0)return;if(typeof f!="object"||f instanceof RegExp||typeof f.compare!="function")throw new Error(`"${i}": format "${d}" does not define "compare" function`);let m=e.scopeValue("formats",{key:d,ref:f,code:s.code.formats?(0,bt._)`${s.code.formats}${(0,bt.getProperty)(d)}`:void 0});r.fail$data(p(m))}function p(d){return(0,bt._)`${d}.compare(${t}, ${n}) ${Js[i].fail} 0`}},dependencies:["format"]};var wC=r=>(r.addKeyword(Bn.formatLimitDefinition),r);Bn.default=wC});var Gx=_((eo,Wx)=>{"use strict";Object.defineProperty(eo,"__esModule",{value:!0});var Vn=Fx(),kC=Hx(),Gp=H(),Bx=new Gp.Name("fullFormats"),SC=new Gp.Name("fastFormats"),Kp=(r,e={keywords:!0})=>{if(Array.isArray(e))return Vx(r,e,Vn.fullFormats,Bx),r;let[t,n]=e.mode==="fast"?[Vn.fastFormats,SC]:[Vn.fullFormats,Bx],i=e.formats||Vn.formatNames;return Vx(r,i,t,n),e.keywords&&(0,kC.default)(r),r};Kp.get=(r,e="full")=>{let n=(e==="fast"?Vn.fastFormats:Vn.fullFormats)[r];if(!n)throw new Error(`Unknown format "${r}"`);return n};function Vx(r,e,t,n){var i,o;(i=(o=r.opts.code).formats)!==null&&i!==void 0||(o.formats=(0,Gp._)`require("ajv-formats/dist/formats").${n}`);for(let s of e)r.addFormat(s,t[s])}Wx.exports=eo=Kp;Object.defineProperty(eo,"__esModule",{value:!0});eo.default=Kp});var Iy=_((PZ,Cy)=>{"use strict";var Py=N("url"),Ry=1800,hd=class{constructor(e){this.options=e||{},this.cookies=[]}set(e,t){let n=Py.parse(t||""),i=this.parse(e),o;return i.domain?(o=i.domain.replace(/^\./,""),(n.hostname.length<o.length||("."+n.hostname).substr(-o.length+1)!=="."+o)&&(i.domain=n.hostname)):i.domain=n.hostname,i.path||(i.path=this.getPath(n.pathname)),i.expires||(i.expires=new Date(Date.now()+(Number(this.options.sessionTimeout||Ry)||Ry)*1e3)),this.add(i)}get(e){return this.list(e).map(t=>t.name+"="+t.value).join("; ")}list(e){let t=[];for(let n=this.cookies.length-1;n>=0;n--){let i=this.cookies[n];if(this.isExpired(i)){this.cookies.splice(n,1);continue}this.match(i,e)&&t.unshift(i)}return t}parse(e){let t={};return(e||"").toString().split(";").forEach(n=>{let i=n.split("="),o=i.shift().trim().toLowerCase(),s=i.join("=").trim(),a;if(o)switch(o){case"expires":s=new Date(s),s.toString()!=="Invalid Date"&&(t.expires=s);break;case"path":t.path=s;break;case"domain":a=s.toLowerCase(),a.length&&a.charAt(0)!=="."&&(a="."+a),t.domain=a;break;case"max-age":t.expires=new Date(Date.now()+(Number(s)||0)*1e3);break;case"secure":t.secure=!0;break;case"httponly":t.httponly=!0;break;default:t.name||(t.name=o,t.value=s)}}),t}match(e,t){let n=Py.parse(t||"");return!(n.hostname!==e.domain&&(e.domain.charAt(0)!=="."||("."+n.hostname).substr(-e.domain.length)!==e.domain)||this.getPath(n.pathname).substr(0,e.path.length)!==e.path||e.secure&&n.protocol!=="https:")}add(e){if(!e||!e.name)return!1;for(let t=0,n=this.cookies.length;t<n;t++)if(this.compare(this.cookies[t],e))return this.isExpired(e)?(this.cookies.splice(t,1),!1):(this.cookies[t]=e,!0);return this.isExpired(e)||this.cookies.push(e),!0}compare(e,t){return e.name===t.name&&e.path===t.path&&e.domain===t.domain&&e.secure===t.secure&&e.httponly===t.httponly}isExpired(e){return e.expires&&e.expires<new Date||!e.value}getPath(e){let t=(e||"/").split("/");return t.pop(),t=t.join("/").trim(),t.charAt(0)!=="/"&&(t="/"+t),t.substr(-1)!=="/"&&(t+="/"),t}};Cy.exports=hd});var wt=_((RZ,pI)=>{pI.exports={name:"nodemailer",version:"8.0.5",description:"Easy as cake e-mail sending from your Node.js applications",main:"lib/nodemailer.js",scripts:{test:"node --test --test-concurrency=1 test/**/*.test.js test/**/*-test.js","test:coverage":"c8 node --test --test-concurrency=1 test/**/*.test.js test/**/*-test.js",format:'prettier --write "**/*.{js,json,md}"',"format:check":'prettier --check "**/*.{js,json,md}"',lint:"eslint .","lint:fix":"eslint . --fix",update:"rm -rf node_modules/ package-lock.json && ncu -u && npm install","test:syntax":'docker run --rm -v "$PWD:/app:ro" -w /app node:6-alpine node test/syntax-compat.js'},repository:{type:"git",url:"https://github.com/nodemailer/nodemailer.git"},keywords:["Nodemailer"],author:"Andris Reinman",license:"MIT-0",bugs:{url:"https://github.com/nodemailer/nodemailer/issues"},homepage:"https://nodemailer.com/",devDependencies:{"@aws-sdk/client-sesv2":"3.1025.0",bunyan:"1.8.15",c8:"11.0.0",eslint:"10.2.0","eslint-config-prettier":"10.1.8",globals:"17.4.0",libbase64:"1.3.0",libmime:"5.3.7",libqp:"2.1.1","nodemailer-ntlm-auth":"1.0.4",prettier:"3.8.1",proxy:"1.0.2","proxy-test-server":"1.0.0","smtp-server":"3.18.3"},engines:{node:">=6.0.0"}}});var kt=_((CZ,gd)=>{"use strict";var Ay={ECONNECTION:"Connection closed unexpectedly",ETIMEDOUT:"Connection or operation timed out",ESOCKET:"Socket-level error",EDNS:"DNS resolution failed",ETLS:"TLS handshake or STARTTLS failed",EREQUIRETLS:"REQUIRETLS not supported by server (RFC 8689)",EPROTOCOL:"Invalid SMTP server response",EENVELOPE:"Invalid mail envelope (sender or recipients)",EMESSAGE:"Message delivery error",ESTREAM:"Stream processing error",EAUTH:"Authentication failed",ENOAUTH:"Authentication credentials not provided",EOAUTH2:"OAuth2 token generation or refresh error",EMAXLIMIT:"Pool resource limit reached (max messages per connection)",ESENDMAIL:"Sendmail command error",ESES:"AWS SES transport error",ECONFIG:"Invalid configuration",EPROXY:"Proxy connection error",EFILEACCESS:"File access rejected (disableFileAccess is set)",EURLACCESS:"URL access rejected (disableUrlAccess is set)",EFETCH:"HTTP fetch error"};gd.exports={ERROR_CODES:Ay};for(let r of Object.keys(Ay))gd.exports[r]=r});var so=_((IZ,vd)=>{"use strict";var dI=N("http"),mI=N("https"),Oy=N("url"),fI=N("zlib"),{PassThrough:hI}=N("stream"),Ny=Iy(),gI=wt(),vI=N("net"),Lt=kt(),xI=5;vd.exports=function(r,e){return jy(r,e)};vd.exports.Cookies=Ny;function jy(r,e){e=e||{},e.fetchRes=e.fetchRes||new hI,e.cookies=e.cookies||new Ny,e.redirects=e.redirects||0,e.maxRedirects=isNaN(e.maxRedirects)?xI:e.maxRedirects,e.cookie&&([].concat(e.cookie||[]).forEach(d=>{e.cookies.set(d,r)}),e.cookie=!1);let t=e.fetchRes,n=Oy.parse(r),i=(e.method||"").toString().trim().toUpperCase()||"GET",o=!1,s,a,c=n.protocol==="https:"?mI:dI,l={"accept-encoding":"gzip,deflate","user-agent":"nodemailer/"+gI.version};if(Object.keys(e.headers||{}).forEach(d=>{l[d.toLowerCase().trim()]=e.headers[d]}),e.userAgent&&(l["user-agent"]=e.userAgent),n.auth&&(l.Authorization="Basic "+Buffer.from(n.auth).toString("base64")),(s=e.cookies.get(r))&&(l.cookie=s),e.body){if(e.contentType!==!1&&(l["Content-Type"]=e.contentType||"application/x-www-form-urlencoded"),typeof e.body.pipe=="function")l["Transfer-Encoding"]="chunked",a=e.body,a.on("error",d=>{o||(o=!0,d.code=Lt.EFETCH,d.sourceUrl=r,t.emit("error",d))});else{if(e.body instanceof Buffer)a=e.body;else if(typeof e.body=="object")try{a=Buffer.from(Object.keys(e.body).map(d=>{let f=e.body[d].toString().trim();return encodeURIComponent(d)+"="+encodeURIComponent(f)}).join("&"))}catch(d){if(o)return;o=!0,d.code=Lt.EFETCH,d.sourceUrl=r,t.emit("error",d);return}else a=Buffer.from(e.body.toString().trim());l["Content-Type"]=e.contentType||"application/x-www-form-urlencoded",l["Content-Length"]=a.length}i=(e.method||"").toString().trim().toUpperCase()||"POST"}let u,p={method:i,host:n.hostname,path:n.path,port:n.port?n.port:n.protocol==="https:"?443:80,headers:l,rejectUnauthorized:!1,agent:!1};e.tls&&Object.assign(p,e.tls),n.protocol==="https:"&&n.hostname&&n.hostname!==p.host&&!vI.isIP(n.hostname)&&!p.servername&&(p.servername=n.hostname);try{u=c.request(p)}catch(d){return o=!0,setImmediate(()=>{d.code=Lt.EFETCH,d.sourceUrl=r,t.emit("error",d)}),t}return e.timeout&&u.setTimeout(e.timeout,()=>{if(o)return;o=!0,u.abort();let d=new Error("Request Timeout");d.code=Lt.EFETCH,d.sourceUrl=r,t.emit("error",d)}),u.on("error",d=>{o||(o=!0,d.code=Lt.EFETCH,d.sourceUrl=r,t.emit("error",d))}),u.on("response",d=>{let f;if(!o){switch(d.headers["content-encoding"]){case"gzip":case"deflate":f=fI.createUnzip();break}if(d.headers["set-cookie"]&&[].concat(d.headers["set-cookie"]||[]).forEach(m=>{e.cookies.set(m,r)}),[301,302,303,307,308].includes(d.statusCode)&&d.headers.location){if(e.redirects++,e.redirects>e.maxRedirects){o=!0;let m=new Error("Maximum redirect count exceeded");m.code=Lt.EFETCH,m.sourceUrl=r,t.emit("error",m),u.abort();return}return e.method="GET",e.body=!1,jy(Oy.resolve(r,d.headers.location),e)}if(t.statusCode=d.statusCode,t.headers=d.headers,d.statusCode>=300&&!e.allowErrorResponse){o=!0;let m=new Error("Invalid status code "+d.statusCode);m.code=Lt.EFETCH,m.sourceUrl=r,t.emit("error",m),u.abort();return}d.on("error",m=>{o||(o=!0,m.code=Lt.EFETCH,m.sourceUrl=r,t.emit("error",m),u.abort())}),f?(d.pipe(f).pipe(t),f.on("error",m=>{o||(o=!0,m.code=Lt.EFETCH,m.sourceUrl=r,t.emit("error",m),u.abort())})):d.pipe(t)}}),setImmediate(()=>{if(a)try{if(typeof a.pipe=="function")return a.pipe(u);u.write(a)}catch(d){o=!0,d.code=Lt.EFETCH,d.sourceUrl=r,t.emit("error",d);return}u.end()}),t}});var qe=_((AZ,Se)=>{"use strict";var yI=N("url"),_I=N("util"),bI=N("fs"),wI=so(),Dt=N("dns"),kI=N("net"),SI=N("os"),ao=5*60*1e3,EI=30*1e3,My=1e3,pa=0;Se.exports._lastCacheCleanup=()=>pa;Se.exports._resetCacheCleanup=()=>{pa=0};var Dy;try{Dy=SI.networkInterfaces()}catch{}Se.exports.networkInterfaces=Dy;var qy=(r,e)=>{let t=Se.exports.networkInterfaces;return t?Object.keys(t).map(n=>t[n]).reduce((n,i)=>n.concat(i),[]).filter(n=>!n.internal||e).some(n=>n.family==="IPv"+r||n.family===r):!0},Ly=(r,e,t,n)=>{if(t=t||{},!qy(r,t.allowInternalNetworkInterfaces))return n(null,[]);(Dt.Resolver?new Dt.Resolver(t):Dt)["resolve"+r](e,(o,s)=>{if(o){switch(o.code){case Dt.NODATA:case Dt.NOTFOUND:case Dt.NOTIMP:case Dt.SERVFAIL:case Dt.CONNREFUSED:case Dt.REFUSED:case"EAI_AGAIN":return n(null,[])}return n(o)}return n(null,Array.isArray(s)?s:[].concat(s||[]))})},dt=Se.exports.dnsCache=new Map,_r=(r,e)=>{if(!r)return Object.assign({},e||{});let t=r.addresses||[],n=t.length>0?t[Math.floor(Math.random()*t.length)]:null;return Object.assign({servername:r.servername,host:n,_addresses:t},e||{})};Se.exports.resolveHostname=(r,e)=>{if(r=r||{},!r.host&&r.servername&&(r.host=r.servername),!r.host||kI.isIP(r.host)){let a={addresses:[r.host],servername:r.servername||!1};return e(null,_r(a,{cached:!1}))}let t;if(dt.has(r.host)){t=dt.get(r.host);let a=Date.now();if(a-pa>EI){pa=a;for(let[c,l]of dt.entries())l.expires&&l.expires<a&&dt.delete(c);if(dt.size>My){let c=Math.floor(My*.1);Array.from(dt.keys()).slice(0,c).forEach(u=>dt.delete(u))}}if(!t.expires||t.expires>=a)return e(null,_r(t.value,{cached:!0}))}let n=[],i=[],o=null,s=null;Ly(4,r.host,r,(a,c)=>{a?o=a:n=c||[],Ly(6,r.host,r,(l,u)=>{l?s=l:i=u||[];let p=n.concat(i);if(p.length){let d={addresses:p,servername:r.servername||r.host};return dt.set(r.host,{value:d,expires:Date.now()+(r.dnsTtl||ao)}),e(null,_r(d,{cached:!1}))}if(o&&s&&t)return dt.set(r.host,{value:t.value,expires:Date.now()+(r.dnsTtl||ao)}),e(null,_r(t.value,{cached:!0,error:o}));try{Dt.lookup(r.host,{all:!0},(d,f)=>{if(d)return t?(dt.set(r.host,{value:t.value,expires:Date.now()+(r.dnsTtl||ao)}),e(null,_r(t.value,{cached:!0,error:d}))):e(d);let m=f?f.filter(v=>qy(v.family)).map(v=>v.address):[];if(f&&f.length&&!m.length&&console.warn(`Failed to resolve IPv${f[0].family} addresses with current network`),!m.length&&t)return e(null,_r(t.value,{cached:!0}));let h={addresses:m.length?m:[r.host],servername:r.servername||r.host};return dt.set(r.host,{value:h,expires:Date.now()+(r.dnsTtl||ao)}),e(null,_r(h,{cached:!1}))})}catch(d){return t?(dt.set(r.host,{value:t.value,expires:Date.now()+(r.dnsTtl||ao)}),e(null,_r(t.value,{cached:!0,error:d}))):e(o||s||d)}})})};Se.exports.parseConnectionUrl=r=>{r=r||"";let e={},t=yI.parse(r,!0);switch(t.protocol){case"smtp:":e.secure=!1;break;case"smtps:":e.secure=!0;break;case"direct:":e.direct=!0;break}if(!isNaN(t.port)&&Number(t.port)&&(e.port=Number(t.port)),t.hostname&&(e.host=t.hostname),t.auth){let n=t.auth.split(":");e.auth={user:n.shift(),pass:n.join(":")}}return Object.keys(t.query||{}).forEach(n=>{let i=e,o=n,s=t.query[n];switch(isNaN(s)||(s=Number(s)),s){case"true":s=!0;break;case"false":s=!1;break}if(n.indexOf("tls.")===0)o=n.substr(4),e.tls||(e.tls={}),i=e.tls;else if(n.indexOf(".")>=0)return;o in i||(i[o]=s)}),e};Se.exports._logFunc=(r,e,t,n,i,...o)=>{let s=Object.assign({},t||{},n||{});delete s.level,r[e](s,i,...o)};Se.exports.getLogger=(r,e)=>{r=r||{};let t={},n=["trace","debug","info","warn","error","fatal"];if(!r.logger)return n.forEach(o=>{t[o]=()=>!1}),t;let i=r.logger===!0?$I(n):r.logger;return n.forEach(o=>{t[o]=(s,a,...c)=>{Se.exports._logFunc(i,o,e,s,a,...c)}}),t};Se.exports.callbackPromise=(r,e)=>function(){let t=Array.from(arguments),n=t.shift();n?e(n):r(...t)};Se.exports.parseDataURI=r=>{if(typeof r!="string"||!r.startsWith("data:"))return null;let e=r.indexOf(",");if(e===-1)return null;let t=r.substring(e+1),n=r.substring(5,e),i,o=n.split(";");if(o.length>0){let l=o[o.length-1].toLowerCase().trim();["base64","utf8","utf-8"].includes(l)&&l.indexOf("=")===-1&&(i=l,o.pop())}let s=o.length>0?o.shift():"application/octet-stream",a={};for(let l=0;l<o.length;l++){let u=o[l],p=u.indexOf("=");if(p>0){let d=u.substring(0,p).trim(),f=u.substring(p+1).trim();d&&(a[d]=f)}}let c;try{if(i==="base64")c=Buffer.from(t,"base64");else try{c=Buffer.from(decodeURIComponent(t))}catch{c=Buffer.from(t)}}catch{c=Buffer.alloc(0)}return{data:c,encoding:i||null,contentType:s||"application/octet-stream",params:a}};Se.exports.resolveContent=(r,e,t)=>{let n;t||(n=new Promise((s,a)=>{t=Se.exports.callbackPromise(s,a)}));let i=r&&r[e]&&r[e].content||r[e],o=(typeof r[e]=="object"&&r[e].encoding||"utf8").toString().toLowerCase().replace(/[-_\s]/g,"");if(!i)return t(null,i);if(typeof i=="object"){if(typeof i.pipe=="function")return xd(i,(s,a)=>{if(s)return t(s);r[e].content?r[e].content=a:r[e]=a,t(null,a)});if(/^https?:\/\//i.test(i.path||i.href))return xd(wI(i.path||i.href),t);if(/^data:/i.test(i.path||i.href)){let s=Se.exports.parseDataURI(i.path||i.href);return!s||!s.data?t(null,Buffer.from(0)):t(null,s.data)}else if(i.path)return xd(bI.createReadStream(i.path),t)}return typeof r[e].content=="string"&&!["utf8","usascii","ascii"].includes(o)&&(i=Buffer.from(r[e].content,o)),setImmediate(()=>t(null,i)),n};Se.exports.assign=function(){let r=Array.from(arguments),e=r.shift()||{};return r.forEach(t=>{Object.keys(t||{}).forEach(n=>{["tls","auth"].includes(n)&&t[n]&&typeof t[n]=="object"?e[n]=Object.assign(e[n]||{},t[n]):e[n]=t[n]})}),e};Se.exports.encodeXText=r=>{if(!/[^\x21-\x2A\x2C-\x3C\x3E-\x7E]/.test(r))return r;let e=Buffer.from(r),t="";for(let n=0,i=e.length;n<i;n++){let o=e[n];o<33||o>126||o===43||o===61?t+="+"+(o<16?"0":"")+o.toString(16).toUpperCase():t+=String.fromCharCode(o)}return t};function xd(r,e){let t=!1,n=[],i=0;r.on("error",o=>{t||(t=!0,e(o))}),r.on("readable",()=>{let o;for(;(o=r.read())!==null;)n.push(o),i+=o.length}),r.on("end",()=>{if(t)return;t=!0;let o;try{o=Buffer.concat(n,i)}catch(s){return e(s)}e(null,o)})}function $I(r){let e=r.reduce((o,s)=>Math.max(o,s.length),0),t=new Map;r.forEach(o=>{let s=o.toUpperCase();s.length<e&&(s+=" ".repeat(e-s.length)),t.set(o,s)});let n=(o,s,a,...c)=>{let l="";s&&(s.tnx==="server"?l="S: ":s.tnx==="client"&&(l="C: "),s.sid&&(l="["+s.sid+"] "+l),s.cid&&(l="[#"+s.cid+"] "+l)),a=_I.format(a,...c),a.split(/\r?\n/).forEach(u=>{console.log("[%s] %s %s",new Date().toISOString().substr(0,19).replace(/T/," "),t.get(o),l+u)})},i={};return r.forEach(o=>{i[o]=n.bind(null,o)}),i}});var yd=_((OZ,Hy)=>{"use strict";var TI=N("path"),Zy="application/octet-stream",zI="bin",Uy=new Map([["application/acad","dwg"],["application/applixware","aw"],["application/arj","arj"],["application/atom+xml","xml"],["application/atomcat+xml","atomcat"],["application/atomsvc+xml","atomsvc"],["application/base64",["mm","mme"]],["application/binhex","hqx"],["application/binhex4","hqx"],["application/book",["book","boo"]],["application/ccxml+xml,","ccxml"],["application/cdf","cdf"],["application/cdmi-capability","cdmia"],["application/cdmi-container","cdmic"],["application/cdmi-domain","cdmid"],["application/cdmi-object","cdmio"],["application/cdmi-queue","cdmiq"],["application/clariscad","ccad"],["application/commonground","dp"],["application/cu-seeme","cu"],["application/davmount+xml","davmount"],["application/drafting","drw"],["application/dsptype","tsp"],["application/dssc+der","dssc"],["application/dssc+xml","xdssc"],["application/dxf","dxf"],["application/ecmascript",["js","es"]],["application/emma+xml","emma"],["application/envoy","evy"],["application/epub+zip","epub"],["application/excel",["xls","xl","xla","xlb","xlc","xld","xlk","xll","xlm","xlt","xlv","xlw"]],["application/exi","exi"],["application/font-tdpfr","pfr"],["application/fractals","fif"],["application/freeloader","frl"],["application/futuresplash","spl"],["application/geo+json","geojson"],["application/gnutar","tgz"],["application/groupwise","vew"],["application/hlp","hlp"],["application/hta","hta"],["application/hyperstudio","stk"],["application/i-deas","unv"],["application/iges",["iges","igs"]],["application/inf","inf"],["application/internet-property-stream","acx"],["application/ipfix","ipfix"],["application/java","class"],["application/java-archive","jar"],["application/java-byte-code","class"],["application/java-serialized-object","ser"],["application/java-vm","class"],["application/javascript","js"],["application/json","json"],["application/lha","lha"],["application/lzx","lzx"],["application/mac-binary","bin"],["application/mac-binhex","hqx"],["application/mac-binhex40","hqx"],["application/mac-compactpro","cpt"],["application/macbinary","bin"],["application/mads+xml","mads"],["application/marc","mrc"],["application/marcxml+xml","mrcx"],["application/mathematica","ma"],["application/mathml+xml","mathml"],["application/mbedlet","mbd"],["application/mbox","mbox"],["application/mcad","mcd"],["application/mediaservercontrol+xml","mscml"],["application/metalink4+xml","meta4"],["application/mets+xml","mets"],["application/mime","aps"],["application/mods+xml","mods"],["application/mp21","m21"],["application/mp4","mp4"],["application/mspowerpoint",["ppt","pot","pps","ppz"]],["application/msword",["doc","dot","w6w","wiz","word"]],["application/mswrite","wri"],["application/mxf","mxf"],["application/netmc","mcp"],["application/octet-stream",["*"]],["application/oda","oda"],["application/oebps-package+xml","opf"],["application/ogg","ogx"],["application/olescript","axs"],["application/onenote","onetoc"],["application/patch-ops-error+xml","xer"],["application/pdf","pdf"],["application/pgp-encrypted","asc"],["application/pgp-signature","pgp"],["application/pics-rules","prf"],["application/pkcs-12","p12"],["application/pkcs-crl","crl"],["application/pkcs10","p10"],["application/pkcs7-mime",["p7c","p7m"]],["application/pkcs7-signature","p7s"],["application/pkcs8","p8"],["application/pkix-attr-cert","ac"],["application/pkix-cert",["cer","crt"]],["application/pkix-crl","crl"],["application/pkix-pkipath","pkipath"],["application/pkixcmp","pki"],["application/plain","text"],["application/pls+xml","pls"],["application/postscript",["ps","ai","eps"]],["application/powerpoint","ppt"],["application/pro_eng",["part","prt"]],["application/prs.cww","cww"],["application/pskc+xml","pskcxml"],["application/rdf+xml","rdf"],["application/reginfo+xml","rif"],["application/relax-ng-compact-syntax","rnc"],["application/resource-lists+xml","rl"],["application/resource-lists-diff+xml","rld"],["application/ringing-tones","rng"],["application/rls-services+xml","rs"],["application/rsd+xml","rsd"],["application/rss+xml","xml"],["application/rtf",["rtf","rtx"]],["application/sbml+xml","sbml"],["application/scvp-cv-request","scq"],["application/scvp-cv-response","scs"],["application/scvp-vp-request","spq"],["application/scvp-vp-response","spp"],["application/sdp","sdp"],["application/sea","sea"],["application/set","set"],["application/set-payment-initiation","setpay"],["application/set-registration-initiation","setreg"],["application/shf+xml","shf"],["application/sla","stl"],["application/smil",["smi","smil"]],["application/smil+xml","smi"],["application/solids","sol"],["application/sounder","sdr"],["application/sparql-query","rq"],["application/sparql-results+xml","srx"],["application/srgs","gram"],["application/srgs+xml","grxml"],["application/sru+xml","sru"],["application/ssml+xml","ssml"],["application/step",["step","stp"]],["application/streamingmedia","ssm"],["application/tei+xml","tei"],["application/thraud+xml","tfi"],["application/timestamped-data","tsd"],["application/toolbook","tbk"],["application/vda","vda"],["application/vnd.3gpp.pic-bw-large","plb"],["application/vnd.3gpp.pic-bw-small","psb"],["application/vnd.3gpp.pic-bw-var","pvb"],["application/vnd.3gpp2.tcap","tcap"],["application/vnd.3m.post-it-notes","pwn"],["application/vnd.accpac.simply.aso","aso"],["application/vnd.accpac.simply.imp","imp"],["application/vnd.acucobol","acu"],["application/vnd.acucorp","atc"],["application/vnd.adobe.air-application-installer-package+zip","air"],["application/vnd.adobe.fxp","fxp"],["application/vnd.adobe.xdp+xml","xdp"],["application/vnd.adobe.xfdf","xfdf"],["application/vnd.ahead.space","ahead"],["application/vnd.airzip.filesecure.azf","azf"],["application/vnd.airzip.filesecure.azs","azs"],["application/vnd.amazon.ebook","azw"],["application/vnd.americandynamics.acc","acc"],["application/vnd.amiga.ami","ami"],["application/vnd.android.package-archive","apk"],["application/vnd.anser-web-certificate-issue-initiation","cii"],["application/vnd.anser-web-funds-transfer-initiation","fti"],["application/vnd.antix.game-component","atx"],["application/vnd.apple.installer+xml","mpkg"],["application/vnd.apple.mpegurl","m3u8"],["application/vnd.aristanetworks.swi","swi"],["application/vnd.audiograph","aep"],["application/vnd.blueice.multipass","mpm"],["application/vnd.bmi","bmi"],["application/vnd.businessobjects","rep"],["application/vnd.chemdraw+xml","cdxml"],["application/vnd.chipnuts.karaoke-mmd","mmd"],["application/vnd.cinderella","cdy"],["application/vnd.claymore","cla"],["application/vnd.cloanto.rp9","rp9"],["application/vnd.clonk.c4group","c4g"],["application/vnd.cluetrust.cartomobile-config","c11amc"],["application/vnd.cluetrust.cartomobile-config-pkg","c11amz"],["application/vnd.commonspace","csp"],["application/vnd.contact.cmsg","cdbcmsg"],["application/vnd.cosmocaller","cmc"],["application/vnd.crick.clicker","clkx"],["application/vnd.crick.clicker.keyboard","clkk"],["application/vnd.crick.clicker.palette","clkp"],["application/vnd.crick.clicker.template","clkt"],["application/vnd.crick.clicker.wordbank","clkw"],["application/vnd.criticaltools.wbs+xml","wbs"],["application/vnd.ctc-posml","pml"],["application/vnd.cups-ppd","ppd"],["application/vnd.curl.car","car"],["application/vnd.curl.pcurl","pcurl"],["application/vnd.data-vision.rdz","rdz"],["application/vnd.denovo.fcselayout-link","fe_launch"],["application/vnd.dna","dna"],["application/vnd.dolby.mlp","mlp"],["application/vnd.dpgraph","dpg"],["application/vnd.dreamfactory","dfac"],["application/vnd.dvb.ait","ait"],["application/vnd.dvb.service","svc"],["application/vnd.dynageo","geo"],["application/vnd.ecowin.chart","mag"],["application/vnd.enliven","nml"],["application/vnd.epson.esf","esf"],["application/vnd.epson.msf","msf"],["application/vnd.epson.quickanime","qam"],["application/vnd.epson.salt","slt"],["application/vnd.epson.ssf","ssf"],["application/vnd.eszigno3+xml","es3"],["application/vnd.ezpix-album","ez2"],["application/vnd.ezpix-package","ez3"],["application/vnd.fdf","fdf"],["application/vnd.fdsn.seed","seed"],["application/vnd.flographit","gph"],["application/vnd.fluxtime.clip","ftc"],["application/vnd.framemaker","fm"],["application/vnd.frogans.fnc","fnc"],["application/vnd.frogans.ltf","ltf"],["application/vnd.fsc.weblaunch","fsc"],["application/vnd.fujitsu.oasys","oas"],["application/vnd.fujitsu.oasys2","oa2"],["application/vnd.fujitsu.oasys3","oa3"],["application/vnd.fujitsu.oasysgp","fg5"],["application/vnd.fujitsu.oasysprs","bh2"],["application/vnd.fujixerox.ddd","ddd"],["application/vnd.fujixerox.docuworks","xdw"],["application/vnd.fujixerox.docuworks.binder","xbd"],["application/vnd.fuzzysheet","fzs"],["application/vnd.genomatix.tuxedo","txd"],["application/vnd.geogebra.file","ggb"],["application/vnd.geogebra.tool","ggt"],["application/vnd.geometry-explorer","gex"],["application/vnd.geonext","gxt"],["application/vnd.geoplan","g2w"],["application/vnd.geospace","g3w"],["application/vnd.gmx","gmx"],["application/vnd.google-earth.kml+xml","kml"],["application/vnd.google-earth.kmz","kmz"],["application/vnd.grafeq","gqf"],["application/vnd.groove-account","gac"],["application/vnd.groove-help","ghf"],["application/vnd.groove-identity-message","gim"],["application/vnd.groove-injector","grv"],["application/vnd.groove-tool-message","gtm"],["application/vnd.groove-tool-template","tpl"],["application/vnd.groove-vcard","vcg"],["application/vnd.hal+xml","hal"],["application/vnd.handheld-entertainment+xml","zmm"],["application/vnd.hbci","hbci"],["application/vnd.hhe.lesson-player","les"],["application/vnd.hp-hpgl",["hgl","hpg","hpgl"]],["application/vnd.hp-hpid","hpid"],["application/vnd.hp-hps","hps"],["application/vnd.hp-jlyt","jlt"],["application/vnd.hp-pcl","pcl"],["application/vnd.hp-pclxl","pclxl"],["application/vnd.hydrostatix.sof-data","sfd-hdstx"],["application/vnd.hzn-3d-crossword","x3d"],["application/vnd.ibm.minipay","mpy"],["application/vnd.ibm.modcap","afp"],["application/vnd.ibm.rights-management","irm"],["application/vnd.ibm.secure-container","sc"],["application/vnd.iccprofile","icc"],["application/vnd.igloader","igl"],["application/vnd.immervision-ivp","ivp"],["application/vnd.immervision-ivu","ivu"],["application/vnd.insors.igm","igm"],["application/vnd.intercon.formnet","xpw"],["application/vnd.intergeo","i2g"],["application/vnd.intu.qbo","qbo"],["application/vnd.intu.qfx","qfx"],["application/vnd.ipunplugged.rcprofile","rcprofile"],["application/vnd.irepository.package+xml","irp"],["application/vnd.is-xpr","xpr"],["application/vnd.isac.fcs","fcs"],["application/vnd.jam","jam"],["application/vnd.jcp.javame.midlet-rms","rms"],["application/vnd.jisp","jisp"],["application/vnd.joost.joda-archive","joda"],["application/vnd.kahootz","ktz"],["application/vnd.kde.karbon","karbon"],["application/vnd.kde.kchart","chrt"],["application/vnd.kde.kformula","kfo"],["application/vnd.kde.kivio","flw"],["application/vnd.kde.kontour","kon"],["application/vnd.kde.kpresenter","kpr"],["application/vnd.kde.kspread","ksp"],["application/vnd.kde.kword","kwd"],["application/vnd.kenameaapp","htke"],["application/vnd.kidspiration","kia"],["application/vnd.kinar","kne"],["application/vnd.koan","skp"],["application/vnd.kodak-descriptor","sse"],["application/vnd.las.las+xml","lasxml"],["application/vnd.llamagraphics.life-balance.desktop","lbd"],["application/vnd.llamagraphics.life-balance.exchange+xml","lbe"],["application/vnd.lotus-1-2-3","123"],["application/vnd.lotus-approach","apr"],["application/vnd.lotus-freelance","pre"],["application/vnd.lotus-notes","nsf"],["application/vnd.lotus-organizer","org"],["application/vnd.lotus-screencam","scm"],["application/vnd.lotus-wordpro","lwp"],["application/vnd.macports.portpkg","portpkg"],["application/vnd.mcd","mcd"],["application/vnd.medcalcdata","mc1"],["application/vnd.mediastation.cdkey","cdkey"],["application/vnd.mfer","mwf"],["application/vnd.mfmp","mfm"],["application/vnd.micrografx.flo","flo"],["application/vnd.micrografx.igx","igx"],["application/vnd.mif","mif"],["application/vnd.mobius.daf","daf"],["application/vnd.mobius.dis","dis"],["application/vnd.mobius.mbk","mbk"],["application/vnd.mobius.mqy","mqy"],["application/vnd.mobius.msl","msl"],["application/vnd.mobius.plc","plc"],["application/vnd.mobius.txf","txf"],["application/vnd.mophun.application","mpn"],["application/vnd.mophun.certificate","mpc"],["application/vnd.mozilla.xul+xml","xul"],["application/vnd.ms-artgalry","cil"],["application/vnd.ms-cab-compressed","cab"],["application/vnd.ms-excel",["xls","xla","xlc","xlm","xlt","xlw","xlb","xll"]],["application/vnd.ms-excel.addin.macroenabled.12","xlam"],["application/vnd.ms-excel.sheet.binary.macroenabled.12","xlsb"],["application/vnd.ms-excel.sheet.macroenabled.12","xlsm"],["application/vnd.ms-excel.template.macroenabled.12","xltm"],["application/vnd.ms-fontobject","eot"],["application/vnd.ms-htmlhelp","chm"],["application/vnd.ms-ims","ims"],["application/vnd.ms-lrm","lrm"],["application/vnd.ms-officetheme","thmx"],["application/vnd.ms-outlook","msg"],["application/vnd.ms-pki.certstore","sst"],["application/vnd.ms-pki.pko","pko"],["application/vnd.ms-pki.seccat","cat"],["application/vnd.ms-pki.stl","stl"],["application/vnd.ms-pkicertstore","sst"],["application/vnd.ms-pkiseccat","cat"],["application/vnd.ms-pkistl","stl"],["application/vnd.ms-powerpoint",["ppt","pot","pps","ppa","pwz"]],["application/vnd.ms-powerpoint.addin.macroenabled.12","ppam"],["application/vnd.ms-powerpoint.presentation.macroenabled.12","pptm"],["application/vnd.ms-powerpoint.slide.macroenabled.12","sldm"],["application/vnd.ms-powerpoint.slideshow.macroenabled.12","ppsm"],["application/vnd.ms-powerpoint.template.macroenabled.12","potm"],["application/vnd.ms-project","mpp"],["application/vnd.ms-word.document.macroenabled.12","docm"],["application/vnd.ms-word.template.macroenabled.12","dotm"],["application/vnd.ms-works",["wks","wcm","wdb","wps"]],["application/vnd.ms-wpl","wpl"],["application/vnd.ms-xpsdocument","xps"],["application/vnd.mseq","mseq"],["application/vnd.musician","mus"],["application/vnd.muvee.style","msty"],["application/vnd.neurolanguage.nlu","nlu"],["application/vnd.noblenet-directory","nnd"],["application/vnd.noblenet-sealer","nns"],["application/vnd.noblenet-web","nnw"],["application/vnd.nokia.configuration-message","ncm"],["application/vnd.nokia.n-gage.data","ngdat"],["application/vnd.nokia.n-gage.symbian.install","n-gage"],["application/vnd.nokia.radio-preset","rpst"],["application/vnd.nokia.radio-presets","rpss"],["application/vnd.nokia.ringing-tone","rng"],["application/vnd.novadigm.edm","edm"],["application/vnd.novadigm.edx","edx"],["application/vnd.novadigm.ext","ext"],["application/vnd.oasis.opendocument.chart","odc"],["application/vnd.oasis.opendocument.chart-template","otc"],["application/vnd.oasis.opendocument.database","odb"],["application/vnd.oasis.opendocument.formula","odf"],["application/vnd.oasis.opendocument.formula-template","odft"],["application/vnd.oasis.opendocument.graphics","odg"],["application/vnd.oasis.opendocument.graphics-template","otg"],["application/vnd.oasis.opendocument.image","odi"],["application/vnd.oasis.opendocument.image-template","oti"],["application/vnd.oasis.opendocument.presentation","odp"],["application/vnd.oasis.opendocument.presentation-template","otp"],["application/vnd.oasis.opendocument.spreadsheet","ods"],["application/vnd.oasis.opendocument.spreadsheet-template","ots"],["application/vnd.oasis.opendocument.text","odt"],["application/vnd.oasis.opendocument.text-master","odm"],["application/vnd.oasis.opendocument.text-template","ott"],["application/vnd.oasis.opendocument.text-web","oth"],["application/vnd.olpc-sugar","xo"],["application/vnd.oma.dd2+xml","dd2"],["application/vnd.openofficeorg.extension","oxt"],["application/vnd.openxmlformats-officedocument.presentationml.presentation","pptx"],["application/vnd.openxmlformats-officedocument.presentationml.slide","sldx"],["application/vnd.openxmlformats-officedocument.presentationml.slideshow","ppsx"],["application/vnd.openxmlformats-officedocument.presentationml.template","potx"],["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","xlsx"],["application/vnd.openxmlformats-officedocument.spreadsheetml.template","xltx"],["application/vnd.openxmlformats-officedocument.wordprocessingml.document","docx"],["application/vnd.openxmlformats-officedocument.wordprocessingml.template","dotx"],["application/vnd.osgeo.mapguide.package","mgp"],["application/vnd.osgi.dp","dp"],["application/vnd.palm","pdb"],["application/vnd.pawaafile","paw"],["application/vnd.pg.format","str"],["application/vnd.pg.osasli","ei6"],["application/vnd.picsel","efif"],["application/vnd.pmi.widget","wg"],["application/vnd.pocketlearn","plf"],["application/vnd.powerbuilder6","pbd"],["application/vnd.previewsystems.box","box"],["application/vnd.proteus.magazine","mgz"],["application/vnd.publishare-delta-tree","qps"],["application/vnd.pvi.ptid1","ptid"],["application/vnd.quark.quarkxpress","qxd"],["application/vnd.realvnc.bed","bed"],["application/vnd.recordare.musicxml","mxl"],["application/vnd.recordare.musicxml+xml","musicxml"],["application/vnd.rig.cryptonote","cryptonote"],["application/vnd.rim.cod","cod"],["application/vnd.rn-realmedia","rm"],["application/vnd.rn-realplayer","rnx"],["application/vnd.route66.link66+xml","link66"],["application/vnd.sailingtracker.track","st"],["application/vnd.seemail","see"],["application/vnd.sema","sema"],["application/vnd.semd","semd"],["application/vnd.semf","semf"],["application/vnd.shana.informed.formdata","ifm"],["application/vnd.shana.informed.formtemplate","itp"],["application/vnd.shana.informed.interchange","iif"],["application/vnd.shana.informed.package","ipk"],["application/vnd.simtech-mindmapper","twd"],["application/vnd.smaf","mmf"],["application/vnd.smart.teacher","teacher"],["application/vnd.solent.sdkm+xml","sdkm"],["application/vnd.spotfire.dxp","dxp"],["application/vnd.spotfire.sfs","sfs"],["application/vnd.stardivision.calc","sdc"],["application/vnd.stardivision.draw","sda"],["application/vnd.stardivision.impress","sdd"],["application/vnd.stardivision.math","smf"],["application/vnd.stardivision.writer","sdw"],["application/vnd.stardivision.writer-global","sgl"],["application/vnd.stepmania.stepchart","sm"],["application/vnd.sun.xml.calc","sxc"],["application/vnd.sun.xml.calc.template","stc"],["application/vnd.sun.xml.draw","sxd"],["application/vnd.sun.xml.draw.template","std"],["application/vnd.sun.xml.impress","sxi"],["application/vnd.sun.xml.impress.template","sti"],["application/vnd.sun.xml.math","sxm"],["application/vnd.sun.xml.writer","sxw"],["application/vnd.sun.xml.writer.global","sxg"],["application/vnd.sun.xml.writer.template","stw"],["application/vnd.sus-calendar","sus"],["application/vnd.svd","svd"],["application/vnd.symbian.install","sis"],["application/vnd.syncml+xml","xsm"],["application/vnd.syncml.dm+wbxml","bdm"],["application/vnd.syncml.dm+xml","xdm"],["application/vnd.tao.intent-module-archive","tao"],["application/vnd.tmobile-livetv","tmo"],["application/vnd.trid.tpt","tpt"],["application/vnd.triscape.mxs","mxs"],["application/vnd.trueapp","tra"],["application/vnd.ufdl","ufd"],["application/vnd.uiq.theme","utz"],["application/vnd.umajin","umj"],["application/vnd.unity","unityweb"],["application/vnd.uoml+xml","uoml"],["application/vnd.vcx","vcx"],["application/vnd.visio","vsd"],["application/vnd.visionary","vis"],["application/vnd.vsf","vsf"],["application/vnd.wap.wbxml","wbxml"],["application/vnd.wap.wmlc","wmlc"],["application/vnd.wap.wmlscriptc","wmlsc"],["application/vnd.webturbo","wtb"],["application/vnd.wolfram.player","nbp"],["application/vnd.wordperfect","wpd"],["application/vnd.wqd","wqd"],["application/vnd.wt.stf","stf"],["application/vnd.xara",["web","xar"]],["application/vnd.xfdl","xfdl"],["application/vnd.yamaha.hv-dic","hvd"],["application/vnd.yamaha.hv-script","hvs"],["application/vnd.yamaha.hv-voice","hvp"],["application/vnd.yamaha.openscoreformat","osf"],["application/vnd.yamaha.openscoreformat.osfpvg+xml","osfpvg"],["application/vnd.yamaha.smaf-audio","saf"],["application/vnd.yamaha.smaf-phrase","spf"],["application/vnd.yellowriver-custom-menu","cmp"],["application/vnd.zul","zir"],["application/vnd.zzazz.deck+xml","zaz"],["application/vocaltec-media-desc","vmd"],["application/vocaltec-media-file","vmf"],["application/voicexml+xml","vxml"],["application/widget","wgt"],["application/winhlp","hlp"],["application/wordperfect",["wp","wp5","wp6","wpd"]],["application/wordperfect6.0",["w60","wp5"]],["application/wordperfect6.1","w61"],["application/wsdl+xml","wsdl"],["application/wspolicy+xml","wspolicy"],["application/x-123","wk1"],["application/x-7z-compressed","7z"],["application/x-abiword","abw"],["application/x-ace-compressed","ace"],["application/x-aim","aim"],["application/x-authorware-bin","aab"],["application/x-authorware-map","aam"],["application/x-authorware-seg","aas"],["application/x-bcpio","bcpio"],["application/x-binary","bin"],["application/x-binhex40","hqx"],["application/x-bittorrent","torrent"],["application/x-bsh",["bsh","sh","shar"]],["application/x-bytecode.elisp","elc"],["application/x-bytecode.python","pyc"],["application/x-bzip","bz"],["application/x-bzip2",["boz","bz2"]],["application/x-cdf","cdf"],["application/x-cdlink","vcd"],["application/x-chat",["cha","chat"]],["application/x-chess-pgn","pgn"],["application/x-cmu-raster","ras"],["application/x-cocoa","cco"],["application/x-compactpro","cpt"],["application/x-compress","z"],["application/x-compressed",["tgz","gz","z","zip"]],["application/x-conference","nsc"],["application/x-cpio","cpio"],["application/x-cpt","cpt"],["application/x-csh","csh"],["application/x-debian-package","deb"],["application/x-deepv","deepv"],["application/x-director",["dir","dcr","dxr"]],["application/x-doom","wad"],["application/x-dtbncx+xml","ncx"],["application/x-dtbook+xml","dtb"],["application/x-dtbresource+xml","res"],["application/x-dvi","dvi"],["application/x-elc","elc"],["application/x-envoy",["env","evy"]],["application/x-esrehber","es"],["application/x-excel",["xls","xla","xlb","xlc","xld","xlk","xll","xlm","xlt","xlv","xlw"]],["application/x-font-bdf","bdf"],["application/x-font-ghostscript","gsf"],["application/x-font-linux-psf","psf"],["application/x-font-otf","otf"],["application/x-font-pcf","pcf"],["application/x-font-snf","snf"],["application/x-font-ttf","ttf"],["application/x-font-type1","pfa"],["application/x-font-woff","woff"],["application/x-frame","mif"],["application/x-freelance","pre"],["application/x-futuresplash","spl"],["application/x-gnumeric","gnumeric"],["application/x-gsp","gsp"],["application/x-gss","gss"],["application/x-gtar","gtar"],["application/x-gzip",["gz","gzip"]],["application/x-hdf","hdf"],["application/x-helpfile",["help","hlp"]],["application/x-httpd-imap","imap"],["application/x-ima","ima"],["application/x-internet-signup",["ins","isp"]],["application/x-internett-signup","ins"],["application/x-inventor","iv"],["application/x-ip2","ip"],["application/x-iphone","iii"],["application/x-java-class","class"],["application/x-java-commerce","jcm"],["application/x-java-jnlp-file","jnlp"],["application/x-javascript","js"],["application/x-koan",["skd","skm","skp","skt"]],["application/x-ksh","ksh"],["application/x-latex",["latex","ltx"]],["application/x-lha","lha"],["application/x-lisp","lsp"],["application/x-livescreen","ivy"],["application/x-lotus","wq1"],["application/x-lotusscreencam","scm"],["application/x-lzh","lzh"],["application/x-lzx","lzx"],["application/x-mac-binhex40","hqx"],["application/x-macbinary","bin"],["application/x-magic-cap-package-1.0","mc$"],["application/x-mathcad","mcd"],["application/x-meme","mm"],["application/x-midi",["mid","midi"]],["application/x-mif","mif"],["application/x-mix-transfer","nix"],["application/x-mobipocket-ebook","prc"],["application/x-mplayer2","asx"],["application/x-ms-application","application"],["application/x-ms-wmd","wmd"],["application/x-ms-wmz","wmz"],["application/x-ms-xbap","xbap"],["application/x-msaccess","mdb"],["application/x-msbinder","obd"],["application/x-mscardfile","crd"],["application/x-msclip","clp"],["application/x-msdownload",["exe","dll"]],["application/x-msexcel",["xls","xla","xlw"]],["application/x-msmediaview",["mvb","m13","m14"]],["application/x-msmetafile","wmf"],["application/x-msmoney","mny"],["application/x-mspowerpoint","ppt"],["application/x-mspublisher","pub"],["application/x-msschedule","scd"],["application/x-msterminal","trm"],["application/x-mswrite","wri"],["application/x-navi-animation","ani"],["application/x-navidoc","nvd"],["application/x-navimap","map"],["application/x-navistyle","stl"],["application/x-netcdf",["cdf","nc"]],["application/x-newton-compatible-pkg","pkg"],["application/x-nokia-9000-communicator-add-on-software","aos"],["application/x-omc","omc"],["application/x-omcdatamaker","omcd"],["application/x-omcregerator","omcr"],["application/x-pagemaker",["pm4","pm5"]],["application/x-pcl","pcl"],["application/x-perfmon",["pma","pmc","pml","pmr","pmw"]],["application/x-pixclscript","plx"],["application/x-pkcs10","p10"],["application/x-pkcs12",["p12","pfx"]],["application/x-pkcs7-certificates",["p7b","spc"]],["application/x-pkcs7-certreqresp","p7r"],["application/x-pkcs7-mime",["p7m","p7c"]],["application/x-pkcs7-signature",["p7s","p7a"]],["application/x-pointplus","css"],["application/x-portable-anymap","pnm"],["application/x-project",["mpc","mpt","mpv","mpx"]],["application/x-qpro","wb1"],["application/x-rar-compressed","rar"],["application/x-rtf","rtf"],["application/x-sdp","sdp"],["application/x-sea","sea"],["application/x-seelogo","sl"],["application/x-sh","sh"],["application/x-shar",["shar","sh"]],["application/x-shockwave-flash","swf"],["application/x-silverlight-app","xap"],["application/x-sit","sit"],["application/x-sprite",["spr","sprite"]],["application/x-stuffit","sit"],["application/x-stuffitx","sitx"],["application/x-sv4cpio","sv4cpio"],["application/x-sv4crc","sv4crc"],["application/x-tar","tar"],["application/x-tbook",["sbk","tbk"]],["application/x-tcl","tcl"],["application/x-tex","tex"],["application/x-tex-tfm","tfm"],["application/x-texinfo",["texi","texinfo"]],["application/x-troff",["roff","t","tr"]],["application/x-troff-man","man"],["application/x-troff-me","me"],["application/x-troff-ms","ms"],["application/x-troff-msvideo","avi"],["application/x-ustar","ustar"],["application/x-visio",["vsd","vst","vsw"]],["application/x-vnd.audioexplosion.mzz","mzz"],["application/x-vnd.ls-xpix","xpix"],["application/x-vrml","vrml"],["application/x-wais-source",["src","wsrc"]],["application/x-winhelp","hlp"],["application/x-wintalk","wtk"],["application/x-world",["wrl","svr"]],["application/x-wpwin","wpd"],["application/x-wri","wri"],["application/x-x509-ca-cert",["cer","crt","der"]],["application/x-x509-user-cert","crt"],["application/x-xfig","fig"],["application/x-xpinstall","xpi"],["application/x-zip-compressed","zip"],["application/xcap-diff+xml","xdf"],["application/xenc+xml","xenc"],["application/xhtml+xml","xhtml"],["application/xml","xml"],["application/xml-dtd","dtd"],["application/xop+xml","xop"],["application/xslt+xml","xslt"],["application/xspf+xml","xspf"],["application/xv+xml","mxml"],["application/yang","yang"],["application/yin+xml","yin"],["application/ynd.ms-pkipko","pko"],["application/zip","zip"],["audio/adpcm","adp"],["audio/aiff",["aiff","aif","aifc"]],["audio/basic",["snd","au"]],["audio/it","it"],["audio/make",["funk","my","pfunk"]],["audio/make.my.funk","pfunk"],["audio/mid",["mid","rmi"]],["audio/midi",["midi","kar","mid"]],["audio/mod","mod"],["audio/mp4","mp4a"],["audio/mpeg",["mpga","mp3","m2a","mp2","mpa","mpg"]],["audio/mpeg3","mp3"],["audio/nspaudio",["la","lma"]],["audio/ogg","oga"],["audio/s3m","s3m"],["audio/tsp-audio","tsi"],["audio/tsplayer","tsp"],["audio/vnd.dece.audio","uva"],["audio/vnd.digital-winds","eol"],["audio/vnd.dra","dra"],["audio/vnd.dts","dts"],["audio/vnd.dts.hd","dtshd"],["audio/vnd.lucent.voice","lvp"],["audio/vnd.ms-playready.media.pya","pya"],["audio/vnd.nuera.ecelp4800","ecelp4800"],["audio/vnd.nuera.ecelp7470","ecelp7470"],["audio/vnd.nuera.ecelp9600","ecelp9600"],["audio/vnd.qcelp","qcp"],["audio/vnd.rip","rip"],["audio/voc","voc"],["audio/voxware","vox"],["audio/wav","wav"],["audio/webm","weba"],["audio/x-aac","aac"],["audio/x-adpcm","snd"],["audio/x-aiff",["aiff","aif","aifc"]],["audio/x-au","au"],["audio/x-gsm",["gsd","gsm"]],["audio/x-jam","jam"],["audio/x-liveaudio","lam"],["audio/x-mid",["mid","midi"]],["audio/x-midi",["midi","mid"]],["audio/x-mod","mod"],["audio/x-mpeg","mp2"],["audio/x-mpeg-3","mp3"],["audio/x-mpegurl","m3u"],["audio/x-mpequrl","m3u"],["audio/x-ms-wax","wax"],["audio/x-ms-wma","wma"],["audio/x-nspaudio",["la","lma"]],["audio/x-pn-realaudio",["ra","ram","rm","rmm","rmp"]],["audio/x-pn-realaudio-plugin",["ra","rmp","rpm"]],["audio/x-psid","sid"],["audio/x-realaudio","ra"],["audio/x-twinvq","vqf"],["audio/x-twinvq-plugin",["vqe","vql"]],["audio/x-vnd.audioexplosion.mjuicemediafile","mjf"],["audio/x-voc","voc"],["audio/x-wav","wav"],["audio/xm","xm"],["chemical/x-cdx","cdx"],["chemical/x-cif","cif"],["chemical/x-cmdf","cmdf"],["chemical/x-cml","cml"],["chemical/x-csml","csml"],["chemical/x-pdb",["pdb","xyz"]],["chemical/x-xyz","xyz"],["drawing/x-dwf","dwf"],["i-world/i-vrml","ivr"],["image/bmp",["bmp","bm"]],["image/cgm","cgm"],["image/cis-cod","cod"],["image/cmu-raster",["ras","rast"]],["image/fif","fif"],["image/florian",["flo","turbot"]],["image/g3fax","g3"],["image/gif","gif"],["image/ief",["ief","iefs"]],["image/jpeg",["jpeg","jpe","jpg","jfif","jfif-tbnl"]],["image/jutvision","jut"],["image/ktx","ktx"],["image/naplps",["nap","naplps"]],["image/pict",["pic","pict"]],["image/pipeg","jfif"],["image/pjpeg",["jfif","jpe","jpeg","jpg"]],["image/png",["png","x-png"]],["image/prs.btif","btif"],["image/svg+xml","svg"],["image/tiff",["tif","tiff"]],["image/vasa","mcf"],["image/vnd.adobe.photoshop","psd"],["image/vnd.dece.graphic","uvi"],["image/vnd.djvu","djvu"],["image/vnd.dvb.subtitle","sub"],["image/vnd.dwg",["dwg","dxf","svf"]],["image/vnd.dxf","dxf"],["image/vnd.fastbidsheet","fbs"],["image/vnd.fpx","fpx"],["image/vnd.fst","fst"],["image/vnd.fujixerox.edmics-mmr","mmr"],["image/vnd.fujixerox.edmics-rlc","rlc"],["image/vnd.ms-modi","mdi"],["image/vnd.net-fpx",["fpx","npx"]],["image/vnd.rn-realflash","rf"],["image/vnd.rn-realpix","rp"],["image/vnd.wap.wbmp","wbmp"],["image/vnd.xiff","xif"],["image/webp","webp"],["image/x-cmu-raster","ras"],["image/x-cmx","cmx"],["image/x-dwg",["dwg","dxf","svf"]],["image/x-freehand","fh"],["image/x-icon","ico"],["image/x-jg","art"],["image/x-jps","jps"],["image/x-niff",["niff","nif"]],["image/x-pcx","pcx"],["image/x-pict",["pct","pic"]],["image/x-portable-anymap","pnm"],["image/x-portable-bitmap","pbm"],["image/x-portable-graymap","pgm"],["image/x-portable-greymap","pgm"],["image/x-portable-pixmap","ppm"],["image/x-quicktime",["qif","qti","qtif"]],["image/x-rgb","rgb"],["image/x-tiff",["tif","tiff"]],["image/x-windows-bmp","bmp"],["image/x-xbitmap","xbm"],["image/x-xbm","xbm"],["image/x-xpixmap",["xpm","pm"]],["image/x-xwd","xwd"],["image/x-xwindowdump","xwd"],["image/xbm","xbm"],["image/xpm","xpm"],["message/rfc822",["eml","mht","mhtml","nws","mime"]],["model/iges",["iges","igs"]],["model/mesh","msh"],["model/vnd.collada+xml","dae"],["model/vnd.dwf","dwf"],["model/vnd.gdl","gdl"],["model/vnd.gtw","gtw"],["model/vnd.mts","mts"],["model/vnd.vtu","vtu"],["model/vrml",["vrml","wrl","wrz"]],["model/x-pov","pov"],["multipart/x-gzip","gzip"],["multipart/x-ustar","ustar"],["multipart/x-zip","zip"],["music/crescendo",["mid","midi"]],["music/x-karaoke","kar"],["paleovu/x-pv","pvu"],["text/asp","asp"],["text/calendar","ics"],["text/css","css"],["text/csv","csv"],["text/ecmascript","js"],["text/h323","323"],["text/html",["html","htm","stm","acgi","htmls","htx","shtml"]],["text/iuls","uls"],["text/javascript","js"],["text/mcf","mcf"],["text/n3","n3"],["text/pascal","pas"],["text/plain",["txt","bas","c","h","c++","cc","com","conf","cxx","def","f","f90","for","g","hh","idc","jav","java","list","log","lst","m","mar","pl","sdml","text"]],["text/plain-bas","par"],["text/prs.lines.tag","dsc"],["text/richtext",["rtx","rt","rtf"]],["text/scriplet","wsc"],["text/scriptlet","sct"],["text/sgml",["sgm","sgml"]],["text/tab-separated-values","tsv"],["text/troff","t"],["text/turtle","ttl"],["text/uri-list",["uni","unis","uri","uris"]],["text/vnd.abc","abc"],["text/vnd.curl","curl"],["text/vnd.curl.dcurl","dcurl"],["text/vnd.curl.mcurl","mcurl"],["text/vnd.curl.scurl","scurl"],["text/vnd.fly","fly"],["text/vnd.fmi.flexstor","flx"],["text/vnd.graphviz","gv"],["text/vnd.in3d.3dml","3dml"],["text/vnd.in3d.spot","spot"],["text/vnd.rn-realtext","rt"],["text/vnd.sun.j2me.app-descriptor","jad"],["text/vnd.wap.wml","wml"],["text/vnd.wap.wmlscript","wmls"],["text/webviewhtml","htt"],["text/x-asm",["asm","s"]],["text/x-audiosoft-intra","aip"],["text/x-c",["c","cc","cpp"]],["text/x-component","htc"],["text/x-fortran",["for","f","f77","f90"]],["text/x-h",["h","hh"]],["text/x-java-source",["java","jav"]],["text/x-java-source,java","java"],["text/x-la-asf","lsx"],["text/x-m","m"],["text/x-pascal","p"],["text/x-script","hlb"],["text/x-script.csh","csh"],["text/x-script.elisp","el"],["text/x-script.guile","scm"],["text/x-script.ksh","ksh"],["text/x-script.lisp","lsp"],["text/x-script.perl","pl"],["text/x-script.perl-module","pm"],["text/x-script.phyton","py"],["text/x-script.rexx","rexx"],["text/x-script.scheme","scm"],["text/x-script.sh","sh"],["text/x-script.tcl","tcl"],["text/x-script.tcsh","tcsh"],["text/x-script.zsh","zsh"],["text/x-server-parsed-html",["shtml","ssi"]],["text/x-setext","etx"],["text/x-sgml",["sgm","sgml"]],["text/x-speech",["spc","talk"]],["text/x-uil","uil"],["text/x-uuencode",["uu","uue"]],["text/x-vcalendar","vcs"],["text/x-vcard","vcf"],["text/xml","xml"],["video/3gpp","3gp"],["video/3gpp2","3g2"],["video/animaflex","afl"],["video/avi","avi"],["video/avs-video","avs"],["video/dl","dl"],["video/fli","fli"],["video/gl","gl"],["video/h261","h261"],["video/h263","h263"],["video/h264","h264"],["video/jpeg","jpgv"],["video/jpm","jpm"],["video/mj2","mj2"],["video/mp4","mp4"],["video/mpeg",["mpeg","mp2","mpa","mpe","mpg","mpv2","m1v","m2v","mp3"]],["video/msvideo","avi"],["video/ogg","ogv"],["video/quicktime",["mov","qt","moov"]],["video/vdo","vdo"],["video/vivo",["viv","vivo"]],["video/vnd.dece.hd","uvh"],["video/vnd.dece.mobile","uvm"],["video/vnd.dece.pd","uvp"],["video/vnd.dece.sd","uvs"],["video/vnd.dece.video","uvv"],["video/vnd.fvt","fvt"],["video/vnd.mpegurl","mxu"],["video/vnd.ms-playready.media.pyv","pyv"],["video/vnd.rn-realvideo","rv"],["video/vnd.uvvu.mp4","uvu"],["video/vnd.vivo",["viv","vivo"]],["video/vosaic","vos"],["video/webm","webm"],["video/x-amt-demorun","xdr"],["video/x-amt-showrun","xsr"],["video/x-atomic3d-feature","fmf"],["video/x-dl","dl"],["video/x-dv",["dif","dv"]],["video/x-f4v","f4v"],["video/x-fli","fli"],["video/x-flv","flv"],["video/x-gl","gl"],["video/x-isvideo","isu"],["video/x-la-asf",["lsf","lsx"]],["video/x-m4v","m4v"],["video/x-motion-jpeg","mjpg"],["video/x-mpeg",["mp3","mp2"]],["video/x-mpeq2a","mp2"],["video/x-ms-asf",["asf","asr","asx"]],["video/x-ms-asf-plugin","asx"],["video/x-ms-wm","wm"],["video/x-ms-wmv","wmv"],["video/x-ms-wmx","wmx"],["video/x-ms-wvx","wvx"],["video/x-msvideo","avi"],["video/x-qtc","qtc"],["video/x-scm","scm"],["video/x-sgi-movie",["movie","mv"]],["windows/metafile","wmf"],["www/mime","mime"],["x-conference/x-cooltalk","ice"],["x-music/x-midi",["mid","midi"]],["x-world/x-3dmf",["3dm","3dmf","qd3","qd3d"]],["x-world/x-svr","svr"],["x-world/x-vrml",["flr","vrml","wrl","wrz","xaf","xof"]],["x-world/x-vrt","vrt"],["xgl/drawing","xgz"],["xgl/movie","xmz"]]),Fy=new Map([["123","application/vnd.lotus-1-2-3"],["323","text/h323"],["*","application/octet-stream"],["3dm","x-world/x-3dmf"],["3dmf","x-world/x-3dmf"],["3dml","text/vnd.in3d.3dml"],["3g2","video/3gpp2"],["3gp","video/3gpp"],["7z","application/x-7z-compressed"],["a","application/octet-stream"],["aab","application/x-authorware-bin"],["aac","audio/x-aac"],["aam","application/x-authorware-map"],["aas","application/x-authorware-seg"],["abc","text/vnd.abc"],["abw","application/x-abiword"],["ac","application/pkix-attr-cert"],["acc","application/vnd.americandynamics.acc"],["ace","application/x-ace-compressed"],["acgi","text/html"],["acu","application/vnd.acucobol"],["acx","application/internet-property-stream"],["adp","audio/adpcm"],["aep","application/vnd.audiograph"],["afl","video/animaflex"],["afp","application/vnd.ibm.modcap"],["ahead","application/vnd.ahead.space"],["ai","application/postscript"],["aif",["audio/aiff","audio/x-aiff"]],["aifc",["audio/aiff","audio/x-aiff"]],["aiff",["audio/aiff","audio/x-aiff"]],["aim","application/x-aim"],["aip","text/x-audiosoft-intra"],["air","application/vnd.adobe.air-application-installer-package+zip"],["ait","application/vnd.dvb.ait"],["ami","application/vnd.amiga.ami"],["ani","application/x-navi-animation"],["aos","application/x-nokia-9000-communicator-add-on-software"],["apk","application/vnd.android.package-archive"],["application","application/x-ms-application"],["apr","application/vnd.lotus-approach"],["aps","application/mime"],["arc","application/octet-stream"],["arj",["application/arj","application/octet-stream"]],["art","image/x-jg"],["asf","video/x-ms-asf"],["asm","text/x-asm"],["aso","application/vnd.accpac.simply.aso"],["asp","text/asp"],["asr","video/x-ms-asf"],["asx",["video/x-ms-asf","application/x-mplayer2","video/x-ms-asf-plugin"]],["atc","application/vnd.acucorp"],["atomcat","application/atomcat+xml"],["atomsvc","application/atomsvc+xml"],["atx","application/vnd.antix.game-component"],["au",["audio/basic","audio/x-au"]],["avi",["video/avi","video/msvideo","application/x-troff-msvideo","video/x-msvideo"]],["avs","video/avs-video"],["aw","application/applixware"],["axs","application/olescript"],["azf","application/vnd.airzip.filesecure.azf"],["azs","application/vnd.airzip.filesecure.azs"],["azw","application/vnd.amazon.ebook"],["bas","text/plain"],["bcpio","application/x-bcpio"],["bdf","application/x-font-bdf"],["bdm","application/vnd.syncml.dm+wbxml"],["bed","application/vnd.realvnc.bed"],["bh2","application/vnd.fujitsu.oasysprs"],["bin",["application/octet-stream","application/mac-binary","application/macbinary","application/x-macbinary","application/x-binary"]],["bm","image/bmp"],["bmi","application/vnd.bmi"],["bmp",["image/bmp","image/x-windows-bmp"]],["boo","application/book"],["book","application/book"],["box","application/vnd.previewsystems.box"],["boz","application/x-bzip2"],["bsh","application/x-bsh"],["btif","image/prs.btif"],["bz","application/x-bzip"],["bz2","application/x-bzip2"],["c",["text/plain","text/x-c"]],["c++","text/plain"],["c11amc","application/vnd.cluetrust.cartomobile-config"],["c11amz","application/vnd.cluetrust.cartomobile-config-pkg"],["c4g","application/vnd.clonk.c4group"],["cab","application/vnd.ms-cab-compressed"],["car","application/vnd.curl.car"],["cat",["application/vnd.ms-pkiseccat","application/vnd.ms-pki.seccat"]],["cc",["text/plain","text/x-c"]],["ccad","application/clariscad"],["cco","application/x-cocoa"],["ccxml","application/ccxml+xml,"],["cdbcmsg","application/vnd.contact.cmsg"],["cdf",["application/cdf","application/x-cdf","application/x-netcdf"]],["cdkey","application/vnd.mediastation.cdkey"],["cdmia","application/cdmi-capability"],["cdmic","application/cdmi-container"],["cdmid","application/cdmi-domain"],["cdmio","application/cdmi-object"],["cdmiq","application/cdmi-queue"],["cdx","chemical/x-cdx"],["cdxml","application/vnd.chemdraw+xml"],["cdy","application/vnd.cinderella"],["cer",["application/pkix-cert","application/x-x509-ca-cert"]],["cgm","image/cgm"],["cha","application/x-chat"],["chat","application/x-chat"],["chm","application/vnd.ms-htmlhelp"],["chrt","application/vnd.kde.kchart"],["cif","chemical/x-cif"],["cii","application/vnd.anser-web-certificate-issue-initiation"],["cil","application/vnd.ms-artgalry"],["cla","application/vnd.claymore"],["class",["application/octet-stream","application/java","application/java-byte-code","application/java-vm","application/x-java-class"]],["clkk","application/vnd.crick.clicker.keyboard"],["clkp","application/vnd.crick.clicker.palette"],["clkt","application/vnd.crick.clicker.template"],["clkw","application/vnd.crick.clicker.wordbank"],["clkx","application/vnd.crick.clicker"],["clp","application/x-msclip"],["cmc","application/vnd.cosmocaller"],["cmdf","chemical/x-cmdf"],["cml","chemical/x-cml"],["cmp","application/vnd.yellowriver-custom-menu"],["cmx","image/x-cmx"],["cod",["image/cis-cod","application/vnd.rim.cod"]],["com",["application/octet-stream","text/plain"]],["conf","text/plain"],["cpio","application/x-cpio"],["cpp","text/x-c"],["cpt",["application/mac-compactpro","application/x-compactpro","application/x-cpt"]],["crd","application/x-mscardfile"],["crl",["application/pkix-crl","application/pkcs-crl"]],["crt",["application/pkix-cert","application/x-x509-user-cert","application/x-x509-ca-cert"]],["cryptonote","application/vnd.rig.cryptonote"],["csh",["text/x-script.csh","application/x-csh"]],["csml","chemical/x-csml"],["csp","application/vnd.commonspace"],["css",["text/css","application/x-pointplus"]],["csv","text/csv"],["cu","application/cu-seeme"],["curl","text/vnd.curl"],["cww","application/prs.cww"],["cxx","text/plain"],["dae","model/vnd.collada+xml"],["daf","application/vnd.mobius.daf"],["davmount","application/davmount+xml"],["dcr","application/x-director"],["dcurl","text/vnd.curl.dcurl"],["dd2","application/vnd.oma.dd2+xml"],["ddd","application/vnd.fujixerox.ddd"],["deb","application/x-debian-package"],["deepv","application/x-deepv"],["def","text/plain"],["der","application/x-x509-ca-cert"],["dfac","application/vnd.dreamfactory"],["dif","video/x-dv"],["dir","application/x-director"],["dis","application/vnd.mobius.dis"],["djvu","image/vnd.djvu"],["dl",["video/dl","video/x-dl"]],["dll","application/x-msdownload"],["dms","application/octet-stream"],["dna","application/vnd.dna"],["doc","application/msword"],["docm","application/vnd.ms-word.document.macroenabled.12"],["docx","application/vnd.openxmlformats-officedocument.wordprocessingml.document"],["dot","application/msword"],["dotm","application/vnd.ms-word.template.macroenabled.12"],["dotx","application/vnd.openxmlformats-officedocument.wordprocessingml.template"],["dp",["application/commonground","application/vnd.osgi.dp"]],["dpg","application/vnd.dpgraph"],["dra","audio/vnd.dra"],["drw","application/drafting"],["dsc","text/prs.lines.tag"],["dssc","application/dssc+der"],["dtb","application/x-dtbook+xml"],["dtd","application/xml-dtd"],["dts","audio/vnd.dts"],["dtshd","audio/vnd.dts.hd"],["dump","application/octet-stream"],["dv","video/x-dv"],["dvi","application/x-dvi"],["dwf",["model/vnd.dwf","drawing/x-dwf"]],["dwg",["application/acad","image/vnd.dwg","image/x-dwg"]],["dxf",["application/dxf","image/vnd.dwg","image/vnd.dxf","image/x-dwg"]],["dxp","application/vnd.spotfire.dxp"],["dxr","application/x-director"],["ecelp4800","audio/vnd.nuera.ecelp4800"],["ecelp7470","audio/vnd.nuera.ecelp7470"],["ecelp9600","audio/vnd.nuera.ecelp9600"],["edm","application/vnd.novadigm.edm"],["edx","application/vnd.novadigm.edx"],["efif","application/vnd.picsel"],["ei6","application/vnd.pg.osasli"],["el","text/x-script.elisp"],["elc",["application/x-elc","application/x-bytecode.elisp"]],["eml","message/rfc822"],["emma","application/emma+xml"],["env","application/x-envoy"],["eol","audio/vnd.digital-winds"],["eot","application/vnd.ms-fontobject"],["eps","application/postscript"],["epub","application/epub+zip"],["es",["application/ecmascript","application/x-esrehber"]],["es3","application/vnd.eszigno3+xml"],["esf","application/vnd.epson.esf"],["etx","text/x-setext"],["evy",["application/envoy","application/x-envoy"]],["exe",["application/octet-stream","application/x-msdownload"]],["exi","application/exi"],["ext","application/vnd.novadigm.ext"],["ez2","application/vnd.ezpix-album"],["ez3","application/vnd.ezpix-package"],["f",["text/plain","text/x-fortran"]],["f4v","video/x-f4v"],["f77","text/x-fortran"],["f90",["text/plain","text/x-fortran"]],["fbs","image/vnd.fastbidsheet"],["fcs","application/vnd.isac.fcs"],["fdf","application/vnd.fdf"],["fe_launch","application/vnd.denovo.fcselayout-link"],["fg5","application/vnd.fujitsu.oasysgp"],["fh","image/x-freehand"],["fif",["application/fractals","image/fif"]],["fig","application/x-xfig"],["fli",["video/fli","video/x-fli"]],["flo",["image/florian","application/vnd.micrografx.flo"]],["flr","x-world/x-vrml"],["flv","video/x-flv"],["flw","application/vnd.kde.kivio"],["flx","text/vnd.fmi.flexstor"],["fly","text/vnd.fly"],["fm","application/vnd.framemaker"],["fmf","video/x-atomic3d-feature"],["fnc","application/vnd.frogans.fnc"],["for",["text/plain","text/x-fortran"]],["fpx",["image/vnd.fpx","image/vnd.net-fpx"]],["frl","application/freeloader"],["fsc","application/vnd.fsc.weblaunch"],["fst","image/vnd.fst"],["ftc","application/vnd.fluxtime.clip"],["fti","application/vnd.anser-web-funds-transfer-initiation"],["funk","audio/make"],["fvt","video/vnd.fvt"],["fxp","application/vnd.adobe.fxp"],["fzs","application/vnd.fuzzysheet"],["g","text/plain"],["g2w","application/vnd.geoplan"],["g3","image/g3fax"],["g3w","application/vnd.geospace"],["gac","application/vnd.groove-account"],["gdl","model/vnd.gdl"],["geo","application/vnd.dynageo"],["geojson","application/geo+json"],["gex","application/vnd.geometry-explorer"],["ggb","application/vnd.geogebra.file"],["ggt","application/vnd.geogebra.tool"],["ghf","application/vnd.groove-help"],["gif","image/gif"],["gim","application/vnd.groove-identity-message"],["gl",["video/gl","video/x-gl"]],["gmx","application/vnd.gmx"],["gnumeric","application/x-gnumeric"],["gph","application/vnd.flographit"],["gqf","application/vnd.grafeq"],["gram","application/srgs"],["grv","application/vnd.groove-injector"],["grxml","application/srgs+xml"],["gsd","audio/x-gsm"],["gsf","application/x-font-ghostscript"],["gsm","audio/x-gsm"],["gsp","application/x-gsp"],["gss","application/x-gss"],["gtar","application/x-gtar"],["gtm","application/vnd.groove-tool-message"],["gtw","model/vnd.gtw"],["gv","text/vnd.graphviz"],["gxt","application/vnd.geonext"],["gz",["application/x-gzip","application/x-compressed"]],["gzip",["multipart/x-gzip","application/x-gzip"]],["h",["text/plain","text/x-h"]],["h261","video/h261"],["h263","video/h263"],["h264","video/h264"],["hal","application/vnd.hal+xml"],["hbci","application/vnd.hbci"],["hdf","application/x-hdf"],["help","application/x-helpfile"],["hgl","application/vnd.hp-hpgl"],["hh",["text/plain","text/x-h"]],["hlb","text/x-script"],["hlp",["application/winhlp","application/hlp","application/x-helpfile","application/x-winhelp"]],["hpg","application/vnd.hp-hpgl"],["hpgl","application/vnd.hp-hpgl"],["hpid","application/vnd.hp-hpid"],["hps","application/vnd.hp-hps"],["hqx",["application/mac-binhex40","application/binhex","application/binhex4","application/mac-binhex","application/x-binhex40","application/x-mac-binhex40"]],["hta","application/hta"],["htc","text/x-component"],["htke","application/vnd.kenameaapp"],["htm","text/html"],["html","text/html"],["htmls","text/html"],["htt","text/webviewhtml"],["htx","text/html"],["hvd","application/vnd.yamaha.hv-dic"],["hvp","application/vnd.yamaha.hv-voice"],["hvs","application/vnd.yamaha.hv-script"],["i2g","application/vnd.intergeo"],["icc","application/vnd.iccprofile"],["ice","x-conference/x-cooltalk"],["ico","image/x-icon"],["ics","text/calendar"],["idc","text/plain"],["ief","image/ief"],["iefs","image/ief"],["ifm","application/vnd.shana.informed.formdata"],["iges",["application/iges","model/iges"]],["igl","application/vnd.igloader"],["igm","application/vnd.insors.igm"],["igs",["application/iges","model/iges"]],["igx","application/vnd.micrografx.igx"],["iif","application/vnd.shana.informed.interchange"],["iii","application/x-iphone"],["ima","application/x-ima"],["imap","application/x-httpd-imap"],["imp","application/vnd.accpac.simply.imp"],["ims","application/vnd.ms-ims"],["inf","application/inf"],["ins",["application/x-internet-signup","application/x-internett-signup"]],["ip","application/x-ip2"],["ipfix","application/ipfix"],["ipk","application/vnd.shana.informed.package"],["irm","application/vnd.ibm.rights-management"],["irp","application/vnd.irepository.package+xml"],["isp","application/x-internet-signup"],["isu","video/x-isvideo"],["it","audio/it"],["itp","application/vnd.shana.informed.formtemplate"],["iv","application/x-inventor"],["ivp","application/vnd.immervision-ivp"],["ivr","i-world/i-vrml"],["ivu","application/vnd.immervision-ivu"],["ivy","application/x-livescreen"],["jad","text/vnd.sun.j2me.app-descriptor"],["jam",["application/vnd.jam","audio/x-jam"]],["jar","application/java-archive"],["jav",["text/plain","text/x-java-source"]],["java",["text/plain","text/x-java-source,java","text/x-java-source"]],["jcm","application/x-java-commerce"],["jfif",["image/pipeg","image/jpeg","image/pjpeg"]],["jfif-tbnl","image/jpeg"],["jisp","application/vnd.jisp"],["jlt","application/vnd.hp-jlyt"],["jnlp","application/x-java-jnlp-file"],["joda","application/vnd.joost.joda-archive"],["jpe",["image/jpeg","image/pjpeg"]],["jpeg",["image/jpeg","image/pjpeg"]],["jpg",["image/jpeg","image/pjpeg"]],["jpgv","video/jpeg"],["jpm","video/jpm"],["jps","image/x-jps"],["js",["application/javascript","application/ecmascript","text/javascript","text/ecmascript","application/x-javascript"]],["json","application/json"],["jut","image/jutvision"],["kar",["audio/midi","music/x-karaoke"]],["karbon","application/vnd.kde.karbon"],["kfo","application/vnd.kde.kformula"],["kia","application/vnd.kidspiration"],["kml","application/vnd.google-earth.kml+xml"],["kmz","application/vnd.google-earth.kmz"],["kne","application/vnd.kinar"],["kon","application/vnd.kde.kontour"],["kpr","application/vnd.kde.kpresenter"],["ksh",["application/x-ksh","text/x-script.ksh"]],["ksp","application/vnd.kde.kspread"],["ktx","image/ktx"],["ktz","application/vnd.kahootz"],["kwd","application/vnd.kde.kword"],["la",["audio/nspaudio","audio/x-nspaudio"]],["lam","audio/x-liveaudio"],["lasxml","application/vnd.las.las+xml"],["latex","application/x-latex"],["lbd","application/vnd.llamagraphics.life-balance.desktop"],["lbe","application/vnd.llamagraphics.life-balance.exchange+xml"],["les","application/vnd.hhe.lesson-player"],["lha",["application/octet-stream","application/lha","application/x-lha"]],["lhx","application/octet-stream"],["link66","application/vnd.route66.link66+xml"],["list","text/plain"],["lma",["audio/nspaudio","audio/x-nspaudio"]],["log","text/plain"],["lrm","application/vnd.ms-lrm"],["lsf","video/x-la-asf"],["lsp",["application/x-lisp","text/x-script.lisp"]],["lst","text/plain"],["lsx",["video/x-la-asf","text/x-la-asf"]],["ltf","application/vnd.frogans.ltf"],["ltx","application/x-latex"],["lvp","audio/vnd.lucent.voice"],["lwp","application/vnd.lotus-wordpro"],["lzh",["application/octet-stream","application/x-lzh"]],["lzx",["application/lzx","application/octet-stream","application/x-lzx"]],["m",["text/plain","text/x-m"]],["m13","application/x-msmediaview"],["m14","application/x-msmediaview"],["m1v","video/mpeg"],["m21","application/mp21"],["m2a","audio/mpeg"],["m2v","video/mpeg"],["m3u",["audio/x-mpegurl","audio/x-mpequrl"]],["m3u8","application/vnd.apple.mpegurl"],["m4v","video/x-m4v"],["ma","application/mathematica"],["mads","application/mads+xml"],["mag","application/vnd.ecowin.chart"],["man","application/x-troff-man"],["map","application/x-navimap"],["mar","text/plain"],["mathml","application/mathml+xml"],["mbd","application/mbedlet"],["mbk","application/vnd.mobius.mbk"],["mbox","application/mbox"],["mc$","application/x-magic-cap-package-1.0"],["mc1","application/vnd.medcalcdata"],["mcd",["application/mcad","application/vnd.mcd","application/x-mathcad"]],["mcf",["image/vasa","text/mcf"]],["mcp","application/netmc"],["mcurl","text/vnd.curl.mcurl"],["mdb","application/x-msaccess"],["mdi","image/vnd.ms-modi"],["me","application/x-troff-me"],["meta4","application/metalink4+xml"],["mets","application/mets+xml"],["mfm","application/vnd.mfmp"],["mgp","application/vnd.osgeo.mapguide.package"],["mgz","application/vnd.proteus.magazine"],["mht","message/rfc822"],["mhtml","message/rfc822"],["mid",["audio/mid","audio/midi","music/crescendo","x-music/x-midi","audio/x-midi","application/x-midi","audio/x-mid"]],["midi",["audio/midi","music/crescendo","x-music/x-midi","audio/x-midi","application/x-midi","audio/x-mid"]],["mif",["application/vnd.mif","application/x-mif","application/x-frame"]],["mime",["message/rfc822","www/mime"]],["mj2","video/mj2"],["mjf","audio/x-vnd.audioexplosion.mjuicemediafile"],["mjpg","video/x-motion-jpeg"],["mlp","application/vnd.dolby.mlp"],["mm",["application/base64","application/x-meme"]],["mmd","application/vnd.chipnuts.karaoke-mmd"],["mme","application/base64"],["mmf","application/vnd.smaf"],["mmr","image/vnd.fujixerox.edmics-mmr"],["mny","application/x-msmoney"],["mod",["audio/mod","audio/x-mod"]],["mods","application/mods+xml"],["moov","video/quicktime"],["mov","video/quicktime"],["movie","video/x-sgi-movie"],["mp2",["video/mpeg","audio/mpeg","video/x-mpeg","audio/x-mpeg","video/x-mpeq2a"]],["mp3",["audio/mpeg","audio/mpeg3","video/mpeg","audio/x-mpeg-3","video/x-mpeg"]],["mp4",["video/mp4","application/mp4"]],["mp4a","audio/mp4"],["mpa",["video/mpeg","audio/mpeg"]],["mpc",["application/vnd.mophun.certificate","application/x-project"]],["mpe","video/mpeg"],["mpeg","video/mpeg"],["mpg",["video/mpeg","audio/mpeg"]],["mpga","audio/mpeg"],["mpkg","application/vnd.apple.installer+xml"],["mpm","application/vnd.blueice.multipass"],["mpn","application/vnd.mophun.application"],["mpp","application/vnd.ms-project"],["mpt","application/x-project"],["mpv","application/x-project"],["mpv2","video/mpeg"],["mpx","application/x-project"],["mpy","application/vnd.ibm.minipay"],["mqy","application/vnd.mobius.mqy"],["mrc","application/marc"],["mrcx","application/marcxml+xml"],["ms","application/x-troff-ms"],["mscml","application/mediaservercontrol+xml"],["mseq","application/vnd.mseq"],["msf","application/vnd.epson.msf"],["msg","application/vnd.ms-outlook"],["msh","model/mesh"],["msl","application/vnd.mobius.msl"],["msty","application/vnd.muvee.style"],["mts","model/vnd.mts"],["mus","application/vnd.musician"],["musicxml","application/vnd.recordare.musicxml+xml"],["mv","video/x-sgi-movie"],["mvb","application/x-msmediaview"],["mwf","application/vnd.mfer"],["mxf","application/mxf"],["mxl","application/vnd.recordare.musicxml"],["mxml","application/xv+xml"],["mxs","application/vnd.triscape.mxs"],["mxu","video/vnd.mpegurl"],["my","audio/make"],["mzz","application/x-vnd.audioexplosion.mzz"],["n-gage","application/vnd.nokia.n-gage.symbian.install"],["n3","text/n3"],["nap","image/naplps"],["naplps","image/naplps"],["nbp","application/vnd.wolfram.player"],["nc","application/x-netcdf"],["ncm","application/vnd.nokia.configuration-message"],["ncx","application/x-dtbncx+xml"],["ngdat","application/vnd.nokia.n-gage.data"],["nif","image/x-niff"],["niff","image/x-niff"],["nix","application/x-mix-transfer"],["nlu","application/vnd.neurolanguage.nlu"],["nml","application/vnd.enliven"],["nnd","application/vnd.noblenet-directory"],["nns","application/vnd.noblenet-sealer"],["nnw","application/vnd.noblenet-web"],["npx","image/vnd.net-fpx"],["nsc","application/x-conference"],["nsf","application/vnd.lotus-notes"],["nvd","application/x-navidoc"],["nws","message/rfc822"],["o","application/octet-stream"],["oa2","application/vnd.fujitsu.oasys2"],["oa3","application/vnd.fujitsu.oasys3"],["oas","application/vnd.fujitsu.oasys"],["obd","application/x-msbinder"],["oda","application/oda"],["odb","application/vnd.oasis.opendocument.database"],["odc","application/vnd.oasis.opendocument.chart"],["odf","application/vnd.oasis.opendocument.formula"],["odft","application/vnd.oasis.opendocument.formula-template"],["odg","application/vnd.oasis.opendocument.graphics"],["odi","application/vnd.oasis.opendocument.image"],["odm","application/vnd.oasis.opendocument.text-master"],["odp","application/vnd.oasis.opendocument.presentation"],["ods","application/vnd.oasis.opendocument.spreadsheet"],["odt","application/vnd.oasis.opendocument.text"],["oga","audio/ogg"],["ogv","video/ogg"],["ogx","application/ogg"],["omc","application/x-omc"],["omcd","application/x-omcdatamaker"],["omcr","application/x-omcregerator"],["onetoc","application/onenote"],["opf","application/oebps-package+xml"],["org","application/vnd.lotus-organizer"],["osf","application/vnd.yamaha.openscoreformat"],["osfpvg","application/vnd.yamaha.openscoreformat.osfpvg+xml"],["otc","application/vnd.oasis.opendocument.chart-template"],["otf","application/x-font-otf"],["otg","application/vnd.oasis.opendocument.graphics-template"],["oth","application/vnd.oasis.opendocument.text-web"],["oti","application/vnd.oasis.opendocument.image-template"],["otp","application/vnd.oasis.opendocument.presentation-template"],["ots","application/vnd.oasis.opendocument.spreadsheet-template"],["ott","application/vnd.oasis.opendocument.text-template"],["oxt","application/vnd.openofficeorg.extension"],["p","text/x-pascal"],["p10",["application/pkcs10","application/x-pkcs10"]],["p12",["application/pkcs-12","application/x-pkcs12"]],["p7a","application/x-pkcs7-signature"],["p7b","application/x-pkcs7-certificates"],["p7c",["application/pkcs7-mime","application/x-pkcs7-mime"]],["p7m",["application/pkcs7-mime","application/x-pkcs7-mime"]],["p7r","application/x-pkcs7-certreqresp"],["p7s",["application/pkcs7-signature","application/x-pkcs7-signature"]],["p8","application/pkcs8"],["par","text/plain-bas"],["part","application/pro_eng"],["pas","text/pascal"],["paw","application/vnd.pawaafile"],["pbd","application/vnd.powerbuilder6"],["pbm","image/x-portable-bitmap"],["pcf","application/x-font-pcf"],["pcl",["application/vnd.hp-pcl","application/x-pcl"]],["pclxl","application/vnd.hp-pclxl"],["pct","image/x-pict"],["pcurl","application/vnd.curl.pcurl"],["pcx","image/x-pcx"],["pdb",["application/vnd.palm","chemical/x-pdb"]],["pdf","application/pdf"],["pfa","application/x-font-type1"],["pfr","application/font-tdpfr"],["pfunk",["audio/make","audio/make.my.funk"]],["pfx","application/x-pkcs12"],["pgm",["image/x-portable-graymap","image/x-portable-greymap"]],["pgn","application/x-chess-pgn"],["pgp","application/pgp-signature"],["pic",["image/pict","image/x-pict"]],["pict","image/pict"],["pkg","application/x-newton-compatible-pkg"],["pki","application/pkixcmp"],["pkipath","application/pkix-pkipath"],["pko",["application/ynd.ms-pkipko","application/vnd.ms-pki.pko"]],["pl",["text/plain","text/x-script.perl"]],["plb","application/vnd.3gpp.pic-bw-large"],["plc","application/vnd.mobius.plc"],["plf","application/vnd.pocketlearn"],["pls","application/pls+xml"],["plx","application/x-pixclscript"],["pm",["text/x-script.perl-module","image/x-xpixmap"]],["pm4","application/x-pagemaker"],["pm5","application/x-pagemaker"],["pma","application/x-perfmon"],["pmc","application/x-perfmon"],["pml",["application/vnd.ctc-posml","application/x-perfmon"]],["pmr","application/x-perfmon"],["pmw","application/x-perfmon"],["png","image/png"],["pnm",["application/x-portable-anymap","image/x-portable-anymap"]],["portpkg","application/vnd.macports.portpkg"],["pot",["application/vnd.ms-powerpoint","application/mspowerpoint"]],["potm","application/vnd.ms-powerpoint.template.macroenabled.12"],["potx","application/vnd.openxmlformats-officedocument.presentationml.template"],["pov","model/x-pov"],["ppa","application/vnd.ms-powerpoint"],["ppam","application/vnd.ms-powerpoint.addin.macroenabled.12"],["ppd","application/vnd.cups-ppd"],["ppm","image/x-portable-pixmap"],["pps",["application/vnd.ms-powerpoint","application/mspowerpoint"]],["ppsm","application/vnd.ms-powerpoint.slideshow.macroenabled.12"],["ppsx","application/vnd.openxmlformats-officedocument.presentationml.slideshow"],["ppt",["application/vnd.ms-powerpoint","application/mspowerpoint","application/powerpoint","application/x-mspowerpoint"]],["pptm","application/vnd.ms-powerpoint.presentation.macroenabled.12"],["pptx","application/vnd.openxmlformats-officedocument.presentationml.presentation"],["ppz","application/mspowerpoint"],["prc","application/x-mobipocket-ebook"],["pre",["application/vnd.lotus-freelance","application/x-freelance"]],["prf","application/pics-rules"],["prt","application/pro_eng"],["ps","application/postscript"],["psb","application/vnd.3gpp.pic-bw-small"],["psd",["application/octet-stream","image/vnd.adobe.photoshop"]],["psf","application/x-font-linux-psf"],["pskcxml","application/pskc+xml"],["ptid","application/vnd.pvi.ptid1"],["pub","application/x-mspublisher"],["pvb","application/vnd.3gpp.pic-bw-var"],["pvu","paleovu/x-pv"],["pwn","application/vnd.3m.post-it-notes"],["pwz","application/vnd.ms-powerpoint"],["py","text/x-script.phyton"],["pya","audio/vnd.ms-playready.media.pya"],["pyc","application/x-bytecode.python"],["pyv","video/vnd.ms-playready.media.pyv"],["qam","application/vnd.epson.quickanime"],["qbo","application/vnd.intu.qbo"],["qcp","audio/vnd.qcelp"],["qd3","x-world/x-3dmf"],["qd3d","x-world/x-3dmf"],["qfx","application/vnd.intu.qfx"],["qif","image/x-quicktime"],["qps","application/vnd.publishare-delta-tree"],["qt","video/quicktime"],["qtc","video/x-qtc"],["qti","image/x-quicktime"],["qtif","image/x-quicktime"],["qxd","application/vnd.quark.quarkxpress"],["ra",["audio/x-realaudio","audio/x-pn-realaudio","audio/x-pn-realaudio-plugin"]],["ram","audio/x-pn-realaudio"],["rar","application/x-rar-compressed"],["ras",["image/cmu-raster","application/x-cmu-raster","image/x-cmu-raster"]],["rast","image/cmu-raster"],["rcprofile","application/vnd.ipunplugged.rcprofile"],["rdf","application/rdf+xml"],["rdz","application/vnd.data-vision.rdz"],["rep","application/vnd.businessobjects"],["res","application/x-dtbresource+xml"],["rexx","text/x-script.rexx"],["rf","image/vnd.rn-realflash"],["rgb","image/x-rgb"],["rif","application/reginfo+xml"],["rip","audio/vnd.rip"],["rl","application/resource-lists+xml"],["rlc","image/vnd.fujixerox.edmics-rlc"],["rld","application/resource-lists-diff+xml"],["rm",["application/vnd.rn-realmedia","audio/x-pn-realaudio"]],["rmi","audio/mid"],["rmm","audio/x-pn-realaudio"],["rmp",["audio/x-pn-realaudio-plugin","audio/x-pn-realaudio"]],["rms","application/vnd.jcp.javame.midlet-rms"],["rnc","application/relax-ng-compact-syntax"],["rng",["application/ringing-tones","application/vnd.nokia.ringing-tone"]],["rnx","application/vnd.rn-realplayer"],["roff","application/x-troff"],["rp","image/vnd.rn-realpix"],["rp9","application/vnd.cloanto.rp9"],["rpm","audio/x-pn-realaudio-plugin"],["rpss","application/vnd.nokia.radio-presets"],["rpst","application/vnd.nokia.radio-preset"],["rq","application/sparql-query"],["rs","application/rls-services+xml"],["rsd","application/rsd+xml"],["rt",["text/richtext","text/vnd.rn-realtext"]],["rtf",["application/rtf","text/richtext","application/x-rtf"]],["rtx",["text/richtext","application/rtf"]],["rv","video/vnd.rn-realvideo"],["s","text/x-asm"],["s3m","audio/s3m"],["saf","application/vnd.yamaha.smaf-audio"],["saveme","application/octet-stream"],["sbk","application/x-tbook"],["sbml","application/sbml+xml"],["sc","application/vnd.ibm.secure-container"],["scd","application/x-msschedule"],["scm",["application/vnd.lotus-screencam","video/x-scm","text/x-script.guile","application/x-lotusscreencam","text/x-script.scheme"]],["scq","application/scvp-cv-request"],["scs","application/scvp-cv-response"],["sct","text/scriptlet"],["scurl","text/vnd.curl.scurl"],["sda","application/vnd.stardivision.draw"],["sdc","application/vnd.stardivision.calc"],["sdd","application/vnd.stardivision.impress"],["sdkm","application/vnd.solent.sdkm+xml"],["sdml","text/plain"],["sdp",["application/sdp","application/x-sdp"]],["sdr","application/sounder"],["sdw","application/vnd.stardivision.writer"],["sea",["application/sea","application/x-sea"]],["see","application/vnd.seemail"],["seed","application/vnd.fdsn.seed"],["sema","application/vnd.sema"],["semd","application/vnd.semd"],["semf","application/vnd.semf"],["ser","application/java-serialized-object"],["set","application/set"],["setpay","application/set-payment-initiation"],["setreg","application/set-registration-initiation"],["sfd-hdstx","application/vnd.hydrostatix.sof-data"],["sfs","application/vnd.spotfire.sfs"],["sgl","application/vnd.stardivision.writer-global"],["sgm",["text/sgml","text/x-sgml"]],["sgml",["text/sgml","text/x-sgml"]],["sh",["application/x-shar","application/x-bsh","application/x-sh","text/x-script.sh"]],["shar",["application/x-bsh","application/x-shar"]],["shf","application/shf+xml"],["shtml",["text/html","text/x-server-parsed-html"]],["sid","audio/x-psid"],["sis","application/vnd.symbian.install"],["sit",["application/x-stuffit","application/x-sit"]],["sitx","application/x-stuffitx"],["skd","application/x-koan"],["skm","application/x-koan"],["skp",["application/vnd.koan","application/x-koan"]],["skt","application/x-koan"],["sl","application/x-seelogo"],["sldm","application/vnd.ms-powerpoint.slide.macroenabled.12"],["sldx","application/vnd.openxmlformats-officedocument.presentationml.slide"],["slt","application/vnd.epson.salt"],["sm","application/vnd.stepmania.stepchart"],["smf","application/vnd.stardivision.math"],["smi",["application/smil","application/smil+xml"]],["smil","application/smil"],["snd",["audio/basic","audio/x-adpcm"]],["snf","application/x-font-snf"],["sol","application/solids"],["spc",["text/x-speech","application/x-pkcs7-certificates"]],["spf","application/vnd.yamaha.smaf-phrase"],["spl",["application/futuresplash","application/x-futuresplash"]],["spot","text/vnd.in3d.spot"],["spp","application/scvp-vp-response"],["spq","application/scvp-vp-request"],["spr","application/x-sprite"],["sprite","application/x-sprite"],["src","application/x-wais-source"],["sru","application/sru+xml"],["srx","application/sparql-results+xml"],["sse","application/vnd.kodak-descriptor"],["ssf","application/vnd.epson.ssf"],["ssi","text/x-server-parsed-html"],["ssm","application/streamingmedia"],["ssml","application/ssml+xml"],["sst",["application/vnd.ms-pkicertstore","application/vnd.ms-pki.certstore"]],["st","application/vnd.sailingtracker.track"],["stc","application/vnd.sun.xml.calc.template"],["std","application/vnd.sun.xml.draw.template"],["step","application/step"],["stf","application/vnd.wt.stf"],["sti","application/vnd.sun.xml.impress.template"],["stk","application/hyperstudio"],["stl",["application/vnd.ms-pkistl","application/sla","application/vnd.ms-pki.stl","application/x-navistyle"]],["stm","text/html"],["stp","application/step"],["str","application/vnd.pg.format"],["stw","application/vnd.sun.xml.writer.template"],["sub","image/vnd.dvb.subtitle"],["sus","application/vnd.sus-calendar"],["sv4cpio","application/x-sv4cpio"],["sv4crc","application/x-sv4crc"],["svc","application/vnd.dvb.service"],["svd","application/vnd.svd"],["svf",["image/vnd.dwg","image/x-dwg"]],["svg","image/svg+xml"],["svr",["x-world/x-svr","application/x-world"]],["swf","application/x-shockwave-flash"],["swi","application/vnd.aristanetworks.swi"],["sxc","application/vnd.sun.xml.calc"],["sxd","application/vnd.sun.xml.draw"],["sxg","application/vnd.sun.xml.writer.global"],["sxi","application/vnd.sun.xml.impress"],["sxm","application/vnd.sun.xml.math"],["sxw","application/vnd.sun.xml.writer"],["t",["text/troff","application/x-troff"]],["talk","text/x-speech"],["tao","application/vnd.tao.intent-module-archive"],["tar","application/x-tar"],["tbk",["application/toolbook","application/x-tbook"]],["tcap","application/vnd.3gpp2.tcap"],["tcl",["text/x-script.tcl","application/x-tcl"]],["tcsh","text/x-script.tcsh"],["teacher","application/vnd.smart.teacher"],["tei","application/tei+xml"],["tex","application/x-tex"],["texi","application/x-texinfo"],["texinfo","application/x-texinfo"],["text",["application/plain","text/plain"]],["tfi","application/thraud+xml"],["tfm","application/x-tex-tfm"],["tgz",["application/gnutar","application/x-compressed"]],["thmx","application/vnd.ms-officetheme"],["tif",["image/tiff","image/x-tiff"]],["tiff",["image/tiff","image/x-tiff"]],["tmo","application/vnd.tmobile-livetv"],["torrent","application/x-bittorrent"],["tpl","application/vnd.groove-tool-template"],["tpt","application/vnd.trid.tpt"],["tr","application/x-troff"],["tra","application/vnd.trueapp"],["trm","application/x-msterminal"],["tsd","application/timestamped-data"],["tsi","audio/tsp-audio"],["tsp",["application/dsptype","audio/tsplayer"]],["tsv","text/tab-separated-values"],["ttf","application/x-font-ttf"],["ttl","text/turtle"],["turbot","image/florian"],["twd","application/vnd.simtech-mindmapper"],["txd","application/vnd.genomatix.tuxedo"],["txf","application/vnd.mobius.txf"],["txt","text/plain"],["ufd","application/vnd.ufdl"],["uil","text/x-uil"],["uls","text/iuls"],["umj","application/vnd.umajin"],["uni","text/uri-list"],["unis","text/uri-list"],["unityweb","application/vnd.unity"],["unv","application/i-deas"],["uoml","application/vnd.uoml+xml"],["uri","text/uri-list"],["uris","text/uri-list"],["ustar",["application/x-ustar","multipart/x-ustar"]],["utz","application/vnd.uiq.theme"],["uu",["application/octet-stream","text/x-uuencode"]],["uue","text/x-uuencode"],["uva","audio/vnd.dece.audio"],["uvh","video/vnd.dece.hd"],["uvi","image/vnd.dece.graphic"],["uvm","video/vnd.dece.mobile"],["uvp","video/vnd.dece.pd"],["uvs","video/vnd.dece.sd"],["uvu","video/vnd.uvvu.mp4"],["uvv","video/vnd.dece.video"],["vcd","application/x-cdlink"],["vcf","text/x-vcard"],["vcg","application/vnd.groove-vcard"],["vcs","text/x-vcalendar"],["vcx","application/vnd.vcx"],["vda","application/vda"],["vdo","video/vdo"],["vew","application/groupwise"],["vis","application/vnd.visionary"],["viv",["video/vivo","video/vnd.vivo"]],["vivo",["video/vivo","video/vnd.vivo"]],["vmd","application/vocaltec-media-desc"],["vmf","application/vocaltec-media-file"],["voc",["audio/voc","audio/x-voc"]],["vos","video/vosaic"],["vox","audio/voxware"],["vqe","audio/x-twinvq-plugin"],["vqf","audio/x-twinvq"],["vql","audio/x-twinvq-plugin"],["vrml",["model/vrml","x-world/x-vrml","application/x-vrml"]],["vrt","x-world/x-vrt"],["vsd",["application/vnd.visio","application/x-visio"]],["vsf","application/vnd.vsf"],["vst","application/x-visio"],["vsw","application/x-visio"],["vtu","model/vnd.vtu"],["vxml","application/voicexml+xml"],["w60","application/wordperfect6.0"],["w61","application/wordperfect6.1"],["w6w","application/msword"],["wad","application/x-doom"],["wav",["audio/wav","audio/x-wav"]],["wax","audio/x-ms-wax"],["wb1","application/x-qpro"],["wbmp","image/vnd.wap.wbmp"],["wbs","application/vnd.criticaltools.wbs+xml"],["wbxml","application/vnd.wap.wbxml"],["wcm","application/vnd.ms-works"],["wdb","application/vnd.ms-works"],["web","application/vnd.xara"],["weba","audio/webm"],["webm","video/webm"],["webp","image/webp"],["wg","application/vnd.pmi.widget"],["wgt","application/widget"],["wiz","application/msword"],["wk1","application/x-123"],["wks","application/vnd.ms-works"],["wm","video/x-ms-wm"],["wma","audio/x-ms-wma"],["wmd","application/x-ms-wmd"],["wmf",["windows/metafile","application/x-msmetafile"]],["wml","text/vnd.wap.wml"],["wmlc","application/vnd.wap.wmlc"],["wmls","text/vnd.wap.wmlscript"],["wmlsc","application/vnd.wap.wmlscriptc"],["wmv","video/x-ms-wmv"],["wmx","video/x-ms-wmx"],["wmz","application/x-ms-wmz"],["woff","application/x-font-woff"],["word","application/msword"],["wp","application/wordperfect"],["wp5",["application/wordperfect","application/wordperfect6.0"]],["wp6","application/wordperfect"],["wpd",["application/wordperfect","application/vnd.wordperfect","application/x-wpwin"]],["wpl","application/vnd.ms-wpl"],["wps","application/vnd.ms-works"],["wq1","application/x-lotus"],["wqd","application/vnd.wqd"],["wri",["application/mswrite","application/x-wri","application/x-mswrite"]],["wrl",["model/vrml","x-world/x-vrml","application/x-world"]],["wrz",["model/vrml","x-world/x-vrml"]],["wsc","text/scriplet"],["wsdl","application/wsdl+xml"],["wspolicy","application/wspolicy+xml"],["wsrc","application/x-wais-source"],["wtb","application/vnd.webturbo"],["wtk","application/x-wintalk"],["wvx","video/x-ms-wvx"],["x-png","image/png"],["x3d","application/vnd.hzn-3d-crossword"],["xaf","x-world/x-vrml"],["xap","application/x-silverlight-app"],["xar","application/vnd.xara"],["xbap","application/x-ms-xbap"],["xbd","application/vnd.fujixerox.docuworks.binder"],["xbm",["image/xbm","image/x-xbm","image/x-xbitmap"]],["xdf","application/xcap-diff+xml"],["xdm","application/vnd.syncml.dm+xml"],["xdp","application/vnd.adobe.xdp+xml"],["xdr","video/x-amt-demorun"],["xdssc","application/dssc+xml"],["xdw","application/vnd.fujixerox.docuworks"],["xenc","application/xenc+xml"],["xer","application/patch-ops-error+xml"],["xfdf","application/vnd.adobe.xfdf"],["xfdl","application/vnd.xfdl"],["xgz","xgl/drawing"],["xhtml","application/xhtml+xml"],["xif","image/vnd.xiff"],["xl","application/excel"],["xla",["application/vnd.ms-excel","application/excel","application/x-msexcel","application/x-excel"]],["xlam","application/vnd.ms-excel.addin.macroenabled.12"],["xlb",["application/excel","application/vnd.ms-excel","application/x-excel"]],["xlc",["application/vnd.ms-excel","application/excel","application/x-excel"]],["xld",["application/excel","application/x-excel"]],["xlk",["application/excel","application/x-excel"]],["xll",["application/excel","application/vnd.ms-excel","application/x-excel"]],["xlm",["application/vnd.ms-excel","application/excel","application/x-excel"]],["xls",["application/vnd.ms-excel","application/excel","application/x-msexcel","application/x-excel"]],["xlsb","application/vnd.ms-excel.sheet.binary.macroenabled.12"],["xlsm","application/vnd.ms-excel.sheet.macroenabled.12"],["xlsx","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"],["xlt",["application/vnd.ms-excel","application/excel","application/x-excel"]],["xltm","application/vnd.ms-excel.template.macroenabled.12"],["xltx","application/vnd.openxmlformats-officedocument.spreadsheetml.template"],["xlv",["application/excel","application/x-excel"]],["xlw",["application/vnd.ms-excel","application/excel","application/x-msexcel","application/x-excel"]],["xm","audio/xm"],["xml",["application/xml","text/xml","application/atom+xml","application/rss+xml"]],["xmz","xgl/movie"],["xo","application/vnd.olpc-sugar"],["xof","x-world/x-vrml"],["xop","application/xop+xml"],["xpi","application/x-xpinstall"],["xpix","application/x-vnd.ls-xpix"],["xpm",["image/xpm","image/x-xpixmap"]],["xpr","application/vnd.is-xpr"],["xps","application/vnd.ms-xpsdocument"],["xpw","application/vnd.intercon.formnet"],["xslt","application/xslt+xml"],["xsm","application/vnd.syncml+xml"],["xspf","application/xspf+xml"],["xsr","video/x-amt-showrun"],["xul","application/vnd.mozilla.xul+xml"],["xwd",["image/x-xwd","image/x-xwindowdump"]],["xyz",["chemical/x-xyz","chemical/x-pdb"]],["yang","application/yang"],["yin","application/yin+xml"],["z",["application/x-compressed","application/x-compress"]],["zaz","application/vnd.zzazz.deck+xml"],["zip",["application/zip","multipart/x-zip","application/x-zip-compressed","application/x-compressed"]],["zir","application/vnd.zul"],["zmm","application/vnd.handheld-entertainment+xml"],["zoo","application/octet-stream"],["zsh","text/x-script.zsh"]]);Hy.exports={detectMimeType(r){if(!r)return Zy;let e=TI.parse(r),t=(e.ext.substr(1)||e.name||"").split("?").shift().trim().toLowerCase(),n=Fy.has(t)?Fy.get(t):Zy;return Array.isArray(n)?n[0]:n},detectExtension(r){if(!r)return zI;let e=(r||"").toLowerCase().trim().split("/"),t=e.shift().trim(),n=e.join("/").trim();if(Uy.has(t+"/"+n)){let i=Uy.get(t+"/"+n);return Array.isArray(i)?i[0]:i}switch(t){case"text":return"txt";default:return"bin"}}}});var wd=_((NZ,Qy)=>{"use strict";var Vy="-",PI=/^xn--/,RI=/[^\0-\x7F]/,CI=/[\x2E\u3002\uFF0E\uFF61]/g,II={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},_d=35,qt=Math.floor,bd=String.fromCharCode;function br(r){throw new RangeError(II[r])}function AI(r,e){let t=[],n=r.length;for(;n--;)t[n]=e(r[n]);return t}function Wy(r,e){let t=r.split("@"),n="";t.length>1&&(n=t[0]+"@",r=t[1]),r=r.replace(CI,".");let i=r.split("."),o=AI(i,e).join(".");return n+o}function Gy(r){let e=[],t=0,n=r.length;for(;t<n;){let i=r.charCodeAt(t++);if(i>=55296&&i<=56319&&t<n){let o=r.charCodeAt(t++);(o&64512)==56320?e.push(((i&1023)<<10)+(o&1023)+65536):(e.push(i),t--)}else e.push(i)}return e}var OI=r=>String.fromCodePoint(...r),NI=function(r){return r>=48&&r<58?26+(r-48):r>=65&&r<91?r-65:r>=97&&r<123?r-97:36},By=function(r,e){return r+22+75*(r<26)-((e!=0)<<5)},Ky=function(r,e,t){let n=0;for(r=t?qt(r/700):r>>1,r+=qt(r/e);r>_d*26>>1;n+=36)r=qt(r/_d);return qt(n+(_d+1)*r/(r+38))},Jy=function(r){let e=[],t=r.length,n=0,i=128,o=72,s=r.lastIndexOf(Vy);s<0&&(s=0);for(let a=0;a<s;++a)r.charCodeAt(a)>=128&&br("not-basic"),e.push(r.charCodeAt(a));for(let a=s>0?s+1:0;a<t;){let c=n;for(let u=1,p=36;;p+=36){a>=t&&br("invalid-input");let d=NI(r.charCodeAt(a++));d>=36&&br("invalid-input"),d>qt((2147483647-n)/u)&&br("overflow"),n+=d*u;let f=p<=o?1:p>=o+26?26:p-o;if(d<f)break;let m=36-f;u>qt(2147483647/m)&&br("overflow"),u*=m}let l=e.length+1;o=Ky(n-c,l,c==0),qt(n/l)>2147483647-i&&br("overflow"),i+=qt(n/l),n%=l,e.splice(n++,0,i)}return String.fromCodePoint(...e)},Xy=function(r){let e=[];r=Gy(r);let t=r.length,n=128,i=0,o=72;for(let c of r)c<128&&e.push(bd(c));let s=e.length,a=s;for(s&&e.push(Vy);a<t;){let c=2147483647;for(let u of r)u>=n&&u<c&&(c=u);let l=a+1;c-n>qt((2147483647-i)/l)&&br("overflow"),i+=(c-n)*l,n=c;for(let u of r)if(u<n&&++i>2147483647&&br("overflow"),u===n){let p=i;for(let d=36;;d+=36){let f=d<=o?1:d>=o+26?26:d-o;if(p<f)break;let m=p-f,h=36-f;e.push(bd(By(f+m%h,0))),p=qt(m/h)}e.push(bd(By(p,0))),o=Ky(i,l,a===s),i=0,++a}++i,++n}return e.join("")},jI=function(r){return Wy(r,function(e){return PI.test(e)?Jy(e.slice(4).toLowerCase()):e})},MI=function(r){return Wy(r,function(e){return RI.test(e)?"xn--"+Xy(e):e})},LI={version:"2.3.1",ucs2:{decode:Gy,encode:OI},decode:Jy,encode:Xy,toASCII:MI,toUnicode:jI};Qy.exports=LI});var Ed=_((jZ,e_)=>{"use strict";var{Transform:DI}=N("stream");function kd(r){return typeof r=="string"&&(r=Buffer.from(r,"utf-8")),r.toString("base64")}function Yy(r,e){if(r=(r||"").toString(),e=e||76,r.length<=e)return r;let t=[],n=0,i=e*1024,o=new RegExp(".{"+e+"}","g");for(;n<r.length;){let s=r.substr(n,i).replace(o,`$&\r
|
|
9
|
+
`);t.push(s),n+=i}return t.join("")}var Sd=class extends DI{constructor(e){super(),this.options=e||{},this.options.lineLength!==!1&&(this.options.lineLength=this.options.lineLength||76),this._curLine="",this._remainingBytes=!1,this.inputBytes=0,this.outputBytes=0}_transform(e,t,n){if(t!=="buffer"&&(e=Buffer.from(e,t)),!e||!e.length)return setImmediate(n);this.inputBytes+=e.length,this._remainingBytes&&this._remainingBytes.length&&(e=Buffer.concat([this._remainingBytes,e],this._remainingBytes.length+e.length),this._remainingBytes=!1),e.length%3?(this._remainingBytes=e.slice(e.length-e.length%3),e=e.slice(0,e.length-e.length%3)):this._remainingBytes=!1;let i=this._curLine+kd(e);if(this.options.lineLength){i=Yy(i,this.options.lineLength);let o=i.lastIndexOf(`
|
|
10
|
+
`);o<0?(this._curLine=i,i=""):(this._curLine=i.substring(o+1),i=i.substring(0,o+1),i&&!i.endsWith(`\r
|
|
11
|
+
`)&&(i+=`\r
|
|
12
|
+
`))}else this._curLine="";i&&(this.outputBytes+=i.length,this.push(Buffer.from(i,"ascii"))),setImmediate(n)}_flush(e){this._remainingBytes&&this._remainingBytes.length&&(this._curLine+=kd(this._remainingBytes)),this._curLine&&(this.outputBytes+=this._curLine.length,this.push(Buffer.from(this._curLine,"ascii")),this._curLine=""),e()}};e_.exports={encode:kd,wrap:Yy,Encoder:Sd}});var zd=_((MZ,r_)=>{"use strict";var{Transform:qI}=N("stream"),ZI=[[9],[10],[13],[32,60],[62,126]];function $d(r){typeof r=="string"&&(r=Buffer.from(r,"utf-8"));let e="",t;for(let n=0,i=r.length;n<i;n++){if(t=r[n],UI(t,ZI)&&!((t===32||t===9)&&(n===i-1||r[n+1]===10||r[n+1]===13))){e+=String.fromCharCode(t);continue}e+="="+(t<16?"0":"")+t.toString(16).toUpperCase()}return e}function t_(r,e){if(r=(r||"").toString(),e=e||76,r.length<=e)return r;let t=0,n=r.length,i,o,s,a=Math.floor(e/3),c="";for(;t<n;){if(s=r.substr(t,e),i=s.match(/\r\n/)){s=s.substr(0,i.index+i[0].length),c+=s,t+=s.length;continue}if(s.substr(-1)===`
|
|
13
|
+
`){c+=s,t+=s.length;continue}if(i=s.substr(-a).match(/\n.*?$/)){s=s.substr(0,s.length-(i[0].length-1)),c+=s,t+=s.length;continue}if(s.length>e-a&&(i=s.substr(-a).match(/[ \t.,!?][^ \t.,!?]*$/)))s=s.substr(0,s.length-(i[0].length-1));else if(s.match(/[=][\da-f]{0,2}$/i))for((i=s.match(/[=][\da-f]{0,1}$/i))&&(s=s.substr(0,s.length-i[0].length));s.length>3&&s.length<n-t&&!s.match(/^(?:=[\da-f]{2}){1,4}$/i)&&(i=s.match(/[=][\da-f]{2}$/gi))&&(o=parseInt(i[0].substr(1,2),16),!(o<128||(s=s.substr(0,s.length-3),o>=192))););t+s.length<n&&s.substr(-1)!==`
|
|
14
|
+
`?(s.length===e&&s.match(/[=][\da-f]{2}$/i)?s=s.substr(0,s.length-3):s.length===e&&(s=s.substr(0,s.length-1)),t+=s.length,s+=`=\r
|
|
15
|
+
`):t+=s.length,c+=s}return c}function UI(r,e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.length&&(n.length===1&&r===n[0]||n.length===2&&r>=n[0]&&r<=n[1]))return!0}return!1}var Td=class extends qI{constructor(e){super(),this.options=e||{},this.options.lineLength!==!1&&(this.options.lineLength=this.options.lineLength||76),this._curLine="",this.inputBytes=0,this.outputBytes=0}_transform(e,t,n){let i;if(t!=="buffer"&&(e=Buffer.from(e,t)),!e||!e.length)return n();this.inputBytes+=e.length,this.options.lineLength?(i=this._curLine+$d(e),i=t_(i,this.options.lineLength),i=i.replace(/(^|\n)([^\n]*)$/,(o,s,a)=>(this._curLine=a,s)),i&&(this.outputBytes+=i.length,this.push(i))):(i=$d(e),this.outputBytes+=i.length,this.push(i,"ascii")),n()}_flush(e){this._curLine&&(this.outputBytes+=this._curLine.length,this.push(this._curLine,"ascii")),e()}};r_.exports={encode:$d,wrap:t_,Encoder:Td}});var lo=_((LZ,i_)=>{"use strict";var co=Ed(),FI=zd(),n_=yd();i_.exports={isPlainText(r,e){return typeof r=="string"&&!(e?/[\x00-\x08\x0b\x0c\x0e-\x1f"\u0080-\uFFFF]/:/[\x00-\x08\x0b\x0c\x0e-\x1f\u0080-\uFFFF]/).test(r)},hasLongerLines(r,e){return r.length>128*1024?!0:new RegExp("^.{"+(e+1)+",}","m").test(r)},encodeWord(r,e,t){e=(e||"Q").toString().toUpperCase().trim().charAt(0),t=t||0;let n,i="UTF-8";if(t&&t>7+i.length&&(t-=7+i.length),e==="Q"?n=FI.encode(r).replace(/[^a-z0-9!*+\-/=]/gi,o=>{let s=o.charCodeAt(0).toString(16).toUpperCase();return o===" "?"_":"="+(s.length===1?"0"+s:s)}):e==="B"&&(n=typeof r=="string"?r:co.encode(r),t=t?Math.max(3,(t-t%4)/4*3):0),t&&(e!=="B"?n:co.encode(r)).length>t)if(e==="Q")n=this.splitMimeEncodedString(n,t).join("?= =?"+i+"?"+e+"?");else{let o=[],s="";for(let a=0,c=n.length;a<c;a++){let l=n.charAt(a);/[\ud83c\ud83d\ud83e]/.test(l)&&a<c-1&&(l+=n.charAt(++a)),Buffer.byteLength(s+l)<=t||a===0?s+=l:(o.push(co.encode(s)),s=l)}s&&o.push(co.encode(s)),o.length>1?n=o.join("?= =?"+i+"?"+e+"?"):n=o.join("")}else e==="B"&&(n=co.encode(r));return"=?"+i+"?"+e+"?"+n+(n.substr(-2)==="?="?"":"?=")},encodeWords(r,e,t,n){t=t||0;let i=r.match(/(?:^|\s)([^\s]*["\u0080-\uFFFF])/);if(!i)return r;if(n)return this.encodeWord(r,e,t);let o=r.match(/(["\u0080-\uFFFF][^\s]*)[^"\u0080-\uFFFF]*$/);if(!o)return r;let s=i.index+(i[0].match(/[^\s]/)||{index:0}).index,a=o.index+(o[1]||"").length;return(s?r.substr(0,s):"")+this.encodeWord(r.substring(s,a),e||"Q",t)+(a<r.length?r.substr(a):"")},buildHeaderValue(r){let e=[];return Object.keys(r.params||{}).forEach(t=>{let n=r.params[t];!this.isPlainText(n,!0)||n.length>=75?this.buildHeaderParam(t,n,50).forEach(i=>{!/[\s"\\;:/=(),<>@[\]?]|^[-']|'$/.test(i.value)||i.key.substr(-1)==="*"?e.push(i.key+"="+i.value):e.push(i.key+"="+JSON.stringify(i.value))}):/[\s'"\\;:/=(),<>@[\]?]|^-/.test(n)?e.push(t+"="+JSON.stringify(n)):e.push(t+"="+n)}),r.value+(e.length?"; "+e.join("; "):"")},buildHeaderParam(r,e,t){let n=[],i=typeof e=="string"?e:(e||"").toString(),o,s,a,c=0,l,u;if(t=t||50,this.isPlainText(e,!0)){if(i.length<=t)return[{key:r,value:i}];i=i.replace(new RegExp(".{"+t+"}","g"),p=>(n.push({line:p}),"")),i&&n.push({line:i})}else{if(/[\uD800-\uDBFF]/.test(i)){let d=[];for(l=0,u=i.length;l<u;l++)o=i.charAt(l),s=o.charCodeAt(0),s>=55296&&s<=56319&&l<u-1?(o+=i.charAt(l+1),d.push(o),l++):d.push(o);i=d}a="utf-8''";let p=!0;for(c=0,l=0,u=i.length;l<u;l++){if(o=i[l],p)o=this.safeEncodeURIComponent(o);else if(o=o===" "?o:this.safeEncodeURIComponent(o),o!==i[l])if((this.safeEncodeURIComponent(a)+o).length>=t)n.push({line:a,encoded:p}),a="",c=l-1;else{p=!0,l=c,a="";continue}(a+o).length>=t?(n.push({line:a,encoded:p}),a=o=i[l]===" "?" ":this.safeEncodeURIComponent(i[l]),o===i[l]?(p=!1,c=l-1):p=!0):a+=o}a&&n.push({line:a,encoded:p})}return n.map((p,d)=>({key:r+"*"+d+(p.encoded?"*":""),value:p.line}))},parseHeaderValue(r){let e={value:!1,params:{}},t=!1,n="",i="value",o=!1,s=!1,a;for(let c=0,l=r.length;c<l;c++)if(a=r.charAt(c),i==="key"){if(a==="="){t=n.trim().toLowerCase(),i="value",n="";continue}n+=a}else{if(s)n+=a;else if(a==="\\"){s=!0;continue}else o&&a===o?o=!1:!o&&a==='"'?o=a:!o&&a===";"?(t===!1?e.value=n.trim():e.params[t]=n.trim(),i="key",n=""):n+=a;s=!1}return i==="value"?t===!1?e.value=n.trim():e.params[t]=n.trim():n.trim()&&(e.params[n.trim().toLowerCase()]=""),Object.keys(e.params).forEach(c=>{let l,u,p,d;(p=c.match(/(\*(\d+)|\*(\d+)\*|\*)$/))&&(l=c.substr(0,p.index),u=Number(p[2]||p[3])||0,(!e.params[l]||typeof e.params[l]!="object")&&(e.params[l]={charset:!1,values:[]}),d=e.params[c],u===0&&p[0].substr(-1)==="*"&&(p=d.match(/^([^']*)'[^']*'(.*)$/))&&(e.params[l].charset=p[1]||"iso-8859-1",d=p[2]),e.params[l].values[u]=d,delete e.params[c])}),Object.keys(e.params).forEach(c=>{let l;e.params[c]&&Array.isArray(e.params[c].values)&&(l=e.params[c].values.map(u=>u||"").join(""),e.params[c].charset?e.params[c]="=?"+e.params[c].charset+"?Q?"+l.replace(/[=?_\s]/g,u=>{let p=u.charCodeAt(0).toString(16);return u===" "?"_":"%"+(p.length<2?"0":"")+p}).replace(/%/g,"=")+"?=":e.params[c]=l)}),e},detectExtension:r=>n_.detectExtension(r),detectMimeType:r=>n_.detectMimeType(r),foldLines(r,e,t){r=(r||"").toString(),e=e||76;let n=0,i=r.length,o="",s,a;for(;n<i;){if(s=r.substr(n,e),s.length<e){o+=s;break}if(a=s.match(/^[^\n\r]*(\r?\n|\r)/)){s=a[0],o+=s,n+=s.length;continue}else(a=s.match(/(\s+)[^\s]*$/))&&a[0].length-(t?(a[1]||"").length:0)<s.length?s=s.substr(0,s.length-(a[0].length-(t?(a[1]||"").length:0))):(a=r.substr(n+s.length).match(/^[^\s]+(\s*)/))&&(s=s+a[0].substr(0,a[0].length-(t?0:(a[1]||"").length)));o+=s,n+=s.length,n<i&&(o+=`\r
|
|
16
|
+
`)}return o},splitMimeEncodedString:(r,e)=>{let t=[],n,i,o,s;for(e=Math.max(e||0,12);r.length;){for(n=r.substr(0,e),(i=n.match(/[=][0-9A-F]?$/i))&&(n=n.substr(0,i.index)),s=!1;!s;)s=!0,(i=r.substr(n.length).match(/^[=]([0-9A-F]{2})/i))&&(o=parseInt(i[1],16),o<194&&o>127&&(n=n.substr(0,n.length-3),s=!1));n.length&&t.push(n),r=r.substr(n.length)}return t},encodeURICharComponent:r=>{let e="",t=r.charCodeAt(0).toString(16).toUpperCase();if(t.length%2&&(t="0"+t),t.length>2)for(let n=0,i=t.length/2;n<i;n++)e+="%"+t.substr(n,2);else e+="%"+t;return e},safeEncodeURIComponent(r){r=(r||"").toString();try{r=encodeURIComponent(r)}catch{return r.replace(/[^\x00-\x1F *'()<>@,;:\\"[\]?=\u007F-\uFFFF]+/g,"")}return r.replace(/[\x00-\x1F *'()<>@,;:\\"[\]?=\u007F-\uFFFF]/g,e=>this.encodeURICharComponent(e))}}});var a_=_((DZ,s_)=>{"use strict";function HI(r,e){let t=!1,n="text",i=[],o={address:[],comment:[],group:[],text:[],textWasQuoted:[]},s=!1;for(let a=0,c=r.length;a<c;a++){let l=r[a],u=a?r[a-1]:null;if(l.type==="operator")switch(l.value){case"<":n="address",s=!1;break;case"(":n="comment",s=!1;break;case":":n="group",t=!0,s=!1;break;case'"':s=!s,n="text";break;default:n="text",s=!1;break}else l.value&&(n==="address"&&(l.value=l.value.replace(/^[^<]*<\s*/,"")),u&&u.noBreak&&o[n].length?(o[n][o[n].length-1]+=l.value,n==="text"&&s&&(o.textWasQuoted[o.textWasQuoted.length-1]=!0)):(o[n].push(l.value),n==="text"&&o.textWasQuoted.push(s)))}if(!o.text.length&&o.comment.length&&(o.text=o.comment,o.comment=[]),t){o.text=o.text.join(" ");let a=[];o.group.length&&o_(o.group.join(","),{_depth:e+1}).forEach(l=>{l.group?a=a.concat(l.group):a.push(l)}),i.push({name:o.text||"",group:a})}else{if(!o.address.length&&o.text.length){for(let c=o.text.length-1;c>=0;c--)if(!o.textWasQuoted[c]&&/^[^@\s]+@[^@\s]+$/.test(o.text[c])){o.address=o.text.splice(c,1),o.textWasQuoted.splice(c,1);break}if(!o.address.length){let c=!1;for(let l=o.text.length-1;l>=0&&!(!o.textWasQuoted[l]&&(o.text[l]=o.text[l].replace(/\s*\b[^@\s]+@[^\s]+\b\s*/,u=>c?u:(o.address=[u.trim()],c=!0," ")).trim(),c));l--);}}!o.text.length&&o.comment.length&&(o.text=o.comment,o.comment=[]),o.address.length>1&&(o.text=o.text.concat(o.address.splice(1))),o.text=o.text.join(" "),o.address=o.address.join(" ");let a={address:o.address||o.text||"",name:o.text||o.address||""};a.address===a.name&&(/@/.test(a.address||"")?a.name="":a.address=""),i.push(a)}return i}var Pd=class{constructor(e){this.str=(e||"").toString(),this.operatorCurrent="",this.operatorExpecting="",this.node=null,this.escaped=!1,this.list=[],this.operators={'"':'"',"(":")","<":">",",":"",":":";",";":""}}tokenize(){let e=[];for(let t=0,n=this.str.length;t<n;t++){let i=this.str.charAt(t),o=t<n-1?this.str.charAt(t+1):null;this.checkChar(i,o)}return this.list.forEach(t=>{t.value=(t.value||"").toString().trim(),t.value&&e.push(t)}),e}checkChar(e,t){if(!this.escaped){if(e===this.operatorExpecting){this.node={type:"operator",value:e},t&&![" "," ","\r",`
|
|
17
|
+
`,",",";"].includes(t)&&(this.node.noBreak=!0),this.list.push(this.node),this.node=null,this.operatorExpecting="",this.escaped=!1;return}else if(!this.operatorExpecting&&e in this.operators){this.node={type:"operator",value:e},this.list.push(this.node),this.node=null,this.operatorExpecting=this.operators[e],this.escaped=!1;return}else if(['"',"'"].includes(this.operatorExpecting)&&e==="\\"){this.escaped=!0;return}}this.node||(this.node={type:"text",value:""},this.list.push(this.node)),e===`
|
|
18
|
+
`&&(e=" "),(e.charCodeAt(0)>=33||[" "," "].includes(e))&&(this.node.value+=e),this.escaped=!1}},BI=50;function o_(r,e){e=e||{};let t=e._depth||0;if(t>BI)return[];let i=new Pd(r).tokenize(),o=[],s=[],a=[];i.forEach(c=>{c.type==="operator"&&(c.value===","||c.value===";")?(s.length&&o.push(s),s=[]):s.push(c)}),s.length&&o.push(s),o.forEach(c=>{let l=HI(c,t);l.length&&(a=a.concat(l))});for(let c=a.length-2;c>=0;c--){let l=a[c],u=a[c+1];l.address===""&&l.name&&!l.group&&u.address&&u.name&&(u.name=l.name+", "+u.name,a.splice(c,1))}if(e.flatten){let c=[],l=u=>{u.forEach(p=>{if(p.group)return l(p.group);c.push(p)})};return l(a),c}return a}s_.exports=o_});var l_=_((qZ,c_)=>{"use strict";var{Transform:VI}=N("stream"),Rd=class extends VI{constructor(){super(),this.lastByte=!1}_transform(e,t,n){e.length&&(this.lastByte=e[e.length-1]),this.push(e),n()}_flush(e){return this.lastByte===10?e():this.lastByte===13?(this.push(Buffer.from(`
|
|
19
|
+
`)),e()):(this.push(Buffer.from(`\r
|
|
20
|
+
`)),e())}};c_.exports=Rd});var Id=_((ZZ,u_)=>{"use strict";var{Transform:WI}=N("stream"),Cd=class extends WI{constructor(e){super(e),this.lastByte=!1}_transform(e,t,n){let i,o=0;for(let s=0,a=e.length;s<a;s++)e[s]===10&&(s&&e[s-1]!==13||!s&&this.lastByte!==13)&&(s>o&&(i=e.slice(o,s),this.push(i)),this.push(Buffer.from(`\r
|
|
21
|
+
`)),o=s+1);o&&o<e.length?(i=e.slice(o),this.push(i)):o||this.push(e),this.lastByte=e[e.length-1],n()}};u_.exports=Cd});var d_=_((UZ,p_)=>{"use strict";var{Transform:GI}=N("stream"),Ad=class extends GI{constructor(e){super(e)}_transform(e,t,n){let i,o=0;for(let s=0,a=e.length;s<a;s++)e[s]===13&&(i=e.slice(o,s),o=s+1,this.push(i));o&&o<e.length?(i=e.slice(o),this.push(i)):o||this.push(e),n()}};p_.exports=Ad});var da=_((FZ,f_)=>{"use strict";var Od=N("crypto"),KI=N("fs"),JI=wd(),{PassThrough:uo}=N("stream"),XI=qe(),St=lo(),QI=zd(),YI=Ed(),eA=a_(),tA=so(),m_=kt(),rA=l_(),nA=Id(),iA=d_(),oA=["From","Sender","To","Cc","Bcc","Reply-To","Date","References"],Nd=class r{constructor(e,t){this.nodeCounter=0,t=t||{},this.baseBoundary=t.baseBoundary||Od.randomBytes(8).toString("hex"),this.boundaryPrefix=t.boundaryPrefix||"--_NmP",this.disableFileAccess=!!t.disableFileAccess,this.disableUrlAccess=!!t.disableUrlAccess,this.normalizeHeaderKey=t.normalizeHeaderKey,this.date=t.parentNode?null:new Date,this.rootNode=t.rootNode||this,this.keepBcc=!!t.keepBcc,t.filename&&(this.filename=t.filename,e||(e=St.detectMimeType(this.filename.split(".").pop()))),this.textEncoding=(t.textEncoding||"").toString().trim().charAt(0).toUpperCase(),this.parentNode=t.parentNode,this.hostname=t.hostname,this.newline=t.newline,this.childNodes=[],this._nodeId=++this.rootNode.nodeCounter,this._headers=[],this._isPlainText=!1,this._hasLongLines=!1,this._envelope=!1,this._raw=!1,this._transforms=[],this._processFuncs=[],e&&this.setHeader("Content-Type",e)}createChild(e,t){!t&&typeof e=="object"&&(t=e,e=void 0);let n=new r(e,t);return this.appendChild(n),n}appendChild(e){return e.rootNode!==this.rootNode&&(e.rootNode=this.rootNode,e._nodeId=++this.rootNode.nodeCounter),e.parentNode=this,this.childNodes.push(e),e}replace(e){return e===this?this:(this.parentNode.childNodes.forEach((t,n)=>{t===this&&(e.rootNode=this.rootNode,e.parentNode=this.parentNode,e._nodeId=this._nodeId,this.rootNode=this,this.parentNode=void 0,e.parentNode.childNodes[n]=e)}),e)}remove(){if(!this.parentNode)return this;for(let e=this.parentNode.childNodes.length-1;e>=0;e--)if(this.parentNode.childNodes[e]===this)return this.parentNode.childNodes.splice(e,1),this.parentNode=void 0,this.rootNode=this,this}setHeader(e,t){let n=!1;if(!t&&e&&typeof e=="object")return e.key&&"value"in e?this.setHeader(e.key,e.value):Array.isArray(e)?e.forEach(o=>{this.setHeader(o.key,o.value)}):Object.keys(e).forEach(o=>{this.setHeader(o,e[o])}),this;e=this._normalizeHeaderKey(e);let i={key:e,value:t};for(let o=0,s=this._headers.length;o<s;o++)this._headers[o].key===e&&(n?(this._headers.splice(o,1),o--,s--):(this._headers[o]=i,n=!0));return n||this._headers.push(i),this}addHeader(e,t){return!t&&e&&typeof e=="object"?(e.key&&e.value?this.addHeader(e.key,e.value):Array.isArray(e)?e.forEach(n=>{this.addHeader(n.key,n.value)}):Object.keys(e).forEach(n=>{this.addHeader(n,e[n])}),this):Array.isArray(t)?(t.forEach(n=>{this.addHeader(e,n)}),this):(this._headers.push({key:this._normalizeHeaderKey(e),value:t}),this)}getHeader(e){e=this._normalizeHeaderKey(e);for(let t=0,n=this._headers.length;t<n;t++)if(this._headers[t].key===e)return this._headers[t].value}setContent(e){return this.content=e,typeof this.content.pipe=="function"?(this._contentErrorHandler=t=>{this.content.removeListener("error",this._contentErrorHandler),this.content=t},this.content.once("error",this._contentErrorHandler)):typeof this.content=="string"&&(this._isPlainText=St.isPlainText(this.content),this._isPlainText&&St.hasLongerLines(this.content,76)&&(this._hasLongLines=!0)),this}build(e){let t;e||(t=new Promise((a,c)=>{e=XI.callbackPromise(a,c)}));let n=this.createReadStream(),i=[],o=0,s=!1;return n.on("readable",()=>{let a;for(;(a=n.read())!==null;)i.push(a),o+=a.length}),n.once("error",a=>{if(!s)return s=!0,e(a)}),n.once("end",a=>{if(!s)return s=!0,a&&a.length&&(i.push(a),o+=a.length),e(null,Buffer.concat(i,o))}),t}getTransferEncoding(){let e=!1,t=(this.getHeader("Content-Type")||"").toString().toLowerCase().trim();return this.content&&(e=(this.getHeader("Content-Transfer-Encoding")||"").toString().toLowerCase().trim(),(!e||!["base64","quoted-printable"].includes(e))&&(/^text\//i.test(t)?this._isPlainText&&!this._hasLongLines?e="7bit":typeof this.content=="string"||this.content instanceof Buffer?e=this._getTextEncoding(this.content)==="Q"?"quoted-printable":"base64":e=this.textEncoding==="B"?"base64":"quoted-printable":/^(multipart|message)\//i.test(t)||(e=e||"base64"))),e}buildHeaders(){let e=this.getTransferEncoding(),t=[];if(e&&this.setHeader("Content-Transfer-Encoding",e),this.filename&&!this.getHeader("Content-Disposition")&&this.setHeader("Content-Disposition","attachment"),this.rootNode===this){this.getHeader("Date")||this.setHeader("Date",this.date.toUTCString().replace(/GMT/,"+0000")),this.messageId(),this.getHeader("MIME-Version")||this.setHeader("MIME-Version","1.0");for(let n=this._headers.length-2;n>=0;n--){let i=this._headers[n];i.key==="Content-Type"&&(this._headers.splice(n,1),this._headers.push(i))}}return this._headers.forEach(n=>{let i=n.key,o=n.value,s,a,c={};if(!(o&&typeof o=="object"&&!oA.includes(i)&&(Object.keys(o).forEach(u=>{u!=="value"&&(c[u]=o[u])}),o=(o.value||"").toString(),!o.trim()))){if(c.prepared){c.foldLines?t.push(St.foldLines(i+": "+o)):t.push(i+": "+o);return}switch(n.key){case"Content-Disposition":s=St.parseHeaderValue(o),this.filename&&(s.params.filename=this.filename),o=St.buildHeaderValue(s);break;case"Content-Type":s=St.parseHeaderValue(o),this._handleContentType(s),s.value.match(/^text\/plain\b/)&&typeof this.content=="string"&&/[\u0080-\uFFFF]/.test(this.content)&&(s.params.charset="utf-8"),o=St.buildHeaderValue(s),this.filename&&(a=this._encodeWords(this.filename),(a!==this.filename||/[\s'"\\;:/=(),<>@[\]?]|^-/.test(a))&&(a='"'+a+'"'),o+="; name="+a);break;case"Bcc":if(!this.keepBcc)return;break}if(o=this._encodeHeaderValue(i,o),!!(o||"").toString().trim()){if(typeof this.normalizeHeaderKey=="function"){let u=this.normalizeHeaderKey(i,o);u&&typeof u=="string"&&u.length&&(i=u)}t.push(St.foldLines(i+": "+o,76))}}}),t.join(`\r
|
|
22
|
+
`)}createReadStream(e){e=e||{};let t=new uo(e),n=t,i;this.stream(t,e,o=>{if(o){n.emit("error",o);return}t.end()});for(let o=0,s=this._transforms.length;o<s;o++)i=typeof this._transforms[o]=="function"?this._transforms[o]():this._transforms[o],n.once("error",a=>{i.emit("error",a)}),n=n.pipe(i);i=new rA,n.once("error",o=>{i.emit("error",o)}),n=n.pipe(i);for(let o=0,s=this._processFuncs.length;o<s;o++)i=this._processFuncs[o],n=i(n);if(this.newline){let s=["win","windows","dos",`\r
|
|
23
|
+
`].includes(this.newline.toString().toLowerCase())?new nA:new iA,a=n.pipe(s);return n.on("error",c=>a.emit("error",c)),a}return n}transform(e){this._transforms.push(e)}processFunc(e){this._processFuncs.push(e)}stream(e,t,n){let i=this.getTransferEncoding(),o,s,a=!1,c=p=>{a||(a=!0,n(p))},l=()=>{let p=0,d=()=>{if(p>=this.childNodes.length)return e.write(`\r
|
|
24
|
+
--`+this.boundary+`--\r
|
|
25
|
+
`),c();let f=this.childNodes[p++];e.write((p>1?`\r
|
|
26
|
+
`:"")+"--"+this.boundary+`\r
|
|
27
|
+
`),f.stream(e,t,m=>{if(m)return c(m);setImmediate(d)})};if(this.multipart)setImmediate(d);else return c()},u=()=>{if(this.content){if(Object.prototype.toString.call(this.content)==="[object Error]")return c(this.content);typeof this.content.pipe=="function"&&(this.content.removeListener("error",this._contentErrorHandler),this._contentErrorHandler=d=>c(d),this.content.once("error",this._contentErrorHandler));let p=()=>{["quoted-printable","base64"].includes(i)?(o=new(i==="base64"?YI:QI).Encoder(t),o.pipe(e,{end:!1}),o.once("end",l),o.once("error",d=>c(d)),s=this._getStream(this.content),s.pipe(o)):(s=this._getStream(this.content),s.pipe(e,{end:!1}),s.once("end",l)),s.once("error",d=>c(d))};if(this.content._resolve){let d=[],f=0,m=!1,h=this._getStream(this.content);h.on("error",v=>{m||(m=!0,c(v))}),h.on("readable",()=>{let v;for(;(v=h.read())!==null;)d.push(v),f+=v.length}),h.on("end",()=>{m||(m=!0,this.content._resolve=!1,this.content._resolvedValue=Buffer.concat(d,f),setImmediate(p))})}else setImmediate(p);return}return setImmediate(l)};this._raw?setImmediate(()=>{if(Object.prototype.toString.call(this._raw)==="[object Error]")return c(this._raw);typeof this._raw.pipe=="function"&&this._raw.removeListener("error",this._contentErrorHandler);let p=this._getStream(this._raw);p.pipe(e,{end:!1}),p.on("error",d=>e.emit("error",d)),p.on("end",l)}):(e.write(this.buildHeaders()+`\r
|
|
28
|
+
\r
|
|
29
|
+
`),setImmediate(u))}setEnvelope(e){let t;this._envelope={from:!1,to:[]},e.from&&(t=[],this._convertAddresses(this._parseAddresses(e.from),t),t=t.filter(i=>i&&i.address),t.length&&t[0]&&(this._envelope.from=t[0].address)),["to","cc","bcc"].forEach(i=>{e[i]&&this._convertAddresses(this._parseAddresses(e[i]),this._envelope.to)}),this._envelope.to=this._envelope.to.map(i=>i.address).filter(i=>i);let n=["to","cc","bcc","from"];return Object.keys(e).forEach(i=>{n.includes(i)||(this._envelope[i]=e[i])}),this}getAddresses(){let e={};return this._headers.forEach(t=>{let n=t.key.toLowerCase();["from","sender","reply-to","to","cc","bcc"].includes(n)&&(Array.isArray(e[n])||(e[n]=[]),this._convertAddresses(this._parseAddresses(t.value),e[n]))}),e}getEnvelope(){if(this._envelope)return this._envelope;let e={from:!1,to:[]};return this._headers.forEach(t=>{let n=[];t.key==="From"||!e.from&&["Reply-To","Sender"].includes(t.key)?(this._convertAddresses(this._parseAddresses(t.value),n),n.length&&n[0]&&(e.from=n[0].address)):["To","Cc","Bcc"].includes(t.key)&&this._convertAddresses(this._parseAddresses(t.value),e.to)}),e.to=e.to.map(t=>t.address),e}messageId(){let e=this.getHeader("Message-ID");return e||(e=this._generateMessageId(),this.setHeader("Message-ID",e)),e}setRaw(e){return this._raw=e,this._raw&&typeof this._raw.pipe=="function"&&(this._contentErrorHandler=t=>{this._raw.removeListener("error",this._contentErrorHandler),this._raw=t},this._raw.once("error",this._contentErrorHandler)),this}_getStream(e){let t;return e._resolvedValue?(t=new uo,setImmediate(()=>{try{t.end(e._resolvedValue)}catch(n){t.emit("error",n)}}),t):typeof e.pipe=="function"?e:e&&typeof e.path=="string"&&!e.href?this.disableFileAccess?(t=new uo,setImmediate(()=>{let n=new Error("File access rejected for "+e.path);n.code=m_.EFILEACCESS,t.emit("error",n)}),t):KI.createReadStream(e.path):e&&typeof e.href=="string"?this.disableUrlAccess?(t=new uo,setImmediate(()=>{let n=new Error("Url access rejected for "+e.href);n.code=m_.EURLACCESS,t.emit("error",n)}),t):tA(e.href,{headers:e.httpHeaders}):(t=new uo,setImmediate(()=>{try{t.end(e||"")}catch(n){t.emit("error",n)}}),t)}_parseAddresses(e){return[].concat.apply([],[].concat(e).map(t=>t&&t.address?(t.address=this._normalizeAddress(t.address),t.name=t.name||"",[t]):eA(t)))}_normalizeHeaderKey(e){return e=(e||"").toString().replace(/\r?\n|\r/g," ").trim().toLowerCase().replace(/^X-SMTPAPI$|^(MIME|DKIM|ARC|BIMI)\b|^[a-z]|-(SPF|FBL|ID|MD5)$|-[a-z]/gi,t=>t.toUpperCase()).replace(/^Content-Features$/i,"Content-features"),e}_handleContentType(e){this.contentType=e.value.trim().toLowerCase(),this.multipart=/^multipart\//i.test(this.contentType)?this.contentType.substr(this.contentType.indexOf("/")+1):!1,this.multipart?this.boundary=e.params.boundary=e.params.boundary||this.boundary||this._generateBoundary():this.boundary=!1}_generateBoundary(){return this.rootNode.boundaryPrefix+"-"+this.rootNode.baseBoundary+"-Part_"+this._nodeId}_encodeHeaderValue(e,t){switch(e=this._normalizeHeaderKey(e),e){case"From":case"Sender":case"To":case"Cc":case"Bcc":case"Reply-To":return this._convertAddresses(this._parseAddresses(t));case"Message-ID":case"In-Reply-To":case"Content-Id":return t=(t||"").toString().replace(/\r?\n|\r/g," "),t.charAt(0)!=="<"&&(t="<"+t),t.charAt(t.length-1)!==">"&&(t=t+">"),t;case"References":return t=[].concat.apply([],[].concat(t||"").map(n=>(n=(n||"").toString().replace(/\r?\n|\r/g," ").trim(),n.replace(/<[^>]*>/g,i=>i.replace(/\s/g,"")).split(/\s+/)))).map(n=>(n.charAt(0)!=="<"&&(n="<"+n),n.charAt(n.length-1)!==">"&&(n=n+">"),n)),t.join(" ").trim();case"Date":return Object.prototype.toString.call(t)==="[object Date]"?t.toUTCString().replace(/GMT/,"+0000"):(t=(t||"").toString().replace(/\r?\n|\r/g," "),this._encodeWords(t));case"Content-Type":case"Content-Disposition":return(t||"").toString().replace(/\r?\n|\r/g," ");default:return t=(t||"").toString().replace(/\r?\n|\r/g," "),this._encodeWords(t)}}_convertAddresses(e,t){let n=[];return t=t||[],[].concat(e||[]).forEach(i=>{if(i.address)i.address=this._normalizeAddress(i.address),i.name?n.push(`${this._encodeAddressName(i.name)} <${i.address}>`):n.push(i.address.indexOf(" ")>=0?`<${i.address}>`:`${i.address}`),t.some(o=>o.address===i.address)||t.push(i);else if(i.group){let o=(i.group.length?this._convertAddresses(i.group,t):"").trim();n.push(`${this._encodeAddressName(i.name)}:${o};`)}}),n.join(", ")}_normalizeAddress(e){e=(e||"").toString().replace(/[\x00-\x1F<>]+/g," ").trim();let t=e.lastIndexOf("@");if(t<0)return e;let n=e.substr(0,t),i=e.substr(t+1),o;try{o=JI.toASCII(i.toLowerCase())}catch{}return n.indexOf(" ")>=0&&(n.charAt(0)!=='"'&&(n='"'+n),n.substr(-1)!=='"'&&(n=n+'"')),`${n}@${o}`}_encodeAddressName(e){return/^[\w ]*$/.test(e)?e:/^[\x20-\x7e]*$/.test(e)?'"'+e.replace(/([\\"])/g,"\\$1")+'"':St.encodeWord(e,this._getTextEncoding(e),52)}_encodeWords(e){return St.encodeWords(e,this._getTextEncoding(e),52,!0)}_getTextEncoding(e){if(e=(e||"").toString(),this.textEncoding)return this.textEncoding;let t=0,n=0;for(let i=0,o=e.length;i<o;i++){let s=e.charCodeAt(i);s>=0&&s<=8||s===11||s===12||s>=14&&s<=31||s>=128?t++:(s>=65&&s<=90||s>=97&&s<=122)&&n++}return t<n?"Q":"B"}_generateMessageId(){return"<"+[2,2,2,6].reduce((e,t)=>e+"-"+Od.randomBytes(t).toString("hex"),Od.randomBytes(4).toString("hex"))+"@"+(this.getEnvelope().from||this.hostname||"localhost").split("@").pop()+">"}};f_.exports=Nd});var g_=_((HZ,h_)=>{"use strict";var po=da(),jd=lo(),{parseDataURI:sA}=qe(),Md=class{constructor(e){this.mail=e||{},this.message=!1}compile(){return this._alternatives=this.getAlternatives(),this._htmlNode=this._alternatives.filter(e=>/^text\/html\b/i.test(e.contentType)).pop(),this._attachments=this.getAttachments(!!this._htmlNode),this._useRelated=!!(this._htmlNode&&this._attachments.related.length),this._useAlternative=this._alternatives.length>1,this._useMixed=this._attachments.attached.length>1||this._alternatives.length&&this._attachments.attached.length===1,this.mail.raw?this.message=new po("message/rfc822",{newline:this.mail.newline}).setRaw(this.mail.raw):this._useMixed?this.message=this._createMixed():this._useAlternative?this.message=this._createAlternative():this._useRelated?this.message=this._createRelated():this.message=this._createContentNode(!1,[].concat(this._alternatives||[]).concat(this._attachments.attached||[]).shift()||{contentType:"text/plain",content:""}),this.mail.headers&&this.message.addHeader(this.mail.headers),["from","sender","to","cc","bcc","reply-to","in-reply-to","references","subject","message-id","date"].forEach(e=>{let t=e.replace(/-(\w)/g,(n,i)=>i.toUpperCase());this.mail[t]&&this.message.setHeader(e,this.mail[t])}),this.mail.envelope&&this.message.setEnvelope(this.mail.envelope),this.message.messageId(),this.message}getAttachments(e){let t,n,i=[].concat(this.mail.attachments||[]).map((o,s)=>{/^data:/i.test(o.path||o.href)&&(o=this._processDataUrl(o));let a=o.contentType||jd.detectMimeType(o.filename||o.path||o.href||"bin"),c=/^image\//i.test(a),l=/^message\//i.test(a),u=o.contentDisposition||(l||c&&o.cid?"inline":"attachment"),p;"contentTransferEncoding"in o?p=o.contentTransferEncoding:l?p="8bit":p="base64";let d={contentType:a,contentDisposition:u,contentTransferEncoding:p};return o.filename?d.filename=o.filename:!l&&o.filename!==!1&&(d.filename=(o.path||o.href||"").split("/").pop().split("?").shift()||"attachment-"+(s+1),d.filename.indexOf(".")<0&&(d.filename+="."+jd.detectExtension(d.contentType))),/^https?:\/\//i.test(o.path)&&(o.href=o.path,o.path=void 0),o.cid&&(d.cid=o.cid),o.raw?d.raw=o.raw:o.path?d.content={path:o.path}:o.href?d.content={href:o.href,httpHeaders:o.httpHeaders}:d.content=o.content||"",o.encoding&&(d.encoding=o.encoding),o.headers&&(d.headers=o.headers),d});return this.mail.icalEvent&&(typeof this.mail.icalEvent=="object"&&(this.mail.icalEvent.content||this.mail.icalEvent.path||this.mail.icalEvent.href||this.mail.icalEvent.raw)?t=this.mail.icalEvent:t={content:this.mail.icalEvent},n=Object.assign({},t),n.contentType="application/ics",n.headers||(n.headers={}),n.filename=n.filename||"invite.ics",n.headers["Content-Disposition"]="attachment",n.headers["Content-Transfer-Encoding"]="base64"),e?{attached:i.filter(o=>!o.cid).concat(n||[]),related:i.filter(o=>!!o.cid)}:{attached:i.concat(n||[]),related:[]}}getAlternatives(){let e=[],t,n,i,o,s,a;return this.mail.text&&(typeof this.mail.text=="object"&&(this.mail.text.content||this.mail.text.path||this.mail.text.href||this.mail.text.raw)?t=this.mail.text:t={content:this.mail.text},t.contentType="text/plain; charset=utf-8"),this.mail.watchHtml&&(typeof this.mail.watchHtml=="object"&&(this.mail.watchHtml.content||this.mail.watchHtml.path||this.mail.watchHtml.href||this.mail.watchHtml.raw)?i=this.mail.watchHtml:i={content:this.mail.watchHtml},i.contentType="text/watch-html; charset=utf-8"),this.mail.amp&&(typeof this.mail.amp=="object"&&(this.mail.amp.content||this.mail.amp.path||this.mail.amp.href||this.mail.amp.raw)?o=this.mail.amp:o={content:this.mail.amp},o.contentType="text/x-amp-html; charset=utf-8"),this.mail.icalEvent&&(typeof this.mail.icalEvent=="object"&&(this.mail.icalEvent.content||this.mail.icalEvent.path||this.mail.icalEvent.href||this.mail.icalEvent.raw)?s=this.mail.icalEvent:s={content:this.mail.icalEvent},a=Object.assign({},s),a.content&&typeof a.content=="object"&&(a.content._resolve=!0),a.filename=!1,a.contentType="text/calendar; charset=utf-8; method="+(a.method||"PUBLISH").toString().trim().toUpperCase(),a.headers||(a.headers={})),this.mail.html&&(typeof this.mail.html=="object"&&(this.mail.html.content||this.mail.html.path||this.mail.html.href||this.mail.html.raw)?n=this.mail.html:n={content:this.mail.html},n.contentType="text/html; charset=utf-8"),[].concat(t||[]).concat(i||[]).concat(o||[]).concat(n||[]).concat(a||[]).concat(this.mail.alternatives||[]).forEach(c=>{/^data:/i.test(c.path||c.href)&&(c=this._processDataUrl(c));let l={contentType:c.contentType||jd.detectMimeType(c.filename||c.path||c.href||"txt"),contentTransferEncoding:c.contentTransferEncoding};c.filename&&(l.filename=c.filename),/^https?:\/\//i.test(c.path)&&(c.href=c.path,c.path=void 0),c.raw?l.raw=c.raw:c.path?l.content={path:c.path}:c.href?l.content={href:c.href}:l.content=c.content||"",c.encoding&&(l.encoding=c.encoding),c.headers&&(l.headers=c.headers),e.push(l)}),e}_createMixed(e){let t=e?e.createChild("multipart/mixed",{disableUrlAccess:this.mail.disableUrlAccess,disableFileAccess:this.mail.disableFileAccess,normalizeHeaderKey:this.mail.normalizeHeaderKey,newline:this.mail.newline}):new po("multipart/mixed",{baseBoundary:this.mail.baseBoundary,textEncoding:this.mail.textEncoding,boundaryPrefix:this.mail.boundaryPrefix,disableUrlAccess:this.mail.disableUrlAccess,disableFileAccess:this.mail.disableFileAccess,normalizeHeaderKey:this.mail.normalizeHeaderKey,newline:this.mail.newline});return this._useAlternative?this._createAlternative(t):this._useRelated&&this._createRelated(t),[].concat(!this._useAlternative&&this._alternatives||[]).concat(this._attachments.attached||[]).forEach(n=>{(!this._useRelated||n!==this._htmlNode)&&this._createContentNode(t,n)}),t}_createAlternative(e){let t=e?e.createChild("multipart/alternative",{disableUrlAccess:this.mail.disableUrlAccess,disableFileAccess:this.mail.disableFileAccess,normalizeHeaderKey:this.mail.normalizeHeaderKey,newline:this.mail.newline}):new po("multipart/alternative",{baseBoundary:this.mail.baseBoundary,textEncoding:this.mail.textEncoding,boundaryPrefix:this.mail.boundaryPrefix,disableUrlAccess:this.mail.disableUrlAccess,disableFileAccess:this.mail.disableFileAccess,normalizeHeaderKey:this.mail.normalizeHeaderKey,newline:this.mail.newline});return this._alternatives.forEach(n=>{this._useRelated&&this._htmlNode===n?this._createRelated(t):this._createContentNode(t,n)}),t}_createRelated(e){let t=e?e.createChild('multipart/related; type="text/html"',{disableUrlAccess:this.mail.disableUrlAccess,disableFileAccess:this.mail.disableFileAccess,normalizeHeaderKey:this.mail.normalizeHeaderKey,newline:this.mail.newline}):new po('multipart/related; type="text/html"',{baseBoundary:this.mail.baseBoundary,textEncoding:this.mail.textEncoding,boundaryPrefix:this.mail.boundaryPrefix,disableUrlAccess:this.mail.disableUrlAccess,disableFileAccess:this.mail.disableFileAccess,normalizeHeaderKey:this.mail.normalizeHeaderKey,newline:this.mail.newline});return this._createContentNode(t,this._htmlNode),this._attachments.related.forEach(n=>this._createContentNode(t,n)),t}_createContentNode(e,t){t=t||{},t.content=t.content||"";let n=(t.encoding||"utf8").toString().toLowerCase().replace(/[-_\s]/g,""),i=e?e.createChild(t.contentType,{filename:t.filename,textEncoding:this.mail.textEncoding,disableUrlAccess:this.mail.disableUrlAccess,disableFileAccess:this.mail.disableFileAccess,normalizeHeaderKey:this.mail.normalizeHeaderKey,newline:this.mail.newline}):new po(t.contentType,{filename:t.filename,baseBoundary:this.mail.baseBoundary,textEncoding:this.mail.textEncoding,boundaryPrefix:this.mail.boundaryPrefix,disableUrlAccess:this.mail.disableUrlAccess,disableFileAccess:this.mail.disableFileAccess,normalizeHeaderKey:this.mail.normalizeHeaderKey,newline:this.mail.newline});return t.headers&&i.addHeader(t.headers),t.cid&&i.setHeader("Content-Id","<"+t.cid.replace(/[<>]/g,"")+">"),t.contentTransferEncoding?i.setHeader("Content-Transfer-Encoding",t.contentTransferEncoding):this.mail.encoding&&/^text\//i.test(t.contentType)&&i.setHeader("Content-Transfer-Encoding",this.mail.encoding),(!/^text\//i.test(t.contentType)||t.contentDisposition)&&i.setHeader("Content-Disposition",t.contentDisposition||(t.cid&&/^image\//i.test(t.contentType)?"inline":"attachment")),typeof t.content=="string"&&!["utf8","usascii","ascii"].includes(n)&&(t.content=Buffer.from(t.content,n)),t.raw?i.setRaw(t.raw):i.setContent(t.content),i}_processDataUrl(e){let t=e.path||e.href;if(!t||typeof t!="string"||!t.startsWith("data:"))return e;if(t.length>52428800){let i="application/octet-stream",o=t.indexOf(",");if(o>0&&o<200){let a=t.substring(5,o).split(";");a[0]&&a[0].includes("/")&&(i=a[0].trim())}return Object.assign({},e,{path:!1,href:!1,content:Buffer.alloc(0),contentType:e.contentType||i})}let n;try{n=sA(t)}catch{return e}return n&&(e.content=n.data,e.contentType=e.contentType||n.contentType,"path"in e&&(e.path=!1),"href"in e&&(e.href=!1)),e}};h_.exports=Md});var x_=_((BZ,v_)=>{"use strict";var{Transform:aA}=N("stream"),Ld=class extends aA{constructor(e){super(e),this.lastBytes=Buffer.alloc(4),this.headersParsed=!1,this.headerBytes=0,this.headerChunks=[],this.rawHeaders=!1,this.bodySize=0}updateLastBytes(e){let t=this.lastBytes.length,n=Math.min(e.length,t);for(let i=0,o=t-n;i<o;i++)this.lastBytes[i]=this.lastBytes[i+n];for(let i=1;i<=n;i++)this.lastBytes[t-i]=e[e.length-i]}checkHeaders(e){if(this.headersParsed)return!0;let t=this.lastBytes.length,n=0;for(let i=0,o=this.lastBytes.length+e.length;i<o;i++){let s;if(i<t?s=this.lastBytes[i]:s=e[i-t],s===10&&i){let a=i-1<t?this.lastBytes[i-1]:e[i-1-t],c=i>1?i-2<t?this.lastBytes[i-2]:e[i-2-t]:!1;if(a===10){this.headersParsed=!0,n=i-t+1,this.headerBytes+=n;break}else if(a===13&&c===10){this.headersParsed=!0,n=i-t+1,this.headerBytes+=n;break}}}if(this.headersParsed){if(this.headerChunks.push(e.slice(0,n)),this.rawHeaders=Buffer.concat(this.headerChunks,this.headerBytes),this.headerChunks=null,this.emit("headers",this.parseHeaders()),e.length-1>n){let i=e.slice(n);this.bodySize+=i.length,setImmediate(()=>this.push(i))}return!1}return this.headerBytes+=e.length,this.headerChunks.push(e),this.updateLastBytes(e),!1}_transform(e,t,n){if(!e||!e.length)return n();typeof e=="string"&&(e=Buffer.from(e,t));let i;try{i=this.checkHeaders(e)}catch(o){return n(o)}i&&(this.bodySize+=e.length,this.push(e)),setImmediate(n)}_flush(e){if(this.headerChunks){let t=Buffer.concat(this.headerChunks,this.headerBytes);this.bodySize+=t.length,this.push(t),this.headerChunks=null}e()}parseHeaders(){let e=(this.rawHeaders||"").toString().split(/\r?\n/);for(let t=e.length-1;t>0;t--)/^\s/.test(e[t])&&(e[t-1]+=`
|
|
30
|
+
`+e[t],e.splice(t,1));return e.filter(t=>t.trim()).map(t=>({key:t.substr(0,t.indexOf(":")).trim().toLowerCase(),line:t}))}};v_.exports=Ld});var __=_((VZ,y_)=>{"use strict";var{Transform:cA}=N("stream"),lA=N("crypto"),Dd=class extends cA{constructor(e){super(),e=e||{},this.chunkBuffer=[],this.chunkBufferLen=0,this.bodyHash=lA.createHash(e.hashAlgo||"sha1"),this.remainder="",this.byteLength=0,this.debug=e.debug,this._debugBody=e.debug?[]:!1}updateHash(e){let t,n="",i="file";for(let s=e.length-1;s>=0;s--){let a=e[s];if(!(i==="file"&&(a===10||a===13))){if(i==="file"&&(a===9||a===32))i="line";else if(!(i==="line"&&(a===9||a===32))){if((i==="file"||i==="line")&&(i="body",s===e.length-1))break}}if(s===0){if(i==="file"&&(!this.remainder||/[\r\n]$/.test(this.remainder))||i==="line"&&(!this.remainder||/[ \t]$/.test(this.remainder))){this.remainder+=e.toString("binary");return}else if(i==="line"||i==="file"){n=e.toString("binary"),e=!1;break}}if(i==="body"){n=e.slice(s+1).toString("binary"),e=e.slice(0,s+1);break}}let o=!!this.remainder;if(e&&!o){for(let s=0,a=e.length;s<a;s++)if(s&&e[s]===10&&e[s-1]!==13){o=!0;break}else if(s&&e[s]===13&&e[s-1]===32){o=!0;break}else if(s&&e[s]===32&&e[s-1]===32){o=!0;break}else if(e[s]===9){o=!0;break}}o?(t=this.remainder+(e?e.toString("binary"):""),this.remainder=n,t=t.replace(/\r?\n/g,`
|
|
31
|
+
`).replace(/[ \t]*$/gm,"").replace(/[ \t]+/gm," ").replace(/\n/g,`\r
|
|
32
|
+
`),e=Buffer.from(t,"binary")):n&&(this.remainder=n),this.debug&&this._debugBody.push(e),this.bodyHash.update(e)}_transform(e,t,n){if(!e||!e.length)return n();typeof e=="string"&&(e=Buffer.from(e,t)),this.updateHash(e),this.byteLength+=e.length,this.push(e),n()}_flush(e){/[\r\n]$/.test(this.remainder)&&this.byteLength>2&&this.bodyHash.update(Buffer.from(`\r
|
|
33
|
+
`)),this.byteLength||this.push(Buffer.from(`\r
|
|
34
|
+
`)),this.emit("hash",this.bodyHash.digest("base64"),this.debug?Buffer.concat(this._debugBody):!1),e()}};y_.exports=Dd});var k_=_((WZ,qd)=>{"use strict";var uA=wd(),pA=lo(),dA=N("crypto");qd.exports=(r,e,t,n)=>{n=n||{};let o=n.headerFieldNames||"From:Sender:Reply-To:Subject:Date:Message-ID:To:Cc:MIME-Version:Content-Type:Content-Transfer-Encoding:Content-ID:Content-Description:Resent-Date:Resent-From:Resent-Sender:Resent-To:Resent-Cc:Resent-Message-ID:In-Reply-To:References:List-Id:List-Help:List-Unsubscribe:List-Subscribe:List-Post:List-Owner:List-Archive",s=b_(r,o,n.skipFields),a=mA(n.domainName,n.keySelector,s.fieldNames,e,t);s.headers+="dkim-signature:"+w_(a);let c=dA.createSign(("rsa-"+e).toUpperCase());c.update(s.headers);let l;try{l=c.sign(n.privateKey,"base64")}catch{return!1}return a+l.replace(/(^.{73}|.{75}(?!\r?\n|\r))/g,`$&\r
|
|
35
|
+
`).trim()};qd.exports.relaxedHeaders=b_;function mA(r,e,t,n,i){let o=["v=1","a=rsa-"+n,"c=relaxed/relaxed","d="+uA.toASCII(r),"q=dns/txt","s="+e,"bh="+i,"h="+t].join("; ");return pA.foldLines("DKIM-Signature: "+o,76)+`;\r
|
|
36
|
+
b=`}function b_(r,e,t){let n=new Set,i=new Set,o=new Map;(t||"").toLowerCase().split(":").forEach(c=>{i.add(c.trim())}),(e||"").toLowerCase().split(":").filter(c=>!i.has(c.trim())).forEach(c=>{n.add(c.trim())});for(let c=r.length-1;c>=0;c--){let l=r[c];n.has(l.key)&&!o.has(l.key)&&o.set(l.key,w_(l.line))}let s=[],a=[];return n.forEach(c=>{o.has(c)&&(a.push(c),s.push(c+":"+o.get(c)))}),{headers:s.join(`\r
|
|
37
|
+
`)+`\r
|
|
38
|
+
`,fieldNames:a.join(":")}}function w_(r){return r.substr(r.indexOf(":")+1).replace(/\r?\n/g,"").replace(/\s+/g," ").trim()}});var E_=_((GZ,S_)=>{"use strict";var fA=x_(),hA=__(),gA=k_(),{PassThrough:Zd}=N("stream"),Ud=N("fs"),vA=N("path"),xA=N("crypto"),yA="sha256",_A=2*1024*1024,Fd=class{constructor(e,t,n,i){this.options=e||{},this.keys=t,this.cacheTreshold=Number(this.options.cacheTreshold)||_A,this.hashAlgo=this.options.hashAlgo||yA,this.cacheDir=this.options.cacheDir||!1,this.chunks=[],this.chunklen=0,this.readPos=0,this.cachePath=this.cacheDir?vA.join(this.cacheDir,"message."+Date.now()+"-"+xA.randomBytes(14).toString("hex")):!1,this.cache=!1,this.headers=!1,this.bodyHash=!1,this.parser=!1,this.relaxedBody=!1,this.input=n,this.output=i,this.output.usingCache=!1,this.hasErrored=!1,this.input.on("error",o=>{this.hasErrored=!0,this.cleanup(),i.emit("error",o)})}cleanup(){!this.cache||!this.cachePath||Ud.unlink(this.cachePath,()=>!1)}createReadCache(){this.cache=Ud.createReadStream(this.cachePath),this.cache.once("error",e=>{this.cleanup(),this.output.emit("error",e)}),this.cache.once("close",()=>{this.cleanup()}),this.cache.pipe(this.output)}sendNextChunk(){if(this.hasErrored)return;if(this.readPos>=this.chunks.length)return this.cache?this.createReadCache():this.output.end();let e=this.chunks[this.readPos++];if(this.output.write(e)===!1)return this.output.once("drain",()=>{this.sendNextChunk()});setImmediate(()=>this.sendNextChunk())}sendSignedOutput(){let e=0,t=()=>{if(e>=this.keys.length)return this.output.write(this.parser.rawHeaders),setImmediate(()=>this.sendNextChunk());let n=this.keys[e++],i=gA(this.headers,this.hashAlgo,this.bodyHash,{domainName:n.domainName,keySelector:n.keySelector,privateKey:n.privateKey,headerFieldNames:this.options.headerFieldNames,skipFields:this.options.skipFields});return i&&this.output.write(Buffer.from(i+`\r
|
|
39
|
+
`)),setImmediate(t)};if(this.bodyHash&&this.headers)return t();this.output.write(this.parser.rawHeaders),this.sendNextChunk()}createWriteCache(){this.output.usingCache=!0,this.cache=Ud.createWriteStream(this.cachePath),this.cache.once("error",e=>{this.cleanup(),this.relaxedBody.unpipe(this.cache),this.relaxedBody.on("readable",()=>{for(;this.relaxedBody.read()!==null;);}),this.hasErrored=!0,this.output.emit("error",e)}),this.cache.once("close",()=>{this.sendSignedOutput()}),this.relaxedBody.removeAllListeners("readable"),this.relaxedBody.pipe(this.cache)}signStream(){this.parser=new fA,this.relaxedBody=new hA({hashAlgo:this.hashAlgo}),this.parser.on("headers",e=>{this.headers=e}),this.relaxedBody.on("hash",e=>{this.bodyHash=e}),this.relaxedBody.on("readable",()=>{let e;if(!this.cache){for(;(e=this.relaxedBody.read())!==null;)if(this.chunks.push(e),this.chunklen+=e.length,this.chunklen>=this.cacheTreshold&&this.cachePath)return this.createWriteCache()}}),this.relaxedBody.on("end",()=>{this.cache||this.sendSignedOutput()}),this.parser.pipe(this.relaxedBody),setImmediate(()=>this.input.pipe(this.parser))}},Hd=class{constructor(e){this.options=e||{},this.keys=[].concat(this.options.keys||{domainName:e.domainName,keySelector:e.keySelector,privateKey:e.privateKey})}sign(e,t){let n=new Zd,i=e,o=!1;Buffer.isBuffer(e)?(o=e,i=new Zd):typeof e=="string"&&(o=Buffer.from(e),i=new Zd);let s=this.options;t&&Object.keys(t).length&&(s=Object.assign({},t,this.options));let a=new Fd(s,this.keys,i,n);return setImmediate(()=>{a.signStream(),o&&setImmediate(()=>{i.end(o)})}),n}};S_.exports=Hd});var R_=_((KZ,P_)=>{"use strict";var $_=N("net"),T_=N("tls"),bA=N("url"),wA=kt();function z_(r,e,t,n){let i=bA.parse(r),o={host:i.hostname,port:Number(i.port)?Number(i.port):i.protocol==="https:"?443:80},s;i.protocol==="https:"?(o.rejectUnauthorized=!1,s=T_.connect.bind(T_)):s=$_.connect.bind($_);let a,c=!1,l=p=>{if(!c){c=!0;try{a.destroy()}catch{}n(p)}},u=()=>{let p=new Error("Proxy socket timed out");p.code="ETIMEDOUT",l(p)};a=s(o,()=>{if(c)return;let p={Host:t+":"+e,Connection:"close"};i.auth&&(p["Proxy-Authorization"]="Basic "+Buffer.from(i.auth).toString("base64")),a.write("CONNECT "+t+":"+e+` HTTP/1.1\r
|
|
40
|
+
`+Object.keys(p).map(m=>m+": "+p[m]).join(`\r
|
|
41
|
+
`)+`\r
|
|
42
|
+
\r
|
|
43
|
+
`);let d="",f=m=>{let h,v;if(!c&&(d+=m.toString("binary"),h=d.match(/\r\n\r\n/))){if(a.removeListener("data",f),v=d.substr(h.index+h[0].length),d=d.substr(0,h.index),v&&a.unshift(Buffer.from(v,"binary")),c=!0,h=d.match(/^HTTP\/\d+\.\d+ (\d+)/i),!h||(h[1]||"").charAt(0)!=="2"){try{a.destroy()}catch{}let b=new Error("Invalid response from proxy"+(h&&": "+h[1]||""));return b.code=wA.EPROXY,n(b)}return a.removeListener("error",l),a.removeListener("timeout",u),a.setTimeout(0),n(null,a)}};a.on("data",f)}),a.setTimeout(z_.timeout||30*1e3),a.on("timeout",u),a.once("error",l)}P_.exports=z_});var A_=_((JZ,I_)=>{"use strict";var C_=qe(),kA=da(),Gn=lo(),Bd=class{constructor(e,t){this.mailer=e,this.data={},this.message=null,t=t||{};let n=e.options||{},i=e._defaults||{};Object.assign(this.data,t),this.data.headers=this.data.headers||{},Object.keys(i).forEach(o=>{o in this.data?o==="headers"&&Object.keys(i.headers).forEach(s=>{s in this.data.headers||(this.data.headers[s]=i.headers[s])}):this.data[o]=i[o]}),["disableFileAccess","disableUrlAccess","normalizeHeaderKey"].forEach(o=>{o in n&&(this.data[o]=n[o])})}resolveContent(...e){return C_.resolveContent(...e)}resolveAll(e){let t=[[this.data,"html"],[this.data,"text"],[this.data,"watchHtml"],[this.data,"amp"],[this.data,"icalEvent"]];this.data.alternatives&&this.data.alternatives.length&&this.data.alternatives.forEach((c,l)=>{t.push([this.data.alternatives,l])}),this.data.attachments&&this.data.attachments.length&&this.data.attachments.forEach((c,l)=>{c.filename||(c.filename=(c.path||c.href||"").split("/").pop().split("?").shift()||"attachment-"+(l+1),c.filename.indexOf(".")<0&&(c.filename+="."+Gn.detectExtension(c.contentType))),c.contentType||(c.contentType=Gn.detectMimeType(c.filename||c.path||c.href||"bin")),t.push([this.data.attachments,l])});let n=new kA;["from","to","cc","bcc","sender","replyTo"].forEach(c=>{let l;this.message?l=[].concat(n._parseAddresses(this.message.getHeader(c==="replyTo"?"reply-to":c))||[]):this.data[c]&&(l=[].concat(n._parseAddresses(this.data[c])||[])),l&&l.length?this.data[c]=l:c in this.data&&(this.data[c]=null)}),["from","sender"].forEach(c=>{this.data[c]&&(this.data[c]=this.data[c].shift())});let s=0,a=()=>{if(s>=t.length)return e(null,this.data);let c=t[s++];if(!c[0]||!c[0][c[1]])return a();C_.resolveContent(...c,(l,u)=>{if(l)return e(l);let p={content:u};c[0][c[1]]&&typeof c[0][c[1]]=="object"&&!Buffer.isBuffer(c[0][c[1]])&&Object.keys(c[0][c[1]]).forEach(d=>{!(d in p)&&!["content","path","href","raw"].includes(d)&&(p[d]=c[0][c[1]][d])}),c[0][c[1]]=p,a()})};setImmediate(()=>a())}normalize(e){let t=this.data.envelope||this.message.getEnvelope(),n=this.message.messageId();this.resolveAll((i,o)=>i?e(i):(o.envelope=t,o.messageId=n,["html","text","watchHtml","amp"].forEach(s=>{o[s]&&o[s].content&&(typeof o[s].content=="string"?o[s]=o[s].content:Buffer.isBuffer(o[s].content)&&(o[s]=o[s].content.toString()))}),o.icalEvent&&Buffer.isBuffer(o.icalEvent.content)&&(o.icalEvent.content=o.icalEvent.content.toString("base64"),o.icalEvent.encoding="base64"),o.alternatives&&o.alternatives.length&&o.alternatives.forEach(s=>{s&&s.content&&Buffer.isBuffer(s.content)&&(s.content=s.content.toString("base64"),s.encoding="base64")}),o.attachments&&o.attachments.length&&o.attachments.forEach(s=>{s&&s.content&&Buffer.isBuffer(s.content)&&(s.content=s.content.toString("base64"),s.encoding="base64")}),o.normalizedHeaders={},Object.keys(o.headers||{}).forEach(s=>{let a=[].concat(o.headers[s]||[]).shift();a=a&&a.value||a,a&&(["references","in-reply-to","message-id","content-id"].includes(s)&&(a=this.message._encodeHeaderValue(s,a)),o.normalizedHeaders[s]=a)}),o.list&&typeof o.list=="object"&&this._getListHeaders(o.list).forEach(a=>{o.normalizedHeaders[a.key]=a.value.map(c=>c&&c.value||c).join(", ")}),o.references&&(o.normalizedHeaders.references=this.message._encodeHeaderValue("references",o.references)),o.inReplyTo&&(o.normalizedHeaders["in-reply-to"]=this.message._encodeHeaderValue("in-reply-to",o.inReplyTo)),e(null,o)))}setMailerHeader(){!this.message||!this.data.xMailer||this.message.setHeader("X-Mailer",this.data.xMailer)}setPriorityHeaders(){if(!(!this.message||!this.data.priority))switch((this.data.priority||"").toString().toLowerCase()){case"high":this.message.setHeader("X-Priority","1 (Highest)"),this.message.setHeader("X-MSMail-Priority","High"),this.message.setHeader("Importance","High");break;case"low":this.message.setHeader("X-Priority","5 (Lowest)"),this.message.setHeader("X-MSMail-Priority","Low"),this.message.setHeader("Importance","Low");break;default:}}setListHeaders(){!this.message||!this.data.list||typeof this.data.list!="object"||this._getListHeaders(this.data.list).forEach(e=>{e.value.forEach(t=>{this.message.addHeader(e.key,t)})})}_getListHeaders(e){return Object.keys(e).map(t=>({key:"list-"+t.toLowerCase().trim(),value:[].concat(e[t]||[]).map(n=>({prepared:!0,foldLines:!0,value:[].concat(n||[]).map(i=>{if(typeof i=="string"&&(i={url:i}),i&&i.url){if(t.toLowerCase().trim()==="id"){let s=i.comment||"";return Gn.isPlainText(s)?s='"'+s+'"':s=Gn.encodeWord(s),(i.comment?s+" ":"")+this._formatListUrl(i.url).replace(/^<[^:]+\/{,2}/,"")}let o=i.comment||"";return Gn.isPlainText(o)||(o=Gn.encodeWord(o)),this._formatListUrl(i.url)+(i.comment?" ("+o+")":"")}return""}).filter(i=>i).join(", ")}))}))}_formatListUrl(e){return e=e.replace(/[\s<]+|[\s>]+/g,""),/^(https?|mailto|ftp):/.test(e)?"<"+e+">":/^[^@]+@[^@]+$/.test(e)?"<mailto:"+e+">":"<http://"+e+">"}};I_.exports=Bd});var L_=_((XZ,M_)=>{"use strict";var SA=N("events"),O_=qe(),EA=yd(),$A=g_(),N_=E_(),TA=R_(),j_=kt(),zA=N("util"),PA=N("url"),Vd=wt(),RA=A_(),CA=N("net"),IA=N("dns"),AA=N("crypto"),Wd=class extends SA{constructor(e,t,n){super(),this.options=t||{},this._defaults=n||{},this._defaultPlugins={compile:[(...i)=>this._convertDataImages(...i)],stream:[]},this._userPlugins={compile:[],stream:[]},this.meta=new Map,this.dkim=this.options.dkim?new N_(this.options.dkim):!1,this.transporter=e,this.transporter.mailer=this,this.logger=O_.getLogger(this.options,{component:this.options.component||"mail"}),this.logger.debug({tnx:"create"},"Creating transport: %s",this.getVersionString()),typeof this.transporter.on=="function"&&(this.transporter.on("log",i=>{this.logger.debug({tnx:"transport"},"%s: %s",i.type,i.message)}),this.transporter.on("error",i=>{this.logger.error({err:i,tnx:"transport"},"Transport Error: %s",i.message),this.emit("error",i)}),this.transporter.on("idle",(...i)=>{this.emit("idle",...i)}),this.transporter.on("clear",(...i)=>{this.emit("clear",...i)})),["close","isIdle","verify"].forEach(i=>{this[i]=(...o)=>typeof this.transporter[i]=="function"?(i==="verify"&&typeof this.getSocket=="function"&&(this.transporter.getSocket=this.getSocket,this.getSocket=!1),this.transporter[i](...o)):(this.logger.warn({tnx:"transport",methodName:i},"Non existing method %s called for transport",i),!1)}),this.options.proxy&&typeof this.options.proxy=="string"&&this.setupProxy(this.options.proxy)}use(e,t){return e=(e||"").toString(),this._userPlugins.hasOwnProperty(e)?this._userPlugins[e].push(t):this._userPlugins[e]=[t],this}sendMail(e,t=null){let n;t||(n=new Promise((o,s)=>{t=O_.callbackPromise(o,s)})),typeof this.getSocket=="function"&&(this.transporter.getSocket=this.getSocket,this.getSocket=!1);let i=new RA(this,e);return this.logger.debug({tnx:"transport",name:this.transporter.name,version:this.transporter.version,action:"send"},"Sending mail using %s/%s",this.transporter.name,this.transporter.version),this._processPlugins("compile",i,o=>{if(o)return this.logger.error({err:o,tnx:"plugin",action:"compile"},"PluginCompile Error: %s",o.message),t(o);i.message=new $A(i.data).compile(),i.setMailerHeader(),i.setPriorityHeaders(),i.setListHeaders(),this._processPlugins("stream",i,s=>{if(s)return this.logger.error({err:s,tnx:"plugin",action:"stream"},"PluginStream Error: %s",s.message),t(s);(i.data.dkim||this.dkim)&&i.message.processFunc(a=>{let c=i.data.dkim?new N_(i.data.dkim):this.dkim;return this.logger.debug({tnx:"DKIM",messageId:i.message.messageId(),dkimDomains:c.keys.map(l=>l.keySelector+"."+l.domainName).join(", ")},"Signing outgoing message with %s keys",c.keys.length),c.sign(a,i.data._dkim)}),this.transporter.send(i,(...a)=>{a[0]&&this.logger.error({err:a[0],tnx:"transport",action:"send"},"Send Error: %s",a[0].message),t(...a)})})}),n}getVersionString(){return zA.format("%s (%s; +%s; %s/%s)",Vd.name,Vd.version,Vd.homepage,this.transporter.name,this.transporter.version)}_processPlugins(e,t,n){if(e=(e||"").toString(),!this._userPlugins.hasOwnProperty(e))return n();let i=this._userPlugins[e]||[],o=this._defaultPlugins[e]||[];if(i.length&&this.logger.debug({tnx:"transaction",pluginCount:i.length,step:e},"Using %s plugins for %s",i.length,e),i.length+o.length===0)return n();let s=0,a="default",c=()=>{let l=a==="default"?o:i;if(s>=l.length)if(a==="default"&&i.length)a="user",s=0,l=i;else return n();let u=l[s++];u(t,p=>{if(p)return n(p);c()})};c()}setupProxy(e){let t=PA.parse(e);this.getSocket=(n,i)=>{let o=t.protocol.replace(/:$/,"").toLowerCase();if(this.meta.has("proxy_handler_"+o))return this.meta.get("proxy_handler_"+o)(t,n,i);switch(o){case"http":case"https":TA(t.href,n.port,n.host,(a,c)=>a?i(a):i(null,{connection:c}));return;case"socks":case"socks5":case"socks4":case"socks4a":{if(!this.meta.has("proxy_socks_module")){let c=new Error("Socks module not loaded");return c.code=j_.EPROXY,i(c)}let a=c=>{let l=!!this.meta.get("proxy_socks_module").SocksClient,u=l?this.meta.get("proxy_socks_module").SocksClient:this.meta.get("proxy_socks_module"),p=Number(t.protocol.replace(/\D/g,""))||5,d={proxy:{ipaddress:c,port:Number(t.port),type:p},[l?"destination":"target"]:{host:n.host,port:n.port},command:"connect"};if(t.auth){let f=decodeURIComponent(t.auth.split(":").shift()),m=decodeURIComponent(t.auth.split(":").pop());l?(d.proxy.userId=f,d.proxy.password=m):p===4?d.userid=f:d.authentication={username:f,password:m}}u.createConnection(d,(f,m)=>f?i(f):i(null,{connection:m.socket||m}))};return CA.isIP(t.hostname)?a(t.hostname):IA.resolve(t.hostname,(c,l)=>{if(c)return i(c);a(Array.isArray(l)?l[0]:l)})}}let s=new Error("Unknown proxy configuration");s.code=j_.EPROXY,i(s)}}_convertDataImages(e,t){if(!this.options.attachDataUrls&&!e.data.attachDataUrls||!e.data.html)return t();e.resolveContent(e.data,"html",(n,i)=>{if(n)return t(n);let o=0;i=(i||"").toString().replace(/(<img\b[^<>]{0,1024} src\s{0,20}=[\s"']{0,20})(data:([^;]+);[^"'>\s]+)/gi,(s,a,c,l)=>{let u=AA.randomBytes(10).toString("hex")+"@localhost";return e.data.attachments||(e.data.attachments=[]),Array.isArray(e.data.attachments)||(e.data.attachments=[].concat(e.data.attachments||[])),e.data.attachments.push({path:c,cid:u,filename:"image-"+ ++o+"."+EA.detectExtension(l)}),a+"cid:"+u}),e.data.html=i,t()})}set(e,t){return this.meta.set(e,t)}get(e){return this.meta.get(e)}};M_.exports=Wd});var q_=_((QZ,D_)=>{"use strict";var{Transform:OA}=N("stream"),Gd=class extends OA{constructor(e){super(e),this.options=e||{},this.inByteCount=0,this.outByteCount=0,this.lastByte=!1}_transform(e,t,n){let i=[],o=0,s,a,c=0,l;if(!e||!e.length)return n();for(typeof e=="string"&&(e=Buffer.from(e)),this.inByteCount+=e.length,s=0,a=e.length;s<a;s++)e[s]===46?(s&&e[s-1]===10||!s&&(!this.lastByte||this.lastByte===10))&&(l=e.slice(c,s+1),i.push(l),i.push(Buffer.from(".")),o+=l.length+1,c=s+1):e[s]===10&&(s&&e[s-1]!==13||!s&&this.lastByte!==13)&&(s>c?(l=e.slice(c,s),i.push(l),o+=l.length+2):o+=2,i.push(Buffer.from(`\r
|
|
44
|
+
`)),c=s+1);o?(c<e.length&&(l=e.slice(c),i.push(l),o+=l.length),this.outByteCount+=o,this.push(Buffer.concat(i,o))):(this.outByteCount+=e.length,this.push(e)),this.lastByte=e[e.length-1],n()}_flush(e){let t;this.lastByte===10?t=Buffer.from(`.\r
|
|
45
|
+
`):this.lastByte===13?t=Buffer.from(`
|
|
46
|
+
.\r
|
|
47
|
+
`):t=Buffer.from(`\r
|
|
48
|
+
.\r
|
|
49
|
+
`),this.outByteCount+=t.length,this.push(t),e()}};D_.exports=Gd});var ma=_((YZ,W_)=>{"use strict";var NA=wt(),{EventEmitter:jA}=N("events"),Z_=N("net"),U_=N("tls"),MA=N("os"),F_=N("crypto"),LA=q_(),{PassThrough:H_}=N("stream"),ln=qe(),DA=2*60*1e3,B_=10*60*1e3,qA=30*1e3,ZA=30*1e3,UA=()=>{};function V_(r){if(!r)return r;let e=Buffer.from(r,"binary").toString("utf8");return e.includes("\uFFFD")?r:e}var Kd=class extends jA{constructor(e){super(e),this.id=F_.randomBytes(8).toString("base64").replace(/\W/g,""),this.stage="init",this.options=e||{},this.secureConnection=!!this.options.secure,this.alreadySecured=!!this.options.secured,this.port=Number(this.options.port)||(this.secureConnection?465:587),this.host=this.options.host||"localhost",this.servername=this.options.servername?this.options.servername:Z_.isIP(this.host)?!1:this.host,this.allowInternalNetworkInterfaces=this.options.allowInternalNetworkInterfaces||!1,typeof this.options.secure>"u"&&this.port===465&&(this.secureConnection=!0),this.name=(this.options.name||this._getHostname()).toString().replace(/[\r\n]+/g,""),this.logger=ln.getLogger(this.options,{component:this.options.component||"smtp-connection",sid:this.id}),this.customAuth=new Map;for(let t of Object.keys(this.options.customAuth||{})){let n=(t||"").toString().trim().toUpperCase();n&&this.customAuth.set(n,this.options.customAuth[t])}this.version=NA.version,this.authenticated=!1,this.destroyed=!1,this.secure=!!this.secureConnection,this._remainder="",this._responseQueue=[],this.lastServerResponse=!1,this._socket=!1,this._supportedAuth=[],this.allowsAuth=!1,this._envelope=!1,this._supportedExtensions=[],this._maxAllowedSize=0,this._responseActions=[],this._recipientQueue=[],this._greetingTimeout=!1,this._connectionTimeout=!1,this._destroyed=!1,this._closing=!1,this._onSocketData=t=>this._onData(t),this._onSocketError=t=>this._onError(t,"ESOCKET",!1,"CONN"),this._onSocketClose=()=>this._onClose(),this._onSocketEnd=()=>this._onEnd(),this._onSocketTimeout=()=>this._onTimeout(),this._onConnectionSocketError=t=>this._onConnectionError(t,"ESOCKET"),this._connectionAttemptId=0}connect(e){if(typeof e=="function"){this.once("connect",()=>{this.logger.debug({tnx:"smtp"},"SMTP handshake finished"),e()});let n=this._isDestroyedMessage("connect");if(n)return e(this._formatError(n,"ECONNECTION",!1,"CONN"))}let t={port:this.port,host:this.host,allowInternalNetworkInterfaces:this.allowInternalNetworkInterfaces,timeout:this.options.dnsTimeout||ZA};if(this.options.localAddress&&(t.localAddress=this.options.localAddress),this.options.connection){this._socket=this.options.connection,this._setupConnectionHandlers(),this.secureConnection&&!this.alreadySecured?setImmediate(()=>this._upgradeConnection(n=>{if(n){this._onError(new Error("Error initiating TLS - "+(n.message||n)),"ETLS",!1,"CONN");return}this._onConnect()})):setImmediate(()=>this._onConnect());return}else return this.options.socket?(this._socket=this.options.socket,this._resolveAndConnect(t,n=>{try{this._socket.connect(this.port,this.host,()=>{this._socket.setKeepAlive(!0),this._onConnect()}),this._setupConnectionHandlers()}catch(i){return setImmediate(()=>this._onError(i,"ECONNECTION",!1,"CONN"))}})):(this.secureConnection&&(Object.assign(t,this.options.tls||{}),this.servername&&!t.servername&&(t.servername=this.servername)),this._resolveAndConnect(t,n=>{this._fallbackAddresses=(n._addresses||[]).filter(i=>i!==t.host),this._connectOpts=Object.assign({},t),this._connectToHost(t,this.secureConnection)}))}_resolveAndConnect(e,t){return ln.resolveHostname(e,(n,i)=>{if(n)return setImmediate(()=>this._onError(n,"EDNS",!1,"CONN"));this.logger.debug({tnx:"dns",source:e.host,resolved:i.host,cached:!!i.cached},"Resolved %s as %s [cache %s]",e.host,i.host,i.cached?"hit":"miss");for(let o of Object.keys(i))o.charAt(0)!=="_"&&i[o]&&(e[o]=i[o]);t(i)})}_connectToHost(e,t){this._connectionAttemptId++;let n=this._connectionAttemptId,i=t?U_.connect:Z_.connect;try{this._socket=i(e,()=>{this._connectionAttemptId===n&&(this._socket.setKeepAlive(!0),this._onConnect())}),this._setupConnectionHandlers()}catch(o){return setImmediate(()=>this._onError(o,"ECONNECTION",!1,"CONN"))}}_setupConnectionHandlers(){this._connectionTimeout=setTimeout(()=>{this._onConnectionError("Connection timeout","ETIMEDOUT")},this.options.connectionTimeout||DA),this._socket.on("error",this._onConnectionSocketError)}_onConnectionError(e,t){if(clearTimeout(this._connectionTimeout),!(this._fallbackAddresses&&this._fallbackAddresses.length&&this.stage==="init"&&!this._destroyed)){this._onError(e,t,!1,"CONN");return}let i=this._fallbackAddresses.shift();if(this.logger.info({tnx:"network",failedHost:this._connectOpts.host,nextHost:i,error:e.message||e},"Connection to %s failed, trying %s",this._connectOpts.host,i),this._socket){try{this._socket.removeListener("error",this._onConnectionSocketError),this._socket.destroy()}catch{}this._socket=null}this._connectOpts.host=i,this._connectToHost(this._connectOpts,this.secureConnection)}quit(){this._sendCommand("QUIT"),this._responseActions.push(this.close)}close(){if(clearTimeout(this._connectionTimeout),clearTimeout(this._greetingTimeout),this._responseActions=[],this._closing)return;this._closing=!0;let e=this.stage==="init"?"destroy":"end";this.logger.debug({tnx:"smtp"},'Closing connection to the server using "%s"',e);let t=this._socket&&this._socket.socket||this._socket;if(t&&!t.destroyed)try{t.setTimeout(0),t.removeListener("data",this._onSocketData),t.removeListener("timeout",this._onSocketTimeout),t.removeListener("close",this._onSocketClose),t.removeListener("end",this._onSocketEnd),t.removeListener("error",this._onSocketError),t.removeListener("error",this._onConnectionSocketError),t.on("error",UA),t[e]()}catch{}this._destroy()}login(e,t){let n=this._isDestroyedMessage("login");if(n)return t(this._formatError(n,"ECONNECTION",!1,"API"));if(this._auth=e||{},this._authMethod=(this._auth.method||"").toString().trim().toUpperCase()||!1,!this._authMethod&&this._auth.oauth2&&!this._auth.credentials?this._authMethod="XOAUTH2":(!this._authMethod||this._authMethod==="XOAUTH2"&&!this._auth.oauth2)&&(this._authMethod=(this._supportedAuth[0]||"PLAIN").toUpperCase().trim()),this._authMethod!=="XOAUTH2"&&(!this._auth.credentials||!this._auth.credentials.user||!this._auth.credentials.pass))if(this._auth.user&&this._auth.pass||this.customAuth.has(this._authMethod))this._auth.credentials={user:this._auth.user,pass:this._auth.pass,options:this._auth.options};else return t(this._formatError('Missing credentials for "'+this._authMethod+'"',"EAUTH",!1,"API"));if(this.customAuth.has(this._authMethod)){let i=this.customAuth.get(this._authMethod),o,s=!1,a=()=>{s||(s=!0,this.logger.info({tnx:"smtp",username:this._auth.user,action:"authenticated",method:this._authMethod},"User %s authenticated",JSON.stringify(this._auth.user)),this.authenticated=!0,t(null,!0))},c=u=>{s||(s=!0,t(this._formatError(u,"EAUTH",o,"AUTH "+this._authMethod)))},l=i({auth:this._auth,method:this._authMethod,extensions:[].concat(this._supportedExtensions),authMethods:[].concat(this._supportedAuth),maxAllowedSize:this._maxAllowedSize||!1,sendCommand:(u,p)=>{let d;return p||(d=new Promise((f,m)=>{p=ln.callbackPromise(f,m)})),this._responseActions.push(f=>{o=f;let m=f.match(/^(\d+)(?:\s(\d+\.\d+\.\d+))?\s/),h={command:u,response:f};m?(h.status=Number(m[1])||0,m[2]&&(h.code=m[2]),h.text=f.substr(m[0].length)):(h.text=f,h.status=0),p(null,h)}),setImmediate(()=>this._sendCommand(u)),d},resolve:a,reject:c});l&&typeof l.catch=="function"&&l.then(a).catch(c);return}switch(this._authMethod){case"XOAUTH2":this._handleXOauth2Token(!1,t);return;case"LOGIN":this._responseActions.push(i=>{this._actionAUTH_LOGIN_USER(i,t)}),this._sendCommand("AUTH LOGIN");return;case"PLAIN":this._responseActions.push(i=>{this._actionAUTHComplete(i,t)}),this._sendCommand("AUTH PLAIN "+Buffer.from("\0"+this._auth.credentials.user+"\0"+this._auth.credentials.pass,"utf-8").toString("base64"),"AUTH PLAIN "+Buffer.from("\0"+this._auth.credentials.user+"\0/* secret */","utf-8").toString("base64"));return;case"CRAM-MD5":this._responseActions.push(i=>{this._actionAUTH_CRAM_MD5(i,t)}),this._sendCommand("AUTH CRAM-MD5");return}return t(this._formatError('Unknown authentication method "'+this._authMethod+'"',"EAUTH",!1,"API"))}send(e,t,n){if(!t)return n(this._formatError("Empty message","EMESSAGE",!1,"API"));let i=this._isDestroyedMessage("send message");if(i)return n(this._formatError(i,"ECONNECTION",!1,"API"));if(this._maxAllowedSize&&e.size>this._maxAllowedSize)return setImmediate(()=>{n(this._formatError("Message size larger than allowed "+this._maxAllowedSize,"EMESSAGE",!1,"MAIL FROM"))});let o=!1,s=function(){o||(o=!0,n(...arguments))};typeof t.on=="function"&&t.on("error",c=>s(this._formatError(c,"ESTREAM",!1,"API")));let a=Date.now();this._setEnvelope(e,(c,l)=>{if(c){let d=new H_;return typeof t.pipe=="function"?t.pipe(d):(d.write(t),d.end()),s(c)}let u=Date.now(),p=this._createSendStream((d,f)=>d?s(d):(l.envelopeTime=u-a,l.messageTime=Date.now()-u,l.messageSize=p.outByteCount,l.response=f,s(null,l)));typeof t.pipe=="function"?t.pipe(p):(p.write(t),p.end())})}reset(e){this._sendCommand("RSET"),this._responseActions.push(t=>t.charAt(0)!=="2"?e(this._formatError("Could not reset session state. response="+t,"EPROTOCOL",t,"RSET")):(this._envelope=!1,e(null,!0)))}_onConnect(){if(clearTimeout(this._connectionTimeout),this.logger.info({tnx:"network",localAddress:this._socket.localAddress,localPort:this._socket.localPort,remoteAddress:this._socket.remoteAddress,remotePort:this._socket.remotePort},"%s established to %s:%s",this.secure?"Secure connection":"Connection",this._socket.remoteAddress,this._socket.remotePort),this._destroyed){this.close();return}this.stage="connected",this._socket.removeListener("data",this._onSocketData),this._socket.removeListener("timeout",this._onSocketTimeout),this._socket.removeListener("close",this._onSocketClose),this._socket.removeListener("end",this._onSocketEnd),this._socket.removeListener("error",this._onConnectionSocketError),this._socket.on("error",this._onSocketError),this._socket.on("data",this._onSocketData),this._socket.once("close",this._onSocketClose),this._socket.once("end",this._onSocketEnd),this._socket.setTimeout(this.options.socketTimeout||B_),this._socket.on("timeout",this._onSocketTimeout),this._greetingTimeout=setTimeout(()=>{this._socket&&!this._destroyed&&this._responseActions[0]===this._actionGreeting&&this._onError("Greeting never received","ETIMEDOUT",!1,"CONN")},this.options.greetingTimeout||qA),this._responseActions.push(this._actionGreeting),this._socket.resume()}_onData(e){if(this._destroyed||!e||!e.length)return;let t=(e||"").toString("binary"),n=(this._remainder+t).split(/\r?\n/),i;this._remainder=n.pop();for(let o=0,s=n.length;o<s;o++){if(this._responseQueue.length&&(i=this._responseQueue[this._responseQueue.length-1],/^\d+-/.test(i.split(`
|
|
50
|
+
`).pop()))){this._responseQueue[this._responseQueue.length-1]+=`
|
|
51
|
+
`+n[o];continue}this._responseQueue.push(n[o])}this._responseQueue.length&&(i=this._responseQueue[this._responseQueue.length-1],/^\d+-/.test(i.split(`
|
|
52
|
+
`).pop()))||this._processResponse()}_onError(e,t,n,i){if(clearTimeout(this._connectionTimeout),clearTimeout(this._greetingTimeout),this._destroyed)return;e=this._formatError(e,t,n,i),["ETIMEDOUT","ESOCKET","ECONNECTION"].includes(e.code)?this.logger.warn(n,e.message):this.logger.error(n,e.message),this.emit("error",e),this.close()}_formatError(e,t,n,i){let o;/Error\]$/i.test(Object.prototype.toString.call(e))?o=e:o=new Error(e),t&&t!=="Error"&&(o.code=t),n&&(o.response=n,o.message+=": "+n);let s=typeof n=="string"&&Number((n.match(/^\d+/)||[])[0])||!1;return s&&(o.responseCode=s),i&&(o.command=i),o}_onClose(){let e=!1;if(this._remainder&&this._remainder.trim()&&(this.lastServerResponse=e=V_(this._remainder.trim()),(this.options.debug||this.options.transactionLog)&&this.logger.debug({tnx:"server"},e)),this.logger.info({tnx:"network"},"Connection closed"),this.upgrading&&!this._destroyed)return this._onError(new Error("Connection closed unexpectedly"),"ETLS",e,"CONN");if(![this._actionGreeting,this.close].includes(this._responseActions[0])&&!this._destroyed)return this._onError(new Error("Connection closed unexpectedly"),"ECONNECTION",e,"CONN");if(/^[45]\d{2}\b/.test(e))return this._onError(new Error("Connection closed unexpectedly"),"ECONNECTION",e,"CONN");this._destroy()}_onEnd(){this._socket&&!this._socket.destroyed&&this._socket.destroy()}_onTimeout(){return this._onError(new Error("Timeout"),"ETIMEDOUT",!1,"CONN")}_destroy(){this._destroyed||(this._destroyed=!0,this.emit("end"))}_upgradeConnection(e){this._socket.removeListener("data",this._onSocketData),this._socket.removeListener("timeout",this._onSocketTimeout);let t=this._socket,n=Object.assign({socket:this._socket,host:this.host},this.options.tls||{});this.servername&&!n.servername&&(n.servername=this.servername),this.upgrading=!0;try{this._socket=U_.connect(n,()=>(this.secure=!0,this.upgrading=!1,this._socket.on("data",this._onSocketData),t.removeListener("close",this._onSocketClose),t.removeListener("end",this._onSocketEnd),t.removeListener("error",this._onSocketError),e(null,!0)))}catch(i){return e(i)}this._socket.on("error",this._onSocketError),this._socket.once("close",this._onSocketClose),this._socket.once("end",this._onSocketEnd),this._socket.setTimeout(this.options.socketTimeout||B_),this._socket.on("timeout",this._onSocketTimeout),t.resume()}_processResponse(){if(!this._responseQueue.length)return!1;let e=this.lastServerResponse=V_((this._responseQueue.shift()||"").toString());if(/^\d+-/.test(e.split(`
|
|
53
|
+
`).pop()))return;(this.options.debug||this.options.transactionLog)&&this.logger.debug({tnx:"server"},e.replace(/\r?\n$/,"")),e.trim()||setImmediate(()=>this._processResponse());let t=this._responseActions.shift();if(typeof t=="function")t.call(this,e),setImmediate(()=>this._processResponse());else return this._onError(new Error("Unexpected Response"),"EPROTOCOL",e,"CONN")}_sendCommand(e,t){if(!this._destroyed){if(this._socket.destroyed)return this.close();(this.options.debug||this.options.transactionLog)&&this.logger.debug({tnx:"client"},(t||e||"").toString().replace(/\r?\n$/,"")),this._socket.write(Buffer.from(e+`\r
|
|
54
|
+
`,"utf-8"))}}_setEnvelope(e,t){let n=[],i=!1;if(this._envelope=e||{},this._envelope.from=(this._envelope.from&&this._envelope.from.address||this._envelope.from||"").toString().trim(),this._envelope.to=[].concat(this._envelope.to||[]).map(o=>(o&&o.address||o||"").toString().trim()),!this._envelope.to.length)return t(this._formatError("No recipients defined","EENVELOPE",!1,"API"));if(this._envelope.from&&/[\r\n<>]/.test(this._envelope.from))return t(this._formatError("Invalid sender "+JSON.stringify(this._envelope.from),"EENVELOPE",!1,"API"));/[\x80-\uFFFF]/.test(this._envelope.from)&&(i=!0);for(let o=0,s=this._envelope.to.length;o<s;o++){if(!this._envelope.to[o]||/[\r\n<>]/.test(this._envelope.to[o]))return t(this._formatError("Invalid recipient "+JSON.stringify(this._envelope.to[o]),"EENVELOPE",!1,"API"));/[\x80-\uFFFF]/.test(this._envelope.to[o])&&(i=!0)}if(this._envelope.rcptQueue=[].concat(this._envelope.to||[]),this._envelope.rejected=[],this._envelope.rejectedErrors=[],this._envelope.accepted=[],this._envelope.dsn)try{this._envelope.dsn=this._setDsnEnvelope(this._envelope.dsn)}catch(o){return t(this._formatError("Invalid DSN "+o.message,"EENVELOPE",!1,"API"))}if(this._responseActions.push(o=>{this._actionMAIL(o,t)}),i&&this._supportedExtensions.includes("SMTPUTF8")&&(n.push("SMTPUTF8"),this._usingSmtpUtf8=!0),this._envelope.use8BitMime&&this._supportedExtensions.includes("8BITMIME")&&(n.push("BODY=8BITMIME"),this._using8BitMime=!0),this._envelope.size&&this._supportedExtensions.includes("SIZE")){let o=Number(this._envelope.size)||0;o>0&&n.push("SIZE="+o)}if(this._envelope.dsn&&this._supportedExtensions.includes("DSN")&&(this._envelope.dsn.ret&&n.push("RET="+ln.encodeXText(this._envelope.dsn.ret)),this._envelope.dsn.envid&&n.push("ENVID="+ln.encodeXText(this._envelope.dsn.envid))),this._envelope.requireTLSExtensionEnabled){if(!this.secure)return t(this._formatError("REQUIRETLS can only be used over TLS connections (RFC 8689)","EREQUIRETLS",!1,"MAIL FROM"));if(!this._supportedExtensions.includes("REQUIRETLS"))return t(this._formatError("Server does not support REQUIRETLS extension (RFC 8689)","EREQUIRETLS",!1,"MAIL FROM"));n.push("REQUIRETLS")}this._sendCommand("MAIL FROM:<"+this._envelope.from+">"+(n.length?" "+n.join(" "):""))}_setDsnEnvelope(e){let t=(e.ret||e.return||"").toString().toUpperCase()||null;if(t)switch(t){case"HDRS":case"HEADERS":t="HDRS";break;case"FULL":case"BODY":t="FULL";break}if(t&&!["FULL","HDRS"].includes(t))throw new Error("ret: "+JSON.stringify(t));let n=(e.envid||e.id||"").toString()||null,i=e.notify||null;if(i){typeof i=="string"&&(i=i.split(",")),i=i.map(c=>c.trim().toUpperCase());let s=["NEVER","SUCCESS","FAILURE","DELAY"];if(i.filter(c=>!s.includes(c)).length||i.length>1&&i.includes("NEVER"))throw new Error("notify: "+JSON.stringify(i.join(",")));i=i.join(",")}let o=(e.recipient||e.orcpt||"").toString()||null;return o&&o.indexOf(";")<0&&(o="rfc822;"+o),{ret:t,envid:n,notify:i,orcpt:o}}_getDsnRcptToArgs(){let e=[];return this._envelope.dsn&&this._supportedExtensions.includes("DSN")&&(this._envelope.dsn.notify&&e.push("NOTIFY="+ln.encodeXText(this._envelope.dsn.notify)),this._envelope.dsn.orcpt&&e.push("ORCPT="+ln.encodeXText(this._envelope.dsn.orcpt))),e.length?" "+e.join(" "):""}_createSendStream(e){let t=new LA;if(this.options.lmtp?this._envelope.accepted.forEach((n,i)=>{let o=i===this._envelope.accepted.length-1;this._responseActions.push(s=>{this._actionLMTPStream(n,o,s,e)})}):this._responseActions.push(n=>{this._actionSMTPStream(n,e)}),t.pipe(this._socket,{end:!1}),this.options.debug){let n=new H_;n.on("readable",()=>{let i;for(;i=n.read();)this.logger.debug({tnx:"message"},i.toString("binary").replace(/\r?\n$/,""))}),t.pipe(n)}return t.once("end",()=>{this.logger.info({tnx:"message",inByteCount:t.inByteCount,outByteCount:t.outByteCount},"<%s bytes encoded mime message (source size %s bytes)>",t.outByteCount,t.inByteCount)}),t}_actionGreeting(e){if(clearTimeout(this._greetingTimeout),e.substr(0,3)!=="220"){this._onError(new Error("Invalid greeting. response="+e),"EPROTOCOL",e,"CONN");return}this.options.lmtp?(this._responseActions.push(this._actionLHLO),this._sendCommand("LHLO "+this.name)):(this._responseActions.push(this._actionEHLO),this._sendCommand("EHLO "+this.name))}_actionLHLO(e){if(e.charAt(0)!=="2"){this._onError(new Error("Invalid LHLO. response="+e),"EPROTOCOL",e,"LHLO");return}this._actionEHLO(e)}_actionEHLO(e){let t;if(e.substr(0,3)==="421"){this._onError(new Error("Server terminates connection. response="+e),"ECONNECTION",e,"EHLO");return}if(e.charAt(0)!=="2"){if(this.options.requireTLS){this._onError(new Error("EHLO failed but HELO does not support required STARTTLS. response="+e),"ECONNECTION",e,"EHLO");return}this._responseActions.push(this._actionHELO),this._sendCommand("HELO "+this.name);return}if(this._ehloLines=e.split(/\r?\n/).map(n=>n.replace(/^\d+[ -]/,"").trim()).filter(n=>n).slice(1),!this.secure&&!this.options.ignoreTLS&&(/[ -]STARTTLS\b/im.test(e)||this.options.requireTLS)){this._sendCommand("STARTTLS"),this._responseActions.push(this._actionSTARTTLS);return}/[ -]SMTPUTF8\b/im.test(e)&&this._supportedExtensions.push("SMTPUTF8"),/[ -]DSN\b/im.test(e)&&this._supportedExtensions.push("DSN"),/[ -]8BITMIME\b/im.test(e)&&this._supportedExtensions.push("8BITMIME"),/[ -]REQUIRETLS\b/im.test(e)&&this._supportedExtensions.push("REQUIRETLS"),/[ -]PIPELINING\b/im.test(e)&&this._supportedExtensions.push("PIPELINING"),/[ -]AUTH\b/i.test(e)&&(this.allowsAuth=!0),/[ -]AUTH(?:(\s+|=)[^\n]*\s+|\s+|=)PLAIN/i.test(e)&&this._supportedAuth.push("PLAIN"),/[ -]AUTH(?:(\s+|=)[^\n]*\s+|\s+|=)LOGIN/i.test(e)&&this._supportedAuth.push("LOGIN"),/[ -]AUTH(?:(\s+|=)[^\n]*\s+|\s+|=)CRAM-MD5/i.test(e)&&this._supportedAuth.push("CRAM-MD5"),/[ -]AUTH(?:(\s+|=)[^\n]*\s+|\s+|=)XOAUTH2/i.test(e)&&this._supportedAuth.push("XOAUTH2"),(t=e.match(/[ -]SIZE(?:[ \t]+(\d+))?/im))&&(this._supportedExtensions.push("SIZE"),this._maxAllowedSize=Number(t[1])||0),this.emit("connect")}_actionHELO(e){if(e.charAt(0)!=="2"){this._onError(new Error("Invalid HELO. response="+e),"EPROTOCOL",e,"HELO");return}this.allowsAuth=!0,this.emit("connect")}_actionSTARTTLS(e){if(e.charAt(0)!=="2"){if(this.options.opportunisticTLS)return this.logger.info({tnx:"smtp"},"Failed STARTTLS upgrade, continuing unencrypted"),this.emit("connect");this._onError(new Error("Error upgrading connection with STARTTLS"),"ETLS",e,"STARTTLS");return}this._upgradeConnection((t,n)=>{if(t){this._onError(new Error("Error initiating TLS - "+(t.message||t)),"ETLS",!1,"STARTTLS");return}this.logger.info({tnx:"smtp"},"Connection upgraded with STARTTLS"),n?this.options.lmtp?(this._responseActions.push(this._actionLHLO),this._sendCommand("LHLO "+this.name)):(this._responseActions.push(this._actionEHLO),this._sendCommand("EHLO "+this.name)):this.emit("connect")})}_actionAUTH_LOGIN_USER(e,t){if(!/^334[ -]/.test(e)){t(this._formatError('Invalid login sequence while waiting for "334 VXNlcm5hbWU6"',"EAUTH",e,"AUTH LOGIN"));return}this._responseActions.push(n=>{this._actionAUTH_LOGIN_PASS(n,t)}),this._sendCommand(Buffer.from(this._auth.credentials.user+"","utf-8").toString("base64"))}_actionAUTH_CRAM_MD5(e,t){let n=e.match(/^334\s+(.+)$/);if(!n)return t(this._formatError("Invalid login sequence while waiting for server challenge string","EAUTH",e,"AUTH CRAM-MD5"));let i=Buffer.from(n[1],"base64").toString("ascii"),o=F_.createHmac("md5",this._auth.credentials.pass);o.update(i);let s=this._auth.credentials.user+" "+o.digest("hex");this._responseActions.push(a=>{this._actionAUTH_CRAM_MD5_PASS(a,t)}),this._sendCommand(Buffer.from(s).toString("base64"),Buffer.from(this._auth.credentials.user+" /* secret */").toString("base64"))}_actionAUTH_CRAM_MD5_PASS(e,t){if(!e.match(/^235\s+/))return t(this._formatError('Invalid login sequence while waiting for "235"',"EAUTH",e,"AUTH CRAM-MD5"));this.logger.info({tnx:"smtp",username:this._auth.user,action:"authenticated",method:this._authMethod},"User %s authenticated",JSON.stringify(this._auth.user)),this.authenticated=!0,t(null,!0)}_actionAUTH_LOGIN_PASS(e,t){if(!/^334[ -]/.test(e))return t(this._formatError('Invalid login sequence while waiting for "334 UGFzc3dvcmQ6"',"EAUTH",e,"AUTH LOGIN"));this._responseActions.push(n=>{this._actionAUTHComplete(n,t)}),this._sendCommand(Buffer.from((this._auth.credentials.pass||"").toString(),"utf-8").toString("base64"),Buffer.from("/* secret */","utf-8").toString("base64"))}_actionAUTHComplete(e,t,n){if(!n&&typeof t=="function"&&(n=t,t=!1),e.substr(0,3)==="334"){this._responseActions.push(i=>{t||this._authMethod!=="XOAUTH2"?this._actionAUTHComplete(i,!0,n):setImmediate(()=>this._handleXOauth2Token(!0,n))}),this._sendCommand("");return}if(e.charAt(0)!=="2")return this.logger.info({tnx:"smtp",username:this._auth.user,action:"authfail",method:this._authMethod},"User %s failed to authenticate",JSON.stringify(this._auth.user)),n(this._formatError("Invalid login","EAUTH",e,"AUTH "+this._authMethod));this.logger.info({tnx:"smtp",username:this._auth.user,action:"authenticated",method:this._authMethod},"User %s authenticated",JSON.stringify(this._auth.user)),this.authenticated=!0,n(null,!0)}_actionMAIL(e,t){if(Number(e.charAt(0))!==2){let i=this._usingSmtpUtf8&&/^550 /.test(e)&&/[\x80-\uFFFF]/.test(this._envelope.from)?"Internationalized mailbox name not allowed":"Mail command failed";return t(this._formatError(i,"EENVELOPE",e,"MAIL FROM"))}if(!this._envelope.rcptQueue.length)return t(this._formatError("Can't send mail - no recipients defined","EENVELOPE",!1,"API"));this._recipientQueue=[];let n=this._supportedExtensions.includes("PIPELINING");do{let i=this._envelope.rcptQueue.shift();this._recipientQueue.push(i),this._responseActions.push(o=>{this._actionRCPT(o,t)}),this._sendCommand("RCPT TO:<"+i+">"+this._getDsnRcptToArgs())}while(n&&this._envelope.rcptQueue.length)}_actionRCPT(e,t){let n,i=this._recipientQueue.shift();if(Number(e.charAt(0))!==2){let o=this._usingSmtpUtf8&&/^553 /.test(e)&&/[\x80-\uFFFF]/.test(i)?"Internationalized mailbox name not allowed":"Recipient command failed";this._envelope.rejected.push(i),n=this._formatError(o,"EENVELOPE",e,"RCPT TO"),n.recipient=i,this._envelope.rejectedErrors.push(n)}else this._envelope.accepted.push(i);if(!this._envelope.rcptQueue.length&&!this._recipientQueue.length)if(this._envelope.rejected.length<this._envelope.to.length)this._responseActions.push(o=>{this._actionDATA(o,t)}),this._sendCommand("DATA");else return n=this._formatError("Can't send mail - all recipients were rejected","EENVELOPE",e,"RCPT TO"),n.rejected=this._envelope.rejected,n.rejectedErrors=this._envelope.rejectedErrors,t(n);else if(this._envelope.rcptQueue.length){let o=this._envelope.rcptQueue.shift();this._recipientQueue.push(o),this._responseActions.push(s=>{this._actionRCPT(s,t)}),this._sendCommand("RCPT TO:<"+o+">"+this._getDsnRcptToArgs())}}_actionDATA(e,t){if(!/^[23]/.test(e))return t(this._formatError("Data command failed","EENVELOPE",e,"DATA"));let n={accepted:this._envelope.accepted,rejected:this._envelope.rejected};this._ehloLines&&this._ehloLines.length&&(n.ehlo=this._ehloLines),this._envelope.rejectedErrors.length&&(n.rejectedErrors=this._envelope.rejectedErrors),t(null,n)}_actionSMTPStream(e,t){return Number(e.charAt(0))!==2?t(this._formatError("Message failed","EMESSAGE",e,"DATA")):t(null,e)}_actionLMTPStream(e,t,n,i){let o;if(Number(n.charAt(0))!==2){o=this._formatError("Message failed for recipient "+e,"EMESSAGE",n,"DATA"),o.recipient=e,this._envelope.rejected.push(e),this._envelope.rejectedErrors.push(o);for(let s=0,a=this._envelope.accepted.length;s<a;s++)this._envelope.accepted[s]===e&&this._envelope.accepted.splice(s,1)}if(t)return i(null,n)}_handleXOauth2Token(e,t){this._auth.oauth2.getToken(e,(n,i)=>{if(n)return this.logger.info({tnx:"smtp",username:this._auth.user,action:"authfail",method:this._authMethod},"User %s failed to authenticate",JSON.stringify(this._auth.user)),t(this._formatError(n,"EAUTH",!1,"AUTH XOAUTH2"));this._responseActions.push(o=>{this._actionAUTHComplete(o,e,t)}),this._sendCommand("AUTH XOAUTH2 "+this._auth.oauth2.buildXOAuth2Token(i),"AUTH XOAUTH2 "+this._auth.oauth2.buildXOAuth2Token("/* secret */"))})}_isDestroyedMessage(e){if(this._destroyed)return"Cannot "+e+" - smtp connection is already destroyed.";if(this._socket){if(this._socket.destroyed)return"Cannot "+e+" - smtp connection socket is already destroyed.";if(!this._socket.writable)return"Cannot "+e+" - smtp connection socket is already half-closed."}}_getHostname(){let e;try{e=MA.hostname()||""}catch{e="localhost"}return(!e||e.indexOf(".")<0)&&(e="[127.0.0.1]"),e.match(/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/)&&(e="["+e+"]"),e}};W_.exports=Kd});var Xd=_((e2,G_)=>{"use strict";var{Stream:FA}=N("stream"),HA=so(),BA=N("crypto"),VA=qe(),un=kt(),Jd=class extends FA{constructor(e,t){if(super(),this.options=e||{},e&&e.serviceClient){if(!e.privateKey||!e.user){let i=new Error('Options "privateKey" and "user" are required for service account!');i.code=un.EOAUTH2,setImmediate(()=>this.emit("error",i));return}let n=Math.min(Math.max(Number(this.options.serviceRequestTimeout)||0,0),3600);this.options.serviceRequestTimeout=n||5*60}if(this.logger=VA.getLogger({logger:t},{component:this.options.component||"OAuth2"}),this.provisionCallback=typeof this.options.provisionCallback=="function"?this.options.provisionCallback:!1,this.options.accessUrl=this.options.accessUrl||"https://accounts.google.com/o/oauth2/token",this.options.customHeaders=this.options.customHeaders||{},this.options.customParams=this.options.customParams||{},this.accessToken=this.options.accessToken||!1,this.options.expires&&Number(this.options.expires))this.expires=this.options.expires;else{let n=Math.max(Number(this.options.timeout)||0,0);this.expires=n&&Date.now()+n*1e3||0}this.renewing=!1,this.renewalQueue=[]}getToken(e,t){if(!e&&this.accessToken&&(!this.expires||this.expires>Date.now()))return this.logger.debug({tnx:"OAUTH2",user:this.options.user,action:"reuse"},"Reusing existing access token for %s",this.options.user),t(null,this.accessToken);if(!this.provisionCallback&&!this.options.refreshToken&&!this.options.serviceClient){if(this.accessToken)return this.logger.debug({tnx:"OAUTH2",user:this.options.user,action:"reuse"},"Reusing existing access token (no refresh capability) for %s",this.options.user),t(null,this.accessToken);this.logger.error({tnx:"OAUTH2",user:this.options.user,action:"renew"},"Cannot renew access token for %s: No refresh mechanism available",this.options.user);let i=new Error("Can't create new access token for user");return i.code=un.EOAUTH2,t(i)}if(this.renewing)return this.renewalQueue.push({renew:e,callback:t});this.renewing=!0;let n=(i,o)=>{this.renewalQueue.forEach(s=>s.callback(i,o)),this.renewalQueue=[],this.renewing=!1,i?this.logger.error({err:i,tnx:"OAUTH2",user:this.options.user,action:"renew"},"Failed generating new Access Token for %s",this.options.user):this.logger.info({tnx:"OAUTH2",user:this.options.user,action:"renew"},"Generated new Access Token for %s",this.options.user),t(i,o)};this.provisionCallback?this.provisionCallback(this.options.user,!!e,(i,o,s)=>{!i&&o&&(this.accessToken=o,this.expires=s||0),n(i,o)}):this.generateToken(n)}updateToken(e,t){this.accessToken=e,t=Math.max(Number(t)||0,0),this.expires=t&&Date.now()+t*1e3||0,this.emit("token",{user:this.options.user,accessToken:e||"",expires:this.expires})}generateToken(e){let t,n;if(this.options.serviceClient){let i=Math.floor(Date.now()/1e3),o={iss:this.options.serviceClient,scope:this.options.scope||"https://mail.google.com/",sub:this.options.user,aud:this.options.accessUrl,iat:i,exp:i+this.options.serviceRequestTimeout},s;try{s=this.jwtSignRS256(o)}catch{let c=new Error("Can't generate token. Check your auth options");return c.code=un.EOAUTH2,e(c)}t={grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:s},n={grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:o}}else{if(!this.options.refreshToken){let i=new Error("Can't create new access token for user");return i.code=un.EOAUTH2,e(i)}t={client_id:this.options.clientId||"",client_secret:this.options.clientSecret||"",refresh_token:this.options.refreshToken,grant_type:"refresh_token"},n={client_id:this.options.clientId||"",client_secret:(this.options.clientSecret||"").substr(0,6)+"...",refresh_token:(this.options.refreshToken||"").substr(0,6)+"...",grant_type:"refresh_token"}}Object.assign(t,this.options.customParams),Object.assign(n,this.options.customParams),this.logger.debug({tnx:"OAUTH2",user:this.options.user,action:"generate"},"Requesting token using: %s",JSON.stringify(n)),this.postRequest(this.options.accessUrl,t,this.options,(i,o)=>{let s;if(i)return e(i);try{s=JSON.parse(o.toString())}catch(l){return e(l)}if(!s||typeof s!="object"){this.logger.debug({tnx:"OAUTH2",user:this.options.user,action:"post"},"Response: %s",(o||"").toString());let l=new Error("Invalid authentication response");return l.code=un.EOAUTH2,e(l)}let a=Object.assign({},s);if(a.access_token&&(a.access_token=(a.access_token||"").toString().substr(0,6)+"..."),this.logger.debug({tnx:"OAUTH2",user:this.options.user,action:"post"},"Response: %s",JSON.stringify(a)),s.error){let l=s.error;s.error_description&&(l+=": "+s.error_description),s.error_uri&&(l+=" ("+s.error_uri+")");let u=new Error(l);return u.code=un.EOAUTH2,e(u)}if(s.access_token)return this.updateToken(s.access_token,s.expires_in),e(null,this.accessToken);let c=new Error("No access token");return c.code=un.EOAUTH2,e(c)})}buildXOAuth2Token(e){let t=["user="+(this.options.user||""),"auth=Bearer "+(e||this.accessToken),"",""];return Buffer.from(t.join(""),"utf-8").toString("base64")}postRequest(e,t,n,i){let o=!1,s=[],a=0,c=HA(e,{method:"post",headers:n.customHeaders,body:t,allowErrorResponse:!0});c.on("readable",()=>{let l;for(;(l=c.read())!==null;)s.push(l),a+=l.length}),c.once("error",l=>{if(!o)return o=!0,i(l)}),c.once("end",()=>{if(!o)return o=!0,i(null,Buffer.concat(s,a))})}toBase64URL(e){return typeof e=="string"&&(e=Buffer.from(e)),e.toString("base64").replace(/[=]+/g,"").replace(/\+/g,"-").replace(/\//g,"_")}jwtSignRS256(e){e=['{"alg":"RS256","typ":"JWT"}',JSON.stringify(e)].map(n=>this.toBase64URL(n)).join(".");let t=BA.createSign("RSA-SHA256").update(e).sign(this.options.privateKey);return e+"."+this.toBase64URL(t)}};G_.exports=Jd});var X_=_((t2,J_)=>{"use strict";var WA=ma(),GA=qe().assign,KA=Xd(),K_=kt(),JA=N("events"),Qd=class extends JA{constructor(e){if(super(),this.pool=e,this.options=e.options,this.logger=this.pool.logger,this.options.auth)switch((this.options.auth.type||"").toString().toUpperCase()){case"OAUTH2":{let t=new KA(this.options.auth,this.logger);t.provisionCallback=this.pool.mailer&&this.pool.mailer.get("oauth2_provision_cb")||t.provisionCallback,this.auth={type:"OAUTH2",user:this.options.auth.user,oauth2:t,method:"XOAUTH2"},t.on("token",n=>this.pool.mailer.emit("token",n)),t.on("error",n=>this.emit("error",n));break}default:if(!this.options.auth.user&&!this.options.auth.pass)break;this.auth={type:(this.options.auth.type||"").toString().toUpperCase()||"LOGIN",user:this.options.auth.user,credentials:{user:this.options.auth.user||"",pass:this.options.auth.pass,options:this.options.auth.options},method:(this.options.auth.method||"").trim().toUpperCase()||this.options.authMethod||!1}}this._connection=!1,this._connected=!1,this.messages=0,this.available=!0}connect(e){this.pool.getSocket(this.options,(t,n)=>{if(t)return e(t);let i=!1,o=this.options;n&&n.connection&&(this.logger.info({tnx:"proxy",remoteAddress:n.connection.remoteAddress,remotePort:n.connection.remotePort,destHost:o.host||"",destPort:o.port||"",action:"connected"},"Using proxied socket from %s:%s to %s:%s",n.connection.remoteAddress,n.connection.remotePort,o.host||"",o.port||""),o=Object.assign(GA(!1,o),n)),this.connection=new WA(o),this.connection.once("error",s=>{if(this.emit("error",s),!i)return i=!0,e(s)}),this.connection.once("end",()=>{if(this.close(),i)return;i=!0;let s=setTimeout(()=>{if(i)return;let a=new Error("Unexpected socket close");this.connection&&this.connection._socket&&this.connection._socket.upgrading&&(a.code=K_.ETLS),e(a)},1e3);try{s.unref()}catch{}}),this.connection.connect(()=>{if(!i)if(this.auth&&(this.connection.allowsAuth||o.forceAuth))this.connection.login(this.auth,s=>{if(!i){if(i=!0,s)return this.connection.close(),this.emit("error",s),e(s);this._connected=!0,e(null,!0)}});else return i=!0,this._connected=!0,e(null,!0)})})}send(e,t){if(!this._connected)return this.connect(s=>s?t(s):this.send(e,t));let n=e.message.getEnvelope(),i=e.message.messageId(),o=[].concat(n.to||[]);o.length>3&&o.push("...and "+o.splice(2).length+" more"),this.logger.info({tnx:"send",messageId:i,cid:this.id},"Sending message %s using #%s to <%s>",i,this.id,o.join(", ")),e.data.dsn&&(n.dsn=e.data.dsn),e.data.requireTLSExtensionEnabled&&(n.requireTLSExtensionEnabled=e.data.requireTLSExtensionEnabled),this.connection.send(n,e.message.createReadStream(),(s,a)=>{if(this.messages++,s)return this.connection.close(),this.emit("error",s),t(s);a.envelope={from:n.from,to:n.to},a.messageId=i,setImmediate(()=>{if(this.messages>=this.options.maxMessages){let c=new Error("Resource exhausted");c.code=K_.EMAXLIMIT,this.connection.close(),this.emit("error",c)}else this.pool._checkRateLimit(()=>{this.available=!0,this.emit("available")})}),t(null,a)})}close(){this._connected=!1,this.auth&&this.auth.oauth2&&this.auth.oauth2.removeAllListeners(),this.connection&&this.connection.close(),this.emit("close")}};J_.exports=Qd});var Q_=_((r2,XA)=>{XA.exports={"1und1":{description:"1&1 Mail (German hosting provider)",host:"smtp.1und1.de",port:465,secure:!0,authMethod:"LOGIN"},"126":{description:"126 Mail (NetEase)",host:"smtp.126.com",port:465,secure:!0},"163":{description:"163 Mail (NetEase)",host:"smtp.163.com",port:465,secure:!0},Aliyun:{description:"Alibaba Cloud Mail",domains:["aliyun.com"],host:"smtp.aliyun.com",port:465,secure:!0},AliyunQiye:{description:"Alibaba Cloud Enterprise Mail",host:"smtp.qiye.aliyun.com",port:465,secure:!0},AOL:{description:"AOL Mail",domains:["aol.com"],host:"smtp.aol.com",port:587},Aruba:{description:"Aruba PEC (Italian email provider)",domains:["aruba.it","pec.aruba.it"],aliases:["Aruba PEC"],host:"smtps.aruba.it",port:465,secure:!0,authMethod:"LOGIN"},Bluewin:{description:"Bluewin (Swiss email provider)",host:"smtpauths.bluewin.ch",domains:["bluewin.ch"],port:465},BOL:{description:"BOL Mail (Brazilian provider)",domains:["bol.com.br"],host:"smtp.bol.com.br",port:587,requireTLS:!0},DebugMail:{description:"DebugMail (email testing service)",host:"debugmail.io",port:25},Disroot:{description:"Disroot (privacy-focused provider)",domains:["disroot.org"],host:"disroot.org",port:587,secure:!1,authMethod:"LOGIN"},DynectEmail:{description:"Dyn Email Delivery",aliases:["Dynect"],host:"smtp.dynect.net",port:25},ElasticEmail:{description:"Elastic Email",aliases:["Elastic Email"],host:"smtp.elasticemail.com",port:465,secure:!0},Ethereal:{description:"Ethereal Email (email testing service)",aliases:["ethereal.email"],host:"smtp.ethereal.email",port:587},FastMail:{description:"FastMail",domains:["fastmail.fm"],host:"smtp.fastmail.com",port:465,secure:!0},"Feishu Mail":{description:"Feishu Mail (Lark)",aliases:["Feishu","FeishuMail"],domains:["www.feishu.cn"],host:"smtp.feishu.cn",port:465,secure:!0},"Forward Email":{description:"Forward Email (email forwarding service)",aliases:["FE","ForwardEmail"],domains:["forwardemail.net"],host:"smtp.forwardemail.net",port:465,secure:!0},GandiMail:{description:"Gandi Mail",aliases:["Gandi","Gandi Mail"],host:"mail.gandi.net",port:587},Gmail:{description:"Gmail",aliases:["Google Mail"],domains:["gmail.com","googlemail.com"],host:"smtp.gmail.com",port:465,secure:!0},GmailWorkspace:{description:"Gmail Workspace",aliases:["Google Workspace Mail"],host:"smtp-relay.gmail.com",port:465,secure:!0},GMX:{description:"GMX Mail",domains:["gmx.com","gmx.net","gmx.de"],host:"mail.gmx.com",port:587},Godaddy:{description:"GoDaddy Email (US)",host:"smtpout.secureserver.net",port:25},GodaddyAsia:{description:"GoDaddy Email (Asia)",host:"smtp.asia.secureserver.net",port:25},GodaddyEurope:{description:"GoDaddy Email (Europe)",host:"smtp.europe.secureserver.net",port:25},"hot.ee":{description:"Hot.ee (Estonian email provider)",host:"mail.hot.ee"},Hotmail:{description:"Outlook.com / Hotmail",aliases:["Outlook","Outlook.com","Hotmail.com"],domains:["hotmail.com","outlook.com"],host:"smtp-mail.outlook.com",port:587},iCloud:{description:"iCloud Mail",aliases:["Me","Mac"],domains:["me.com","mac.com"],host:"smtp.mail.me.com",port:587},Infomaniak:{description:"Infomaniak Mail (Swiss hosting provider)",host:"mail.infomaniak.com",domains:["ik.me","ikmail.com","etik.com"],port:587},KolabNow:{description:"KolabNow (secure email service)",domains:["kolabnow.com"],aliases:["Kolab"],host:"smtp.kolabnow.com",port:465,secure:!0,authMethod:"LOGIN"},Loopia:{description:"Loopia (Swedish hosting provider)",host:"mailcluster.loopia.se",port:465},Loops:{description:"Loops",host:"smtp.loops.so",port:587},"mail.ee":{description:"Mail.ee (Estonian email provider)",host:"smtp.mail.ee"},"Mail.ru":{description:"Mail.ru",host:"smtp.mail.ru",port:465,secure:!0},"Mailcatch.app":{description:"Mailcatch (email testing service)",host:"sandbox-smtp.mailcatch.app",port:2525},Maildev:{description:"MailDev (local email testing)",port:1025,ignoreTLS:!0},MailerSend:{description:"MailerSend",host:"smtp.mailersend.net",port:587},Mailgun:{description:"Mailgun",host:"smtp.mailgun.org",port:465,secure:!0},Mailjet:{description:"Mailjet",host:"in.mailjet.com",port:587},Mailosaur:{description:"Mailosaur (email testing service)",host:"mailosaur.io",port:25},Mailtrap:{description:"Mailtrap",host:"live.smtp.mailtrap.io",port:587},Mandrill:{description:"Mandrill (by Mailchimp)",host:"smtp.mandrillapp.com",port:587},Naver:{description:"Naver Mail (Korean email provider)",host:"smtp.naver.com",port:587},OhMySMTP:{description:"OhMySMTP (email delivery service)",host:"smtp.ohmysmtp.com",port:587,secure:!1},One:{description:"One.com Email",host:"send.one.com",port:465,secure:!0},OpenMailBox:{description:"OpenMailBox",aliases:["OMB","openmailbox.org"],host:"smtp.openmailbox.org",port:465,secure:!0},Outlook365:{description:"Microsoft 365 / Office 365",host:"smtp.office365.com",port:587,secure:!1},Postmark:{description:"Postmark",aliases:["PostmarkApp"],host:"smtp.postmarkapp.com",port:2525},Proton:{description:"Proton Mail",aliases:["ProtonMail","Proton.me","Protonmail.com","Protonmail.ch"],domains:["proton.me","protonmail.com","pm.me","protonmail.ch"],host:"smtp.protonmail.ch",port:587,requireTLS:!0},"qiye.aliyun":{description:"Alibaba Mail Enterprise Edition",host:"smtp.mxhichina.com",port:"465",secure:!0},QQ:{description:"QQ Mail",domains:["qq.com"],host:"smtp.qq.com",port:465,secure:!0},QQex:{description:"QQ Enterprise Mail",aliases:["QQ Enterprise"],domains:["exmail.qq.com"],host:"smtp.exmail.qq.com",port:465,secure:!0},Resend:{description:"Resend",host:"smtp.resend.com",port:465,secure:!0},Runbox:{description:"Runbox (Norwegian email provider)",domains:["runbox.com"],host:"smtp.runbox.com",port:465,secure:!0},SendCloud:{description:"SendCloud (Chinese email delivery)",host:"smtp.sendcloud.net",port:2525},SendGrid:{description:"SendGrid",host:"smtp.sendgrid.net",port:587},SendinBlue:{description:"Brevo (formerly Sendinblue)",aliases:["Brevo"],host:"smtp-relay.brevo.com",port:587},SendPulse:{description:"SendPulse",host:"smtp-pulse.com",port:465,secure:!0},SES:{description:"AWS SES US East (N. Virginia)",host:"email-smtp.us-east-1.amazonaws.com",port:465,secure:!0},"SES-AP-NORTHEAST-1":{description:"AWS SES Asia Pacific (Tokyo)",host:"email-smtp.ap-northeast-1.amazonaws.com",port:465,secure:!0},"SES-AP-NORTHEAST-2":{description:"AWS SES Asia Pacific (Seoul)",host:"email-smtp.ap-northeast-2.amazonaws.com",port:465,secure:!0},"SES-AP-NORTHEAST-3":{description:"AWS SES Asia Pacific (Osaka)",host:"email-smtp.ap-northeast-3.amazonaws.com",port:465,secure:!0},"SES-AP-SOUTH-1":{description:"AWS SES Asia Pacific (Mumbai)",host:"email-smtp.ap-south-1.amazonaws.com",port:465,secure:!0},"SES-AP-SOUTHEAST-1":{description:"AWS SES Asia Pacific (Singapore)",host:"email-smtp.ap-southeast-1.amazonaws.com",port:465,secure:!0},"SES-AP-SOUTHEAST-2":{description:"AWS SES Asia Pacific (Sydney)",host:"email-smtp.ap-southeast-2.amazonaws.com",port:465,secure:!0},"SES-CA-CENTRAL-1":{description:"AWS SES Canada (Central)",host:"email-smtp.ca-central-1.amazonaws.com",port:465,secure:!0},"SES-EU-CENTRAL-1":{description:"AWS SES Europe (Frankfurt)",host:"email-smtp.eu-central-1.amazonaws.com",port:465,secure:!0},"SES-EU-NORTH-1":{description:"AWS SES Europe (Stockholm)",host:"email-smtp.eu-north-1.amazonaws.com",port:465,secure:!0},"SES-EU-WEST-1":{description:"AWS SES Europe (Ireland)",host:"email-smtp.eu-west-1.amazonaws.com",port:465,secure:!0},"SES-EU-WEST-2":{description:"AWS SES Europe (London)",host:"email-smtp.eu-west-2.amazonaws.com",port:465,secure:!0},"SES-EU-WEST-3":{description:"AWS SES Europe (Paris)",host:"email-smtp.eu-west-3.amazonaws.com",port:465,secure:!0},"SES-SA-EAST-1":{description:"AWS SES South America (S\xE3o Paulo)",host:"email-smtp.sa-east-1.amazonaws.com",port:465,secure:!0},"SES-US-EAST-1":{description:"AWS SES US East (N. Virginia)",host:"email-smtp.us-east-1.amazonaws.com",port:465,secure:!0},"SES-US-EAST-2":{description:"AWS SES US East (Ohio)",host:"email-smtp.us-east-2.amazonaws.com",port:465,secure:!0},"SES-US-GOV-EAST-1":{description:"AWS SES GovCloud (US-East)",host:"email-smtp.us-gov-east-1.amazonaws.com",port:465,secure:!0},"SES-US-GOV-WEST-1":{description:"AWS SES GovCloud (US-West)",host:"email-smtp.us-gov-west-1.amazonaws.com",port:465,secure:!0},"SES-US-WEST-1":{description:"AWS SES US West (N. California)",host:"email-smtp.us-west-1.amazonaws.com",port:465,secure:!0},"SES-US-WEST-2":{description:"AWS SES US West (Oregon)",host:"email-smtp.us-west-2.amazonaws.com",port:465,secure:!0},Seznam:{description:"Seznam Email (Czech email provider)",aliases:["Seznam Email"],domains:["seznam.cz","email.cz","post.cz","spoluzaci.cz"],host:"smtp.seznam.cz",port:465,secure:!0},SMTP2GO:{description:"SMTP2GO",host:"mail.smtp2go.com",port:2525},Sparkpost:{description:"SparkPost",aliases:["SparkPost","SparkPost Mail"],domains:["sparkpost.com"],host:"smtp.sparkpostmail.com",port:587,secure:!1},Tipimail:{description:"Tipimail (email delivery service)",host:"smtp.tipimail.com",port:587},Tutanota:{description:"Tutanota (Tuta Mail)",domains:["tutanota.com","tuta.com","tutanota.de","tuta.io"],host:"smtp.tutanota.com",port:465,secure:!0},Yahoo:{description:"Yahoo Mail",domains:["yahoo.com"],host:"smtp.mail.yahoo.com",port:465,secure:!0},Yandex:{description:"Yandex Mail",domains:["yandex.ru"],host:"smtp.yandex.ru",port:465,secure:!0},Zimbra:{description:"Zimbra Mail Server",aliases:["Zimbra Collaboration"],host:"smtp.zimbra.com",port:587,requireTLS:!0},Zoho:{description:"Zoho Mail",host:"smtp.zoho.com",port:465,secure:!0,authMethod:"LOGIN"}}});var Yd=_((n2,eb)=>{"use strict";var Y_=Q_(),fa={};Object.keys(Y_).forEach(r=>{let e=Y_[r],t=QA(e);fa[ha(r)]=t,[].concat(e.aliases||[]).forEach(n=>{fa[ha(n)]=t}),[].concat(e.domains||[]).forEach(n=>{fa[ha(n)]=t})});function ha(r){return r.replace(/[^a-zA-Z0-9.-]/g,"").toLowerCase()}function QA(r){let e={};return Object.keys(r).forEach(t=>{["domains","aliases"].includes(t)||(e[t]=r[t])}),e}eb.exports=function(r){return r=ha(r.split("@").pop()),fa[r]||!1}});var ob=_((i2,ib)=>{"use strict";var YA=N("events"),tb=X_(),eO=ma(),tO=Yd(),mo=qe(),rb=kt(),nb=wt(),em=class extends YA{constructor(e){super(),e=e||{},typeof e=="string"&&(e={url:e});let t,n=e.service;typeof e.getSocket=="function"&&(this.getSocket=e.getSocket),e.url&&(t=mo.parseConnectionUrl(e.url),n=n||t.service),this.options=mo.assign(!1,e,t,n&&tO(n)),this.options.maxConnections=this.options.maxConnections||5,this.options.maxMessages=this.options.maxMessages||100,this.logger=mo.getLogger(this.options,{component:this.options.component||"smtp-pool"}),this.name="SMTP (pool)",this.version=nb.version+"[client:"+nb.version+"]",this._rateLimit={counter:0,timeout:null,waiting:[],checkpoint:!1,delta:Number(this.options.rateDelta)||1e3,limit:Number(this.options.rateLimit)||0},this._closed=!1,this._queue=[],this._connections=[],this._connectionCounter=0,this.idling=!0,setImmediate(()=>{this.idling&&this.emit("idle")})}getSocket(e,t){return setImmediate(()=>t(null,!1))}send(e,t){return this._closed?!1:(this._queue.push({mail:e,requeueAttempts:0,callback:t}),this.idling&&this._queue.length>=this.options.maxConnections&&(this.idling=!1),setImmediate(()=>this._processMessages()),!0)}close(){let e,t=this._connections.length;if(this._closed=!0,clearTimeout(this._rateLimit.timeout),!t&&!this._queue.length)return;for(let i=t-1;i>=0;i--)this._connections[i]&&this._connections[i].available&&(e=this._connections[i],e.close(),this.logger.info({tnx:"connection",cid:e.id,action:"removed"},"Connection #%s removed",e.id));if(t&&!this._connections.length&&this.logger.debug({tnx:"connection"},"All connections removed"),!this._queue.length)return;let n=()=>{if(!this._queue.length){this.logger.debug({tnx:"connection"},"Pending queue entries cleared");return}let i=this._queue.shift();if(i&&typeof i.callback=="function")try{i.callback(new Error("Connection pool was closed"))}catch(o){this.logger.error({err:o,tnx:"callback",cid:e.id},"Callback error for #%s: %s",e.id,o.message)}setImmediate(n)};setImmediate(n)}_processMessages(){if(this._closed)return;if(!this._queue.length){this.idling||(this.idling=!0,this.emit("idle"));return}let e=this._connections.find(n=>n.available);if(!e&&this._connections.length<this.options.maxConnections&&(e=this._createConnection()),!e){this.idling=!1;return}!this.idling&&this._queue.length<this.options.maxConnections&&(this.idling=!0,this.emit("idle"));let t=e.queueEntry=this._queue.shift();t.messageId=(e.queueEntry.mail.message.getHeader("message-id")||"").replace(/[<>\s]/g,""),e.available=!1,this.logger.debug({tnx:"pool",cid:e.id,messageId:t.messageId,action:"assign"},"Assigned message <%s> to #%s (%s)",t.messageId,e.id,e.messages+1),this._rateLimit.limit&&(this._rateLimit.counter++,this._rateLimit.checkpoint||(this._rateLimit.checkpoint=Date.now())),e.send(t.mail,(n,i)=>{if(t===e.queueEntry){try{t.callback(n,i)}catch(o){this.logger.error({err:o,tnx:"callback",cid:e.id},"Callback error for #%s: %s",e.id,o.message)}e.queueEntry=!1}})}_createConnection(){let e=new tb(this);return e.id=++this._connectionCounter,this.logger.info({tnx:"pool",cid:e.id,action:"conection"},"Created new pool resource #%s",e.id),e.on("available",()=>{this.logger.debug({tnx:"connection",cid:e.id,action:"available"},"Connection #%s became available",e.id),this._closed?this.close():this._processMessages()}),e.once("error",t=>{if(t.code!==rb.EMAXLIMIT?this.logger.warn({err:t,tnx:"pool",cid:e.id},"Pool Error for #%s: %s",e.id,t.message):this.logger.debug({tnx:"pool",cid:e.id,action:"maxlimit"},"Max messages limit exchausted for #%s",e.id),e.queueEntry){try{e.queueEntry.callback(t)}catch(n){this.logger.error({err:n,tnx:"callback",cid:e.id},"Callback error for #%s: %s",e.id,n.message)}e.queueEntry=!1}this._removeConnection(e),this._continueProcessing()}),e.once("close",()=>{this.logger.info({tnx:"connection",cid:e.id,action:"closed"},"Connection #%s was closed",e.id),this._removeConnection(e),e.queueEntry?setTimeout(()=>{e.queueEntry&&(this._shouldRequeuOnConnectionClose(e.queueEntry)?this._requeueEntryOnConnectionClose(e):this._failDeliveryOnConnectionClose(e)),this._continueProcessing()},50):(!this._closed&&this.idling&&!this._connections.length&&this.emit("clear"),this._continueProcessing())}),this._connections.push(e),e}_shouldRequeuOnConnectionClose(e){return this.options.maxRequeues===void 0||this.options.maxRequeues<0?!0:e.requeueAttempts<this.options.maxRequeues}_failDeliveryOnConnectionClose(e){if(e.queueEntry&&e.queueEntry.callback){try{e.queueEntry.callback(new Error("Reached maximum number of retries after connection was closed"))}catch(t){this.logger.error({err:t,tnx:"callback",messageId:e.queueEntry.messageId,cid:e.id},"Callback error for #%s: %s",e.id,t.message)}e.queueEntry=!1}}_requeueEntryOnConnectionClose(e){e.queueEntry.requeueAttempts+=1,this.logger.debug({tnx:"pool",cid:e.id,messageId:e.queueEntry.messageId,action:"requeue"},"Re-queued message <%s> for #%s. Attempt: #%s",e.queueEntry.messageId,e.id,e.queueEntry.requeueAttempts),this._queue.unshift(e.queueEntry),e.queueEntry=!1}_continueProcessing(){this._closed?this.close():setTimeout(()=>this._processMessages(),100)}_removeConnection(e){let t=this._connections.indexOf(e);t!==-1&&this._connections.splice(t,1)}_checkRateLimit(e){if(!this._rateLimit.limit)return e();let t=Date.now();if(this._rateLimit.counter<this._rateLimit.limit)return e();if(this._rateLimit.waiting.push(e),this._rateLimit.checkpoint<=t-this._rateLimit.delta)return this._clearRateLimit();this._rateLimit.timeout||(this._rateLimit.timeout=setTimeout(()=>this._clearRateLimit(),this._rateLimit.delta-(t-this._rateLimit.checkpoint)),this._rateLimit.checkpoint=t)}_clearRateLimit(){for(clearTimeout(this._rateLimit.timeout),this._rateLimit.timeout=null,this._rateLimit.counter=0,this._rateLimit.checkpoint=!1;this._rateLimit.waiting.length;){let e=this._rateLimit.waiting.shift();setImmediate(e)}}isIdle(){return this.idling}verify(e){let t;e||(t=new Promise((i,o)=>{e=mo.callbackPromise(i,o)}));let n=new tb(this).auth;return this.getSocket(this.options,(i,o)=>{if(i)return e(i);let s=this.options;o&&o.connection&&(this.logger.info({tnx:"proxy",remoteAddress:o.connection.remoteAddress,remotePort:o.connection.remotePort,destHost:s.host||"",destPort:s.port||"",action:"connected"},"Using proxied socket from %s:%s to %s:%s",o.connection.remoteAddress,o.connection.remotePort,s.host||"",s.port||""),s=Object.assign(mo.assign(!1,s),o));let a=new eO(s),c=!1;a.once("error",u=>{if(!c)return c=!0,a.close(),e(u)}),a.once("end",()=>{if(!c)return c=!0,e(new Error("Connection closed"))});let l=()=>{if(!c)return c=!0,a.quit(),e(null,!0)};a.connect(()=>{if(!c)if(n&&(a.allowsAuth||s.forceAuth))a.login(n,u=>{if(!c){if(u)return c=!0,a.close(),e(u);l()}});else if(!n&&a.allowsAuth&&s.forceAuth){let u=new Error("Authentication info was not provided");return u.code=rb.ENOAUTH,c=!0,a.close(),e(u)}else l()})}),t}};ib.exports=em});var ub=_((o2,lb)=>{"use strict";var rO=N("events"),sb=ma(),nO=Yd(),Kn=qe(),iO=Xd(),ab=kt(),cb=wt(),tm=class extends rO{constructor(e){super(),e=e||{},typeof e=="string"&&(e={url:e});let t,n=e.service;typeof e.getSocket=="function"&&(this.getSocket=e.getSocket),e.url&&(t=Kn.parseConnectionUrl(e.url),n=n||t.service),this.options=Kn.assign(!1,e,t,n&&nO(n)),this.logger=Kn.getLogger(this.options,{component:this.options.component||"smtp-transport"}),this.name="SMTP",this.version=cb.version+"[client:"+cb.version+"]",this.options.auth&&(this.auth=this.getAuth({}))}getSocket(e,t){return setImmediate(()=>t(null,!1))}getAuth(e){if(!e)return this.auth;let t=Object.assign({},this.options.auth&&typeof this.options.auth=="object"?this.options.auth:{},e&&typeof e=="object"?e:{});if(Object.keys(t).length===0)return!1;switch((t.type||"").toString().toUpperCase()){case"OAUTH2":{if(!t.service&&!t.user)return!1;let n=new iO(t,this.logger);return n.provisionCallback=this.mailer&&this.mailer.get("oauth2_provision_cb")||n.provisionCallback,n.on("token",i=>this.mailer.emit("token",i)),n.on("error",i=>this.emit("error",i)),{type:"OAUTH2",user:t.user,oauth2:n,method:"XOAUTH2"}}default:return{type:(t.type||"").toString().toUpperCase()||"LOGIN",user:t.user,credentials:{user:t.user||"",pass:t.pass,options:t.options},method:(t.method||"").trim().toUpperCase()||this.options.authMethod||!1}}}send(e,t){this.getSocket(this.options,(n,i)=>{if(n)return t(n);let o=!1,s=this.options;i&&i.connection&&(this.logger.info({tnx:"proxy",remoteAddress:i.connection.remoteAddress,remotePort:i.connection.remotePort,destHost:s.host||"",destPort:s.port||"",action:"connected"},"Using proxied socket from %s:%s to %s:%s",i.connection.remoteAddress,i.connection.remotePort,s.host||"",s.port||""),s=Object.assign(Kn.assign(!1,s),i));let a=new sb(s);a.once("error",l=>{if(!o)return o=!0,a.close(),t(l)}),a.once("end",()=>{if(o)return;let l=setTimeout(()=>{if(o)return;o=!0;let u=new Error("Unexpected socket close");a&&a._socket&&a._socket.upgrading&&(u.code=ab.ETLS),t(u)},1e3);try{l.unref()}catch{}});let c=()=>{let l=e.message.getEnvelope(),u=e.message.messageId(),p=[].concat(l.to||[]);p.length>3&&p.push("...and "+p.splice(2).length+" more"),e.data.dsn&&(l.dsn=e.data.dsn),e.data.requireTLSExtensionEnabled&&(l.requireTLSExtensionEnabled=e.data.requireTLSExtensionEnabled),this.logger.info({tnx:"send",messageId:u},"Sending message %s to <%s>",u,p.join(", ")),a.send(l,e.message.createReadStream(),(d,f)=>{if(o=!0,a.close(),d)return this.logger.error({err:d,tnx:"send"},"Send error for %s: %s",u,d.message),t(d);f.envelope={from:l.from,to:l.to},f.messageId=u;try{return t(null,f)}catch(m){this.logger.error({err:m,tnx:"callback"},"Callback error for %s: %s",u,m.message)}})};a.connect(()=>{if(o)return;let l=this.getAuth(e.data.auth);l&&(a.allowsAuth||s.forceAuth)?a.login(l,u=>{if(l&&l!==this.auth&&l.oauth2&&l.oauth2.removeAllListeners(),!o){if(u)return o=!0,a.close(),t(u);c()}}):c()})})}verify(e){let t;return e||(t=new Promise((n,i)=>{e=Kn.callbackPromise(n,i)})),this.getSocket(this.options,(n,i)=>{if(n)return e(n);let o=this.options;i&&i.connection&&(this.logger.info({tnx:"proxy",remoteAddress:i.connection.remoteAddress,remotePort:i.connection.remotePort,destHost:o.host||"",destPort:o.port||"",action:"connected"},"Using proxied socket from %s:%s to %s:%s",i.connection.remoteAddress,i.connection.remotePort,o.host||"",o.port||""),o=Object.assign(Kn.assign(!1,o),i));let s=new sb(o),a=!1;s.once("error",l=>{if(!a)return a=!0,s.close(),e(l)}),s.once("end",()=>{if(!a)return a=!0,e(new Error("Connection closed"))});let c=()=>{if(!a)return a=!0,s.quit(),e(null,!0)};s.connect(()=>{if(a)return;let l=this.getAuth({});if(l&&(s.allowsAuth||o.forceAuth))s.login(l,u=>{if(!a){if(u)return a=!0,s.close(),e(u);c()}});else if(!l&&s.allowsAuth&&o.forceAuth){let u=new Error("Authentication info was not provided");return u.code=ab.ENOAUTH,a=!0,s.close(),e(u)}else c()})}),t}close(){this.auth&&this.auth.oauth2&&this.auth.oauth2.removeAllListeners(),this.emit("close")}};lb.exports=tm});var db=_((s2,pb)=>{"use strict";var{spawn:oO}=N("child_process"),sO=wt(),aO=qe(),rm=kt(),nm=class{constructor(e){e=e||{},this._spawn=oO,this.options=e,this.name="Sendmail",this.version=sO.version,this.path="sendmail",this.args=!1,this.logger=aO.getLogger(this.options,{component:this.options.component||"sendmail"}),typeof e=="string"?this.path=e:typeof e=="object"&&(e.path&&(this.path=e.path),Array.isArray(e.args)&&(this.args=e.args))}send(e,t){e.message.keepBcc=!0;let n=e.data.envelope||e.message.getEnvelope(),i=e.message.messageId(),o;if([].concat(n.from||[]).concat(n.to||[]).some(u=>/^-/.test(u))){let u=new Error("Can not send mail. Invalid envelope addresses.");return u.code=rm.ESENDMAIL,t(u)}let a=this.args?["-i"].concat(this.args).concat(n.to):["-i"].concat(n.from?["-f",n.from]:[]).concat(n.to),c=u=>{if(!o&&(o=!0,typeof t=="function"))return u?t(u):t(null,{envelope:n,messageId:i,response:"Messages queued for delivery"})},l;try{l=this._spawn(this.path,a)}catch(u){return this.logger.error({err:u,tnx:"spawn",messageId:i},"Error occurred while spawning sendmail. %s",u.message),c(u)}if(l){l.on("error",d=>{this.logger.error({err:d,tnx:"spawn",messageId:i},"Error occurred when sending message %s. %s",i,d.message),c(d)}),l.once("exit",d=>{if(!d)return c();let f=new Error(d===127?"Sendmail command not found, process exited with code "+d:"Sendmail exited with code "+d);f.code=rm.ESENDMAIL,this.logger.error({err:f,tnx:"stdin",messageId:i},"Error sending message %s to sendmail. %s",i,f.message),c(f)}),l.once("close",c),l.stdin.on("error",d=>{this.logger.error({err:d,tnx:"stdin",messageId:i},"Error occurred when piping message %s to sendmail. %s",i,d.message),c(d)});let u=[].concat(n.to||[]);u.length>3&&u.push("...and "+u.splice(2).length+" more"),this.logger.info({tnx:"send",messageId:i},"Sending message %s to <%s>",i,u.join(", "));let p=e.message.createReadStream();p.once("error",d=>{this.logger.error({err:d,tnx:"stdin",messageId:i},"Error occurred when generating message %s. %s",i,d.message),l.kill("SIGINT"),c(d)}),p.pipe(l.stdin)}else{let u=new Error("sendmail was not found");return u.code=rm.ESENDMAIL,c(u)}}};pb.exports=nm});var fb=_((a2,mb)=>{"use strict";var cO=wt(),lO=qe(),im=class{constructor(e){e=e||{},this.options=e,this.name="StreamTransport",this.version=cO.version,this.logger=lO.getLogger(this.options,{component:this.options.component||"stream-transport"}),this.winbreak=["win","windows","dos",`\r
|
|
55
|
+
`].includes((e.newline||"").toString().toLowerCase())}send(e,t){e.message.keepBcc=!0;let n=e.data.envelope||e.message.getEnvelope(),i=e.message.messageId(),o=[].concat(n.to||[]);o.length>3&&o.push("...and "+o.splice(2).length+" more"),this.logger.info({tnx:"send",messageId:i},"Sending message %s to <%s> using %s line breaks",i,o.join(", "),this.winbreak?"<CR><LF>":"<LF>"),setImmediate(()=>{let s;try{s=e.message.createReadStream()}catch(l){return this.logger.error({err:l,tnx:"send",messageId:i},"Creating send stream failed for %s. %s",i,l.message),t(l)}if(!this.options.buffer)return s.once("error",l=>{this.logger.error({err:l,tnx:"send",messageId:i},"Failed creating message for %s. %s",i,l.message)}),t(null,{envelope:n,messageId:i,message:s});let a=[],c=0;s.on("readable",()=>{let l;for(;(l=s.read())!==null;)a.push(l),c+=l.length}),s.once("error",l=>(this.logger.error({err:l,tnx:"send",messageId:i},"Failed creating message for %s. %s",i,l.message),t(l))),s.on("end",()=>t(null,{envelope:n,messageId:i,message:Buffer.concat(a,c)}))})}};mb.exports=im});var gb=_((c2,hb)=>{"use strict";var uO=wt(),pO=qe(),om=class{constructor(e){e=e||{},this.options=e,this.name="JSONTransport",this.version=uO.version,this.logger=pO.getLogger(this.options,{component:this.options.component||"json-transport"})}send(e,t){e.message.keepBcc=!0;let n=e.data.envelope||e.message.getEnvelope(),i=e.message.messageId(),o=[].concat(n.to||[]);o.length>3&&o.push("...and "+o.splice(2).length+" more"),this.logger.info({tnx:"send",messageId:i},"Composing JSON structure of %s to <%s>",i,o.join(", ")),setImmediate(()=>{e.normalize((s,a)=>s?(this.logger.error({err:s,tnx:"send",messageId:i},"Failed building JSON structure for %s. %s",i,s.message),t(s)):(delete a.envelope,delete a.normalizedHeaders,t(null,{envelope:n,messageId:i,message:this.options.skipEncoding?a:JSON.stringify(a)})))})}};hb.exports=om});var yb=_((l2,xb)=>{"use strict";var dO=N("events"),mO=wt(),vb=qe(),fO=Id(),hO=da(),sm=class extends dO{constructor(e){super(),e=e||{},this.options=e,this.ses=this.options.SES,this.name="SESTransport",this.version=mO.version,this.logger=vb.getLogger(this.options,{component:this.options.component||"ses-transport"})}getRegion(e){return this.ses.sesClient.config&&typeof this.ses.sesClient.config.region=="function"?this.ses.sesClient.config.region().then(t=>e(null,t)).catch(t=>e(t)):e(null,!1)}send(e,t){let n=e.message._headers.find(c=>/^from$/i.test(c.key));if(n){let c=new hO("text/plain");n=c._convertAddresses(c._parseAddresses(n.value))}let i=e.data.envelope||e.message.getEnvelope(),o=e.message.messageId(),s=[].concat(i.to||[]);s.length>3&&s.push("...and "+s.splice(2).length+" more"),this.logger.info({tnx:"send",messageId:o},"Sending message %s to <%s>",o,s.join(", "));let a=c=>{e.data._dkim||(e.data._dkim={}),e.data._dkim.skipFields&&typeof e.data._dkim.skipFields=="string"?e.data._dkim.skipFields+=":date:message-id":e.data._dkim.skipFields="date:message-id";let l=e.message.createReadStream(),u=l.pipe(new fO),p=[],d=0;u.on("readable",()=>{let f;for(;(f=u.read())!==null;)p.push(f),d+=f.length}),l.once("error",f=>u.emit("error",f)),u.once("error",f=>c(f)),u.once("end",()=>c(null,Buffer.concat(p,d)))};setImmediate(()=>a((c,l)=>{if(c)return this.logger.error({err:c,tnx:"send",messageId:o},"Failed creating message for %s. %s",o,c.message),t(c);let u=Object.assign({Content:{Raw:{Data:l}},FromEmailAddress:n||i.from,Destination:{ToAddresses:i.to}},e.data.ses||{});this.getRegion((p,d)=>{(p||!d)&&(d="us-east-1");let f=new this.ses.SendEmailCommand(u);this.ses.sesClient.send(f).then(h=>{d==="us-east-1"&&(d="email"),t(null,{envelope:{from:i.from,to:i.to},messageId:"<"+h.MessageId+(/@/.test(h.MessageId)?"":"@"+d+".amazonses.com")+">",response:h.MessageId,raw:l})}).catch(h=>{this.logger.error({err:h,tnx:"send"},"Send error for %s: %s",o,h.message),t(h)})})}))}verify(e){let t;e||(t=new Promise((o,s)=>{e=vb.callbackPromise(o,s)}));let n=o=>o&&!["InvalidParameterValue","MessageRejected"].includes(o.code||o.Code||o.name)?e(o):e(null,!0),i={Content:{Raw:{Data:Buffer.from(`From: <invalid@invalid>\r
|
|
56
|
+
To: <invalid@invalid>\r
|
|
57
|
+
Subject: Invalid\r
|
|
58
|
+
\r
|
|
59
|
+
Invalid`)}},FromEmailAddress:"invalid@invalid",Destination:{ToAddresses:["invalid@invalid"]}};return this.getRegion((o,s)=>{(o||!s)&&(s="us-east-1");let a=new this.ses.SendEmailCommand(i);this.ses.sesClient.send(a).then(l=>n(null,l)).catch(l=>n(l))}),t}};xb.exports=sm});var kb=_((u2,ga)=>{"use strict";var gO=L_(),wb=qe(),vO=ob(),xO=ub(),yO=db(),_O=fb(),bO=gb(),wO=yb(),kO=kt(),SO=so(),_b=wt(),EO=(process.env.ETHEREAL_API||"https://api.nodemailer.com").replace(/\/+$/,""),$O=(process.env.ETHEREAL_WEB||"https://ethereal.email").replace(/\/+$/,""),bb=(process.env.ETHEREAL_API_KEY||"").replace(/\s*/g,"")||null,TO=["true","yes","y","1"].includes((process.env.ETHEREAL_CACHE||"yes").toString().trim().toLowerCase()),fo=!1;ga.exports.createTransport=function(r,e){let t;if(typeof r=="object"&&typeof r.send!="function"||typeof r=="string"&&/^(smtps?|direct):/i.test(r)){let n=typeof r=="string"?r:r.url;if(n?t=wb.parseConnectionUrl(n):t=r,t.pool)r=new vO(t);else if(t.sendmail)r=new yO(t);else if(t.streamTransport)r=new _O(t);else if(t.jsonTransport)r=new bO(t);else if(t.SES){if(t.SES.ses&&t.SES.aws){let i=new Error("Using legacy SES configuration, expecting @aws-sdk/client-sesv2, see https://nodemailer.com/transports/ses/");throw i.code=kO.ECONFIG,i}r=new wO(t)}else r=new xO(t)}return new gO(r,t,e)};ga.exports.createTestAccount=function(r,e){let t;if(!e&&typeof r=="function"&&(e=r,r=!1),e||(t=new Promise((c,l)=>{e=wb.callbackPromise(c,l)})),TO&&fo)return setImmediate(()=>e(null,fo)),t;r=r||EO;let n=[],i=0,o={},s={requestor:_b.name,version:_b.version};bb&&(o.Authorization="Bearer "+bb);let a=SO(r+"/user",{contentType:"application/json",method:"POST",headers:o,body:Buffer.from(JSON.stringify(s))});return a.on("readable",()=>{let c;for(;(c=a.read())!==null;)n.push(c),i+=c.length}),a.once("error",c=>e(c)),a.once("end",()=>{let c=Buffer.concat(n,i),l;try{l=JSON.parse(c.toString())}catch(u){return e(u)}if(l.status!=="success"||l.error)return e(new Error(l.error||"Request failed"));delete l.status,fo=l,e(null,fo)}),t};ga.exports.getTestMessageUrl=function(r){if(!r||!r.response)return!1;let e=new Map;return r.response.replace(/\[([^\]]+)\]$/,(t,n)=>{n.replace(/\b([A-Z0-9]+)=([^\s]+)/g,(i,o,s)=>{e.set(o,s)})}),e.has("STATUS")&&e.has("MSGID")?(fo.web||$O)+"/message/"+e.get("MSGID"):!1}});var g={};wa(g,{BRAND:()=>aw,DIRTY:()=>Sr,EMPTY_PATH:()=>Db,INVALID:()=>M,NEVER:()=>Hw,OK:()=>Ce,ParseStatus:()=>Ee,Schema:()=>F,ZodAny:()=>nr,ZodArray:()=>Bt,ZodBigInt:()=>$r,ZodBoolean:()=>Tr,ZodBranded:()=>Yn,ZodCatch:()=>Lr,ZodDate:()=>zr,ZodDefault:()=>Mr,ZodDiscriminatedUnion:()=>xo,ZodEffects:()=>nt,ZodEnum:()=>Nr,ZodError:()=>Ze,ZodFirstPartyTypeKind:()=>S,ZodFunction:()=>_o,ZodIntersection:()=>Ir,ZodIssueCode:()=>k,ZodLazy:()=>Ar,ZodLiteral:()=>Or,ZodMap:()=>xn,ZodNaN:()=>_n,ZodNativeEnum:()=>jr,ZodNever:()=>mt,ZodNull:()=>Rr,ZodNullable:()=>Tt,ZodNumber:()=>Er,ZodObject:()=>Fe,ZodOptional:()=>Ue,ZodParsedType:()=>T,ZodPipeline:()=>ei,ZodPromise:()=>ir,ZodReadonly:()=>Dr,ZodRecord:()=>yo,ZodSchema:()=>F,ZodSet:()=>yn,ZodString:()=>rr,ZodSymbol:()=>gn,ZodTransformer:()=>nt,ZodTuple:()=>$t,ZodType:()=>F,ZodUndefined:()=>Pr,ZodUnion:()=>Cr,ZodUnknown:()=>Ht,ZodVoid:()=>vn,addIssueToContext:()=>$,any:()=>gw,array:()=>_w,bigint:()=>pw,boolean:()=>Sm,coerce:()=>Fw,custom:()=>bm,date:()=>dw,datetimeRegex:()=>ym,defaultErrorMap:()=>Ut,discriminatedUnion:()=>kw,effect:()=>Nw,enum:()=>Iw,function:()=>Pw,getErrorMap:()=>mn,getParsedType:()=>Et,instanceof:()=>lw,intersection:()=>Sw,isAborted:()=>go,isAsync:()=>fn,isDirty:()=>vo,isValid:()=>tr,late:()=>cw,lazy:()=>Rw,literal:()=>Cw,makeIssue:()=>Qn,map:()=>Tw,nan:()=>uw,nativeEnum:()=>Aw,never:()=>xw,null:()=>hw,nullable:()=>Mw,number:()=>km,object:()=>Ta,objectUtil:()=>Sa,oboolean:()=>Uw,onumber:()=>Zw,optional:()=>jw,ostring:()=>qw,pipeline:()=>Dw,preprocess:()=>Lw,promise:()=>Ow,quotelessJson:()=>jb,record:()=>$w,set:()=>zw,setErrorMap:()=>Lb,strictObject:()=>bw,string:()=>wm,symbol:()=>mw,transformer:()=>Nw,tuple:()=>Ew,undefined:()=>fw,union:()=>ww,unknown:()=>vw,util:()=>W,void:()=>yw});var W;(function(r){r.assertEqual=i=>{};function e(i){}r.assertIs=e;function t(i){throw new Error}r.assertNever=t,r.arrayToEnum=i=>{let o={};for(let s of i)o[s]=s;return o},r.getValidEnumValues=i=>{let o=r.objectKeys(i).filter(a=>typeof i[i[a]]!="number"),s={};for(let a of o)s[a]=i[a];return r.objectValues(s)},r.objectValues=i=>r.objectKeys(i).map(function(o){return i[o]}),r.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let o=[];for(let s in i)Object.prototype.hasOwnProperty.call(i,s)&&o.push(s);return o},r.find=(i,o)=>{for(let s of i)if(o(s))return s},r.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function n(i,o=" | "){return i.map(s=>typeof s=="string"?`'${s}'`:s).join(o)}r.joinValues=n,r.jsonStringifyReplacer=(i,o)=>typeof o=="bigint"?o.toString():o})(W||(W={}));var Sa;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(Sa||(Sa={}));var T=W.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Et=r=>{switch(typeof r){case"undefined":return T.undefined;case"string":return T.string;case"number":return Number.isNaN(r)?T.nan:T.number;case"boolean":return T.boolean;case"function":return T.function;case"bigint":return T.bigint;case"symbol":return T.symbol;case"object":return Array.isArray(r)?T.array:r===null?T.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?T.promise:typeof Map<"u"&&r instanceof Map?T.map:typeof Set<"u"&&r instanceof Set?T.set:typeof Date<"u"&&r instanceof Date?T.date:T.object;default:return T.unknown}};var k=W.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),jb=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:"),Ze=class r extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(o){return o.message},n={_errors:[]},i=o=>{for(let s of o.issues)if(s.code==="invalid_union")s.unionErrors.map(i);else if(s.code==="invalid_return_type")i(s.returnTypeError);else if(s.code==="invalid_arguments")i(s.argumentsError);else if(s.path.length===0)n._errors.push(t(s));else{let a=n,c=0;for(;c<s.path.length;){let l=s.path[c];c===s.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(t(s))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return i(this),n}static assert(e){if(!(e instanceof r))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,W.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},n=[];for(let i of this.issues)if(i.path.length>0){let o=i.path[0];t[o]=t[o]||[],t[o].push(e(i))}else n.push(e(i));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};Ze.create=r=>new Ze(r);var Mb=(r,e)=>{let t;switch(r.code){case k.invalid_type:r.received===T.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case k.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,W.jsonStringifyReplacer)}`;break;case k.unrecognized_keys:t=`Unrecognized key(s) in object: ${W.joinValues(r.keys,", ")}`;break;case k.invalid_union:t="Invalid input";break;case k.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${W.joinValues(r.options)}`;break;case k.invalid_enum_value:t=`Invalid enum value. Expected ${W.joinValues(r.options)}, received '${r.received}'`;break;case k.invalid_arguments:t="Invalid function arguments";break;case k.invalid_return_type:t="Invalid function return type";break;case k.invalid_date:t="Invalid date";break;case k.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:W.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case k.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="bigint"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case k.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case k.custom:t="Invalid input";break;case k.invalid_intersection_types:t="Intersection results could not be merged";break;case k.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case k.not_finite:t="Number must be finite";break;default:t=e.defaultError,W.assertNever(r)}return{message:t}},Ut=Mb;var fm=Ut;function Lb(r){fm=r}function mn(){return fm}var Qn=r=>{let{data:e,path:t,errorMaps:n,issueData:i}=r,o=[...t,...i.path||[]],s={...i,path:o};if(i.message!==void 0)return{...i,path:o,message:i.message};let a="",c=n.filter(l=>!!l).slice().reverse();for(let l of c)a=l(s,{data:e,defaultError:a}).message;return{...i,path:o,message:a}},Db=[];function $(r,e){let t=mn(),n=Qn({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===Ut?void 0:Ut].filter(i=>!!i)});r.common.issues.push(n)}var Ee=class r{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let n=[];for(let i of t){if(i.status==="aborted")return M;i.status==="dirty"&&e.dirty(),n.push(i.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){let n=[];for(let i of t){let o=await i.key,s=await i.value;n.push({key:o,value:s})}return r.mergeObjectSync(e,n)}static mergeObjectSync(e,t){let n={};for(let i of t){let{key:o,value:s}=i;if(o.status==="aborted"||s.status==="aborted")return M;o.status==="dirty"&&e.dirty(),s.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof s.value<"u"||i.alwaysSet)&&(n[o.value]=s.value)}return{status:e.value,value:n}}},M=Object.freeze({status:"aborted"}),Sr=r=>({status:"dirty",value:r}),Ce=r=>({status:"valid",value:r}),go=r=>r.status==="aborted",vo=r=>r.status==="dirty",tr=r=>r.status==="valid",fn=r=>typeof Promise<"u"&&r instanceof Promise;var R;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message})(R||(R={}));var rt=class{constructor(e,t,n,i){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},hm=(r,e)=>{if(tr(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new Ze(r.common.issues);return this._error=t,this._error}}};function Z(r){if(!r)return{};let{errorMap:e,invalid_type_error:t,required_error:n,description:i}=r;if(e&&(t||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:i}:{errorMap:(s,a)=>{let{message:c}=r;return s.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:s.code!=="invalid_type"?{message:a.defaultError}:{message:c??t??a.defaultError}},description:i}}var F=class{get description(){return this._def.description}_getType(e){return Et(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Et(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ee,ctx:{common:e.parent.common,data:e.data,parsedType:Et(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(fn(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Et(e)},i=this._parseSync({data:e,path:n.path,parent:n});return hm(n,i)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Et(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:t});return tr(n)?{value:n.value}:{issues:t.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(n=>tr(n)?{value:n.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Et(e)},i=this._parse({data:e,path:n.path,parent:n}),o=await(fn(i)?i:Promise.resolve(i));return hm(n,o)}refine(e,t){let n=i=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(i):t;return this._refinement((i,o)=>{let s=e(i),a=()=>o.addIssue({code:k.custom,...n(i)});return typeof Promise<"u"&&s instanceof Promise?s.then(c=>c?!0:(a(),!1)):s?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,i)=>e(n)?!0:(i.addIssue(typeof t=="function"?t(n,i):t),!1))}_refinement(e){return new nt({schema:this,typeName:S.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return Ue.create(this,this._def)}nullable(){return Tt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Bt.create(this)}promise(){return ir.create(this,this._def)}or(e){return Cr.create([this,e],this._def)}and(e){return Ir.create(this,e,this._def)}transform(e){return new nt({...Z(this._def),schema:this,typeName:S.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new Mr({...Z(this._def),innerType:this,defaultValue:t,typeName:S.ZodDefault})}brand(){return new Yn({typeName:S.ZodBranded,type:this,...Z(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new Lr({...Z(this._def),innerType:this,catchValue:t,typeName:S.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return ei.create(this,e)}readonly(){return Dr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},qb=/^c[^\s-]{8,}$/i,Zb=/^[0-9a-z]+$/,Ub=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Fb=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Hb=/^[a-z0-9_-]{21}$/i,Bb=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Vb=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Wb=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Gb="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Ea,Kb=/^(?:(?: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])$/,Jb=/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,Xb=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Qb=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Yb=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ew=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,vm="((\\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])))",tw=new RegExp(`^${vm}$`);function xm(r){let e="[0-5]\\d";r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`);let t=r.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function rw(r){return new RegExp(`^${xm(r)}$`)}function ym(r){let e=`${vm}T${xm(r)}`,t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function nw(r,e){return!!((e==="v4"||!e)&&Kb.test(r)||(e==="v6"||!e)&&Xb.test(r))}function iw(r,e){if(!Bb.test(r))return!1;try{let[t]=r.split(".");if(!t)return!1;let n=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),i=JSON.parse(atob(n));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||e&&i.alg!==e)}catch{return!1}}function ow(r,e){return!!((e==="v4"||!e)&&Jb.test(r)||(e==="v6"||!e)&&Qb.test(r))}var rr=class r extends F{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==T.string){let o=this._getOrReturnCtx(e);return $(o,{code:k.invalid_type,expected:T.string,received:o.parsedType}),M}let n=new Ee,i;for(let o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(i=this._getOrReturnCtx(e,i),$(i,{code:k.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="max")e.data.length>o.value&&(i=this._getOrReturnCtx(e,i),$(i,{code:k.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){let s=e.data.length>o.value,a=e.data.length<o.value;(s||a)&&(i=this._getOrReturnCtx(e,i),s?$(i,{code:k.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&$(i,{code:k.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")Wb.test(e.data)||(i=this._getOrReturnCtx(e,i),$(i,{validation:"email",code:k.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")Ea||(Ea=new RegExp(Gb,"u")),Ea.test(e.data)||(i=this._getOrReturnCtx(e,i),$(i,{validation:"emoji",code:k.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")Fb.test(e.data)||(i=this._getOrReturnCtx(e,i),$(i,{validation:"uuid",code:k.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")Hb.test(e.data)||(i=this._getOrReturnCtx(e,i),$(i,{validation:"nanoid",code:k.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")qb.test(e.data)||(i=this._getOrReturnCtx(e,i),$(i,{validation:"cuid",code:k.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")Zb.test(e.data)||(i=this._getOrReturnCtx(e,i),$(i,{validation:"cuid2",code:k.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")Ub.test(e.data)||(i=this._getOrReturnCtx(e,i),$(i,{validation:"ulid",code:k.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{i=this._getOrReturnCtx(e,i),$(i,{validation:"url",code:k.invalid_string,message:o.message}),n.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(e.data)||(i=this._getOrReturnCtx(e,i),$(i,{validation:"regex",code:k.invalid_string,message:o.message}),n.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(i=this._getOrReturnCtx(e,i),$(i,{code:k.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),n.dirty()):o.kind==="toLowerCase"?e.data=e.data.toLowerCase():o.kind==="toUpperCase"?e.data=e.data.toUpperCase():o.kind==="startsWith"?e.data.startsWith(o.value)||(i=this._getOrReturnCtx(e,i),$(i,{code:k.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(i=this._getOrReturnCtx(e,i),$(i,{code:k.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?ym(o).test(e.data)||(i=this._getOrReturnCtx(e,i),$(i,{code:k.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?tw.test(e.data)||(i=this._getOrReturnCtx(e,i),$(i,{code:k.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?rw(o).test(e.data)||(i=this._getOrReturnCtx(e,i),$(i,{code:k.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?Vb.test(e.data)||(i=this._getOrReturnCtx(e,i),$(i,{validation:"duration",code:k.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?nw(e.data,o.version)||(i=this._getOrReturnCtx(e,i),$(i,{validation:"ip",code:k.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?iw(e.data,o.alg)||(i=this._getOrReturnCtx(e,i),$(i,{validation:"jwt",code:k.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?ow(e.data,o.version)||(i=this._getOrReturnCtx(e,i),$(i,{validation:"cidr",code:k.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?Yb.test(e.data)||(i=this._getOrReturnCtx(e,i),$(i,{validation:"base64",code:k.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?ew.test(e.data)||(i=this._getOrReturnCtx(e,i),$(i,{validation:"base64url",code:k.invalid_string,message:o.message}),n.dirty()):W.assertNever(o);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement(i=>e.test(i),{validation:t,code:k.invalid_string,...R.errToObj(n)})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...R.errToObj(e)})}url(e){return this._addCheck({kind:"url",...R.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...R.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...R.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...R.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...R.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...R.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...R.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...R.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...R.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...R.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...R.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...R.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...R.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...R.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...R.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...R.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...R.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...R.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...R.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...R.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...R.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...R.errToObj(t)})}nonempty(e){return this.min(1,R.errToObj(e))}trim(){return new r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};rr.create=r=>new rr({checks:[],typeName:S.ZodString,coerce:r?.coerce??!1,...Z(r)});function sw(r,e){let t=(r.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,i=t>n?t:n,o=Number.parseInt(r.toFixed(i).replace(".","")),s=Number.parseInt(e.toFixed(i).replace(".",""));return o%s/10**i}var Er=class r extends F{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==T.number){let o=this._getOrReturnCtx(e);return $(o,{code:k.invalid_type,expected:T.number,received:o.parsedType}),M}let n,i=new Ee;for(let o of this._def.checks)o.kind==="int"?W.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),$(n,{code:k.invalid_type,expected:"integer",received:"float",message:o.message}),i.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),$(n,{code:k.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),$(n,{code:k.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?sw(e.data,o.value)!==0&&(n=this._getOrReturnCtx(e,n),$(n,{code:k.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),$(n,{code:k.not_finite,message:o.message}),i.dirty()):W.assertNever(o);return{status:i.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,R.toString(t))}gt(e,t){return this.setLimit("min",e,!1,R.toString(t))}lte(e,t){return this.setLimit("max",e,!0,R.toString(t))}lt(e,t){return this.setLimit("max",e,!1,R.toString(t))}setLimit(e,t,n,i){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:R.toString(i)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:R.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:R.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:R.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:R.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:R.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:R.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:R.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:R.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:R.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&W.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(t===null||n.value>t)&&(t=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}};Er.create=r=>new Er({checks:[],typeName:S.ZodNumber,coerce:r?.coerce||!1,...Z(r)});var $r=class r extends F{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==T.bigint)return this._getInvalidInput(e);let n,i=new Ee;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),$(n,{code:k.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),$(n,{code:k.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),$(n,{code:k.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):W.assertNever(o);return{status:i.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return $(t,{code:k.invalid_type,expected:T.bigint,received:t.parsedType}),M}gte(e,t){return this.setLimit("min",e,!0,R.toString(t))}gt(e,t){return this.setLimit("min",e,!1,R.toString(t))}lte(e,t){return this.setLimit("max",e,!0,R.toString(t))}lt(e,t){return this.setLimit("max",e,!1,R.toString(t))}setLimit(e,t,n,i){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:R.toString(i)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:R.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:R.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:R.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:R.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:R.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};$r.create=r=>new $r({checks:[],typeName:S.ZodBigInt,coerce:r?.coerce??!1,...Z(r)});var Tr=class extends F{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==T.boolean){let n=this._getOrReturnCtx(e);return $(n,{code:k.invalid_type,expected:T.boolean,received:n.parsedType}),M}return Ce(e.data)}};Tr.create=r=>new Tr({typeName:S.ZodBoolean,coerce:r?.coerce||!1,...Z(r)});var zr=class r extends F{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==T.date){let o=this._getOrReturnCtx(e);return $(o,{code:k.invalid_type,expected:T.date,received:o.parsedType}),M}if(Number.isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return $(o,{code:k.invalid_date}),M}let n=new Ee,i;for(let o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(i=this._getOrReturnCtx(e,i),$(i,{code:k.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),n.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(i=this._getOrReturnCtx(e,i),$(i,{code:k.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):W.assertNever(o);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:R.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:R.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};zr.create=r=>new zr({checks:[],coerce:r?.coerce||!1,typeName:S.ZodDate,...Z(r)});var gn=class extends F{_parse(e){if(this._getType(e)!==T.symbol){let n=this._getOrReturnCtx(e);return $(n,{code:k.invalid_type,expected:T.symbol,received:n.parsedType}),M}return Ce(e.data)}};gn.create=r=>new gn({typeName:S.ZodSymbol,...Z(r)});var Pr=class extends F{_parse(e){if(this._getType(e)!==T.undefined){let n=this._getOrReturnCtx(e);return $(n,{code:k.invalid_type,expected:T.undefined,received:n.parsedType}),M}return Ce(e.data)}};Pr.create=r=>new Pr({typeName:S.ZodUndefined,...Z(r)});var Rr=class extends F{_parse(e){if(this._getType(e)!==T.null){let n=this._getOrReturnCtx(e);return $(n,{code:k.invalid_type,expected:T.null,received:n.parsedType}),M}return Ce(e.data)}};Rr.create=r=>new Rr({typeName:S.ZodNull,...Z(r)});var nr=class extends F{constructor(){super(...arguments),this._any=!0}_parse(e){return Ce(e.data)}};nr.create=r=>new nr({typeName:S.ZodAny,...Z(r)});var Ht=class extends F{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ce(e.data)}};Ht.create=r=>new Ht({typeName:S.ZodUnknown,...Z(r)});var mt=class extends F{_parse(e){let t=this._getOrReturnCtx(e);return $(t,{code:k.invalid_type,expected:T.never,received:t.parsedType}),M}};mt.create=r=>new mt({typeName:S.ZodNever,...Z(r)});var vn=class extends F{_parse(e){if(this._getType(e)!==T.undefined){let n=this._getOrReturnCtx(e);return $(n,{code:k.invalid_type,expected:T.void,received:n.parsedType}),M}return Ce(e.data)}};vn.create=r=>new vn({typeName:S.ZodVoid,...Z(r)});var Bt=class r extends F{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),i=this._def;if(t.parsedType!==T.array)return $(t,{code:k.invalid_type,expected:T.array,received:t.parsedType}),M;if(i.exactLength!==null){let s=t.data.length>i.exactLength.value,a=t.data.length<i.exactLength.value;(s||a)&&($(t,{code:s?k.too_big:k.too_small,minimum:a?i.exactLength.value:void 0,maximum:s?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),n.dirty())}if(i.minLength!==null&&t.data.length<i.minLength.value&&($(t,{code:k.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),n.dirty()),i.maxLength!==null&&t.data.length>i.maxLength.value&&($(t,{code:k.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((s,a)=>i.type._parseAsync(new rt(t,s,t.path,a)))).then(s=>Ee.mergeArray(n,s));let o=[...t.data].map((s,a)=>i.type._parseSync(new rt(t,s,t.path,a)));return Ee.mergeArray(n,o)}get element(){return this._def.type}min(e,t){return new r({...this._def,minLength:{value:e,message:R.toString(t)}})}max(e,t){return new r({...this._def,maxLength:{value:e,message:R.toString(t)}})}length(e,t){return new r({...this._def,exactLength:{value:e,message:R.toString(t)}})}nonempty(e){return this.min(1,e)}};Bt.create=(r,e)=>new Bt({type:r,minLength:null,maxLength:null,exactLength:null,typeName:S.ZodArray,...Z(e)});function hn(r){if(r instanceof Fe){let e={};for(let t in r.shape){let n=r.shape[t];e[t]=Ue.create(hn(n))}return new Fe({...r._def,shape:()=>e})}else return r instanceof Bt?new Bt({...r._def,type:hn(r.element)}):r instanceof Ue?Ue.create(hn(r.unwrap())):r instanceof Tt?Tt.create(hn(r.unwrap())):r instanceof $t?$t.create(r.items.map(e=>hn(e))):r}var Fe=class r extends F{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=W.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==T.object){let l=this._getOrReturnCtx(e);return $(l,{code:k.invalid_type,expected:T.object,received:l.parsedType}),M}let{status:n,ctx:i}=this._processInputParams(e),{shape:o,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof mt&&this._def.unknownKeys==="strip"))for(let l in i.data)s.includes(l)||a.push(l);let c=[];for(let l of s){let u=o[l],p=i.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new rt(i,p,i.path,l)),alwaysSet:l in i.data})}if(this._def.catchall instanceof mt){let l=this._def.unknownKeys;if(l==="passthrough")for(let u of a)c.push({key:{status:"valid",value:u},value:{status:"valid",value:i.data[u]}});else if(l==="strict")a.length>0&&($(i,{code:k.unrecognized_keys,keys:a}),n.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let u of a){let p=i.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new rt(i,p,i.path,u)),alwaysSet:u in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let l=[];for(let u of c){let p=await u.key,d=await u.value;l.push({key:p,value:d,alwaysSet:u.alwaysSet})}return l}).then(l=>Ee.mergeObjectSync(n,l)):Ee.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return R.errToObj,new r({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{let i=this._def.errorMap?.(t,n).message??n.defaultError;return t.code==="unrecognized_keys"?{message:R.errToObj(e).message??i}:{message:i}}}:{}})}strip(){return new r({...this._def,unknownKeys:"strip"})}passthrough(){return new r({...this._def,unknownKeys:"passthrough"})}extend(e){return new r({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new r({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:S.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new r({...this._def,catchall:e})}pick(e){let t={};for(let n of W.objectKeys(e))e[n]&&this.shape[n]&&(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}omit(e){let t={};for(let n of W.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}deepPartial(){return hn(this)}partial(e){let t={};for(let n of W.objectKeys(this.shape)){let i=this.shape[n];e&&!e[n]?t[n]=i:t[n]=i.optional()}return new r({...this._def,shape:()=>t})}required(e){let t={};for(let n of W.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof Ue;)o=o._def.innerType;t[n]=o}return new r({...this._def,shape:()=>t})}keyof(){return _m(W.objectKeys(this.shape))}};Fe.create=(r,e)=>new Fe({shape:()=>r,unknownKeys:"strip",catchall:mt.create(),typeName:S.ZodObject,...Z(e)});Fe.strictCreate=(r,e)=>new Fe({shape:()=>r,unknownKeys:"strict",catchall:mt.create(),typeName:S.ZodObject,...Z(e)});Fe.lazycreate=(r,e)=>new Fe({shape:r,unknownKeys:"strip",catchall:mt.create(),typeName:S.ZodObject,...Z(e)});var Cr=class extends F{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function i(o){for(let a of o)if(a.result.status==="valid")return a.result;for(let a of o)if(a.result.status==="dirty")return t.common.issues.push(...a.ctx.common.issues),a.result;let s=o.map(a=>new Ze(a.ctx.common.issues));return $(t,{code:k.invalid_union,unionErrors:s}),M}if(t.common.async)return Promise.all(n.map(async o=>{let s={...t,common:{...t.common,issues:[]},parent:null};return{result:await o._parseAsync({data:t.data,path:t.path,parent:s}),ctx:s}})).then(i);{let o,s=[];for(let c of n){let l={...t,common:{...t.common,issues:[]},parent:null},u=c._parseSync({data:t.data,path:t.path,parent:l});if(u.status==="valid")return u;u.status==="dirty"&&!o&&(o={result:u,ctx:l}),l.common.issues.length&&s.push(l.common.issues)}if(o)return t.common.issues.push(...o.ctx.common.issues),o.result;let a=s.map(c=>new Ze(c));return $(t,{code:k.invalid_union,unionErrors:a}),M}}get options(){return this._def.options}};Cr.create=(r,e)=>new Cr({options:r,typeName:S.ZodUnion,...Z(e)});var Ft=r=>r instanceof Ar?Ft(r.schema):r instanceof nt?Ft(r.innerType()):r instanceof Or?[r.value]:r instanceof Nr?r.options:r instanceof jr?W.objectValues(r.enum):r instanceof Mr?Ft(r._def.innerType):r instanceof Pr?[void 0]:r instanceof Rr?[null]:r instanceof Ue?[void 0,...Ft(r.unwrap())]:r instanceof Tt?[null,...Ft(r.unwrap())]:r instanceof Yn||r instanceof Dr?Ft(r.unwrap()):r instanceof Lr?Ft(r._def.innerType):[],xo=class r extends F{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==T.object)return $(t,{code:k.invalid_type,expected:T.object,received:t.parsedType}),M;let n=this.discriminator,i=t.data[n],o=this.optionsMap.get(i);return o?t.common.async?o._parseAsync({data:t.data,path:t.path,parent:t}):o._parseSync({data:t.data,path:t.path,parent:t}):($(t,{code:k.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),M)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){let i=new Map;for(let o of t){let s=Ft(o.shape[e]);if(!s.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of s){if(i.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);i.set(a,o)}}return new r({typeName:S.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:i,...Z(n)})}};function $a(r,e){let t=Et(r),n=Et(e);if(r===e)return{valid:!0,data:r};if(t===T.object&&n===T.object){let i=W.objectKeys(e),o=W.objectKeys(r).filter(a=>i.indexOf(a)!==-1),s={...r,...e};for(let a of o){let c=$a(r[a],e[a]);if(!c.valid)return{valid:!1};s[a]=c.data}return{valid:!0,data:s}}else if(t===T.array&&n===T.array){if(r.length!==e.length)return{valid:!1};let i=[];for(let o=0;o<r.length;o++){let s=r[o],a=e[o],c=$a(s,a);if(!c.valid)return{valid:!1};i.push(c.data)}return{valid:!0,data:i}}else return t===T.date&&n===T.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}var Ir=class extends F{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),i=(o,s)=>{if(go(o)||go(s))return M;let a=$a(o.value,s.value);return a.valid?((vo(o)||vo(s))&&t.dirty(),{status:t.value,value:a.data}):($(n,{code:k.invalid_intersection_types}),M)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([o,s])=>i(o,s)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Ir.create=(r,e,t)=>new Ir({left:r,right:e,typeName:S.ZodIntersection,...Z(t)});var $t=class r extends F{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==T.array)return $(n,{code:k.invalid_type,expected:T.array,received:n.parsedType}),M;if(n.data.length<this._def.items.length)return $(n,{code:k.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),M;!this._def.rest&&n.data.length>this._def.items.length&&($(n,{code:k.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let o=[...n.data].map((s,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new rt(n,s,n.path,a)):null}).filter(s=>!!s);return n.common.async?Promise.all(o).then(s=>Ee.mergeArray(t,s)):Ee.mergeArray(t,o)}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};$t.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new $t({items:r,typeName:S.ZodTuple,rest:null,...Z(e)})};var yo=class r extends F{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==T.object)return $(n,{code:k.invalid_type,expected:T.object,received:n.parsedType}),M;let i=[],o=this._def.keyType,s=this._def.valueType;for(let a in n.data)i.push({key:o._parse(new rt(n,a,n.path,a)),value:s._parse(new rt(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Ee.mergeObjectAsync(t,i):Ee.mergeObjectSync(t,i)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof F?new r({keyType:e,valueType:t,typeName:S.ZodRecord,...Z(n)}):new r({keyType:rr.create(),valueType:e,typeName:S.ZodRecord,...Z(t)})}},xn=class extends F{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==T.map)return $(n,{code:k.invalid_type,expected:T.map,received:n.parsedType}),M;let i=this._def.keyType,o=this._def.valueType,s=[...n.data.entries()].map(([a,c],l)=>({key:i._parse(new rt(n,a,n.path,[l,"key"])),value:o._parse(new rt(n,c,n.path,[l,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of s){let l=await c.key,u=await c.value;if(l.status==="aborted"||u.status==="aborted")return M;(l.status==="dirty"||u.status==="dirty")&&t.dirty(),a.set(l.value,u.value)}return{status:t.value,value:a}})}else{let a=new Map;for(let c of s){let l=c.key,u=c.value;if(l.status==="aborted"||u.status==="aborted")return M;(l.status==="dirty"||u.status==="dirty")&&t.dirty(),a.set(l.value,u.value)}return{status:t.value,value:a}}}};xn.create=(r,e,t)=>new xn({valueType:e,keyType:r,typeName:S.ZodMap,...Z(t)});var yn=class r extends F{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==T.set)return $(n,{code:k.invalid_type,expected:T.set,received:n.parsedType}),M;let i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&($(n,{code:k.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),t.dirty()),i.maxSize!==null&&n.data.size>i.maxSize.value&&($(n,{code:k.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),t.dirty());let o=this._def.valueType;function s(c){let l=new Set;for(let u of c){if(u.status==="aborted")return M;u.status==="dirty"&&t.dirty(),l.add(u.value)}return{status:t.value,value:l}}let a=[...n.data.values()].map((c,l)=>o._parse(new rt(n,c,n.path,l)));return n.common.async?Promise.all(a).then(c=>s(c)):s(a)}min(e,t){return new r({...this._def,minSize:{value:e,message:R.toString(t)}})}max(e,t){return new r({...this._def,maxSize:{value:e,message:R.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};yn.create=(r,e)=>new yn({valueType:r,minSize:null,maxSize:null,typeName:S.ZodSet,...Z(e)});var _o=class r extends F{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==T.function)return $(t,{code:k.invalid_type,expected:T.function,received:t.parsedType}),M;function n(a,c){return Qn({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,mn(),Ut].filter(l=>!!l),issueData:{code:k.invalid_arguments,argumentsError:c}})}function i(a,c){return Qn({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,mn(),Ut].filter(l=>!!l),issueData:{code:k.invalid_return_type,returnTypeError:c}})}let o={errorMap:t.common.contextualErrorMap},s=t.data;if(this._def.returns instanceof ir){let a=this;return Ce(async function(...c){let l=new Ze([]),u=await a._def.args.parseAsync(c,o).catch(f=>{throw l.addIssue(n(c,f)),l}),p=await Reflect.apply(s,this,u);return await a._def.returns._def.type.parseAsync(p,o).catch(f=>{throw l.addIssue(i(p,f)),l})})}else{let a=this;return Ce(function(...c){let l=a._def.args.safeParse(c,o);if(!l.success)throw new Ze([n(c,l.error)]);let u=Reflect.apply(s,this,l.data),p=a._def.returns.safeParse(u,o);if(!p.success)throw new Ze([i(u,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:$t.create(e).rest(Ht.create())})}returns(e){return new r({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new r({args:e||$t.create([]).rest(Ht.create()),returns:t||Ht.create(),typeName:S.ZodFunction,...Z(n)})}},Ar=class extends F{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};Ar.create=(r,e)=>new Ar({getter:r,typeName:S.ZodLazy,...Z(e)});var Or=class extends F{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return $(t,{received:t.data,code:k.invalid_literal,expected:this._def.value}),M}return{status:"valid",value:e.data}}get value(){return this._def.value}};Or.create=(r,e)=>new Or({value:r,typeName:S.ZodLiteral,...Z(e)});function _m(r,e){return new Nr({values:r,typeName:S.ZodEnum,...Z(e)})}var Nr=class r extends F{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),n=this._def.values;return $(t,{expected:W.joinValues(n),received:t.parsedType,code:k.invalid_type}),M}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return $(t,{received:t.data,code:k.invalid_enum_value,options:n}),M}return Ce(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return r.create(e,{...this._def,...t})}exclude(e,t=this._def){return r.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}};Nr.create=_m;var jr=class extends F{_parse(e){let t=W.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==T.string&&n.parsedType!==T.number){let i=W.objectValues(t);return $(n,{expected:W.joinValues(i),received:n.parsedType,code:k.invalid_type}),M}if(this._cache||(this._cache=new Set(W.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let i=W.objectValues(t);return $(n,{received:n.data,code:k.invalid_enum_value,options:i}),M}return Ce(e.data)}get enum(){return this._def.values}};jr.create=(r,e)=>new jr({values:r,typeName:S.ZodNativeEnum,...Z(e)});var ir=class extends F{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==T.promise&&t.common.async===!1)return $(t,{code:k.invalid_type,expected:T.promise,received:t.parsedType}),M;let n=t.parsedType===T.promise?t.data:Promise.resolve(t.data);return Ce(n.then(i=>this._def.type.parseAsync(i,{path:t.path,errorMap:t.common.contextualErrorMap})))}};ir.create=(r,e)=>new ir({type:r,typeName:S.ZodPromise,...Z(e)});var nt=class extends F{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===S.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),i=this._def.effect||null,o={addIssue:s=>{$(n,s),s.fatal?t.abort():t.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),i.type==="preprocess"){let s=i.transform(n.data,o);if(n.common.async)return Promise.resolve(s).then(async a=>{if(t.value==="aborted")return M;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?M:c.status==="dirty"?Sr(c.value):t.value==="dirty"?Sr(c.value):c});{if(t.value==="aborted")return M;let a=this._def.schema._parseSync({data:s,path:n.path,parent:n});return a.status==="aborted"?M:a.status==="dirty"?Sr(a.value):t.value==="dirty"?Sr(a.value):a}}if(i.type==="refinement"){let s=a=>{let c=i.refinement(a,o);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?M:(a.status==="dirty"&&t.dirty(),s(a.value),{status:t.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?M:(a.status==="dirty"&&t.dirty(),s(a.value).then(()=>({status:t.value,value:a.value}))))}if(i.type==="transform")if(n.common.async===!1){let s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!tr(s))return M;let a=i.transform(s.value,o);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(s=>tr(s)?Promise.resolve(i.transform(s.value,o)).then(a=>({status:t.value,value:a})):M);W.assertNever(i)}};nt.create=(r,e,t)=>new nt({schema:r,typeName:S.ZodEffects,effect:e,...Z(t)});nt.createWithPreprocess=(r,e,t)=>new nt({schema:e,effect:{type:"preprocess",transform:r},typeName:S.ZodEffects,...Z(t)});var Ue=class extends F{_parse(e){return this._getType(e)===T.undefined?Ce(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ue.create=(r,e)=>new Ue({innerType:r,typeName:S.ZodOptional,...Z(e)});var Tt=class extends F{_parse(e){return this._getType(e)===T.null?Ce(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Tt.create=(r,e)=>new Tt({innerType:r,typeName:S.ZodNullable,...Z(e)});var Mr=class extends F{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===T.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};Mr.create=(r,e)=>new Mr({innerType:r,typeName:S.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Z(e)});var Lr=class extends F{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return fn(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Ze(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Ze(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Lr.create=(r,e)=>new Lr({innerType:r,typeName:S.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Z(e)});var _n=class extends F{_parse(e){if(this._getType(e)!==T.nan){let n=this._getOrReturnCtx(e);return $(n,{code:k.invalid_type,expected:T.nan,received:n.parsedType}),M}return{status:"valid",value:e.data}}};_n.create=r=>new _n({typeName:S.ZodNaN,...Z(r)});var aw=Symbol("zod_brand"),Yn=class extends F{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},ei=class r extends F{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?M:o.status==="dirty"?(t.dirty(),Sr(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{let i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?M:i.status==="dirty"?(t.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(e,t){return new r({in:e,out:t,typeName:S.ZodPipeline})}},Dr=class extends F{_parse(e){let t=this._def.innerType._parse(e),n=i=>(tr(i)&&(i.value=Object.freeze(i.value)),i);return fn(t)?t.then(i=>n(i)):n(t)}unwrap(){return this._def.innerType}};Dr.create=(r,e)=>new Dr({innerType:r,typeName:S.ZodReadonly,...Z(e)});function gm(r,e){let t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function bm(r,e={},t){return r?nr.create().superRefine((n,i)=>{let o=r(n);if(o instanceof Promise)return o.then(s=>{if(!s){let a=gm(e,n),c=a.fatal??t??!0;i.addIssue({code:"custom",...a,fatal:c})}});if(!o){let s=gm(e,n),a=s.fatal??t??!0;i.addIssue({code:"custom",...s,fatal:a})}}):nr.create()}var cw={object:Fe.lazycreate},S;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(S||(S={}));var lw=(r,e={message:`Input not instance of ${r.name}`})=>bm(t=>t instanceof r,e),wm=rr.create,km=Er.create,uw=_n.create,pw=$r.create,Sm=Tr.create,dw=zr.create,mw=gn.create,fw=Pr.create,hw=Rr.create,gw=nr.create,vw=Ht.create,xw=mt.create,yw=vn.create,_w=Bt.create,Ta=Fe.create,bw=Fe.strictCreate,ww=Cr.create,kw=xo.create,Sw=Ir.create,Ew=$t.create,$w=yo.create,Tw=xn.create,zw=yn.create,Pw=_o.create,Rw=Ar.create,Cw=Or.create,Iw=Nr.create,Aw=jr.create,Ow=ir.create,Nw=nt.create,jw=Ue.create,Mw=Tt.create,Lw=nt.createWithPreprocess,Dw=ei.create,qw=()=>wm().optional(),Zw=()=>km().optional(),Uw=()=>Sm().optional(),Fw={string:r=>rr.create({...r,coerce:!0}),number:r=>Er.create({...r,coerce:!0}),boolean:r=>Tr.create({...r,coerce:!0}),bigint:r=>$r.create({...r,coerce:!0}),date:r=>zr.create({...r,coerce:!0})};var Hw=M;var Bw=Object.freeze({status:"aborted"});function y(r,e,t){function n(a,c){var l;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(l=a._zod).traits??(l.traits=new Set),a._zod.traits.add(r),e(a,c);for(let u in s.prototype)u in a||Object.defineProperty(a,u,{value:s.prototype[u].bind(a)});a._zod.constr=s,a._zod.def=c}let i=t?.Parent??Object;class o extends i{}Object.defineProperty(o,"name",{value:r});function s(a){var c;let l=t?.Parent?new o:this;n(l,a),(c=l._zod).deferred??(c.deferred=[]);for(let u of l._zod.deferred)u();return l}return Object.defineProperty(s,"init",{value:n}),Object.defineProperty(s,Symbol.hasInstance,{value:a=>t?.Parent&&a instanceof t.Parent?!0:a?._zod?.traits?.has(r)}),Object.defineProperty(s,"name",{value:r}),s}var Vw=Symbol("zod_brand"),Vt=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},bo={};function Ke(r){return r&&Object.assign(bo,r),bo}var G={};wa(G,{BIGINT_FORMAT_RANGES:()=>$m,Class:()=>Pa,NUMBER_FORMAT_RANGES:()=>ja,aborted:()=>Zr,allowsEval:()=>Aa,assert:()=>Xw,assertEqual:()=>Ww,assertIs:()=>Kw,assertNever:()=>Jw,assertNotEqual:()=>Gw,assignProp:()=>Ia,cached:()=>ni,captureStackTrace:()=>ko,cleanEnum:()=>u0,cleanRegex:()=>oi,clone:()=>Je,createTransparentProxy:()=>n0,defineLazy:()=>ce,esc:()=>qr,escapeRegex:()=>or,extend:()=>s0,finalizeIssue:()=>ft,floatSafeRemainder:()=>Ca,getElementAtPath:()=>Qw,getEnumValues:()=>ri,getLengthableOrigin:()=>si,getParsedType:()=>r0,getSizableOrigin:()=>Tm,isObject:()=>bn,isPlainObject:()=>wn,issue:()=>Ma,joinValues:()=>wo,jsonStringifyReplacer:()=>Ra,merge:()=>a0,normalizeParams:()=>L,nullish:()=>ii,numKeys:()=>t0,omit:()=>o0,optionalKeys:()=>Na,partial:()=>c0,pick:()=>i0,prefixIssues:()=>zt,primitiveTypes:()=>Em,promiseAllObject:()=>Yw,propertyKeyTypes:()=>Oa,randomString:()=>e0,required:()=>l0,stringifyPrimitive:()=>So,unwrapMessage:()=>ti});function Ww(r){return r}function Gw(r){return r}function Kw(r){}function Jw(r){throw new Error}function Xw(r){}function ri(r){let e=Object.values(r).filter(n=>typeof n=="number");return Object.entries(r).filter(([n,i])=>e.indexOf(+n)===-1).map(([n,i])=>i)}function wo(r,e="|"){return r.map(t=>So(t)).join(e)}function Ra(r,e){return typeof e=="bigint"?e.toString():e}function ni(r){return{get value(){{let t=r();return Object.defineProperty(this,"value",{value:t}),t}throw new Error("cached value already set")}}}function ii(r){return r==null}function oi(r){let e=r.startsWith("^")?1:0,t=r.endsWith("$")?r.length-1:r.length;return r.slice(e,t)}function Ca(r,e){let t=(r.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,i=t>n?t:n,o=Number.parseInt(r.toFixed(i).replace(".","")),s=Number.parseInt(e.toFixed(i).replace(".",""));return o%s/10**i}function ce(r,e,t){Object.defineProperty(r,e,{get(){{let i=t();return r[e]=i,i}throw new Error("cached value already set")},set(i){Object.defineProperty(r,e,{value:i})},configurable:!0})}function Ia(r,e,t){Object.defineProperty(r,e,{value:t,writable:!0,enumerable:!0,configurable:!0})}function Qw(r,e){return e?e.reduce((t,n)=>t?.[n],r):r}function Yw(r){let e=Object.keys(r),t=e.map(n=>r[n]);return Promise.all(t).then(n=>{let i={};for(let o=0;o<e.length;o++)i[e[o]]=n[o];return i})}function e0(r=10){let e="abcdefghijklmnopqrstuvwxyz",t="";for(let n=0;n<r;n++)t+=e[Math.floor(Math.random()*e.length)];return t}function qr(r){return JSON.stringify(r)}var ko=Error.captureStackTrace?Error.captureStackTrace:(...r)=>{};function bn(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}var Aa=ni(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let r=Function;return new r(""),!0}catch{return!1}});function wn(r){if(bn(r)===!1)return!1;let e=r.constructor;if(e===void 0)return!0;let t=e.prototype;return!(bn(t)===!1||Object.prototype.hasOwnProperty.call(t,"isPrototypeOf")===!1)}function t0(r){let e=0;for(let t in r)Object.prototype.hasOwnProperty.call(r,t)&&e++;return e}var r0=r=>{let e=typeof r;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(r)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(r)?"array":r===null?"null":r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?"promise":typeof Map<"u"&&r instanceof Map?"map":typeof Set<"u"&&r instanceof Set?"set":typeof Date<"u"&&r instanceof Date?"date":typeof File<"u"&&r instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},Oa=new Set(["string","number","symbol"]),Em=new Set(["string","number","bigint","boolean","symbol","undefined"]);function or(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Je(r,e,t){let n=new r._zod.constr(e??r._zod.def);return(!e||t?.parent)&&(n._zod.parent=r),n}function L(r){let e=r;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 n0(r){let e;return new Proxy({},{get(t,n,i){return e??(e=r()),Reflect.get(e,n,i)},set(t,n,i,o){return e??(e=r()),Reflect.set(e,n,i,o)},has(t,n){return e??(e=r()),Reflect.has(e,n)},deleteProperty(t,n){return e??(e=r()),Reflect.deleteProperty(e,n)},ownKeys(t){return e??(e=r()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(t,n){return e??(e=r()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(t,n,i){return e??(e=r()),Reflect.defineProperty(e,n,i)}})}function So(r){return typeof r=="bigint"?r.toString()+"n":typeof r=="string"?`"${r}"`:`${r}`}function Na(r){return Object.keys(r).filter(e=>r[e]._zod.optin==="optional"&&r[e]._zod.optout==="optional")}var ja={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]},$m={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function i0(r,e){let t={},n=r._zod.def;for(let i in e){if(!(i in n.shape))throw new Error(`Unrecognized key: "${i}"`);e[i]&&(t[i]=n.shape[i])}return Je(r,{...r._zod.def,shape:t,checks:[]})}function o0(r,e){let t={...r._zod.def.shape},n=r._zod.def;for(let i in e){if(!(i in n.shape))throw new Error(`Unrecognized key: "${i}"`);e[i]&&delete t[i]}return Je(r,{...r._zod.def,shape:t,checks:[]})}function s0(r,e){if(!wn(e))throw new Error("Invalid input to extend: expected a plain object");let t={...r._zod.def,get shape(){let n={...r._zod.def.shape,...e};return Ia(this,"shape",n),n},checks:[]};return Je(r,t)}function a0(r,e){return Je(r,{...r._zod.def,get shape(){let t={...r._zod.def.shape,...e._zod.def.shape};return Ia(this,"shape",t),t},catchall:e._zod.def.catchall,checks:[]})}function c0(r,e,t){let n=e._zod.def.shape,i={...n};if(t)for(let o in t){if(!(o in n))throw new Error(`Unrecognized key: "${o}"`);t[o]&&(i[o]=r?new r({type:"optional",innerType:n[o]}):n[o])}else for(let o in n)i[o]=r?new r({type:"optional",innerType:n[o]}):n[o];return Je(e,{...e._zod.def,shape:i,checks:[]})}function l0(r,e,t){let n=e._zod.def.shape,i={...n};if(t)for(let o in t){if(!(o in i))throw new Error(`Unrecognized key: "${o}"`);t[o]&&(i[o]=new r({type:"nonoptional",innerType:n[o]}))}else for(let o in n)i[o]=new r({type:"nonoptional",innerType:n[o]});return Je(e,{...e._zod.def,shape:i,checks:[]})}function Zr(r,e=0){for(let t=e;t<r.issues.length;t++)if(r.issues[t]?.continue!==!0)return!0;return!1}function zt(r,e){return e.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(r),t})}function ti(r){return typeof r=="string"?r:r?.message}function ft(r,e,t){let n={...r,path:r.path??[]};if(!r.message){let i=ti(r.inst?._zod.def?.error?.(r))??ti(e?.error?.(r))??ti(t.customError?.(r))??ti(t.localeError?.(r))??"Invalid input";n.message=i}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function Tm(r){return r instanceof Set?"set":r instanceof Map?"map":r instanceof File?"file":"unknown"}function si(r){return Array.isArray(r)?"array":typeof r=="string"?"string":"unknown"}function Ma(...r){let[e,t,n]=r;return typeof e=="string"?{message:e,code:"custom",input:t,inst:n}:{...e}}function u0(r){return Object.entries(r).filter(([e,t])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var Pa=class{constructor(...e){}};var zm=(r,e)=>{r.name="$ZodError",Object.defineProperty(r,"_zod",{value:r._zod,enumerable:!1}),Object.defineProperty(r,"issues",{value:e,enumerable:!1}),Object.defineProperty(r,"message",{get(){return JSON.stringify(e,Ra,2)},enumerable:!0}),Object.defineProperty(r,"toString",{value:()=>r.message,enumerable:!1})},Eo=y("$ZodError",zm),ai=y("$ZodError",zm,{Parent:Error});function La(r,e=t=>t.message){let t={},n=[];for(let i of r.issues)i.path.length>0?(t[i.path[0]]=t[i.path[0]]||[],t[i.path[0]].push(e(i))):n.push(e(i));return{formErrors:n,fieldErrors:t}}function Da(r,e){let t=e||function(o){return o.message},n={_errors:[]},i=o=>{for(let s of o.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(a=>i({issues:a}));else if(s.code==="invalid_key")i({issues:s.issues});else if(s.code==="invalid_element")i({issues:s.issues});else if(s.path.length===0)n._errors.push(t(s));else{let a=n,c=0;for(;c<s.path.length;){let l=s.path[c];c===s.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(t(s))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return i(r),n}var qa=r=>(e,t,n,i)=>{let o=n?Object.assign(n,{async:!1}):{async:!1},s=e._zod.run({value:t,issues:[]},o);if(s instanceof Promise)throw new Vt;if(s.issues.length){let a=new(i?.Err??r)(s.issues.map(c=>ft(c,o,Ke())));throw ko(a,i?.callee),a}return s.value},Za=qa(ai),Ua=r=>async(e,t,n,i)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},s=e._zod.run({value:t,issues:[]},o);if(s instanceof Promise&&(s=await s),s.issues.length){let a=new(i?.Err??r)(s.issues.map(c=>ft(c,o,Ke())));throw ko(a,i?.callee),a}return s.value},Fa=Ua(ai),Ha=r=>(e,t,n)=>{let i=n?{...n,async:!1}:{async:!1},o=e._zod.run({value:t,issues:[]},i);if(o instanceof Promise)throw new Vt;return o.issues.length?{success:!1,error:new(r??Eo)(o.issues.map(s=>ft(s,i,Ke())))}:{success:!0,data:o.value}},Ur=Ha(ai),Ba=r=>async(e,t,n)=>{let i=n?Object.assign(n,{async:!0}):{async:!0},o=e._zod.run({value:t,issues:[]},i);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new r(o.issues.map(s=>ft(s,i,Ke())))}:{success:!0,data:o.value}},Fr=Ba(ai);var Pm=/^[cC][^\s-]{8,}$/,Rm=/^[0-9a-z]+$/,Cm=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Im=/^[0-9a-vA-V]{20}$/,Am=/^[A-Za-z0-9]{27}$/,Om=/^[a-zA-Z0-9_-]{21}$/,Nm=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var jm=/^([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})$/,Va=r=>r?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${r}[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)$/;var Mm=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var d0="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Lm(){return new RegExp(d0,"u")}var Dm=/^(?:(?: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])$/,qm=/^(([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})$/,Zm=/^((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])$/,Um=/^(([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])$/,Fm=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Wa=/^[A-Za-z0-9_-]*$/,Hm=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var Bm=/^\+(?:[0-9]){6,14}[0-9]$/,Vm="(?:(?:\\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])))",Wm=new RegExp(`^${Vm}$`);function Gm(r){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof r.precision=="number"?r.precision===-1?`${e}`:r.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${r.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Km(r){return new RegExp(`^${Gm(r)}$`)}function Jm(r){let e=Gm({precision:r.precision}),t=["Z"];r.local&&t.push(""),r.offset&&t.push("([+-]\\d{2}:\\d{2})");let n=`${e}(?:${t.join("|")})`;return new RegExp(`^${Vm}T(?:${n})$`)}var Xm=r=>{let e=r?`[\\s\\S]{${r?.minimum??0},${r?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)};var Qm=/^\d+$/,Ym=/^-?\d+(?:\.\d+)?/i,ef=/true|false/i,tf=/null/i;var rf=/^[^A-Z]*$/,nf=/^[^a-z]*$/;var $e=y("$ZodCheck",(r,e)=>{var t;r._zod??(r._zod={}),r._zod.def=e,(t=r._zod).onattach??(t.onattach=[])}),of={number:"number",bigint:"bigint",object:"date"},Ga=y("$ZodCheckLessThan",(r,e)=>{$e.init(r,e);let t=of[typeof e.value];r._zod.onattach.push(n=>{let i=n._zod.bag,o=(e.inclusive?i.maximum:i.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<o&&(e.inclusive?i.maximum=e.value:i.exclusiveMaximum=e.value)}),r._zod.check=n=>{(e.inclusive?n.value<=e.value:n.value<e.value)||n.issues.push({origin:t,code:"too_big",maximum:e.value,input:n.value,inclusive:e.inclusive,inst:r,continue:!e.abort})}}),Ka=y("$ZodCheckGreaterThan",(r,e)=>{$e.init(r,e);let t=of[typeof e.value];r._zod.onattach.push(n=>{let i=n._zod.bag,o=(e.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>o&&(e.inclusive?i.minimum=e.value:i.exclusiveMinimum=e.value)}),r._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:t,code:"too_small",minimum:e.value,input:n.value,inclusive:e.inclusive,inst:r,continue:!e.abort})}}),sf=y("$ZodCheckMultipleOf",(r,e)=>{$e.init(r,e),r._zod.onattach.push(t=>{var n;(n=t._zod.bag).multipleOf??(n.multipleOf=e.value)}),r._zod.check=t=>{if(typeof t.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof t.value=="bigint"?t.value%e.value===BigInt(0):Ca(t.value,e.value)===0)||t.issues.push({origin:typeof t.value,code:"not_multiple_of",divisor:e.value,input:t.value,inst:r,continue:!e.abort})}}),af=y("$ZodCheckNumberFormat",(r,e)=>{$e.init(r,e),e.format=e.format||"float64";let t=e.format?.includes("int"),n=t?"int":"number",[i,o]=ja[e.format];r._zod.onattach.push(s=>{let a=s._zod.bag;a.format=e.format,a.minimum=i,a.maximum=o,t&&(a.pattern=Qm)}),r._zod.check=s=>{let a=s.value;if(t){if(!Number.isInteger(a)){s.issues.push({expected:n,format:e.format,code:"invalid_type",input:a,inst:r});return}if(!Number.isSafeInteger(a)){a>0?s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:r,origin:n,continue:!e.abort}):s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:r,origin:n,continue:!e.abort});return}}a<i&&s.issues.push({origin:"number",input:a,code:"too_small",minimum:i,inclusive:!0,inst:r,continue:!e.abort}),a>o&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:o,inst:r})}});var cf=y("$ZodCheckMaxLength",(r,e)=>{var t;$e.init(r,e),(t=r._zod.def).when??(t.when=n=>{let i=n.value;return!ii(i)&&i.length!==void 0}),r._zod.onattach.push(n=>{let i=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<i&&(n._zod.bag.maximum=e.maximum)}),r._zod.check=n=>{let i=n.value;if(i.length<=e.maximum)return;let s=si(i);n.issues.push({origin:s,code:"too_big",maximum:e.maximum,inclusive:!0,input:i,inst:r,continue:!e.abort})}}),lf=y("$ZodCheckMinLength",(r,e)=>{var t;$e.init(r,e),(t=r._zod.def).when??(t.when=n=>{let i=n.value;return!ii(i)&&i.length!==void 0}),r._zod.onattach.push(n=>{let i=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>i&&(n._zod.bag.minimum=e.minimum)}),r._zod.check=n=>{let i=n.value;if(i.length>=e.minimum)return;let s=si(i);n.issues.push({origin:s,code:"too_small",minimum:e.minimum,inclusive:!0,input:i,inst:r,continue:!e.abort})}}),uf=y("$ZodCheckLengthEquals",(r,e)=>{var t;$e.init(r,e),(t=r._zod.def).when??(t.when=n=>{let i=n.value;return!ii(i)&&i.length!==void 0}),r._zod.onattach.push(n=>{let i=n._zod.bag;i.minimum=e.length,i.maximum=e.length,i.length=e.length}),r._zod.check=n=>{let i=n.value,o=i.length;if(o===e.length)return;let s=si(i),a=o>e.length;n.issues.push({origin:s,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:r,continue:!e.abort})}}),ci=y("$ZodCheckStringFormat",(r,e)=>{var t,n;$e.init(r,e),r._zod.onattach.push(i=>{let o=i._zod.bag;o.format=e.format,e.pattern&&(o.patterns??(o.patterns=new Set),o.patterns.add(e.pattern))}),e.pattern?(t=r._zod).check??(t.check=i=>{e.pattern.lastIndex=0,!e.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:e.format,input:i.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:r,continue:!e.abort})}):(n=r._zod).check??(n.check=()=>{})}),pf=y("$ZodCheckRegex",(r,e)=>{ci.init(r,e),r._zod.check=t=>{e.pattern.lastIndex=0,!e.pattern.test(t.value)&&t.issues.push({origin:"string",code:"invalid_format",format:"regex",input:t.value,pattern:e.pattern.toString(),inst:r,continue:!e.abort})}}),df=y("$ZodCheckLowerCase",(r,e)=>{e.pattern??(e.pattern=rf),ci.init(r,e)}),mf=y("$ZodCheckUpperCase",(r,e)=>{e.pattern??(e.pattern=nf),ci.init(r,e)}),ff=y("$ZodCheckIncludes",(r,e)=>{$e.init(r,e);let t=or(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${t}`:t);e.pattern=n,r._zod.onattach.push(i=>{let o=i._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),r._zod.check=i=>{i.value.includes(e.includes,e.position)||i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:i.value,inst:r,continue:!e.abort})}}),hf=y("$ZodCheckStartsWith",(r,e)=>{$e.init(r,e);let t=new RegExp(`^${or(e.prefix)}.*`);e.pattern??(e.pattern=t),r._zod.onattach.push(n=>{let i=n._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(t)}),r._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:r,continue:!e.abort})}}),gf=y("$ZodCheckEndsWith",(r,e)=>{$e.init(r,e);let t=new RegExp(`.*${or(e.suffix)}$`);e.pattern??(e.pattern=t),r._zod.onattach.push(n=>{let i=n._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(t)}),r._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:r,continue:!e.abort})}});var vf=y("$ZodCheckOverwrite",(r,e)=>{$e.init(r,e),r._zod.check=t=>{t.value=e.tx(t.value)}});var To=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 n=e.split(`
|
|
60
|
+
`).filter(s=>s),i=Math.min(...n.map(s=>s.length-s.trimStart().length)),o=n.map(s=>s.slice(i)).map(s=>" ".repeat(this.indent*2)+s);for(let s of o)this.content.push(s)}compile(){let e=Function,t=this?.args,i=[...(this?.content??[""]).map(o=>` ${o}`)];return new e(...t,i.join(`
|
|
61
|
+
`))}};var yf={major:4,minor:0,patch:0};var ne=y("$ZodType",(r,e)=>{var t;r??(r={}),r._zod.def=e,r._zod.bag=r._zod.bag||{},r._zod.version=yf;let n=[...r._zod.def.checks??[]];r._zod.traits.has("$ZodCheck")&&n.unshift(r);for(let i of n)for(let o of i._zod.onattach)o(r);if(n.length===0)(t=r._zod).deferred??(t.deferred=[]),r._zod.deferred?.push(()=>{r._zod.run=r._zod.parse});else{let i=(o,s,a)=>{let c=Zr(o),l;for(let u of s){if(u._zod.def.when){if(!u._zod.def.when(o))continue}else if(c)continue;let p=o.issues.length,d=u._zod.check(o);if(d instanceof Promise&&a?.async===!1)throw new Vt;if(l||d instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await d,o.issues.length!==p&&(c||(c=Zr(o,p)))});else{if(o.issues.length===p)continue;c||(c=Zr(o,p))}}return l?l.then(()=>o):o};r._zod.run=(o,s)=>{let a=r._zod.parse(o,s);if(a instanceof Promise){if(s.async===!1)throw new Vt;return a.then(c=>i(c,n,s))}return i(a,n,s)}}r["~standard"]={validate:i=>{try{let o=Ur(r,i);return o.success?{value:o.data}:{issues:o.error?.issues}}catch{return Fr(r,i).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}}),li=y("$ZodString",(r,e)=>{ne.init(r,e),r._zod.pattern=[...r?._zod.bag?.patterns??[]].pop()??Xm(r._zod.bag),r._zod.parse=(t,n)=>{if(e.coerce)try{t.value=String(t.value)}catch{}return typeof t.value=="string"||t.issues.push({expected:"string",code:"invalid_type",input:t.value,inst:r}),t}}),le=y("$ZodStringFormat",(r,e)=>{ci.init(r,e),li.init(r,e)}),Xa=y("$ZodGUID",(r,e)=>{e.pattern??(e.pattern=jm),le.init(r,e)}),Qa=y("$ZodUUID",(r,e)=>{if(e.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(n===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=Va(n))}else e.pattern??(e.pattern=Va());le.init(r,e)}),Ya=y("$ZodEmail",(r,e)=>{e.pattern??(e.pattern=Mm),le.init(r,e)}),ec=y("$ZodURL",(r,e)=>{le.init(r,e),r._zod.check=t=>{try{let n=t.value,i=new URL(n),o=i.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(i.hostname)||t.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:Hm.source,input:t.value,inst:r,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||t.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:t.value,inst:r,continue:!e.abort})),!n.endsWith("/")&&o.endsWith("/")?t.value=o.slice(0,-1):t.value=o;return}catch{t.issues.push({code:"invalid_format",format:"url",input:t.value,inst:r,continue:!e.abort})}}}),tc=y("$ZodEmoji",(r,e)=>{e.pattern??(e.pattern=Lm()),le.init(r,e)}),rc=y("$ZodNanoID",(r,e)=>{e.pattern??(e.pattern=Om),le.init(r,e)}),nc=y("$ZodCUID",(r,e)=>{e.pattern??(e.pattern=Pm),le.init(r,e)}),ic=y("$ZodCUID2",(r,e)=>{e.pattern??(e.pattern=Rm),le.init(r,e)}),oc=y("$ZodULID",(r,e)=>{e.pattern??(e.pattern=Cm),le.init(r,e)}),sc=y("$ZodXID",(r,e)=>{e.pattern??(e.pattern=Im),le.init(r,e)}),ac=y("$ZodKSUID",(r,e)=>{e.pattern??(e.pattern=Am),le.init(r,e)}),Pf=y("$ZodISODateTime",(r,e)=>{e.pattern??(e.pattern=Jm(e)),le.init(r,e)}),Rf=y("$ZodISODate",(r,e)=>{e.pattern??(e.pattern=Wm),le.init(r,e)}),Cf=y("$ZodISOTime",(r,e)=>{e.pattern??(e.pattern=Km(e)),le.init(r,e)}),If=y("$ZodISODuration",(r,e)=>{e.pattern??(e.pattern=Nm),le.init(r,e)}),cc=y("$ZodIPv4",(r,e)=>{e.pattern??(e.pattern=Dm),le.init(r,e),r._zod.onattach.push(t=>{let n=t._zod.bag;n.format="ipv4"})}),lc=y("$ZodIPv6",(r,e)=>{e.pattern??(e.pattern=qm),le.init(r,e),r._zod.onattach.push(t=>{let n=t._zod.bag;n.format="ipv6"}),r._zod.check=t=>{try{new URL(`http://[${t.value}]`)}catch{t.issues.push({code:"invalid_format",format:"ipv6",input:t.value,inst:r,continue:!e.abort})}}}),uc=y("$ZodCIDRv4",(r,e)=>{e.pattern??(e.pattern=Zm),le.init(r,e)}),pc=y("$ZodCIDRv6",(r,e)=>{e.pattern??(e.pattern=Um),le.init(r,e),r._zod.check=t=>{let[n,i]=t.value.split("/");try{if(!i)throw new Error;let o=Number(i);if(`${o}`!==i)throw new Error;if(o<0||o>128)throw new Error;new URL(`http://[${n}]`)}catch{t.issues.push({code:"invalid_format",format:"cidrv6",input:t.value,inst:r,continue:!e.abort})}}});function Af(r){if(r==="")return!0;if(r.length%4!==0)return!1;try{return atob(r),!0}catch{return!1}}var dc=y("$ZodBase64",(r,e)=>{e.pattern??(e.pattern=Fm),le.init(r,e),r._zod.onattach.push(t=>{t._zod.bag.contentEncoding="base64"}),r._zod.check=t=>{Af(t.value)||t.issues.push({code:"invalid_format",format:"base64",input:t.value,inst:r,continue:!e.abort})}});function m0(r){if(!Wa.test(r))return!1;let e=r.replace(/[-_]/g,n=>n==="-"?"+":"/"),t=e.padEnd(Math.ceil(e.length/4)*4,"=");return Af(t)}var mc=y("$ZodBase64URL",(r,e)=>{e.pattern??(e.pattern=Wa),le.init(r,e),r._zod.onattach.push(t=>{t._zod.bag.contentEncoding="base64url"}),r._zod.check=t=>{m0(t.value)||t.issues.push({code:"invalid_format",format:"base64url",input:t.value,inst:r,continue:!e.abort})}}),fc=y("$ZodE164",(r,e)=>{e.pattern??(e.pattern=Bm),le.init(r,e)});function f0(r,e=null){try{let t=r.split(".");if(t.length!==3)return!1;let[n]=t;if(!n)return!1;let i=JSON.parse(atob(n));return!("typ"in i&&i?.typ!=="JWT"||!i.alg||e&&(!("alg"in i)||i.alg!==e))}catch{return!1}}var hc=y("$ZodJWT",(r,e)=>{le.init(r,e),r._zod.check=t=>{f0(t.value,e.alg)||t.issues.push({code:"invalid_format",format:"jwt",input:t.value,inst:r,continue:!e.abort})}});var Po=y("$ZodNumber",(r,e)=>{ne.init(r,e),r._zod.pattern=r._zod.bag.pattern??Ym,r._zod.parse=(t,n)=>{if(e.coerce)try{t.value=Number(t.value)}catch{}let i=t.value;if(typeof i=="number"&&!Number.isNaN(i)&&Number.isFinite(i))return t;let o=typeof i=="number"?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return t.issues.push({expected:"number",code:"invalid_type",input:i,inst:r,...o?{received:o}:{}}),t}}),gc=y("$ZodNumber",(r,e)=>{af.init(r,e),Po.init(r,e)}),vc=y("$ZodBoolean",(r,e)=>{ne.init(r,e),r._zod.pattern=ef,r._zod.parse=(t,n)=>{if(e.coerce)try{t.value=!!t.value}catch{}let i=t.value;return typeof i=="boolean"||t.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:r}),t}});var xc=y("$ZodNull",(r,e)=>{ne.init(r,e),r._zod.pattern=tf,r._zod.values=new Set([null]),r._zod.parse=(t,n)=>{let i=t.value;return i===null||t.issues.push({expected:"null",code:"invalid_type",input:i,inst:r}),t}});var yc=y("$ZodUnknown",(r,e)=>{ne.init(r,e),r._zod.parse=t=>t}),_c=y("$ZodNever",(r,e)=>{ne.init(r,e),r._zod.parse=(t,n)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:r}),t)});function _f(r,e,t){r.issues.length&&e.issues.push(...zt(t,r.issues)),e.value[t]=r.value}var bc=y("$ZodArray",(r,e)=>{ne.init(r,e),r._zod.parse=(t,n)=>{let i=t.value;if(!Array.isArray(i))return t.issues.push({expected:"array",code:"invalid_type",input:i,inst:r}),t;t.value=Array(i.length);let o=[];for(let s=0;s<i.length;s++){let a=i[s],c=e.element._zod.run({value:a,issues:[]},n);c instanceof Promise?o.push(c.then(l=>_f(l,t,s))):_f(c,t,s)}return o.length?Promise.all(o).then(()=>t):t}});function zo(r,e,t){r.issues.length&&e.issues.push(...zt(t,r.issues)),e.value[t]=r.value}function bf(r,e,t,n){r.issues.length?n[t]===void 0?t in n?e.value[t]=void 0:e.value[t]=r.value:e.issues.push(...zt(t,r.issues)):r.value===void 0?t in n&&(e.value[t]=void 0):e.value[t]=r.value}var Ro=y("$ZodObject",(r,e)=>{ne.init(r,e);let t=ni(()=>{let p=Object.keys(e.shape);for(let f of p)if(!(e.shape[f]instanceof ne))throw new Error(`Invalid element at key "${f}": expected a Zod schema`);let d=Na(e.shape);return{shape:e.shape,keys:p,keySet:new Set(p),numKeys:p.length,optionalKeys:new Set(d)}});ce(r._zod,"propValues",()=>{let p=e.shape,d={};for(let f in p){let m=p[f]._zod;if(m.values){d[f]??(d[f]=new Set);for(let h of m.values)d[f].add(h)}}return d});let n=p=>{let d=new To(["shape","payload","ctx"]),f=t.value,m=w=>{let E=qr(w);return`shape[${E}]._zod.run({ value: input[${E}], issues: [] }, ctx)`};d.write("const input = payload.value;");let h=Object.create(null),v=0;for(let w of f.keys)h[w]=`key_${v++}`;d.write("const newResult = {}");for(let w of f.keys)if(f.optionalKeys.has(w)){let E=h[w];d.write(`const ${E} = ${m(w)};`);let P=qr(w);d.write(`
|
|
62
|
+
if (${E}.issues.length) {
|
|
63
|
+
if (input[${P}] === undefined) {
|
|
64
|
+
if (${P} in input) {
|
|
65
|
+
newResult[${P}] = undefined;
|
|
66
|
+
}
|
|
67
|
+
} else {
|
|
68
|
+
payload.issues = payload.issues.concat(
|
|
69
|
+
${E}.issues.map((iss) => ({
|
|
70
|
+
...iss,
|
|
71
|
+
path: iss.path ? [${P}, ...iss.path] : [${P}],
|
|
72
|
+
}))
|
|
73
|
+
);
|
|
74
|
+
}
|
|
75
|
+
} else if (${E}.value === undefined) {
|
|
76
|
+
if (${P} in input) newResult[${P}] = undefined;
|
|
77
|
+
} else {
|
|
78
|
+
newResult[${P}] = ${E}.value;
|
|
79
|
+
}
|
|
80
|
+
`)}else{let E=h[w];d.write(`const ${E} = ${m(w)};`),d.write(`
|
|
81
|
+
if (${E}.issues.length) payload.issues = payload.issues.concat(${E}.issues.map(iss => ({
|
|
82
|
+
...iss,
|
|
83
|
+
path: iss.path ? [${qr(w)}, ...iss.path] : [${qr(w)}]
|
|
84
|
+
})));`),d.write(`newResult[${qr(w)}] = ${E}.value`)}d.write("payload.value = newResult;"),d.write("return payload;");let b=d.compile();return(w,E)=>b(p,w,E)},i,o=bn,s=!bo.jitless,c=s&&Aa.value,l=e.catchall,u;r._zod.parse=(p,d)=>{u??(u=t.value);let f=p.value;if(!o(f))return p.issues.push({expected:"object",code:"invalid_type",input:f,inst:r}),p;let m=[];if(s&&c&&d?.async===!1&&d.jitless!==!0)i||(i=n(e.shape)),p=i(p,d);else{p.value={};let E=u.shape;for(let P of u.keys){let j=E[P],Ne=j._zod.run({value:f[P],issues:[]},d),tt=j._zod.optin==="optional"&&j._zod.optout==="optional";Ne instanceof Promise?m.push(Ne.then(dn=>tt?bf(dn,p,P,f):zo(dn,p,P))):tt?bf(Ne,p,P,f):zo(Ne,p,P)}}if(!l)return m.length?Promise.all(m).then(()=>p):p;let h=[],v=u.keySet,b=l._zod,w=b.def.type;for(let E of Object.keys(f)){if(v.has(E))continue;if(w==="never"){h.push(E);continue}let P=b.run({value:f[E],issues:[]},d);P instanceof Promise?m.push(P.then(j=>zo(j,p,E))):zo(P,p,E)}return h.length&&p.issues.push({code:"unrecognized_keys",keys:h,input:f,inst:r}),m.length?Promise.all(m).then(()=>p):p}});function wf(r,e,t,n){for(let i of r)if(i.issues.length===0)return e.value=i.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:t,errors:r.map(i=>i.issues.map(o=>ft(o,n,Ke())))}),e}var Co=y("$ZodUnion",(r,e)=>{ne.init(r,e),ce(r._zod,"optin",()=>e.options.some(t=>t._zod.optin==="optional")?"optional":void 0),ce(r._zod,"optout",()=>e.options.some(t=>t._zod.optout==="optional")?"optional":void 0),ce(r._zod,"values",()=>{if(e.options.every(t=>t._zod.values))return new Set(e.options.flatMap(t=>Array.from(t._zod.values)))}),ce(r._zod,"pattern",()=>{if(e.options.every(t=>t._zod.pattern)){let t=e.options.map(n=>n._zod.pattern);return new RegExp(`^(${t.map(n=>oi(n.source)).join("|")})$`)}}),r._zod.parse=(t,n)=>{let i=!1,o=[];for(let s of e.options){let a=s._zod.run({value:t.value,issues:[]},n);if(a instanceof Promise)o.push(a),i=!0;else{if(a.issues.length===0)return a;o.push(a)}}return i?Promise.all(o).then(s=>wf(s,t,r,n)):wf(o,t,r,n)}}),wc=y("$ZodDiscriminatedUnion",(r,e)=>{Co.init(r,e);let t=r._zod.parse;ce(r._zod,"propValues",()=>{let i={};for(let o of e.options){let s=o._zod.propValues;if(!s||Object.keys(s).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(o)}"`);for(let[a,c]of Object.entries(s)){i[a]||(i[a]=new Set);for(let l of c)i[a].add(l)}}return i});let n=ni(()=>{let i=e.options,o=new Map;for(let s of i){let a=s._zod.propValues[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let c of a){if(o.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);o.set(c,s)}}return o});r._zod.parse=(i,o)=>{let s=i.value;if(!bn(s))return i.issues.push({code:"invalid_type",expected:"object",input:s,inst:r}),i;let a=n.value.get(s?.[e.discriminator]);return a?a._zod.run(i,o):e.unionFallback?t(i,o):(i.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:s,path:[e.discriminator],inst:r}),i)}}),kc=y("$ZodIntersection",(r,e)=>{ne.init(r,e),r._zod.parse=(t,n)=>{let i=t.value,o=e.left._zod.run({value:i,issues:[]},n),s=e.right._zod.run({value:i,issues:[]},n);return o instanceof Promise||s instanceof Promise?Promise.all([o,s]).then(([c,l])=>kf(t,c,l)):kf(t,o,s)}});function Ja(r,e){if(r===e)return{valid:!0,data:r};if(r instanceof Date&&e instanceof Date&&+r==+e)return{valid:!0,data:r};if(wn(r)&&wn(e)){let t=Object.keys(e),n=Object.keys(r).filter(o=>t.indexOf(o)!==-1),i={...r,...e};for(let o of n){let s=Ja(r[o],e[o]);if(!s.valid)return{valid:!1,mergeErrorPath:[o,...s.mergeErrorPath]};i[o]=s.data}return{valid:!0,data:i}}if(Array.isArray(r)&&Array.isArray(e)){if(r.length!==e.length)return{valid:!1,mergeErrorPath:[]};let t=[];for(let n=0;n<r.length;n++){let i=r[n],o=e[n],s=Ja(i,o);if(!s.valid)return{valid:!1,mergeErrorPath:[n,...s.mergeErrorPath]};t.push(s.data)}return{valid:!0,data:t}}return{valid:!1,mergeErrorPath:[]}}function kf(r,e,t){if(e.issues.length&&r.issues.push(...e.issues),t.issues.length&&r.issues.push(...t.issues),Zr(r))return r;let n=Ja(e.value,t.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return r.value=n.data,r}var Sc=y("$ZodRecord",(r,e)=>{ne.init(r,e),r._zod.parse=(t,n)=>{let i=t.value;if(!wn(i))return t.issues.push({expected:"record",code:"invalid_type",input:i,inst:r}),t;let o=[];if(e.keyType._zod.values){let s=e.keyType._zod.values;t.value={};for(let c of s)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let l=e.valueType._zod.run({value:i[c],issues:[]},n);l instanceof Promise?o.push(l.then(u=>{u.issues.length&&t.issues.push(...zt(c,u.issues)),t.value[c]=u.value})):(l.issues.length&&t.issues.push(...zt(c,l.issues)),t.value[c]=l.value)}let a;for(let c in i)s.has(c)||(a=a??[],a.push(c));a&&a.length>0&&t.issues.push({code:"unrecognized_keys",input:i,inst:r,keys:a})}else{t.value={};for(let s of Reflect.ownKeys(i)){if(s==="__proto__")continue;let a=e.keyType._zod.run({value:s,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){t.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(l=>ft(l,n,Ke())),input:s,path:[s],inst:r}),t.value[a.value]=a.value;continue}let c=e.valueType._zod.run({value:i[s],issues:[]},n);c instanceof Promise?o.push(c.then(l=>{l.issues.length&&t.issues.push(...zt(s,l.issues)),t.value[a.value]=l.value})):(c.issues.length&&t.issues.push(...zt(s,c.issues)),t.value[a.value]=c.value)}}return o.length?Promise.all(o).then(()=>t):t}});var Ec=y("$ZodEnum",(r,e)=>{ne.init(r,e);let t=ri(e.entries);r._zod.values=new Set(t),r._zod.pattern=new RegExp(`^(${t.filter(n=>Oa.has(typeof n)).map(n=>typeof n=="string"?or(n):n.toString()).join("|")})$`),r._zod.parse=(n,i)=>{let o=n.value;return r._zod.values.has(o)||n.issues.push({code:"invalid_value",values:t,input:o,inst:r}),n}}),$c=y("$ZodLiteral",(r,e)=>{ne.init(r,e),r._zod.values=new Set(e.values),r._zod.pattern=new RegExp(`^(${e.values.map(t=>typeof t=="string"?or(t):t?t.toString():String(t)).join("|")})$`),r._zod.parse=(t,n)=>{let i=t.value;return r._zod.values.has(i)||t.issues.push({code:"invalid_value",values:e.values,input:i,inst:r}),t}});var Tc=y("$ZodTransform",(r,e)=>{ne.init(r,e),r._zod.parse=(t,n)=>{let i=e.transform(t.value,t);if(n.async)return(i instanceof Promise?i:Promise.resolve(i)).then(s=>(t.value=s,t));if(i instanceof Promise)throw new Vt;return t.value=i,t}}),zc=y("$ZodOptional",(r,e)=>{ne.init(r,e),r._zod.optin="optional",r._zod.optout="optional",ce(r._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),ce(r._zod,"pattern",()=>{let t=e.innerType._zod.pattern;return t?new RegExp(`^(${oi(t.source)})?$`):void 0}),r._zod.parse=(t,n)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(t,n):t.value===void 0?t:e.innerType._zod.run(t,n)}),Pc=y("$ZodNullable",(r,e)=>{ne.init(r,e),ce(r._zod,"optin",()=>e.innerType._zod.optin),ce(r._zod,"optout",()=>e.innerType._zod.optout),ce(r._zod,"pattern",()=>{let t=e.innerType._zod.pattern;return t?new RegExp(`^(${oi(t.source)}|null)$`):void 0}),ce(r._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),r._zod.parse=(t,n)=>t.value===null?t:e.innerType._zod.run(t,n)}),Rc=y("$ZodDefault",(r,e)=>{ne.init(r,e),r._zod.optin="optional",ce(r._zod,"values",()=>e.innerType._zod.values),r._zod.parse=(t,n)=>{if(t.value===void 0)return t.value=e.defaultValue,t;let i=e.innerType._zod.run(t,n);return i instanceof Promise?i.then(o=>Sf(o,e)):Sf(i,e)}});function Sf(r,e){return r.value===void 0&&(r.value=e.defaultValue),r}var Cc=y("$ZodPrefault",(r,e)=>{ne.init(r,e),r._zod.optin="optional",ce(r._zod,"values",()=>e.innerType._zod.values),r._zod.parse=(t,n)=>(t.value===void 0&&(t.value=e.defaultValue),e.innerType._zod.run(t,n))}),Ic=y("$ZodNonOptional",(r,e)=>{ne.init(r,e),ce(r._zod,"values",()=>{let t=e.innerType._zod.values;return t?new Set([...t].filter(n=>n!==void 0)):void 0}),r._zod.parse=(t,n)=>{let i=e.innerType._zod.run(t,n);return i instanceof Promise?i.then(o=>Ef(o,r)):Ef(i,r)}});function Ef(r,e){return!r.issues.length&&r.value===void 0&&r.issues.push({code:"invalid_type",expected:"nonoptional",input:r.value,inst:e}),r}var Ac=y("$ZodCatch",(r,e)=>{ne.init(r,e),r._zod.optin="optional",ce(r._zod,"optout",()=>e.innerType._zod.optout),ce(r._zod,"values",()=>e.innerType._zod.values),r._zod.parse=(t,n)=>{let i=e.innerType._zod.run(t,n);return i instanceof Promise?i.then(o=>(t.value=o.value,o.issues.length&&(t.value=e.catchValue({...t,error:{issues:o.issues.map(s=>ft(s,n,Ke()))},input:t.value}),t.issues=[]),t)):(t.value=i.value,i.issues.length&&(t.value=e.catchValue({...t,error:{issues:i.issues.map(o=>ft(o,n,Ke()))},input:t.value}),t.issues=[]),t)}});var Oc=y("$ZodPipe",(r,e)=>{ne.init(r,e),ce(r._zod,"values",()=>e.in._zod.values),ce(r._zod,"optin",()=>e.in._zod.optin),ce(r._zod,"optout",()=>e.out._zod.optout),r._zod.parse=(t,n)=>{let i=e.in._zod.run(t,n);return i instanceof Promise?i.then(o=>$f(o,e,n)):$f(i,e,n)}});function $f(r,e,t){return Zr(r)?r:e.out._zod.run({value:r.value,issues:r.issues},t)}var Nc=y("$ZodReadonly",(r,e)=>{ne.init(r,e),ce(r._zod,"propValues",()=>e.innerType._zod.propValues),ce(r._zod,"values",()=>e.innerType._zod.values),ce(r._zod,"optin",()=>e.innerType._zod.optin),ce(r._zod,"optout",()=>e.innerType._zod.optout),r._zod.parse=(t,n)=>{let i=e.innerType._zod.run(t,n);return i instanceof Promise?i.then(Tf):Tf(i)}});function Tf(r){return r.value=Object.freeze(r.value),r}var jc=y("$ZodCustom",(r,e)=>{$e.init(r,e),ne.init(r,e),r._zod.parse=(t,n)=>t,r._zod.check=t=>{let n=t.value,i=e.fn(n);if(i instanceof Promise)return i.then(o=>zf(o,t,n,r));zf(i,t,n,r)}});function zf(r,e,t,n){if(!r){let i={code:"custom",input:t,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(i.params=n._zod.def.params),e.issues.push(Ma(i))}}var h0=r=>{let e=typeof r;switch(e){case"number":return Number.isNaN(r)?"NaN":"number";case"object":{if(Array.isArray(r))return"array";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return e},g0=()=>{let r={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function e(n){return r[n]??null}let t={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return n=>{switch(n.code){case"invalid_type":return`Invalid input: expected ${n.expected}, received ${h0(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${So(n.values[0])}`:`Invalid option: expected one of ${wo(n.values,"|")}`;case"too_big":{let i=n.inclusive?"<=":"<",o=e(n.origin);return o?`Too big: expected ${n.origin??"value"} to have ${i}${n.maximum.toString()} ${o.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${i}${n.maximum.toString()}`}case"too_small":{let i=n.inclusive?">=":">",o=e(n.origin);return o?`Too small: expected ${n.origin} to have ${i}${n.minimum.toString()} ${o.unit}`:`Too small: expected ${n.origin} to be ${i}${n.minimum.toString()}`}case"invalid_format":{let i=n;return i.format==="starts_with"?`Invalid string: must start with "${i.prefix}"`:i.format==="ends_with"?`Invalid string: must end with "${i.suffix}"`:i.format==="includes"?`Invalid string: must include "${i.includes}"`:i.format==="regex"?`Invalid string: must match pattern ${i.pattern}`:`Invalid ${t[i.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${wo(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}};function Of(){return{localeError:g0()}}var v0=Symbol("ZodOutput"),x0=Symbol("ZodInput"),ui=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...t){let n=t[0];if(this._map.set(e,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t=="object"&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};function Nf(){return new ui}var sr=Nf();function Mc(r,e){return new r({type:"string",...L(e)})}function Lc(r,e){return new r({type:"string",format:"email",check:"string_format",abort:!1,...L(e)})}function Io(r,e){return new r({type:"string",format:"guid",check:"string_format",abort:!1,...L(e)})}function Dc(r,e){return new r({type:"string",format:"uuid",check:"string_format",abort:!1,...L(e)})}function qc(r,e){return new r({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...L(e)})}function Zc(r,e){return new r({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...L(e)})}function Uc(r,e){return new r({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...L(e)})}function Fc(r,e){return new r({type:"string",format:"url",check:"string_format",abort:!1,...L(e)})}function Hc(r,e){return new r({type:"string",format:"emoji",check:"string_format",abort:!1,...L(e)})}function Bc(r,e){return new r({type:"string",format:"nanoid",check:"string_format",abort:!1,...L(e)})}function Vc(r,e){return new r({type:"string",format:"cuid",check:"string_format",abort:!1,...L(e)})}function Wc(r,e){return new r({type:"string",format:"cuid2",check:"string_format",abort:!1,...L(e)})}function Gc(r,e){return new r({type:"string",format:"ulid",check:"string_format",abort:!1,...L(e)})}function Kc(r,e){return new r({type:"string",format:"xid",check:"string_format",abort:!1,...L(e)})}function Jc(r,e){return new r({type:"string",format:"ksuid",check:"string_format",abort:!1,...L(e)})}function Xc(r,e){return new r({type:"string",format:"ipv4",check:"string_format",abort:!1,...L(e)})}function Qc(r,e){return new r({type:"string",format:"ipv6",check:"string_format",abort:!1,...L(e)})}function Yc(r,e){return new r({type:"string",format:"cidrv4",check:"string_format",abort:!1,...L(e)})}function el(r,e){return new r({type:"string",format:"cidrv6",check:"string_format",abort:!1,...L(e)})}function tl(r,e){return new r({type:"string",format:"base64",check:"string_format",abort:!1,...L(e)})}function rl(r,e){return new r({type:"string",format:"base64url",check:"string_format",abort:!1,...L(e)})}function nl(r,e){return new r({type:"string",format:"e164",check:"string_format",abort:!1,...L(e)})}function il(r,e){return new r({type:"string",format:"jwt",check:"string_format",abort:!1,...L(e)})}function jf(r,e){return new r({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...L(e)})}function Mf(r,e){return new r({type:"string",format:"date",check:"string_format",...L(e)})}function Lf(r,e){return new r({type:"string",format:"time",check:"string_format",precision:null,...L(e)})}function Df(r,e){return new r({type:"string",format:"duration",check:"string_format",...L(e)})}function ol(r,e){return new r({type:"number",checks:[],...L(e)})}function sl(r,e){return new r({type:"number",check:"number_format",abort:!1,format:"safeint",...L(e)})}function al(r,e){return new r({type:"boolean",...L(e)})}function cl(r,e){return new r({type:"null",...L(e)})}function ll(r){return new r({type:"unknown"})}function ul(r,e){return new r({type:"never",...L(e)})}function Ao(r,e){return new Ga({check:"less_than",...L(e),value:r,inclusive:!1})}function pi(r,e){return new Ga({check:"less_than",...L(e),value:r,inclusive:!0})}function Oo(r,e){return new Ka({check:"greater_than",...L(e),value:r,inclusive:!1})}function di(r,e){return new Ka({check:"greater_than",...L(e),value:r,inclusive:!0})}function No(r,e){return new sf({check:"multiple_of",...L(e),value:r})}function jo(r,e){return new cf({check:"max_length",...L(e),maximum:r})}function kn(r,e){return new lf({check:"min_length",...L(e),minimum:r})}function Mo(r,e){return new uf({check:"length_equals",...L(e),length:r})}function pl(r,e){return new pf({check:"string_format",format:"regex",...L(e),pattern:r})}function dl(r){return new df({check:"string_format",format:"lowercase",...L(r)})}function ml(r){return new mf({check:"string_format",format:"uppercase",...L(r)})}function fl(r,e){return new ff({check:"string_format",format:"includes",...L(e),includes:r})}function hl(r,e){return new hf({check:"string_format",format:"starts_with",...L(e),prefix:r})}function gl(r,e){return new gf({check:"string_format",format:"ends_with",...L(e),suffix:r})}function Hr(r){return new vf({check:"overwrite",tx:r})}function vl(r){return Hr(e=>e.normalize(r))}function xl(){return Hr(r=>r.trim())}function yl(){return Hr(r=>r.toLowerCase())}function _l(){return Hr(r=>r.toUpperCase())}function qf(r,e,t){return new r({type:"array",element:e,...L(t)})}function bl(r,e,t){let n=L(t);return n.abort??(n.abort=!0),new r({type:"custom",check:"custom",fn:e,...n})}function wl(r,e,t){return new r({type:"custom",check:"custom",fn:e,...L(t)})}var Lo=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??sr,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,t={path:[],schemaPath:[]}){var n;let i=e._zod.def,o={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},s=this.seen.get(e);if(s)return s.count++,t.schemaPath.includes(e)&&(s.cycle=t.path),s.schema;let a={schema:{},count:1,cycle:void 0,path:t.path};this.seen.set(e,a);let c=e._zod.toJSONSchema?.();if(c)a.schema=c;else{let p={...t,schemaPath:[...t.schemaPath,e],path:t.path},d=e._zod.parent;if(d)a.ref=d,this.process(d,p),this.seen.get(d).isParent=!0;else{let f=a.schema;switch(i.type){case"string":{let m=f;m.type="string";let{minimum:h,maximum:v,format:b,patterns:w,contentEncoding:E}=e._zod.bag;if(typeof h=="number"&&(m.minLength=h),typeof v=="number"&&(m.maxLength=v),b&&(m.format=o[b]??b,m.format===""&&delete m.format),E&&(m.contentEncoding=E),w&&w.size>0){let P=[...w];P.length===1?m.pattern=P[0].source:P.length>1&&(a.schema.allOf=[...P.map(j=>({...this.target==="draft-7"?{type:"string"}:{},pattern:j.source}))])}break}case"number":{let m=f,{minimum:h,maximum:v,format:b,multipleOf:w,exclusiveMaximum:E,exclusiveMinimum:P}=e._zod.bag;typeof b=="string"&&b.includes("int")?m.type="integer":m.type="number",typeof P=="number"&&(m.exclusiveMinimum=P),typeof h=="number"&&(m.minimum=h,typeof P=="number"&&(P>=h?delete m.minimum:delete m.exclusiveMinimum)),typeof E=="number"&&(m.exclusiveMaximum=E),typeof v=="number"&&(m.maximum=v,typeof E=="number"&&(E<=v?delete m.maximum:delete m.exclusiveMaximum)),typeof w=="number"&&(m.multipleOf=w);break}case"boolean":{let m=f;m.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{f.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{f.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let m=f,{minimum:h,maximum:v}=e._zod.bag;typeof h=="number"&&(m.minItems=h),typeof v=="number"&&(m.maxItems=v),m.type="array",m.items=this.process(i.element,{...p,path:[...p.path,"items"]});break}case"object":{let m=f;m.type="object",m.properties={};let h=i.shape;for(let w in h)m.properties[w]=this.process(h[w],{...p,path:[...p.path,"properties",w]});let v=new Set(Object.keys(h)),b=new Set([...v].filter(w=>{let E=i.shape[w]._zod;return this.io==="input"?E.optin===void 0:E.optout===void 0}));b.size>0&&(m.required=Array.from(b)),i.catchall?._zod.def.type==="never"?m.additionalProperties=!1:i.catchall?i.catchall&&(m.additionalProperties=this.process(i.catchall,{...p,path:[...p.path,"additionalProperties"]})):this.io==="output"&&(m.additionalProperties=!1);break}case"union":{let m=f;m.anyOf=i.options.map((h,v)=>this.process(h,{...p,path:[...p.path,"anyOf",v]}));break}case"intersection":{let m=f,h=this.process(i.left,{...p,path:[...p.path,"allOf",0]}),v=this.process(i.right,{...p,path:[...p.path,"allOf",1]}),b=E=>"allOf"in E&&Object.keys(E).length===1,w=[...b(h)?h.allOf:[h],...b(v)?v.allOf:[v]];m.allOf=w;break}case"tuple":{let m=f;m.type="array";let h=i.items.map((w,E)=>this.process(w,{...p,path:[...p.path,"prefixItems",E]}));if(this.target==="draft-2020-12"?m.prefixItems=h:m.items=h,i.rest){let w=this.process(i.rest,{...p,path:[...p.path,"items"]});this.target==="draft-2020-12"?m.items=w:m.additionalItems=w}i.rest&&(m.items=this.process(i.rest,{...p,path:[...p.path,"items"]}));let{minimum:v,maximum:b}=e._zod.bag;typeof v=="number"&&(m.minItems=v),typeof b=="number"&&(m.maxItems=b);break}case"record":{let m=f;m.type="object",m.propertyNames=this.process(i.keyType,{...p,path:[...p.path,"propertyNames"]}),m.additionalProperties=this.process(i.valueType,{...p,path:[...p.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{let m=f,h=ri(i.entries);h.every(v=>typeof v=="number")&&(m.type="number"),h.every(v=>typeof v=="string")&&(m.type="string"),m.enum=h;break}case"literal":{let m=f,h=[];for(let v of i.values)if(v===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof v=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");h.push(Number(v))}else h.push(v);if(h.length!==0)if(h.length===1){let v=h[0];m.type=v===null?"null":typeof v,m.const=v}else h.every(v=>typeof v=="number")&&(m.type="number"),h.every(v=>typeof v=="string")&&(m.type="string"),h.every(v=>typeof v=="boolean")&&(m.type="string"),h.every(v=>v===null)&&(m.type="null"),m.enum=h;break}case"file":{let m=f,h={type:"string",format:"binary",contentEncoding:"binary"},{minimum:v,maximum:b,mime:w}=e._zod.bag;v!==void 0&&(h.minLength=v),b!==void 0&&(h.maxLength=b),w?w.length===1?(h.contentMediaType=w[0],Object.assign(m,h)):m.anyOf=w.map(E=>({...h,contentMediaType:E})):Object.assign(m,h);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let m=this.process(i.innerType,p);f.anyOf=[m,{type:"null"}];break}case"nonoptional":{this.process(i.innerType,p),a.ref=i.innerType;break}case"success":{let m=f;m.type="boolean";break}case"default":{this.process(i.innerType,p),a.ref=i.innerType,f.default=JSON.parse(JSON.stringify(i.defaultValue));break}case"prefault":{this.process(i.innerType,p),a.ref=i.innerType,this.io==="input"&&(f._prefault=JSON.parse(JSON.stringify(i.defaultValue)));break}case"catch":{this.process(i.innerType,p),a.ref=i.innerType;let m;try{m=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}f.default=m;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let m=f,h=e._zod.pattern;if(!h)throw new Error("Pattern not found in template literal");m.type="string",m.pattern=h.source;break}case"pipe":{let m=this.io==="input"?i.in._zod.def.type==="transform"?i.out:i.in:i.out;this.process(m,p),a.ref=m;break}case"readonly":{this.process(i.innerType,p),a.ref=i.innerType,f.readOnly=!0;break}case"promise":{this.process(i.innerType,p),a.ref=i.innerType;break}case"optional":{this.process(i.innerType,p),a.ref=i.innerType;break}case"lazy":{let m=e._zod.innerType;this.process(m,p),a.ref=m;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}default:}}}let l=this.metadataRegistry.get(e);return l&&Object.assign(a.schema,l),this.io==="input"&&_e(e)&&(delete a.schema.examples,delete a.schema.default),this.io==="input"&&a.schema._prefault&&((n=a.schema).default??(n.default=a.schema._prefault)),delete a.schema._prefault,this.seen.get(e).schema}emit(e,t){let n={cycles:t?.cycles??"ref",reused:t?.reused??"inline",external:t?.external??void 0},i=this.seen.get(e);if(!i)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=u=>{let p=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){let h=n.external.registry.get(u[0])?.id,v=n.external.uri??(w=>w);if(h)return{ref:v(h)};let b=u[1].defId??u[1].schema.id??`schema${this.counter++}`;return u[1].defId=b,{defId:b,ref:`${v("__shared")}#/${p}/${b}`}}if(u[1]===i)return{ref:"#"};let f=`#/${p}/`,m=u[1].schema.id??`__schema${this.counter++}`;return{defId:m,ref:f+m}},s=u=>{if(u[1].schema.$ref)return;let p=u[1],{ref:d,defId:f}=o(u);p.def={...p.schema},f&&(p.defId=f);let m=p.schema;for(let h in m)delete m[h];m.$ref=d};if(n.cycles==="throw")for(let u of this.seen.entries()){let p=u[1];if(p.cycle)throw new Error(`Cycle detected: #/${p.cycle?.join("/")}/<root>
|
|
85
|
+
|
|
86
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let u of this.seen.entries()){let p=u[1];if(e===u[0]){s(u);continue}if(n.external){let f=n.external.registry.get(u[0])?.id;if(e!==u[0]&&f){s(u);continue}}if(this.metadataRegistry.get(u[0])?.id){s(u);continue}if(p.cycle){s(u);continue}if(p.count>1&&n.reused==="ref"){s(u);continue}}let a=(u,p)=>{let d=this.seen.get(u),f=d.def??d.schema,m={...f};if(d.ref===null)return;let h=d.ref;if(d.ref=null,h){a(h,p);let v=this.seen.get(h).schema;v.$ref&&p.target==="draft-7"?(f.allOf=f.allOf??[],f.allOf.push(v)):(Object.assign(f,v),Object.assign(f,m))}d.isParent||this.override({zodSchema:u,jsonSchema:f,path:d.path??[]})};for(let u of[...this.seen.entries()].reverse())a(u[0],{target:this.target});let c={};if(this.target==="draft-2020-12"?c.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?c.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),n.external?.uri){let u=n.external.registry.get(e)?.id;if(!u)throw new Error("Schema is missing an `id` property");c.$id=n.external.uri(u)}Object.assign(c,i.def);let l=n.external?.defs??{};for(let u of this.seen.entries()){let p=u[1];p.def&&p.defId&&(l[p.defId]=p.def)}n.external||Object.keys(l).length>0&&(this.target==="draft-2020-12"?c.$defs=l:c.definitions=l);try{return JSON.parse(JSON.stringify(c))}catch{throw new Error("Error converting schema to JSON.")}}};function kl(r,e){if(r instanceof ui){let n=new Lo(e),i={};for(let a of r._idmap.entries()){let[c,l]=a;n.process(l)}let o={},s={registry:r,uri:e?.uri,defs:i};for(let a of r._idmap.entries()){let[c,l]=a;o[c]=n.emit(l,{...e,external:s})}if(Object.keys(i).length>0){let a=n.target==="draft-2020-12"?"$defs":"definitions";o.__shared={[a]:i}}return{schemas:o}}let t=new Lo(e);return t.process(r),t.emit(r,e)}function _e(r,e){let t=e??{seen:new Set};if(t.seen.has(r))return!1;t.seen.add(r);let i=r._zod.def;switch(i.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return _e(i.element,t);case"object":{for(let o in i.shape)if(_e(i.shape[o],t))return!0;return!1}case"union":{for(let o of i.options)if(_e(o,t))return!0;return!1}case"intersection":return _e(i.left,t)||_e(i.right,t);case"tuple":{for(let o of i.items)if(_e(o,t))return!0;return!!(i.rest&&_e(i.rest,t))}case"record":return _e(i.keyType,t)||_e(i.valueType,t);case"map":return _e(i.keyType,t)||_e(i.valueType,t);case"set":return _e(i.valueType,t);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return _e(i.innerType,t);case"lazy":return _e(i.getter(),t);case"default":return _e(i.innerType,t);case"prefault":return _e(i.innerType,t);case"custom":return!1;case"transform":return!0;case"pipe":return _e(i.in,t)||_e(i.out,t);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${i.type}`)}var Y0=y("ZodMiniType",(r,e)=>{if(!r._zod)throw new Error("Uninitialized schema in ZodMiniType.");ne.init(r,e),r.def=e,r.parse=(t,n)=>Za(r,t,n,{callee:r.parse}),r.safeParse=(t,n)=>Ur(r,t,n),r.parseAsync=async(t,n)=>Fa(r,t,n,{callee:r.parseAsync}),r.safeParseAsync=async(t,n)=>Fr(r,t,n),r.check=(...t)=>r.clone({...e,checks:[...e.checks??[],...t.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),r.clone=(t,n)=>Je(r,t,n),r.brand=()=>r,r.register=(t,n)=>(t.add(r,n),r)});var ek=y("ZodMiniObject",(r,e)=>{Ro.init(r,e),Y0.init(r,e),G.defineLazy(r,"shape",()=>e.shape)});function Sl(r,e){let t={type:"object",get shape(){return G.assignProp(this,"shape",{...r}),this.shape},...G.normalizeParams(e)};return new ek(t)}function it(r){return!!r._zod}function Vr(r){let e=Object.values(r);if(e.length===0)return Sl({});let t=e.every(it),n=e.every(i=>!it(i));if(t)return Sl(r);if(n)return Ta(r);throw new Error("Mixed Zod versions detected in object shape.")}function ar(r,e){return it(r)?Ur(r,e):r.safeParse(e)}async function Do(r,e){return it(r)?await Fr(r,e):await r.safeParseAsync(e)}function cr(r){if(!r)return;let e;if(it(r)?e=r._zod?.def?.shape:e=r.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Sn(r){if(r){if(typeof r=="object"){let e=r,t=r;if(!e._def&&!t._zod){let n=Object.values(r);if(n.length>0&&n.every(i=>typeof i=="object"&&i!==null&&(i._def!==void 0||i._zod!==void 0||typeof i.parse=="function")))return Vr(r)}}if(it(r)){let t=r._zod?.def;if(t&&(t.type==="object"||t.shape!==void 0))return r}else if(r.shape!==void 0)return r}}function qo(r){if(r&&typeof r=="object"){if("message"in r&&typeof r.message=="string")return r.message;if("issues"in r&&Array.isArray(r.issues)&&r.issues.length>0){let e=r.issues[0];if(e&&typeof e=="object"&&"message"in e)return String(e.message)}try{return JSON.stringify(r)}catch{return String(r)}}return String(r)}function Uf(r){return r.description}function Ff(r){if(it(r))return r._zod?.def?.type==="optional";let e=r;return typeof r.isOptional=="function"?r.isOptional():e._def?.typeName==="ZodOptional"}function Zo(r){if(it(r)){let o=r._zod?.def;if(o){if(o.value!==void 0)return o.value;if(Array.isArray(o.values)&&o.values.length>0)return o.values[0]}}let t=r._def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}let n=r.value;if(n!==void 0)return n}var mi={};wa(mi,{ZodISODate:()=>Bf,ZodISODateTime:()=>Hf,ZodISODuration:()=>Wf,ZodISOTime:()=>Vf,date:()=>$l,datetime:()=>El,duration:()=>zl,time:()=>Tl});var Hf=y("ZodISODateTime",(r,e)=>{Pf.init(r,e),fe.init(r,e)});function El(r){return jf(Hf,r)}var Bf=y("ZodISODate",(r,e)=>{Rf.init(r,e),fe.init(r,e)});function $l(r){return Mf(Bf,r)}var Vf=y("ZodISOTime",(r,e)=>{Cf.init(r,e),fe.init(r,e)});function Tl(r){return Lf(Vf,r)}var Wf=y("ZodISODuration",(r,e)=>{If.init(r,e),fe.init(r,e)});function zl(r){return Df(Wf,r)}var Gf=(r,e)=>{Eo.init(r,e),r.name="ZodError",Object.defineProperties(r,{format:{value:t=>Da(r,t)},flatten:{value:t=>La(r,t)},addIssue:{value:t=>r.issues.push(t)},addIssues:{value:t=>r.issues.push(...t)},isEmpty:{get(){return r.issues.length===0}}})},lj=y("ZodError",Gf),fi=y("ZodError",Gf,{Parent:Error});var Kf=qa(fi),Jf=Ua(fi),Xf=Ha(fi),Qf=Ba(fi);var xe=y("ZodType",(r,e)=>(ne.init(r,e),r.def=e,Object.defineProperty(r,"_def",{value:e}),r.check=(...t)=>r.clone({...e,checks:[...e.checks??[],...t.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),r.clone=(t,n)=>Je(r,t,n),r.brand=()=>r,r.register=(t,n)=>(t.add(r,n),r),r.parse=(t,n)=>Kf(r,t,n,{callee:r.parse}),r.safeParse=(t,n)=>Xf(r,t,n),r.parseAsync=async(t,n)=>Jf(r,t,n,{callee:r.parseAsync}),r.safeParseAsync=async(t,n)=>Qf(r,t,n),r.spa=r.safeParseAsync,r.refine=(t,n)=>r.check(Xk(t,n)),r.superRefine=t=>r.check(Qk(t)),r.overwrite=t=>r.check(Hr(t)),r.optional=()=>ge(r),r.nullable=()=>th(r),r.nullish=()=>ge(th(r)),r.nonoptional=t=>Hk(r,t),r.array=()=>K(r),r.or=t=>pe([r,t]),r.and=t=>Fo(r,t),r.transform=t=>Rl(r,ah(t)),r.default=t=>Zk(r,t),r.prefault=t=>Fk(r,t),r.catch=t=>Vk(r,t),r.pipe=t=>Rl(r,t),r.readonly=()=>Kk(r),r.describe=t=>{let n=r.clone();return sr.add(n,{description:t}),n},Object.defineProperty(r,"description",{get(){return sr.get(r)?.description},configurable:!0}),r.meta=(...t)=>{if(t.length===0)return sr.get(r);let n=r.clone();return sr.add(n,t[0]),n},r.isOptional=()=>r.safeParse(void 0).success,r.isNullable=()=>r.safeParse(null).success,r)),rh=y("_ZodString",(r,e)=>{li.init(r,e),xe.init(r,e);let t=r._zod.bag;r.format=t.format??null,r.minLength=t.minimum??null,r.maxLength=t.maximum??null,r.regex=(...n)=>r.check(pl(...n)),r.includes=(...n)=>r.check(fl(...n)),r.startsWith=(...n)=>r.check(hl(...n)),r.endsWith=(...n)=>r.check(gl(...n)),r.min=(...n)=>r.check(kn(...n)),r.max=(...n)=>r.check(jo(...n)),r.length=(...n)=>r.check(Mo(...n)),r.nonempty=(...n)=>r.check(kn(1,...n)),r.lowercase=n=>r.check(dl(n)),r.uppercase=n=>r.check(ml(n)),r.trim=()=>r.check(xl()),r.normalize=(...n)=>r.check(vl(...n)),r.toLowerCase=()=>r.check(yl()),r.toUpperCase=()=>r.check(_l())}),lk=y("ZodString",(r,e)=>{li.init(r,e),rh.init(r,e),r.email=t=>r.check(Lc(uk,t)),r.url=t=>r.check(Fc(pk,t)),r.jwt=t=>r.check(il($k,t)),r.emoji=t=>r.check(Hc(dk,t)),r.guid=t=>r.check(Io(Yf,t)),r.uuid=t=>r.check(Dc(Uo,t)),r.uuidv4=t=>r.check(qc(Uo,t)),r.uuidv6=t=>r.check(Zc(Uo,t)),r.uuidv7=t=>r.check(Uc(Uo,t)),r.nanoid=t=>r.check(Bc(mk,t)),r.guid=t=>r.check(Io(Yf,t)),r.cuid=t=>r.check(Vc(fk,t)),r.cuid2=t=>r.check(Wc(hk,t)),r.ulid=t=>r.check(Gc(gk,t)),r.base64=t=>r.check(tl(kk,t)),r.base64url=t=>r.check(rl(Sk,t)),r.xid=t=>r.check(Kc(vk,t)),r.ksuid=t=>r.check(Jc(xk,t)),r.ipv4=t=>r.check(Xc(yk,t)),r.ipv6=t=>r.check(Qc(_k,t)),r.cidrv4=t=>r.check(Yc(bk,t)),r.cidrv6=t=>r.check(el(wk,t)),r.e164=t=>r.check(nl(Ek,t)),r.datetime=t=>r.check(El(t)),r.date=t=>r.check($l(t)),r.time=t=>r.check(Tl(t)),r.duration=t=>r.check(zl(t))});function x(r){return Mc(lk,r)}var fe=y("ZodStringFormat",(r,e)=>{le.init(r,e),rh.init(r,e)}),uk=y("ZodEmail",(r,e)=>{Ya.init(r,e),fe.init(r,e)});var Yf=y("ZodGUID",(r,e)=>{Xa.init(r,e),fe.init(r,e)});var Uo=y("ZodUUID",(r,e)=>{Qa.init(r,e),fe.init(r,e)});var pk=y("ZodURL",(r,e)=>{ec.init(r,e),fe.init(r,e)});var dk=y("ZodEmoji",(r,e)=>{tc.init(r,e),fe.init(r,e)});var mk=y("ZodNanoID",(r,e)=>{rc.init(r,e),fe.init(r,e)});var fk=y("ZodCUID",(r,e)=>{nc.init(r,e),fe.init(r,e)});var hk=y("ZodCUID2",(r,e)=>{ic.init(r,e),fe.init(r,e)});var gk=y("ZodULID",(r,e)=>{oc.init(r,e),fe.init(r,e)});var vk=y("ZodXID",(r,e)=>{sc.init(r,e),fe.init(r,e)});var xk=y("ZodKSUID",(r,e)=>{ac.init(r,e),fe.init(r,e)});var yk=y("ZodIPv4",(r,e)=>{cc.init(r,e),fe.init(r,e)});var _k=y("ZodIPv6",(r,e)=>{lc.init(r,e),fe.init(r,e)});var bk=y("ZodCIDRv4",(r,e)=>{uc.init(r,e),fe.init(r,e)});var wk=y("ZodCIDRv6",(r,e)=>{pc.init(r,e),fe.init(r,e)});var kk=y("ZodBase64",(r,e)=>{dc.init(r,e),fe.init(r,e)});var Sk=y("ZodBase64URL",(r,e)=>{mc.init(r,e),fe.init(r,e)});var Ek=y("ZodE164",(r,e)=>{fc.init(r,e),fe.init(r,e)});var $k=y("ZodJWT",(r,e)=>{hc.init(r,e),fe.init(r,e)});var nh=y("ZodNumber",(r,e)=>{Po.init(r,e),xe.init(r,e),r.gt=(n,i)=>r.check(Oo(n,i)),r.gte=(n,i)=>r.check(di(n,i)),r.min=(n,i)=>r.check(di(n,i)),r.lt=(n,i)=>r.check(Ao(n,i)),r.lte=(n,i)=>r.check(pi(n,i)),r.max=(n,i)=>r.check(pi(n,i)),r.int=n=>r.check(eh(n)),r.safe=n=>r.check(eh(n)),r.positive=n=>r.check(Oo(0,n)),r.nonnegative=n=>r.check(di(0,n)),r.negative=n=>r.check(Ao(0,n)),r.nonpositive=n=>r.check(pi(0,n)),r.multipleOf=(n,i)=>r.check(No(n,i)),r.step=(n,i)=>r.check(No(n,i)),r.finite=()=>r;let t=r._zod.bag;r.minValue=Math.max(t.minimum??Number.NEGATIVE_INFINITY,t.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,r.maxValue=Math.min(t.maximum??Number.POSITIVE_INFINITY,t.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,r.isInt=(t.format??"").includes("int")||Number.isSafeInteger(t.multipleOf??.5),r.isFinite=!0,r.format=t.format??null});function te(r){return ol(nh,r)}var Tk=y("ZodNumberFormat",(r,e)=>{gc.init(r,e),nh.init(r,e)});function eh(r){return sl(Tk,r)}var zk=y("ZodBoolean",(r,e)=>{vc.init(r,e),xe.init(r,e)});function we(r){return al(zk,r)}var Pk=y("ZodNull",(r,e)=>{xc.init(r,e),xe.init(r,e)});function ih(r){return cl(Pk,r)}var Rk=y("ZodUnknown",(r,e)=>{yc.init(r,e),xe.init(r,e)});function he(){return ll(Rk)}var Ck=y("ZodNever",(r,e)=>{_c.init(r,e),xe.init(r,e)});function Ik(r){return ul(Ck,r)}var Ak=y("ZodArray",(r,e)=>{bc.init(r,e),xe.init(r,e),r.element=e.element,r.min=(t,n)=>r.check(kn(t,n)),r.nonempty=t=>r.check(kn(1,t)),r.max=(t,n)=>r.check(jo(t,n)),r.length=(t,n)=>r.check(Mo(t,n)),r.unwrap=()=>r.element});function K(r,e){return qf(Ak,r,e)}var oh=y("ZodObject",(r,e)=>{Ro.init(r,e),xe.init(r,e),G.defineLazy(r,"shape",()=>e.shape),r.keyof=()=>He(Object.keys(r._zod.def.shape)),r.catchall=t=>r.clone({...r._zod.def,catchall:t}),r.passthrough=()=>r.clone({...r._zod.def,catchall:he()}),r.loose=()=>r.clone({...r._zod.def,catchall:he()}),r.strict=()=>r.clone({...r._zod.def,catchall:Ik()}),r.strip=()=>r.clone({...r._zod.def,catchall:void 0}),r.extend=t=>G.extend(r,t),r.merge=t=>G.merge(r,t),r.pick=t=>G.pick(r,t),r.omit=t=>G.omit(r,t),r.partial=(...t)=>G.partial(ch,r,t[0]),r.required=(...t)=>G.required(lh,r,t[0])});function z(r,e){let t={type:"object",get shape(){return G.assignProp(this,"shape",{...r}),this.shape},...G.normalizeParams(e)};return new oh(t)}function je(r,e){return new oh({type:"object",get shape(){return G.assignProp(this,"shape",{...r}),this.shape},catchall:he(),...G.normalizeParams(e)})}var sh=y("ZodUnion",(r,e)=>{Co.init(r,e),xe.init(r,e),r.options=e.options});function pe(r,e){return new sh({type:"union",options:r,...G.normalizeParams(e)})}var Ok=y("ZodDiscriminatedUnion",(r,e)=>{sh.init(r,e),wc.init(r,e)});function Cl(r,e,t){return new Ok({type:"union",options:e,discriminator:r,...G.normalizeParams(t)})}var Nk=y("ZodIntersection",(r,e)=>{kc.init(r,e),xe.init(r,e)});function Fo(r,e){return new Nk({type:"intersection",left:r,right:e})}var jk=y("ZodRecord",(r,e)=>{Sc.init(r,e),xe.init(r,e),r.keyType=e.keyType,r.valueType=e.valueType});function ue(r,e,t){return new jk({type:"record",keyType:r,valueType:e,...G.normalizeParams(t)})}var Pl=y("ZodEnum",(r,e)=>{Ec.init(r,e),xe.init(r,e),r.enum=e.entries,r.options=Object.values(e.entries);let t=new Set(Object.keys(e.entries));r.extract=(n,i)=>{let o={};for(let s of n)if(t.has(s))o[s]=e.entries[s];else throw new Error(`Key ${s} not found in enum`);return new Pl({...e,checks:[],...G.normalizeParams(i),entries:o})},r.exclude=(n,i)=>{let o={...e.entries};for(let s of n)if(t.has(s))delete o[s];else throw new Error(`Key ${s} not found in enum`);return new Pl({...e,checks:[],...G.normalizeParams(i),entries:o})}});function He(r,e){let t=Array.isArray(r)?Object.fromEntries(r.map(n=>[n,n])):r;return new Pl({type:"enum",entries:t,...G.normalizeParams(e)})}var Mk=y("ZodLiteral",(r,e)=>{$c.init(r,e),xe.init(r,e),r.values=new Set(e.values),Object.defineProperty(r,"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(r,e){return new Mk({type:"literal",values:Array.isArray(r)?r:[r],...G.normalizeParams(e)})}var Lk=y("ZodTransform",(r,e)=>{Tc.init(r,e),xe.init(r,e),r._zod.parse=(t,n)=>{t.addIssue=o=>{if(typeof o=="string")t.issues.push(G.issue(o,t.value,e));else{let s=o;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=t.value),s.inst??(s.inst=r),s.continue??(s.continue=!0),t.issues.push(G.issue(s))}};let i=e.transform(t.value,t);return i instanceof Promise?i.then(o=>(t.value=o,t)):(t.value=i,t)}});function ah(r){return new Lk({type:"transform",transform:r})}var ch=y("ZodOptional",(r,e)=>{zc.init(r,e),xe.init(r,e),r.unwrap=()=>r._zod.def.innerType});function ge(r){return new ch({type:"optional",innerType:r})}var Dk=y("ZodNullable",(r,e)=>{Pc.init(r,e),xe.init(r,e),r.unwrap=()=>r._zod.def.innerType});function th(r){return new Dk({type:"nullable",innerType:r})}var qk=y("ZodDefault",(r,e)=>{Rc.init(r,e),xe.init(r,e),r.unwrap=()=>r._zod.def.innerType,r.removeDefault=r.unwrap});function Zk(r,e){return new qk({type:"default",innerType:r,get defaultValue(){return typeof e=="function"?e():e}})}var Uk=y("ZodPrefault",(r,e)=>{Cc.init(r,e),xe.init(r,e),r.unwrap=()=>r._zod.def.innerType});function Fk(r,e){return new Uk({type:"prefault",innerType:r,get defaultValue(){return typeof e=="function"?e():e}})}var lh=y("ZodNonOptional",(r,e)=>{Ic.init(r,e),xe.init(r,e),r.unwrap=()=>r._zod.def.innerType});function Hk(r,e){return new lh({type:"nonoptional",innerType:r,...G.normalizeParams(e)})}var Bk=y("ZodCatch",(r,e)=>{Ac.init(r,e),xe.init(r,e),r.unwrap=()=>r._zod.def.innerType,r.removeCatch=r.unwrap});function Vk(r,e){return new Bk({type:"catch",innerType:r,catchValue:typeof e=="function"?e:()=>e})}var Wk=y("ZodPipe",(r,e)=>{Oc.init(r,e),xe.init(r,e),r.in=e.in,r.out=e.out});function Rl(r,e){return new Wk({type:"pipe",in:r,out:e})}var Gk=y("ZodReadonly",(r,e)=>{Nc.init(r,e),xe.init(r,e)});function Kk(r){return new Gk({type:"readonly",innerType:r})}var uh=y("ZodCustom",(r,e)=>{jc.init(r,e),xe.init(r,e)});function Jk(r){let e=new $e({check:"custom"});return e._zod.check=r,e}function ph(r,e){return bl(uh,r??(()=>!0),e)}function Xk(r,e={}){return wl(uh,r,e)}function Qk(r){let e=Jk(t=>(t.addIssue=n=>{if(typeof n=="string")t.issues.push(G.issue(n,t.value,e._zod.def));else{let i=n;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=t.value),i.inst??(i.inst=e),i.continue??(i.continue=!e._zod.def.abort),t.issues.push(G.issue(i))}},r(t.value,t)));return e}function Il(r,e){return Rl(ah(r),e)}Ke(Of());var Ol="2025-11-25";var dh=[Ol,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],lr="io.modelcontextprotocol/related-task",Bo="2.0",be=ph(r=>r!==null&&(typeof r=="object"||typeof r=="function")),mh=pe([x(),te().int()]),fh=x(),kj=je({ttl:te().optional(),pollInterval:te().optional()}),Yk=z({ttl:te().optional()}),eS=z({taskId:x()}),Nl=je({progressToken:mh.optional(),[lr]:eS.optional()}),Xe=z({_meta:Nl.optional()}),hi=Xe.extend({task:Yk.optional()}),hh=r=>hi.safeParse(r).success,Te=z({method:x(),params:Xe.loose().optional()}),ot=z({_meta:Nl.optional()}),st=z({method:x(),params:ot.loose().optional()}),ze=je({_meta:Nl.optional()}),Vo=pe([x(),te().int()]),gh=z({jsonrpc:I(Bo),id:Vo,...Te.shape}).strict(),jl=r=>gh.safeParse(r).success,vh=z({jsonrpc:I(Bo),...st.shape}).strict(),xh=r=>vh.safeParse(r).success,Ml=z({jsonrpc:I(Bo),id:Vo,result:ze}).strict(),gi=r=>Ml.safeParse(r).success;var O;(function(r){r[r.ConnectionClosed=-32e3]="ConnectionClosed",r[r.RequestTimeout=-32001]="RequestTimeout",r[r.ParseError=-32700]="ParseError",r[r.InvalidRequest=-32600]="InvalidRequest",r[r.MethodNotFound=-32601]="MethodNotFound",r[r.InvalidParams=-32602]="InvalidParams",r[r.InternalError=-32603]="InternalError",r[r.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(O||(O={}));var Ll=z({jsonrpc:I(Bo),id:Vo.optional(),error:z({code:te().int(),message:x(),data:he().optional()})}).strict();var yh=r=>Ll.safeParse(r).success;var _h=pe([gh,vh,Ml,Ll]),Sj=pe([Ml,Ll]),Wo=ze.strict(),tS=ot.extend({requestId:Vo.optional(),reason:x().optional()}),Go=st.extend({method:I("notifications/cancelled"),params:tS}),rS=z({src:x(),mimeType:x().optional(),sizes:K(x()).optional(),theme:He(["light","dark"]).optional()}),vi=z({icons:K(rS).optional()}),En=z({name:x(),title:x().optional()}),bh=En.extend({...En.shape,...vi.shape,version:x(),websiteUrl:x().optional(),description:x().optional()}),nS=Fo(z({applyDefaults:we().optional()}),ue(x(),he())),iS=Il(r=>r&&typeof r=="object"&&!Array.isArray(r)&&Object.keys(r).length===0?{form:{}}:r,Fo(z({form:nS.optional(),url:be.optional()}),ue(x(),he()).optional())),oS=je({list:be.optional(),cancel:be.optional(),requests:je({sampling:je({createMessage:be.optional()}).optional(),elicitation:je({create:be.optional()}).optional()}).optional()}),sS=je({list:be.optional(),cancel:be.optional(),requests:je({tools:je({call:be.optional()}).optional()}).optional()}),aS=z({experimental:ue(x(),be).optional(),sampling:z({context:be.optional(),tools:be.optional()}).optional(),elicitation:iS.optional(),roots:z({listChanged:we().optional()}).optional(),tasks:oS.optional(),extensions:ue(x(),be).optional()}),cS=Xe.extend({protocolVersion:x(),capabilities:aS,clientInfo:bh}),Dl=Te.extend({method:I("initialize"),params:cS});var lS=z({experimental:ue(x(),be).optional(),logging:be.optional(),completions:be.optional(),prompts:z({listChanged:we().optional()}).optional(),resources:z({subscribe:we().optional(),listChanged:we().optional()}).optional(),tools:z({listChanged:we().optional()}).optional(),tasks:sS.optional(),extensions:ue(x(),be).optional()}),uS=ze.extend({protocolVersion:x(),capabilities:lS,serverInfo:bh,instructions:x().optional()}),ql=st.extend({method:I("notifications/initialized"),params:ot.optional()});var Ko=Te.extend({method:I("ping"),params:Xe.optional()}),pS=z({progress:te(),total:ge(te()),message:ge(x())}),dS=z({...ot.shape,...pS.shape,progressToken:mh}),Jo=st.extend({method:I("notifications/progress"),params:dS}),mS=Xe.extend({cursor:fh.optional()}),xi=Te.extend({params:mS.optional()}),yi=ze.extend({nextCursor:fh.optional()}),fS=He(["working","input_required","completed","failed","cancelled"]),_i=z({taskId:x(),status:fS,ttl:pe([te(),ih()]),createdAt:x(),lastUpdatedAt:x(),pollInterval:ge(te()),statusMessage:ge(x())}),$n=ze.extend({task:_i}),hS=ot.merge(_i),bi=st.extend({method:I("notifications/tasks/status"),params:hS}),Xo=Te.extend({method:I("tasks/get"),params:Xe.extend({taskId:x()})}),Qo=ze.merge(_i),Yo=Te.extend({method:I("tasks/result"),params:Xe.extend({taskId:x()})}),Ej=ze.loose(),es=xi.extend({method:I("tasks/list")}),ts=yi.extend({tasks:K(_i)}),rs=Te.extend({method:I("tasks/cancel"),params:Xe.extend({taskId:x()})}),wh=ze.merge(_i),kh=z({uri:x(),mimeType:ge(x()),_meta:ue(x(),he()).optional()}),Sh=kh.extend({text:x()}),Zl=x().refine(r=>{try{return atob(r),!0}catch{return!1}},{message:"Invalid Base64 string"}),Eh=kh.extend({blob:Zl}),wi=He(["user","assistant"]),Tn=z({audience:K(wi).optional(),priority:te().min(0).max(1).optional(),lastModified:mi.datetime({offset:!0}).optional()}),$h=z({...En.shape,...vi.shape,uri:x(),description:ge(x()),mimeType:ge(x()),size:ge(te()),annotations:Tn.optional(),_meta:ge(je({}))}),gS=z({...En.shape,...vi.shape,uriTemplate:x(),description:ge(x()),mimeType:ge(x()),annotations:Tn.optional(),_meta:ge(je({}))}),ns=xi.extend({method:I("resources/list")}),vS=yi.extend({resources:K($h)}),is=xi.extend({method:I("resources/templates/list")}),xS=yi.extend({resourceTemplates:K(gS)}),Ul=Xe.extend({uri:x()}),yS=Ul,os=Te.extend({method:I("resources/read"),params:yS}),_S=ze.extend({contents:K(pe([Sh,Eh]))}),bS=st.extend({method:I("notifications/resources/list_changed"),params:ot.optional()}),wS=Ul,kS=Te.extend({method:I("resources/subscribe"),params:wS}),SS=Ul,ES=Te.extend({method:I("resources/unsubscribe"),params:SS}),$S=ot.extend({uri:x()}),TS=st.extend({method:I("notifications/resources/updated"),params:$S}),zS=z({name:x(),description:ge(x()),required:ge(we())}),PS=z({...En.shape,...vi.shape,description:ge(x()),arguments:ge(K(zS)),_meta:ge(je({}))}),ss=xi.extend({method:I("prompts/list")}),RS=yi.extend({prompts:K(PS)}),CS=Xe.extend({name:x(),arguments:ue(x(),x()).optional()}),as=Te.extend({method:I("prompts/get"),params:CS}),Fl=z({type:I("text"),text:x(),annotations:Tn.optional(),_meta:ue(x(),he()).optional()}),Hl=z({type:I("image"),data:Zl,mimeType:x(),annotations:Tn.optional(),_meta:ue(x(),he()).optional()}),Bl=z({type:I("audio"),data:Zl,mimeType:x(),annotations:Tn.optional(),_meta:ue(x(),he()).optional()}),IS=z({type:I("tool_use"),name:x(),id:x(),input:ue(x(),he()),_meta:ue(x(),he()).optional()}),AS=z({type:I("resource"),resource:pe([Sh,Eh]),annotations:Tn.optional(),_meta:ue(x(),he()).optional()}),OS=$h.extend({type:I("resource_link")}),Vl=pe([Fl,Hl,Bl,OS,AS]),NS=z({role:wi,content:Vl}),jS=ze.extend({description:x().optional(),messages:K(NS)}),MS=st.extend({method:I("notifications/prompts/list_changed"),params:ot.optional()}),LS=z({title:x().optional(),readOnlyHint:we().optional(),destructiveHint:we().optional(),idempotentHint:we().optional(),openWorldHint:we().optional()}),DS=z({taskSupport:He(["required","optional","forbidden"]).optional()}),Th=z({...En.shape,...vi.shape,description:x().optional(),inputSchema:z({type:I("object"),properties:ue(x(),be).optional(),required:K(x()).optional()}).catchall(he()),outputSchema:z({type:I("object"),properties:ue(x(),be).optional(),required:K(x()).optional()}).catchall(he()).optional(),annotations:LS.optional(),execution:DS.optional(),_meta:ue(x(),he()).optional()}),cs=xi.extend({method:I("tools/list")}),qS=yi.extend({tools:K(Th)}),ls=ze.extend({content:K(Vl).default([]),structuredContent:ue(x(),he()).optional(),isError:we().optional()}),$j=ls.or(ze.extend({toolResult:he()})),ZS=hi.extend({name:x(),arguments:ue(x(),he()).optional()}),zn=Te.extend({method:I("tools/call"),params:ZS}),US=st.extend({method:I("notifications/tools/list_changed"),params:ot.optional()}),Tj=z({autoRefresh:we().default(!0),debounceMs:te().int().nonnegative().default(300)}),ki=He(["debug","info","notice","warning","error","critical","alert","emergency"]),FS=Xe.extend({level:ki}),Wl=Te.extend({method:I("logging/setLevel"),params:FS}),HS=ot.extend({level:ki,logger:x().optional(),data:he()}),BS=st.extend({method:I("notifications/message"),params:HS}),VS=z({name:x().optional()}),WS=z({hints:K(VS).optional(),costPriority:te().min(0).max(1).optional(),speedPriority:te().min(0).max(1).optional(),intelligencePriority:te().min(0).max(1).optional()}),GS=z({mode:He(["auto","required","none"]).optional()}),KS=z({type:I("tool_result"),toolUseId:x().describe("The unique identifier for the corresponding tool call."),content:K(Vl).default([]),structuredContent:z({}).loose().optional(),isError:we().optional(),_meta:ue(x(),he()).optional()}),JS=Cl("type",[Fl,Hl,Bl]),Ho=Cl("type",[Fl,Hl,Bl,IS,KS]),XS=z({role:wi,content:pe([Ho,K(Ho)]),_meta:ue(x(),he()).optional()}),QS=hi.extend({messages:K(XS),modelPreferences:WS.optional(),systemPrompt:x().optional(),includeContext:He(["none","thisServer","allServers"]).optional(),temperature:te().optional(),maxTokens:te().int(),stopSequences:K(x()).optional(),metadata:be.optional(),tools:K(Th).optional(),toolChoice:GS.optional()}),YS=Te.extend({method:I("sampling/createMessage"),params:QS}),Si=ze.extend({model:x(),stopReason:ge(He(["endTurn","stopSequence","maxTokens"]).or(x())),role:wi,content:JS}),Gl=ze.extend({model:x(),stopReason:ge(He(["endTurn","stopSequence","maxTokens","toolUse"]).or(x())),role:wi,content:pe([Ho,K(Ho)])}),eE=z({type:I("boolean"),title:x().optional(),description:x().optional(),default:we().optional()}),tE=z({type:I("string"),title:x().optional(),description:x().optional(),minLength:te().optional(),maxLength:te().optional(),format:He(["email","uri","date","date-time"]).optional(),default:x().optional()}),rE=z({type:He(["number","integer"]),title:x().optional(),description:x().optional(),minimum:te().optional(),maximum:te().optional(),default:te().optional()}),nE=z({type:I("string"),title:x().optional(),description:x().optional(),enum:K(x()),default:x().optional()}),iE=z({type:I("string"),title:x().optional(),description:x().optional(),oneOf:K(z({const:x(),title:x()})),default:x().optional()}),oE=z({type:I("string"),title:x().optional(),description:x().optional(),enum:K(x()),enumNames:K(x()).optional(),default:x().optional()}),sE=pe([nE,iE]),aE=z({type:I("array"),title:x().optional(),description:x().optional(),minItems:te().optional(),maxItems:te().optional(),items:z({type:I("string"),enum:K(x())}),default:K(x()).optional()}),cE=z({type:I("array"),title:x().optional(),description:x().optional(),minItems:te().optional(),maxItems:te().optional(),items:z({anyOf:K(z({const:x(),title:x()}))}),default:K(x()).optional()}),lE=pe([aE,cE]),uE=pe([oE,sE,lE]),pE=pe([uE,eE,tE,rE]),dE=hi.extend({mode:I("form").optional(),message:x(),requestedSchema:z({type:I("object"),properties:ue(x(),pE),required:K(x()).optional()})}),mE=hi.extend({mode:I("url"),message:x(),elicitationId:x(),url:x().url()}),fE=pe([dE,mE]),hE=Te.extend({method:I("elicitation/create"),params:fE}),gE=ot.extend({elicitationId:x()}),vE=st.extend({method:I("notifications/elicitation/complete"),params:gE}),Pn=ze.extend({action:He(["accept","decline","cancel"]),content:Il(r=>r===null?void 0:r,ue(x(),pe([x(),te(),we(),K(x())])).optional())}),xE=z({type:I("ref/resource"),uri:x()});var yE=z({type:I("ref/prompt"),name:x()}),_E=Xe.extend({ref:pe([yE,xE]),argument:z({name:x(),value:x()}),context:z({arguments:ue(x(),x()).optional()}).optional()}),us=Te.extend({method:I("completion/complete"),params:_E});function zh(r){if(r.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${r.params.ref.type}`)}function Ph(r){if(r.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${r.params.ref.type}`)}var bE=ze.extend({completion:je({values:K(x()).max(100),total:ge(te().int()),hasMore:ge(we())})}),wE=z({uri:x().startsWith("file://"),name:x().optional(),_meta:ue(x(),he()).optional()}),kE=Te.extend({method:I("roots/list"),params:Xe.optional()}),Kl=ze.extend({roots:K(wE)}),SE=st.extend({method:I("notifications/roots/list_changed"),params:ot.optional()}),zj=pe([Ko,Dl,us,Wl,as,ss,ns,is,os,kS,ES,zn,cs,Xo,Yo,es,rs]),Pj=pe([Go,Jo,ql,SE,bi]),Rj=pe([Wo,Si,Gl,Pn,Kl,Qo,ts,$n]),Cj=pe([Ko,YS,hE,kE,Xo,Yo,es,rs]),Ij=pe([Go,Jo,BS,TS,bS,US,MS,bi,vE]),Aj=pe([Wo,uS,bE,jS,RS,vS,xS,_S,ls,qS,Qo,ts,$n]),C=class r extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,t,n){if(e===O.UrlElicitationRequired&&n){let i=n;if(i.elicitations)return new Al(i.elicitations,t)}return new r(e,t,n)}},Al=class extends C{constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(O.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function ur(r){return r==="completed"||r==="failed"||r==="cancelled"}var Ch=Symbol("Let zodToJsonSchema decide on which parser to use");var Rh={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},Ih=r=>typeof r=="string"?{...Rh,name:r}:{...Rh,...r};var Ah=r=>{let e=Ih(r),t=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:t,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,i])=>[i._def,{def:i._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function Jl(r,e,t,n){n?.errorMessages&&t&&(r.errorMessage={...r.errorMessage,[e]:t})}function J(r,e,t,n,i){r[e]=t,Jl(r,e,n,i)}var ps=(r,e)=>{let t=0;for(;t<r.length&&t<e.length&&r[t]===e[t];t++);return[(r.length-t).toString(),...e.slice(t)].join("/")};function ve(r){if(r.target!=="openAi")return{};let e=[...r.basePath,r.definitionPath,r.openAiAnyTypeName];return r.flags.hasReferencedOpenAiAnyType=!0,{$ref:r.$refStrategy==="relative"?ps(e,r.currentPath):e.join("/")}}function Oh(r,e){let t={type:"array"};return r.type?._def&&r.type?._def?.typeName!==S.ZodAny&&(t.items=D(r.type._def,{...e,currentPath:[...e.currentPath,"items"]})),r.minLength&&J(t,"minItems",r.minLength.value,r.minLength.message,e),r.maxLength&&J(t,"maxItems",r.maxLength.value,r.maxLength.message,e),r.exactLength&&(J(t,"minItems",r.exactLength.value,r.exactLength.message,e),J(t,"maxItems",r.exactLength.value,r.exactLength.message,e)),t}function Nh(r,e){let t={type:"integer",format:"int64"};if(!r.checks)return t;for(let n of r.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?J(t,"minimum",n.value,n.message,e):J(t,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(t.exclusiveMinimum=!0),J(t,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?J(t,"maximum",n.value,n.message,e):J(t,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(t.exclusiveMaximum=!0),J(t,"maximum",n.value,n.message,e));break;case"multipleOf":J(t,"multipleOf",n.value,n.message,e);break}return t}function jh(){return{type:"boolean"}}function ds(r,e){return D(r.type._def,e)}var Mh=(r,e)=>D(r.innerType._def,e);function Xl(r,e,t){let n=t??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((i,o)=>Xl(r,e,i))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return EE(r,e)}}var EE=(r,e)=>{let t={type:"integer",format:"unix-time"};if(e.target==="openApi3")return t;for(let n of r.checks)switch(n.kind){case"min":J(t,"minimum",n.value,n.message,e);break;case"max":J(t,"maximum",n.value,n.message,e);break}return t};function Lh(r,e){return{...D(r.innerType._def,e),default:r.defaultValue()}}function Dh(r,e){return e.effectStrategy==="input"?D(r.schema._def,e):ve(e)}function qh(r){return{type:"string",enum:Array.from(r.values)}}var $E=r=>"type"in r&&r.type==="string"?!1:"allOf"in r;function Zh(r,e){let t=[D(r.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),D(r.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(o=>!!o),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,i=[];return t.forEach(o=>{if($E(o))i.push(...o.allOf),o.unevaluatedProperties===void 0&&(n=void 0);else{let s=o;if("additionalProperties"in o&&o.additionalProperties===!1){let{additionalProperties:a,...c}=o;s=c}else n=void 0;i.push(s)}}),i.length?{allOf:i,...n}:void 0}function Uh(r,e){let t=typeof r.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(r.value)?"array":"object"}:e.target==="openApi3"?{type:t==="bigint"?"integer":t,enum:[r.value]}:{type:t==="bigint"?"integer":t,const:r.value}}var Ql,ht={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Ql===void 0&&(Ql=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Ql),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?: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])$/,ipv4Cidr:/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function ms(r,e){let t={type:"string"};if(r.checks)for(let n of r.checks)switch(n.kind){case"min":J(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,n.value):n.value,n.message,e);break;case"max":J(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":gt(t,"email",n.message,e);break;case"format:idn-email":gt(t,"idn-email",n.message,e);break;case"pattern:zod":Me(t,ht.email,n.message,e);break}break;case"url":gt(t,"uri",n.message,e);break;case"uuid":gt(t,"uuid",n.message,e);break;case"regex":Me(t,n.regex,n.message,e);break;case"cuid":Me(t,ht.cuid,n.message,e);break;case"cuid2":Me(t,ht.cuid2,n.message,e);break;case"startsWith":Me(t,RegExp(`^${Yl(n.value,e)}`),n.message,e);break;case"endsWith":Me(t,RegExp(`${Yl(n.value,e)}$`),n.message,e);break;case"datetime":gt(t,"date-time",n.message,e);break;case"date":gt(t,"date",n.message,e);break;case"time":gt(t,"time",n.message,e);break;case"duration":gt(t,"duration",n.message,e);break;case"length":J(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,n.value):n.value,n.message,e),J(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,n.value):n.value,n.message,e);break;case"includes":{Me(t,RegExp(Yl(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&>(t,"ipv4",n.message,e),n.version!=="v4"&>(t,"ipv6",n.message,e);break}case"base64url":Me(t,ht.base64url,n.message,e);break;case"jwt":Me(t,ht.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&Me(t,ht.ipv4Cidr,n.message,e),n.version!=="v4"&&Me(t,ht.ipv6Cidr,n.message,e);break}case"emoji":Me(t,ht.emoji(),n.message,e);break;case"ulid":{Me(t,ht.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{gt(t,"binary",n.message,e);break}case"contentEncoding:base64":{J(t,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{Me(t,ht.base64,n.message,e);break}}break}case"nanoid":Me(t,ht.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return t}function Yl(r,e){return e.patternStrategy==="escape"?zE(r):r}var TE=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function zE(r){let e="";for(let t=0;t<r.length;t++)TE.has(r[t])||(e+="\\"),e+=r[t];return e}function gt(r,e,t,n){r.format||r.anyOf?.some(i=>i.format)?(r.anyOf||(r.anyOf=[]),r.format&&(r.anyOf.push({format:r.format,...r.errorMessage&&n.errorMessages&&{errorMessage:{format:r.errorMessage.format}}}),delete r.format,r.errorMessage&&(delete r.errorMessage.format,Object.keys(r.errorMessage).length===0&&delete r.errorMessage)),r.anyOf.push({format:e,...t&&n.errorMessages&&{errorMessage:{format:t}}})):J(r,"format",e,t,n)}function Me(r,e,t,n){r.pattern||r.allOf?.some(i=>i.pattern)?(r.allOf||(r.allOf=[]),r.pattern&&(r.allOf.push({pattern:r.pattern,...r.errorMessage&&n.errorMessages&&{errorMessage:{pattern:r.errorMessage.pattern}}}),delete r.pattern,r.errorMessage&&(delete r.errorMessage.pattern,Object.keys(r.errorMessage).length===0&&delete r.errorMessage)),r.allOf.push({pattern:Fh(e,n),...t&&n.errorMessages&&{errorMessage:{pattern:t}}})):J(r,"pattern",Fh(e,n),t,n)}function Fh(r,e){if(!e.applyRegexFlags||!r.flags)return r.source;let t={i:r.flags.includes("i"),m:r.flags.includes("m"),s:r.flags.includes("s")},n=t.i?r.source.toLowerCase():r.source,i="",o=!1,s=!1,a=!1;for(let c=0;c<n.length;c++){if(o){i+=n[c],o=!1;continue}if(t.i){if(s){if(n[c].match(/[a-z]/)){a?(i+=n[c],i+=`${n[c-2]}-${n[c]}`.toUpperCase(),a=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(i+=n[c],a=!0):i+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){i+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(t.m){if(n[c]==="^"){i+=`(^|(?<=[\r
|
|
87
|
+
]))`;continue}else if(n[c]==="$"){i+=`($|(?=[\r
|
|
88
|
+
]))`;continue}}if(t.s&&n[c]==="."){i+=s?`${n[c]}\r
|
|
89
|
+
`:`[${n[c]}\r
|
|
90
|
+
]`;continue}i+=n[c],n[c]==="\\"?o=!0:s&&n[c]==="]"?s=!1:!s&&n[c]==="["&&(s=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),r.source}return i}function fs(r,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&r.keyType?._def.typeName===S.ZodEnum)return{type:"object",required:r.keyType._def.values,properties:r.keyType._def.values.reduce((n,i)=>({...n,[i]:D(r.valueType._def,{...e,currentPath:[...e.currentPath,"properties",i]})??ve(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let t={type:"object",additionalProperties:D(r.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return t;if(r.keyType?._def.typeName===S.ZodString&&r.keyType._def.checks?.length){let{type:n,...i}=ms(r.keyType._def,e);return{...t,propertyNames:i}}else{if(r.keyType?._def.typeName===S.ZodEnum)return{...t,propertyNames:{enum:r.keyType._def.values}};if(r.keyType?._def.typeName===S.ZodBranded&&r.keyType._def.type._def.typeName===S.ZodString&&r.keyType._def.type._def.checks?.length){let{type:n,...i}=ds(r.keyType._def,e);return{...t,propertyNames:i}}}return t}function Hh(r,e){if(e.mapStrategy==="record")return fs(r,e);let t=D(r.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||ve(e),n=D(r.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||ve(e);return{type:"array",maxItems:125,items:{type:"array",items:[t,n],minItems:2,maxItems:2}}}function Bh(r){let e=r.values,n=Object.keys(r.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[o]),i=Array.from(new Set(n.map(o=>typeof o)));return{type:i.length===1?i[0]==="string"?"string":"number":["string","number"],enum:n}}function Vh(r){return r.target==="openAi"?void 0:{not:ve({...r,currentPath:[...r.currentPath,"not"]})}}function Wh(r){return r.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Ei={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Kh(r,e){if(e.target==="openApi3")return Gh(r,e);let t=r.options instanceof Map?Array.from(r.options.values()):r.options;if(t.every(n=>n._def.typeName in Ei&&(!n._def.checks||!n._def.checks.length))){let n=t.reduce((i,o)=>{let s=Ei[o._def.typeName];return s&&!i.includes(s)?[...i,s]:i},[]);return{type:n.length>1?n:n[0]}}else if(t.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=t.reduce((i,o)=>{let s=typeof o._def.value;switch(s){case"string":case"number":case"boolean":return[...i,s];case"bigint":return[...i,"integer"];case"object":if(o._def.value===null)return[...i,"null"];case"symbol":case"undefined":case"function":default:return i}},[]);if(n.length===t.length){let i=n.filter((o,s,a)=>a.indexOf(o)===s);return{type:i.length>1?i:i[0],enum:t.reduce((o,s)=>o.includes(s._def.value)?o:[...o,s._def.value],[])}}}else if(t.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:t.reduce((n,i)=>[...n,...i._def.values.filter(o=>!n.includes(o))],[])};return Gh(r,e)}var Gh=(r,e)=>{let t=(r.options instanceof Map?Array.from(r.options.values()):r.options).map((n,i)=>D(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${i}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return t.length?{anyOf:t}:void 0};function Jh(r,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(r.innerType._def.typeName)&&(!r.innerType._def.checks||!r.innerType._def.checks.length))return e.target==="openApi3"?{type:Ei[r.innerType._def.typeName],nullable:!0}:{type:[Ei[r.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=D(r.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let t=D(r.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return t&&{anyOf:[t,{type:"null"}]}}function Xh(r,e){let t={type:"number"};if(!r.checks)return t;for(let n of r.checks)switch(n.kind){case"int":t.type="integer",Jl(t,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?J(t,"minimum",n.value,n.message,e):J(t,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(t.exclusiveMinimum=!0),J(t,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?J(t,"maximum",n.value,n.message,e):J(t,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(t.exclusiveMaximum=!0),J(t,"maximum",n.value,n.message,e));break;case"multipleOf":J(t,"multipleOf",n.value,n.message,e);break}return t}function Qh(r,e){let t=e.target==="openAi",n={type:"object",properties:{}},i=[],o=r.shape();for(let a in o){let c=o[a];if(c===void 0||c._def===void 0)continue;let l=RE(c);l&&t&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),l=!1);let u=D(c._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});u!==void 0&&(n.properties[a]=u,l||i.push(a))}i.length&&(n.required=i);let s=PE(r,e);return s!==void 0&&(n.additionalProperties=s),n}function PE(r,e){if(r.catchall._def.typeName!=="ZodNever")return D(r.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(r.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function RE(r){try{return r.isOptional()}catch{return!0}}var Yh=(r,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return D(r.innerType._def,e);let t=D(r.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return t?{anyOf:[{not:ve(e)},t]}:ve(e)};var eg=(r,e)=>{if(e.pipeStrategy==="input")return D(r.in._def,e);if(e.pipeStrategy==="output")return D(r.out._def,e);let t=D(r.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=D(r.out._def,{...e,currentPath:[...e.currentPath,"allOf",t?"1":"0"]});return{allOf:[t,n].filter(i=>i!==void 0)}};function tg(r,e){return D(r.type._def,e)}function rg(r,e){let n={type:"array",uniqueItems:!0,items:D(r.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return r.minSize&&J(n,"minItems",r.minSize.value,r.minSize.message,e),r.maxSize&&J(n,"maxItems",r.maxSize.value,r.maxSize.message,e),n}function ng(r,e){return r.rest?{type:"array",minItems:r.items.length,items:r.items.map((t,n)=>D(t._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((t,n)=>n===void 0?t:[...t,n],[]),additionalItems:D(r.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:r.items.length,maxItems:r.items.length,items:r.items.map((t,n)=>D(t._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((t,n)=>n===void 0?t:[...t,n],[])}}function ig(r){return{not:ve(r)}}function og(r){return ve(r)}var sg=(r,e)=>D(r.innerType._def,e);var ag=(r,e,t)=>{switch(e){case S.ZodString:return ms(r,t);case S.ZodNumber:return Xh(r,t);case S.ZodObject:return Qh(r,t);case S.ZodBigInt:return Nh(r,t);case S.ZodBoolean:return jh();case S.ZodDate:return Xl(r,t);case S.ZodUndefined:return ig(t);case S.ZodNull:return Wh(t);case S.ZodArray:return Oh(r,t);case S.ZodUnion:case S.ZodDiscriminatedUnion:return Kh(r,t);case S.ZodIntersection:return Zh(r,t);case S.ZodTuple:return ng(r,t);case S.ZodRecord:return fs(r,t);case S.ZodLiteral:return Uh(r,t);case S.ZodEnum:return qh(r);case S.ZodNativeEnum:return Bh(r);case S.ZodNullable:return Jh(r,t);case S.ZodOptional:return Yh(r,t);case S.ZodMap:return Hh(r,t);case S.ZodSet:return rg(r,t);case S.ZodLazy:return()=>r.getter()._def;case S.ZodPromise:return tg(r,t);case S.ZodNaN:case S.ZodNever:return Vh(t);case S.ZodEffects:return Dh(r,t);case S.ZodAny:return ve(t);case S.ZodUnknown:return og(t);case S.ZodDefault:return Lh(r,t);case S.ZodBranded:return ds(r,t);case S.ZodReadonly:return sg(r,t);case S.ZodCatch:return Mh(r,t);case S.ZodPipeline:return eg(r,t);case S.ZodFunction:case S.ZodVoid:case S.ZodSymbol:return;default:return(n=>{})(e)}};function D(r,e,t=!1){let n=e.seen.get(r);if(e.override){let a=e.override?.(r,e,n,t);if(a!==Ch)return a}if(n&&!t){let a=CE(n,e);if(a!==void 0)return a}let i={def:r,path:e.currentPath,jsonSchema:void 0};e.seen.set(r,i);let o=ag(r,r.typeName,e),s=typeof o=="function"?D(o(),e):o;if(s&&IE(r,e,s),e.postProcess){let a=e.postProcess(s,r,e);return i.jsonSchema=s,a}return i.jsonSchema=s,s}var CE=(r,e)=>{switch(e.$refStrategy){case"root":return{$ref:r.path.join("/")};case"relative":return{$ref:ps(e.currentPath,r.path)};case"none":case"seen":return r.path.length<e.currentPath.length&&r.path.every((t,n)=>e.currentPath[n]===t)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),ve(e)):e.$refStrategy==="seen"?ve(e):void 0}},IE=(r,e,t)=>(r.description&&(t.description=r.description,e.markdownDescription&&(t.markdownDescription=r.description)),t);var eu=(r,e)=>{let t=Ah(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[l,u])=>({...c,[l]:D(u._def,{...t,currentPath:[...t.basePath,t.definitionPath,l]},!0)??ve(t)}),{}):void 0,i=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,o=D(r._def,i===void 0?t:{...t,currentPath:[...t.basePath,t.definitionPath,i]},!1)??ve(t),s=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;s!==void 0&&(o.title=s),t.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[t.openAiAnyTypeName]||(n[t.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:t.$refStrategy==="relative"?"1":[...t.basePath,t.definitionPath,t.openAiAnyTypeName].join("/")}}));let a=i===void 0?n?{...o,[t.definitionPath]:n}:o:{$ref:[...t.$refStrategy==="relative"?[]:t.basePath,t.definitionPath,i].join("/"),[t.definitionPath]:{...n,[i]:o}};return t.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(t.target==="jsonSchema2019-09"||t.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),t.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a};function AE(r){return!r||r==="jsonSchema7"||r==="draft-7"?"draft-7":r==="jsonSchema2019-09"||r==="draft-2020-12"?"draft-2020-12":"draft-7"}function tu(r,e){return it(r)?kl(r,{target:AE(e?.target),io:e?.pipeStrategy??"input"}):eu(r,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function ru(r){let t=cr(r)?.method;if(!t)throw new Error("Schema is missing a method literal");let n=Zo(t);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function nu(r,e){let t=ar(r,e);if(!t.success)throw t.error;return t.data}var OE=6e4,hs=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(Go,t=>{this._oncancel(t)}),this.setNotificationHandler(Jo,t=>{this._onprogress(t)}),this.setRequestHandler(Ko,t=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Xo,async(t,n)=>{let i=await this._taskStore.getTask(t.params.taskId,n.sessionId);if(!i)throw new C(O.InvalidParams,"Failed to retrieve task: Task not found");return{...i}}),this.setRequestHandler(Yo,async(t,n)=>{let i=async()=>{let o=t.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(o,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,l=c.id,u=this._requestResolvers.get(l);if(u)if(this._requestResolvers.delete(l),a.type==="response")u(c);else{let p=c,d=new C(p.error.code,p.error.message,p.error.data);u(d)}else{let p=a.type==="response"?"Response":"Error";this._onerror(new Error(`${p} handler missing for request ${l}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let s=await this._taskStore.getTask(o,n.sessionId);if(!s)throw new C(O.InvalidParams,`Task not found: ${o}`);if(!ur(s.status))return await this._waitForTaskUpdate(o,n.signal),await i();if(ur(s.status)){let a=await this._taskStore.getTaskResult(o,n.sessionId);return this._clearTaskQueue(o),{...a,_meta:{...a._meta,[lr]:{taskId:o}}}}return await i()};return await i()}),this.setRequestHandler(es,async(t,n)=>{try{let{tasks:i,nextCursor:o}=await this._taskStore.listTasks(t.params?.cursor,n.sessionId);return{tasks:i,nextCursor:o,_meta:{}}}catch(i){throw new C(O.InvalidParams,`Failed to list tasks: ${i instanceof Error?i.message:String(i)}`)}}),this.setRequestHandler(rs,async(t,n)=>{try{let i=await this._taskStore.getTask(t.params.taskId,n.sessionId);if(!i)throw new C(O.InvalidParams,`Task not found: ${t.params.taskId}`);if(ur(i.status))throw new C(O.InvalidParams,`Cannot cancel task in terminal status: ${i.status}`);await this._taskStore.updateTaskStatus(t.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(t.params.taskId);let o=await this._taskStore.getTask(t.params.taskId,n.sessionId);if(!o)throw new C(O.InvalidParams,`Task not found after cancellation: ${t.params.taskId}`);return{_meta:{},...o}}catch(i){throw i instanceof C?i:new C(O.InvalidRequest,`Failed to cancel task: ${i instanceof Error?i.message:String(i)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,n,i,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(i,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:o,onTimeout:i})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let n=Date.now()-t.startTime;if(t.maxTotalTimeout&&n>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),C.fromError(O.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:n});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.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 t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=o=>{n?.(o),this._onerror(o)};let i=this._transport?.onmessage;this._transport.onmessage=(o,s)=>{i?.(o,s),gi(o)||yh(o)?this._onresponse(o):jl(o)?this._onrequest(o,s):xh(o)?this._onnotification(o):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let t=C.fromError(O.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){let t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;t!==void 0&&Promise.resolve().then(()=>t(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,t){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,i=this._transport,o=e.params?._meta?.[lr]?.taskId;if(n===void 0){let u={jsonrpc:"2.0",id:e.id,error:{code:O.MethodNotFound,message:"Method not found"}};o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:u,timestamp:Date.now()},i?.sessionId).catch(p=>this._onerror(new Error(`Failed to enqueue error response: ${p}`))):i?.send(u).catch(p=>this._onerror(new Error(`Failed to send an error response: ${p}`)));return}let s=new AbortController;this._requestHandlerAbortControllers.set(e.id,s);let a=hh(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,i?.sessionId):void 0,l={signal:s.signal,sessionId:i?.sessionId,_meta:e.params?._meta,sendNotification:async u=>{if(s.signal.aborted)return;let p={relatedRequestId:e.id};o&&(p.relatedTask={taskId:o}),await this.notification(u,p)},sendRequest:async(u,p,d)=>{if(s.signal.aborted)throw new C(O.ConnectionClosed,"Request was cancelled");let f={...d,relatedRequestId:e.id};o&&!f.relatedTask&&(f.relatedTask={taskId:o});let m=f.relatedTask?.taskId??o;return m&&c&&await c.updateTaskStatus(m,"input_required"),await this.request(u,p,f)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:o,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,l)).then(async u=>{if(s.signal.aborted)return;let p={result:u,jsonrpc:"2.0",id:e.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"response",message:p,timestamp:Date.now()},i?.sessionId):await i?.send(p)},async u=>{if(s.signal.aborted)return;let p={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}}};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"error",message:p,timestamp:Date.now()},i?.sessionId):await i?.send(p)}).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:t,...n}=e.params,i=Number(t),o=this._progressHandlers.get(i);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let s=this._responseHandlers.get(i),a=this._timeoutInfo.get(i);if(a&&s&&a.resetTimeoutOnProgress)try{this._resetTimeout(i)}catch(c){this._responseHandlers.delete(i),this._progressHandlers.delete(i),this._cleanupTimeout(i),s(c);return}o(n)}_onresponse(e){let t=Number(e.id),n=this._requestResolvers.get(t);if(n){if(this._requestResolvers.delete(t),gi(e))n(e);else{let s=new C(e.error.code,e.error.message,e.error.data);n(s)}return}let i=this._responseHandlers.get(t);if(i===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t);let o=!1;if(gi(e)&&e.result&&typeof e.result=="object"){let s=e.result;if(s.task&&typeof s.task=="object"){let a=s.task;typeof a.taskId=="string"&&(o=!0,this._taskProgressTokens.set(a.taskId,t))}}if(o||this._progressHandlers.delete(t),gi(e))i(e);else{let s=C.fromError(e.error.code,e.error.message,e.error.data);i(s)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,t,n){let{task:i}=n??{};if(!i){try{yield{type:"result",result:await this.request(e,t,n)}}catch(s){yield{type:"error",error:s instanceof C?s:new C(O.InternalError,String(s))}}return}let o;try{let s=await this.request(e,$n,n);if(s.task)o=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new C(O.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:o},n);if(yield{type:"taskStatus",task:a},ur(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},t,n)}:a.status==="failed"?yield{type:"error",error:new C(O.InternalError,`Task ${o} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new C(O.InternalError,`Task ${o} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},t,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(l=>setTimeout(l,c)),n?.signal?.throwIfAborted()}}catch(s){yield{type:"error",error:s instanceof C?s:new C(O.InternalError,String(s))}}}request(e,t,n){let{relatedRequestId:i,resumptionToken:o,onresumptiontoken:s,task:a,relatedTask:c}=n??{};return new Promise((l,u)=>{let p=w=>{u(w)};if(!this._transport){p(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(w){p(w);return}n?.signal?.throwIfAborted();let d=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:d};n?.onprogress&&(this._progressHandlers.set(d,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:d}}),a&&(f.params={...f.params,task:a}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[lr]:c}});let m=w=>{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(w)}},{relatedRequestId:i,resumptionToken:o,onresumptiontoken:s}).catch(P=>this._onerror(new Error(`Failed to send cancellation: ${P}`)));let E=w instanceof C?w:new C(O.RequestTimeout,String(w));u(E)};this._responseHandlers.set(d,w=>{if(!n?.signal?.aborted){if(w instanceof Error)return u(w);try{let E=ar(t,w.result);E.success?l(E.data):u(E.error)}catch(E){u(E)}}}),n?.signal?.addEventListener("abort",()=>{m(n?.signal?.reason)});let h=n?.timeout??OE,v=()=>m(C.fromError(O.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(d,h,n?.maxTotalTimeout,v,n?.resetTimeoutOnProgress??!1);let b=c?.taskId;if(b){let w=E=>{let P=this._responseHandlers.get(d);P?P(E):this._onerror(new Error(`Response handler missing for side-channeled request ${d}`))};this._requestResolvers.set(d,w),this._enqueueTaskMessage(b,{type:"request",message:f,timestamp:Date.now()}).catch(E=>{this._cleanupTimeout(d),u(E)})}else this._transport.send(f,{relatedRequestId:i,resumptionToken:o,onresumptiontoken:s}).catch(w=>{this._cleanupTimeout(d),u(w)})})}async getTask(e,t){return this.request({method:"tasks/get",params:e},Qo,t)}async getTaskResult(e,t,n){return this.request({method:"tasks/result",params:e},t,n)}async listTasks(e,t){return this.request({method:"tasks/list",params:e},ts,t)}async cancelTask(e,t){return this.request({method:"tasks/cancel",params:e},wh,t)}async notification(e,t){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=t?.relatedTask?.taskId;if(n){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[lr]:t.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.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 a={...e,jsonrpc:"2.0"};t?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[lr]:t.relatedTask}}}),this._transport?.send(a,t).catch(c=>this._onerror(c))});return}let s={...e,jsonrpc:"2.0"};t?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[lr]:t.relatedTask}}}),await this._transport.send(s,t)}setRequestHandler(e,t){let n=ru(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(i,o)=>{let s=nu(e,i);return Promise.resolve(t(s,o))})}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,t){let n=ru(e);this._notificationHandlers.set(n,i=>{let o=nu(e,i);return Promise.resolve(t(o))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let t=this._taskProgressTokens.get(e);t!==void 0&&(this._progressHandlers.delete(t),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,t,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let i=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,n,i)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,t);for(let i of n)if(i.type==="request"&&jl(i.message)){let o=i.message.id,s=this._requestResolvers.get(o);s?(s(new C(O.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o)):this._onerror(new Error(`Resolver missing for request ${o} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let n=this._options?.defaultTaskPollInterval??1e3;try{let i=await this._taskStore?.getTask(e);i?.pollInterval&&(n=i.pollInterval)}catch{}return new Promise((i,o)=>{if(t.aborted){o(new C(O.InvalidRequest,"Request cancelled"));return}let s=setTimeout(i,n);t.addEventListener("abort",()=>{clearTimeout(s),o(new C(O.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,t){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async i=>{if(!e)throw new Error("No request provided");return await n.createTask(i,e.id,{method:e.method,params:e.params},t)},getTask:async i=>{let o=await n.getTask(i,t);if(!o)throw new C(O.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(i,o,s)=>{await n.storeTaskResult(i,o,s,t);let a=await n.getTask(i,t);if(a){let c=bi.parse({method:"notifications/tasks/status",params:a});await this.notification(c),ur(a.status)&&this._cleanupTaskProgressHandler(i)}},getTaskResult:i=>n.getTaskResult(i,t),updateTaskStatus:async(i,o,s)=>{let a=await n.getTask(i,t);if(!a)throw new C(O.InvalidParams,`Task "${i}" not found - it may have been cleaned up`);if(ur(a.status))throw new C(O.InvalidParams,`Cannot update task "${i}" from terminal status "${a.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(i,o,s,t);let c=await n.getTask(i,t);if(c){let l=bi.parse({method:"notifications/tasks/status",params:c});await this.notification(l),ur(c.status)&&this._cleanupTaskProgressHandler(i)}},listTasks:i=>n.listTasks(i,t)}}};function cg(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function lg(r,e){let t={...r};for(let n in e){let i=n,o=e[i];if(o===void 0)continue;let s=t[i];cg(s)&&cg(o)?t[i]={...s,...o}:t[i]=o}return t}var Kx=ka(Up(),1),Jx=ka(Gx(),1);function EC(){let r=new Kx.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Jx.default)(r),r}var Xs=class{constructor(e){this._ajv=e??EC()}getValidator(e){let t="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>t(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}};var Qs=class{constructor(e){this._server=e}requestStream(e,t,n){return this._server.requestStream(e,t,n)}createMessageStream(e,t){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let i=e.messages[e.messages.length-1],o=Array.isArray(i.content)?i.content:[i.content],s=o.some(u=>u.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],l=c.some(u=>u.type==="tool_use");if(s){if(o.some(u=>u.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 u=new Set(c.filter(d=>d.type==="tool_use").map(d=>d.id)),p=new Set(o.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(u.size!==p.size||![...u].every(d=>p.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},Si,t)}elicitInputStream(e,t){let n=this._server.getClientCapabilities(),i=e.mode??"form";switch(i){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let o=i==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:o},Pn,t)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,n){return this._server.getTaskResult({taskId:e},t,n)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}};function Xx(r,e,t){if(!r)throw new Error(`${t} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!r.tools?.call)throw new Error(`${t} does not support task creation for tools/call (required for ${e})`);break;default:break}}function Qx(r,e,t){if(!r)throw new Error(`${t} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!r.sampling?.createMessage)throw new Error(`${t} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!r.elicitation?.create)throw new Error(`${t} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var Ys=class extends hs{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(ki.options.map((n,i)=>[n,i])),this.isMessageIgnored=(n,i)=>{let o=this._loggingLevels.get(i);return o?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(o):!1},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new Xs,this.setRequestHandler(Dl,n=>this._oninitialize(n)),this.setNotificationHandler(ql,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Wl,async(n,i)=>{let o=i.sessionId||i.requestInfo?.headers["mcp-session-id"]||void 0,{level:s}=n.params,a=ki.safeParse(s);return a.success&&this._loggingLevels.set(o,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Qs(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=lg(this._capabilities,e)}setRequestHandler(e,t){let i=cr(e)?.method;if(!i)throw new Error("Schema is missing a method literal");let o;if(it(i)){let a=i;o=a._zod?.def?.value??a.value}else{let a=i;o=a._def?.value??a.value}if(typeof o!="string")throw new Error("Schema method literal must be a string");if(o==="tools/call"){let a=async(c,l)=>{let u=ar(zn,c);if(!u.success){let m=u.error instanceof Error?u.error.message:String(u.error);throw new C(O.InvalidParams,`Invalid tools/call request: ${m}`)}let{params:p}=u.data,d=await Promise.resolve(t(c,l));if(p.task){let m=ar($n,d);if(!m.success){let h=m.error instanceof Error?m.error.message:String(m.error);throw new C(O.InvalidParams,`Invalid task creation result: ${h}`)}return m.data}let f=ar(ls,d);if(!f.success){let m=f.error instanceof Error?f.error.message:String(f.error);throw new C(O.InvalidParams,`Invalid tools/call result: ${m}`)}return f.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,t)}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){Qx(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&Xx(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:dh.includes(t)?t:Ol,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"},Wo)}async createMessage(e,t){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 n=e.messages[e.messages.length-1],i=Array.isArray(n.content)?n.content:[n.content],o=i.some(l=>l.type==="tool_result"),s=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=s?Array.isArray(s.content)?s.content:[s.content]:[],c=a.some(l=>l.type==="tool_use");if(o){if(i.some(l=>l.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 l=new Set(a.filter(p=>p.type==="tool_use").map(p=>p.id)),u=new Set(i.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(l.size!==u.size||![...l].every(p=>u.has(p)))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},Gl,t):this.request({method:"sampling/createMessage",params:e},Si,t)}async elicitInput(e,t){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let i=e;return this.request({method:"elicitation/create",params:i},Pn,t)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let i=e.mode==="form"?e:{...e,mode:"form"},o=await this.request({method:"elicitation/create",params:i},Pn,t);if(o.action==="accept"&&o.content&&i.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(i.requestedSchema)(o.content);if(!a.valid)throw new C(O.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(s){throw s instanceof C?s:new C(O.InternalError,`Error validating elicitation response: ${s instanceof Error?s.message:String(s)}`)}return o}}}createElicitationCompletionNotifier(e,t){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}},t)}async listRoots(e,t){return this.request({method:"roots/list",params:e},Kl,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))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"})}};var ey=Symbol.for("mcp.completable");function Jp(r){return!!r&&typeof r=="object"&&ey in r}function ty(r){return r[ey]?.complete}var Yx;(function(r){r.Completable="McpCompletable"})(Yx||(Yx={}));var $C=/^[A-Za-z0-9._-]{1,128}$/;function TC(r){let e=[];if(r.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(r.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${r.length})`]};if(r.includes(" ")&&e.push("Tool name contains spaces, which may cause parsing issues"),r.includes(",")&&e.push("Tool name contains commas, which may cause parsing issues"),(r.startsWith("-")||r.endsWith("-"))&&e.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(r.startsWith(".")||r.endsWith("."))&&e.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!$C.test(r)){let t=r.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,i,o)=>o.indexOf(n)===i);return e.push(`Tool name contains invalid characters: ${t.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function zC(r,e){if(e.length>0){console.warn(`Tool name validation warning for "${r}":`);for(let t of e)console.warn(` - ${t}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function Xp(r){let e=TC(r);return zC(r,e.warnings),e.isValid}var ea=class{constructor(e){this._mcpServer=e}registerToolTask(e,t,n){let i={taskSupport:"required",...t.execution};if(i.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,i,t._meta,n)}};var ta=class{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Ys(e,t)}get experimental(){return this._experimental||(this._experimental={tasks:new ea(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(yr(cs)),this.server.assertCanSetRequestHandler(yr(zn)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(cs,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:(()=>{let i=Sn(t.inputSchema);return i?tu(i,{strictUnions:!0,pipeStrategy:"input"}):PC})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let i=Sn(t.outputSchema);i&&(n.outputSchema=tu(i,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(zn,async(e,t)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new C(O.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new C(O.InvalidParams,`Tool ${e.params.name} disabled`);let i=!!e.params.task,o=n.execution?.taskSupport,s="createTask"in n.handler;if((o==="required"||o==="optional")&&!s)throw new C(O.InternalError,`Tool ${e.params.name} has taskSupport '${o}' but was not registered with registerToolTask`);if(o==="required"&&!i)throw new C(O.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(o==="optional"&&!i&&s)return await this.handleAutomaticTaskPolling(n,e,t);let a=await this.validateToolInput(n,e.params.arguments,e.params.name),c=await this.executeToolHandler(n,a,t);return i||await this.validateToolOutput(n,c,e.params.name),c}catch(n){if(n instanceof C&&n.code===O.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,t,n){if(!e.inputSchema)return;let o=Sn(e.inputSchema)??e.inputSchema,s=await Do(o,t);if(!s.success){let a="error"in s?s.error:"Unknown error",c=qo(a);throw new C(O.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${c}`)}return s.data}async validateToolOutput(e,t,n){if(!e.outputSchema||!("content"in t)||t.isError)return;if(!t.structuredContent)throw new C(O.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let i=Sn(e.outputSchema),o=await Do(i,t.structuredContent);if(!o.success){let s="error"in o?o.error:"Unknown error",a=qo(s);throw new C(O.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(e,t,n){let i=e.handler;if("createTask"in i){if(!n.taskStore)throw new Error("No task store provided.");let s={...n,taskStore:n.taskStore};if(e.inputSchema){let a=i;return await Promise.resolve(a.createTask(t,s))}else{let a=i;return await Promise.resolve(a.createTask(s))}}if(e.inputSchema){let s=i;return await Promise.resolve(s(t,n))}else{let s=i;return await Promise.resolve(s(n))}}async handleAutomaticTaskPolling(e,t,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let i=await this.validateToolInput(e,t.params.arguments,t.params.name),o=e.handler,s={...n,taskStore:n.taskStore},a=i?await Promise.resolve(o.createTask(i,s)):await Promise.resolve(o.createTask(s)),c=a.task.taskId,l=a.task,u=l.pollInterval??5e3;for(;l.status!=="completed"&&l.status!=="failed"&&l.status!=="cancelled";){await new Promise(d=>setTimeout(d,u));let p=await n.taskStore.getTask(c);if(!p)throw new C(O.InternalError,`Task ${c} not found during polling`);l=p}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(yr(us)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(us,async e=>{switch(e.params.ref.type){case"ref/prompt":return zh(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return Ph(e),this.handleResourceCompletion(e,e.params.ref);default:throw new C(O.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,t){let n=this._registeredPrompts[t.name];if(!n)throw new C(O.InvalidParams,`Prompt ${t.name} not found`);if(!n.enabled)throw new C(O.InvalidParams,`Prompt ${t.name} disabled`);if(!n.argsSchema)return to;let o=cr(n.argsSchema)?.[e.params.argument.name];if(!Jp(o))return to;let s=ty(o);if(!s)return to;let a=await s(e.params.argument.value,e.params.context);return ny(a)}async handleResourceCompletion(e,t){let n=Object.values(this._registeredResourceTemplates).find(s=>s.resourceTemplate.uriTemplate.toString()===t.uri);if(!n){if(this._registeredResources[t.uri])return to;throw new C(O.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let i=n.resourceTemplate.completeCallback(e.params.argument.name);if(!i)return to;let o=await i(e.params.argument.value,e.params.context);return ny(o)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(yr(ns)),this.server.assertCanSetRequestHandler(yr(is)),this.server.assertCanSetRequestHandler(yr(os)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(ns,async(e,t)=>{let n=Object.entries(this._registeredResources).filter(([o,s])=>s.enabled).map(([o,s])=>({uri:o,name:s.name,...s.metadata})),i=[];for(let o of Object.values(this._registeredResourceTemplates)){if(!o.resourceTemplate.listCallback)continue;let s=await o.resourceTemplate.listCallback(t);for(let a of s.resources)i.push({...o.metadata,...a})}return{resources:[...n,...i]}}),this.server.setRequestHandler(is,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([t,n])=>({name:t,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(os,async(e,t)=>{let n=new URL(e.params.uri),i=this._registeredResources[n.toString()];if(i){if(!i.enabled)throw new C(O.InvalidParams,`Resource ${n} disabled`);return i.readCallback(n,t)}for(let o of Object.values(this._registeredResourceTemplates)){let s=o.resourceTemplate.uriTemplate.match(n.toString());if(s)return o.readCallback(n,s,t)}throw new C(O.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(yr(ss)),this.server.assertCanSetRequestHandler(yr(as)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(ss,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?RC(t.argsSchema):void 0}))})),this.server.setRequestHandler(as,async(e,t)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new C(O.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new C(O.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let i=Sn(n.argsSchema),o=await Do(i,e.params.arguments);if(!o.success){let c="error"in o?o.error:"Unknown error",l=qo(c);throw new C(O.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${l}`)}let s=o.data,a=n.callback;return await Promise.resolve(a(s,t))}else{let i=n.callback;return await Promise.resolve(i(t))}}),this._promptHandlersInitialized=!0)}resource(e,t,...n){let i;typeof n[0]=="object"&&(i=n.shift());let o=n[0];if(typeof t=="string"){if(this._registeredResources[t])throw new Error(`Resource ${t} is already registered`);let s=this._createRegisteredResource(e,void 0,t,i,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let s=this._createRegisteredResourceTemplate(e,void 0,t,i,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}registerResource(e,t,n,i){if(typeof t=="string"){if(this._registeredResources[t])throw new Error(`Resource ${t} is already registered`);let o=this._createRegisteredResource(e,n.title,t,n,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let o=this._createRegisteredResourceTemplate(e,n.title,t,n,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}}_createRegisteredResource(e,t,n,i,o){let s={name:e,title:t,metadata:i,readCallback:o,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=s)),typeof a.name<"u"&&(s.name=a.name),typeof a.title<"u"&&(s.title=a.title),typeof a.metadata<"u"&&(s.metadata=a.metadata),typeof a.callback<"u"&&(s.readCallback=a.callback),typeof a.enabled<"u"&&(s.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=s,s}_createRegisteredResourceTemplate(e,t,n,i,o){let s={resourceTemplate:n,title:t,metadata:i,readCallback:o,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({name:null}),update:l=>{typeof l.name<"u"&&l.name!==e&&(delete this._registeredResourceTemplates[e],l.name&&(this._registeredResourceTemplates[l.name]=s)),typeof l.title<"u"&&(s.title=l.title),typeof l.template<"u"&&(s.resourceTemplate=l.template),typeof l.metadata<"u"&&(s.metadata=l.metadata),typeof l.callback<"u"&&(s.readCallback=l.callback),typeof l.enabled<"u"&&(s.enabled=l.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=s;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(l=>!!n.completeCallback(l))&&this.setCompletionRequestHandler(),s}_createRegisteredPrompt(e,t,n,i,o){let s={title:t,description:n,argsSchema:i===void 0?void 0:Vr(i),callback:o,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==e&&(delete this._registeredPrompts[e],a.name&&(this._registeredPrompts[a.name]=s)),typeof a.title<"u"&&(s.title=a.title),typeof a.description<"u"&&(s.description=a.description),typeof a.argsSchema<"u"&&(s.argsSchema=Vr(a.argsSchema)),typeof a.callback<"u"&&(s.callback=a.callback),typeof a.enabled<"u"&&(s.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=s,i&&Object.values(i).some(c=>{let l=c instanceof Ue?c._def?.innerType:c;return Jp(l)})&&this.setCompletionRequestHandler(),s}_createRegisteredTool(e,t,n,i,o,s,a,c,l){Xp(e);let u={title:t,description:n,inputSchema:ry(i),outputSchema:ry(o),annotations:s,execution:a,_meta:c,handler:l,enabled:!0,disable:()=>u.update({enabled:!1}),enable:()=>u.update({enabled:!0}),remove:()=>u.update({name:null}),update:p=>{typeof p.name<"u"&&p.name!==e&&(typeof p.name=="string"&&Xp(p.name),delete this._registeredTools[e],p.name&&(this._registeredTools[p.name]=u)),typeof p.title<"u"&&(u.title=p.title),typeof p.description<"u"&&(u.description=p.description),typeof p.paramsSchema<"u"&&(u.inputSchema=Vr(p.paramsSchema)),typeof p.outputSchema<"u"&&(u.outputSchema=Vr(p.outputSchema)),typeof p.callback<"u"&&(u.handler=p.callback),typeof p.annotations<"u"&&(u.annotations=p.annotations),typeof p._meta<"u"&&(u._meta=p._meta),typeof p.enabled<"u"&&(u.enabled=p.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=u,this.setToolRequestHandlers(),this.sendToolListChanged(),u}tool(e,...t){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,i,o,s;if(typeof t[0]=="string"&&(n=t.shift()),t.length>1){let c=t[0];if(Qp(c))i=t.shift(),t.length>1&&typeof t[0]=="object"&&t[0]!==null&&!Qp(t[0])&&(s=t.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(l=>typeof l=="object"&&l!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);s=t.shift()}}let a=t[0];return this._createRegisteredTool(e,void 0,n,i,o,s,{taskSupport:"forbidden"},void 0,a)}registerTool(e,t,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:i,description:o,inputSchema:s,outputSchema:a,annotations:c,_meta:l}=t;return this._createRegisteredTool(e,i,o,s,a,c,{taskSupport:"forbidden"},l,n)}prompt(e,...t){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n;typeof t[0]=="string"&&(n=t.shift());let i;t.length>1&&(i=t.shift());let o=t[0],s=this._createRegisteredPrompt(e,void 0,n,i,o);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}registerPrompt(e,t,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:i,description:o,argsSchema:s}=t,a=this._createRegisteredPrompt(e,i,o,s,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var PC={type:"object",properties:{}};function iy(r){return r!==null&&typeof r=="object"&&"parse"in r&&typeof r.parse=="function"&&"safeParse"in r&&typeof r.safeParse=="function"}function oy(r){return"_def"in r||"_zod"in r||iy(r)}function Qp(r){return typeof r!="object"||r===null||oy(r)?!1:Object.keys(r).length===0?!0:Object.values(r).some(iy)}function ry(r){if(r){if(Qp(r))return Vr(r);if(!oy(r))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return r}}function RC(r){let e=cr(r);return e?Object.entries(e).map(([t,n])=>{let i=Uf(n),o=Ff(n);return{name:t,description:i,required:!o}}):[]}function yr(r){let t=cr(r)?.method;if(!t)throw new Error("Schema is missing a method literal");let n=Zo(t);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function ny(r){return{completion:{values:r.slice(0,100),total:r.length,hasMore:r.length>100}}}var to={completion:{values:[],hasMore:!1}};import ay from"node:process";var ra=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
91
|
+
`);if(e===-1)return null;let t=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),CC(t)}clear(){this._buffer=void 0}};function CC(r){return _h.parse(JSON.parse(r))}function sy(r){return JSON.stringify(r)+`
|
|
92
|
+
`}var na=class{constructor(e=ay.stdin,t=ay.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new ra,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}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(t=>{let n=sy(e);this._stdout.write(n)?t():this._stdout.once("drain",t)})}};var Yp={debug:0,info:1,warn:2,error:3},IC={debug:"\x1B[90m[DEBUG]\x1B[0m",info:"\x1B[36m[INFO]\x1B[0m ",warn:"\x1B[33m[WARN]\x1B[0m ",error:"\x1B[31m[ERROR]\x1B[0m"},AC={server:"\x1B[35m",terminal:"\x1B[32m",git:"\x1B[33m",knowledge:"\x1B[36m",metrics:"\x1B[34m",dispatch:"\x1B[35m",board:"\x1B[32m",worker:"\x1B[33m",notification:"\x1B[34m",config:"\x1B[90m",orchestrator:"\x1B[33m",tfidf:"\x1B[36m"},OC="\x1B[0m";function NC(){let r=(process.env.CATALYST_LOG_LEVEL??"info").toLowerCase();return r in Yp?r:"info"}function jC(){let r=new Date,e=String(r.getUTCHours()).padStart(2,"0"),t=String(r.getUTCMinutes()).padStart(2,"0"),n=String(r.getUTCSeconds()).padStart(2,"0"),i=String(r.getUTCMilliseconds()).padStart(3,"0");return`\x1B[90m${e}:${t}:${n}.${i}Z\x1B[0m`}function MC(r){return`${AC[r]??"\x1B[37m"}[${r}]${OC}`}function ia(r,e,t,n){if(Yp[r]<Yp[NC()])return;let i=`${jC()} ${IC[r]} ${MC(e)} ${t}`;if(n&&Object.keys(n).length>0){let o=Object.entries(n).map(([s,a])=>{let c=typeof a=="string"?a:JSON.stringify(a),l=c.length>120?c.slice(0,117)+"...":c;return`\x1B[90m${s}=\x1B[0m${l}`});i+=" "+o.join(" ")}process.stderr.write(i+`
|
|
93
|
+
`)}function oe(r){return{debug:(e,t)=>ia("debug",r,e,t),info:(e,t)=>ia("info",r,e,t),warn:(e,t)=>ia("warn",r,e,t),error:(e,t)=>ia("error",r,e,t)}}import{readFileSync as LC,existsSync as DC}from"node:fs";import{join as qC}from"node:path";var ed=oe("config"),oa={version:"1.0.0",global:{confidence_threshold:7,max_findings:20,output_style:"concise",auto_chain:!0},pillars:{}};function cy(r){let e=r??process.cwd(),t=qC(e,".github","catalyst.config.json");if(!DC(t))return ed.info("No config file found, using defaults",{path:t}),oa;try{let n=LC(t,"utf-8"),i=JSON.parse(n);return ed.info("Config loaded",{path:t,version:i.version??"unknown"}),{...oa,...i,global:{...oa.global,...i.global}}}catch(n){return ed.warn("Failed to parse config, using defaults",{path:t,error:n.message}),oa}}function ly(r,e,t){let n=r.pillars[e];if(!n?.enabled)return!1;let i=n.skills[t];return i?i.enabled!==!1:!0}function uy(r,e,t){return r.pillars[e]?.skills[t]??{}}import{execSync as ZC,spawn as UC,exec as FC}from"node:child_process";import{promisify as HC}from"node:util";var ro=oe("terminal"),BC=HC(FC),VC=new Map;function py(r){r.tool("catalyst_exec","Execute a shell command synchronously and return stdout/stderr",{command:g.string().describe("Shell command to execute"),cwd:g.string().optional().describe("Working directory (defaults to project root)"),timeout:g.number().optional().describe("Timeout in milliseconds (default: 30000)")},async({command:e,cwd:t,timeout:n})=>{ro.info("Executing command",{command:e.slice(0,80),cwd:t??".",timeout:n??3e4});let i=[{pattern:/rm\s+(-\w*r\w*f\w*|-\w*f\w*r\w*)\s+[/~]/,reason:"Recursive force-delete on root or home path"},{pattern:/git\s+push\s+.*--force.*\s+(main|master|release)/,reason:"Force-push to protected branch"},{pattern:/git\s+reset\s+--hard.*\s+(main|master|release|origin)/,reason:"Hard reset on shared/protected branch"},{pattern:/DROP\s+(DATABASE|TABLE)\s/i,reason:"Destructive database operation"},{pattern:/TRUNCATE\s+/i,reason:"Destructive database truncation"},{pattern:/chmod\s+.*-R\s+777/,reason:"Insecure recursive permission change"},{pattern:/(curl|wget)\s+.*\|\s*(sh|bash|zsh)/,reason:"Piping remote script to shell is unsafe"},{pattern:/docker\s+system\s+prune\s+-\w*a\w*f/,reason:"Docker system prune without confirmation"},{pattern:/mkfs\./,reason:"Filesystem format operation"},{pattern:/>(\/dev\/sda|\/dev\/nvme|\/dev\/disk)/,reason:"Writing directly to disk device"}];for(let{pattern:o,reason:s}of i)if(o.test(e))return ro.warn("Blocked destructive command",{command:e.slice(0,80),reason:s}),{content:[{type:"text",text:`\u26D4 Command blocked: ${s}
|
|
94
|
+
|
|
95
|
+
Command: ${e}
|
|
96
|
+
|
|
97
|
+
This command is on the Catalyst safety blocklist. If you need to run this, execute it manually in your terminal.`}],isError:!0};try{return{content:[{type:"text",text:ZC(e,{cwd:t??process.cwd(),timeout:n??3e4,encoding:"utf-8",maxBuffer:10485760,env:{...process.env,FORCE_COLOR:"0"}}).trim()||"(no output)"}]}}catch(o){let s=o;return ro.error("Command failed",{command:e.slice(0,80),error:(s.stderr||s.message).slice(0,120)}),{content:[{type:"text",text:`Exit error:
|
|
98
|
+
${s.stderr||s.stdout||s.message}`}],isError:!0}}}),r.tool("catalyst_exec_background","Start a long-running background process (e.g., dev server). Returns a process ID to check later.",{command:g.string().describe("Shell command to run in background"),cwd:g.string().optional().describe("Working directory"),label:g.string().describe("Human-readable label for this process")},async({command:e,cwd:t,label:n})=>{ro.info("Starting background process",{label:n,command:e.slice(0,80)});let i=`bg-${Date.now()}`,o=UC("sh",["-c",e],{cwd:t??process.cwd(),stdio:["ignore","pipe","pipe"],detached:!0}),s="";return o.stdout?.on("data",a=>{s+=a.toString(),s.length>5e4&&(s=s.slice(-5e4))}),o.stderr?.on("data",a=>{s+=a.toString(),s.length>5e4&&(s=s.slice(-5e4))}),VC.set(i,o),await new Promise(a=>setTimeout(a,2e3)),{content:[{type:"text",text:`Background process started: ${n}
|
|
99
|
+
ID: ${i}
|
|
100
|
+
PID: ${o.pid}
|
|
101
|
+
Initial output:
|
|
102
|
+
${s||"(waiting for output...)"}`}]}}),r.tool("catalyst_exec_parallel","Execute multiple shell commands concurrently and return all results. Use for independent tasks like running linters, tests, and builds in parallel.",{commands:g.array(g.object({command:g.string().describe("Shell command to execute"),label:g.string().describe("Short label for this command"),cwd:g.string().optional().describe("Working directory")})).describe("List of commands to run in parallel"),timeout:g.number().optional().describe("Per-command timeout in ms (default: 60000)")},async({commands:e,timeout:t})=>{ro.info("Running parallel commands",{count:e.length,labels:e.map(a=>a.label).join(", ")});let n=t??6e4,i=await Promise.allSettled(e.map(async a=>{let{stdout:c,stderr:l}=await BC(a.command,{cwd:a.cwd??process.cwd(),timeout:n,maxBuffer:10485760,env:{...process.env,FORCE_COLOR:"0"}});return{label:a.label,stdout:c.trim(),stderr:l.trim()}})),o=i.map((a,c)=>{let l=e[c].label;if(a.status==="fulfilled"){let u=a.value.stderr?`${a.value.stdout}
|
|
103
|
+
[stderr] ${a.value.stderr}`:a.value.stdout||"(no output)";return`### \u2713 ${l}
|
|
104
|
+
${u}`}return`### \u2717 ${l}
|
|
105
|
+
Error: ${a.reason.message}`}).join(`
|
|
106
|
+
|
|
107
|
+
`),s=i.filter(a=>a.status==="fulfilled").length;return{content:[{type:"text",text:`Parallel execution: ${s}/${i.length} succeeded
|
|
108
|
+
|
|
109
|
+
${o}`}],isError:s<i.length}})}import{spawnSync as my}from"node:child_process";import dy from"better-sqlite3";import{existsSync as GC,mkdirSync as KC,renameSync as td}from"node:fs";import{join as JC,dirname as XC}from"node:path";var no=class{corpus=new Map;idf=new Map;docCount=0;buildIndex(e){if(this.corpus.clear(),this.idf.clear(),this.docCount=e.length,this.docCount===0)return;let t=new Map;for(let n of e){let i=this.tokenize(n.text);this.corpus.set(n.id,i);let o=new Set;for(let s of Object.keys(i))o.has(s)||(t.set(s,(t.get(s)??0)+1),o.add(s))}for(let[n,i]of t)this.idf.set(n,Math.log((this.docCount+1)/(i+1))+1)}search(e,t=10){if(this.corpus.size===0)return[];let n=this.tokenize(e),i=this.toTfIdfVector(n),o=[];for(let[s,a]of this.corpus){let c=this.toTfIdfVector(a),l=this.cosineSimilarity(i,c);l>.01&&o.push({id:s,score:l})}return o.sort((s,a)=>a.score-s.score).slice(0,t)}tokenize(e){let t={},n=e.toLowerCase().replace(/[^a-z0-9\s_-]/g," ").split(/\s+/).filter(o=>o.length>2&&!WC.has(o));for(let o of n)t[o]=(t[o]??0)+1;let i=Math.max(...Object.values(t),1);for(let o of Object.keys(t))t[o]=.5+.5*(t[o]/i);return t}toTfIdfVector(e){let t=new Map;for(let[n,i]of Object.entries(e)){let o=this.idf.get(n)??1;t.set(n,i*o)}return t}cosineSimilarity(e,t){let n=0,i=0,o=0;for(let[a,c]of e){i+=c*c;let l=t.get(a);l!==void 0&&(n+=c*l)}for(let a of t.values())o+=a*a;let s=Math.sqrt(i)*Math.sqrt(o);return s===0?0:n/s}},WC=new Set(["the","be","to","of","and","a","in","that","have","i","it","for","not","on","with","he","as","you","do","at","this","but","his","by","from","they","we","say","her","she","or","an","will","my","one","all","would","there","their","what","so","up","out","if","about","who","get","which","go","me","when","make","can","like","time","no","just","him","know","take","people","into","year","your","good","some","could","them","see","other","than","then","now","look","only","come","its","over","think","also","back","after","use","two","how","our","work","first","well","way","even","new","want","because","any","these","give","day","most","us","was","were","been","has","had","are","is","did","does","doing","done","being","should","very","more","such","much","still","own","may","each"]);var Qt=oe("knowledge"),pt=class{db;tfidf;indexDirty=!0;constructor(e){let t=e??JC(process.cwd(),".catalyst","knowledge.db"),n=XC(t);GC(n)||KC(n,{recursive:!0});try{this.db=new dy(t),this.db.pragma("journal_mode = WAL"),this.db.pragma("foreign_keys = ON"),this.tfidf=new no,this.init()}catch(i){Qt.error("DB open/init failed \u2014 backing up corrupt file and recreating",{path:t,error:i.message});let o=`${t}.corrupt.${Date.now()}`;try{td(t,o)}catch{}try{td(`${t}-wal`,`${o}-wal`)}catch{}try{td(`${t}-shm`,`${o}-shm`)}catch{}this.db=new dy(t),this.db.pragma("journal_mode = WAL"),this.db.pragma("foreign_keys = ON"),this.tfidf=new no,this.init(),Qt.warn("Recreated knowledge DB from scratch",{backup:o})}Qt.info("Knowledge store initialized",{path:t})}init(){this.db.exec(`
|
|
110
|
+
CREATE TABLE IF NOT EXISTS entries (
|
|
111
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
112
|
+
type TEXT NOT NULL CHECK(type IN ('decision', 'lesson', 'pattern', 'convention')),
|
|
113
|
+
title TEXT NOT NULL,
|
|
114
|
+
content TEXT NOT NULL,
|
|
115
|
+
summary TEXT NOT NULL DEFAULT '',
|
|
116
|
+
tags TEXT NOT NULL DEFAULT '[]',
|
|
117
|
+
related_files TEXT NOT NULL DEFAULT '[]',
|
|
118
|
+
timestamp TEXT NOT NULL,
|
|
119
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
120
|
+
);
|
|
121
|
+
|
|
122
|
+
-- Add summary column to existing tables (safe to re-run)
|
|
123
|
+
CREATE TABLE IF NOT EXISTS _migration_check (id INTEGER);
|
|
124
|
+
`),this.db.prepare("PRAGMA table_info(entries)").all().some(t=>t.name==="summary")||this.db.exec("ALTER TABLE entries ADD COLUMN summary TEXT NOT NULL DEFAULT ''"),this.db.exec(`
|
|
125
|
+
CREATE VIRTUAL TABLE IF NOT EXISTS entries_fts USING fts5(
|
|
126
|
+
title, content, summary, tags,
|
|
127
|
+
content='entries',
|
|
128
|
+
content_rowid='id'
|
|
129
|
+
);
|
|
130
|
+
|
|
131
|
+
CREATE TRIGGER IF NOT EXISTS entries_ai AFTER INSERT ON entries BEGIN
|
|
132
|
+
INSERT INTO entries_fts(rowid, title, content, summary, tags)
|
|
133
|
+
VALUES (new.id, new.title, new.content, new.summary, new.tags);
|
|
134
|
+
END;
|
|
135
|
+
|
|
136
|
+
CREATE TRIGGER IF NOT EXISTS entries_ad AFTER DELETE ON entries BEGIN
|
|
137
|
+
INSERT INTO entries_fts(entries_fts, rowid, title, content, summary, tags)
|
|
138
|
+
VALUES ('delete', old.id, old.title, old.content, old.summary, old.tags);
|
|
139
|
+
END;
|
|
140
|
+
|
|
141
|
+
CREATE TRIGGER IF NOT EXISTS entries_au AFTER UPDATE ON entries BEGIN
|
|
142
|
+
INSERT INTO entries_fts(entries_fts, rowid, title, content, summary, tags)
|
|
143
|
+
VALUES ('delete', old.id, old.title, old.content, old.summary, old.tags);
|
|
144
|
+
INSERT INTO entries_fts(rowid, title, content, summary, tags)
|
|
145
|
+
VALUES (new.id, new.title, new.content, new.summary, new.tags);
|
|
146
|
+
END;
|
|
147
|
+
`)}store(e){let t=e.summary||this.autoSummarize(e.content);Qt.info("Storing knowledge entry",{type:e.type,title:e.title,tags:e.tags.join(", ")});let i=this.db.prepare(`
|
|
148
|
+
INSERT INTO entries (type, title, content, summary, tags, related_files, timestamp)
|
|
149
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
150
|
+
`).run(e.type,e.title,e.content,t,JSON.stringify(e.tags),JSON.stringify(e.related_files),e.timestamp);return this.indexDirty=!0,Qt.debug("Entry stored",{id:Number(i.lastInsertRowid)}),Number(i.lastInsertRowid)}search(e,t,n=10){Qt.debug("FTS5 search",{query:e,type:t??"all",limit:n});let i=`
|
|
151
|
+
SELECT e.* FROM entries e
|
|
152
|
+
JOIN entries_fts f ON e.id = f.rowid
|
|
153
|
+
WHERE entries_fts MATCH ?
|
|
154
|
+
`,o=[e];return t&&(i+=" AND e.type = ?",o.push(t)),i+=" ORDER BY rank LIMIT ?",o.push(n),this.db.prepare(i).all(...o).map(this.rowToEntry)}timeline(e,t,n){let i="SELECT * FROM entries WHERE timestamp >= ?",o=[this.normalizeDate(e)];return t&&(i+=" AND timestamp <= ?",o.push(this.normalizeDate(t))),n&&(i+=" AND type = ?",o.push(n)),i+=" ORDER BY timestamp DESC",this.db.prepare(i).all(...o).map(this.rowToEntry)}patternStats(e){let t=e?this.db.prepare("SELECT * FROM entries WHERE tags LIKE ?").all(`%"${e}"%`):this.db.prepare("SELECT * FROM entries").all(),n={},i={},o={};for(let s of t){let a=s.type;n[a]=(n[a]??0)+1;let c=JSON.parse(s.tags);for(let u of c)i[u]=(i[u]??0)+1;let l=s.timestamp.slice(0,10);o[l]=(o[l]??0)+1}return{total_entries:t.length,by_type:n,by_tag:i,recent_activity:Object.entries(o).sort(([s],[a])=>a.localeCompare(s)).slice(0,14).map(([s,a])=>({date:s,count:a}))}}exportAll(){let e=this.db.prepare("SELECT * FROM entries ORDER BY timestamp DESC").all(),t={};for(let i of e){let o=this.rowToEntry(i);t[o.type]||(t[o.type]=[]),t[o.type].push(o)}let n=`# Catalyst Knowledge Base Export
|
|
155
|
+
|
|
156
|
+
`;n+=`Generated: ${new Date().toISOString()}
|
|
157
|
+
`,n+=`Total entries: ${e.length}
|
|
158
|
+
|
|
159
|
+
`;for(let[i,o]of Object.entries(t)){n+=`## ${i.charAt(0).toUpperCase()+i.slice(1)}s
|
|
160
|
+
|
|
161
|
+
`;for(let s of o)n+=`### ${s.title}
|
|
162
|
+
`,n+=`*${s.timestamp.slice(0,10)}* | Tags: ${s.tags.join(", ")}
|
|
163
|
+
|
|
164
|
+
`,n+=`${s.content}
|
|
165
|
+
|
|
166
|
+
`,s.related_files.length>0&&(n+=`Related: ${s.related_files.join(", ")}
|
|
167
|
+
|
|
168
|
+
`),n+=`---
|
|
169
|
+
|
|
170
|
+
`}return n}semanticSearch(e,t,n=10){Qt.debug("TF-IDF semantic search",{query:e,type:t??"all",limit:n}),this.refreshIndex();let i=this.tfidf.search(e,n*2);if(i.length===0)return this.search(e,t,n).map(p=>({...p,score:0}));let o=i.map(p=>p.id),s=new Map(i.map(p=>[p.id,p.score])),c=`SELECT * FROM entries WHERE id IN (${o.map(()=>"?").join(",")})`,l=[...o];return t&&(c+=" AND type = ?",l.push(t)),this.db.prepare(c).all(...l).map(p=>({...this.rowToEntry(p),score:s.get(p.id)??0})).sort((p,d)=>d.score-p.score).slice(0,n)}searchSummaries(e,t,n=20){this.refreshIndex();let i=this.tfidf.search(e,n*2);if(i.length===0){let p=`
|
|
171
|
+
SELECT e.id, e.type, e.title, e.summary, e.tags, e.timestamp
|
|
172
|
+
FROM entries e JOIN entries_fts f ON e.id = f.rowid
|
|
173
|
+
WHERE entries_fts MATCH ?
|
|
174
|
+
`,d=[e];return t&&(p+=" AND e.type = ?",d.push(t)),p+=" ORDER BY rank LIMIT ?",d.push(n),this.db.prepare(p).all(...d).map(this.rowToSummary)}let o=i.map(p=>p.id),s=new Map(i.map(p=>[p.id,p.score])),c=`SELECT id, type, title, summary, tags, timestamp FROM entries WHERE id IN (${o.map(()=>"?").join(",")})`,l=[...o];return t&&(c+=" AND type = ?",l.push(t)),this.db.prepare(c).all(...l).map(p=>({...this.rowToSummary(p),_score:s.get(p.id)??0})).sort((p,d)=>d._score-p._score).slice(0,n).map(({_score:p,...d})=>d)}getById(e){let t=this.db.prepare("SELECT * FROM entries WHERE id = ?").get(e);return t?this.rowToEntry(t):null}refreshIndex(){if(!this.indexDirty)return;let e=this.db.prepare("SELECT id, title || ' ' || content || ' ' || tags AS text FROM entries").all();this.tfidf.buildIndex(e),this.indexDirty=!1}autoSummarize(e){let t=e.match(/^[^.!?\n]+[.!?]?/)?.[0]??e;return t.length>120?t.slice(0,117)+"...":t}rowToSummary(e){return{id:e.id,type:e.type,title:e.title,summary:e.summary||e.title,tags:JSON.parse(e.tags),timestamp:e.timestamp}}rowToEntry(e){return{id:e.id,type:e.type,title:e.title,content:e.content,summary:e.summary||"",tags:JSON.parse(e.tags),related_files:JSON.parse(e.related_files),timestamp:e.timestamp}}normalizeDate(e){let t=e.match(/^(\d+)\s+(day|week|month|year)s?\s+ago$/i);if(t){let n=parseInt(t[1]),i=t[2].toLowerCase(),o=new Date;switch(i){case"day":o.setDate(o.getDate()-n);break;case"week":o.setDate(o.getDate()-n*7);break;case"month":o.setMonth(o.getMonth()-n);break;case"year":o.setFullYear(o.getFullYear()-n);break}return o.toISOString()}return e}purge(e){let t=new Date;t.setDate(t.getDate()-e);let n=t.toISOString();Qt.info("Purging knowledge entries",{olderThanDays:e,cutoff:n});let i=this.db.prepare("DELETE FROM entries WHERE timestamp < ?").run(n);return this.indexDirty=!0,Qt.info("Purged entries",{deleted:i.changes}),i.changes}};var nn=oe("git"),rd=null;function QC(){return rd||(rd=new pt),rd}function YC(r,e){let t=r.toLowerCase(),n=[{pattern:/\bdecision:\s*/i,type:"decision"},{pattern:/\blesson:\s*/i,type:"lesson"},{pattern:/\bpattern:\s*/i,type:"pattern"},{pattern:/\bbreaking[\s-]?change/i,type:"decision"},{pattern:/\brefactor\(/i,type:"pattern"}];for(let{pattern:i,type:o}of n)if(i.test(r))try{nn.info("Auto-capturing commit as knowledge",{type:o,message:r.slice(0,80)});let s=[];try{s=(my("git",["diff","HEAD~1","--name-only"],{cwd:e??process.cwd(),encoding:"utf-8",timeout:5e3}).stdout??"").trim().split(`
|
|
175
|
+
`).filter(Boolean)}catch{}return QC().store({type:o,title:r.split(`
|
|
176
|
+
`)[0].slice(0,120),content:`Auto-captured from commit:
|
|
177
|
+
${r}${s.length?`
|
|
178
|
+
|
|
179
|
+
Changed files:
|
|
180
|
+
${s.map(a=>`- ${a}`).join(`
|
|
181
|
+
`)}`:""}`,tags:["auto-captured","git-commit",o],related_files:s.slice(0,10),timestamp:new Date().toISOString()}),`
|
|
182
|
+
\u{1F4DA} Auto-captured as [${o}] in knowledge base.`}catch(s){nn.debug("Auto-capture skipped",{error:s.message})}return""}function Nt(r,e){let t=my("git",r,{cwd:e??process.cwd(),encoding:"utf-8",timeout:15e3,env:{...process.env,GIT_PAGER:""}});if(t.status!==0&&t.stderr?.trim())throw new Error(t.stderr.trim());return(t.stdout??"").trim()}function fy(r){r.tool("catalyst_git_status","Get git status: staged, unstaged, and untracked files",{cwd:g.string().optional().describe("Repository path")},async({cwd:e})=>{nn.info("Getting git status");let t=Nt(["status","--porcelain=v2","--branch"],e),n=Nt(["diff","--stat"],e);return{content:[{type:"text",text:`${t}
|
|
183
|
+
|
|
184
|
+
--- Diff Summary ---
|
|
185
|
+
${n}`}]}}),r.tool("catalyst_git_diff","Get diff for staged, unstaged, or between refs",{target:g.enum(["staged","unstaged","head","refs"]).describe("What to diff: staged, unstaged, head (last commit), or refs (between two refs)"),from:g.string().optional().describe("Start ref (for refs mode)"),to:g.string().optional().describe("End ref (for refs mode, default: HEAD)"),path:g.string().optional().describe("Limit diff to a specific file or directory"),cwd:g.string().optional().describe("Repository path")},async({target:e,from:t,to:n,path:i,cwd:o})=>{nn.info("Getting diff",{target:e,from:t,to:n,path:i});let s=["diff"];switch(e){case"staged":s.push("--cached");break;case"unstaged":break;case"head":s.push("HEAD~1","HEAD");break;case"refs":s.push(`${t??"main"}..${n??"HEAD"}`);break}return i&&s.push("--",i),{content:[{type:"text",text:Nt(s,o)||"(no differences)"}]}}),r.tool("catalyst_git_log","Get commit history with optional filtering",{count:g.number().optional().describe("Number of commits (default: 20)"),since:g.string().optional().describe("Date filter, e.g. '1 week ago'"),author:g.string().optional().describe("Filter by author"),path:g.string().optional().describe("Filter by file path"),format:g.enum(["oneline","full","json"]).optional().describe("Output format (default: oneline)"),cwd:g.string().optional().describe("Repository path")},async({count:e,since:t,author:n,path:i,format:o,cwd:s})=>{nn.info("Getting commit history",{count:e??20,since:t,author:n});let a=e??20,c;switch(o){case"full":c="--format=fuller";break;case"json":c='--format={"hash":"%H","short":"%h","author":"%an","date":"%ai","subject":"%s"},';break;default:c="--oneline"}let l=["log",`-${a}`,c];return t&&l.push(`--since=${t}`),n&&l.push(`--author=${n}`),i&&l.push("--",i),{content:[{type:"text",text:Nt(l,s)||"(no commits found)"}]}}),r.tool("catalyst_git_stage","Stage files for commit",{files:g.array(g.string()).describe("Files to stage (use ['.'] for all)"),cwd:g.string().optional().describe("Repository path")},async({files:e,cwd:t})=>(nn.info("Staging files",{files:e}),Nt(["add",...e],t),{content:[{type:"text",text:`Staged.
|
|
186
|
+
${Nt(["status","--short"],t)}`}]})),r.tool("catalyst_git_commit","Create a commit with a message",{message:g.string().describe("Commit message (conventional format recommended)"),cwd:g.string().optional().describe("Repository path")},async({message:e,cwd:t})=>{nn.info("Committing",{message:e.slice(0,80)});let n=Nt(["commit","-m",e],t),i=YC(e,t);return{content:[{type:"text",text:n+i}]}}),r.tool("catalyst_git_branch","List, create, or switch branches",{action:g.enum(["list","create","switch"]).describe("Branch operation"),name:g.string().optional().describe("Branch name (for create/switch)"),cwd:g.string().optional().describe("Repository path")},async({action:e,name:t,cwd:n})=>{let i;switch(e){case"list":i=Nt(["branch","-a","--format=%(refname:short) %(objectname:short) %(subject)"],n);break;case"create":if(!t)throw new Error("Branch name required for create");i=Nt(["checkout","-b",t],n);break;case"switch":if(!t)throw new Error("Branch name required for switch");i=Nt(["checkout",t],n);break}return{content:[{type:"text",text:i}]}})}var on=oe("knowledge"),nd=null;function Yt(){return nd||(nd=new pt),nd}function hy(r){r.tool("catalyst_knowledge_store","Store a decision, lesson learned, or pattern in the persistent knowledge base",{type:g.enum(["decision","lesson","pattern","convention"]).describe("Entry type"),title:g.string().describe("Short title for the entry"),content:g.string().describe("Full content \u2014 decision rationale, lesson details, or pattern description"),tags:g.array(g.string()).describe("Category tags (e.g., architecture, security, performance)"),related_files:g.array(g.string()).optional().describe("Related file paths in the project")},async({type:e,title:t,content:n,tags:i,related_files:o})=>{on.info("Storing knowledge entry",{type:e,title:t});let a=Yt().store({type:e,title:t,content:n,tags:i,related_files:o??[],timestamp:new Date().toISOString()});return{content:[{type:"text",text:`Stored: [${e}] "${t}" (id: ${a})
|
|
187
|
+
Tags: ${i.join(", ")}`}]}}),r.tool("catalyst_knowledge_search","Search the knowledge base using full-text search",{query:g.string().describe("Search query \u2014 natural language or keywords"),type:g.enum(["decision","lesson","pattern","convention","all"]).optional().describe("Filter by entry type (default: all)"),limit:g.number().optional().describe("Max results (default: 10)")},async({query:e,type:t,limit:n})=>{on.info("Searching knowledge (FTS5)",{query:e,type:t??"all"});let o=Yt().search(e,t==="all"?void 0:t,n??10);if(o.length===0)return{content:[{type:"text",text:`No results for "${e}"`}]};let s=o.map((a,c)=>`${c+1}. [${a.type}] ${a.title} (${a.timestamp.slice(0,10)})
|
|
188
|
+
${a.content.slice(0,200)}${a.content.length>200?"...":""}
|
|
189
|
+
Tags: ${a.tags.join(", ")}`).join(`
|
|
190
|
+
|
|
191
|
+
`);return{content:[{type:"text",text:`Found ${o.length} results:
|
|
192
|
+
|
|
193
|
+
${s}`}]}}),r.tool("catalyst_knowledge_timeline","Retrieve knowledge entries within a time range",{since:g.string().describe("Start date (ISO format or natural like '1 week ago')"),until:g.string().optional().describe("End date (default: now)"),type:g.enum(["decision","lesson","pattern","convention","all"]).optional().describe("Filter by type")},async({since:e,until:t,type:n})=>{on.info("Querying knowledge timeline",{since:e,until:t,type:n??"all"});let o=Yt().timeline(e,t,n==="all"?void 0:n);if(o.length===0)return{content:[{type:"text",text:"No entries in this time range."}]};let s=o.reduce((c,l)=>{let u=l.timestamp.slice(0,10);return(c[u]??=[]).push(l),c},{});return{content:[{type:"text",text:Object.entries(s).map(([c,l])=>`### ${c}
|
|
194
|
+
${l.map(u=>`- [${u.type}] ${u.title}`).join(`
|
|
195
|
+
`)}`).join(`
|
|
196
|
+
|
|
197
|
+
`)}]}}),r.tool("catalyst_knowledge_patterns","Analyze pattern frequency and trends in the knowledge base",{tag:g.string().optional().describe("Filter by tag")},async({tag:e})=>{on.info("Analyzing pattern stats",{tag:e??"all"});let n=Yt().patternStats(e);return{content:[{type:"text",text:JSON.stringify(n,null,2)}]}}),r.tool("catalyst_knowledge_export","Export the full knowledge base as a structured markdown document",{},async()=>(on.info("Exporting full knowledge base"),{content:[{type:"text",text:Yt().exportAll()}]})),r.tool("catalyst_knowledge_semantic_search","Search the knowledge base using TF-IDF cosine similarity for better relevance ranking",{query:g.string().describe("Natural language search query"),type:g.enum(["decision","lesson","pattern","convention","all"]).optional().describe("Filter by entry type (default: all)"),limit:g.number().optional().describe("Max results (default: 10)")},async({query:e,type:t,limit:n})=>{on.info("Semantic search (TF-IDF)",{query:e,type:t??"all"});let o=Yt().semanticSearch(e,t==="all"?void 0:t,n??10);if(o.length===0)return{content:[{type:"text",text:`No results for "${e}"`}]};let s=o.map((a,c)=>`${c+1}. [${a.type}] ${a.title} (score: ${a.score.toFixed(3)})
|
|
198
|
+
${a.content.slice(0,200)}${a.content.length>200?"...":""}
|
|
199
|
+
Tags: ${a.tags.join(", ")}`).join(`
|
|
200
|
+
|
|
201
|
+
`);return{content:[{type:"text",text:`Found ${o.length} results:
|
|
202
|
+
|
|
203
|
+
${s}`}]}}),r.tool("catalyst_knowledge_summaries","Progressive disclosure: search and return compact summaries (not full content). Use catalyst_knowledge_get to expand.",{query:g.string().describe("Search query"),type:g.enum(["decision","lesson","pattern","convention","all"]).optional().describe("Filter by entry type"),limit:g.number().optional().describe("Max results (default: 20)")},async({query:e,type:t,limit:n})=>{let o=Yt().searchSummaries(e,t==="all"?void 0:t,n??20);if(o.length===0)return{content:[{type:"text",text:`No results for "${e}"`}]};let s=o.map((a,c)=>`${c+1}. [${a.type}] #${a.id} \u2014 ${a.title}
|
|
204
|
+
${a.summary}
|
|
205
|
+
Tags: ${a.tags.join(", ")}`).join(`
|
|
206
|
+
|
|
207
|
+
`);return{content:[{type:"text",text:`Found ${o.length} summaries:
|
|
208
|
+
|
|
209
|
+
${s}
|
|
210
|
+
|
|
211
|
+
Use catalyst_knowledge_get with an id to see full content.`}]}}),r.tool("catalyst_knowledge_get","Fetch a single knowledge entry by ID (use after searching summaries)",{id:g.number().describe("Entry ID")},async({id:e})=>{let n=Yt().getById(e);return n?{content:[{type:"text",text:`[${n.type}] ${n.title}
|
|
212
|
+
|
|
213
|
+
${n.content}
|
|
214
|
+
|
|
215
|
+
Tags: ${n.tags.join(", ")}
|
|
216
|
+
Files: ${n.related_files.join(", ")||"none"}
|
|
217
|
+
Date: ${n.timestamp}`}]}:{content:[{type:"text",text:`No entry with id ${e}`}]}}),r.tool("catalyst_knowledge_purge","Delete knowledge entries older than a given number of days. Use for retention management. Irreversible \u2014 confirm with the user first.",{older_than_days:g.number().min(1).describe("Delete entries older than this many days")},async({older_than_days:e})=>(on.info("Purging old entries",{older_than_days:e}),{content:[{type:"text",text:`Purged ${Yt().purge(e)} entries older than ${e} days.`}]}))}import{execSync as eI}from"node:child_process";var id=oe("metrics");function jt(r,e){try{return eI(r,{cwd:e??process.cwd(),encoding:"utf-8",timeout:6e4,env:{...process.env,FORCE_COLOR:"0"}}).trim()}catch(t){let n=t;return n.stdout||n.stderr||n.message}}function gy(r){r.tool("catalyst_metrics_coverage","Run test coverage and return a summary report. Optionally compare against another branch for delta analysis.",{command:g.string().optional().describe("Custom coverage command (auto-detected if omitted)"),cwd:g.string().optional().describe("Project directory"),compare_branch:g.string().optional().describe("Branch to compare coverage against (e.g., 'main'). Runs coverage on both branches and shows delta.")},async({command:e,cwd:t,compare_branch:n})=>{id.info("Running test coverage",{command:e??"auto-detect",compareBranch:n});let i=t??process.cwd(),o=e;if(!o){let a=await import("node:fs");if(a.existsSync(`${i}/package.json`)){let c=JSON.parse(a.readFileSync(`${i}/package.json`,"utf-8"));c.scripts?.["test:coverage"]?o="npm run test:coverage":c.scripts?.test&&(o="npx jest --coverage --coverageReporters=text-summary 2>&1 || npx vitest run --coverage 2>&1 || npm test 2>&1")}else(a.existsSync(`${i}/pytest.ini`)||a.existsSync(`${i}/setup.py`))&&(o="python -m pytest --cov --cov-report=term-summary 2>&1");o||(o="echo 'Could not auto-detect test runner. Provide a command.'")}let s=jt(o,i);if(n)try{let a=jt("git rev-parse --abbrev-ref HEAD",i),c=jt("git status --porcelain",i).length>0;c&&jt("git stash --include-untracked",i),jt(`git checkout ${n}`,i);let l=jt(o,i);jt(`git checkout ${a}`,i),c&&jt("git stash pop",i);let u=m=>{let h=m.match(/(?:All files|TOTAL|Stmts|Lines)\s*[|:]\s*(\d+(?:\.\d+)?)\s*%/i)??m.match(/(\d+(?:\.\d+)?)\s*%\s*(?:coverage|covered|statements|lines)/i);return h?parseFloat(h[1]):null},p=u(s),d=u(l),f="";if(p!==null&&d!==null){let m=p-d,h=m>0?"\u{1F4C8}":m<0?"\u{1F4C9}":"\u27A1\uFE0F";f=`
|
|
218
|
+
|
|
219
|
+
--- Coverage Delta (vs ${n}) ---
|
|
220
|
+
${h} ${a}: ${p}% | ${n}: ${d}% | Delta: ${m>0?"+":""}${m.toFixed(1)}%`}else f=`
|
|
221
|
+
|
|
222
|
+
--- Coverage on ${n} ---
|
|
223
|
+
${l}`;return{content:[{type:"text",text:s+f}]}}catch(a){return{content:[{type:"text",text:s+`
|
|
224
|
+
|
|
225
|
+
(Coverage delta failed: ${a.message})`}]}}return{content:[{type:"text",text:s}]}}),r.tool("catalyst_metrics_complexity","Analyze code complexity (cyclomatic, cognitive, nesting depth) for files or directories",{target:g.string().describe("File or directory path to analyze"),cwd:g.string().optional().describe("Project root")},async({target:e,cwd:t})=>{id.info("Analyzing complexity",{target:e});let n=t??process.cwd(),i=jt(`find "${e}" -type f \\( -name "*.ts" -o -name "*.js" -o -name "*.py" -o -name "*.java" \\) | head -20 | while read f; do echo "=== $f ==="; wc -l "$f"; grep -c "if\\|for\\|while\\|switch\\|catch\\|&&\\|||\\|?" "$f" 2>/dev/null || echo "0 complexity indicators"; echo; done`,n);return{content:[{type:"text",text:`Complexity analysis for ${e}:
|
|
226
|
+
|
|
227
|
+
${i}`}]}}),r.tool("catalyst_metrics_bundle","Analyze JavaScript/TypeScript bundle size and composition",{command:g.string().optional().describe("Custom bundle analysis command (auto-detected if omitted)"),cwd:g.string().optional().describe("Project directory")},async({command:e,cwd:t})=>{id.info("Analyzing bundle size",{command:e??"auto-detect"});let n=t??process.cwd(),i=e;return i||(i='du -sh dist/ build/ .next/ 2>/dev/null || echo "No build output found. Run a build first."'),{content:[{type:"text",text:jt(i,n)}]}})}var sa=oe("dispatch"),od=null;function tI(){return od||(od=new pt),od}var rI={code:[{name:"Correctness",focus:"Logic errors, edge cases, error handling",prompt:"Review this code focusing exclusively on correctness: logic errors, off-by-one, null safety, edge cases, error handling. Ignore style."},{name:"Security",focus:"Vulnerabilities, injection, data exposure",prompt:"Review this code focusing exclusively on security: injection vectors, auth gaps, data exposure, OWASP Top 10 relevance. Ignore style."},{name:"Performance",focus:"Algorithmic complexity, resource usage, bottlenecks",prompt:"Review this code focusing exclusively on performance: O(n\xB2) patterns, unnecessary allocations, N+1 queries, caching opportunities. Ignore style."},{name:"Maintainability",focus:"Readability, coupling, naming, structure",prompt:"Review this code focusing exclusively on maintainability: naming clarity, coupling, cohesion, function length, SOLID adherence. Ignore micro-style."}],architecture:[{name:"Scalability",focus:"Can this grow? Bottlenecks? Horizontal scaling?",prompt:"Evaluate this architecture focusing on scalability: bottlenecks, stateful components, data partitioning, horizontal scaling ability."},{name:"Reliability",focus:"Failure modes, recovery, degradation",prompt:"Evaluate this architecture focusing on reliability: single points of failure, retry strategies, circuit breakers, graceful degradation, data durability."},{name:"Operability",focus:"Monitoring, debugging, deployment, rollback",prompt:"Evaluate this architecture focusing on operability: observability, health checks, logging, deployment strategy, rollback capability, configuration management."}]};function vy(r){r.tool("catalyst_dispatch_review","Generate structured multi-perspective review prompts for code or architecture. Returns prompts that the client should evaluate independently.",{domain:g.enum(["code","architecture"]).describe("Review domain \u2014 determines which perspectives to use"),context:g.string().describe("The code or architecture description to review"),custom_perspectives:g.array(g.object({name:g.string(),focus:g.string(),prompt:g.string()})).optional().describe("Custom perspectives to use instead of defaults")},async({domain:e,context:t,custom_perspectives:n})=>{let i=n??rI[e]??[];sa.info("Generating review prompts",{domain:e,perspectives:i.length});let o="";try{let a=tI().semanticSearch(t.slice(0,200),void 0,5);a.length>0&&(sa.debug("Injecting past knowledge into review",{count:a.length}),o=`
|
|
228
|
+
|
|
229
|
+
--- Past Knowledge (from previous reviews/decisions) ---
|
|
230
|
+
`+a.map(c=>`\u2022 [${c.type}] ${c.title}: ${c.content.slice(0,150)}`).join(`
|
|
231
|
+
`)+`
|
|
232
|
+
--- Consider these patterns when reviewing. ---`)}catch{sa.debug("Knowledge not available for review context")}let s=i.map(a=>({perspective:a.name,focus:a.focus,full_prompt:`${a.prompt}${o}
|
|
233
|
+
|
|
234
|
+
---
|
|
235
|
+
|
|
236
|
+
${t}`}));return{content:[{type:"text",text:JSON.stringify({domain:e,perspectives_count:s.length,prompts:s,instructions:"Evaluate each prompt independently. Synthesize findings into a unified report, noting where perspectives agree (high confidence) and disagree (needs discussion)."},null,2)}]}}),r.tool("catalyst_dispatch_parallel","Structure a task for parallel execution by breaking it into independent sub-tasks",{task:g.string().describe("The overall task description"),subtasks:g.array(g.object({id:g.string(),description:g.string(),dependencies:g.array(g.string()).optional()})).describe("Sub-tasks with optional dependency declarations")},async({task:e,subtasks:t})=>{sa.info("Planning parallel execution",{task:e.slice(0,60),subtasks:t.length});let n=new Map;for(let c of t)n.set(c.id,c.dependencies??[]);let i=[],o=new Set,s=new Set(t.map(c=>c.id));for(;s.size>0;){let c=[...s].filter(l=>(n.get(l)??[]).every(u=>o.has(u)));if(c.length===0)return{content:[{type:"text",text:`Circular dependency detected among: ${[...s].join(", ")}`}],isError:!0};i.push(c);for(let l of c)o.add(l),s.delete(l)}let a=i.map((c,l)=>({wave:l+1,parallel:c.length>1,tasks:c.map(u=>t.find(p=>p.id===u))}));return{content:[{type:"text",text:JSON.stringify({task:e,total_subtasks:t.length,waves:a.length,execution_plan:a},null,2)}]}}),r.tool("catalyst_dispatch_consensus","Merge multiple review perspectives into a consensus report with confidence scoring",{perspectives:g.array(g.object({name:g.string().describe("Perspective name"),findings:g.array(g.string()).describe("List of findings from this perspective"),severity:g.enum(["critical","high","medium","low"]).describe("Overall severity from this perspective")})).describe("Results from multiple review perspectives")},async({perspectives:e})=>{let t=e.flatMap(s=>s.findings.map(a=>({perspective:s.name,finding:a,severity:s.severity}))),n=s=>new Set(s.toLowerCase().split(/\s+/).filter(a=>a.length>3)),i=[];for(let s of t){let a=n(s.finding),c=!1;for(let l of i){let u=n(l.findings[0].finding);if([...a].filter(d=>u.has(d)).length>=2){l.findings.push(s),l.agreement=l.findings.length,c=!0;break}}c||i.push({findings:[s],agreement:1})}let o=i.sort((s,a)=>a.agreement-s.agreement).map(s=>({finding:s.findings[0].finding,agreed_by:s.findings.map(a=>a.perspective),confidence:Math.round(s.agreement/e.length*100),severity:s.findings.sort((a,c)=>{let l={critical:0,high:1,medium:2,low:3};return l[a.severity]-l[c.severity]})[0].severity}));return{content:[{type:"text",text:JSON.stringify({total_perspectives:e.length,unique_findings:i.length,consensus_findings:o.filter(s=>s.confidence>=50),disputed_findings:o.filter(s=>s.confidence<50)},null,2)}]}})}import{execSync as cn,spawnSync as ud}from"node:child_process";import{readFileSync as by,existsSync as wy}from"node:fs";import{join as ky}from"node:path";import{execSync as _y,spawnSync as ke}from"node:child_process";import{readFileSync as nI,existsSync as iI}from"node:fs";import{join as xy}from"node:path";var Qe=oe("board"),cd=class{provider="github";repo;projectConfig=null;constructor(e){this.repo=e??this.detectRepo(),Qe.info("GitHub board adapter connecting",{repo:this.repo});try{this.detectProject()}catch(t){Qe.debug("Project detection skipped",{reason:t.message})}}detectRepo(){try{return this.exec("git remote get-url origin").match(/github\.com[:/](.+?)(?:\.git)?$/)?.[1]??""}catch{return""}}detectProject(){let e=this.repo.split("/")[0];if(!e)return;let t=this.repo.split("/")[1]?.toLowerCase()??"",i=JSON.parse(this.exec(`gh project list --owner ${e} --format json --limit 5`)).projects?.filter(l=>!l.closed)??[];if(i.length===0)return;let o=i.find(l=>l.title.toLowerCase()===t)??i.find(l=>l.title.toLowerCase().includes(t))??i.sort((l,u)=>(u.items?.totalCount??0)-(l.items?.totalCount??0))[0];if(!o)return;let a=JSON.parse(this.exec(`gh project field-list ${o.number} --owner ${e} --format json`)).fields?.find(l=>l.name==="Status"&&l.type==="ProjectV2SingleSelectField");if(!a?.options)return;let c={};for(let l of a.options)c[l.name]=l.id;this.projectConfig={projectNumber:o.number,owner:e,statusFieldId:a.id,statusOptions:c}}getProjectItemId(e){if(!this.projectConfig)return null;let{projectNumber:t,owner:n}=this.projectConfig;return JSON.parse(this.exec(`gh project item-list ${t} --owner ${n} --format json --limit 200`)).items?.find(s=>s.content?.type==="Issue"&&String(s.content.number)===e)?.id??null}setProjectStatus(e,t){if(!this.projectConfig)return!1;let i={todo:"Todo","in-progress":"In Progress","in-review":"In Review",done:"Done"}[t]??t,o=this.projectConfig.statusOptions[i];if(!o)return!1;let s=this.getProjectItemId(e);if(!s)return!1;let{projectNumber:a,owner:c,statusFieldId:l}=this.projectConfig,u=this.getProjectNodeId(a,c);return u?(ke("gh",["project","item-edit","--project-id",u,"--id",s,"--field-id",l,"--single-select-option-id",o],{encoding:"utf-8",timeout:15e3,env:{...process.env,GH_FORCE_TTY:"0",NO_COLOR:"1"}}),!0):!1}getProjectNodeId(e,t){try{return JSON.parse(this.exec(`gh project list --owner ${t} --format json --limit 5`)).projects?.find(i=>i.number===e)?.id??null}catch{return null}}addToProject(e){if(!this.projectConfig)return;let{projectNumber:t,owner:n}=this.projectConfig;this.getProjectNodeId(t,n)&&ke("gh",["project","item-add",String(t),"--owner",n,"--url",e],{encoding:"utf-8",timeout:15e3,env:{...process.env,GH_FORCE_TTY:"0",NO_COLOR:"1"}})}getProjectBoardStatus(e){if(!this.projectConfig)return null;let{projectNumber:t,owner:n}=this.projectConfig;return JSON.parse(this.exec(`gh project item-list ${t} --owner ${n} --format json --limit 200`)).items?.find(s=>s.content?.type==="Issue"&&String(s.content.number)===e)?.status??null}exec(e){return _y(e,{encoding:"utf-8",timeout:15e3,env:{...process.env,GH_FORCE_TTY:"0",NO_COLOR:"1"}}).trim()}ghJson(e){let t=this.exec(`gh ${e}`);return t?JSON.parse(t):(Qe.debug("GitHub CLI returned empty output",{args:e.slice(0,30)}),[])}listMyItems(e,t){Qe.debug("Listing my items",{status:e??"all",labels:t??[]});let n="gh issue list --assignee=@me --json number,title,body,state,labels,assignees,url --limit 50";return(e==="open"||e==="closed")&&(n+=` --state ${e}`),t?.length&&(n+=` --label "${t.join(",")}"`),this.ghJson(n.replace("gh ","")).map(sd)}getItem(e){try{let t=this.ghJson(`issue view ${e} --json number,title,body,state,labels,assignees,url`);return sd(t)}catch{return null}}createItem(e){Qe.info("Creating board item",{title:e.title,assignee:e.assignee??"unassigned"});let t=["issue","create","--title",e.title,"--body-file","-"];e.assignee&&t.push("--assignee",e.assignee),e.labels?.length&&t.push("--label",e.labels.join(","));let n=ke("gh",t,{input:e.description,encoding:"utf-8",timeout:15e3,env:{...process.env,GH_FORCE_TTY:"0",NO_COLOR:"1"}}),i=(n.stdout??"").trim();if(n.status!==0)throw new Error(n.stderr?.trim()||"Failed to create issue");let o=i.match(/#(\d+)|\/issues\/(\d+)/)?.[1]??i.match(/\/(\d+)$/)?.[1]??"",s=this.getItem(o)??{id:o,title:e.title,description:e.description,status:"open",assignee:e.assignee??"",labels:e.labels??[],priority:e.priority??"",points:e.points??null,url:i};try{this.addToProject(i.startsWith("http")?i:s.url),this.setProjectStatus(o,"todo")}catch{}return s}updateStatus(e,t){if(Qe.info("Updating item status",{id:e,status:t}),t==="done")try{this.exec(`gh issue close ${e}`)}catch{}else t==="closed"?this.exec(`gh issue close ${e}`):(t==="open"||t==="reopen")&&this.exec(`gh issue reopen ${e}`);if(!this.setProjectStatus(e,t)){let i=`status:${t}`;ke("gh",["label","create",i,"--color","ededed","--force"],{encoding:"utf-8",timeout:1e4,env:{...process.env,GH_FORCE_TTY:"0",NO_COLOR:"1"}});try{let s=(ke("gh",["issue","view",e,"--json","labels","--jq",".labels[].name"],{encoding:"utf-8",timeout:1e4,env:{...process.env,GH_FORCE_TTY:"0",NO_COLOR:"1"}}).stdout??"").split(`
|
|
237
|
+
`).filter(a=>a.startsWith("status:"));for(let a of s)ke("gh",["issue","edit",e,"--remove-label",a],{encoding:"utf-8",timeout:1e4,env:{...process.env,GH_FORCE_TTY:"0",NO_COLOR:"1"}})}catch{}this.exec(`gh issue edit ${e} --add-label "${yy(i)}"`)}}assign(e,t){this.exec(`gh issue edit ${e} --add-assignee "${yy(t)}"`)}addComment(e,t){let n=ke("gh",["issue","comment",e,"--body-file","-"],{input:t,encoding:"utf-8",timeout:15e3,env:{...process.env,GH_FORCE_TTY:"0",NO_COLOR:"1"}});if(n.status!==0)throw new Error(n.stderr?.trim()||"Failed to add comment")}createEpic(e){let t=[...e.labels??[],"epic"];return this.createItem({...e,labels:t})}createSubtask(e,t){let n=[...t.labels??[],"subtask",`parent:#${e}`],i=`> Parent: #${e}
|
|
238
|
+
|
|
239
|
+
${t.description}`,o=this.createItem({...t,description:i,labels:n});try{this.addComment(e,`Subtask created: #${o.id} \u2014 ${o.title}`)}catch{}return o}linkPR(e,t){this.addComment(e,`Linked to PR #${t}`)}listColumns(){return["Todo","In Progress","In Review","Done"]}getBoardView(){if(this.projectConfig){let{projectNumber:i,owner:o}=this.projectConfig,s=JSON.parse(this.exec(`gh project item-list ${i} --owner ${o} --format json --limit 200`)),a={};for(let c of this.listColumns())a[c]=[];for(let c of s.items??[]){if(c.content?.type!=="Issue")continue;let l=c.status||"Todo",u={id:String(c.content.number),title:c.title,description:"",status:l,assignee:c.assignees?.[0]??"",labels:[],priority:"",points:null,url:c.content.url??""};(a[l]??=[]).push(u)}return Object.entries(a).map(([c,l])=>({name:c,items:l}))}let t=this.ghJson("issue list --json number,title,body,state,labels,assignees,url --limit 100 --state all").map(sd),n={};for(let i of this.listColumns())n[i]=[];for(let i of t){let o=i.labels.find(a=>a.startsWith("status:")),s=o?o.replace("status:",""):i.status;(n[s]??=[]).push(i)}return Object.entries(n).map(([i,o])=>({name:i,items:o}))}},ld=class{provider="azure";org;project;constructor(e,t){this.org=e,this.project=t}exec(e){return _y(e,{encoding:"utf-8",timeout:15e3,env:{...process.env}}).trim()}azSpawn(e,t){let n=["boards",...e,"--org",`https://dev.azure.com/${this.org}`];t?.noProject||n.push("--project",this.project),n.push("-o","json");let i=ke("az",n,{encoding:"utf-8",timeout:15e3,env:{...process.env}});if(i.error)throw i.error;if(i.status!==0)throw new Error(i.stderr?.trim()||`az exited with code ${i.status}`);return i.stdout.trim()}azJson(e,t){let n=this.azSpawn(e,t);return n?JSON.parse(n):(Qe.debug("Azure CLI returned empty output",{args:e.slice(0,2)}),[])}listMyItems(e,t){let n="SELECT [System.Id], [System.Title], [System.State], [System.AssignedTo], [System.Description] FROM WorkItems WHERE [System.AssignedTo] = @Me";if(e&&(n+=` AND [System.State] = '${e}'`),t?.length){let o=t.map(s=>`[System.Tags] CONTAINS '${s}'`);n+=` AND (${o.join(" OR ")})`}return n+=" ORDER BY [System.ChangedDate] DESC",(this.azJson(["query","--wiql",n])??[]).map(sn)}getItem(e){try{let t=this.azJson(["work-item","show","--id",e],{noProject:!0});return sn(t)}catch{return null}}createItem(e){let t=["work-item","create","--type","Issue","--title",e.title,"--description",ad(e.description)];e.assignee&&t.push("--assigned-to",e.assignee);let n=this.azJson(t);return e.parentId&&this.linkToParent(String(n.id),e.parentId),sn(n)}createEpic(e){let t=["work-item","create","--type","Epic","--title",e.title,"--description",ad(e.description)];e.assignee&&t.push("--assigned-to",e.assignee);let n=this.azJson(t);return sn(n)}createSubtask(e,t){let n=["work-item","create","--type","Task","--title",t.title,"--description",ad(t.description)];t.assignee&&n.push("--assigned-to",t.assignee);let i=this.azJson(n);return this.linkToParent(String(i.id),e),sn(i)}linkToParent(e,t){try{let n=ke("az",["boards","work-item","relation","add","--id",e,"--relation-type","Parent","--target-id",t,"--org",`https://dev.azure.com/${this.org}`,"-o","json"],{encoding:"utf-8",timeout:15e3,env:{...process.env}});n.status!==0&&Qe.info("Failed to link parent",{childId:e,parentId:t,stderr:n.stderr})}catch{}}updateStatus(e,t){this.azSpawn(["work-item","update","--id",e,"--state",t],{noProject:!0})}assign(e,t){this.azSpawn(["work-item","update","--id",e,"--assigned-to",t],{noProject:!0})}addComment(e,t){let n=JSON.stringify({text:t}),i=`https://dev.azure.com/${this.org}/${this.project}/_apis/wit/workitems/${e}/comments?api-version=7.1-preview.4`,o=ke("az",["rest","--method","post","--uri",i,"--body",n,"--resource","499b84ac-1321-427f-aa17-267ca6975798"],{encoding:"utf-8",timeout:15e3,env:{...process.env}});if(o.error)throw o.error;if(o.status!==0)throw new Error(o.stderr?.trim()||`az rest exited with code ${o.status}`)}linkPR(e,t){this.addComment(e,`Linked to PR #${t}`)}listColumns(){return["New","Active","Resolved","Closed"]}getBoardView(){let e=`SELECT [System.Id], [System.Title], [System.State], [System.AssignedTo], [System.Description] FROM WorkItems WHERE [System.TeamProject] = '${this.project}' ORDER BY [System.ChangedDate] DESC`;try{let n=(this.azJson(["query","--wiql",e])??[]).map(sn),i={};for(let o of n){let s=o.status||"New";i[s]||(i[s]=[]),i[s].push(o)}return Object.entries(i).map(([o,s])=>({name:o,items:s}))}catch(t){Qe.info("getBoardView failed, falling back to per-state queries",{error:t.message});let n={};for(let i of this.listColumns()){let o=`SELECT [System.Id], [System.Title], [System.State], [System.AssignedTo], [System.Description] FROM WorkItems WHERE [System.State] = '${i}' AND [System.TeamProject] = '${this.project}' ORDER BY [System.ChangedDate] DESC`;try{let s=this.azJson(["query","--wiql",o]);n[i]=(s??[]).map(sn)}catch{n[i]=[]}}return Object.entries(n).map(([i,o])=>({name:i,items:o}))}}};function aa(){let r=process.cwd(),e=[xy(r,".github","catalyst.config.json"),xy(r,"..",".github","catalyst.config.json")];for(let t of e)if(iI(t))try{let i=JSON.parse(nI(t,"utf-8"))?.board;if(i?.provider){Qe.info("Loading board config from file",{path:t,provider:i.provider});let o={provider:i.provider};if(i.provider==="github")o.github={repo:i.github?.repo||void 0};else if(i.provider==="azure"){if(!i.azure?.org||!i.azure?.project)throw Qe.warn("Azure board config incomplete"),new Error("Azure board not configured. Set 'board.azure.org' and 'board.azure.project' in .github/catalyst.config.json, or call catalyst_board_connect with provider='azure', org='<your-org>', project='<your-project>'.");o.azure={org:i.azure.org,project:i.azure.project}}return o}}catch(n){if(n.message.startsWith("Azure board not configured"))throw n;Qe.debug("Could not read board config from file",{error:n.message})}return{provider:"github"}}function an(r){let e=[];if(r.provider==="github"){let t=ke("which",["gh"],{encoding:"utf-8"}).status===0;if(e.push({name:"gh CLI installed",ok:t,message:t?"gh CLI found":"gh CLI not found",fix:t?void 0:"Install: brew install gh (macOS) or https://cli.github.com"}),t){let n=ke("gh",["auth","status"],{encoding:"utf-8",timeout:1e4}),i=n.status===0,s=((n.stdout??"")+(n.stderr??"")).match(/Logged in to .+ account (.+?)[\s(]/);if(e.push({name:"GitHub authenticated",ok:i,message:i?`Authenticated${s?` as ${s[1]}`:""}`:"Not authenticated",fix:i?void 0:"Run: gh auth login"}),i){let a=r.github?.repo;if(a){let c=ke("gh",["repo","view",a,"--json","name"],{encoding:"utf-8",timeout:1e4});e.push({name:"Repository accessible",ok:c.status===0,message:c.status===0?`Repository ${a} accessible`:`Cannot access ${a}`,fix:c.status===0?void 0:`Check repo exists and you have access: gh repo view ${a}`})}else{let c=ke("git",["remote","get-url","origin"],{encoding:"utf-8",timeout:5e3}),l=c.status===0&&c.stdout.includes("github.com");e.push({name:"Repository detected",ok:l,message:l?"Auto-detected from git remote":"No GitHub repo detected from git remote",fix:l?void 0:"Run from a git repo with a GitHub remote, or specify repo: catalyst_board_connect({ provider: 'github', repo: 'owner/repo' })"})}}}}else if(r.provider==="azure"){let t=ke("which",["az"],{encoding:"utf-8"}).status===0;if(e.push({name:"az CLI installed",ok:t,message:t?"az CLI found":"az CLI not found",fix:t?void 0:"Install: brew install azure-cli (macOS) or https://aka.ms/install-azure-cli"}),t){let i=ke("az",["extension","show","--name","azure-devops"],{encoding:"utf-8",timeout:15e3}).status===0;e.push({name:"azure-devops extension",ok:i,message:i?"azure-devops extension installed":"azure-devops extension not found",fix:i?void 0:"Run: az extension add --name azure-devops"});let o=ke("az",["account","show","-o","json"],{encoding:"utf-8",timeout:1e4}),s=o.status===0,a="";if(s)try{a=JSON.parse(o.stdout).user?.name??""}catch{}if(e.push({name:"Azure authenticated",ok:s,message:s?`Authenticated${a?` as ${a}`:""}`:"Not authenticated",fix:s?void 0:"Run: az login"}),s&&r.azure?.org&&r.azure?.project){let c=ke("az",["boards","query","--wiql",`SELECT [System.Id] FROM WorkItems WHERE [System.TeamProject] = '${r.azure.project}'`,"--org",`https://dev.azure.com/${r.azure.org}`,"--project",r.azure.project,"-o","json"],{encoding:"utf-8",timeout:15e3});e.push({name:"Project accessible",ok:c.status===0,message:c.status===0?`Project ${r.azure.org}/${r.azure.project} accessible`:`Cannot access project ${r.azure.org}/${r.azure.project}`,fix:c.status===0?void 0:`Verify org/project names and access: https://dev.azure.com/${r.azure.org}/${r.azure.project}`})}}}return{ok:e.every(t=>t.ok),provider:r.provider,checks:e}}function io(r){switch(Qe.info("Creating board adapter",{provider:r.provider}),r.provider){case"github":return new cd(r.github?.repo);case"azure":{let e=r.azure;if(!e?.org||!e?.project)throw new Error("Azure board config requires org and project");return new ld(e.org,e.project)}case"local":default:throw new Error("Local board is not supported. Use 'github' or 'azure' provider.")}}function sd(r){let e=r.labels.find(n=>n.name.startsWith("priority:")),t=r.labels.find(n=>n.name.match(/^\d+pts?$/));return{id:String(r.number),title:r.title,description:r.body??"",status:r.state,assignee:r.assignees?.[0]?.login??"",labels:r.labels.map(n=>n.name),priority:e?.name.replace("priority:","")??"",points:t?parseInt(t.name):null,url:r.url}}function sn(r){let e=r.fields??{};return{id:String(r.id),title:e["System.Title"]??"",description:e["System.Description"]??"",status:e["System.State"]??"New",assignee:e["System.AssignedTo"]?.displayName??"",labels:[],priority:String(e["Microsoft.VSTS.Common.Priority"]??""),points:e["Microsoft.VSTS.Scheduling.StoryPoints"]??null,url:r.url??""}}function yy(r){return r.replace(/"/g,'\\"').replace(/\n/g,"\\n")}function ad(r){let e=r.split(`
|
|
240
|
+
`),t=[],n=!1;for(let i of e){let o=i.match(/^## (.+)/);if(o){n&&(t.push("</ul>"),n=!1),t.push(`<h2>${Wn(o[1])}</h2>`);continue}let s=i.match(/^# (.+)/);if(s){n&&(t.push("</ul>"),n=!1),t.push(`<h1>${Wn(s[1])}</h1>`);continue}let a=i.match(/^### (.+)/);if(a){n&&(t.push("</ul>"),n=!1),t.push(`<h3>${Wn(a[1])}</h3>`);continue}let c=i.match(/^- \[( |x)\] (.+)/);if(c){n||(t.push("<ul>"),n=!0);let u=c[1]==="x"?" checked":"";t.push(`<li><input type="checkbox"${u} disabled> ${Wn(c[2])}</li>`);continue}let l=i.match(/^- (.+)/);if(l){n||(t.push("<ul>"),n=!0),t.push(`<li>${Wn(l[1])}</li>`);continue}if(n&&i.trim()===""){t.push("</ul>"),n=!1;continue}i.trim()&&(n&&(t.push("</ul>"),n=!1),t.push(`<p>${Wn(i)}</p>`))}return n&&t.push("</ul>"),t.join(`
|
|
241
|
+
`)}function Wn(r){return r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/`([^`]+)`/g,"<code>$1</code>")}var ca=oe("board"),la=null,pd=null;function oI(){return pd||(pd=new pt),pd}var Sy={Todo:["In Progress"],"In Progress":["In Review","Todo"],"In Review":["Done","In Progress"],Done:[],todo:["in-progress"],"in-progress":["in-review","todo"],"in-review":["done","in-progress"],done:[],open:["todo","in-progress"],closed:["open","todo"],"To Do":["Doing"],Doing:["Done","To Do"]},dd={...process.env,GH_FORCE_TTY:"0",NO_COLOR:"1"};function Ey(){let r=new Map;try{let e=cn("gh api repos/{owner}/{repo}/collaborators --jq '.[].login'",{encoding:"utf-8",timeout:15e3,env:dd}).trim();for(let t of e.split(`
|
|
242
|
+
`).filter(Boolean))r.has(t)||r.set(t,"collaborator")}catch{}try{let e=cn("gh api repos/{owner}/{repo}/contributors --per-page=30 --jq '.[].login'",{encoding:"utf-8",timeout:15e3,env:dd}).trim();for(let t of e.split(`
|
|
243
|
+
`).filter(Boolean))r.has(t)||r.set(t,"contributor")}catch{}try{let e=cn("gh issue list --json assignees --limit 50 --state all",{encoding:"utf-8",timeout:15e3,env:dd}).trim(),t=JSON.parse(e);for(let n of t)for(let i of n.assignees??[])i.login&&!r.has(i.login)&&r.set(i.login,"recent assignee")}catch{}return[...r.entries()].map(([e,t])=>({login:e,source:t}))}var sI=`\u{1F4A1} Hint: call catalyst_board_connect first to set your board provider.
|
|
244
|
+
\u2022 GitHub (auto-detect): catalyst_board_connect({ provider: 'github' })
|
|
245
|
+
\u2022 GitHub (explicit): catalyst_board_connect({ provider: 'github', repo: 'owner/repo' })
|
|
246
|
+
\u2022 Azure DevOps: catalyst_board_connect({ provider: 'azure', org: 'myorg', project: 'myproject' })
|
|
247
|
+
Or configure it in .github/catalyst.config.json under the 'board' section.
|
|
248
|
+
Or run catalyst_board_setup for guided setup.`;function oo(r){let t=[`${r.ok?"\u2705":"\u274C"} Board: ${r.provider}`,""];for(let n of r.checks)t.push(`${n.ok?"\u2705":"\u274C"} ${n.name}: ${n.message}`),!n.ok&&n.fix&&t.push(` \u2192 ${n.fix}`);return t.join(`
|
|
249
|
+
`)}function Mt(){if(!la)try{let r=aa(),e=an(r);if(!e.ok){let t=oo(e);throw new Error(`Board prerequisites not met:
|
|
250
|
+
|
|
251
|
+
${t}
|
|
252
|
+
|
|
253
|
+
Run catalyst_board_setup for guided setup.`)}la=io(r),ca.info("Board auto-connected",{provider:r.provider})}catch(r){throw new Error(`${r.message}
|
|
254
|
+
|
|
255
|
+
${sI}`)}return la}function $y(r){r.tool("catalyst_board_connect","Connect to a project board (GitHub Issues/Projects or Azure Boards). Call this first before other board tools.",{provider:g.enum(["github","azure"]).describe("Board provider"),repo:g.string().optional().describe("GitHub repo (owner/repo). Auto-detected if omitted."),org:g.string().optional().describe("Azure DevOps org name"),project:g.string().optional().describe("Azure DevOps project name")},async({provider:e,repo:t,org:n,project:i})=>{ca.info("Connecting to board",{provider:e,repo:t});let o={provider:e};if(e==="github")o.github={repo:t};else{if(!n||!i)return{content:[{type:"text",text:`Azure DevOps requires both 'org' and 'project' parameters.
|
|
256
|
+
|
|
257
|
+
Example: catalyst_board_connect({ provider: 'azure', org: 'myorg', project: 'myproject' })
|
|
258
|
+
Or set them in .github/catalyst.config.json \u2192 board.azure.org / board.azure.project`}],isError:!0};o.azure={org:n,project:i}}try{let s=an(o);return s.ok?(la=io(o),{content:[{type:"text",text:`${oo(s)}
|
|
259
|
+
|
|
260
|
+
Connected to ${e} board${e==="azure"?` (${n}/${i})`:t?` (${t})`:""}.`}]}):{content:[{type:"text",text:`Connection failed \u2014 prerequisites not met:
|
|
261
|
+
|
|
262
|
+
${oo(s)}
|
|
263
|
+
|
|
264
|
+
Fix the issues above, then retry. Or run catalyst_board_setup for guided setup.`}],isError:!0}}catch(s){return{content:[{type:"text",text:`Failed to connect: ${s.message}`}],isError:!0}}}),r.tool("catalyst_board_setup","Guided board setup \u2014 detects available CLIs, checks authentication, and helps configure the board provider. Run this when you're unsure how to connect or getting connection errors. It will diagnose issues and provide step-by-step fix instructions.",{},async()=>{let e=["# \u{1F527} Board Setup Diagnostics",""],t=ud("which",["gh"],{encoding:"utf-8"}).status===0,n=ud("which",["az"],{encoding:"utf-8"}).status===0;if(e.push("## Available CLIs"),e.push(`- ${t?"\u2705":"\u274C"} **gh** (GitHub CLI)${t?"":" \u2014 Install: `brew install gh` or https://cli.github.com"}`),e.push(`- ${n?"\u2705":"\u274C"} **az** (Azure CLI)${n?"":" \u2014 Install: `brew install azure-cli` or https://aka.ms/install-azure-cli"}`),e.push(""),!t&&!n)return e.push("## \u274C No supported CLI found"),e.push("Install at least one:"),e.push("- **GitHub**: `brew install gh` then `gh auth login`"),e.push("- **Azure DevOps**: `brew install azure-cli` then `az login` and `az extension add --name azure-devops`"),{content:[{type:"text",text:e.join(`
|
|
265
|
+
`)}]};let i=[];if(t){e.push("## GitHub");let c={provider:"github"},l=an(c);e.push(oo(l)),i.push({name:"github",ready:l.ok,config:c}),e.push("")}if(n){e.push("## Azure DevOps");let c=process.cwd(),l=ky(c,".github","catalyst.config.json"),u="",p="";if(wy(l))try{let d=JSON.parse(by(l,"utf-8"));u=d?.board?.azure?.org??"",p=d?.board?.azure?.project??""}catch{}if(u&&p){let d={provider:"azure",azure:{org:u,project:p}},f=an(d);e.push(oo(f)),i.push({name:"azure",ready:f.ok,config:d})}else{let f=ud("az",["account","show","-o","json"],{encoding:"utf-8",timeout:1e4}).status===0;e.push(`- ${f?"\u2705":"\u274C"} Authenticated${f?"":" \u2014 Run: `az login`"}`),f&&(e.push("- \u26A0\uFE0F No Azure DevOps org/project configured"),e.push(" \u2192 Tell me your org and project name, and I'll configure it"),e.push(" \u2192 Or call: `catalyst_board_connect({ provider: 'azure', org: 'myorg', project: 'myproject' })`")),i.push({name:"azure",ready:!1})}e.push("")}let o=process.cwd(),s=ky(o,".github","catalyst.config.json");if(e.push("## Current Configuration"),wy(s))try{let l=JSON.parse(by(s,"utf-8"))?.board;e.push("- Config file: `.github/catalyst.config.json`"),e.push(`- Provider: **${l?.provider??"not set"}**`),l?.provider==="azure"?(e.push(`- Org: \`${l?.azure?.org??"not set"}\``),e.push(`- Project: \`${l?.azure?.project??"not set"}\``)):l?.provider==="github"&&e.push(`- Repo: \`${l?.github?.repo||"auto-detect"}\``)}catch{e.push("- Config file exists but could not be parsed")}else e.push("- No config file found at `.github/catalyst.config.json`"),e.push("- Board will default to GitHub with auto-detect");e.push("");let a=i.filter(c=>c.ready);if(e.push("## Next Steps"),a.length>0){let c=a[0];e.push(`\u2705 **${c.name}** is ready to use.`),e.push("\u2192 Run any board tool (e.g., `catalyst_board_view`) and it will auto-connect."),a.length>1&&e.push(`\u2192 Multiple providers available (${a.map(l=>l.name).join(", ")}). Set your preferred one in \`.github/catalyst.config.json\` under \`board.provider\`.`)}else{e.push("\u274C No provider is fully ready. Fix the issues listed above:");for(let c of i)c.ready||e.push(`- **${c.name}**: see diagnostics above`)}return{content:[{type:"text",text:e.join(`
|
|
266
|
+
`)}]}}),r.tool("catalyst_board_my_items","List work items/issues assigned to the current user",{status:g.string().optional().describe("Filter by status (open/closed/all)"),labels:g.string().optional().describe("Comma-separated labels to filter by (e.g. 'bug,defect' or 'needs-design')")},async({status:e,labels:t})=>{try{let n=t?t.split(",").map(s=>s.trim()).filter(Boolean):void 0,i=Mt().listMyItems(e,n);if(i.length===0)return{content:[{type:"text",text:"No items assigned to you."}]};let o=i.map(s=>`#${s.id} [${s.status}] ${s.title}${s.assignee?` (@${s.assignee})`:""}${s.points?` (${s.points}pts)`:""}`).join(`
|
|
267
|
+
`);return{content:[{type:"text",text:`${i.length} items:
|
|
268
|
+
|
|
269
|
+
${o}`}]}}catch(n){return{content:[{type:"text",text:`Error: ${n.message}`}],isError:!0}}}),r.tool("catalyst_board_prs_to_review","List open pull requests needing review. Use perspective='reviewer' to see PRs requesting your review, or 'author' to see your PRs with their review status.",{perspective:g.enum(["reviewer","author"]).describe("'reviewer' = PRs requesting my review; 'author' = my PRs and their review status")},async({perspective:e})=>{try{let i=cn(`gh pr list ${e==="reviewer"?'--search "review-requested:@me"':"--author @me"} --state open --json number,title,author,url,createdAt,labels,reviewRequests,reviews --limit 30`,{encoding:"utf-8",timeout:15e3,env:{...process.env,GH_FORCE_TTY:"0",NO_COLOR:"1"}}),o=JSON.parse(i);if(o.length===0)return{content:[{type:"text",text:e==="reviewer"?"No PRs requesting your review.":"You have no open PRs."}]};let s=o.map(c=>{let l=Math.floor((Date.now()-new Date(c.createdAt).getTime())/36e5),u=l<24?`${l}h ago`:`${Math.floor(l/24)}d ago`,p=c.labels.length?` [${c.labels.map(d=>d.name).join(", ")}]`:"";if(e==="author"){let d=c.reviews.filter(h=>h.state==="APPROVED").length,f=c.reviews.filter(h=>h.state==="CHANGES_REQUESTED").length,m=d||f?` \u2014 ${d} approval${d!==1?"s":""}${f?`, ${f} change request${f!==1?"s":""}`:""}`:" \u2014 no reviews yet";return` PR #${c.number} "${c.title}" (${u})${p}${m}`}return` PR #${c.number} "${c.title}" by @${c.author.login} (${u})${p}`}).join(`
|
|
270
|
+
`);return{content:[{type:"text",text:`${e==="reviewer"?`${o.length} PR${o.length!==1?"s":""} awaiting your review:`:`${o.length} open PR${o.length!==1?"s":""} you authored:`}
|
|
271
|
+
|
|
272
|
+
${s}`}]}}catch(t){return{content:[{type:"text",text:`Error: ${t.message}`}],isError:!0}}}),r.tool("catalyst_board_get","Get details of a specific work item/issue by ID or number",{id:g.string().regex(/^\d+$/,"id must be a numeric string (e.g. '42')").describe("Issue number or work item ID")},async({id:e})=>{try{let t=Mt().getItem(e);return t?{content:[{type:"text",text:[`# #${t.id} \u2014 ${t.title}`,`Status: ${t.status}`,`Assignee: ${t.assignee||"unassigned"}`,t.priority?`Priority: ${t.priority}`:null,t.points?`Points: ${t.points}`:null,t.labels.length?`Labels: ${t.labels.join(", ")}`:null,`URL: ${t.url}`,`
|
|
273
|
+
${t.description||"(no description)"}`].filter(Boolean).join(`
|
|
274
|
+
`)}]}:{content:[{type:"text",text:`Item #${e} not found.`}]}}catch(t){return{content:[{type:"text",text:`Error: ${t.message}`}],isError:!0}}}),r.tool("catalyst_board_create","Create a new work item/issue on the board. Description MUST follow the structured format: ## Summary, ## Acceptance Criteria, ## Technical Notes. The agent should always generate a detailed, well-structured description so that any reader or agent can understand the task fully.",{title:g.string().describe("Item title \u2014 clear and actionable (e.g., 'Build Flask REST API with CRUD endpoints')"),description:g.string().describe("Structured description in markdown format. MUST include: ## Summary (what and why), ## Acceptance Criteria (checkboxes), ## Technical Notes (stack, constraints, dependencies). Be detailed enough for another agent or dev to implement without asking questions."),assignee:g.string().optional().describe("Assign to (GitHub username or Azure user)"),labels:g.array(g.string()).optional().describe("Labels/tags"),priority:g.string().optional().describe("Priority level"),points:g.number().optional().describe("Story points"),epic_id:g.string().regex(/^\d+$/).optional().describe("Parent epic ID to link this issue under (Azure DevOps hierarchy: Epic \u2192 Issue)")},async({title:e,description:t,assignee:n,labels:i,priority:o,points:s,epic_id:a})=>{try{ca.info("Creating board item",{title:e,labels:i});let c=Mt().createItem({title:e,description:t,assignee:n,labels:i,priority:o,points:s,parentId:a}),l="";try{let u=oI().semanticSearch(e,void 0,3);u.length>0&&(l=`
|
|
275
|
+
|
|
276
|
+
\u{1F4DA} Related knowledge:
|
|
277
|
+
`+u.map(p=>` \u2022 [${p.type}] ${p.title}`).join(`
|
|
278
|
+
`))}catch{}return{content:[{type:"text",text:`Created #${c.id}: "${c.title}" \u2192 Todo
|
|
279
|
+
URL: ${c.url}${l}`}]}}catch(c){return{content:[{type:"text",text:`Error: ${c.message}`}],isError:!0}}}),r.tool("catalyst_board_create_epic","Create an epic on the board. Epics are umbrella items that group related user stories under a common theme or feature area. On GitHub, epics are issues with the 'epic' label. On Azure Boards, epics are native Epic work items.",{title:g.string().describe("Epic title \u2014 theme or feature area (e.g., '[Epic] User Authentication System')"),description:g.string().describe("High-level description of the epic's business goal and scope"),labels:g.array(g.string()).optional().describe("Additional labels/tags")},async({title:e,description:t,labels:n})=>{try{let i=Mt().createEpic({title:e,description:t,labels:n});return{content:[{type:"text",text:`Epic created #${i.id}: "${i.title}"
|
|
280
|
+
URL: ${i.url}
|
|
281
|
+
|
|
282
|
+
Link stories to this epic using label: epic:${e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}`}]}}catch(i){return{content:[{type:"text",text:`Error: ${i.message}`}],isError:!0}}}),r.tool("catalyst_board_create_subtask","Create a subtask linked to a parent story/issue. Subtasks represent implementation steps within a user story (e.g., backend work, frontend work, tests, docs). On GitHub, subtasks are issues with a 'parent:#N' label and a reference in the description. On Azure Boards, subtasks are Task items with a parent-child link.",{parent_id:g.string().regex(/^\d+$/,"parent_id must be a numeric string (e.g. '10')").describe("Parent issue number or work item ID that this subtask belongs to"),title:g.string().describe("Subtask title \u2014 specific implementation step (e.g., '[Backend] Implement authentication endpoint')"),description:g.string().describe("Implementation details for this subtask"),assignee:g.string().optional().describe("Assign to (GitHub username or Azure user)"),labels:g.array(g.string()).optional().describe("Additional labels/tags")},async({parent_id:e,title:t,description:n,assignee:i,labels:o})=>{try{let s=Mt().createSubtask(e,{title:t,description:n,assignee:i,labels:o});return{content:[{type:"text",text:`Subtask created #${s.id}: "${s.title}" \u2192 parent #${e}
|
|
283
|
+
URL: ${s.url}`}]}}catch(s){return{content:[{type:"text",text:`Error: ${s.message}`}],isError:!0}}}),r.tool("catalyst_board_move","Move an item to a different status/column. Validates against allowed transitions: todo \u2192 in-progress \u2192 in-review \u2192 done. Returns an error if the transition is not allowed, along with valid options.",{id:g.string().regex(/^\d+$/,"id must be a numeric string (e.g. '42')").describe("Issue number or work item ID"),status:g.enum(["todo","in-progress","in-review","done","Todo","In Progress","In Review","Done","To Do","Doing"]).describe("Target status. GitHub: 'todo','in-progress','in-review','done'. Azure Basic: 'To Do','Doing','Done'")},async({id:e,status:t})=>{try{ca.info("Moving board item",{id:e,targetStatus:t});let n=Mt().getItem(e);if(!n)return{content:[{type:"text",text:`Item #${e} not found.`}],isError:!0};let i=n.labels.find(a=>a.startsWith("status:")),o=i?i.replace("status:",""):n.status,s=Sy[o]??[];return s.length>0&&!s.includes(t)?{content:[{type:"text",text:`Cannot move #${e} from "${o}" \u2192 "${t}".
|
|
284
|
+
Allowed transitions: ${s.join(", ")}`}],isError:!0}:(Mt().updateStatus(e,t),{content:[{type:"text",text:`#${e} \u2192 ${t} (was: ${o})`}]})}catch(n){return{content:[{type:"text",text:`Error: ${n.message}`}],isError:!0}}}),r.tool("catalyst_board_list_users","List all available users (collaborators, contributors, recent assignees) for this repository. Use this BEFORE assigning a task or reviewer to present a selection list. The agent should present these users as options and let the user pick.",{},async()=>{try{let e=Ey();if(e.length===0)return{content:[{type:"text",text:"No users found. Check repo access or try assigning a username directly."}]};let t={};for(let i of e)t[i.source]||(t[i.source]=[]),t[i.source].push(i.login);return{content:[{type:"text",text:`## Available Users
|
|
285
|
+
|
|
286
|
+
${Object.entries(t).map(([i,o])=>`**${i.charAt(0).toUpperCase()+i.slice(1)}s**: ${o.map(s=>`@${s}`).join(", ")}`).join(`
|
|
287
|
+
`)}
|
|
288
|
+
|
|
289
|
+
Total: ${e.length} users
|
|
290
|
+
|
|
291
|
+
Present these as options to the user and let them pick.`}]}}catch(e){return{content:[{type:"text",text:`Error: ${e.message}`}],isError:!0}}}),r.tool("catalyst_board_assign","Assign a work item to a user. Does NOT change the item status \u2014 use catalyst_board_move to change status separately. IMPORTANT: Before calling this tool, the agent MUST call catalyst_board_list_users to get available users and present them as options to the user. Only assign after the user picks a username.",{id:g.string().regex(/^\d+$/,"id must be a numeric string (e.g. '42')").describe("Issue number or work item ID"),assignee:g.string().describe("Username to assign to")},async({id:e,assignee:t})=>{try{let n=Ey();try{Mt().assign(e,t)}catch(o){let s=o.message??"",a=`Failed to assign @${t} to #${e}.`;return/could not resolve|not found|no user/i.test(s)?a+=`
|
|
292
|
+
|
|
293
|
+
Reason: User @${t} was not found. Verify the username exists and has access to this repository.`:/permission|forbidden|403/i.test(s)?a+=`
|
|
294
|
+
|
|
295
|
+
Reason: Insufficient permissions. The user @${t} may not have access to this repository.`:a+=`
|
|
296
|
+
|
|
297
|
+
Reason: ${s}`,n.length>0&&(a+=`
|
|
298
|
+
|
|
299
|
+
Available users: ${n.map(c=>`@${c.login} (${c.source})`).join(", ")}`),{content:[{type:"text",text:a}],isError:!0}}return{content:[{type:"text",text:`#${e} assigned to @${t} (status unchanged)`}]}}catch(n){return{content:[{type:"text",text:`Error: ${n.message}`}],isError:!0}}}),r.tool("catalyst_board_comment","Add a comment to a work item/issue",{id:g.string().regex(/^\d+$/,"id must be a numeric string (e.g. '42')").describe("Issue number or work item ID"),comment:g.string().describe("Comment text (supports markdown)")},async({id:e,comment:t})=>{try{return Mt().addComment(e,t),{content:[{type:"text",text:`Comment added to #${e}`}]}}catch(n){return{content:[{type:"text",text:`Error: ${n.message}`}],isError:!0}}}),r.tool("catalyst_board_pr_comments","Fetch all review comments and review threads from a pull request. Use this to understand reviewer feedback before fixing issues or to check what was requested during a review.",{pr_number:g.string().regex(/^\d+$/,"pr_number must be a numeric string (e.g. '35')").describe("Pull request number")},async({pr_number:e})=>{try{let t={...process.env,GH_FORCE_TTY:"0",NO_COLOR:"1"},n="";try{n=cn(`gh pr view ${e} --json reviews,comments --jq '.reviews[] | "### Review by @\\(.author.login) \u2014 \\(.state)\\n\\(.body // "(no summary)")\\n"'`,{encoding:"utf-8",timeout:15e3,env:t}).trim()}catch{}let i="";try{i=cn(`gh pr view ${e} --json comments --jq '.comments[] | "**@\\(.author.login)** (\\(.createdAt[:10])):\\n\\(.body)\\n---"'`,{encoding:"utf-8",timeout:15e3,env:t}).trim()}catch{}let o="";try{o=cn(`gh api repos/{owner}/{repo}/pulls/${e}/comments --jq '.[] | "**@\\(.user.login)** on \\(.path):\\(.line // .original_line):\\n\\(.body)\\n---"'`,{encoding:"utf-8",timeout:15e3,env:t}).trim()}catch{}let s=[`## PR #${e} Review Comments
|
|
300
|
+
`];return n&&s.push(`### Reviews
|
|
301
|
+
${n}`),o&&s.push(`### Inline Code Comments
|
|
302
|
+
${o}`),i&&s.push(`### General Comments
|
|
303
|
+
${i}`),!n&&!o&&!i&&s.push("No review comments found on this PR."),{content:[{type:"text",text:s.join(`
|
|
304
|
+
|
|
305
|
+
`)}]}}catch(t){return{content:[{type:"text",text:`Error: ${t.message}`}],isError:!0}}}),r.tool("catalyst_board_view","Show the full board view with items grouped by status/column. Each item shows its current status and valid transitions. Use catalyst_board_move to change an item's status.",{},async()=>{try{let t=Mt().getBoardView().map(i=>{let o=i.items.length?i.items.map(s=>{let a=Sy[i.name]??[],c=a.length?` [can move to: ${a.join(", ")}]`:"";return` - #${s.id} ${s.title}${s.assignee?` (@${s.assignee})`:""}${c}`}).join(`
|
|
306
|
+
`):" (empty)";return`### ${i.name.toUpperCase()} (${i.items.length})
|
|
307
|
+
${o}`}).join(`
|
|
308
|
+
|
|
309
|
+
`),n=["","---","**Status Flow:** todo \u2192 in-progress \u2192 in-review \u2192 done","**Move an item:** Use `catalyst_board_move` with the item ID and target status."].join(`
|
|
310
|
+
`);return{content:[{type:"text",text:t+n}]}}catch(e){return{content:[{type:"text",text:`Error: ${e.message}`}],isError:!0}}})}import{execSync as er,spawnSync as ho}from"node:child_process";import Ty from"better-sqlite3";import{join as aI,dirname as cI}from"node:path";import{mkdirSync as lI,renameSync as md}from"node:fs";import{execSync as fd,spawnSync as uI}from"node:child_process";var Ye=oe("orchestrator"),zy=[{role:"pm",description:"Creates user stories from requirements, meetings, or transcripts",skills:["solution-design","architecture-planner"],triggers:["transcript provided","requirements doc provided","manual"],gates:["approve-task-creation"]},{role:"scrum-master",description:"Assigns tasks, tracks board, detects blockers, generates standups",skills:["board","knowledge-base"],triggers:["daily schedule","new task created","blocker detected"],gates:["approve-assignment"]},{role:"developer",description:"Reads task, creates branch, writes code + tests, commits, opens PR",skills:["feature-builder","test-first","change-management"],triggers:["task assigned to digital-worker"],gates:["approve-plan","approve-pr"]},{role:"reviewer",description:"Reviews PR with multi-pass analysis, posts comments, approves or requests changes",skills:["code-quality","vulnerability-scan","pr-intelligence"],triggers:["pr-opened"],gates:["human-final-approve"]},{role:"monitor",description:"Tracks all activity, updates board status, produces reports, flags anomalies",skills:["pattern-detection","knowledge-base"],triggers:["periodic","event-driven"],gates:[]}],ua=class{db;constructor(e){let t=e??aI(process.cwd(),".catalyst","orchestrator.db");lI(cI(t),{recursive:!0});try{this.db=new Ty(t),this.db.pragma("journal_mode = WAL"),this.init()}catch(n){Ye.error("DB open/init failed \u2014 backing up corrupt file and recreating",{db:t,error:n.message});let i=`${t}.corrupt.${Date.now()}`;try{md(t,i)}catch{}try{md(`${t}-wal`,`${i}-wal`)}catch{}try{md(`${t}-shm`,`${i}-shm`)}catch{}this.db=new Ty(t),this.db.pragma("journal_mode = WAL"),this.init(),Ye.warn("Recreated orchestrator DB from scratch",{backup:i})}Ye.info("Orchestrator initialized",{db:t})}init(){this.db.exec(`
|
|
311
|
+
CREATE TABLE IF NOT EXISTS workflows (
|
|
312
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
313
|
+
item_id TEXT NOT NULL,
|
|
314
|
+
item_title TEXT NOT NULL,
|
|
315
|
+
role TEXT NOT NULL,
|
|
316
|
+
status TEXT NOT NULL DEFAULT 'pending',
|
|
317
|
+
branch TEXT NOT NULL DEFAULT '',
|
|
318
|
+
pr_number TEXT NOT NULL DEFAULT '',
|
|
319
|
+
plan TEXT NOT NULL DEFAULT '{}',
|
|
320
|
+
log TEXT NOT NULL DEFAULT '[]',
|
|
321
|
+
retry_count INTEGER NOT NULL DEFAULT 0,
|
|
322
|
+
previewed_at TEXT NOT NULL DEFAULT '',
|
|
323
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
324
|
+
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
325
|
+
);
|
|
326
|
+
|
|
327
|
+
CREATE INDEX IF NOT EXISTS idx_workflows_status ON workflows(status);
|
|
328
|
+
CREATE INDEX IF NOT EXISTS idx_workflows_item ON workflows(item_id);
|
|
329
|
+
`),this.db.prepare("PRAGMA table_info(workflows)").all().some(t=>t.name==="previewed_at")||this.db.exec("ALTER TABLE workflows ADD COLUMN previewed_at TEXT NOT NULL DEFAULT ''"),this.db.exec(`
|
|
330
|
+
CREATE TABLE IF NOT EXISTS workflow_steps (
|
|
331
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
332
|
+
workflow_id INTEGER NOT NULL REFERENCES workflows(id),
|
|
333
|
+
timestamp TEXT NOT NULL DEFAULT (datetime('now')),
|
|
334
|
+
role TEXT NOT NULL,
|
|
335
|
+
action TEXT NOT NULL,
|
|
336
|
+
result TEXT NOT NULL,
|
|
337
|
+
detail TEXT NOT NULL DEFAULT ''
|
|
338
|
+
);
|
|
339
|
+
CREATE INDEX IF NOT EXISTS idx_steps_workflow ON workflow_steps(workflow_id);
|
|
340
|
+
`),this.migrateJsonLogs()}migrateJsonLogs(){let e=this.db.prepare("SELECT id, log FROM workflows WHERE log != '[]' AND id NOT IN (SELECT DISTINCT workflow_id FROM workflow_steps)").all();if(e.length===0)return;let t=this.db.prepare("INSERT INTO workflow_steps (workflow_id, timestamp, role, action, result, detail) VALUES (?, ?, ?, ?, ?, ?)");this.db.transaction(()=>{for(let i of e)try{let o=JSON.parse(i.log);for(let s of o)t.run(i.id,s.timestamp,s.role,s.action,s.result,s.detail)}catch{}})(),Ye.info("Migrated JSON logs to workflow_steps",{workflows:e.length})}startWorkflow(e,t,n){Ye.info("Starting workflow",{itemId:e,itemTitle:t,role:n});let i=this.getActiveWorkflow(e);if(i)throw new Error(`Item #${e} already has an active workflow (id: ${i.id}, status: ${i.status})`);let a=this.db.prepare(`
|
|
341
|
+
INSERT INTO workflows (item_id, item_title, role, status)
|
|
342
|
+
VALUES (?, ?, ?, 'pending')
|
|
343
|
+
`).run(e,t,n).lastInsertRowid;return this.appendLog(a,n,"workflow-started","success",`Workflow created for item #${e}`),Ye.info("Workflow created",{workflowId:a,itemId:e}),this.getWorkflow(a)}setPlan(e,t){Ye.info("Setting execution plan",{workflowId:e}),this.db.prepare(`
|
|
344
|
+
UPDATE workflows SET plan = ?, status = 'planning', updated_at = datetime('now')
|
|
345
|
+
WHERE id = ?
|
|
346
|
+
`).run(JSON.stringify(t),e),this.appendLog(e,"developer","plan-created","success",`Plan: ${JSON.stringify(t).slice(0,200)}`)}approvePlan(e){Ye.info("Plan approved \u2014 transitioning to in-progress",{workflowId:e}),this.db.prepare(`
|
|
347
|
+
UPDATE workflows SET status = 'in-progress', updated_at = datetime('now')
|
|
348
|
+
WHERE id = ? AND status = 'planning'
|
|
349
|
+
`).run(e),this.appendLog(e,"scrum-master","plan-approved","success","Human approved the execution plan")}setBranch(e,t){Ye.info("Branch set",{workflowId:e,branch:t}),this.db.prepare(`
|
|
350
|
+
UPDATE workflows SET branch = ?, updated_at = datetime('now')
|
|
351
|
+
WHERE id = ?
|
|
352
|
+
`).run(t,e),this.appendLog(e,"developer","branch-created","success",`Branch: ${t}`)}setPR(e,t){Ye.info("PR opened \u2014 transitioning to review",{workflowId:e,prNumber:t}),this.db.prepare(`
|
|
353
|
+
UPDATE workflows SET pr_number = ?, status = 'review', updated_at = datetime('now')
|
|
354
|
+
WHERE id = ?
|
|
355
|
+
`).run(t,e),this.appendLog(e,"developer","pr-opened","success",`PR #${t}`)}approveWorkflow(e){this.db.prepare(`
|
|
356
|
+
UPDATE workflows SET status = 'approved', updated_at = datetime('now')
|
|
357
|
+
WHERE id = ?
|
|
358
|
+
`).run(e),this.appendLog(e,"reviewer","pr-approved","success","PR approved \u2014 ready to merge")}completeWorkflow(e){Ye.info("Workflow completed",{workflowId:e}),this.db.prepare(`
|
|
359
|
+
UPDATE workflows SET status = 'done', updated_at = datetime('now')
|
|
360
|
+
WHERE id = ?
|
|
361
|
+
`).run(e),this.appendLog(e,"monitor","workflow-completed","success","Workflow finished successfully")}failWorkflow(e,t){Ye.warn("Workflow failed",{workflowId:e,reason:t});let i=(this.getWorkflow(e)?.retry_count??0)+1;this.db.prepare(`
|
|
362
|
+
UPDATE workflows SET status = 'failed', retry_count = ?, updated_at = datetime('now')
|
|
363
|
+
WHERE id = ?
|
|
364
|
+
`).run(i,e),this.appendLog(e,"monitor","workflow-failed","failure",`${t} (attempt ${i})`)}blockWorkflow(e,t){Ye.warn("Workflow blocked",{workflowId:e,reason:t}),this.db.prepare(`
|
|
365
|
+
UPDATE workflows SET status = 'blocked', updated_at = datetime('now')
|
|
366
|
+
WHERE id = ?
|
|
367
|
+
`).run(e),this.appendLog(e,"monitor","workflow-blocked","failure",t)}markPreviewed(e){this.db.prepare("UPDATE workflows SET previewed_at = datetime('now'), updated_at = datetime('now') WHERE id = ?").run(e)}isPreviewed(e){return!!this.getWorkflow(e)?.previewed_at}clearPreviewed(e){this.db.prepare("UPDATE workflows SET previewed_at = '', updated_at = datetime('now') WHERE id = ?").run(e)}getWorkflow(e){return this.db.prepare("SELECT * FROM workflows WHERE id = ?").get(e)}getActiveWorkflow(e){return this.db.prepare("SELECT * FROM workflows WHERE item_id = ? AND status NOT IN ('done', 'failed') ORDER BY id DESC LIMIT 1").get(e)}listActive(){return this.db.prepare("SELECT * FROM workflows WHERE status NOT IN ('done', 'failed') ORDER BY created_at DESC").all()}listAll(e=20){return this.db.prepare("SELECT * FROM workflows ORDER BY created_at DESC LIMIT ?").all(e)}getWorkflowLog(e){return this.db.prepare("SELECT timestamp, role, action, result, detail FROM workflow_steps WHERE workflow_id = ? ORDER BY id ASC").all(e)}createBranch(e,t,n){let i=n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,40),o=`catalyst/${t}-${i}`;try{return fd(`git checkout -b "${o}"`,{encoding:"utf-8",timeout:1e4}),this.setBranch(e,o),o}catch(s){try{return fd(`git checkout "${o}"`,{encoding:"utf-8",timeout:1e4}),this.setBranch(e,o),o}catch{throw new Error(`Failed to create/checkout branch: ${s.message}`)}}}openPR(e,t,n){let i=this.getWorkflow(e);if(!i?.branch)throw new Error("No branch set for this workflow");try{fd(`git push -u origin "${i.branch}"`,{encoding:"utf-8",timeout:3e4});let o=uI("gh",["pr","create","--title",t,"--body-file","-","--head",i.branch],{input:n,encoding:"utf-8",timeout:15e3,env:{...process.env,GH_FORCE_TTY:"0",NO_COLOR:"1"}});if(o.status!==0)throw new Error(o.stderr?.trim()||"Failed to create PR");let s=(o.stdout??"").trim(),a=s.match(/\/pull\/(\d+)/)?.[1]??s.match(/#(\d+)/)?.[1]??"";return this.setPR(e,a),a}catch(o){throw new Error(`Failed to open PR: ${o.message}`)}}getDashboard(){let e=this.listAll(50);return{active:e.filter(t=>!["done","failed"].includes(t.status)).length,pending:e.filter(t=>t.status==="pending").length,inProgress:e.filter(t=>t.status==="in-progress").length,inReview:e.filter(t=>t.status==="review").length,done:e.filter(t=>t.status==="done").length,failed:e.filter(t=>t.status==="failed").length,blocked:e.filter(t=>t.status==="blocked").length,workflows:e.slice(0,10)}}appendLog(e,t,n,i,o){this.db.prepare("INSERT INTO workflow_steps (workflow_id, timestamp, role, action, result, detail) VALUES (?, ?, ?, ?, ?, ?)").run(e,new Date().toISOString(),t,n,i,o)}};var Sb=ka(kb(),1);var wr=oe("notification");async function zO(r,e,t,n){wr.info("Sending email via SMTP",{host:r.host,port:r.port,recipients:e.join(", "),subject:t});let o=await Sb.default.createTransport({host:r.host,port:r.port,secure:r.secure,auth:{user:r.user,pass:r.pass}}).sendMail({from:r.from,to:e.join(", "),subject:t,text:n});return wr.info("Email sent successfully",{messageId:o.messageId}),{success:!0,channel:"email",message:`Sent to ${e.join(", ")} (messageId: ${o.messageId})`}}var pn=class{config;constructor(e){this.config={channel:e?.channel??"email",email_recipients:e?.email_recipients??[],smtp:e?.smtp??this.smtpFromEnv()},wr.info("Notification service initialized",{channel:this.config.channel,smtp:this.config.smtp?`${this.config.smtp.host}:${this.config.smtp.port}`:"not configured",recipients:this.config.email_recipients.length})}smtpFromEnv(){let e=process.env.SMTP_HOST,t=process.env.SMTP_USER,n=process.env.SMTP_PASS;if(!e||!t||!n){wr.debug("SMTP env vars not set, email disabled until configured");return}return wr.info("SMTP config loaded from environment",{host:e,user:t}),{host:e,port:Number(process.env.SMTP_PORT??"587"),secure:process.env.SMTP_SECURE==="true",user:t,pass:n,from:process.env.SMTP_FROM??t}}async send(e){let t=e.channel??this.config.channel,n=e.recipients??this.config.email_recipients;switch(t){case"email":return this.config.smtp?n.length===0?(wr.warn("Email send attempted but no recipients configured"),{success:!1,channel:"email",message:"No recipients configured. Call catalyst_notify_configure with email_recipients."}):zO(this.config.smtp,n,e.subject,e.body):(wr.warn("Email send attempted but SMTP not configured"),{success:!1,channel:"email",message:"SMTP not configured. Set env vars (SMTP_HOST, SMTP_USER, SMTP_PASS) or call catalyst_notify_configure with SMTP details."});case"console":default:return wr.debug("Notification displayed in console",{subject:e.subject}),{success:!0,channel:"console",message:"Report displayed in chat (set channel to 'email' to send externally)"}}}getConfig(){return{...this.config,smtp:this.config.smtp?{...this.config.smtp,pass:"***"}:void 0}}};var re=oe("worker"),am=null,cm=null,lm=null,um=null;function PO(r){return r.replace(/\\n/g,`
|
|
368
|
+
`).replace(/\\t/g," ")}function Jn(r,e,t){ho("gh",[r==="pr"?"pr":"issue","comment",e,"--body-file","-"],{input:PO(t),encoding:"utf-8",timeout:15e3,env:{...process.env,GH_FORCE_TTY:"0",NO_COLOR:"1"}})}function se(){return am||(am=new ua),am}function va(){return cm||(cm=io({provider:"github"})),cm}function pm(){return lm||(lm=new pt),lm}function RO(){return um||(um=new pn),um}function kr(r,e){try{RO().send({subject:r,body:e})}catch(t){re.debug("Notification send failed (non-critical)",{error:t.message})}}function Eb(r){r.tool("catalyst_worker_start","Start a digital worker workflow for a board item. The worker picks up the task and begins the agent pipeline (plan \u2192 approve \u2192 implement \u2192 review \u2192 done).",{item_id:g.string().describe("Board item ID (issue number or work item ID)"),item_title:g.string().describe("Item title (for reference)"),role:g.enum(["pm","scrum-master","developer","reviewer","monitor"]).optional().describe("Agent role (default: developer)")},async({item_id:e,item_title:t,role:n})=>{try{re.info("Starting worker workflow",{itemId:e,title:t,role:n??"developer"});let i=se().startWorkflow(e,t,n??"developer");try{va().updateStatus(e,"in-progress")}catch(o){re.debug("Board status update skipped",{error:o.message})}return{content:[{type:"text",text:`Workflow #${i.id} started for item #${e}: "${t}"
|
|
369
|
+
Role: ${i.role}
|
|
370
|
+
Status: ${i.status}
|
|
371
|
+
Board: #${e} \u2192 in-progress
|
|
372
|
+
|
|
373
|
+
Next: Create a plan with catalyst_worker_plan, then approve with catalyst_worker_approve.`}]}}catch(i){return{content:[{type:"text",text:`Error: ${i.message}`}],isError:!0}}}),r.tool("catalyst_worker_plan","Set the execution plan for a workflow. This is reviewed by a human before work begins.",{workflow_id:g.number().describe("Workflow ID"),steps:g.array(g.string()).describe("Ordered list of steps the agent will take"),files_to_change:g.array(g.string()).optional().describe("Files that will be created or modified"),estimated_complexity:g.enum(["trivial","simple","moderate","complex"]).optional().describe("Estimated complexity")},async({workflow_id:e,steps:t,files_to_change:n,estimated_complexity:i})=>{try{re.info("Setting execution plan",{workflowId:e,steps:t.length,complexity:i??"moderate"});let o={steps:t,files_to_change:n??[],complexity:i??"moderate"};se().setPlan(e,o);let s=t.map((l,u)=>` ${u+1}. ${l}`).join(`
|
|
374
|
+
`),a=(n??[]).map(l=>` - ${l}`).join(`
|
|
375
|
+
`),c="";try{let u=se().getWorkflow(e)?.item_title??t.join(" "),p=pm().semanticSearch(u,void 0,3);p.length>0&&(c=`
|
|
376
|
+
|
|
377
|
+
\u{1F4DA} Related knowledge from past work:
|
|
378
|
+
`+p.map(d=>` \u2022 [${d.type}] ${d.title} (score: ${d.score.toFixed(2)})`).join(`
|
|
379
|
+
`))}catch{re.debug("Knowledge not available for plan context")}return{content:[{type:"text",text:`Plan for workflow #${e}:
|
|
380
|
+
|
|
381
|
+
${s}
|
|
382
|
+
|
|
383
|
+
Files:
|
|
384
|
+
${a||" (to be determined)"}
|
|
385
|
+
Complexity: ${i??"moderate"}${c}
|
|
386
|
+
|
|
387
|
+
\u26A0\uFE0F HUMAN GATE: Use catalyst_worker_approve to approve this plan before execution.`}]}}catch(o){return{content:[{type:"text",text:`Error: ${o.message}`}],isError:!0}}}),r.tool("catalyst_worker_approve","Approve a workflow plan \u2014 this is a HUMAN GATE. Only call after reviewing the plan. The plan MUST include test cases (unit tests, integration tests, or both). If the plan does not mention tests, ask the developer to add them before approving.",{workflow_id:g.number().describe("Workflow ID to approve")},async({workflow_id:e})=>{try{re.info("Approving workflow plan (HUMAN GATE)",{workflowId:e}),se().approvePlan(e);let t=se().getWorkflow(e);if(t?.item_id)try{va().updateStatus(t.item_id,"in-progress")}catch(n){re.debug("Board sync skipped",{error:n.message})}return{content:[{type:"text",text:`Workflow #${e} approved \u2192 in-progress.
|
|
388
|
+
|
|
389
|
+
The developer agent can now:
|
|
390
|
+
1. Create branch with catalyst_worker_branch
|
|
391
|
+
2. Implement the changes
|
|
392
|
+
3. Preview changes with catalyst_worker_preview_pr (MUST show to user first)
|
|
393
|
+
4. After user approval, open PR with catalyst_worker_pr`}]}}catch(t){return{content:[{type:"text",text:`Error: ${t.message}`}],isError:!0}}}),r.tool("catalyst_worker_branch","Create a feature branch for a workflow item",{workflow_id:g.number().describe("Workflow ID")},async({workflow_id:e})=>{try{re.info("Creating feature branch",{workflowId:e});let t=se().getWorkflow(e);if(!t)return{content:[{type:"text",text:"Workflow not found"}],isError:!0};if(t.status!=="in-progress")return{content:[{type:"text",text:`Workflow must be in-progress (current: ${t.status}). Approve the plan first.`}],isError:!0};let n=se().createBranch(e,t.item_id,t.item_title);return re.info("Branch created",{branch:n}),{content:[{type:"text",text:`Branch created: ${n}
|
|
394
|
+
Now implement the changes and commit.`}]}}catch(t){return{content:[{type:"text",text:`Error: ${t.message}`}],isError:!0}}}),r.tool("catalyst_worker_preview_pr","Preview all changes before creating a PR. Shows the git diff, list of changed files, and the proposed PR title/body. The agent MUST call this tool and present the output to the user BEFORE calling catalyst_worker_pr. This is a HUMAN GATE \u2014 the user must review and approve the changes before the PR is created.",{workflow_id:g.number().describe("Workflow ID"),title:g.string().describe("Proposed PR title in conventional commit format"),body:g.string().describe("Proposed PR body in markdown")},async({workflow_id:e,title:t,body:n})=>{try{re.info("Previewing PR (HUMAN GATE)",{workflowId:e,title:t});let i=se().getWorkflow(e);if(!i)return{content:[{type:"text",text:"Workflow not found"}],isError:!0};let o={...process.env,GH_FORCE_TTY:"0",NO_COLOR:"1"},s="(unable to get file stats)";try{s=er("git diff --stat origin/main...HEAD",{encoding:"utf-8",timeout:15e3,env:o}).trim()}catch{try{s=er("git diff --stat HEAD~1",{encoding:"utf-8",timeout:15e3,env:o}).trim()}catch{re.debug("Fallback diff --stat HEAD~1 also failed")}}let a="(unable to get diff)";try{let u=er("git diff origin/main...HEAD",{encoding:"utf-8",timeout:15e3,env:o,maxBuffer:524288}).trim();a=u.length>5e3?u.substring(0,5e3)+`
|
|
395
|
+
|
|
396
|
+
... (diff truncated \u2014 ${u.length} chars total)`:u}catch{try{let u=er("git diff HEAD~1",{encoding:"utf-8",timeout:15e3,env:o,maxBuffer:524288}).trim();a=u.length>5e3?u.substring(0,5e3)+`
|
|
397
|
+
|
|
398
|
+
... (diff truncated \u2014 ${u.length} chars total)`:u}catch{re.debug("Fallback diff HEAD~1 also failed")}}let c="";try{let u=await import("node:fs"),p=process.cwd(),d=null;if(u.existsSync(`${p}/package.json`)){let f=JSON.parse(u.readFileSync(`${p}/package.json`,"utf-8"));f.scripts?.["test:coverage"]?d="npm run test:coverage 2>&1 | tail -20":f.scripts?.test&&(d="npx jest --coverage --coverageReporters=text-summary 2>&1 | tail -20 || npx vitest run --coverage 2>&1 | tail -20")}else(u.existsSync(`${p}/pytest.ini`)||u.existsSync(`${p}/setup.py`)||u.existsSync(`${p}/pyproject.toml`))&&(d="python -m pytest --cov --cov-report=term-summary 2>&1 | tail -20");d&&(c=`
|
|
399
|
+
### Test Coverage
|
|
400
|
+
\`\`\`
|
|
401
|
+
${er(d,{encoding:"utf-8",timeout:12e4,cwd:p}).trim()}
|
|
402
|
+
\`\`\`
|
|
403
|
+
`)}catch{re.debug("Coverage not available for PR preview")}let l=[`## PR Preview for Workflow #${e} (Issue #${i.item_id})`,"","### Proposed Title",t,"","### Proposed Body",n,"","### Changed Files","```",s,"```",c,"### Diff","```diff",a,"```","","---","\u26A0\uFE0F **HUMAN GATE:** Review the changes above. If everything looks good, the agent should call `catalyst_worker_pr` to create the PR. If changes are needed, make edits first."].join(`
|
|
404
|
+
`);return se().markPreviewed(e),{content:[{type:"text",text:l}]}}catch(i){return{content:[{type:"text",text:`Error: ${i.message}`}],isError:!0}}}),r.tool("catalyst_worker_pr","Open a pull request for the current workflow. IMPORTANT: The agent MUST call catalyst_worker_preview_pr first to show all changes to the user, and only call this tool AFTER the user has reviewed and approved the changes. This is a HUMAN GATE. The PR must have a conventional commit title and a well-structured body. Does NOT move the issue status \u2014 the issue stays in-progress until a reviewer is assigned via catalyst_pr_assign_reviewer.",{workflow_id:g.number().describe("Workflow ID"),title:g.string().describe("PR title in conventional commit format (e.g., 'feat(scope): description')"),body:g.string().describe("PR body in markdown. MUST include: ## Summary (what and why), ## Changes (list of files changed with descriptions), ## How to Test (step-by-step), and 'Closes #N' to link the issue.")},async({workflow_id:e,title:t,body:n})=>{try{if(re.info("Opening pull request (HUMAN GATE)",{workflowId:e,title:t}),!se().isPreviewed(e))return{content:[{type:"text",text:`\u26D4 HUMAN GATE VIOLATION: You must call catalyst_worker_preview_pr first and get user approval before creating a PR.
|
|
405
|
+
|
|
406
|
+
Call catalyst_worker_preview_pr with the proposed title and body, show the output to the user, and only proceed after they approve.`}],isError:!0};se().clearPreviewed(e);let i=se().openPR(e,t,n);re.info("PR opened",{prNumber:i,workflowId:e});let o=se().getWorkflow(e);if(o?.item_id)try{Jn("issue",o.item_id,`\u{1F517} PR #${i} opened for this issue.`)}catch(s){re.debug("PR link comment failed",{error:s.message})}return kr(`PR #${i} opened`,`Workflow #${e} \u2014 Issue #${o?.item_id} "${o?.item_title}"
|
|
407
|
+
PR: #${i} \u2014 ${t}`),{content:[{type:"text",text:`PR #${i} opened for workflow #${e} (issue #${o?.item_id}).
|
|
408
|
+
Board status: in-progress (unchanged).
|
|
409
|
+
|
|
410
|
+
Next: Assign a reviewer with catalyst_pr_assign_reviewer to move the issue to in-review.`}]}}catch(i){return{content:[{type:"text",text:`Error: ${i.message}`}],isError:!0}}}),r.tool("catalyst_pr_assign_reviewer","Assign a reviewer to a PR and move the linked issue to in-review on the board. IMPORTANT: Before calling this tool, the agent MUST call catalyst_board_list_users to get available users and present them as options to the user. Only assign after the user picks a reviewer.",{workflow_id:g.number().describe("Workflow ID"),reviewer:g.string().describe("GitHub username of the reviewer to assign")},async({workflow_id:e,reviewer:t})=>{try{re.info("Assigning PR reviewer",{workflowId:e,reviewer:t});let n=se().getWorkflow(e);if(!n)return{content:[{type:"text",text:"Workflow not found"}],isError:!0};let i=n.pr_number;if(!i)return{content:[{type:"text",text:"No PR found for this workflow. Open a PR first."}],isError:!0};let o=ho("gh",["pr","edit",i,"--add-reviewer",t],{encoding:"utf-8",timeout:15e3,env:{...process.env,GH_FORCE_TTY:"0",NO_COLOR:"1"}});if(o.status!==0){let s=(o.stderr??"").trim(),a=`Failed to assign @${t} as reviewer on PR #${i}.`;return/could not resolve|not found|no user/i.test(s)?a+=`
|
|
411
|
+
|
|
412
|
+
Reason: User @${t} was not found. Verify the username exists and has access to this repository.`:/permission|forbidden|403/i.test(s)?a+=`
|
|
413
|
+
|
|
414
|
+
Reason: Insufficient permissions \u2014 @${t} may not have repo access.`:a+=`
|
|
415
|
+
|
|
416
|
+
Reason: ${s||"Unknown error"}`,{content:[{type:"text",text:a}],isError:!0}}if(n.item_id)try{va().updateStatus(n.item_id,"in-review")}catch(s){re.debug("Board sync to in-review failed",{error:s.message})}return kr(`Review requested: PR #${i}`,`@${t} assigned to review PR #${i}
|
|
417
|
+
Workflow #${e} \u2014 Issue #${n.item_id} "${n.item_title}"`),{content:[{type:"text",text:`PR #${i} reviewer: @${t}
|
|
418
|
+
Issue #${n.item_id} \u2192 in-review
|
|
419
|
+
|
|
420
|
+
@${t} can now review using catalyst_worker_review_done.`}]}}catch(n){return{content:[{type:"text",text:`Error: ${n.message}`}],isError:!0}}}),r.tool("catalyst_worker_review_done","Submit a review verdict for a workflow's PR. BEFORE calling this tool, the agent MUST: (0) Fetch the linked issue's acceptance criteria (from catalyst_board_get) and verify each criterion is met by the PR \u2014 unmet criteria are automatic blockers. Then perform a multi-pass review using the three Assure skills: (1) code-quality \u2014 correctness, maintainability, performance (read .github/skills/assure-code-quality/SKILL.md), (2) vulnerability-scan \u2014 OWASP/CWE security analysis (read .github/skills/assure-vulnerability-scan/SKILL.md), (3) pr-intelligence \u2014 change inventory, risk assessment, reviewer guidance (read .github/skills/assure-pr-intelligence/SKILL.md). Collect all findings, then call this tool with the verdict and specific comments. When requesting changes, ALWAYS post specific comments on the PR. When approving, post an approval summary.",{workflow_id:g.number().describe("Workflow ID"),verdict:g.enum(["approved","changes-requested","blocked"]).describe("Review verdict"),summary:g.string().optional().describe("Review summary"),comments:g.array(g.string()).optional().describe("List of specific review comments to post on the PR (required when changes-requested)")},async({workflow_id:e,verdict:t,summary:n,comments:i})=>{try{re.info("Submitting review verdict",{workflowId:e,verdict:t,comments:i?.length??0});let o=se().getWorkflow(e),s=o?.pr_number;if(s&&i?.length)for(let a of i)try{Jn("pr",s,a)}catch(c){re.debug("Review comment post failed",{error:c.message})}if(t==="approved"){if(se().approveWorkflow(e),s&&n)try{Jn("pr",s,`\u2705 **Approved**
|
|
421
|
+
|
|
422
|
+
${n}`)}catch(a){re.debug("Approval comment failed",{error:a.message})}return kr(`PR #${s} approved`,`Workflow #${e} PR #${s} approved.${n?`
|
|
423
|
+
${n}`:""}`),{content:[{type:"text",text:`Workflow #${e} PR #${s} approved.${n?`
|
|
424
|
+
|
|
425
|
+
${n}`:""}
|
|
426
|
+
|
|
427
|
+
\u26A0\uFE0F HUMAN GATE: Merge the PR manually, then call catalyst_worker_complete.`}]}}else{if(t==="blocked")return se().blockWorkflow(e,n??"Blocked by reviewer"),kr(`PR #${s} blocked`,`Workflow #${e} blocked.${n?`
|
|
428
|
+
Reason: ${n}`:""}`),{content:[{type:"text",text:`Workflow #${e} blocked by review.${n?`
|
|
429
|
+
|
|
430
|
+
Reason: ${n}`:""}`}]};if(s)try{let a="";o?.item_id&&(a=(ho("gh",["issue","view",o.item_id,"--json","assignees","--jq",".assignees[0].login"],{encoding:"utf-8",timeout:1e4,env:{...process.env,GH_FORCE_TTY:"0",NO_COLOR:"1"}}).stdout??"").trim());let c=a?`@${a} `:"";Jn("pr",s,`\u{1F504} **Changes Requested**
|
|
431
|
+
|
|
432
|
+
${c}Please address the review comments above.${n?`
|
|
433
|
+
|
|
434
|
+
${n}`:""}`)}catch(a){re.debug("Changes-requested comment failed",{error:a.message})}return kr(`Changes requested: PR #${s}`,`Workflow #${e} needs changes.${n?`
|
|
435
|
+
${n}`:""}`),{content:[{type:"text",text:`Changes requested on workflow #${e} PR #${s}.${n?`
|
|
436
|
+
|
|
437
|
+
${n}`:""}${i?.length?`
|
|
438
|
+
|
|
439
|
+
Posted ${i.length} review comment(s) on the PR.`:""}
|
|
440
|
+
|
|
441
|
+
The developer agent should address comments and push fixes.`}]}}}catch(o){return{content:[{type:"text",text:`Error: ${o.message}`}],isError:!0}}}),r.tool("catalyst_worker_push_fixes","Push fixes to an existing PR branch after review comments. This does NOT create a new PR \u2014 it commits and pushes to the same branch so the existing PR is updated. Use this when a reviewer has requested changes and the developer has made fixes. The agent MUST call catalyst_worker_preview_pr first to show changes to the user before pushing.",{workflow_id:g.number().describe("Workflow ID"),commit_message:g.string().describe("Commit message for the fix (conventional commit format, e.g., 'fix(scope): address review comments')")},async({workflow_id:e,commit_message:t})=>{try{re.info("Pushing fixes to existing PR",{workflowId:e});let n=se().getWorkflow(e);if(!n)return{content:[{type:"text",text:"Workflow not found"}],isError:!0};if(!n.pr_number)return{content:[{type:"text",text:"No PR found for this workflow. Cannot push fixes without an existing PR."}],isError:!0};if(!n.branch)return{content:[{type:"text",text:"No branch found for this workflow."}],isError:!0};if(!se().isPreviewed(e))return{content:[{type:"text",text:`\u26D4 HUMAN GATE VIOLATION: You must call catalyst_worker_preview_pr first and get user approval before pushing fixes.
|
|
442
|
+
|
|
443
|
+
Call catalyst_worker_preview_pr to show the changes, then proceed after user approval.`}],isError:!0};se().clearPreviewed(e);let i={...process.env,GH_FORCE_TTY:"0",NO_COLOR:"1"};if(er("git branch --show-current",{encoding:"utf-8",timeout:1e4,env:i}).trim()!==n.branch&&er(`git checkout ${n.branch}`,{encoding:"utf-8",timeout:15e3,env:i}),er("git add -A",{encoding:"utf-8",timeout:1e4,env:i}),!er("git status --porcelain",{encoding:"utf-8",timeout:1e4,env:i}).trim())return{content:[{type:"text",text:"No changes to commit. Make sure you've edited the files before pushing fixes."}],isError:!0};ho("git",["commit","-m",t],{encoding:"utf-8",timeout:15e3,env:i});let a=ho("git",["push","origin",n.branch],{encoding:"utf-8",timeout:3e4,env:i});if(a.status!==0)return{content:[{type:"text",text:`Failed to push fixes: ${(a.stderr??"").trim()}`}],isError:!0};try{Jn("pr",n.pr_number,`\u{1F527} **Fixes pushed**
|
|
444
|
+
|
|
445
|
+
Commit: \`${t}\`
|
|
446
|
+
|
|
447
|
+
Review comments have been addressed. Please re-review.`)}catch{re.debug("Fix comment on PR failed")}return kr(`Fixes pushed to PR #${n.pr_number}`,`Workflow #${e}: fixes pushed to branch ${n.branch}.
|
|
448
|
+
Commit: ${t}`),{content:[{type:"text",text:`Fixes pushed to PR #${n.pr_number} (branch: ${n.branch}).
|
|
449
|
+
Commit: ${t}
|
|
450
|
+
|
|
451
|
+
A comment has been posted on the PR. The reviewer can now re-review.`}]}}catch(n){return{content:[{type:"text",text:`Error: ${n.message}`}],isError:!0}}}),r.tool("catalyst_worker_complete","Mark a workflow as done (after PR is merged). Automatically closes the linked board issue and moves it to done.",{workflow_id:g.number().describe("Workflow ID")},async({workflow_id:e})=>{try{re.info("Completing workflow",{workflowId:e}),se().completeWorkflow(e);let t=se().getWorkflow(e),n=se().getWorkflowLog(e),i=t?IO(t.created_at,t.updated_at):"unknown";if(t?.item_id)try{Jn("issue",t.item_id,`\u2705 Completed via workflow #${e}. PR #${t.pr_number} merged.`),va().updateStatus(t.item_id,"done")}catch(o){re.debug("Issue close/board sync skipped",{error:o.message})}try{let o=t?.plan?JSON.parse(t.plan):{},s=(o.steps??[]).join("; ");pm().store({type:"lesson",title:`Completed: ${t?.item_title??`workflow #${e}`}`,content:`Workflow #${e} completed successfully.
|
|
452
|
+
Item: #${t?.item_id}
|
|
453
|
+
Branch: ${t?.branch}
|
|
454
|
+
PR: #${t?.pr_number}
|
|
455
|
+
Duration: ${i}
|
|
456
|
+
Steps: ${s}
|
|
457
|
+
Files: ${(o.files_to_change??[]).join(", ")}`,tags:["workflow-completion","automated"],related_files:o.files_to_change??[],timestamp:new Date().toISOString()})}catch(o){re.debug("Knowledge store not available for completion lesson",{error:o.message})}return kr(`Workflow #${e} completed`,`"${t?.item_title}" done in ${i}.
|
|
458
|
+
PR #${t?.pr_number} merged. Issue #${t?.item_id} closed.`),re.info("Workflow completed",{workflowId:e,duration:i,item:t?.item_id}),{content:[{type:"text",text:`Workflow #${e} completed \u2713
|
|
459
|
+
Item: #${t?.item_id} "${t?.item_title}" \u2192 closed
|
|
460
|
+
Branch: ${t?.branch}
|
|
461
|
+
PR: #${t?.pr_number}
|
|
462
|
+
Duration: ${i}
|
|
463
|
+
Steps: ${n.length}`}]}}catch(t){return{content:[{type:"text",text:`Error: ${t.message}`}],isError:!0}}}),r.tool("catalyst_worker_fail","Mark a workflow as failed (circuit breaker after max retries)",{workflow_id:g.number().describe("Workflow ID"),reason:g.string().describe("Why the workflow failed")},async({workflow_id:e,reason:t})=>{try{re.warn("Failing workflow (circuit breaker)",{workflowId:e,reason:t}),se().failWorkflow(e,t);try{let n=se().getWorkflow(e);pm().store({type:"lesson",title:`Failed: ${n?.item_title??`workflow #${e}`}`,content:`Workflow #${e} failed.
|
|
464
|
+
Item: #${n?.item_id}
|
|
465
|
+
Reason: ${t}`,tags:["workflow-failure","automated"],related_files:[],timestamp:new Date().toISOString()})}catch(n){re.debug("Knowledge store not available for failure lesson",{error:n.message})}return kr(`Workflow #${e} failed`,`Reason: ${t}
|
|
466
|
+
Escalate to human.`),{content:[{type:"text",text:`Workflow #${e} failed: ${t}
|
|
467
|
+
|
|
468
|
+
Escalate to human.`}]}}catch(n){return{content:[{type:"text",text:`Error: ${n.message}`}],isError:!0}}}),r.tool("catalyst_worker_dashboard","Show the digital worker dashboard \u2014 all active and recent workflows",{},async()=>{try{let e=se().getDashboard(),t=[],n=!0;try{let i=aa(),o=an(i);if(!o.ok){n=!1,t.push(`\u26A0\uFE0F Board Disconnected (${o.provider})`);for(let s of o.checks)s.ok||t.push(` \u274C ${s.name}: ${s.message}${s.fix?` \u2192 ${s.fix}`:""}`);t.push(" \u2192 Run catalyst_board_setup or catalyst_board_connect to fix."),t.push("")}}catch{n=!1,t.push("\u26A0\uFE0F Board Disconnected \u2014 could not load board config."),t.push(" \u2192 Check .github/catalyst.config.json or run catalyst_board_setup."),t.push("")}if(t.push(`Digital Worker Dashboard${n?"":" (board disconnected)"}`),t.push("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),t.push(`Active: ${e.active} | Pending: ${e.pending} | In Progress: ${e.inProgress} | In Review: ${e.inReview}`),t.push(`Done: ${e.done} | Failed: ${e.failed} | Blocked: ${e.blocked}`),t.push(""),e.workflows.length>0){t.push("Recent workflows:");for(let i of e.workflows){let o=CO(i.status);t.push(` ${o} #${i.id} [${i.status}] #${i.item_id} "${i.item_title}" (${i.role})${i.pr_number?` \u2192 PR #${i.pr_number}`:""}`)}}else t.push("No workflows yet. Use catalyst_worker_start to begin.");return{content:[{type:"text",text:t.join(`
|
|
469
|
+
`)}]}}catch(e){return{content:[{type:"text",text:`Error: ${e.message}`}],isError:!0}}}),r.tool("catalyst_worker_log","Show the step-by-step log for a specific workflow",{workflow_id:g.number().describe("Workflow ID")},async({workflow_id:e})=>{try{let t=se().getWorkflow(e);if(!t)return{content:[{type:"text",text:"Workflow not found"}],isError:!0};let n=se().getWorkflowLog(e),i=`Workflow #${e}: "${t.item_title}" [${t.status}]`,o=n.map((s,a)=>{let c=s.result==="success"?"\u2713":s.result==="failure"?"\u2717":"\u25CB";return` ${a+1}. ${c} [${s.role}] ${s.action} \u2014 ${s.detail}`}).join(`
|
|
470
|
+
`);return{content:[{type:"text",text:`${i}
|
|
471
|
+
|
|
472
|
+
${o||"(no steps recorded)"}`}]}}catch(t){return{content:[{type:"text",text:`Error: ${t.message}`}],isError:!0}}}),r.tool("catalyst_worker_roles","List all digital worker agent roles and their capabilities",{},async()=>({content:[{type:"text",text:`Digital Worker Agent Roles:
|
|
473
|
+
|
|
474
|
+
${zy.map(t=>[`### ${t.role.toUpperCase()}`,`${t.description}`,`Skills: ${t.skills.join(", ")}`,`Triggers: ${t.triggers.join(", ")}`,`Human gates: ${t.gates.length?t.gates.join(", "):"none"}`].join(`
|
|
475
|
+
`)).join(`
|
|
476
|
+
|
|
477
|
+
`)}`}]}))}function CO(r){return{pending:"\u23F3",planning:"\u{1F4DD}","in-progress":"\u{1F528}",review:"\u{1F50D}",approved:"\u2705",done:"\u2713",failed:"\u2717",blocked:"\u{1F6AB}"}[r]??"\u25CB"}function IO(r,e){let t=new Date(e).getTime()-new Date(r).getTime();return t<6e4?`${Math.round(t/1e3)}s`:t<36e5?`${Math.round(t/6e4)}m`:`${(t/36e5).toFixed(1)}h`}var $b=oe("notification"),xa=null;function Tb(){return xa||(xa=new pn),xa}function zb(r){r.tool("catalyst_notify_configure","Configure email notifications with SMTP. Alternatively set env vars: SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASS, SMTP_FROM, SMTP_SECURE.",{channel:g.enum(["console","email"]).describe("Delivery channel (default: email)"),email_recipients:g.array(g.string()).describe("Email addresses to send reports to"),smtp_host:g.string().optional().describe("SMTP server host (e.g. smtp.gmail.com, smtp.office365.com)"),smtp_port:g.number().optional().describe("SMTP port (587 for TLS, 465 for SSL). Default: 587"),smtp_secure:g.boolean().optional().describe("Use SSL (true for port 465). Default: false"),smtp_user:g.string().optional().describe("SMTP username / email address"),smtp_pass:g.string().optional().describe("SMTP password or app password"),smtp_from:g.string().optional().describe("From address (defaults to smtp_user)")},async({channel:e,email_recipients:t,smtp_host:n,smtp_port:i,smtp_secure:o,smtp_user:s,smtp_pass:a,smtp_from:c})=>{$b.info("Configuring notifications",{channel:e,recipients:t.length,smtp:n??"from env"});let l=n&&s&&a?{host:n,port:i??587,secure:o??!1,user:s,pass:a,from:c??s}:void 0;xa=new pn({channel:e,email_recipients:t,smtp:l});let u=l?`SMTP: ${l.host}:${l.port}`:"SMTP: from env vars";return{content:[{type:"text",text:`Notifications configured \u2192 channel: ${e}, recipients: ${t.join(", ")}, ${u}`}]}}),r.tool("catalyst_notify_send","Send a notification via SMTP email or display in console. Configure with catalyst_notify_configure or SMTP env vars first.",{subject:g.string().describe("Subject line / title"),body:g.string().describe("Full notification body (plain text)"),channel:g.enum(["console","email"]).optional().describe("Override channel for this message"),recipients:g.array(g.string()).optional().describe("Override recipients for this message")},async({subject:e,body:t,channel:n,recipients:i})=>{try{$b.info("Sending notification",{subject:e,channel:n??"default",recipients:i?.length});let o=await Tb().send({subject:e,body:t,channel:n,recipients:i});return o.success?{content:[{type:"text",text:`\u2713 ${o.channel}: ${o.message}`}]}:{content:[{type:"text",text:`\u2717 ${o.channel}: ${o.message}`}],isError:!0}}catch(o){return{content:[{type:"text",text:`Error sending email: ${o.message}`}],isError:!0}}}),r.tool("catalyst_notify_status","Show the current notification configuration",{},async()=>{let e=Tb().getConfig(),t=e.smtp?`${e.smtp.host}:${e.smtp.port} (user: ${e.smtp.user}, from: ${e.smtp.from})`:"not configured";return{content:[{type:"text",text:`Notification config:
|
|
478
|
+
Channel: ${e.channel}
|
|
479
|
+
Recipients: ${e.email_recipients.length?e.email_recipients.join(", "):"none"}
|
|
480
|
+
SMTP: ${t}`}]}})}var et=oe("server");et.info("Initializing CrewPilot MCP server");var Zt=new ta({name:"crewpilot",version:"1.0.0"});et.info("Registering tool modules...");py(Zt);et.debug("Registered terminal tools (3)");fy(Zt);et.debug("Registered git tools (6)");hy(Zt);et.debug("Registered knowledge tools (9)");gy(Zt);et.debug("Registered metrics tools (3)");vy(Zt);et.debug("Registered dispatch tools (3)");$y(Zt);et.debug("Registered board tools (13)");Eb(Zt);et.debug("Registered orchestrator/worker tools (14)");zb(Zt);et.debug("Registered notification tools (3)");Zt.tool("catalyst_config_get","Read Catalyst configuration: global settings, pillar toggles, and skill-level overrides. Returns the fully resolved config (defaults merged with .github/catalyst.config.json).",{pillar:g.string().optional().describe("Pillar name to check (e.g., 'engineer', 'assure'). Returns full config if omitted."),skill:g.string().optional().describe("Skill name within the pillar (e.g., 'test-first'). Requires pillar.")},async({pillar:r,skill:e})=>{let t=cy();if(!r)return{content:[{type:"text",text:JSON.stringify(t,null,2)}]};if(e){let i=ly(t,r,e),o=uy(t,r,e);return{content:[{type:"text",text:`${r}/${e}: enabled=${i}
|
|
481
|
+
Overrides: ${JSON.stringify(o)}`}]}}let n=t.pillars[r];return{content:[{type:"text",text:n?JSON.stringify(n,null,2):`Pillar "${r}" not configured (defaults apply).`}]}});et.debug("Registered config tool (1)");et.info("All 55 tools registered across 8 modules + config");async function AO(){let r=new na;await Zt.connect(r),et.info("CrewPilot MCP server running on stdio",{transport:"stdio",version:"1.0.0"})}AO();
|