@intelliweave/embedded 2.0.72-beta.6 → 2.0.72-beta.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/component/chunk-FSRPMVAS.js +1 -0
- package/dist/component/component.d.ts +42 -2
- package/dist/component/component.js +265 -47
- package/dist/component/ort-wasm-simd-threaded.wasm +0 -0
- package/dist/component/ort.bundle.min-5QOPZPPI.js +1834 -0
- package/dist/intelliweave-wordpress.zip +0 -0
- package/dist/node/node.d.ts +44 -4
- package/dist/node/node.js +29 -22
- package/dist/react/react.d.ts +38 -2
- package/dist/react/react.js +143 -35
- package/dist/script-tag/script-tag.js +177 -69
- package/dist/webpack/index.d.ts +58 -4
- package/dist/webpack/index.js +156 -48
- package/package.json +1 -1
- package/tests/common.html +357 -0
- package/tests/fullscreen.html +37 -0
- package/tests/images.html +35 -0
- package/tests/index.html +32 -0
- package/tests/local-hub.html +34 -0
- package/tests/subagents.html +128 -0
|
@@ -1,51 +1,138 @@
|
|
|
1
|
-
import tt from"openai";import{v4 as $e}from"uuid";var k=class{constructor(){this.size=4096;this.groups=[]}createGroup(t){let e=new Me;return e.id=t,this.groups.push(e),e}group(t){return this.groups.find(e=>e.id===t)}static countTokensInText(t){return t==null?t="":typeof t=="number"?t=t+"":typeof t!="string"&&(t=JSON.stringify(t)),Math.ceil(t.length/3)}countTokens(){return this.groups.reduce((t,e)=>t+e.tokenCount,0)}removeOverflow(){let t=this.countTokens(),e=this.groups.reduce((i,o)=>i+o.weight,0);for(;t>this.size;){let i=this.groups.slice().sort((s,n)=>{let a=Math.floor(s.weight/e*this.size),l=Math.floor(n.weight/e*this.size),c=s.tokenCount-a;return n.tokenCount-l-c}),o=this.removeOneItem(i);if(!o)throw new Error("Too many items in the token window that cannot be removed.");t-=o.tokenCount}}removeOneItem(t){for(let e of t){let i=e.items.findIndex(s=>!s.cannotRemove);if(i===-1)continue;let o=e.items[i];return e.items.splice(i,1),e.tokenCount-=o.tokenCount,o}return null}},Me=class{constructor(){this.id="";this.items=[];this.weight=1;this.tokenCount=0;this.separator=`
|
|
2
|
-
`;this.itemPadding=0;this.sortFunction=(t,e)=>t.sortOrder!==e.sortOrder?t.sortOrder-e.sortOrder:t.dateAdded!==e.dateAdded?t.dateAdded-e.dateAdded:0}setItemPadding(t){return this.itemPadding=t,this.recalculateTokens(),this}sortBy(t){return this.sortFunction=t,this.items.sort(this.sortFunction),this}setSeparator(t){return this.separator==t?this:(this.separator=t,this.recalculateTokens(),this)}setWeight(t){return this.weight=t,this}recalculateTokens(){this.tokenCount=this.items.reduce((t,e)=>(e.tokenCount=k.countTokensInText(typeof e.data=="string"?e.data:JSON.stringify(e.data))+k.countTokensInText(this.separator)+this.itemPadding,t+e.tokenCount),0)}add(t){typeof t=="string"&&(t={source:"user",data:t});let e=t;e.id===void 0&&(e.id=$e()),!e.sections?.length&&typeof e.data=="string"?e.text=e.data:e.text=e.sections?.map(o=>{if(o.type==="text")return o.text||"";if(o.type==="tool_call")return`[Tool Call: ${o.toolKbName||o.toolName}] `;if(o.type==="tool_result"&&o.toolErrorResponse)return`[Tool Error: ${o.toolErrorResponse}] `}).filter(o=>!!o).join(`
|
|
1
|
+
import{b as C,c as ed,d as r_}from"./chunk-FSRPMVAS.js";var wf=C(Je=>{"use strict";Object.defineProperty(Je,"__esModule",{value:!0});Je.regexpCode=Je.getEsmExportName=Je.getProperty=Je.safeStringify=Je.stringify=Je.strConcat=Je.addCodeArg=Je.str=Je._=Je.nil=Je._Code=Je.Name=Je.IDENTIFIER=Je._CodeOrName=void 0;var _f=class{};Je._CodeOrName=_f;Je.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Ea=class extends _f{constructor(e){if(super(),!Je.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}}};Je.Name=Ea;var jn=class extends _f{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((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof Ea&&(r[n.str]=(r[n.str]||0)+1),r),{})}};Je._Code=jn;Je.nil=new jn("");function oz(t,...e){let r=[t[0]],n=0;for(;n<e.length;)vx(r,e[n]),r.push(t[++n]);return new jn(r)}Je._=oz;var yx=new jn("+");function sz(t,...e){let r=[bf(t[0])],n=0;for(;n<e.length;)r.push(yx),vx(r,e[n]),r.push(yx,bf(t[++n]));return KF(r),new jn(r)}Je.str=sz;function vx(t,e){e instanceof jn?t.push(...e._items):e instanceof Ea?t.push(e):t.push(QF(e))}Je.addCodeArg=vx;function KF(t){let e=1;for(;e<t.length-1;){if(t[e]===yx){let r=JF(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function JF(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Ea||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof Ea))return`"${t}${e.slice(1)}`}function YF(t,e){return e.emptyStr()?t:t.emptyStr()?e:sz`${t}${e}`}Je.strConcat=YF;function QF(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:bf(Array.isArray(t)?t.join(","):t)}function e9(t){return new jn(bf(t))}Je.stringify=e9;function bf(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}Je.safeStringify=bf;function t9(t){return typeof t=="string"&&Je.IDENTIFIER.test(t)?new jn(`.${t}`):oz`[${t}]`}Je.getProperty=t9;function r9(t){if(typeof t=="string"&&Je.IDENTIFIER.test(t))return new jn(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}Je.getEsmExportName=r9;function n9(t){return new jn(t.toString())}Je.regexpCode=n9});var wx=C(tn=>{"use strict";Object.defineProperty(tn,"__esModule",{value:!0});tn.ValueScope=tn.ValueScopeName=tn.Scope=tn.varKinds=tn.UsedValueState=void 0;var en=wf(),_x=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Tg;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Tg||(tn.UsedValueState=Tg={}));tn.varKinds={const:new en.Name("const"),let:new en.Name("let"),var:new en.Name("var")};var Ag=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof en.Name?e:this.name(e)}name(e){return new en.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._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}}};tn.Scope=Ag;var zg=class extends en.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,en._)`.${new en.Name(r)}[${n}]`}};tn.ValueScopeName=zg;var i9=(0,en._)`\n`,bx=class extends Ag{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?i9:en.nil}}get(){return this._scope}name(e){return new zg(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let i=this.toName(e),{prefix:o}=i,s=(n=r.key)!==null&&n!==void 0?n:r.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 l=this._scope[o]||(this._scope[o]=[]),c=l.length;return l[c]=r.ref,i.setValue(r,{property:o,itemIndex:c}),i}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,en._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,i=>{if(i.value===void 0)throw new Error(`CodeGen: name "${i}" has no value`);return i.value.code},r,n)}_reduceValues(e,r,n={},i){let o=en.nil;for(let s in e){let a=e[s];if(!a)continue;let l=n[s]=n[s]||new Map;a.forEach(c=>{if(l.has(c))return;l.set(c,Tg.Started);let u=r(c);if(u){let d=this.opts.es5?tn.varKinds.var:tn.varKinds.const;o=(0,en._)`${o}${d} ${c} = ${u};${this.opts._n}`}else if(u=i?.(c))o=(0,en._)`${o}${u}${this.opts._n}`;else throw new _x(c);l.set(c,Tg.Completed)})}return o}};tn.ValueScope=bx});var Ue=C(Me=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.or=Me.and=Me.not=Me.CodeGen=Me.operators=Me.varKinds=Me.ValueScopeName=Me.ValueScope=Me.Scope=Me.Name=Me.regexpCode=Me.stringify=Me.getProperty=Me.nil=Me.strConcat=Me.str=Me._=void 0;var We=wf(),ai=wx(),gs=wf();Object.defineProperty(Me,"_",{enumerable:!0,get:function(){return gs._}});Object.defineProperty(Me,"str",{enumerable:!0,get:function(){return gs.str}});Object.defineProperty(Me,"strConcat",{enumerable:!0,get:function(){return gs.strConcat}});Object.defineProperty(Me,"nil",{enumerable:!0,get:function(){return gs.nil}});Object.defineProperty(Me,"getProperty",{enumerable:!0,get:function(){return gs.getProperty}});Object.defineProperty(Me,"stringify",{enumerable:!0,get:function(){return gs.stringify}});Object.defineProperty(Me,"regexpCode",{enumerable:!0,get:function(){return gs.regexpCode}});Object.defineProperty(Me,"Name",{enumerable:!0,get:function(){return gs.Name}});var Rg=wx();Object.defineProperty(Me,"Scope",{enumerable:!0,get:function(){return Rg.Scope}});Object.defineProperty(Me,"ValueScope",{enumerable:!0,get:function(){return Rg.ValueScope}});Object.defineProperty(Me,"ValueScopeName",{enumerable:!0,get:function(){return Rg.ValueScopeName}});Object.defineProperty(Me,"varKinds",{enumerable:!0,get:function(){return Rg.varKinds}});Me.operators={GT:new We._Code(">"),GTE:new We._Code(">="),LT:new We._Code("<"),LTE:new We._Code("<="),EQ:new We._Code("==="),NEQ:new We._Code("!=="),NOT:new We._Code("!"),OR:new We._Code("||"),AND:new We._Code("&&"),ADD:new We._Code("+")};var xo=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},xx=class extends xo{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?ai.varKinds.var:this.varKind,i=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${i};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=Qc(this.rhs,e,r)),this}get names(){return this.rhs instanceof We._CodeOrName?this.rhs.names:{}}},Cg=class extends xo{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof We.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Qc(this.rhs,e,r),this}get names(){let e=this.lhs instanceof We.Name?{}:{...this.lhs.names};return Og(e,this.rhs)}},$x=class extends Cg{constructor(e,r,n,i){super(e,n,i),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},kx=class extends xo{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Sx=class extends xo{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Ix=class extends xo{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Ex=class extends xo{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=Qc(this.code,e,r),this}get names(){return this.code instanceof We._CodeOrName?this.code.names:{}}},xf=class extends xo{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,i=n.length;for(;i--;){let o=n[i];o.optimizeNames(e,r)||(o9(e,o.names),n.splice(i,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>Aa(e,r.names),{})}},$o=class extends xf{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Px=class extends xf{},Yc=class extends $o{};Yc.kind="else";var Pa=class t extends $o{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new Yc(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(az(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=Qc(this.condition,e,r),this}get names(){let e=super.names;return Og(e,this.condition),this.else&&Aa(e,this.else.names),e}};Pa.kind="if";var Ta=class extends $o{};Ta.kind="for";var Tx=class extends Ta{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=Qc(this.iteration,e,r),this}get names(){return Aa(super.names,this.iteration.names)}},Ax=class extends Ta{constructor(e,r,n,i){super(),this.varKind=e,this.name=r,this.from=n,this.to=i}render(e){let r=e.es5?ai.varKinds.var:this.varKind,{name:n,from:i,to:o}=this;return`for(${r} ${n}=${i}; ${n}<${o}; ${n}++)`+super.render(e)}get names(){let e=Og(super.names,this.from);return Og(e,this.to)}},Ng=class extends Ta{constructor(e,r,n,i){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=i}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=Qc(this.iterable,e,r),this}get names(){return Aa(super.names,this.iterable.names)}},$f=class extends $o{constructor(e,r,n){super(),this.name=e,this.args=r,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};$f.kind="func";var kf=class extends xf{render(e){return"return "+super.render(e)}};kf.kind="return";var zx=class extends $o{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,i;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(i=this.finally)===null||i===void 0||i.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&Aa(e,this.catch.names),this.finally&&Aa(e,this.finally.names),e}},Sf=class extends $o{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Sf.kind="catch";var If=class extends $o{render(e){return"finally"+super.render(e)}};If.kind="finally";var Cx=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
2
|
+
`:""},this._extScope=e,this._scope=new ai.Scope({parent:e}),this._nodes=[new Px]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,i){let o=this._scope.toName(r);return n!==void 0&&i&&(this._constants[o.str]=n),this._leafNode(new xx(e,o,n)),o}const(e,r,n){return this._def(ai.varKinds.const,e,r,n)}let(e,r,n){return this._def(ai.varKinds.let,e,r,n)}var(e,r,n){return this._def(ai.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new Cg(e,r,n))}add(e,r){return this._leafNode(new $x(e,Me.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==We.nil&&this._leafNode(new Ex(e)),this}object(...e){let r=["{"];for(let[n,i]of e)r.length>1&&r.push(","),r.push(n),(n!==i||this.opts.es5)&&(r.push(":"),(0,We.addCodeArg)(r,i));return r.push("}"),new We._Code(r)}if(e,r,n){if(this._blockNode(new Pa(e)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new Pa(e))}else(){return this._elseNode(new Yc)}endIf(){return this._endBlockNode(Pa,Yc)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Tx(e),r)}forRange(e,r,n,i,o=this.opts.es5?ai.varKinds.var:ai.varKinds.let){let s=this._scope.toName(e);return this._for(new Ax(o,s,r,n),()=>i(s))}forOf(e,r,n,i=ai.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let s=r instanceof We.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,We._)`${s}.length`,a=>{this.var(o,(0,We._)`${s}[${a}]`),n(o)})}return this._for(new Ng("of",i,o,r),()=>n(o))}forIn(e,r,n,i=this.opts.es5?ai.varKinds.var:ai.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,We._)`Object.keys(${r})`,n);let o=this._scope.toName(e);return this._for(new Ng("in",i,o,r),()=>n(o))}endFor(){return this._endBlockNode(Ta)}label(e){return this._leafNode(new kx(e))}break(e){return this._leafNode(new Sx(e))}return(e){let r=new kf;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(kf)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let i=new zx;if(this._blockNode(i),this.code(e),r){let o=this.name("e");this._currNode=i.catch=new Sf(o),r(o)}return n&&(this._currNode=i.finally=new If,this.code(n)),this._endBlockNode(Sf,If)}throw(e){return this._leafNode(new Ix(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=We.nil,n,i){return this._blockNode(new $f(e,r,n)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode($f)}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,r){let n=this._currNode;if(n instanceof e||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof Pa))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};Me.CodeGen=Cx;function Aa(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Og(t,e){return e instanceof We._CodeOrName?Aa(t,e.names):t}function Qc(t,e,r){if(t instanceof We.Name)return n(t);if(!i(t))return t;return new We._Code(t._items.reduce((o,s)=>(s instanceof We.Name&&(s=n(s)),s instanceof We._Code?o.push(...s._items):o.push(s),o),[]));function n(o){let s=r[o.str];return s===void 0||e[o.str]!==1?o:(delete e[o.str],s)}function i(o){return o instanceof We._Code&&o._items.some(s=>s instanceof We.Name&&e[s.str]===1&&r[s.str]!==void 0)}}function o9(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function az(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,We._)`!${Nx(t)}`}Me.not=az;var s9=lz(Me.operators.AND);function a9(...t){return t.reduce(s9)}Me.and=a9;var l9=lz(Me.operators.OR);function c9(...t){return t.reduce(l9)}Me.or=c9;function lz(t){return(e,r)=>e===We.nil?r:r===We.nil?e:(0,We._)`${Nx(e)} ${t} ${Nx(r)}`}function Nx(t){return t instanceof We.Name?t:(0,We._)`(${t})`}});var Ye=C(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.checkStrictMode=Ze.getErrorPath=Ze.Type=Ze.useFunc=Ze.setEvaluated=Ze.evaluatedPropsToName=Ze.mergeEvaluated=Ze.eachItem=Ze.unescapeJsonPointer=Ze.escapeJsonPointer=Ze.escapeFragment=Ze.unescapeFragment=Ze.schemaRefOrVal=Ze.schemaHasRulesButRef=Ze.schemaHasRules=Ze.checkUnknownRules=Ze.alwaysValidSchema=Ze.toHash=void 0;var mt=Ue(),u9=wf();function d9(t){let e={};for(let r of t)e[r]=!0;return e}Ze.toHash=d9;function f9(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(dz(t,e),!fz(e,t.self.RULES.all))}Ze.alwaysValidSchema=f9;function dz(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let i=n.RULES.keywords;for(let o in e)i[o]||hz(t,`unknown keyword: "${o}"`)}Ze.checkUnknownRules=dz;function fz(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}Ze.schemaHasRules=fz;function p9(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}Ze.schemaHasRulesButRef=p9;function m9({topSchemaRef:t,schemaPath:e},r,n,i){if(!i){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,mt._)`${r}`}return(0,mt._)`${t}${e}${(0,mt.getProperty)(n)}`}Ze.schemaRefOrVal=m9;function h9(t){return pz(decodeURIComponent(t))}Ze.unescapeFragment=h9;function g9(t){return encodeURIComponent(Rx(t))}Ze.escapeFragment=g9;function Rx(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}Ze.escapeJsonPointer=Rx;function pz(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}Ze.unescapeJsonPointer=pz;function y9(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}Ze.eachItem=y9;function cz({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(i,o,s,a)=>{let l=s===void 0?o:s instanceof mt.Name?(o instanceof mt.Name?t(i,o,s):e(i,o,s),s):o instanceof mt.Name?(e(i,s,o),o):r(o,s);return a===mt.Name&&!(l instanceof mt.Name)?n(i,l):l}}Ze.mergeEvaluated={props:cz({mergeNames:(t,e,r)=>t.if((0,mt._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,mt._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,mt._)`${r} || {}`).code((0,mt._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,mt._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,mt._)`${r} || {}`),Mx(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:mz}),items:cz({mergeNames:(t,e,r)=>t.if((0,mt._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,mt._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,mt._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,mt._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function mz(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,mt._)`{}`);return e!==void 0&&Mx(t,r,e),r}Ze.evaluatedPropsToName=mz;function Mx(t,e,r){Object.keys(r).forEach(n=>t.assign((0,mt._)`${e}${(0,mt.getProperty)(n)}`,!0))}Ze.setEvaluated=Mx;var uz={};function v9(t,e){return t.scopeValue("func",{ref:e,code:uz[e.code]||(uz[e.code]=new u9._Code(e.code))})}Ze.useFunc=v9;var Ox;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Ox||(Ze.Type=Ox={}));function _9(t,e,r){if(t instanceof mt.Name){let n=e===Ox.Num;return r?n?(0,mt._)`"[" + ${t} + "]"`:(0,mt._)`"['" + ${t} + "']"`:n?(0,mt._)`"/" + ${t}`:(0,mt._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,mt.getProperty)(t).toString():"/"+Rx(t)}Ze.getErrorPath=_9;function hz(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}Ze.checkStrictMode=hz});var ko=C(jx=>{"use strict";Object.defineProperty(jx,"__esModule",{value:!0});var Ar=Ue(),b9={data:new Ar.Name("data"),valCxt:new Ar.Name("valCxt"),instancePath:new Ar.Name("instancePath"),parentData:new Ar.Name("parentData"),parentDataProperty:new Ar.Name("parentDataProperty"),rootData:new Ar.Name("rootData"),dynamicAnchors:new Ar.Name("dynamicAnchors"),vErrors:new Ar.Name("vErrors"),errors:new Ar.Name("errors"),this:new Ar.Name("this"),self:new Ar.Name("self"),scope:new Ar.Name("scope"),json:new Ar.Name("json"),jsonPos:new Ar.Name("jsonPos"),jsonLen:new Ar.Name("jsonLen"),jsonPart:new Ar.Name("jsonPart")};jx.default=b9});var Ef=C(zr=>{"use strict";Object.defineProperty(zr,"__esModule",{value:!0});zr.extendErrors=zr.resetErrorsCount=zr.reportExtraError=zr.reportError=zr.keyword$DataError=zr.keywordError=void 0;var He=Ue(),Mg=Ye(),Zr=ko();zr.keywordError={message:({keyword:t})=>(0,He.str)`must pass "${t}" keyword validation`};zr.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,He.str)`"${t}" keyword must be ${e} ($data)`:(0,He.str)`"${t}" keyword is invalid ($data)`};function w9(t,e=zr.keywordError,r,n){let{it:i}=t,{gen:o,compositeRule:s,allErrors:a}=i,l=vz(t,e,r);n??(s||a)?gz(o,l):yz(i,(0,He._)`[${l}]`)}zr.reportError=w9;function x9(t,e=zr.keywordError,r){let{it:n}=t,{gen:i,compositeRule:o,allErrors:s}=n,a=vz(t,e,r);gz(i,a),o||s||yz(n,Zr.default.vErrors)}zr.reportExtraError=x9;function $9(t,e){t.assign(Zr.default.errors,e),t.if((0,He._)`${Zr.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,He._)`${Zr.default.vErrors}.length`,e),()=>t.assign(Zr.default.vErrors,null)))}zr.resetErrorsCount=$9;function k9({gen:t,keyword:e,schemaValue:r,data:n,errsCount:i,it:o}){if(i===void 0)throw new Error("ajv implementation error");let s=t.name("err");t.forRange("i",i,Zr.default.errors,a=>{t.const(s,(0,He._)`${Zr.default.vErrors}[${a}]`),t.if((0,He._)`${s}.instancePath === undefined`,()=>t.assign((0,He._)`${s}.instancePath`,(0,He.strConcat)(Zr.default.instancePath,o.errorPath))),t.assign((0,He._)`${s}.schemaPath`,(0,He.str)`${o.errSchemaPath}/${e}`),o.opts.verbose&&(t.assign((0,He._)`${s}.schema`,r),t.assign((0,He._)`${s}.data`,n))})}zr.extendErrors=k9;function gz(t,e){let r=t.const("err",e);t.if((0,He._)`${Zr.default.vErrors} === null`,()=>t.assign(Zr.default.vErrors,(0,He._)`[${r}]`),(0,He._)`${Zr.default.vErrors}.push(${r})`),t.code((0,He._)`${Zr.default.errors}++`)}function yz(t,e){let{gen:r,validateName:n,schemaEnv:i}=t;i.$async?r.throw((0,He._)`new ${t.ValidationError}(${e})`):(r.assign((0,He._)`${n}.errors`,e),r.return(!1))}var za={keyword:new He.Name("keyword"),schemaPath:new He.Name("schemaPath"),params:new He.Name("params"),propertyName:new He.Name("propertyName"),message:new He.Name("message"),schema:new He.Name("schema"),parentSchema:new He.Name("parentSchema")};function vz(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,He._)`{}`:S9(t,e,r)}function S9(t,e,r={}){let{gen:n,it:i}=t,o=[I9(i,r),E9(t,r)];return P9(t,e,o),n.object(...o)}function I9({errorPath:t},{instancePath:e}){let r=e?(0,He.str)`${t}${(0,Mg.getErrorPath)(e,Mg.Type.Str)}`:t;return[Zr.default.instancePath,(0,He.strConcat)(Zr.default.instancePath,r)]}function E9({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let i=n?e:(0,He.str)`${e}/${t}`;return r&&(i=(0,He.str)`${i}${(0,Mg.getErrorPath)(r,Mg.Type.Str)}`),[za.schemaPath,i]}function P9(t,{params:e,message:r},n){let{keyword:i,data:o,schemaValue:s,it:a}=t,{opts:l,propertyName:c,topSchemaRef:u,schemaPath:d}=a;n.push([za.keyword,i],[za.params,typeof e=="function"?e(t):e||(0,He._)`{}`]),l.messages&&n.push([za.message,typeof r=="function"?r(t):r]),l.verbose&&n.push([za.schema,s],[za.parentSchema,(0,He._)`${u}${d}`],[Zr.default.data,o]),c&&n.push([za.propertyName,c])}});var bz=C(eu=>{"use strict";Object.defineProperty(eu,"__esModule",{value:!0});eu.boolOrEmptySchema=eu.topBoolOrEmptySchema=void 0;var T9=Ef(),A9=Ue(),z9=ko(),C9={message:"boolean schema is false"};function N9(t){let{gen:e,schema:r,validateName:n}=t;r===!1?_z(t,!1):typeof r=="object"&&r.$async===!0?e.return(z9.default.data):(e.assign((0,A9._)`${n}.errors`,null),e.return(!0))}eu.topBoolOrEmptySchema=N9;function O9(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),_z(t)):r.var(e,!0)}eu.boolOrEmptySchema=O9;function _z(t,e){let{gen:r,data:n}=t,i={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,T9.reportError)(i,C9,void 0,e)}});var Dx=C(tu=>{"use strict";Object.defineProperty(tu,"__esModule",{value:!0});tu.getRules=tu.isJSONType=void 0;var R9=["string","number","integer","boolean","null","object","array"],M9=new Set(R9);function j9(t){return typeof t=="string"&&M9.has(t)}tu.isJSONType=j9;function D9(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}tu.getRules=D9});var Lx=C(ys=>{"use strict";Object.defineProperty(ys,"__esModule",{value:!0});ys.shouldUseRule=ys.shouldUseGroup=ys.schemaHasRulesForType=void 0;function L9({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&wz(t,n)}ys.schemaHasRulesForType=L9;function wz(t,e){return e.rules.some(r=>xz(t,r))}ys.shouldUseGroup=wz;function xz(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}ys.shouldUseRule=xz});var Pf=C(Cr=>{"use strict";Object.defineProperty(Cr,"__esModule",{value:!0});Cr.reportTypeError=Cr.checkDataTypes=Cr.checkDataType=Cr.coerceAndCheckDataType=Cr.getJSONTypes=Cr.getSchemaTypes=Cr.DataType=void 0;var U9=Dx(),Z9=Lx(),F9=Ef(),ze=Ue(),$z=Ye(),ru;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(ru||(Cr.DataType=ru={}));function V9(t){let e=kz(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}Cr.getSchemaTypes=V9;function kz(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(U9.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Cr.getJSONTypes=kz;function q9(t,e){let{gen:r,data:n,opts:i}=t,o=W9(e,i.coerceTypes),s=e.length>0&&!(o.length===0&&e.length===1&&(0,Z9.schemaHasRulesForType)(t,e[0]));if(s){let a=Zx(e,n,i.strictNumbers,ru.Wrong);r.if(a,()=>{o.length?B9(t,e,o):Fx(t)})}return s}Cr.coerceAndCheckDataType=q9;var Sz=new Set(["string","number","integer","boolean","null"]);function W9(t,e){return e?t.filter(r=>Sz.has(r)||e==="array"&&r==="array"):[]}function B9(t,e,r){let{gen:n,data:i,opts:o}=t,s=n.let("dataType",(0,ze._)`typeof ${i}`),a=n.let("coerced",(0,ze._)`undefined`);o.coerceTypes==="array"&&n.if((0,ze._)`${s} == 'object' && Array.isArray(${i}) && ${i}.length == 1`,()=>n.assign(i,(0,ze._)`${i}[0]`).assign(s,(0,ze._)`typeof ${i}`).if(Zx(e,i,o.strictNumbers),()=>n.assign(a,i))),n.if((0,ze._)`${a} !== undefined`);for(let c of r)(Sz.has(c)||c==="array"&&o.coerceTypes==="array")&&l(c);n.else(),Fx(t),n.endIf(),n.if((0,ze._)`${a} !== undefined`,()=>{n.assign(i,a),G9(t,a)});function l(c){switch(c){case"string":n.elseIf((0,ze._)`${s} == "number" || ${s} == "boolean"`).assign(a,(0,ze._)`"" + ${i}`).elseIf((0,ze._)`${i} === null`).assign(a,(0,ze._)`""`);return;case"number":n.elseIf((0,ze._)`${s} == "boolean" || ${i} === null
|
|
3
|
+
|| (${s} == "string" && ${i} && ${i} == +${i})`).assign(a,(0,ze._)`+${i}`);return;case"integer":n.elseIf((0,ze._)`${s} === "boolean" || ${i} === null
|
|
4
|
+
|| (${s} === "string" && ${i} && ${i} == +${i} && !(${i} % 1))`).assign(a,(0,ze._)`+${i}`);return;case"boolean":n.elseIf((0,ze._)`${i} === "false" || ${i} === 0 || ${i} === null`).assign(a,!1).elseIf((0,ze._)`${i} === "true" || ${i} === 1`).assign(a,!0);return;case"null":n.elseIf((0,ze._)`${i} === "" || ${i} === 0 || ${i} === false`),n.assign(a,null);return;case"array":n.elseIf((0,ze._)`${s} === "string" || ${s} === "number"
|
|
5
|
+
|| ${s} === "boolean" || ${i} === null`).assign(a,(0,ze._)`[${i}]`)}}}function G9({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,ze._)`${e} !== undefined`,()=>t.assign((0,ze._)`${e}[${r}]`,n))}function Ux(t,e,r,n=ru.Correct){let i=n===ru.Correct?ze.operators.EQ:ze.operators.NEQ,o;switch(t){case"null":return(0,ze._)`${e} ${i} null`;case"array":o=(0,ze._)`Array.isArray(${e})`;break;case"object":o=(0,ze._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":o=s((0,ze._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":o=s();break;default:return(0,ze._)`typeof ${e} ${i} ${t}`}return n===ru.Correct?o:(0,ze.not)(o);function s(a=ze.nil){return(0,ze.and)((0,ze._)`typeof ${e} == "number"`,a,r?(0,ze._)`isFinite(${e})`:ze.nil)}}Cr.checkDataType=Ux;function Zx(t,e,r,n){if(t.length===1)return Ux(t[0],e,r,n);let i,o=(0,$z.toHash)(t);if(o.array&&o.object){let s=(0,ze._)`typeof ${e} != "object"`;i=o.null?s:(0,ze._)`!${e} || ${s}`,delete o.null,delete o.array,delete o.object}else i=ze.nil;o.number&&delete o.integer;for(let s in o)i=(0,ze.and)(i,Ux(s,e,r,n));return i}Cr.checkDataTypes=Zx;var H9={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,ze._)`{type: ${t}}`:(0,ze._)`{type: ${e}}`};function Fx(t){let e=X9(t);(0,F9.reportError)(e,H9)}Cr.reportTypeError=Fx;function X9(t){let{gen:e,data:r,schema:n}=t,i=(0,$z.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:i,schemaValue:i,parentSchema:n,params:{},it:t}}});var Ez=C(jg=>{"use strict";Object.defineProperty(jg,"__esModule",{value:!0});jg.assignDefaults=void 0;var nu=Ue(),K9=Ye();function J9(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let i in r)Iz(t,i,r[i].default);else e==="array"&&Array.isArray(n)&&n.forEach((i,o)=>Iz(t,o,i.default))}jg.assignDefaults=J9;function Iz(t,e,r){let{gen:n,compositeRule:i,data:o,opts:s}=t;if(r===void 0)return;let a=(0,nu._)`${o}${(0,nu.getProperty)(e)}`;if(i){(0,K9.checkStrictMode)(t,`default is ignored for: ${a}`);return}let l=(0,nu._)`${a} === undefined`;s.useDefaults==="empty"&&(l=(0,nu._)`${l} || ${a} === null || ${a} === ""`),n.if(l,(0,nu._)`${a} = ${(0,nu.stringify)(r)}`)}});var Dn=C(dt=>{"use strict";Object.defineProperty(dt,"__esModule",{value:!0});dt.validateUnion=dt.validateArray=dt.usePattern=dt.callValidateCode=dt.schemaProperties=dt.allSchemaProperties=dt.noPropertyInData=dt.propertyInData=dt.isOwnProperty=dt.hasPropFunc=dt.reportMissingProp=dt.checkMissingProp=dt.checkReportMissingProp=void 0;var xt=Ue(),Vx=Ye(),vs=ko(),Y9=Ye();function Q9(t,e){let{gen:r,data:n,it:i}=t;r.if(Wx(r,n,e,i.opts.ownProperties),()=>{t.setParams({missingProperty:(0,xt._)`${e}`},!0),t.error()})}dt.checkReportMissingProp=Q9;function e5({gen:t,data:e,it:{opts:r}},n,i){return(0,xt.or)(...n.map(o=>(0,xt.and)(Wx(t,e,o,r.ownProperties),(0,xt._)`${i} = ${o}`)))}dt.checkMissingProp=e5;function t5(t,e){t.setParams({missingProperty:e},!0),t.error()}dt.reportMissingProp=t5;function Pz(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,xt._)`Object.prototype.hasOwnProperty`})}dt.hasPropFunc=Pz;function qx(t,e,r){return(0,xt._)`${Pz(t)}.call(${e}, ${r})`}dt.isOwnProperty=qx;function r5(t,e,r,n){let i=(0,xt._)`${e}${(0,xt.getProperty)(r)} !== undefined`;return n?(0,xt._)`${i} && ${qx(t,e,r)}`:i}dt.propertyInData=r5;function Wx(t,e,r,n){let i=(0,xt._)`${e}${(0,xt.getProperty)(r)} === undefined`;return n?(0,xt.or)(i,(0,xt.not)(qx(t,e,r))):i}dt.noPropertyInData=Wx;function Tz(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}dt.allSchemaProperties=Tz;function n5(t,e){return Tz(e).filter(r=>!(0,Vx.alwaysValidSchema)(t,e[r]))}dt.schemaProperties=n5;function i5({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:i,errorPath:o},it:s},a,l,c){let u=c?(0,xt._)`${t}, ${e}, ${n}${i}`:e,d=[[vs.default.instancePath,(0,xt.strConcat)(vs.default.instancePath,o)],[vs.default.parentData,s.parentData],[vs.default.parentDataProperty,s.parentDataProperty],[vs.default.rootData,vs.default.rootData]];s.opts.dynamicRef&&d.push([vs.default.dynamicAnchors,vs.default.dynamicAnchors]);let p=(0,xt._)`${u}, ${r.object(...d)}`;return l!==xt.nil?(0,xt._)`${a}.call(${l}, ${p})`:(0,xt._)`${a}(${p})`}dt.callValidateCode=i5;var o5=(0,xt._)`new RegExp`;function s5({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:i}=e.code,o=i(r,n);return t.scopeValue("pattern",{key:o.toString(),ref:o,code:(0,xt._)`${i.code==="new RegExp"?o5:(0,Y9.useFunc)(t,i)}(${r}, ${n})`})}dt.usePattern=s5;function a5(t){let{gen:e,data:r,keyword:n,it:i}=t,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 l=e.const("len",(0,xt._)`${r}.length`);e.forRange("i",0,l,c=>{t.subschema({keyword:n,dataProp:c,dataPropType:Vx.Type.Num},o),e.if((0,xt.not)(o),a)})}}dt.validateArray=a5;function l5(t){let{gen:e,schema:r,keyword:n,it:i}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(l=>(0,Vx.alwaysValidSchema)(i,l))&&!i.opts.unevaluated)return;let s=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((l,c)=>{let u=t.subschema({keyword:n,schemaProp:c,compositeRule:!0},a);e.assign(s,(0,xt._)`${s} || ${a}`),t.mergeValidEvaluated(u,a)||e.if((0,xt.not)(s))})),t.result(s,()=>t.reset(),()=>t.error(!0))}dt.validateUnion=l5});var Cz=C(Oi=>{"use strict";Object.defineProperty(Oi,"__esModule",{value:!0});Oi.validateKeywordUsage=Oi.validSchemaType=Oi.funcKeywordCode=Oi.macroKeywordCode=void 0;var Fr=Ue(),Ca=ko(),c5=Dn(),u5=Ef();function d5(t,e){let{gen:r,keyword:n,schema:i,parentSchema:o,it:s}=t,a=e.macro.call(s.self,i,o,s),l=zz(r,n,a);s.opts.validateSchema!==!1&&s.self.validateSchema(a,!0);let c=r.name("valid");t.subschema({schema:a,schemaPath:Fr.nil,errSchemaPath:`${s.errSchemaPath}/${n}`,topSchemaRef:l,compositeRule:!0},c),t.pass(c,()=>t.error(!0))}Oi.macroKeywordCode=d5;function f5(t,e){var r;let{gen:n,keyword:i,schema:o,parentSchema:s,$data:a,it:l}=t;m5(l,e);let c=!a&&e.compile?e.compile.call(l.self,o,s,l):e.validate,u=zz(n,i,c),d=n.let("valid");t.block$data(d,p),t.ok((r=e.valid)!==null&&r!==void 0?r:d);function p(){if(e.errors===!1)h(),e.modifying&&Az(t),y(()=>t.error());else{let g=e.async?f():m();e.modifying&&Az(t),y(()=>p5(t,g))}}function f(){let g=n.let("ruleErrs",null);return n.try(()=>h((0,Fr._)`await `),_=>n.assign(d,!1).if((0,Fr._)`${_} instanceof ${l.ValidationError}`,()=>n.assign(g,(0,Fr._)`${_}.errors`),()=>n.throw(_))),g}function m(){let g=(0,Fr._)`${u}.errors`;return n.assign(g,null),h(Fr.nil),g}function h(g=e.async?(0,Fr._)`await `:Fr.nil){let _=l.opts.passContext?Ca.default.this:Ca.default.self,b=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,Fr._)`${g}${(0,c5.callValidateCode)(t,u,_,b)}`,e.modifying)}function y(g){var _;n.if((0,Fr.not)((_=e.valid)!==null&&_!==void 0?_:d),g)}}Oi.funcKeywordCode=f5;function Az(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,Fr._)`${n.parentData}[${n.parentDataProperty}]`))}function p5(t,e){let{gen:r}=t;r.if((0,Fr._)`Array.isArray(${e})`,()=>{r.assign(Ca.default.vErrors,(0,Fr._)`${Ca.default.vErrors} === null ? ${e} : ${Ca.default.vErrors}.concat(${e})`).assign(Ca.default.errors,(0,Fr._)`${Ca.default.vErrors}.length`),(0,u5.extendErrors)(t)},()=>t.error())}function m5({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function zz(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,Fr.stringify)(r)})}function h5(t,e,r=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(t):n==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==n||r&&typeof t>"u")}Oi.validSchemaType=h5;function g5({schema:t,opts:e,self:r,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(t,a)))throw new Error(`parent schema must have dependencies of ${o}: ${s.join(",")}`);if(i.validateSchema&&!i.validateSchema(t[o])){let l=`keyword "${o}" value is invalid at path "${n}": `+r.errorsText(i.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(l);else throw new Error(l)}}Oi.validateKeywordUsage=g5});var Oz=C(_s=>{"use strict";Object.defineProperty(_s,"__esModule",{value:!0});_s.extendSubschemaMode=_s.extendSubschemaData=_s.getSubschema=void 0;var Ri=Ue(),Nz=Ye();function y5(t,{keyword:e,schemaProp:r,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=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,Ri._)`${t.schemaPath}${(0,Ri.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,Ri._)`${t.schemaPath}${(0,Ri.getProperty)(e)}${(0,Ri.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Nz.escapeFragment)(r)}`}}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')}_s.getSubschema=y5;function v5(t,e,{dataProp:r,dataPropType:n,data:i,dataTypes:o,propertyName:s}){if(i!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:c,dataPathArr:u,opts:d}=e,p=a.let("data",(0,Ri._)`${e.data}${(0,Ri.getProperty)(r)}`,!0);l(p),t.errorPath=(0,Ri.str)`${c}${(0,Nz.getErrorPath)(r,n,d.jsPropertySyntax)}`,t.parentDataProperty=(0,Ri._)`${r}`,t.dataPathArr=[...u,t.parentDataProperty]}if(i!==void 0){let c=i instanceof Ri.Name?i:a.let("data",i,!0);l(c),s!==void 0&&(t.propertyName=s)}o&&(t.dataTypes=o);function l(c){t.data=c,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,c]}}_s.extendSubschemaData=v5;function _5(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:i,allErrors:o}){n!==void 0&&(t.compositeRule=n),i!==void 0&&(t.createErrors=i),o!==void 0&&(t.allErrors=o),t.jtdDiscriminator=e,t.jtdMetadata=r}_s.extendSubschemaMode=_5});var Tf=C((m_e,Rz)=>{"use strict";Rz.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,i,o;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(i=n;i--!==0;)if(!t(e[i],r[i]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(o=Object.keys(e),n=o.length,n!==Object.keys(r).length)return!1;for(i=n;i--!==0;)if(!Object.prototype.hasOwnProperty.call(r,o[i]))return!1;for(i=n;i--!==0;){var s=o[i];if(!t(e[s],r[s]))return!1}return!0}return e!==e&&r!==r}});var Bx=C((h_e,Mz)=>{"use strict";var bs=Mz.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},i=r.post||function(){};Dg(e,n,i,t,"",t)};bs.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};bs.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};bs.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};bs.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 Dg(t,e,r,n,i,o,s,a,l,c){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,i,o,s,a,l,c);for(var u in n){var d=n[u];if(Array.isArray(d)){if(u in bs.arrayKeywords)for(var p=0;p<d.length;p++)Dg(t,e,r,d[p],i+"/"+u+"/"+p,o,i,u,n,p)}else if(u in bs.propsKeywords){if(d&&typeof d=="object")for(var f in d)Dg(t,e,r,d[f],i+"/"+u+"/"+b5(f),o,i,u,n,f)}else(u in bs.keywords||t.allKeys&&!(u in bs.skipKeywords))&&Dg(t,e,r,d,i+"/"+u,o,i,u,n)}r(n,i,o,s,a,l,c)}}function b5(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Af=C(rn=>{"use strict";Object.defineProperty(rn,"__esModule",{value:!0});rn.getSchemaRefs=rn.resolveUrl=rn.normalizeId=rn._getFullPath=rn.getFullPath=rn.inlineRef=void 0;var w5=Ye(),x5=Tf(),$5=Bx(),k5=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function S5(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Gx(t):e?jz(t)<=e:!1}rn.inlineRef=S5;var I5=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Gx(t){for(let e in t){if(I5.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(Gx)||typeof r=="object"&&Gx(r))return!0}return!1}function jz(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!k5.has(r)&&(typeof t[r]=="object"&&(0,w5.eachItem)(t[r],n=>e+=jz(n)),e===1/0))return 1/0}return e}function Dz(t,e="",r){r!==!1&&(e=iu(e));let n=t.parse(e);return Lz(t,n)}rn.getFullPath=Dz;function Lz(t,e){return t.serialize(e).split("#")[0]+"#"}rn._getFullPath=Lz;var E5=/#\/?$/;function iu(t){return t?t.replace(E5,""):""}rn.normalizeId=iu;function P5(t,e,r){return r=iu(r),t.resolve(e,r)}rn.resolveUrl=P5;var T5=/^[a-z_][-a-z0-9._]*$/i;function A5(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,i=iu(t[r]||e),o={"":i},s=Dz(n,i,!1),a={},l=new Set;return $5(t,{allKeys:!0},(d,p,f,m)=>{if(m===void 0)return;let h=s+p,y=o[m];typeof d[r]=="string"&&(y=g.call(this,d[r])),_.call(this,d.$anchor),_.call(this,d.$dynamicAnchor),o[p]=y;function g(b){let E=this.opts.uriResolver.resolve;if(b=iu(y?E(y,b):b),l.has(b))throw u(b);l.add(b);let I=this.refs[b];return typeof I=="string"&&(I=this.refs[I]),typeof I=="object"?c(d,I.schema,b):b!==iu(h)&&(b[0]==="#"?(c(d,a[b],b),a[b]=d):this.refs[b]=h),b}function _(b){if(typeof b=="string"){if(!T5.test(b))throw new Error(`invalid anchor "${b}"`);g.call(this,`#${b}`)}}}),a;function c(d,p,f){if(p!==void 0&&!x5(d,p))throw u(f)}function u(d){return new Error(`reference "${d}" resolves to more than one schema`)}}rn.getSchemaRefs=A5});var Nf=C(ws=>{"use strict";Object.defineProperty(ws,"__esModule",{value:!0});ws.getData=ws.KeywordCxt=ws.validateFunctionCode=void 0;var qz=bz(),Uz=Pf(),Xx=Lx(),Lg=Pf(),z5=Ez(),Cf=Cz(),Hx=Oz(),le=Ue(),xe=ko(),C5=Af(),So=Ye(),zf=Ef();function N5(t){if(Gz(t)&&(Hz(t),Bz(t))){M5(t);return}Wz(t,()=>(0,qz.topBoolOrEmptySchema)(t))}ws.validateFunctionCode=N5;function Wz({gen:t,validateName:e,schema:r,schemaEnv:n,opts:i},o){i.code.es5?t.func(e,(0,le._)`${xe.default.data}, ${xe.default.valCxt}`,n.$async,()=>{t.code((0,le._)`"use strict"; ${Zz(r,i)}`),R5(t,i),t.code(o)}):t.func(e,(0,le._)`${xe.default.data}, ${O5(i)}`,n.$async,()=>t.code(Zz(r,i)).code(o))}function O5(t){return(0,le._)`{${xe.default.instancePath}="", ${xe.default.parentData}, ${xe.default.parentDataProperty}, ${xe.default.rootData}=${xe.default.data}${t.dynamicRef?(0,le._)`, ${xe.default.dynamicAnchors}={}`:le.nil}}={}`}function R5(t,e){t.if(xe.default.valCxt,()=>{t.var(xe.default.instancePath,(0,le._)`${xe.default.valCxt}.${xe.default.instancePath}`),t.var(xe.default.parentData,(0,le._)`${xe.default.valCxt}.${xe.default.parentData}`),t.var(xe.default.parentDataProperty,(0,le._)`${xe.default.valCxt}.${xe.default.parentDataProperty}`),t.var(xe.default.rootData,(0,le._)`${xe.default.valCxt}.${xe.default.rootData}`),e.dynamicRef&&t.var(xe.default.dynamicAnchors,(0,le._)`${xe.default.valCxt}.${xe.default.dynamicAnchors}`)},()=>{t.var(xe.default.instancePath,(0,le._)`""`),t.var(xe.default.parentData,(0,le._)`undefined`),t.var(xe.default.parentDataProperty,(0,le._)`undefined`),t.var(xe.default.rootData,xe.default.data),e.dynamicRef&&t.var(xe.default.dynamicAnchors,(0,le._)`{}`)})}function M5(t){let{schema:e,opts:r,gen:n}=t;Wz(t,()=>{r.$comment&&e.$comment&&Kz(t),Z5(t),n.let(xe.default.vErrors,null),n.let(xe.default.errors,0),r.unevaluated&&j5(t),Xz(t),q5(t)})}function j5(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,le._)`${r}.evaluated`),e.if((0,le._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,le._)`${t.evaluated}.props`,(0,le._)`undefined`)),e.if((0,le._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,le._)`${t.evaluated}.items`,(0,le._)`undefined`))}function Zz(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,le._)`/*# sourceURL=${r} */`:le.nil}function D5(t,e){if(Gz(t)&&(Hz(t),Bz(t))){L5(t,e);return}(0,qz.boolOrEmptySchema)(t,e)}function Bz({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let r in t)if(e.RULES.all[r])return!0;return!1}function Gz(t){return typeof t.schema!="boolean"}function L5(t,e){let{schema:r,gen:n,opts:i}=t;i.$comment&&r.$comment&&Kz(t),F5(t),V5(t);let o=n.const("_errs",xe.default.errors);Xz(t,o),n.var(e,(0,le._)`${o} === ${xe.default.errors}`)}function Hz(t){(0,So.checkUnknownRules)(t),U5(t)}function Xz(t,e){if(t.opts.jtd)return Fz(t,[],!1,e);let r=(0,Uz.getSchemaTypes)(t.schema),n=(0,Uz.coerceAndCheckDataType)(t,r);Fz(t,r,!n,e)}function U5(t){let{schema:e,errSchemaPath:r,opts:n,self:i}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,So.schemaHasRulesButRef)(e,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function Z5(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,So.checkStrictMode)(t,"default is ignored in the schema root")}function F5(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,C5.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function V5(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function Kz({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:i}){let o=r.$comment;if(i.$comment===!0)t.code((0,le._)`${xe.default.self}.logger.log(${o})`);else if(typeof i.$comment=="function"){let s=(0,le.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,le._)`${xe.default.self}.opts.$comment(${o}, ${s}, ${a}.schema)`)}}function q5(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:i,opts:o}=t;r.$async?e.if((0,le._)`${xe.default.errors} === 0`,()=>e.return(xe.default.data),()=>e.throw((0,le._)`new ${i}(${xe.default.vErrors})`)):(e.assign((0,le._)`${n}.errors`,xe.default.vErrors),o.unevaluated&&W5(t),e.return((0,le._)`${xe.default.errors} === 0`))}function W5({gen:t,evaluated:e,props:r,items:n}){r instanceof le.Name&&t.assign((0,le._)`${e}.props`,r),n instanceof le.Name&&t.assign((0,le._)`${e}.items`,n)}function Fz(t,e,r,n){let{gen:i,schema:o,data:s,allErrors:a,opts:l,self:c}=t,{RULES:u}=c;if(o.$ref&&(l.ignoreKeywordsWithRef||!(0,So.schemaHasRulesButRef)(o,u))){i.block(()=>Yz(t,"$ref",u.all.$ref.definition));return}l.jtd||B5(t,e),i.block(()=>{for(let p of u.rules)d(p);d(u.post)});function d(p){(0,Xx.shouldUseGroup)(o,p)&&(p.type?(i.if((0,Lg.checkDataType)(p.type,s,l.strictNumbers)),Vz(t,p),e.length===1&&e[0]===p.type&&r&&(i.else(),(0,Lg.reportTypeError)(t)),i.endIf()):Vz(t,p),a||i.if((0,le._)`${xe.default.errors} === ${n||0}`))}}function Vz(t,e){let{gen:r,schema:n,opts:{useDefaults:i}}=t;i&&(0,z5.assignDefaults)(t,e.type),r.block(()=>{for(let o of e.rules)(0,Xx.shouldUseRule)(n,o)&&Yz(t,o.keyword,o.definition,e.type)})}function B5(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(G5(t,e),t.opts.allowUnionTypes||H5(t,e),X5(t,t.dataTypes))}function G5(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{Jz(t.dataTypes,r)||Kx(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),J5(t,e)}}function H5(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Kx(t,"use allowUnionTypes to allow union type keyword")}function X5(t,e){let r=t.self.RULES.all;for(let n in r){let i=r[n];if(typeof i=="object"&&(0,Xx.shouldUseRule)(t.schema,i)){let{type:o}=i.definition;o.length&&!o.some(s=>K5(e,s))&&Kx(t,`missing type "${o.join(",")}" for keyword "${n}"`)}}}function K5(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function Jz(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function J5(t,e){let r=[];for(let n of t.dataTypes)Jz(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function Kx(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,So.checkStrictMode)(t,e,t.opts.strictTypes)}var Ug=class{constructor(e,r,n){if((0,Cf.validateKeywordUsage)(e,r,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,So.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",Qz(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Cf.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",xe.default.errors))}result(e,r,n){this.failResult((0,le.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,le.not)(e),void 0,r)}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:r}=this;this.fail((0,le._)`${r} !== undefined && (${(0,le.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?zf.reportExtraError:zf.reportError)(this,this.def.error,r)}$dataError(){(0,zf.reportError)(this,this.def.$dataError||zf.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,zf.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=le.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=le.nil,r=le.nil){if(!this.$data)return;let{gen:n,schemaCode:i,schemaType:o,def:s}=this;n.if((0,le.or)((0,le._)`${i} === undefined`,r)),e!==le.nil&&n.assign(e,!0),(o.length||s.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==le.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:i,it:o}=this;return(0,le.or)(s(),a());function s(){if(n.length){if(!(r instanceof le.Name))throw new Error("ajv implementation error");let l=Array.isArray(n)?n:[n];return(0,le._)`${(0,Lg.checkDataTypes)(l,r,o.opts.strictNumbers,Lg.DataType.Wrong)}`}return le.nil}function a(){if(i.validateSchema){let l=e.scopeValue("validate$data",{ref:i.validateSchema});return(0,le._)`!${l}(${r})`}return le.nil}}subschema(e,r){let n=(0,Hx.getSubschema)(this.it,e);(0,Hx.extendSubschemaData)(n,this.it,e),(0,Hx.extendSubschemaMode)(n,e);let i={...this.it,...n,items:void 0,props:void 0};return D5(i,r),i}mergeEvaluated(e,r){let{it:n,gen:i}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=So.mergeEvaluated.props(i,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=So.mergeEvaluated.items(i,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:i}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return i.if(r,()=>this.mergeEvaluated(e,le.Name)),!0}};ws.KeywordCxt=Ug;function Yz(t,e,r,n){let i=new Ug(t,r,e);"code"in r?r.code(i,n):i.$data&&r.validate?(0,Cf.funcKeywordCode)(i,r):"macro"in r?(0,Cf.macroKeywordCode)(i,r):(r.compile||r.validate)&&(0,Cf.funcKeywordCode)(i,r)}var Y5=/^\/(?:[^~]|~0|~1)*$/,Q5=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Qz(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let i,o;if(t==="")return xe.default.rootData;if(t[0]==="/"){if(!Y5.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);i=t,o=xe.default.rootData}else{let c=Q5.exec(t);if(!c)throw new Error(`Invalid JSON-pointer: ${t}`);let u=+c[1];if(i=c[2],i==="#"){if(u>=e)throw new Error(l("property/index",u));return n[e-u]}if(u>e)throw new Error(l("data",u));if(o=r[e-u],!i)return o}let s=o,a=i.split("/");for(let c of a)c&&(o=(0,le._)`${o}${(0,le.getProperty)((0,So.unescapeJsonPointer)(c))}`,s=(0,le._)`${s} && ${o}`);return s;function l(c,u){return`Cannot access ${c} ${u} levels up, current level is ${e}`}}ws.getData=Qz});var Zg=C(Yx=>{"use strict";Object.defineProperty(Yx,"__esModule",{value:!0});var Jx=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Yx.default=Jx});var Of=C(t$=>{"use strict";Object.defineProperty(t$,"__esModule",{value:!0});var Qx=Af(),e$=class extends Error{constructor(e,r,n,i){super(i||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Qx.resolveUrl)(e,r,n),this.missingSchema=(0,Qx.normalizeId)((0,Qx.getFullPath)(e,this.missingRef))}};t$.default=e$});var Vg=C(Ln=>{"use strict";Object.defineProperty(Ln,"__esModule",{value:!0});Ln.resolveSchema=Ln.getCompilingSchema=Ln.resolveRef=Ln.compileSchema=Ln.SchemaEnv=void 0;var li=Ue(),eV=Zg(),Na=ko(),ci=Af(),eC=Ye(),tV=Nf(),ou=class{constructor(e){var r;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=(r=e.baseId)!==null&&r!==void 0?r:(0,ci.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};Ln.SchemaEnv=ou;function n$(t){let e=tC.call(this,t);if(e)return e;let r=(0,ci.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:i}=this.opts.code,{ownProperties:o}=this.opts,s=new li.CodeGen(this.scope,{es5:n,lines:i,ownProperties:o}),a;t.$async&&(a=s.scopeValue("Error",{ref:eV.default,code:(0,li._)`require("ajv/dist/runtime/validation_error").default`}));let l=s.scopeName("validate");t.validateName=l;let c={gen:s,allErrors:this.opts.allErrors,data:Na.default.data,parentData:Na.default.parentData,parentDataProperty:Na.default.parentDataProperty,dataNames:[Na.default.data],dataPathArr:[li.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,li.stringify)(t.schema)}:{ref:t.schema}),validateName:l,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:li.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,li._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(t),(0,tV.validateFunctionCode)(c),s.optimize(this.opts.code.optimize);let d=s.toString();u=`${s.scopeRefs(Na.default.scope)}return ${d}`,this.opts.code.process&&(u=this.opts.code.process(u,t));let f=new Function(`${Na.default.self}`,`${Na.default.scope}`,u)(this,this.scope.get());if(this.scope.value(l,{ref:f}),f.errors=null,f.schema=t.schema,f.schemaEnv=t,t.$async&&(f.$async=!0),this.opts.code.source===!0&&(f.source={validateName:l,validateCode:d,scopeValues:s._values}),this.opts.unevaluated){let{props:m,items:h}=c;f.evaluated={props:m instanceof li.Name?void 0:m,items:h instanceof li.Name?void 0:h,dynamicProps:m instanceof li.Name,dynamicItems:h instanceof li.Name},f.source&&(f.source.evaluated=(0,li.stringify)(f.evaluated))}return t.validate=f,t}catch(d){throw delete t.validate,delete t.validateName,u&&this.logger.error("Error compiling schema, function code:",u),d}finally{this._compilations.delete(t)}}Ln.compileSchema=n$;function rV(t,e,r){var n;r=(0,ci.resolveUrl)(this.opts.uriResolver,e,r);let i=t.refs[r];if(i)return i;let o=oV.call(this,t,r);if(o===void 0){let s=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;s&&(o=new ou({schema:s,schemaId:a,root:t,baseId:e}))}if(o!==void 0)return t.refs[r]=nV.call(this,o)}Ln.resolveRef=rV;function nV(t){return(0,ci.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:n$.call(this,t)}function tC(t){for(let e of this._compilations)if(iV(e,t))return e}Ln.getCompilingSchema=tC;function iV(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function oV(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||Fg.call(this,t,e)}function Fg(t,e){let r=this.opts.uriResolver.parse(e),n=(0,ci._getFullPath)(this.opts.uriResolver,r),i=(0,ci.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===i)return r$.call(this,r,t);let o=(0,ci.normalizeId)(n),s=this.refs[o]||this.schemas[o];if(typeof s=="string"){let a=Fg.call(this,t,s);return typeof a?.schema!="object"?void 0:r$.call(this,r,a)}if(typeof s?.schema=="object"){if(s.validate||n$.call(this,s),o===(0,ci.normalizeId)(e)){let{schema:a}=s,{schemaId:l}=this.opts,c=a[l];return c&&(i=(0,ci.resolveUrl)(this.opts.uriResolver,i,c)),new ou({schema:a,schemaId:l,root:t,baseId:i})}return r$.call(this,r,s)}}Ln.resolveSchema=Fg;var sV=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function r$(t,{baseId:e,schema:r,root:n}){var i;if(((i=t.fragment)===null||i===void 0?void 0:i[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let l=r[(0,eC.unescapeFragment)(a)];if(l===void 0)return;r=l;let c=typeof r=="object"&&r[this.opts.schemaId];!sV.has(a)&&c&&(e=(0,ci.resolveUrl)(this.opts.uriResolver,e,c))}let o;if(typeof r!="boolean"&&r.$ref&&!(0,eC.schemaHasRulesButRef)(r,this.RULES)){let a=(0,ci.resolveUrl)(this.opts.uriResolver,e,r.$ref);o=Fg.call(this,n,a)}let{schemaId:s}=this.opts;if(o=o||new ou({schema:r,schemaId:s,root:n,baseId:e}),o.schema!==o.root.schema)return o}});var rC=C((w_e,aV)=>{aV.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 o$=C((x_e,sC)=>{"use strict";var lV=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),iC=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 i$(t){let e="",r=0,n=0;for(n=0;n<t.length;n++)if(r=t[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n];break}for(n+=1;n<t.length;n++){if(r=t[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n]}return e}var cV=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function nC(t){return t.length=0,!0}function uV(t,e,r){if(t.length){let n=i$(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function dV(t){let e=0,r={error:!1,address:"",zone:""},n=[],i=[],o=!1,s=!1,a=uV;for(let l=0;l<t.length;l++){let c=t[l];if(!(c==="["||c==="]"))if(c===":"){if(o===!0&&(s=!0),!a(i,n,r))break;if(++e>7){r.error=!0;break}l>0&&t[l-1]===":"&&(o=!0),n.push(":");continue}else if(c==="%"){if(!a(i,n,r))break;a=nC}else{i.push(c);continue}}return i.length&&(a===nC?r.zone=i.join(""):s?n.push(i.join("")):n.push(i$(i))),r.address=n.join(""),r}function oC(t){if(fV(t,":")<2)return{host:t,isIPV6:!1};let e=dV(t);if(e.error)return{host:t,isIPV6:!1};{let r=e.address,n=e.address;return e.zone&&(r+="%"+e.zone,n+="%25"+e.zone),{host:r,isIPV6:!0,escapedHost:n}}}function fV(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function pV(t){let e=t,r=[],n=-1,i=0;for(;i=e.length;){if(i===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.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]==="/")){r.push("/");break}}else if(i===3&&e==="/.."){r.length!==0&&r.pop(),r.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),r.length!==0&&r.pop();continue}}if((n=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,n)),e=e.slice(n)}return r.join("")}function mV(t,e){let r=e!==!0?escape:unescape;return t.scheme!==void 0&&(t.scheme=r(t.scheme)),t.userinfo!==void 0&&(t.userinfo=r(t.userinfo)),t.host!==void 0&&(t.host=r(t.host)),t.path!==void 0&&(t.path=r(t.path)),t.query!==void 0&&(t.query=r(t.query)),t.fragment!==void 0&&(t.fragment=r(t.fragment)),t}function hV(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!iC(r)){let n=oC(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=t.host}e.push(r)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}sC.exports={nonSimpleDomain:cV,recomposeAuthority:hV,normalizeComponentEncoding:mV,removeDotSegments:pV,isIPv4:iC,isUUID:lV,normalizeIPv6:oC,stringArrayToHexStripped:i$}});var dC=C(($_e,uC)=>{"use strict";var{isUUID:gV}=o$(),yV=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,vV=["http","https","ws","wss","urn","urn:uuid"];function _V(t){return vV.indexOf(t)!==-1}function s$(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function aC(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function lC(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function bV(t){return t.secure=s$(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function wV(t){if((t.port===(s$(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,r]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=r,t.resourceName=void 0}return t.fragment=void 0,t}function xV(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(yV);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let i=`${n}:${e.nid||t.nid}`,o=a$(i);t.path=void 0,o&&(t=o.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function $V(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",n=t.nid.toLowerCase(),i=`${r}:${e.nid||n}`,o=a$(i);o&&(t=o.serialize(t,e));let s=t,a=t.nss;return s.path=`${n||e.nid}:${a}`,e.skipEscape=!0,s}function kV(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!gV(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function SV(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var cC={scheme:"http",domainHost:!0,parse:aC,serialize:lC},IV={scheme:"https",domainHost:cC.domainHost,parse:aC,serialize:lC},qg={scheme:"ws",domainHost:!0,parse:bV,serialize:wV},EV={scheme:"wss",domainHost:qg.domainHost,parse:qg.parse,serialize:qg.serialize},PV={scheme:"urn",parse:xV,serialize:$V,skipNormalize:!0},TV={scheme:"urn:uuid",parse:kV,serialize:SV,skipNormalize:!0},Wg={http:cC,https:IV,ws:qg,wss:EV,urn:PV,"urn:uuid":TV};Object.setPrototypeOf(Wg,null);function a$(t){return t&&(Wg[t]||Wg[t.toLowerCase()])||void 0}uC.exports={wsIsSecure:s$,SCHEMES:Wg,isValidSchemeName:_V,getSchemeHandler:a$}});var mC=C((k_e,Gg)=>{"use strict";var{normalizeIPv6:AV,removeDotSegments:Rf,recomposeAuthority:zV,normalizeComponentEncoding:Bg,isIPv4:CV,nonSimpleDomain:NV}=o$(),{SCHEMES:OV,getSchemeHandler:fC}=dC();function RV(t,e){return typeof t=="string"?t=Mi(Io(t,e),e):typeof t=="object"&&(t=Io(Mi(t,e),e)),t}function MV(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},i=pC(Io(t,n),Io(e,n),n,!0);return n.skipEscape=!0,Mi(i,n)}function pC(t,e,r,n){let i={};return n||(t=Io(Mi(t,r),r),e=Io(Mi(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(i.scheme=e.scheme,i.userinfo=e.userinfo,i.host=e.host,i.port=e.port,i.path=Rf(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=Rf(e.path||""),i.query=e.query):(e.path?(e.path[0]==="/"?i.path=Rf(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?i.path="/"+e.path:t.path?i.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:i.path=e.path,i.path=Rf(i.path)),i.query=e.query):(i.path=t.path,e.query!==void 0?i.query=e.query:i.query=t.query),i.userinfo=t.userinfo,i.host=t.host,i.port=t.port),i.scheme=t.scheme),i.fragment=e.fragment,i}function jV(t,e,r){return typeof t=="string"?(t=unescape(t),t=Mi(Bg(Io(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=Mi(Bg(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=Mi(Bg(Io(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=Mi(Bg(e,!0),{...r,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function Mi(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),i=[],o=fC(n.scheme||r.scheme);o&&o.serialize&&o.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=unescape(r.path):(r.path=escape(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&i.push(r.scheme,":");let s=zV(r);if(s!==void 0&&(n.reference!=="suffix"&&i.push("//"),i.push(s),r.path&&r.path[0]!=="/"&&i.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!o||!o.absolutePath)&&(a=Rf(a)),s===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),i.push(a)}return r.query!==void 0&&i.push("?",r.query),r.fragment!==void 0&&i.push("#",r.fragment),i.join("")}var DV=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function Io(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},i=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let o=t.match(DV);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(CV(n.host)===!1){let l=AV(n.host);n.host=l.host.toLowerCase(),i=l.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",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let s=fC(r.scheme||n.scheme);if(!r.unicodeSupport&&(!s||!s.unicodeSupport)&&n.host&&(r.domainHost||s&&s.domainHost)&&i===!1&&NV(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)&&(t.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,r)}else n.error=n.error||"URI can not be parsed.";return n}var l$={SCHEMES:OV,normalize:RV,resolve:MV,resolveComponent:pC,equal:jV,serialize:Mi,parse:Io};Gg.exports=l$;Gg.exports.default=l$;Gg.exports.fastUri=l$});var gC=C(c$=>{"use strict";Object.defineProperty(c$,"__esModule",{value:!0});var hC=mC();hC.code='require("ajv/dist/runtime/uri").default';c$.default=hC});var kC=C(yr=>{"use strict";Object.defineProperty(yr,"__esModule",{value:!0});yr.CodeGen=yr.Name=yr.nil=yr.stringify=yr.str=yr._=yr.KeywordCxt=void 0;var LV=Nf();Object.defineProperty(yr,"KeywordCxt",{enumerable:!0,get:function(){return LV.KeywordCxt}});var su=Ue();Object.defineProperty(yr,"_",{enumerable:!0,get:function(){return su._}});Object.defineProperty(yr,"str",{enumerable:!0,get:function(){return su.str}});Object.defineProperty(yr,"stringify",{enumerable:!0,get:function(){return su.stringify}});Object.defineProperty(yr,"nil",{enumerable:!0,get:function(){return su.nil}});Object.defineProperty(yr,"Name",{enumerable:!0,get:function(){return su.Name}});Object.defineProperty(yr,"CodeGen",{enumerable:!0,get:function(){return su.CodeGen}});var UV=Zg(),wC=Of(),ZV=Dx(),Mf=Vg(),FV=Ue(),jf=Af(),Hg=Pf(),d$=Ye(),yC=rC(),VV=gC(),xC=(t,e)=>new RegExp(t,e);xC.code="new RegExp";var qV=["removeAdditional","useDefaults","coerceTypes"],WV=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),BV={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},GV={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},vC=200;function HV(t){var e,r,n,i,o,s,a,l,c,u,d,p,f,m,h,y,g,_,b,E,I,P,M,V,R;let L=t.strict,G=(e=t.code)===null||e===void 0?void 0:e.optimize,H=G===!0||G===void 0?1:G||0,W=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:xC,Y=(i=t.uriResolver)!==null&&i!==void 0?i:VV.default;return{strictSchema:(s=(o=t.strictSchema)!==null&&o!==void 0?o:L)!==null&&s!==void 0?s:!0,strictNumbers:(l=(a=t.strictNumbers)!==null&&a!==void 0?a:L)!==null&&l!==void 0?l:!0,strictTypes:(u=(c=t.strictTypes)!==null&&c!==void 0?c:L)!==null&&u!==void 0?u:"log",strictTuples:(p=(d=t.strictTuples)!==null&&d!==void 0?d:L)!==null&&p!==void 0?p:"log",strictRequired:(m=(f=t.strictRequired)!==null&&f!==void 0?f:L)!==null&&m!==void 0?m:!1,code:t.code?{...t.code,optimize:H,regExp:W}:{optimize:H,regExp:W},loopRequired:(h=t.loopRequired)!==null&&h!==void 0?h:vC,loopEnum:(y=t.loopEnum)!==null&&y!==void 0?y:vC,meta:(g=t.meta)!==null&&g!==void 0?g:!0,messages:(_=t.messages)!==null&&_!==void 0?_:!0,inlineRefs:(b=t.inlineRefs)!==null&&b!==void 0?b:!0,schemaId:(E=t.schemaId)!==null&&E!==void 0?E:"$id",addUsedSchema:(I=t.addUsedSchema)!==null&&I!==void 0?I:!0,validateSchema:(P=t.validateSchema)!==null&&P!==void 0?P:!0,validateFormats:(M=t.validateFormats)!==null&&M!==void 0?M:!0,unicodeRegExp:(V=t.unicodeRegExp)!==null&&V!==void 0?V:!0,int32range:(R=t.int32range)!==null&&R!==void 0?R:!0,uriResolver:Y}}var Df=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...HV(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new FV.ValueScope({scope:{},prefixes:WV,es5:r,lines:n}),this.logger=eq(e.logger);let i=e.validateFormats;e.validateFormats=!1,this.RULES=(0,ZV.getRules)(),_C.call(this,BV,e,"NOT SUPPORTED"),_C.call(this,GV,e,"DEPRECATED","warn"),this._metaOpts=YV.call(this),e.formats&&KV.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&JV.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),XV.call(this),e.validateFormats=i}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,i=yC;n==="id"&&(i={...yC},i.id=i.$id,delete i.$id),r&&e&&this.addMetaSchema(i,i[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){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(r);return"$async"in n||(this.errors=n.errors),i}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){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,r);async function i(u,d){await o.call(this,u.$schema);let p=this._addSchema(u,d);return p.validate||s.call(this,p)}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(d){if(!(d instanceof wC.default))throw d;return a.call(this,d),await l.call(this,d.missingSchema),s.call(this,u)}}function a({missingSchema:u,missingRef:d}){if(this.refs[u])throw new Error(`AnySchema ${u} is loaded but ${d} cannot be resolved`)}async function l(u){let d=await c.call(this,u);this.refs[u]||await o.call(this,d.$schema),this.refs[u]||this.addSchema(d,u,r)}async function c(u){let d=this._loading[u];if(d)return d;try{return await(this._loading[u]=n(u))}finally{delete this._loading[u]}}}addSchema(e,r,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 r=(0,jf.normalizeId)(r||o),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,i,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){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&&r){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 r;for(;typeof(r=bC.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,i=new Mf.SchemaEnv({schema:{},schemaId:n});if(r=Mf.resolveSchema.call(this,i,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}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 r=bC.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let n=e[this.opts.schemaId];return n&&(n=(0,jf.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let n;if(typeof e=="string")n=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof e=="object"&&r===void 0){if(r=e,n=r.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(rq.call(this,n,r),!r)return(0,d$.eachItem)(n,o=>u$.call(this,o)),this;iq.call(this,r);let i={...r,type:(0,Hg.getJSONTypes)(r.type),schemaType:(0,Hg.getJSONTypes)(r.schemaType)};return(0,d$.eachItem)(n,i.type.length===0?o=>u$.call(this,o,i):o=>i.type.forEach(s=>u$.call(this,o,i,s))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let i=n.rules.findIndex(o=>o.keyword===e);i>=0&&n.rules.splice(i,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(i=>`${n}${i.instancePath} ${i.message}`).reduce((i,o)=>i+r+o)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let i of r){let o=i.split("/").slice(1),s=e;for(let a of o)s=s[a];for(let a in n){let l=n[a];if(typeof l!="object")continue;let{$data:c}=l.definition,u=s[a];c&&u&&(s[a]=$C(u))}}return e}_removeAllSchemas(e,r){for(let n in e){let i=e[n];(!r||r.test(n))&&(typeof i=="string"?delete e[n]:i&&!i.meta&&(this._cache.delete(i.schema),delete e[n]))}}_addSchema(e,r,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 l=this._cache.get(e);if(l!==void 0)return l;n=(0,jf.normalizeId)(s||n);let c=jf.getSchemaRefs.call(this,e,n);return l=new Mf.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:c}),this._cache.set(l.schema,l),o&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=l),i&&this.validateSchema(e,!0),l}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):Mf.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let r=this.opts;this.opts=this._metaOpts;try{Mf.compileSchema.call(this,e)}finally{this.opts=r}}};Df.ValidationError=UV.default;Df.MissingRefError=wC.default;yr.default=Df;function _C(t,e,r,n="error"){for(let i in t){let o=i;o in e&&this.logger[n](`${r}: option ${i}. ${t[o]}`)}}function bC(t){return t=(0,jf.normalizeId)(t),this.schemas[t]||this.refs[t]}function XV(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function KV(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function JV(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let r=t[e];r.keyword||(r.keyword=e),this.addKeyword(r)}}function YV(){let t={...this.opts};for(let e of qV)delete t[e];return t}var QV={log(){},warn(){},error(){}};function eq(t){if(t===!1)return QV;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var tq=/^[a-z_$][a-z0-9_$:-]*$/i;function rq(t,e){let{RULES:r}=this;if((0,d$.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!tq.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 u$(t,e,r){var n;let i=e?.post;if(r&&i)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:o}=this,s=i?o.post:o.rules.find(({type:l})=>l===r);if(s||(s={type:r,rules:[]},o.rules.push(s)),o.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,Hg.getJSONTypes)(e.type),schemaType:(0,Hg.getJSONTypes)(e.schemaType)}};e.before?nq.call(this,s,a,e.before):s.rules.push(a),o.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(l=>this.addKeyword(l))}function nq(t,e,r){let n=t.rules.findIndex(i=>i.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function iq(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=$C(e)),t.validateSchema=this.compile(e,!0))}var oq={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function $C(t){return{anyOf:[t,oq]}}});var SC=C(f$=>{"use strict";Object.defineProperty(f$,"__esModule",{value:!0});var sq={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};f$.default=sq});var TC=C(Oa=>{"use strict";Object.defineProperty(Oa,"__esModule",{value:!0});Oa.callRef=Oa.getValidate=void 0;var aq=Of(),IC=Dn(),nn=Ue(),au=ko(),EC=Vg(),Xg=Ye(),lq={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:i,schemaEnv:o,validateName:s,opts:a,self:l}=n,{root:c}=o;if((r==="#"||r==="#/")&&i===c.baseId)return d();let u=EC.resolveRef.call(l,c,i,r);if(u===void 0)throw new aq.default(n.opts.uriResolver,i,r);if(u instanceof EC.SchemaEnv)return p(u);return f(u);function d(){if(o===c)return Kg(t,s,o,o.$async);let m=e.scopeValue("root",{ref:c});return Kg(t,(0,nn._)`${m}.validate`,c,c.$async)}function p(m){let h=PC(t,m);Kg(t,h,m,m.$async)}function f(m){let h=e.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,nn.stringify)(m)}:{ref:m}),y=e.name("valid"),g=t.subschema({schema:m,dataTypes:[],schemaPath:nn.nil,topSchemaRef:h,errSchemaPath:r},y);t.mergeEvaluated(g),t.ok(y)}}};function PC(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,nn._)`${r.scopeValue("wrapper",{ref:e})}.validate`}Oa.getValidate=PC;function Kg(t,e,r,n){let{gen:i,it:o}=t,{allErrors:s,schemaEnv:a,opts:l}=o,c=l.passContext?au.default.this:nn.nil;n?u():d();function u(){if(!a.$async)throw new Error("async schema referenced by sync schema");let m=i.let("valid");i.try(()=>{i.code((0,nn._)`await ${(0,IC.callValidateCode)(t,e,c)}`),f(e),s||i.assign(m,!0)},h=>{i.if((0,nn._)`!(${h} instanceof ${o.ValidationError})`,()=>i.throw(h)),p(h),s||i.assign(m,!1)}),t.ok(m)}function d(){t.result((0,IC.callValidateCode)(t,e,c),()=>f(e),()=>p(e))}function p(m){let h=(0,nn._)`${m}.errors`;i.assign(au.default.vErrors,(0,nn._)`${au.default.vErrors} === null ? ${h} : ${au.default.vErrors}.concat(${h})`),i.assign(au.default.errors,(0,nn._)`${au.default.vErrors}.length`)}function f(m){var h;if(!o.opts.unevaluated)return;let y=(h=r?.validate)===null||h===void 0?void 0:h.evaluated;if(o.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(o.props=Xg.mergeEvaluated.props(i,y.props,o.props));else{let g=i.var("props",(0,nn._)`${m}.evaluated.props`);o.props=Xg.mergeEvaluated.props(i,g,o.props,nn.Name)}if(o.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(o.items=Xg.mergeEvaluated.items(i,y.items,o.items));else{let g=i.var("items",(0,nn._)`${m}.evaluated.items`);o.items=Xg.mergeEvaluated.items(i,g,o.items,nn.Name)}}}Oa.callRef=Kg;Oa.default=lq});var AC=C(p$=>{"use strict";Object.defineProperty(p$,"__esModule",{value:!0});var cq=SC(),uq=TC(),dq=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",cq.default,uq.default];p$.default=dq});var zC=C(m$=>{"use strict";Object.defineProperty(m$,"__esModule",{value:!0});var Jg=Ue(),xs=Jg.operators,Yg={maximum:{okStr:"<=",ok:xs.LTE,fail:xs.GT},minimum:{okStr:">=",ok:xs.GTE,fail:xs.LT},exclusiveMaximum:{okStr:"<",ok:xs.LT,fail:xs.GTE},exclusiveMinimum:{okStr:">",ok:xs.GT,fail:xs.LTE}},fq={message:({keyword:t,schemaCode:e})=>(0,Jg.str)`must be ${Yg[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Jg._)`{comparison: ${Yg[t].okStr}, limit: ${e}}`},pq={keyword:Object.keys(Yg),type:"number",schemaType:"number",$data:!0,error:fq,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,Jg._)`${r} ${Yg[e].fail} ${n} || isNaN(${r})`)}};m$.default=pq});var CC=C(h$=>{"use strict";Object.defineProperty(h$,"__esModule",{value:!0});var Lf=Ue(),mq={message:({schemaCode:t})=>(0,Lf.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Lf._)`{multipleOf: ${t}}`},hq={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:mq,code(t){let{gen:e,data:r,schemaCode:n,it:i}=t,o=i.opts.multipleOfPrecision,s=e.let("res"),a=o?(0,Lf._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${o}`:(0,Lf._)`${s} !== parseInt(${s})`;t.fail$data((0,Lf._)`(${n} === 0 || (${s} = ${r}/${n}, ${a}))`)}};h$.default=hq});var OC=C(g$=>{"use strict";Object.defineProperty(g$,"__esModule",{value:!0});function NC(t){let e=t.length,r=0,n=0,i;for(;n<e;)r++,i=t.charCodeAt(n++),i>=55296&&i<=56319&&n<e&&(i=t.charCodeAt(n),(i&64512)===56320&&n++);return r}g$.default=NC;NC.code='require("ajv/dist/runtime/ucs2length").default'});var RC=C(y$=>{"use strict";Object.defineProperty(y$,"__esModule",{value:!0});var Ra=Ue(),gq=Ye(),yq=OC(),vq={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,Ra.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,Ra._)`{limit: ${t}}`},_q={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:vq,code(t){let{keyword:e,data:r,schemaCode:n,it:i}=t,o=e==="maxLength"?Ra.operators.GT:Ra.operators.LT,s=i.opts.unicode===!1?(0,Ra._)`${r}.length`:(0,Ra._)`${(0,gq.useFunc)(t.gen,yq.default)}(${r})`;t.fail$data((0,Ra._)`${s} ${o} ${n}`)}};y$.default=_q});var MC=C(v$=>{"use strict";Object.defineProperty(v$,"__esModule",{value:!0});var bq=Dn(),Qg=Ue(),wq={message:({schemaCode:t})=>(0,Qg.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Qg._)`{pattern: ${t}}`},xq={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:wq,code(t){let{data:e,$data:r,schema:n,schemaCode:i,it:o}=t,s=o.opts.unicodeRegExp?"u":"",a=r?(0,Qg._)`(new RegExp(${i}, ${s}))`:(0,bq.usePattern)(t,n);t.fail$data((0,Qg._)`!${a}.test(${e})`)}};v$.default=xq});var jC=C(_$=>{"use strict";Object.defineProperty(_$,"__esModule",{value:!0});var Uf=Ue(),$q={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,Uf.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,Uf._)`{limit: ${t}}`},kq={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:$q,code(t){let{keyword:e,data:r,schemaCode:n}=t,i=e==="maxProperties"?Uf.operators.GT:Uf.operators.LT;t.fail$data((0,Uf._)`Object.keys(${r}).length ${i} ${n}`)}};_$.default=kq});var DC=C(b$=>{"use strict";Object.defineProperty(b$,"__esModule",{value:!0});var Zf=Dn(),Ff=Ue(),Sq=Ye(),Iq={message:({params:{missingProperty:t}})=>(0,Ff.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Ff._)`{missingProperty: ${t}}`},Eq={keyword:"required",type:"object",schemaType:"array",$data:!0,error:Iq,code(t){let{gen:e,schema:r,schemaCode:n,data:i,$data:o,it:s}=t,{opts:a}=s;if(!o&&r.length===0)return;let l=r.length>=a.loopRequired;if(s.allErrors?c():u(),a.strictRequired){let f=t.parentSchema.properties,{definedProperties:m}=t.it;for(let h of r)if(f?.[h]===void 0&&!m.has(h)){let y=s.schemaEnv.baseId+s.errSchemaPath,g=`required property "${h}" is not defined at "${y}" (strictRequired)`;(0,Sq.checkStrictMode)(s,g,s.opts.strictRequired)}}function c(){if(l||o)t.block$data(Ff.nil,d);else for(let f of r)(0,Zf.checkReportMissingProp)(t,f)}function u(){let f=e.let("missing");if(l||o){let m=e.let("valid",!0);t.block$data(m,()=>p(f,m)),t.ok(m)}else e.if((0,Zf.checkMissingProp)(t,r,f)),(0,Zf.reportMissingProp)(t,f),e.else()}function d(){e.forOf("prop",n,f=>{t.setParams({missingProperty:f}),e.if((0,Zf.noPropertyInData)(e,i,f,a.ownProperties),()=>t.error())})}function p(f,m){t.setParams({missingProperty:f}),e.forOf(f,n,()=>{e.assign(m,(0,Zf.propertyInData)(e,i,f,a.ownProperties)),e.if((0,Ff.not)(m),()=>{t.error(),e.break()})},Ff.nil)}}};b$.default=Eq});var LC=C(w$=>{"use strict";Object.defineProperty(w$,"__esModule",{value:!0});var Vf=Ue(),Pq={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Vf.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Vf._)`{limit: ${t}}`},Tq={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:Pq,code(t){let{keyword:e,data:r,schemaCode:n}=t,i=e==="maxItems"?Vf.operators.GT:Vf.operators.LT;t.fail$data((0,Vf._)`${r}.length ${i} ${n}`)}};w$.default=Tq});var ey=C(x$=>{"use strict";Object.defineProperty(x$,"__esModule",{value:!0});var UC=Tf();UC.code='require("ajv/dist/runtime/equal").default';x$.default=UC});var ZC=C(k$=>{"use strict";Object.defineProperty(k$,"__esModule",{value:!0});var $$=Pf(),vr=Ue(),Aq=Ye(),zq=ey(),Cq={message:({params:{i:t,j:e}})=>(0,vr.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,vr._)`{i: ${t}, j: ${e}}`},Nq={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:Cq,code(t){let{gen:e,data:r,$data:n,schema:i,parentSchema:o,schemaCode:s,it:a}=t;if(!n&&!i)return;let l=e.let("valid"),c=o.items?(0,$$.getSchemaTypes)(o.items):[];t.block$data(l,u,(0,vr._)`${s} === false`),t.ok(l);function u(){let m=e.let("i",(0,vr._)`${r}.length`),h=e.let("j");t.setParams({i:m,j:h}),e.assign(l,!0),e.if((0,vr._)`${m} > 1`,()=>(d()?p:f)(m,h))}function d(){return c.length>0&&!c.some(m=>m==="object"||m==="array")}function p(m,h){let y=e.name("item"),g=(0,$$.checkDataTypes)(c,y,a.opts.strictNumbers,$$.DataType.Wrong),_=e.const("indices",(0,vr._)`{}`);e.for((0,vr._)`;${m}--;`,()=>{e.let(y,(0,vr._)`${r}[${m}]`),e.if(g,(0,vr._)`continue`),c.length>1&&e.if((0,vr._)`typeof ${y} == "string"`,(0,vr._)`${y} += "_"`),e.if((0,vr._)`typeof ${_}[${y}] == "number"`,()=>{e.assign(h,(0,vr._)`${_}[${y}]`),t.error(),e.assign(l,!1).break()}).code((0,vr._)`${_}[${y}] = ${m}`)})}function f(m,h){let y=(0,Aq.useFunc)(e,zq.default),g=e.name("outer");e.label(g).for((0,vr._)`;${m}--;`,()=>e.for((0,vr._)`${h} = ${m}; ${h}--;`,()=>e.if((0,vr._)`${y}(${r}[${m}], ${r}[${h}])`,()=>{t.error(),e.assign(l,!1).break(g)})))}}};k$.default=Nq});var FC=C(I$=>{"use strict";Object.defineProperty(I$,"__esModule",{value:!0});var S$=Ue(),Oq=Ye(),Rq=ey(),Mq={message:"must be equal to constant",params:({schemaCode:t})=>(0,S$._)`{allowedValue: ${t}}`},jq={keyword:"const",$data:!0,error:Mq,code(t){let{gen:e,data:r,$data:n,schemaCode:i,schema:o}=t;n||o&&typeof o=="object"?t.fail$data((0,S$._)`!${(0,Oq.useFunc)(e,Rq.default)}(${r}, ${i})`):t.fail((0,S$._)`${o} !== ${r}`)}};I$.default=jq});var VC=C(E$=>{"use strict";Object.defineProperty(E$,"__esModule",{value:!0});var qf=Ue(),Dq=Ye(),Lq=ey(),Uq={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,qf._)`{allowedValues: ${t}}`},Zq={keyword:"enum",schemaType:"array",$data:!0,error:Uq,code(t){let{gen:e,data:r,$data:n,schema:i,schemaCode:o,it:s}=t;if(!n&&i.length===0)throw new Error("enum must have non-empty array");let a=i.length>=s.opts.loopEnum,l,c=()=>l??(l=(0,Dq.useFunc)(e,Lq.default)),u;if(a||n)u=e.let("valid"),t.block$data(u,d);else{if(!Array.isArray(i))throw new Error("ajv implementation error");let f=e.const("vSchema",o);u=(0,qf.or)(...i.map((m,h)=>p(f,h)))}t.pass(u);function d(){e.assign(u,!1),e.forOf("v",o,f=>e.if((0,qf._)`${c()}(${r}, ${f})`,()=>e.assign(u,!0).break()))}function p(f,m){let h=i[m];return typeof h=="object"&&h!==null?(0,qf._)`${c()}(${r}, ${f}[${m}])`:(0,qf._)`${r} === ${h}`}}};E$.default=Zq});var qC=C(P$=>{"use strict";Object.defineProperty(P$,"__esModule",{value:!0});var Fq=zC(),Vq=CC(),qq=RC(),Wq=MC(),Bq=jC(),Gq=DC(),Hq=LC(),Xq=ZC(),Kq=FC(),Jq=VC(),Yq=[Fq.default,Vq.default,qq.default,Wq.default,Bq.default,Gq.default,Hq.default,Xq.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},Kq.default,Jq.default];P$.default=Yq});var A$=C(Wf=>{"use strict";Object.defineProperty(Wf,"__esModule",{value:!0});Wf.validateAdditionalItems=void 0;var Ma=Ue(),T$=Ye(),Qq={message:({params:{len:t}})=>(0,Ma.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Ma._)`{limit: ${t}}`},e3={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:Qq,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,T$.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}WC(t,n)}};function WC(t,e){let{gen:r,schema:n,data:i,keyword:o,it:s}=t;s.items=!0;let a=r.const("len",(0,Ma._)`${i}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Ma._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,T$.alwaysValidSchema)(s,n)){let c=r.var("valid",(0,Ma._)`${a} <= ${e.length}`);r.if((0,Ma.not)(c),()=>l(c)),t.ok(c)}function l(c){r.forRange("i",e.length,a,u=>{t.subschema({keyword:o,dataProp:u,dataPropType:T$.Type.Num},c),s.allErrors||r.if((0,Ma.not)(c),()=>r.break())})}}Wf.validateAdditionalItems=WC;Wf.default=e3});var z$=C(Bf=>{"use strict";Object.defineProperty(Bf,"__esModule",{value:!0});Bf.validateTuple=void 0;var BC=Ue(),ty=Ye(),t3=Dn(),r3={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return GC(t,"additionalItems",e);r.items=!0,!(0,ty.alwaysValidSchema)(r,e)&&t.ok((0,t3.validateArray)(t))}};function GC(t,e,r=t.schema){let{gen:n,parentSchema:i,data:o,keyword:s,it:a}=t;u(i),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=ty.mergeEvaluated.items(n,r.length,a.items));let l=n.name("valid"),c=n.const("len",(0,BC._)`${o}.length`);r.forEach((d,p)=>{(0,ty.alwaysValidSchema)(a,d)||(n.if((0,BC._)`${c} > ${p}`,()=>t.subschema({keyword:s,schemaProp:p,dataProp:p},l)),t.ok(l))});function u(d){let{opts:p,errSchemaPath:f}=a,m=r.length,h=m===d.minItems&&(m===d.maxItems||d[e]===!1);if(p.strictTuples&&!h){let y=`"${s}" is ${m}-tuple, but minItems or maxItems/${e} are not specified or different at path "${f}"`;(0,ty.checkStrictMode)(a,y,p.strictTuples)}}}Bf.validateTuple=GC;Bf.default=r3});var HC=C(C$=>{"use strict";Object.defineProperty(C$,"__esModule",{value:!0});var n3=z$(),i3={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,n3.validateTuple)(t,"items")};C$.default=i3});var KC=C(N$=>{"use strict";Object.defineProperty(N$,"__esModule",{value:!0});var XC=Ue(),o3=Ye(),s3=Dn(),a3=A$(),l3={message:({params:{len:t}})=>(0,XC.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,XC._)`{limit: ${t}}`},c3={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:l3,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:i}=r;n.items=!0,!(0,o3.alwaysValidSchema)(n,e)&&(i?(0,a3.validateAdditionalItems)(t,i):t.ok((0,s3.validateArray)(t)))}};N$.default=c3});var JC=C(O$=>{"use strict";Object.defineProperty(O$,"__esModule",{value:!0});var Un=Ue(),ry=Ye(),u3={message:({params:{min:t,max:e}})=>e===void 0?(0,Un.str)`must contain at least ${t} valid item(s)`:(0,Un.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Un._)`{minContains: ${t}}`:(0,Un._)`{minContains: ${t}, maxContains: ${e}}`},d3={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:u3,code(t){let{gen:e,schema:r,parentSchema:n,data:i,it:o}=t,s,a,{minContains:l,maxContains:c}=n;o.opts.next?(s=l===void 0?1:l,a=c):s=1;let u=e.const("len",(0,Un._)`${i}.length`);if(t.setParams({min:s,max:a}),a===void 0&&s===0){(0,ry.checkStrictMode)(o,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&s>a){(0,ry.checkStrictMode)(o,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,ry.alwaysValidSchema)(o,r)){let h=(0,Un._)`${u} >= ${s}`;a!==void 0&&(h=(0,Un._)`${h} && ${u} <= ${a}`),t.pass(h);return}o.items=!0;let d=e.name("valid");a===void 0&&s===1?f(d,()=>e.if(d,()=>e.break())):s===0?(e.let(d,!0),a!==void 0&&e.if((0,Un._)`${i}.length > 0`,p)):(e.let(d,!1),p()),t.result(d,()=>t.reset());function p(){let h=e.name("_valid"),y=e.let("count",0);f(h,()=>e.if(h,()=>m(y)))}function f(h,y){e.forRange("i",0,u,g=>{t.subschema({keyword:"contains",dataProp:g,dataPropType:ry.Type.Num,compositeRule:!0},h),y()})}function m(h){e.code((0,Un._)`${h}++`),a===void 0?e.if((0,Un._)`${h} >= ${s}`,()=>e.assign(d,!0).break()):(e.if((0,Un._)`${h} > ${a}`,()=>e.assign(d,!1).break()),s===1?e.assign(d,!0):e.if((0,Un._)`${h} >= ${s}`,()=>e.assign(d,!0)))}}};O$.default=d3});var eN=C(ji=>{"use strict";Object.defineProperty(ji,"__esModule",{value:!0});ji.validateSchemaDeps=ji.validatePropertyDeps=ji.error=void 0;var R$=Ue(),f3=Ye(),Gf=Dn();ji.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,R$.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,R$._)`{property: ${t},
|
|
6
|
+
missingProperty: ${n},
|
|
7
|
+
depsCount: ${e},
|
|
8
|
+
deps: ${r}}`};var p3={keyword:"dependencies",type:"object",schemaType:"object",error:ji.error,code(t){let[e,r]=m3(t);YC(t,e),QC(t,r)}};function m3({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let i=Array.isArray(t[n])?e:r;i[n]=t[n]}return[e,r]}function YC(t,e=t.schema){let{gen:r,data:n,it:i}=t;if(Object.keys(e).length===0)return;let o=r.let("missing");for(let s in e){let a=e[s];if(a.length===0)continue;let l=(0,Gf.propertyInData)(r,n,s,i.opts.ownProperties);t.setParams({property:s,depsCount:a.length,deps:a.join(", ")}),i.allErrors?r.if(l,()=>{for(let c of a)(0,Gf.checkReportMissingProp)(t,c)}):(r.if((0,R$._)`${l} && (${(0,Gf.checkMissingProp)(t,a,o)})`),(0,Gf.reportMissingProp)(t,o),r.else())}}ji.validatePropertyDeps=YC;function QC(t,e=t.schema){let{gen:r,data:n,keyword:i,it:o}=t,s=r.name("valid");for(let a in e)(0,f3.alwaysValidSchema)(o,e[a])||(r.if((0,Gf.propertyInData)(r,n,a,o.opts.ownProperties),()=>{let l=t.subschema({keyword:i,schemaProp:a},s);t.mergeValidEvaluated(l,s)},()=>r.var(s,!0)),t.ok(s))}ji.validateSchemaDeps=QC;ji.default=p3});var rN=C(M$=>{"use strict";Object.defineProperty(M$,"__esModule",{value:!0});var tN=Ue(),h3=Ye(),g3={message:"property name must be valid",params:({params:t})=>(0,tN._)`{propertyName: ${t.propertyName}}`},y3={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:g3,code(t){let{gen:e,schema:r,data:n,it:i}=t;if((0,h3.alwaysValidSchema)(i,r))return;let o=e.name("valid");e.forIn("key",n,s=>{t.setParams({propertyName:s}),t.subschema({keyword:"propertyNames",data:s,dataTypes:["string"],propertyName:s,compositeRule:!0},o),e.if((0,tN.not)(o),()=>{t.error(!0),i.allErrors||e.break()})}),t.ok(o)}};M$.default=y3});var D$=C(j$=>{"use strict";Object.defineProperty(j$,"__esModule",{value:!0});var ny=Dn(),ui=Ue(),v3=ko(),iy=Ye(),_3={message:"must NOT have additional properties",params:({params:t})=>(0,ui._)`{additionalProperty: ${t.additionalProperty}}`},b3={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:_3,code(t){let{gen:e,schema:r,parentSchema:n,data:i,errsCount:o,it:s}=t;if(!o)throw new Error("ajv implementation error");let{allErrors:a,opts:l}=s;if(s.props=!0,l.removeAdditional!=="all"&&(0,iy.alwaysValidSchema)(s,r))return;let c=(0,ny.allSchemaProperties)(n.properties),u=(0,ny.allSchemaProperties)(n.patternProperties);d(),t.ok((0,ui._)`${o} === ${v3.default.errors}`);function d(){e.forIn("key",i,y=>{!c.length&&!u.length?m(y):e.if(p(y),()=>m(y))})}function p(y){let g;if(c.length>8){let _=(0,iy.schemaRefOrVal)(s,n.properties,"properties");g=(0,ny.isOwnProperty)(e,_,y)}else c.length?g=(0,ui.or)(...c.map(_=>(0,ui._)`${y} === ${_}`)):g=ui.nil;return u.length&&(g=(0,ui.or)(g,...u.map(_=>(0,ui._)`${(0,ny.usePattern)(t,_)}.test(${y})`))),(0,ui.not)(g)}function f(y){e.code((0,ui._)`delete ${i}[${y}]`)}function m(y){if(l.removeAdditional==="all"||l.removeAdditional&&r===!1){f(y);return}if(r===!1){t.setParams({additionalProperty:y}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,iy.alwaysValidSchema)(s,r)){let g=e.name("valid");l.removeAdditional==="failing"?(h(y,g,!1),e.if((0,ui.not)(g),()=>{t.reset(),f(y)})):(h(y,g),a||e.if((0,ui.not)(g),()=>e.break()))}}function h(y,g,_){let b={keyword:"additionalProperties",dataProp:y,dataPropType:iy.Type.Str};_===!1&&Object.assign(b,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(b,g)}}};j$.default=b3});var oN=C(U$=>{"use strict";Object.defineProperty(U$,"__esModule",{value:!0});var w3=Nf(),nN=Dn(),L$=Ye(),iN=D$(),x3={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:i,it:o}=t;o.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&iN.default.code(new w3.KeywordCxt(o,iN.default,"additionalProperties"));let s=(0,nN.allSchemaProperties)(r);for(let d of s)o.definedProperties.add(d);o.opts.unevaluated&&s.length&&o.props!==!0&&(o.props=L$.mergeEvaluated.props(e,(0,L$.toHash)(s),o.props));let a=s.filter(d=>!(0,L$.alwaysValidSchema)(o,r[d]));if(a.length===0)return;let l=e.name("valid");for(let d of a)c(d)?u(d):(e.if((0,nN.propertyInData)(e,i,d,o.opts.ownProperties)),u(d),o.allErrors||e.else().var(l,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(l);function c(d){return o.opts.useDefaults&&!o.compositeRule&&r[d].default!==void 0}function u(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},l)}}};U$.default=x3});var cN=C(Z$=>{"use strict";Object.defineProperty(Z$,"__esModule",{value:!0});var sN=Dn(),oy=Ue(),aN=Ye(),lN=Ye(),$3={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:i,it:o}=t,{opts:s}=o,a=(0,sN.allSchemaProperties)(r),l=a.filter(h=>(0,aN.alwaysValidSchema)(o,r[h]));if(a.length===0||l.length===a.length&&(!o.opts.unevaluated||o.props===!0))return;let c=s.strictSchema&&!s.allowMatchingProperties&&i.properties,u=e.name("valid");o.props!==!0&&!(o.props instanceof oy.Name)&&(o.props=(0,lN.evaluatedPropsToName)(e,o.props));let{props:d}=o;p();function p(){for(let h of a)c&&f(h),o.allErrors?m(h):(e.var(u,!0),m(h),e.if(u))}function f(h){for(let y in c)new RegExp(h).test(y)&&(0,aN.checkStrictMode)(o,`property ${y} matches pattern ${h} (use allowMatchingProperties)`)}function m(h){e.forIn("key",n,y=>{e.if((0,oy._)`${(0,sN.usePattern)(t,h)}.test(${y})`,()=>{let g=l.includes(h);g||t.subschema({keyword:"patternProperties",schemaProp:h,dataProp:y,dataPropType:lN.Type.Str},u),o.opts.unevaluated&&d!==!0?e.assign((0,oy._)`${d}[${y}]`,!0):!g&&!o.allErrors&&e.if((0,oy.not)(u),()=>e.break())})})}}};Z$.default=$3});var uN=C(F$=>{"use strict";Object.defineProperty(F$,"__esModule",{value:!0});var k3=Ye(),S3={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,k3.alwaysValidSchema)(n,r)){t.fail();return}let i=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},i),t.failResult(i,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};F$.default=S3});var dN=C(V$=>{"use strict";Object.defineProperty(V$,"__esModule",{value:!0});var I3=Dn(),E3={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:I3.validateUnion,error:{message:"must match a schema in anyOf"}};V$.default=E3});var fN=C(q$=>{"use strict";Object.defineProperty(q$,"__esModule",{value:!0});var sy=Ue(),P3=Ye(),T3={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,sy._)`{passingSchemas: ${t.passing}}`},A3={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:T3,code(t){let{gen:e,schema:r,parentSchema:n,it:i}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(i.opts.discriminator&&n.discriminator)return;let o=r,s=e.let("valid",!1),a=e.let("passing",null),l=e.name("_valid");t.setParams({passing:a}),e.block(c),t.result(s,()=>t.reset(),()=>t.error(!0));function c(){o.forEach((u,d)=>{let p;(0,P3.alwaysValidSchema)(i,u)?e.var(l,!0):p=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},l),d>0&&e.if((0,sy._)`${l} && ${s}`).assign(s,!1).assign(a,(0,sy._)`[${a}, ${d}]`).else(),e.if(l,()=>{e.assign(s,!0),e.assign(a,d),p&&t.mergeEvaluated(p,sy.Name)})})}}};q$.default=A3});var pN=C(W$=>{"use strict";Object.defineProperty(W$,"__esModule",{value:!0});var z3=Ye(),C3={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let i=e.name("valid");r.forEach((o,s)=>{if((0,z3.alwaysValidSchema)(n,o))return;let a=t.subschema({keyword:"allOf",schemaProp:s},i);t.ok(i),t.mergeEvaluated(a)})}};W$.default=C3});var gN=C(B$=>{"use strict";Object.defineProperty(B$,"__esModule",{value:!0});var ay=Ue(),hN=Ye(),N3={message:({params:t})=>(0,ay.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,ay._)`{failingKeyword: ${t.ifClause}}`},O3={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:N3,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,hN.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let i=mN(n,"then"),o=mN(n,"else");if(!i&&!o)return;let s=e.let("valid",!0),a=e.name("_valid");if(l(),t.reset(),i&&o){let u=e.let("ifClause");t.setParams({ifClause:u}),e.if(a,c("then",u),c("else",u))}else i?e.if(a,c("then")):e.if((0,ay.not)(a),c("else"));t.pass(s,()=>t.error(!0));function l(){let u=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(u)}function c(u,d){return()=>{let p=t.subschema({keyword:u},a);e.assign(s,a),t.mergeValidEvaluated(p,s),d?e.assign(d,(0,ay._)`${u}`):t.setParams({ifClause:u})}}}};function mN(t,e){let r=t.schema[e];return r!==void 0&&!(0,hN.alwaysValidSchema)(t,r)}B$.default=O3});var yN=C(G$=>{"use strict";Object.defineProperty(G$,"__esModule",{value:!0});var R3=Ye(),M3={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,R3.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};G$.default=M3});var vN=C(H$=>{"use strict";Object.defineProperty(H$,"__esModule",{value:!0});var j3=A$(),D3=HC(),L3=z$(),U3=KC(),Z3=JC(),F3=eN(),V3=rN(),q3=D$(),W3=oN(),B3=cN(),G3=uN(),H3=dN(),X3=fN(),K3=pN(),J3=gN(),Y3=yN();function Q3(t=!1){let e=[G3.default,H3.default,X3.default,K3.default,J3.default,Y3.default,V3.default,q3.default,F3.default,W3.default,B3.default];return t?e.push(D3.default,U3.default):e.push(j3.default,L3.default),e.push(Z3.default),e}H$.default=Q3});var _N=C(X$=>{"use strict";Object.defineProperty(X$,"__esModule",{value:!0});var Dt=Ue(),eW={message:({schemaCode:t})=>(0,Dt.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Dt._)`{format: ${t}}`},tW={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:eW,code(t,e){let{gen:r,data:n,$data:i,schema:o,schemaCode:s,it:a}=t,{opts:l,errSchemaPath:c,schemaEnv:u,self:d}=a;if(!l.validateFormats)return;i?p():f();function p(){let m=r.scopeValue("formats",{ref:d.formats,code:l.code.formats}),h=r.const("fDef",(0,Dt._)`${m}[${s}]`),y=r.let("fType"),g=r.let("format");r.if((0,Dt._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>r.assign(y,(0,Dt._)`${h}.type || "string"`).assign(g,(0,Dt._)`${h}.validate`),()=>r.assign(y,(0,Dt._)`"string"`).assign(g,h)),t.fail$data((0,Dt.or)(_(),b()));function _(){return l.strictSchema===!1?Dt.nil:(0,Dt._)`${s} && !${g}`}function b(){let E=u.$async?(0,Dt._)`(${h}.async ? await ${g}(${n}) : ${g}(${n}))`:(0,Dt._)`${g}(${n})`,I=(0,Dt._)`(typeof ${g} == "function" ? ${E} : ${g}.test(${n}))`;return(0,Dt._)`${g} && ${g} !== true && ${y} === ${e} && !${I}`}}function f(){let m=d.formats[o];if(!m){_();return}if(m===!0)return;let[h,y,g]=b(m);h===e&&t.pass(E());function _(){if(l.strictSchema===!1){d.logger.warn(I());return}throw new Error(I());function I(){return`unknown format "${o}" ignored in schema at path "${c}"`}}function b(I){let P=I instanceof RegExp?(0,Dt.regexpCode)(I):l.code.formats?(0,Dt._)`${l.code.formats}${(0,Dt.getProperty)(o)}`:void 0,M=r.scopeValue("formats",{key:o,ref:I,code:P});return typeof I=="object"&&!(I instanceof RegExp)?[I.type||"string",I.validate,(0,Dt._)`${M}.validate`]:["string",I,M]}function E(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!u.$async)throw new Error("async format in sync schema");return(0,Dt._)`await ${g}(${n})`}return typeof y=="function"?(0,Dt._)`${g}(${n})`:(0,Dt._)`${g}.test(${n})`}}}};X$.default=tW});var bN=C(K$=>{"use strict";Object.defineProperty(K$,"__esModule",{value:!0});var rW=_N(),nW=[rW.default];K$.default=nW});var wN=C(lu=>{"use strict";Object.defineProperty(lu,"__esModule",{value:!0});lu.contentVocabulary=lu.metadataVocabulary=void 0;lu.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];lu.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var $N=C(J$=>{"use strict";Object.defineProperty(J$,"__esModule",{value:!0});var iW=AC(),oW=qC(),sW=vN(),aW=bN(),xN=wN(),lW=[iW.default,oW.default,(0,sW.default)(),aW.default,xN.metadataVocabulary,xN.contentVocabulary];J$.default=lW});var SN=C(ly=>{"use strict";Object.defineProperty(ly,"__esModule",{value:!0});ly.DiscrError=void 0;var kN;(function(t){t.Tag="tag",t.Mapping="mapping"})(kN||(ly.DiscrError=kN={}))});var EN=C(Q$=>{"use strict";Object.defineProperty(Q$,"__esModule",{value:!0});var cu=Ue(),Y$=SN(),IN=Vg(),cW=Of(),uW=Ye(),dW={message:({params:{discrError:t,tagName:e}})=>t===Y$.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,cu._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},fW={keyword:"discriminator",type:"object",schemaType:"object",error:dW,code(t){let{gen:e,data:r,schema:n,parentSchema:i,it:o}=t,{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 l=e.let("valid",!1),c=e.const("tag",(0,cu._)`${r}${(0,cu.getProperty)(a)}`);e.if((0,cu._)`typeof ${c} == "string"`,()=>u(),()=>t.error(!1,{discrError:Y$.DiscrError.Tag,tag:c,tagName:a})),t.ok(l);function u(){let f=p();e.if(!1);for(let m in f)e.elseIf((0,cu._)`${c} === ${m}`),e.assign(l,d(f[m]));e.else(),t.error(!1,{discrError:Y$.DiscrError.Mapping,tag:c,tagName:a}),e.endIf()}function d(f){let m=e.name("valid"),h=t.subschema({keyword:"oneOf",schemaProp:f},m);return t.mergeEvaluated(h,cu.Name),m}function p(){var f;let m={},h=g(i),y=!0;for(let E=0;E<s.length;E++){let I=s[E];if(I?.$ref&&!(0,uW.schemaHasRulesButRef)(I,o.self.RULES)){let M=I.$ref;if(I=IN.resolveRef.call(o.self,o.schemaEnv.root,o.baseId,M),I instanceof IN.SchemaEnv&&(I=I.schema),I===void 0)throw new cW.default(o.opts.uriResolver,o.baseId,M)}let P=(f=I?.properties)===null||f===void 0?void 0:f[a];if(typeof P!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);y=y&&(h||g(I)),_(P,E)}if(!y)throw new Error(`discriminator: "${a}" must be required`);return m;function g({required:E}){return Array.isArray(E)&&E.includes(a)}function _(E,I){if(E.const)b(E.const,I);else if(E.enum)for(let P of E.enum)b(P,I);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function b(E,I){if(typeof E!="string"||E in m)throw new Error(`discriminator: "${a}" values must be unique strings`);m[E]=I}}}};Q$.default=fW});var PN=C((fbe,pW)=>{pW.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 AN=C(($t,ek)=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.MissingRefError=$t.ValidationError=$t.CodeGen=$t.Name=$t.nil=$t.stringify=$t.str=$t._=$t.KeywordCxt=$t.Ajv=void 0;var mW=kC(),hW=$N(),gW=EN(),TN=PN(),yW=["/properties"],cy="http://json-schema.org/draft-07/schema",uu=class extends mW.default{_addVocabularies(){super._addVocabularies(),hW.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(gW.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(TN,yW):TN;this.addMetaSchema(e,cy,!1),this.refs["http://json-schema.org/schema"]=cy}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(cy)?cy:void 0)}};$t.Ajv=uu;ek.exports=$t=uu;ek.exports.Ajv=uu;Object.defineProperty($t,"__esModule",{value:!0});$t.default=uu;var vW=Nf();Object.defineProperty($t,"KeywordCxt",{enumerable:!0,get:function(){return vW.KeywordCxt}});var du=Ue();Object.defineProperty($t,"_",{enumerable:!0,get:function(){return du._}});Object.defineProperty($t,"str",{enumerable:!0,get:function(){return du.str}});Object.defineProperty($t,"stringify",{enumerable:!0,get:function(){return du.stringify}});Object.defineProperty($t,"nil",{enumerable:!0,get:function(){return du.nil}});Object.defineProperty($t,"Name",{enumerable:!0,get:function(){return du.Name}});Object.defineProperty($t,"CodeGen",{enumerable:!0,get:function(){return du.CodeGen}});var _W=Zg();Object.defineProperty($t,"ValidationError",{enumerable:!0,get:function(){return _W.default}});var bW=Of();Object.defineProperty($t,"MissingRefError",{enumerable:!0,get:function(){return bW.default}})});var DN=C(Li=>{"use strict";Object.defineProperty(Li,"__esModule",{value:!0});Li.formatNames=Li.fastFormats=Li.fullFormats=void 0;function Di(t,e){return{validate:t,compare:e}}Li.fullFormats={date:Di(ON,ik),time:Di(rk(!0),ok),"date-time":Di(zN(!0),MN),"iso-time":Di(rk(),RN),"iso-date-time":Di(zN(),jN),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:IW,"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:NW,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:EW,int32:{type:"number",validate:AW},int64:{type:"number",validate:zW},float:{type:"number",validate:NN},double:{type:"number",validate:NN},password:!0,binary:!0};Li.fastFormats={...Li.fullFormats,date:Di(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,ik),time:Di(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,ok),"date-time":Di(/^\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,MN),"iso-time":Di(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,RN),"iso-date-time":Di(/^\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,jN),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};Li.formatNames=Object.keys(Li.fullFormats);function wW(t){return t%4===0&&(t%100!==0||t%400===0)}var xW=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,$W=[0,31,28,31,30,31,30,31,31,30,31,30,31];function ON(t){let e=xW.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],i=+e[3];return n>=1&&n<=12&&i>=1&&i<=(n===2&&wW(r)?29:$W[n])}function ik(t,e){if(t&&e)return t>e?1:t<e?-1:0}var tk=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function rk(t){return function(r){let n=tk.exec(r);if(!n)return!1;let i=+n[1],o=+n[2],s=+n[3],a=n[4],l=n[5]==="-"?-1:1,c=+(n[6]||0),u=+(n[7]||0);if(c>23||u>59||t&&!a)return!1;if(i<=23&&o<=59&&s<60)return!0;let d=o-u*l,p=i-c*l-(d<0?1:0);return(p===23||p===-1)&&(d===59||d===-1)&&s<61}}function ok(t,e){if(!(t&&e))return;let r=new Date("2020-01-01T"+t).valueOf(),n=new Date("2020-01-01T"+e).valueOf();if(r&&n)return r-n}function RN(t,e){if(!(t&&e))return;let r=tk.exec(t),n=tk.exec(e);if(r&&n)return t=r[1]+r[2]+r[3],e=n[1]+n[2]+n[3],t>e?1:t<e?-1:0}var nk=/t|\s/i;function zN(t){let e=rk(t);return function(n){let i=n.split(nk);return i.length===2&&ON(i[0])&&e(i[1])}}function MN(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function jN(t,e){if(!(t&&e))return;let[r,n]=t.split(nk),[i,o]=e.split(nk),s=ik(r,i);if(s!==void 0)return s||ok(n,o)}var kW=/\/|:/,SW=/^(?:[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 IW(t){return kW.test(t)&&SW.test(t)}var CN=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function EW(t){return CN.lastIndex=0,CN.test(t)}var PW=-(2**31),TW=2**31-1;function AW(t){return Number.isInteger(t)&&t<=TW&&t>=PW}function zW(t){return Number.isInteger(t)}function NN(){return!0}var CW=/[^\\]\\Z/;function NW(t){if(CW.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var Kf=C(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.regexpCode=Qe.getEsmExportName=Qe.getProperty=Qe.safeStringify=Qe.stringify=Qe.strConcat=Qe.addCodeArg=Qe.str=Qe._=Qe.nil=Qe._Code=Qe.Name=Qe.IDENTIFIER=Qe._CodeOrName=void 0;var Hf=class{};Qe._CodeOrName=Hf;Qe.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var ja=class extends Hf{constructor(e){if(super(),!Qe.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}}};Qe.Name=ja;var Zn=class extends Hf{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((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof ja&&(r[n.str]=(r[n.str]||0)+1),r),{})}};Qe._Code=Zn;Qe.nil=new Zn("");function LN(t,...e){let r=[t[0]],n=0;for(;n<e.length;)ak(r,e[n]),r.push(t[++n]);return new Zn(r)}Qe._=LN;var sk=new Zn("+");function UN(t,...e){let r=[Xf(t[0])],n=0;for(;n<e.length;)r.push(sk),ak(r,e[n]),r.push(sk,Xf(t[++n]));return OW(r),new Zn(r)}Qe.str=UN;function ak(t,e){e instanceof Zn?t.push(...e._items):e instanceof ja?t.push(e):t.push(jW(e))}Qe.addCodeArg=ak;function OW(t){let e=1;for(;e<t.length-1;){if(t[e]===sk){let r=RW(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function RW(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof ja||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof ja))return`"${t}${e.slice(1)}`}function MW(t,e){return e.emptyStr()?t:t.emptyStr()?e:UN`${t}${e}`}Qe.strConcat=MW;function jW(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Xf(Array.isArray(t)?t.join(","):t)}function DW(t){return new Zn(Xf(t))}Qe.stringify=DW;function Xf(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}Qe.safeStringify=Xf;function LW(t){return typeof t=="string"&&Qe.IDENTIFIER.test(t)?new Zn(`.${t}`):LN`[${t}]`}Qe.getProperty=LW;function UW(t){if(typeof t=="string"&&Qe.IDENTIFIER.test(t))return new Zn(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}Qe.getEsmExportName=UW;function ZW(t){return new Zn(t.toString())}Qe.regexpCode=ZW});var dk=C(Vr=>{"use strict";Object.defineProperty(Vr,"__esModule",{value:!0});Vr.ValueScope=Vr.ValueScopeName=Vr.Scope=Vr.varKinds=Vr.UsedValueState=void 0;var on=Kf(),lk=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},ck;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(ck=Vr.UsedValueState||(Vr.UsedValueState={}));Vr.varKinds={const:new on.Name("const"),let:new on.Name("let"),var:new on.Name("var")};var uy=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof on.Name?e:this.name(e)}name(e){return new on.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._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}}};Vr.Scope=uy;var dy=class extends on.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,on._)`.${new on.Name(r)}[${n}]`}};Vr.ValueScopeName=dy;var FW=(0,on._)`\n`,uk=class extends uy{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?FW:on.nil}}get(){return this._scope}name(e){return new dy(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let i=this.toName(e),{prefix:o}=i,s=(n=r.key)!==null&&n!==void 0?n:r.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 l=this._scope[o]||(this._scope[o]=[]),c=l.length;return l[c]=r.ref,i.setValue(r,{property:o,itemIndex:c}),i}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,on._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,i=>{if(i.value===void 0)throw new Error(`CodeGen: name "${i}" has no value`);return i.value.code},r,n)}_reduceValues(e,r,n={},i){let o=on.nil;for(let s in e){let a=e[s];if(!a)continue;let l=n[s]=n[s]||new Map;a.forEach(c=>{if(l.has(c))return;l.set(c,ck.Started);let u=r(c);if(u){let d=this.opts.es5?Vr.varKinds.var:Vr.varKinds.const;o=(0,on._)`${o}${d} ${c} = ${u};${this.opts._n}`}else if(u=i?.(c))o=(0,on._)`${o}${u}${this.opts._n}`;else throw new lk(c);l.set(c,ck.Completed)})}return o}};Vr.ValueScope=uk});var Ne=C(je=>{"use strict";Object.defineProperty(je,"__esModule",{value:!0});je.or=je.and=je.not=je.CodeGen=je.operators=je.varKinds=je.ValueScopeName=je.ValueScope=je.Scope=je.Name=je.regexpCode=je.stringify=je.getProperty=je.nil=je.strConcat=je.str=je._=void 0;var Be=Kf(),di=dk(),$s=Kf();Object.defineProperty(je,"_",{enumerable:!0,get:function(){return $s._}});Object.defineProperty(je,"str",{enumerable:!0,get:function(){return $s.str}});Object.defineProperty(je,"strConcat",{enumerable:!0,get:function(){return $s.strConcat}});Object.defineProperty(je,"nil",{enumerable:!0,get:function(){return $s.nil}});Object.defineProperty(je,"getProperty",{enumerable:!0,get:function(){return $s.getProperty}});Object.defineProperty(je,"stringify",{enumerable:!0,get:function(){return $s.stringify}});Object.defineProperty(je,"regexpCode",{enumerable:!0,get:function(){return $s.regexpCode}});Object.defineProperty(je,"Name",{enumerable:!0,get:function(){return $s.Name}});var hy=dk();Object.defineProperty(je,"Scope",{enumerable:!0,get:function(){return hy.Scope}});Object.defineProperty(je,"ValueScope",{enumerable:!0,get:function(){return hy.ValueScope}});Object.defineProperty(je,"ValueScopeName",{enumerable:!0,get:function(){return hy.ValueScopeName}});Object.defineProperty(je,"varKinds",{enumerable:!0,get:function(){return hy.varKinds}});je.operators={GT:new Be._Code(">"),GTE:new Be._Code(">="),LT:new Be._Code("<"),LTE:new Be._Code("<="),EQ:new Be._Code("==="),NEQ:new Be._Code("!=="),NOT:new Be._Code("!"),OR:new Be._Code("||"),AND:new Be._Code("&&"),ADD:new Be._Code("+")};var Eo=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},fk=class extends Eo{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?di.varKinds.var:this.varKind,i=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${i};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=pu(this.rhs,e,r)),this}get names(){return this.rhs instanceof Be._CodeOrName?this.rhs.names:{}}},fy=class extends Eo{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof Be.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=pu(this.rhs,e,r),this}get names(){let e=this.lhs instanceof Be.Name?{}:{...this.lhs.names};return my(e,this.rhs)}},pk=class extends fy{constructor(e,r,n,i){super(e,n,i),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},mk=class extends Eo{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},hk=class extends Eo{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},gk=class extends Eo{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},yk=class extends Eo{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=pu(this.code,e,r),this}get names(){return this.code instanceof Be._CodeOrName?this.code.names:{}}},Jf=class extends Eo{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,i=n.length;for(;i--;){let o=n[i];o.optimizeNames(e,r)||(VW(e,o.names),n.splice(i,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>Ua(e,r.names),{})}},Po=class extends Jf{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},vk=class extends Jf{},fu=class extends Po{};fu.kind="else";var Da=class t extends Po{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new fu(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(ZN(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=pu(this.condition,e,r),this}get names(){let e=super.names;return my(e,this.condition),this.else&&Ua(e,this.else.names),e}};Da.kind="if";var La=class extends Po{};La.kind="for";var _k=class extends La{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=pu(this.iteration,e,r),this}get names(){return Ua(super.names,this.iteration.names)}},bk=class extends La{constructor(e,r,n,i){super(),this.varKind=e,this.name=r,this.from=n,this.to=i}render(e){let r=e.es5?di.varKinds.var:this.varKind,{name:n,from:i,to:o}=this;return`for(${r} ${n}=${i}; ${n}<${o}; ${n}++)`+super.render(e)}get names(){let e=my(super.names,this.from);return my(e,this.to)}},py=class extends La{constructor(e,r,n,i){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=i}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=pu(this.iterable,e,r),this}get names(){return Ua(super.names,this.iterable.names)}},Yf=class extends Po{constructor(e,r,n){super(),this.name=e,this.args=r,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};Yf.kind="func";var Qf=class extends Jf{render(e){return"return "+super.render(e)}};Qf.kind="return";var wk=class extends Po{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,i;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(i=this.finally)===null||i===void 0||i.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&Ua(e,this.catch.names),this.finally&&Ua(e,this.finally.names),e}},ep=class extends Po{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};ep.kind="catch";var tp=class extends Po{render(e){return"finally"+super.render(e)}};tp.kind="finally";var xk=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
9
|
+
`:""},this._extScope=e,this._scope=new di.Scope({parent:e}),this._nodes=[new vk]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,i){let o=this._scope.toName(r);return n!==void 0&&i&&(this._constants[o.str]=n),this._leafNode(new fk(e,o,n)),o}const(e,r,n){return this._def(di.varKinds.const,e,r,n)}let(e,r,n){return this._def(di.varKinds.let,e,r,n)}var(e,r,n){return this._def(di.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new fy(e,r,n))}add(e,r){return this._leafNode(new pk(e,je.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==Be.nil&&this._leafNode(new yk(e)),this}object(...e){let r=["{"];for(let[n,i]of e)r.length>1&&r.push(","),r.push(n),(n!==i||this.opts.es5)&&(r.push(":"),(0,Be.addCodeArg)(r,i));return r.push("}"),new Be._Code(r)}if(e,r,n){if(this._blockNode(new Da(e)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new Da(e))}else(){return this._elseNode(new fu)}endIf(){return this._endBlockNode(Da,fu)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new _k(e),r)}forRange(e,r,n,i,o=this.opts.es5?di.varKinds.var:di.varKinds.let){let s=this._scope.toName(e);return this._for(new bk(o,s,r,n),()=>i(s))}forOf(e,r,n,i=di.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let s=r instanceof Be.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,Be._)`${s}.length`,a=>{this.var(o,(0,Be._)`${s}[${a}]`),n(o)})}return this._for(new py("of",i,o,r),()=>n(o))}forIn(e,r,n,i=this.opts.es5?di.varKinds.var:di.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,Be._)`Object.keys(${r})`,n);let o=this._scope.toName(e);return this._for(new py("in",i,o,r),()=>n(o))}endFor(){return this._endBlockNode(La)}label(e){return this._leafNode(new mk(e))}break(e){return this._leafNode(new hk(e))}return(e){let r=new Qf;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Qf)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let i=new wk;if(this._blockNode(i),this.code(e),r){let o=this.name("e");this._currNode=i.catch=new ep(o),r(o)}return n&&(this._currNode=i.finally=new tp,this.code(n)),this._endBlockNode(ep,tp)}throw(e){return this._leafNode(new gk(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=Be.nil,n,i){return this._blockNode(new Yf(e,r,n)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(Yf)}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,r){let n=this._currNode;if(n instanceof e||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof Da))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};je.CodeGen=xk;function Ua(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function my(t,e){return e instanceof Be._CodeOrName?Ua(t,e.names):t}function pu(t,e,r){if(t instanceof Be.Name)return n(t);if(!i(t))return t;return new Be._Code(t._items.reduce((o,s)=>(s instanceof Be.Name&&(s=n(s)),s instanceof Be._Code?o.push(...s._items):o.push(s),o),[]));function n(o){let s=r[o.str];return s===void 0||e[o.str]!==1?o:(delete e[o.str],s)}function i(o){return o instanceof Be._Code&&o._items.some(s=>s instanceof Be.Name&&e[s.str]===1&&r[s.str]!==void 0)}}function VW(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function ZN(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,Be._)`!${$k(t)}`}je.not=ZN;var qW=FN(je.operators.AND);function WW(...t){return t.reduce(qW)}je.and=WW;var BW=FN(je.operators.OR);function GW(...t){return t.reduce(BW)}je.or=GW;function FN(t){return(e,r)=>e===Be.nil?r:r===Be.nil?e:(0,Be._)`${$k(e)} ${t} ${$k(r)}`}function $k(t){return t instanceof Be.Name?t:(0,Be._)`(${t})`}});var et=C(De=>{"use strict";Object.defineProperty(De,"__esModule",{value:!0});De.checkStrictMode=De.getErrorPath=De.Type=De.useFunc=De.setEvaluated=De.evaluatedPropsToName=De.mergeEvaluated=De.eachItem=De.unescapeJsonPointer=De.escapeJsonPointer=De.escapeFragment=De.unescapeFragment=De.schemaRefOrVal=De.schemaHasRulesButRef=De.schemaHasRules=De.checkUnknownRules=De.alwaysValidSchema=De.toHash=void 0;var ht=Ne(),HW=Kf();function XW(t){let e={};for(let r of t)e[r]=!0;return e}De.toHash=XW;function KW(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(WN(t,e),!BN(e,t.self.RULES.all))}De.alwaysValidSchema=KW;function WN(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let i=n.RULES.keywords;for(let o in e)i[o]||KN(t,`unknown keyword: "${o}"`)}De.checkUnknownRules=WN;function BN(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}De.schemaHasRules=BN;function JW(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}De.schemaHasRulesButRef=JW;function YW({topSchemaRef:t,schemaPath:e},r,n,i){if(!i){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,ht._)`${r}`}return(0,ht._)`${t}${e}${(0,ht.getProperty)(n)}`}De.schemaRefOrVal=YW;function QW(t){return GN(decodeURIComponent(t))}De.unescapeFragment=QW;function eB(t){return encodeURIComponent(kk(t))}De.escapeFragment=eB;function kk(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}De.escapeJsonPointer=kk;function GN(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}De.unescapeJsonPointer=GN;function tB(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}De.eachItem=tB;function VN({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(i,o,s,a)=>{let l=s===void 0?o:s instanceof ht.Name?(o instanceof ht.Name?t(i,o,s):e(i,o,s),s):o instanceof ht.Name?(e(i,s,o),o):r(o,s);return a===ht.Name&&!(l instanceof ht.Name)?n(i,l):l}}De.mergeEvaluated={props:VN({mergeNames:(t,e,r)=>t.if((0,ht._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,ht._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,ht._)`${r} || {}`).code((0,ht._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,ht._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,ht._)`${r} || {}`),Sk(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:HN}),items:VN({mergeNames:(t,e,r)=>t.if((0,ht._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,ht._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,ht._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,ht._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function HN(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,ht._)`{}`);return e!==void 0&&Sk(t,r,e),r}De.evaluatedPropsToName=HN;function Sk(t,e,r){Object.keys(r).forEach(n=>t.assign((0,ht._)`${e}${(0,ht.getProperty)(n)}`,!0))}De.setEvaluated=Sk;var qN={};function rB(t,e){return t.scopeValue("func",{ref:e,code:qN[e.code]||(qN[e.code]=new HW._Code(e.code))})}De.useFunc=rB;var XN;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(XN=De.Type||(De.Type={}));function nB(t,e,r){if(t instanceof ht.Name){let n=e===XN.Num;return r?n?(0,ht._)`"[" + ${t} + "]"`:(0,ht._)`"['" + ${t} + "']"`:n?(0,ht._)`"/" + ${t}`:(0,ht._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,ht.getProperty)(t).toString():"/"+kk(t)}De.getErrorPath=nB;function KN(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}De.checkStrictMode=KN});var To=C(Ik=>{"use strict";Object.defineProperty(Ik,"__esModule",{value:!0});var Nr=Ne(),iB={data:new Nr.Name("data"),valCxt:new Nr.Name("valCxt"),instancePath:new Nr.Name("instancePath"),parentData:new Nr.Name("parentData"),parentDataProperty:new Nr.Name("parentDataProperty"),rootData:new Nr.Name("rootData"),dynamicAnchors:new Nr.Name("dynamicAnchors"),vErrors:new Nr.Name("vErrors"),errors:new Nr.Name("errors"),this:new Nr.Name("this"),self:new Nr.Name("self"),scope:new Nr.Name("scope"),json:new Nr.Name("json"),jsonPos:new Nr.Name("jsonPos"),jsonLen:new Nr.Name("jsonLen"),jsonPart:new Nr.Name("jsonPart")};Ik.default=iB});var rp=C(Or=>{"use strict";Object.defineProperty(Or,"__esModule",{value:!0});Or.extendErrors=Or.resetErrorsCount=Or.reportExtraError=Or.reportError=Or.keyword$DataError=Or.keywordError=void 0;var Xe=Ne(),gy=et(),qr=To();Or.keywordError={message:({keyword:t})=>(0,Xe.str)`must pass "${t}" keyword validation`};Or.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,Xe.str)`"${t}" keyword must be ${e} ($data)`:(0,Xe.str)`"${t}" keyword is invalid ($data)`};function oB(t,e=Or.keywordError,r,n){let{it:i}=t,{gen:o,compositeRule:s,allErrors:a}=i,l=QN(t,e,r);n??(s||a)?JN(o,l):YN(i,(0,Xe._)`[${l}]`)}Or.reportError=oB;function sB(t,e=Or.keywordError,r){let{it:n}=t,{gen:i,compositeRule:o,allErrors:s}=n,a=QN(t,e,r);JN(i,a),o||s||YN(n,qr.default.vErrors)}Or.reportExtraError=sB;function aB(t,e){t.assign(qr.default.errors,e),t.if((0,Xe._)`${qr.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,Xe._)`${qr.default.vErrors}.length`,e),()=>t.assign(qr.default.vErrors,null)))}Or.resetErrorsCount=aB;function lB({gen:t,keyword:e,schemaValue:r,data:n,errsCount:i,it:o}){if(i===void 0)throw new Error("ajv implementation error");let s=t.name("err");t.forRange("i",i,qr.default.errors,a=>{t.const(s,(0,Xe._)`${qr.default.vErrors}[${a}]`),t.if((0,Xe._)`${s}.instancePath === undefined`,()=>t.assign((0,Xe._)`${s}.instancePath`,(0,Xe.strConcat)(qr.default.instancePath,o.errorPath))),t.assign((0,Xe._)`${s}.schemaPath`,(0,Xe.str)`${o.errSchemaPath}/${e}`),o.opts.verbose&&(t.assign((0,Xe._)`${s}.schema`,r),t.assign((0,Xe._)`${s}.data`,n))})}Or.extendErrors=lB;function JN(t,e){let r=t.const("err",e);t.if((0,Xe._)`${qr.default.vErrors} === null`,()=>t.assign(qr.default.vErrors,(0,Xe._)`[${r}]`),(0,Xe._)`${qr.default.vErrors}.push(${r})`),t.code((0,Xe._)`${qr.default.errors}++`)}function YN(t,e){let{gen:r,validateName:n,schemaEnv:i}=t;i.$async?r.throw((0,Xe._)`new ${t.ValidationError}(${e})`):(r.assign((0,Xe._)`${n}.errors`,e),r.return(!1))}var Za={keyword:new Xe.Name("keyword"),schemaPath:new Xe.Name("schemaPath"),params:new Xe.Name("params"),propertyName:new Xe.Name("propertyName"),message:new Xe.Name("message"),schema:new Xe.Name("schema"),parentSchema:new Xe.Name("parentSchema")};function QN(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,Xe._)`{}`:cB(t,e,r)}function cB(t,e,r={}){let{gen:n,it:i}=t,o=[uB(i,r),dB(t,r)];return fB(t,e,o),n.object(...o)}function uB({errorPath:t},{instancePath:e}){let r=e?(0,Xe.str)`${t}${(0,gy.getErrorPath)(e,gy.Type.Str)}`:t;return[qr.default.instancePath,(0,Xe.strConcat)(qr.default.instancePath,r)]}function dB({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let i=n?e:(0,Xe.str)`${e}/${t}`;return r&&(i=(0,Xe.str)`${i}${(0,gy.getErrorPath)(r,gy.Type.Str)}`),[Za.schemaPath,i]}function fB(t,{params:e,message:r},n){let{keyword:i,data:o,schemaValue:s,it:a}=t,{opts:l,propertyName:c,topSchemaRef:u,schemaPath:d}=a;n.push([Za.keyword,i],[Za.params,typeof e=="function"?e(t):e||(0,Xe._)`{}`]),l.messages&&n.push([Za.message,typeof r=="function"?r(t):r]),l.verbose&&n.push([Za.schema,s],[Za.parentSchema,(0,Xe._)`${u}${d}`],[qr.default.data,o]),c&&n.push([Za.propertyName,c])}});var tO=C(mu=>{"use strict";Object.defineProperty(mu,"__esModule",{value:!0});mu.boolOrEmptySchema=mu.topBoolOrEmptySchema=void 0;var pB=rp(),mB=Ne(),hB=To(),gB={message:"boolean schema is false"};function yB(t){let{gen:e,schema:r,validateName:n}=t;r===!1?eO(t,!1):typeof r=="object"&&r.$async===!0?e.return(hB.default.data):(e.assign((0,mB._)`${n}.errors`,null),e.return(!0))}mu.topBoolOrEmptySchema=yB;function vB(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),eO(t)):r.var(e,!0)}mu.boolOrEmptySchema=vB;function eO(t,e){let{gen:r,data:n}=t,i={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,pB.reportError)(i,gB,void 0,e)}});var Ek=C(hu=>{"use strict";Object.defineProperty(hu,"__esModule",{value:!0});hu.getRules=hu.isJSONType=void 0;var _B=["string","number","integer","boolean","null","object","array"],bB=new Set(_B);function wB(t){return typeof t=="string"&&bB.has(t)}hu.isJSONType=wB;function xB(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}hu.getRules=xB});var Pk=C(ks=>{"use strict";Object.defineProperty(ks,"__esModule",{value:!0});ks.shouldUseRule=ks.shouldUseGroup=ks.schemaHasRulesForType=void 0;function $B({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&rO(t,n)}ks.schemaHasRulesForType=$B;function rO(t,e){return e.rules.some(r=>nO(t,r))}ks.shouldUseGroup=rO;function nO(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}ks.shouldUseRule=nO});var ip=C(_r=>{"use strict";Object.defineProperty(_r,"__esModule",{value:!0});_r.reportTypeError=_r.checkDataTypes=_r.checkDataType=_r.coerceAndCheckDataType=_r.getJSONTypes=_r.getSchemaTypes=_r.DataType=void 0;var kB=Ek(),SB=Pk(),IB=rp(),Ce=Ne(),iO=et(),np;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(np=_r.DataType||(_r.DataType={}));function EB(t){let e=oO(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}_r.getSchemaTypes=EB;function oO(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(kB.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}_r.getJSONTypes=oO;function PB(t,e){let{gen:r,data:n,opts:i}=t,o=TB(e,i.coerceTypes),s=e.length>0&&!(o.length===0&&e.length===1&&(0,SB.schemaHasRulesForType)(t,e[0]));if(s){let a=Ak(e,n,i.strictNumbers,np.Wrong);r.if(a,()=>{o.length?AB(t,e,o):zk(t)})}return s}_r.coerceAndCheckDataType=PB;var sO=new Set(["string","number","integer","boolean","null"]);function TB(t,e){return e?t.filter(r=>sO.has(r)||e==="array"&&r==="array"):[]}function AB(t,e,r){let{gen:n,data:i,opts:o}=t,s=n.let("dataType",(0,Ce._)`typeof ${i}`),a=n.let("coerced",(0,Ce._)`undefined`);o.coerceTypes==="array"&&n.if((0,Ce._)`${s} == 'object' && Array.isArray(${i}) && ${i}.length == 1`,()=>n.assign(i,(0,Ce._)`${i}[0]`).assign(s,(0,Ce._)`typeof ${i}`).if(Ak(e,i,o.strictNumbers),()=>n.assign(a,i))),n.if((0,Ce._)`${a} !== undefined`);for(let c of r)(sO.has(c)||c==="array"&&o.coerceTypes==="array")&&l(c);n.else(),zk(t),n.endIf(),n.if((0,Ce._)`${a} !== undefined`,()=>{n.assign(i,a),zB(t,a)});function l(c){switch(c){case"string":n.elseIf((0,Ce._)`${s} == "number" || ${s} == "boolean"`).assign(a,(0,Ce._)`"" + ${i}`).elseIf((0,Ce._)`${i} === null`).assign(a,(0,Ce._)`""`);return;case"number":n.elseIf((0,Ce._)`${s} == "boolean" || ${i} === null
|
|
10
|
+
|| (${s} == "string" && ${i} && ${i} == +${i})`).assign(a,(0,Ce._)`+${i}`);return;case"integer":n.elseIf((0,Ce._)`${s} === "boolean" || ${i} === null
|
|
11
|
+
|| (${s} === "string" && ${i} && ${i} == +${i} && !(${i} % 1))`).assign(a,(0,Ce._)`+${i}`);return;case"boolean":n.elseIf((0,Ce._)`${i} === "false" || ${i} === 0 || ${i} === null`).assign(a,!1).elseIf((0,Ce._)`${i} === "true" || ${i} === 1`).assign(a,!0);return;case"null":n.elseIf((0,Ce._)`${i} === "" || ${i} === 0 || ${i} === false`),n.assign(a,null);return;case"array":n.elseIf((0,Ce._)`${s} === "string" || ${s} === "number"
|
|
12
|
+
|| ${s} === "boolean" || ${i} === null`).assign(a,(0,Ce._)`[${i}]`)}}}function zB({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,Ce._)`${e} !== undefined`,()=>t.assign((0,Ce._)`${e}[${r}]`,n))}function Tk(t,e,r,n=np.Correct){let i=n===np.Correct?Ce.operators.EQ:Ce.operators.NEQ,o;switch(t){case"null":return(0,Ce._)`${e} ${i} null`;case"array":o=(0,Ce._)`Array.isArray(${e})`;break;case"object":o=(0,Ce._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":o=s((0,Ce._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":o=s();break;default:return(0,Ce._)`typeof ${e} ${i} ${t}`}return n===np.Correct?o:(0,Ce.not)(o);function s(a=Ce.nil){return(0,Ce.and)((0,Ce._)`typeof ${e} == "number"`,a,r?(0,Ce._)`isFinite(${e})`:Ce.nil)}}_r.checkDataType=Tk;function Ak(t,e,r,n){if(t.length===1)return Tk(t[0],e,r,n);let i,o=(0,iO.toHash)(t);if(o.array&&o.object){let s=(0,Ce._)`typeof ${e} != "object"`;i=o.null?s:(0,Ce._)`!${e} || ${s}`,delete o.null,delete o.array,delete o.object}else i=Ce.nil;o.number&&delete o.integer;for(let s in o)i=(0,Ce.and)(i,Tk(s,e,r,n));return i}_r.checkDataTypes=Ak;var CB={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,Ce._)`{type: ${t}}`:(0,Ce._)`{type: ${e}}`};function zk(t){let e=NB(t);(0,IB.reportError)(e,CB)}_r.reportTypeError=zk;function NB(t){let{gen:e,data:r,schema:n}=t,i=(0,iO.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:i,schemaValue:i,parentSchema:n,params:{},it:t}}});var lO=C(yy=>{"use strict";Object.defineProperty(yy,"__esModule",{value:!0});yy.assignDefaults=void 0;var gu=Ne(),OB=et();function RB(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let i in r)aO(t,i,r[i].default);else e==="array"&&Array.isArray(n)&&n.forEach((i,o)=>aO(t,o,i.default))}yy.assignDefaults=RB;function aO(t,e,r){let{gen:n,compositeRule:i,data:o,opts:s}=t;if(r===void 0)return;let a=(0,gu._)`${o}${(0,gu.getProperty)(e)}`;if(i){(0,OB.checkStrictMode)(t,`default is ignored for: ${a}`);return}let l=(0,gu._)`${a} === undefined`;s.useDefaults==="empty"&&(l=(0,gu._)`${l} || ${a} === null || ${a} === ""`),n.if(l,(0,gu._)`${a} = ${(0,gu.stringify)(r)}`)}});var Fn=C(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.validateUnion=ft.validateArray=ft.usePattern=ft.callValidateCode=ft.schemaProperties=ft.allSchemaProperties=ft.noPropertyInData=ft.propertyInData=ft.isOwnProperty=ft.hasPropFunc=ft.reportMissingProp=ft.checkMissingProp=ft.checkReportMissingProp=void 0;var kt=Ne(),Ck=et(),Ss=To(),MB=et();function jB(t,e){let{gen:r,data:n,it:i}=t;r.if(Ok(r,n,e,i.opts.ownProperties),()=>{t.setParams({missingProperty:(0,kt._)`${e}`},!0),t.error()})}ft.checkReportMissingProp=jB;function DB({gen:t,data:e,it:{opts:r}},n,i){return(0,kt.or)(...n.map(o=>(0,kt.and)(Ok(t,e,o,r.ownProperties),(0,kt._)`${i} = ${o}`)))}ft.checkMissingProp=DB;function LB(t,e){t.setParams({missingProperty:e},!0),t.error()}ft.reportMissingProp=LB;function cO(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,kt._)`Object.prototype.hasOwnProperty`})}ft.hasPropFunc=cO;function Nk(t,e,r){return(0,kt._)`${cO(t)}.call(${e}, ${r})`}ft.isOwnProperty=Nk;function UB(t,e,r,n){let i=(0,kt._)`${e}${(0,kt.getProperty)(r)} !== undefined`;return n?(0,kt._)`${i} && ${Nk(t,e,r)}`:i}ft.propertyInData=UB;function Ok(t,e,r,n){let i=(0,kt._)`${e}${(0,kt.getProperty)(r)} === undefined`;return n?(0,kt.or)(i,(0,kt.not)(Nk(t,e,r))):i}ft.noPropertyInData=Ok;function uO(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}ft.allSchemaProperties=uO;function ZB(t,e){return uO(e).filter(r=>!(0,Ck.alwaysValidSchema)(t,e[r]))}ft.schemaProperties=ZB;function FB({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:i,errorPath:o},it:s},a,l,c){let u=c?(0,kt._)`${t}, ${e}, ${n}${i}`:e,d=[[Ss.default.instancePath,(0,kt.strConcat)(Ss.default.instancePath,o)],[Ss.default.parentData,s.parentData],[Ss.default.parentDataProperty,s.parentDataProperty],[Ss.default.rootData,Ss.default.rootData]];s.opts.dynamicRef&&d.push([Ss.default.dynamicAnchors,Ss.default.dynamicAnchors]);let p=(0,kt._)`${u}, ${r.object(...d)}`;return l!==kt.nil?(0,kt._)`${a}.call(${l}, ${p})`:(0,kt._)`${a}(${p})`}ft.callValidateCode=FB;var VB=(0,kt._)`new RegExp`;function qB({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:i}=e.code,o=i(r,n);return t.scopeValue("pattern",{key:o.toString(),ref:o,code:(0,kt._)`${i.code==="new RegExp"?VB:(0,MB.useFunc)(t,i)}(${r}, ${n})`})}ft.usePattern=qB;function WB(t){let{gen:e,data:r,keyword:n,it:i}=t,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 l=e.const("len",(0,kt._)`${r}.length`);e.forRange("i",0,l,c=>{t.subschema({keyword:n,dataProp:c,dataPropType:Ck.Type.Num},o),e.if((0,kt.not)(o),a)})}}ft.validateArray=WB;function BB(t){let{gen:e,schema:r,keyword:n,it:i}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(l=>(0,Ck.alwaysValidSchema)(i,l))&&!i.opts.unevaluated)return;let s=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((l,c)=>{let u=t.subschema({keyword:n,schemaProp:c,compositeRule:!0},a);e.assign(s,(0,kt._)`${s} || ${a}`),t.mergeValidEvaluated(u,a)||e.if((0,kt.not)(s))})),t.result(s,()=>t.reset(),()=>t.error(!0))}ft.validateUnion=BB});var pO=C(Ui=>{"use strict";Object.defineProperty(Ui,"__esModule",{value:!0});Ui.validateKeywordUsage=Ui.validSchemaType=Ui.funcKeywordCode=Ui.macroKeywordCode=void 0;var Wr=Ne(),Fa=To(),GB=Fn(),HB=rp();function XB(t,e){let{gen:r,keyword:n,schema:i,parentSchema:o,it:s}=t,a=e.macro.call(s.self,i,o,s),l=fO(r,n,a);s.opts.validateSchema!==!1&&s.self.validateSchema(a,!0);let c=r.name("valid");t.subschema({schema:a,schemaPath:Wr.nil,errSchemaPath:`${s.errSchemaPath}/${n}`,topSchemaRef:l,compositeRule:!0},c),t.pass(c,()=>t.error(!0))}Ui.macroKeywordCode=XB;function KB(t,e){var r;let{gen:n,keyword:i,schema:o,parentSchema:s,$data:a,it:l}=t;YB(l,e);let c=!a&&e.compile?e.compile.call(l.self,o,s,l):e.validate,u=fO(n,i,c),d=n.let("valid");t.block$data(d,p),t.ok((r=e.valid)!==null&&r!==void 0?r:d);function p(){if(e.errors===!1)h(),e.modifying&&dO(t),y(()=>t.error());else{let g=e.async?f():m();e.modifying&&dO(t),y(()=>JB(t,g))}}function f(){let g=n.let("ruleErrs",null);return n.try(()=>h((0,Wr._)`await `),_=>n.assign(d,!1).if((0,Wr._)`${_} instanceof ${l.ValidationError}`,()=>n.assign(g,(0,Wr._)`${_}.errors`),()=>n.throw(_))),g}function m(){let g=(0,Wr._)`${u}.errors`;return n.assign(g,null),h(Wr.nil),g}function h(g=e.async?(0,Wr._)`await `:Wr.nil){let _=l.opts.passContext?Fa.default.this:Fa.default.self,b=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,Wr._)`${g}${(0,GB.callValidateCode)(t,u,_,b)}`,e.modifying)}function y(g){var _;n.if((0,Wr.not)((_=e.valid)!==null&&_!==void 0?_:d),g)}}Ui.funcKeywordCode=KB;function dO(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,Wr._)`${n.parentData}[${n.parentDataProperty}]`))}function JB(t,e){let{gen:r}=t;r.if((0,Wr._)`Array.isArray(${e})`,()=>{r.assign(Fa.default.vErrors,(0,Wr._)`${Fa.default.vErrors} === null ? ${e} : ${Fa.default.vErrors}.concat(${e})`).assign(Fa.default.errors,(0,Wr._)`${Fa.default.vErrors}.length`),(0,HB.extendErrors)(t)},()=>t.error())}function YB({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function fO(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,Wr.stringify)(r)})}function QB(t,e,r=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(t):n==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==n||r&&typeof t>"u")}Ui.validSchemaType=QB;function eG({schema:t,opts:e,self:r,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(t,a)))throw new Error(`parent schema must have dependencies of ${o}: ${s.join(",")}`);if(i.validateSchema&&!i.validateSchema(t[o])){let l=`keyword "${o}" value is invalid at path "${n}": `+r.errorsText(i.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(l);else throw new Error(l)}}Ui.validateKeywordUsage=eG});var hO=C(Is=>{"use strict";Object.defineProperty(Is,"__esModule",{value:!0});Is.extendSubschemaMode=Is.extendSubschemaData=Is.getSubschema=void 0;var Zi=Ne(),mO=et();function tG(t,{keyword:e,schemaProp:r,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=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,Zi._)`${t.schemaPath}${(0,Zi.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,Zi._)`${t.schemaPath}${(0,Zi.getProperty)(e)}${(0,Zi.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,mO.escapeFragment)(r)}`}}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')}Is.getSubschema=tG;function rG(t,e,{dataProp:r,dataPropType:n,data:i,dataTypes:o,propertyName:s}){if(i!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:c,dataPathArr:u,opts:d}=e,p=a.let("data",(0,Zi._)`${e.data}${(0,Zi.getProperty)(r)}`,!0);l(p),t.errorPath=(0,Zi.str)`${c}${(0,mO.getErrorPath)(r,n,d.jsPropertySyntax)}`,t.parentDataProperty=(0,Zi._)`${r}`,t.dataPathArr=[...u,t.parentDataProperty]}if(i!==void 0){let c=i instanceof Zi.Name?i:a.let("data",i,!0);l(c),s!==void 0&&(t.propertyName=s)}o&&(t.dataTypes=o);function l(c){t.data=c,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,c]}}Is.extendSubschemaData=rG;function nG(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:i,allErrors:o}){n!==void 0&&(t.compositeRule=n),i!==void 0&&(t.createErrors=i),o!==void 0&&(t.allErrors=o),t.jtdDiscriminator=e,t.jtdMetadata=r}Is.extendSubschemaMode=nG});var op=C(sn=>{"use strict";Object.defineProperty(sn,"__esModule",{value:!0});sn.getSchemaRefs=sn.resolveUrl=sn.normalizeId=sn._getFullPath=sn.getFullPath=sn.inlineRef=void 0;var iG=et(),oG=Tf(),sG=Bx(),aG=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function lG(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Rk(t):e?gO(t)<=e:!1}sn.inlineRef=lG;var cG=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Rk(t){for(let e in t){if(cG.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(Rk)||typeof r=="object"&&Rk(r))return!0}return!1}function gO(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!aG.has(r)&&(typeof t[r]=="object"&&(0,iG.eachItem)(t[r],n=>e+=gO(n)),e===1/0))return 1/0}return e}function yO(t,e="",r){r!==!1&&(e=yu(e));let n=t.parse(e);return vO(t,n)}sn.getFullPath=yO;function vO(t,e){return t.serialize(e).split("#")[0]+"#"}sn._getFullPath=vO;var uG=/#\/?$/;function yu(t){return t?t.replace(uG,""):""}sn.normalizeId=yu;function dG(t,e,r){return r=yu(r),t.resolve(e,r)}sn.resolveUrl=dG;var fG=/^[a-z_][-a-z0-9._]*$/i;function pG(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,i=yu(t[r]||e),o={"":i},s=yO(n,i,!1),a={},l=new Set;return sG(t,{allKeys:!0},(d,p,f,m)=>{if(m===void 0)return;let h=s+p,y=o[m];typeof d[r]=="string"&&(y=g.call(this,d[r])),_.call(this,d.$anchor),_.call(this,d.$dynamicAnchor),o[p]=y;function g(b){let E=this.opts.uriResolver.resolve;if(b=yu(y?E(y,b):b),l.has(b))throw u(b);l.add(b);let I=this.refs[b];return typeof I=="string"&&(I=this.refs[I]),typeof I=="object"?c(d,I.schema,b):b!==yu(h)&&(b[0]==="#"?(c(d,a[b],b),a[b]=d):this.refs[b]=h),b}function _(b){if(typeof b=="string"){if(!fG.test(b))throw new Error(`invalid anchor "${b}"`);g.call(this,`#${b}`)}}}),a;function c(d,p,f){if(p!==void 0&&!oG(d,p))throw u(f)}function u(d){return new Error(`reference "${d}" resolves to more than one schema`)}}sn.getSchemaRefs=pG});var lp=C(Es=>{"use strict";Object.defineProperty(Es,"__esModule",{value:!0});Es.getData=Es.KeywordCxt=Es.validateFunctionCode=void 0;var $O=tO(),_O=ip(),jk=Pk(),vy=ip(),mG=lO(),ap=pO(),Mk=hO(),ce=Ne(),$e=To(),hG=op(),Ao=et(),sp=rp();function gG(t){if(IO(t)&&(EO(t),SO(t))){_G(t);return}kO(t,()=>(0,$O.topBoolOrEmptySchema)(t))}Es.validateFunctionCode=gG;function kO({gen:t,validateName:e,schema:r,schemaEnv:n,opts:i},o){i.code.es5?t.func(e,(0,ce._)`${$e.default.data}, ${$e.default.valCxt}`,n.$async,()=>{t.code((0,ce._)`"use strict"; ${bO(r,i)}`),vG(t,i),t.code(o)}):t.func(e,(0,ce._)`${$e.default.data}, ${yG(i)}`,n.$async,()=>t.code(bO(r,i)).code(o))}function yG(t){return(0,ce._)`{${$e.default.instancePath}="", ${$e.default.parentData}, ${$e.default.parentDataProperty}, ${$e.default.rootData}=${$e.default.data}${t.dynamicRef?(0,ce._)`, ${$e.default.dynamicAnchors}={}`:ce.nil}}={}`}function vG(t,e){t.if($e.default.valCxt,()=>{t.var($e.default.instancePath,(0,ce._)`${$e.default.valCxt}.${$e.default.instancePath}`),t.var($e.default.parentData,(0,ce._)`${$e.default.valCxt}.${$e.default.parentData}`),t.var($e.default.parentDataProperty,(0,ce._)`${$e.default.valCxt}.${$e.default.parentDataProperty}`),t.var($e.default.rootData,(0,ce._)`${$e.default.valCxt}.${$e.default.rootData}`),e.dynamicRef&&t.var($e.default.dynamicAnchors,(0,ce._)`${$e.default.valCxt}.${$e.default.dynamicAnchors}`)},()=>{t.var($e.default.instancePath,(0,ce._)`""`),t.var($e.default.parentData,(0,ce._)`undefined`),t.var($e.default.parentDataProperty,(0,ce._)`undefined`),t.var($e.default.rootData,$e.default.data),e.dynamicRef&&t.var($e.default.dynamicAnchors,(0,ce._)`{}`)})}function _G(t){let{schema:e,opts:r,gen:n}=t;kO(t,()=>{r.$comment&&e.$comment&&TO(t),kG(t),n.let($e.default.vErrors,null),n.let($e.default.errors,0),r.unevaluated&&bG(t),PO(t),EG(t)})}function bG(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,ce._)`${r}.evaluated`),e.if((0,ce._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,ce._)`${t.evaluated}.props`,(0,ce._)`undefined`)),e.if((0,ce._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,ce._)`${t.evaluated}.items`,(0,ce._)`undefined`))}function bO(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,ce._)`/*# sourceURL=${r} */`:ce.nil}function wG(t,e){if(IO(t)&&(EO(t),SO(t))){xG(t,e);return}(0,$O.boolOrEmptySchema)(t,e)}function SO({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let r in t)if(e.RULES.all[r])return!0;return!1}function IO(t){return typeof t.schema!="boolean"}function xG(t,e){let{schema:r,gen:n,opts:i}=t;i.$comment&&r.$comment&&TO(t),SG(t),IG(t);let o=n.const("_errs",$e.default.errors);PO(t,o),n.var(e,(0,ce._)`${o} === ${$e.default.errors}`)}function EO(t){(0,Ao.checkUnknownRules)(t),$G(t)}function PO(t,e){if(t.opts.jtd)return wO(t,[],!1,e);let r=(0,_O.getSchemaTypes)(t.schema),n=(0,_O.coerceAndCheckDataType)(t,r);wO(t,r,!n,e)}function $G(t){let{schema:e,errSchemaPath:r,opts:n,self:i}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,Ao.schemaHasRulesButRef)(e,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function kG(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Ao.checkStrictMode)(t,"default is ignored in the schema root")}function SG(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,hG.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function IG(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function TO({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:i}){let o=r.$comment;if(i.$comment===!0)t.code((0,ce._)`${$e.default.self}.logger.log(${o})`);else if(typeof i.$comment=="function"){let s=(0,ce.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,ce._)`${$e.default.self}.opts.$comment(${o}, ${s}, ${a}.schema)`)}}function EG(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:i,opts:o}=t;r.$async?e.if((0,ce._)`${$e.default.errors} === 0`,()=>e.return($e.default.data),()=>e.throw((0,ce._)`new ${i}(${$e.default.vErrors})`)):(e.assign((0,ce._)`${n}.errors`,$e.default.vErrors),o.unevaluated&&PG(t),e.return((0,ce._)`${$e.default.errors} === 0`))}function PG({gen:t,evaluated:e,props:r,items:n}){r instanceof ce.Name&&t.assign((0,ce._)`${e}.props`,r),n instanceof ce.Name&&t.assign((0,ce._)`${e}.items`,n)}function wO(t,e,r,n){let{gen:i,schema:o,data:s,allErrors:a,opts:l,self:c}=t,{RULES:u}=c;if(o.$ref&&(l.ignoreKeywordsWithRef||!(0,Ao.schemaHasRulesButRef)(o,u))){i.block(()=>zO(t,"$ref",u.all.$ref.definition));return}l.jtd||TG(t,e),i.block(()=>{for(let p of u.rules)d(p);d(u.post)});function d(p){(0,jk.shouldUseGroup)(o,p)&&(p.type?(i.if((0,vy.checkDataType)(p.type,s,l.strictNumbers)),xO(t,p),e.length===1&&e[0]===p.type&&r&&(i.else(),(0,vy.reportTypeError)(t)),i.endIf()):xO(t,p),a||i.if((0,ce._)`${$e.default.errors} === ${n||0}`))}}function xO(t,e){let{gen:r,schema:n,opts:{useDefaults:i}}=t;i&&(0,mG.assignDefaults)(t,e.type),r.block(()=>{for(let o of e.rules)(0,jk.shouldUseRule)(n,o)&&zO(t,o.keyword,o.definition,e.type)})}function TG(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(AG(t,e),t.opts.allowUnionTypes||zG(t,e),CG(t,t.dataTypes))}function AG(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{AO(t.dataTypes,r)||Dk(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),OG(t,e)}}function zG(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Dk(t,"use allowUnionTypes to allow union type keyword")}function CG(t,e){let r=t.self.RULES.all;for(let n in r){let i=r[n];if(typeof i=="object"&&(0,jk.shouldUseRule)(t.schema,i)){let{type:o}=i.definition;o.length&&!o.some(s=>NG(e,s))&&Dk(t,`missing type "${o.join(",")}" for keyword "${n}"`)}}}function NG(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function AO(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function OG(t,e){let r=[];for(let n of t.dataTypes)AO(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function Dk(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,Ao.checkStrictMode)(t,e,t.opts.strictTypes)}var _y=class{constructor(e,r,n){if((0,ap.validateKeywordUsage)(e,r,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Ao.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",CO(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,ap.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",$e.default.errors))}result(e,r,n){this.failResult((0,ce.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,ce.not)(e),void 0,r)}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:r}=this;this.fail((0,ce._)`${r} !== undefined && (${(0,ce.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?sp.reportExtraError:sp.reportError)(this,this.def.error,r)}$dataError(){(0,sp.reportError)(this,this.def.$dataError||sp.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,sp.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=ce.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=ce.nil,r=ce.nil){if(!this.$data)return;let{gen:n,schemaCode:i,schemaType:o,def:s}=this;n.if((0,ce.or)((0,ce._)`${i} === undefined`,r)),e!==ce.nil&&n.assign(e,!0),(o.length||s.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==ce.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:i,it:o}=this;return(0,ce.or)(s(),a());function s(){if(n.length){if(!(r instanceof ce.Name))throw new Error("ajv implementation error");let l=Array.isArray(n)?n:[n];return(0,ce._)`${(0,vy.checkDataTypes)(l,r,o.opts.strictNumbers,vy.DataType.Wrong)}`}return ce.nil}function a(){if(i.validateSchema){let l=e.scopeValue("validate$data",{ref:i.validateSchema});return(0,ce._)`!${l}(${r})`}return ce.nil}}subschema(e,r){let n=(0,Mk.getSubschema)(this.it,e);(0,Mk.extendSubschemaData)(n,this.it,e),(0,Mk.extendSubschemaMode)(n,e);let i={...this.it,...n,items:void 0,props:void 0};return wG(i,r),i}mergeEvaluated(e,r){let{it:n,gen:i}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Ao.mergeEvaluated.props(i,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=Ao.mergeEvaluated.items(i,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:i}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return i.if(r,()=>this.mergeEvaluated(e,ce.Name)),!0}};Es.KeywordCxt=_y;function zO(t,e,r,n){let i=new _y(t,r,e);"code"in r?r.code(i,n):i.$data&&r.validate?(0,ap.funcKeywordCode)(i,r):"macro"in r?(0,ap.macroKeywordCode)(i,r):(r.compile||r.validate)&&(0,ap.funcKeywordCode)(i,r)}var RG=/^\/(?:[^~]|~0|~1)*$/,MG=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function CO(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let i,o;if(t==="")return $e.default.rootData;if(t[0]==="/"){if(!RG.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);i=t,o=$e.default.rootData}else{let c=MG.exec(t);if(!c)throw new Error(`Invalid JSON-pointer: ${t}`);let u=+c[1];if(i=c[2],i==="#"){if(u>=e)throw new Error(l("property/index",u));return n[e-u]}if(u>e)throw new Error(l("data",u));if(o=r[e-u],!i)return o}let s=o,a=i.split("/");for(let c of a)c&&(o=(0,ce._)`${o}${(0,ce.getProperty)((0,Ao.unescapeJsonPointer)(c))}`,s=(0,ce._)`${s} && ${o}`);return s;function l(c,u){return`Cannot access ${c} ${u} levels up, current level is ${e}`}}Es.getData=CO});var by=C(Uk=>{"use strict";Object.defineProperty(Uk,"__esModule",{value:!0});var Lk=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Uk.default=Lk});var wy=C(Vk=>{"use strict";Object.defineProperty(Vk,"__esModule",{value:!0});var Zk=op(),Fk=class extends Error{constructor(e,r,n,i){super(i||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Zk.resolveUrl)(e,r,n),this.missingSchema=(0,Zk.normalizeId)((0,Zk.getFullPath)(e,this.missingRef))}};Vk.default=Fk});var $y=C(Vn=>{"use strict";Object.defineProperty(Vn,"__esModule",{value:!0});Vn.resolveSchema=Vn.getCompilingSchema=Vn.resolveRef=Vn.compileSchema=Vn.SchemaEnv=void 0;var fi=Ne(),jG=by(),Va=To(),pi=op(),NO=et(),DG=lp(),vu=class{constructor(e){var r;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=(r=e.baseId)!==null&&r!==void 0?r:(0,pi.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};Vn.SchemaEnv=vu;function Wk(t){let e=OO.call(this,t);if(e)return e;let r=(0,pi.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:i}=this.opts.code,{ownProperties:o}=this.opts,s=new fi.CodeGen(this.scope,{es5:n,lines:i,ownProperties:o}),a;t.$async&&(a=s.scopeValue("Error",{ref:jG.default,code:(0,fi._)`require("ajv/dist/runtime/validation_error").default`}));let l=s.scopeName("validate");t.validateName=l;let c={gen:s,allErrors:this.opts.allErrors,data:Va.default.data,parentData:Va.default.parentData,parentDataProperty:Va.default.parentDataProperty,dataNames:[Va.default.data],dataPathArr:[fi.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,fi.stringify)(t.schema)}:{ref:t.schema}),validateName:l,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:fi.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,fi._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(t),(0,DG.validateFunctionCode)(c),s.optimize(this.opts.code.optimize);let d=s.toString();u=`${s.scopeRefs(Va.default.scope)}return ${d}`,this.opts.code.process&&(u=this.opts.code.process(u,t));let f=new Function(`${Va.default.self}`,`${Va.default.scope}`,u)(this,this.scope.get());if(this.scope.value(l,{ref:f}),f.errors=null,f.schema=t.schema,f.schemaEnv=t,t.$async&&(f.$async=!0),this.opts.code.source===!0&&(f.source={validateName:l,validateCode:d,scopeValues:s._values}),this.opts.unevaluated){let{props:m,items:h}=c;f.evaluated={props:m instanceof fi.Name?void 0:m,items:h instanceof fi.Name?void 0:h,dynamicProps:m instanceof fi.Name,dynamicItems:h instanceof fi.Name},f.source&&(f.source.evaluated=(0,fi.stringify)(f.evaluated))}return t.validate=f,t}catch(d){throw delete t.validate,delete t.validateName,u&&this.logger.error("Error compiling schema, function code:",u),d}finally{this._compilations.delete(t)}}Vn.compileSchema=Wk;function LG(t,e,r){var n;r=(0,pi.resolveUrl)(this.opts.uriResolver,e,r);let i=t.refs[r];if(i)return i;let o=FG.call(this,t,r);if(o===void 0){let s=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;s&&(o=new vu({schema:s,schemaId:a,root:t,baseId:e}))}if(o!==void 0)return t.refs[r]=UG.call(this,o)}Vn.resolveRef=LG;function UG(t){return(0,pi.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Wk.call(this,t)}function OO(t){for(let e of this._compilations)if(ZG(e,t))return e}Vn.getCompilingSchema=OO;function ZG(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function FG(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||xy.call(this,t,e)}function xy(t,e){let r=this.opts.uriResolver.parse(e),n=(0,pi._getFullPath)(this.opts.uriResolver,r),i=(0,pi.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===i)return qk.call(this,r,t);let o=(0,pi.normalizeId)(n),s=this.refs[o]||this.schemas[o];if(typeof s=="string"){let a=xy.call(this,t,s);return typeof a?.schema!="object"?void 0:qk.call(this,r,a)}if(typeof s?.schema=="object"){if(s.validate||Wk.call(this,s),o===(0,pi.normalizeId)(e)){let{schema:a}=s,{schemaId:l}=this.opts,c=a[l];return c&&(i=(0,pi.resolveUrl)(this.opts.uriResolver,i,c)),new vu({schema:a,schemaId:l,root:t,baseId:i})}return qk.call(this,r,s)}}Vn.resolveSchema=xy;var VG=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function qk(t,{baseId:e,schema:r,root:n}){var i;if(((i=t.fragment)===null||i===void 0?void 0:i[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let l=r[(0,NO.unescapeFragment)(a)];if(l===void 0)return;r=l;let c=typeof r=="object"&&r[this.opts.schemaId];!VG.has(a)&&c&&(e=(0,pi.resolveUrl)(this.opts.uriResolver,e,c))}let o;if(typeof r!="boolean"&&r.$ref&&!(0,NO.schemaHasRulesButRef)(r,this.RULES)){let a=(0,pi.resolveUrl)(this.opts.uriResolver,e,r.$ref);o=xy.call(this,n,a)}let{schemaId:s}=this.opts;if(o=o||new vu({schema:r,schemaId:s,root:n,baseId:e}),o.schema!==o.root.schema)return o}});var RO=C((Nbe,qG)=>{qG.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 jO=C((ky,MO)=>{"use strict";(function(t,e){typeof ky=="object"&&typeof MO<"u"?e(ky):typeof define=="function"&&define.amd?define(["exports"],e):e(t.URI=t.URI||{})})(ky,function(t){"use strict";function e(){for(var w=arguments.length,v=Array(w),S=0;S<w;S++)v[S]=arguments[S];if(v.length>1){v[0]=v[0].slice(0,-1);for(var A=v.length-1,z=1;z<A;++z)v[z]=v[z].slice(1,-1);return v[A]=v[A].slice(1),v.join("")}else return v[0]}function r(w){return"(?:"+w+")"}function n(w){return w===void 0?"undefined":w===null?"null":Object.prototype.toString.call(w).split(" ").pop().split("]").shift().toLowerCase()}function i(w){return w.toUpperCase()}function o(w){return w!=null?w instanceof Array?w:typeof w.length!="number"||w.split||w.setInterval||w.call?[w]:Array.prototype.slice.call(w):[]}function s(w,v){var S=w;if(v)for(var A in v)S[A]=v[A];return S}function a(w){var v="[A-Za-z]",S="[\\x0D]",A="[0-9]",z="[\\x22]",re=e(A,"[A-Fa-f]"),Te="[\\x0A]",Ke="[\\x20]",ot=r(r("%[EFef]"+re+"%"+re+re+"%"+re+re)+"|"+r("%[89A-Fa-f]"+re+"%"+re+re)+"|"+r("%"+re+re)),Wt="[\\:\\/\\?\\#\\[\\]\\@]",Ge="[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",Tt=e(Wt,Ge),Bt=w?"[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]":"[]",St=w?"[\\uE000-\\uF8FF]":"[]",tt=e(v,A,"[\\-\\.\\_\\~]",Bt),At=r(v+e(v,A,"[\\+\\-\\.]")+"*"),ct=r(r(ot+"|"+e(tt,Ge,"[\\:]"))+"*"),Ls=r(r("25[0-5]")+"|"+r("2[0-4]"+A)+"|"+r("1"+A+A)+"|"+r("[1-9]"+A)+"|"+A),fn=r(r("25[0-5]")+"|"+r("2[0-4]"+A)+"|"+r("1"+A+A)+"|"+r("0?[1-9]"+A)+"|0?0?"+A),An=r(fn+"\\."+fn+"\\."+fn+"\\."+fn),pt=r(re+"{1,4}"),pn=r(r(pt+"\\:"+pt)+"|"+An),zn=r(r(pt+"\\:")+"{6}"+pn),_i=r("\\:\\:"+r(pt+"\\:")+"{5}"+pn),Us=r(r(pt)+"?\\:\\:"+r(pt+"\\:")+"{4}"+pn),Ki=r(r(r(pt+"\\:")+"{0,1}"+pt)+"?\\:\\:"+r(pt+"\\:")+"{3}"+pn),Xu=r(r(r(pt+"\\:")+"{0,2}"+pt)+"?\\:\\:"+r(pt+"\\:")+"{2}"+pn),$m=r(r(r(pt+"\\:")+"{0,3}"+pt)+"?\\:\\:"+pt+"\\:"+pn),km=r(r(r(pt+"\\:")+"{0,4}"+pt)+"?\\:\\:"+pn),cl=r(r(r(pt+"\\:")+"{0,5}"+pt)+"?\\:\\:"+pt),ul=r(r(r(pt+"\\:")+"{0,6}"+pt)+"?\\:\\:"),Ji=r([zn,_i,Us,Ki,Xu,$m,km,cl,ul].join("|")),dl=r(r(tt+"|"+ot)+"+"),e_=r(Ji+"\\%25"+dl),Zs=r(Ji+r("\\%25|\\%(?!"+re+"{2})")+dl),QD=r("[vV]"+re+"+\\."+e(tt,Ge,"[\\:]")+"+"),e4=r("\\["+r(Zs+"|"+Ji+"|"+QD)+"\\]"),hE=r(r(ot+"|"+e(tt,Ge))+"*"),Ku=r(e4+"|"+An+"(?!"+hE+")|"+hE),Ju=r(A+"*"),gE=r(r(ct+"@")+"?"+Ku+r("\\:"+Ju)+"?"),Yu=r(ot+"|"+e(tt,Ge,"[\\:\\@]")),t4=r(Yu+"*"),yE=r(Yu+"+"),r4=r(r(ot+"|"+e(tt,Ge,"[\\@]"))+"+"),Yi=r(r("\\/"+t4)+"*"),fl=r("\\/"+r(yE+Yi)+"?"),t_=r(r4+Yi),Sm=r(yE+Yi),pl="(?!"+Yu+")",VY=r(Yi+"|"+fl+"|"+t_+"|"+Sm+"|"+pl),ml=r(r(Yu+"|"+e("[\\/\\?]",St))+"*"),Qu=r(r(Yu+"|[\\/\\?]")+"*"),vE=r(r("\\/\\/"+gE+Yi)+"|"+fl+"|"+Sm+"|"+pl),n4=r(At+"\\:"+vE+r("\\?"+ml)+"?"+r("\\#"+Qu)+"?"),i4=r(r("\\/\\/"+gE+Yi)+"|"+fl+"|"+t_+"|"+pl),o4=r(i4+r("\\?"+ml)+"?"+r("\\#"+Qu)+"?"),qY=r(n4+"|"+o4),WY=r(At+"\\:"+vE+r("\\?"+ml)+"?"),BY="^("+At+")\\:"+r(r("\\/\\/("+r("("+ct+")@")+"?("+Ku+")"+r("\\:("+Ju+")")+"?)")+"?("+Yi+"|"+fl+"|"+Sm+"|"+pl+")")+r("\\?("+ml+")")+"?"+r("\\#("+Qu+")")+"?$",GY="^(){0}"+r(r("\\/\\/("+r("("+ct+")@")+"?("+Ku+")"+r("\\:("+Ju+")")+"?)")+"?("+Yi+"|"+fl+"|"+t_+"|"+pl+")")+r("\\?("+ml+")")+"?"+r("\\#("+Qu+")")+"?$",HY="^("+At+")\\:"+r(r("\\/\\/("+r("("+ct+")@")+"?("+Ku+")"+r("\\:("+Ju+")")+"?)")+"?("+Yi+"|"+fl+"|"+Sm+"|"+pl+")")+r("\\?("+ml+")")+"?$",XY="^"+r("\\#("+Qu+")")+"?$",KY="^"+r("("+ct+")@")+"?("+Ku+")"+r("\\:("+Ju+")")+"?$";return{NOT_SCHEME:new RegExp(e("[^]",v,A,"[\\+\\-\\.]"),"g"),NOT_USERINFO:new RegExp(e("[^\\%\\:]",tt,Ge),"g"),NOT_HOST:new RegExp(e("[^\\%\\[\\]\\:]",tt,Ge),"g"),NOT_PATH:new RegExp(e("[^\\%\\/\\:\\@]",tt,Ge),"g"),NOT_PATH_NOSCHEME:new RegExp(e("[^\\%\\/\\@]",tt,Ge),"g"),NOT_QUERY:new RegExp(e("[^\\%]",tt,Ge,"[\\:\\@\\/\\?]",St),"g"),NOT_FRAGMENT:new RegExp(e("[^\\%]",tt,Ge,"[\\:\\@\\/\\?]"),"g"),ESCAPE:new RegExp(e("[^]",tt,Ge),"g"),UNRESERVED:new RegExp(tt,"g"),OTHER_CHARS:new RegExp(e("[^\\%]",tt,Tt),"g"),PCT_ENCODED:new RegExp(ot,"g"),IPV4ADDRESS:new RegExp("^("+An+")$"),IPV6ADDRESS:new RegExp("^\\[?("+Ji+")"+r(r("\\%25|\\%(?!"+re+"{2})")+"("+dl+")")+"?\\]?$")}}var l=a(!1),c=a(!0),u=function(){function w(v,S){var A=[],z=!0,re=!1,Te=void 0;try{for(var Ke=v[Symbol.iterator](),ot;!(z=(ot=Ke.next()).done)&&(A.push(ot.value),!(S&&A.length===S));z=!0);}catch(Wt){re=!0,Te=Wt}finally{try{!z&&Ke.return&&Ke.return()}finally{if(re)throw Te}}return A}return function(v,S){if(Array.isArray(v))return v;if(Symbol.iterator in Object(v))return w(v,S);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),d=function(w){if(Array.isArray(w)){for(var v=0,S=Array(w.length);v<w.length;v++)S[v]=w[v];return S}else return Array.from(w)},p=2147483647,f=36,m=1,h=26,y=38,g=700,_=72,b=128,E="-",I=/^xn--/,P=/[^\0-\x7E]/,M=/[\x2E\u3002\uFF0E\uFF61]/g,V={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},R=f-m,L=Math.floor,G=String.fromCharCode;function H(w){throw new RangeError(V[w])}function W(w,v){for(var S=[],A=w.length;A--;)S[A]=v(w[A]);return S}function Y(w,v){var S=w.split("@"),A="";S.length>1&&(A=S[0]+"@",w=S[1]),w=w.replace(M,".");var z=w.split("."),re=W(z,v).join(".");return A+re}function ie(w){for(var v=[],S=0,A=w.length;S<A;){var z=w.charCodeAt(S++);if(z>=55296&&z<=56319&&S<A){var re=w.charCodeAt(S++);(re&64512)==56320?v.push(((z&1023)<<10)+(re&1023)+65536):(v.push(z),S--)}else v.push(z)}return v}var Ve=function(v){return String.fromCodePoint.apply(String,d(v))},it=function(v){return v-48<10?v-22:v-65<26?v-65:v-97<26?v-97:f},Ot=function(v,S){return v+22+75*(v<26)-((S!=0)<<5)},Pt=function(v,S,A){var z=0;for(v=A?L(v/g):v>>1,v+=L(v/S);v>R*h>>1;z+=f)v=L(v/R);return L(z+(R+1)*v/(v+y))},x=function(v){var S=[],A=v.length,z=0,re=b,Te=_,Ke=v.lastIndexOf(E);Ke<0&&(Ke=0);for(var ot=0;ot<Ke;++ot)v.charCodeAt(ot)>=128&&H("not-basic"),S.push(v.charCodeAt(ot));for(var Wt=Ke>0?Ke+1:0;Wt<A;){for(var Ge=z,Tt=1,Bt=f;;Bt+=f){Wt>=A&&H("invalid-input");var St=it(v.charCodeAt(Wt++));(St>=f||St>L((p-z)/Tt))&&H("overflow"),z+=St*Tt;var tt=Bt<=Te?m:Bt>=Te+h?h:Bt-Te;if(St<tt)break;var At=f-tt;Tt>L(p/At)&&H("overflow"),Tt*=At}var ct=S.length+1;Te=Pt(z-Ge,ct,Ge==0),L(z/ct)>p-re&&H("overflow"),re+=L(z/ct),z%=ct,S.splice(z++,0,re)}return String.fromCodePoint.apply(String,S)},Dr=function(v){var S=[];v=ie(v);var A=v.length,z=b,re=0,Te=_,Ke=!0,ot=!1,Wt=void 0;try{for(var Ge=v[Symbol.iterator](),Tt;!(Ke=(Tt=Ge.next()).done);Ke=!0){var Bt=Tt.value;Bt<128&&S.push(G(Bt))}}catch(Zs){ot=!0,Wt=Zs}finally{try{!Ke&&Ge.return&&Ge.return()}finally{if(ot)throw Wt}}var St=S.length,tt=St;for(St&&S.push(E);tt<A;){var At=p,ct=!0,Ls=!1,fn=void 0;try{for(var An=v[Symbol.iterator](),pt;!(ct=(pt=An.next()).done);ct=!0){var pn=pt.value;pn>=z&&pn<At&&(At=pn)}}catch(Zs){Ls=!0,fn=Zs}finally{try{!ct&&An.return&&An.return()}finally{if(Ls)throw fn}}var zn=tt+1;At-z>L((p-re)/zn)&&H("overflow"),re+=(At-z)*zn,z=At;var _i=!0,Us=!1,Ki=void 0;try{for(var Xu=v[Symbol.iterator](),$m;!(_i=($m=Xu.next()).done);_i=!0){var km=$m.value;if(km<z&&++re>p&&H("overflow"),km==z){for(var cl=re,ul=f;;ul+=f){var Ji=ul<=Te?m:ul>=Te+h?h:ul-Te;if(cl<Ji)break;var dl=cl-Ji,e_=f-Ji;S.push(G(Ot(Ji+dl%e_,0))),cl=L(dl/e_)}S.push(G(Ot(cl,0))),Te=Pt(re,zn,tt==St),re=0,++tt}}}catch(Zs){Us=!0,Ki=Zs}finally{try{!_i&&Xu.return&&Xu.return()}finally{if(Us)throw Ki}}++re,++z}return S.join("")},Hn=function(v){return Y(v,function(S){return I.test(S)?x(S.slice(4).toLowerCase()):S})},k=function(v){return Y(v,function(S){return P.test(S)?"xn--"+Dr(S):S})},Vt={version:"2.1.0",ucs2:{decode:ie,encode:Ve},decode:x,encode:Dr,toASCII:k,toUnicode:Hn},qt={};function Xr(w){var v=w.charCodeAt(0),S=void 0;return v<16?S="%0"+v.toString(16).toUpperCase():v<128?S="%"+v.toString(16).toUpperCase():v<2048?S="%"+(v>>6|192).toString(16).toUpperCase()+"%"+(v&63|128).toString(16).toUpperCase():S="%"+(v>>12|224).toString(16).toUpperCase()+"%"+(v>>6&63|128).toString(16).toUpperCase()+"%"+(v&63|128).toString(16).toUpperCase(),S}function Xn(w){for(var v="",S=0,A=w.length;S<A;){var z=parseInt(w.substr(S+1,2),16);if(z<128)v+=String.fromCharCode(z),S+=3;else if(z>=194&&z<224){if(A-S>=6){var re=parseInt(w.substr(S+4,2),16);v+=String.fromCharCode((z&31)<<6|re&63)}else v+=w.substr(S,6);S+=6}else if(z>=224){if(A-S>=9){var Te=parseInt(w.substr(S+4,2),16),Ke=parseInt(w.substr(S+7,2),16);v+=String.fromCharCode((z&15)<<12|(Te&63)<<6|Ke&63)}else v+=w.substr(S,9);S+=9}else v+=w.substr(S,3),S+=3}return v}function Rt(w,v){function S(A){var z=Xn(A);return z.match(v.UNRESERVED)?z:A}return w.scheme&&(w.scheme=String(w.scheme).replace(v.PCT_ENCODED,S).toLowerCase().replace(v.NOT_SCHEME,"")),w.userinfo!==void 0&&(w.userinfo=String(w.userinfo).replace(v.PCT_ENCODED,S).replace(v.NOT_USERINFO,Xr).replace(v.PCT_ENCODED,i)),w.host!==void 0&&(w.host=String(w.host).replace(v.PCT_ENCODED,S).toLowerCase().replace(v.NOT_HOST,Xr).replace(v.PCT_ENCODED,i)),w.path!==void 0&&(w.path=String(w.path).replace(v.PCT_ENCODED,S).replace(w.scheme?v.NOT_PATH:v.NOT_PATH_NOSCHEME,Xr).replace(v.PCT_ENCODED,i)),w.query!==void 0&&(w.query=String(w.query).replace(v.PCT_ENCODED,S).replace(v.NOT_QUERY,Xr).replace(v.PCT_ENCODED,i)),w.fragment!==void 0&&(w.fragment=String(w.fragment).replace(v.PCT_ENCODED,S).replace(v.NOT_FRAGMENT,Xr).replace(v.PCT_ENCODED,i)),w}function Hi(w){return w.replace(/^0*(.*)/,"$1")||"0"}function Kr(w,v){var S=w.match(v.IPV4ADDRESS)||[],A=u(S,2),z=A[1];return z?z.split(".").map(Hi).join("."):w}function Xi(w,v){var S=w.match(v.IPV6ADDRESS)||[],A=u(S,3),z=A[1],re=A[2];if(z){for(var Te=z.toLowerCase().split("::").reverse(),Ke=u(Te,2),ot=Ke[0],Wt=Ke[1],Ge=Wt?Wt.split(":").map(Hi):[],Tt=ot.split(":").map(Hi),Bt=v.IPV4ADDRESS.test(Tt[Tt.length-1]),St=Bt?7:8,tt=Tt.length-St,At=Array(St),ct=0;ct<St;++ct)At[ct]=Ge[ct]||Tt[tt+ct]||"";Bt&&(At[St-1]=Kr(At[St-1],v));var Ls=At.reduce(function(zn,_i,Us){if(!_i||_i==="0"){var Ki=zn[zn.length-1];Ki&&Ki.index+Ki.length===Us?Ki.length++:zn.push({index:Us,length:1})}return zn},[]),fn=Ls.sort(function(zn,_i){return _i.length-zn.length})[0],An=void 0;if(fn&&fn.length>1){var pt=At.slice(0,fn.index),pn=At.slice(fn.index+fn.length);An=pt.join(":")+"::"+pn.join(":")}else An=At.join(":");return re&&(An+="%"+re),An}else return w}var jo=/^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i,Bu="".match(/(){0}/)[1]===void 0;function En(w){var v=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},S={},A=v.iri!==!1?c:l;v.reference==="suffix"&&(w=(v.scheme?v.scheme+":":"")+"//"+w);var z=w.match(jo);if(z){Bu?(S.scheme=z[1],S.userinfo=z[3],S.host=z[4],S.port=parseInt(z[5],10),S.path=z[6]||"",S.query=z[7],S.fragment=z[8],isNaN(S.port)&&(S.port=z[5])):(S.scheme=z[1]||void 0,S.userinfo=w.indexOf("@")!==-1?z[3]:void 0,S.host=w.indexOf("//")!==-1?z[4]:void 0,S.port=parseInt(z[5],10),S.path=z[6]||"",S.query=w.indexOf("?")!==-1?z[7]:void 0,S.fragment=w.indexOf("#")!==-1?z[8]:void 0,isNaN(S.port)&&(S.port=w.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/)?z[4]:void 0)),S.host&&(S.host=Xi(Kr(S.host,A),A)),S.scheme===void 0&&S.userinfo===void 0&&S.host===void 0&&S.port===void 0&&!S.path&&S.query===void 0?S.reference="same-document":S.scheme===void 0?S.reference="relative":S.fragment===void 0?S.reference="absolute":S.reference="uri",v.reference&&v.reference!=="suffix"&&v.reference!==S.reference&&(S.error=S.error||"URI is not a "+v.reference+" reference.");var re=qt[(v.scheme||S.scheme||"").toLowerCase()];if(!v.unicodeSupport&&(!re||!re.unicodeSupport)){if(S.host&&(v.domainHost||re&&re.domainHost))try{S.host=Vt.toASCII(S.host.replace(A.PCT_ENCODED,Xn).toLowerCase())}catch(Te){S.error=S.error||"Host's domain name can not be converted to ASCII via punycode: "+Te}Rt(S,l)}else Rt(S,A);re&&re.parse&&re.parse(S,v)}else S.error=S.error||"URI can not be parsed.";return S}function _m(w,v){var S=v.iri!==!1?c:l,A=[];return w.userinfo!==void 0&&(A.push(w.userinfo),A.push("@")),w.host!==void 0&&A.push(Xi(Kr(String(w.host),S),S).replace(S.IPV6ADDRESS,function(z,re,Te){return"["+re+(Te?"%25"+Te:"")+"]"})),(typeof w.port=="number"||typeof w.port=="string")&&(A.push(":"),A.push(String(w.port))),A.length?A.join(""):void 0}var Gu=/^\.\.?\//,bm=/^\/\.(\/|$)/,Hu=/^\/\.\.(\/|$)/,wm=/^\/?(?:.|\n)*?(?=\/|$)/;function Do(w){for(var v=[];w.length;)if(w.match(Gu))w=w.replace(Gu,"");else if(w.match(bm))w=w.replace(bm,"/");else if(w.match(Hu))w=w.replace(Hu,"/"),v.pop();else if(w==="."||w==="..")w="";else{var S=w.match(wm);if(S){var A=S[0];w=w.slice(A.length),v.push(A)}else throw new Error("Unexpected dot segment condition")}return v.join("")}function Pn(w){var v=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},S=v.iri?c:l,A=[],z=qt[(v.scheme||w.scheme||"").toLowerCase()];if(z&&z.serialize&&z.serialize(w,v),w.host&&!S.IPV6ADDRESS.test(w.host)){if(v.domainHost||z&&z.domainHost)try{w.host=v.iri?Vt.toUnicode(w.host):Vt.toASCII(w.host.replace(S.PCT_ENCODED,Xn).toLowerCase())}catch(Ke){w.error=w.error||"Host's domain name can not be converted to "+(v.iri?"Unicode":"ASCII")+" via punycode: "+Ke}}Rt(w,S),v.reference!=="suffix"&&w.scheme&&(A.push(w.scheme),A.push(":"));var re=_m(w,v);if(re!==void 0&&(v.reference!=="suffix"&&A.push("//"),A.push(re),w.path&&w.path.charAt(0)!=="/"&&A.push("/")),w.path!==void 0){var Te=w.path;!v.absolutePath&&(!z||!z.absolutePath)&&(Te=Do(Te)),re===void 0&&(Te=Te.replace(/^\/\//,"/%2F")),A.push(Te)}return w.query!==void 0&&(A.push("?"),A.push(w.query)),w.fragment!==void 0&&(A.push("#"),A.push(w.fragment)),A.join("")}function xm(w,v){var S=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},A=arguments[3],z={};return A||(w=En(Pn(w,S),S),v=En(Pn(v,S),S)),S=S||{},!S.tolerant&&v.scheme?(z.scheme=v.scheme,z.userinfo=v.userinfo,z.host=v.host,z.port=v.port,z.path=Do(v.path||""),z.query=v.query):(v.userinfo!==void 0||v.host!==void 0||v.port!==void 0?(z.userinfo=v.userinfo,z.host=v.host,z.port=v.port,z.path=Do(v.path||""),z.query=v.query):(v.path?(v.path.charAt(0)==="/"?z.path=Do(v.path):((w.userinfo!==void 0||w.host!==void 0||w.port!==void 0)&&!w.path?z.path="/"+v.path:w.path?z.path=w.path.slice(0,w.path.lastIndexOf("/")+1)+v.path:z.path=v.path,z.path=Do(z.path)),z.query=v.query):(z.path=w.path,v.query!==void 0?z.query=v.query:z.query=w.query),z.userinfo=w.userinfo,z.host=w.host,z.port=w.port),z.scheme=w.scheme),z.fragment=v.fragment,z}function Jv(w,v,S){var A=s({scheme:"null"},S);return Pn(xm(En(w,A),En(v,A),A,!0),A)}function Yv(w,v){return typeof w=="string"?w=Pn(En(w,v),v):n(w)==="object"&&(w=En(Pn(w,v),v)),w}function j(w,v,S){return typeof w=="string"?w=Pn(En(w,S),S):n(w)==="object"&&(w=Pn(w,S)),typeof v=="string"?v=Pn(En(v,S),S):n(v)==="object"&&(v=Pn(v,S)),w===v}function K(w,v){return w&&w.toString().replace(!v||!v.iri?l.ESCAPE:c.ESCAPE,Xr)}function fe(w,v){return w&&w.toString().replace(!v||!v.iri?l.PCT_ENCODED:c.PCT_ENCODED,Xn)}var Pe={scheme:"http",domainHost:!0,parse:function(v,S){return v.host||(v.error=v.error||"HTTP URIs must have a host."),v},serialize:function(v,S){var A=String(v.scheme).toLowerCase()==="https";return(v.port===(A?443:80)||v.port==="")&&(v.port=void 0),v.path||(v.path="/"),v}},nt={scheme:"https",domainHost:Pe.domainHost,parse:Pe.parse,serialize:Pe.serialize};function Jr(w){return typeof w.secure=="boolean"?w.secure:String(w.scheme).toLowerCase()==="wss"}var dn={scheme:"ws",domainHost:!0,parse:function(v,S){var A=v;return A.secure=Jr(A),A.resourceName=(A.path||"/")+(A.query?"?"+A.query:""),A.path=void 0,A.query=void 0,A},serialize:function(v,S){if((v.port===(Jr(v)?443:80)||v.port==="")&&(v.port=void 0),typeof v.secure=="boolean"&&(v.scheme=v.secure?"wss":"ws",v.secure=void 0),v.resourceName){var A=v.resourceName.split("?"),z=u(A,2),re=z[0],Te=z[1];v.path=re&&re!=="/"?re:void 0,v.query=Te,v.resourceName=void 0}return v.fragment=void 0,v}},Tn={scheme:"wss",domainHost:dn.domainHost,parse:dn.parse,serialize:dn.serialize},js={},Ds=!0,$r="[A-Za-z0-9\\-\\.\\_\\~"+(Ds?"\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF":"")+"]",lr="[0-9A-Fa-f]",Kn=r(r("%[EFef]"+lr+"%"+lr+lr+"%"+lr+lr)+"|"+r("%[89A-Fa-f]"+lr+"%"+lr+lr)+"|"+r("%"+lr+lr)),qD="[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]",WD="[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]",BD=e(WD,'[\\"\\\\]'),GD="[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]",HD=new RegExp($r,"g"),ll=new RegExp(Kn,"g"),XD=new RegExp(e("[^]",qD,"[\\.]",'[\\"]',BD),"g"),dE=new RegExp(e("[^]",$r,GD),"g"),KD=dE;function Qv(w){var v=Xn(w);return v.match(HD)?v:w}var fE={scheme:"mailto",parse:function(v,S){var A=v,z=A.to=A.path?A.path.split(","):[];if(A.path=void 0,A.query){for(var re=!1,Te={},Ke=A.query.split("&"),ot=0,Wt=Ke.length;ot<Wt;++ot){var Ge=Ke[ot].split("=");switch(Ge[0]){case"to":for(var Tt=Ge[1].split(","),Bt=0,St=Tt.length;Bt<St;++Bt)z.push(Tt[Bt]);break;case"subject":A.subject=fe(Ge[1],S);break;case"body":A.body=fe(Ge[1],S);break;default:re=!0,Te[fe(Ge[0],S)]=fe(Ge[1],S);break}}re&&(A.headers=Te)}A.query=void 0;for(var tt=0,At=z.length;tt<At;++tt){var ct=z[tt].split("@");if(ct[0]=fe(ct[0]),S.unicodeSupport)ct[1]=fe(ct[1],S).toLowerCase();else try{ct[1]=Vt.toASCII(fe(ct[1],S).toLowerCase())}catch(Ls){A.error=A.error||"Email address's domain name can not be converted to ASCII via punycode: "+Ls}z[tt]=ct.join("@")}return A},serialize:function(v,S){var A=v,z=o(v.to);if(z){for(var re=0,Te=z.length;re<Te;++re){var Ke=String(z[re]),ot=Ke.lastIndexOf("@"),Wt=Ke.slice(0,ot).replace(ll,Qv).replace(ll,i).replace(XD,Xr),Ge=Ke.slice(ot+1);try{Ge=S.iri?Vt.toUnicode(Ge):Vt.toASCII(fe(Ge,S).toLowerCase())}catch(tt){A.error=A.error||"Email address's domain name can not be converted to "+(S.iri?"Unicode":"ASCII")+" via punycode: "+tt}z[re]=Wt+"@"+Ge}A.path=z.join(",")}var Tt=v.headers=v.headers||{};v.subject&&(Tt.subject=v.subject),v.body&&(Tt.body=v.body);var Bt=[];for(var St in Tt)Tt[St]!==js[St]&&Bt.push(St.replace(ll,Qv).replace(ll,i).replace(dE,Xr)+"="+Tt[St].replace(ll,Qv).replace(ll,i).replace(KD,Xr));return Bt.length&&(A.query=Bt.join("&")),A}},JD=/^([^\:]+)\:(.*)/,pE={scheme:"urn",parse:function(v,S){var A=v.path&&v.path.match(JD),z=v;if(A){var re=S.scheme||z.scheme||"urn",Te=A[1].toLowerCase(),Ke=A[2],ot=re+":"+(S.nid||Te),Wt=qt[ot];z.nid=Te,z.nss=Ke,z.path=void 0,Wt&&(z=Wt.parse(z,S))}else z.error=z.error||"URN can not be parsed.";return z},serialize:function(v,S){var A=S.scheme||v.scheme||"urn",z=v.nid,re=A+":"+(S.nid||z),Te=qt[re];Te&&(v=Te.serialize(v,S));var Ke=v,ot=v.nss;return Ke.path=(z||S.nid)+":"+ot,Ke}},YD=/^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/,mE={scheme:"urn:uuid",parse:function(v,S){var A=v;return A.uuid=A.nss,A.nss=void 0,!S.tolerant&&(!A.uuid||!A.uuid.match(YD))&&(A.error=A.error||"UUID is not valid."),A},serialize:function(v,S){var A=v;return A.nss=(v.uuid||"").toLowerCase(),A}};qt[Pe.scheme]=Pe,qt[nt.scheme]=nt,qt[dn.scheme]=dn,qt[Tn.scheme]=Tn,qt[fE.scheme]=fE,qt[pE.scheme]=pE,qt[mE.scheme]=mE,t.SCHEMES=qt,t.pctEncChar=Xr,t.pctDecChars=Xn,t.parse=En,t.removeDotSegments=Do,t.serialize=Pn,t.resolveComponents=xm,t.resolve=Jv,t.normalize=Yv,t.equal=j,t.escapeComponent=K,t.unescapeComponent=fe,Object.defineProperty(t,"__esModule",{value:!0})})});var LO=C(Bk=>{"use strict";Object.defineProperty(Bk,"__esModule",{value:!0});var DO=jO();DO.code='require("ajv/dist/runtime/uri").default';Bk.default=DO});var GO=C(br=>{"use strict";Object.defineProperty(br,"__esModule",{value:!0});br.CodeGen=br.Name=br.nil=br.stringify=br.str=br._=br.KeywordCxt=void 0;var WG=lp();Object.defineProperty(br,"KeywordCxt",{enumerable:!0,get:function(){return WG.KeywordCxt}});var _u=Ne();Object.defineProperty(br,"_",{enumerable:!0,get:function(){return _u._}});Object.defineProperty(br,"str",{enumerable:!0,get:function(){return _u.str}});Object.defineProperty(br,"stringify",{enumerable:!0,get:function(){return _u.stringify}});Object.defineProperty(br,"nil",{enumerable:!0,get:function(){return _u.nil}});Object.defineProperty(br,"Name",{enumerable:!0,get:function(){return _u.Name}});Object.defineProperty(br,"CodeGen",{enumerable:!0,get:function(){return _u.CodeGen}});var BG=by(),qO=wy(),GG=Ek(),cp=$y(),HG=Ne(),up=op(),Sy=ip(),Hk=et(),UO=RO(),XG=LO(),WO=(t,e)=>new RegExp(t,e);WO.code="new RegExp";var KG=["removeAdditional","useDefaults","coerceTypes"],JG=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),YG={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."},QG={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},ZO=200;function eH(t){var e,r,n,i,o,s,a,l,c,u,d,p,f,m,h,y,g,_,b,E,I,P,M,V,R;let L=t.strict,G=(e=t.code)===null||e===void 0?void 0:e.optimize,H=G===!0||G===void 0?1:G||0,W=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:WO,Y=(i=t.uriResolver)!==null&&i!==void 0?i:XG.default;return{strictSchema:(s=(o=t.strictSchema)!==null&&o!==void 0?o:L)!==null&&s!==void 0?s:!0,strictNumbers:(l=(a=t.strictNumbers)!==null&&a!==void 0?a:L)!==null&&l!==void 0?l:!0,strictTypes:(u=(c=t.strictTypes)!==null&&c!==void 0?c:L)!==null&&u!==void 0?u:"log",strictTuples:(p=(d=t.strictTuples)!==null&&d!==void 0?d:L)!==null&&p!==void 0?p:"log",strictRequired:(m=(f=t.strictRequired)!==null&&f!==void 0?f:L)!==null&&m!==void 0?m:!1,code:t.code?{...t.code,optimize:H,regExp:W}:{optimize:H,regExp:W},loopRequired:(h=t.loopRequired)!==null&&h!==void 0?h:ZO,loopEnum:(y=t.loopEnum)!==null&&y!==void 0?y:ZO,meta:(g=t.meta)!==null&&g!==void 0?g:!0,messages:(_=t.messages)!==null&&_!==void 0?_:!0,inlineRefs:(b=t.inlineRefs)!==null&&b!==void 0?b:!0,schemaId:(E=t.schemaId)!==null&&E!==void 0?E:"$id",addUsedSchema:(I=t.addUsedSchema)!==null&&I!==void 0?I:!0,validateSchema:(P=t.validateSchema)!==null&&P!==void 0?P:!0,validateFormats:(M=t.validateFormats)!==null&&M!==void 0?M:!0,unicodeRegExp:(V=t.unicodeRegExp)!==null&&V!==void 0?V:!0,int32range:(R=t.int32range)!==null&&R!==void 0?R:!0,uriResolver:Y}}var dp=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...eH(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new HG.ValueScope({scope:{},prefixes:JG,es5:r,lines:n}),this.logger=sH(e.logger);let i=e.validateFormats;e.validateFormats=!1,this.RULES=(0,GG.getRules)(),FO.call(this,YG,e,"NOT SUPPORTED"),FO.call(this,QG,e,"DEPRECATED","warn"),this._metaOpts=iH.call(this),e.formats&&rH.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&nH.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),tH.call(this),e.validateFormats=i}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,i=UO;n==="id"&&(i={...UO},i.id=i.$id,delete i.$id),r&&e&&this.addMetaSchema(i,i[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){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(r);return"$async"in n||(this.errors=n.errors),i}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){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,r);async function i(u,d){await o.call(this,u.$schema);let p=this._addSchema(u,d);return p.validate||s.call(this,p)}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(d){if(!(d instanceof qO.default))throw d;return a.call(this,d),await l.call(this,d.missingSchema),s.call(this,u)}}function a({missingSchema:u,missingRef:d}){if(this.refs[u])throw new Error(`AnySchema ${u} is loaded but ${d} cannot be resolved`)}async function l(u){let d=await c.call(this,u);this.refs[u]||await o.call(this,d.$schema),this.refs[u]||this.addSchema(d,u,r)}async function c(u){let d=this._loading[u];if(d)return d;try{return await(this._loading[u]=n(u))}finally{delete this._loading[u]}}}addSchema(e,r,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 r=(0,up.normalizeId)(r||o),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,i,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){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&&r){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 r;for(;typeof(r=VO.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,i=new cp.SchemaEnv({schema:{},schemaId:n});if(r=cp.resolveSchema.call(this,i,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}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 r=VO.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let n=e[this.opts.schemaId];return n&&(n=(0,up.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let n;if(typeof e=="string")n=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof e=="object"&&r===void 0){if(r=e,n=r.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(lH.call(this,n,r),!r)return(0,Hk.eachItem)(n,o=>Gk.call(this,o)),this;uH.call(this,r);let i={...r,type:(0,Sy.getJSONTypes)(r.type),schemaType:(0,Sy.getJSONTypes)(r.schemaType)};return(0,Hk.eachItem)(n,i.type.length===0?o=>Gk.call(this,o,i):o=>i.type.forEach(s=>Gk.call(this,o,i,s))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let i=n.rules.findIndex(o=>o.keyword===e);i>=0&&n.rules.splice(i,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(i=>`${n}${i.instancePath} ${i.message}`).reduce((i,o)=>i+r+o)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let i of r){let o=i.split("/").slice(1),s=e;for(let a of o)s=s[a];for(let a in n){let l=n[a];if(typeof l!="object")continue;let{$data:c}=l.definition,u=s[a];c&&u&&(s[a]=BO(u))}}return e}_removeAllSchemas(e,r){for(let n in e){let i=e[n];(!r||r.test(n))&&(typeof i=="string"?delete e[n]:i&&!i.meta&&(this._cache.delete(i.schema),delete e[n]))}}_addSchema(e,r,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 l=this._cache.get(e);if(l!==void 0)return l;n=(0,up.normalizeId)(s||n);let c=up.getSchemaRefs.call(this,e,n);return l=new cp.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:c}),this._cache.set(l.schema,l),o&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=l),i&&this.validateSchema(e,!0),l}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):cp.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let r=this.opts;this.opts=this._metaOpts;try{cp.compileSchema.call(this,e)}finally{this.opts=r}}};br.default=dp;dp.ValidationError=BG.default;dp.MissingRefError=qO.default;function FO(t,e,r,n="error"){for(let i in t){let o=i;o in e&&this.logger[n](`${r}: option ${i}. ${t[o]}`)}}function VO(t){return t=(0,up.normalizeId)(t),this.schemas[t]||this.refs[t]}function tH(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function rH(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function nH(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let r=t[e];r.keyword||(r.keyword=e),this.addKeyword(r)}}function iH(){let t={...this.opts};for(let e of KG)delete t[e];return t}var oH={log(){},warn(){},error(){}};function sH(t){if(t===!1)return oH;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var aH=/^[a-z_$][a-z0-9_$:-]*$/i;function lH(t,e){let{RULES:r}=this;if((0,Hk.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!aH.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 Gk(t,e,r){var n;let i=e?.post;if(r&&i)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:o}=this,s=i?o.post:o.rules.find(({type:l})=>l===r);if(s||(s={type:r,rules:[]},o.rules.push(s)),o.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,Sy.getJSONTypes)(e.type),schemaType:(0,Sy.getJSONTypes)(e.schemaType)}};e.before?cH.call(this,s,a,e.before):s.rules.push(a),o.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(l=>this.addKeyword(l))}function cH(t,e,r){let n=t.rules.findIndex(i=>i.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function uH(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=BO(e)),t.validateSchema=this.compile(e,!0))}var dH={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function BO(t){return{anyOf:[t,dH]}}});var HO=C(Xk=>{"use strict";Object.defineProperty(Xk,"__esModule",{value:!0});var fH={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Xk.default=fH});var YO=C(qa=>{"use strict";Object.defineProperty(qa,"__esModule",{value:!0});qa.callRef=qa.getValidate=void 0;var pH=wy(),XO=Fn(),an=Ne(),bu=To(),KO=$y(),Iy=et(),mH={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:i,schemaEnv:o,validateName:s,opts:a,self:l}=n,{root:c}=o;if((r==="#"||r==="#/")&&i===c.baseId)return d();let u=KO.resolveRef.call(l,c,i,r);if(u===void 0)throw new pH.default(n.opts.uriResolver,i,r);if(u instanceof KO.SchemaEnv)return p(u);return f(u);function d(){if(o===c)return Ey(t,s,o,o.$async);let m=e.scopeValue("root",{ref:c});return Ey(t,(0,an._)`${m}.validate`,c,c.$async)}function p(m){let h=JO(t,m);Ey(t,h,m,m.$async)}function f(m){let h=e.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,an.stringify)(m)}:{ref:m}),y=e.name("valid"),g=t.subschema({schema:m,dataTypes:[],schemaPath:an.nil,topSchemaRef:h,errSchemaPath:r},y);t.mergeEvaluated(g),t.ok(y)}}};function JO(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,an._)`${r.scopeValue("wrapper",{ref:e})}.validate`}qa.getValidate=JO;function Ey(t,e,r,n){let{gen:i,it:o}=t,{allErrors:s,schemaEnv:a,opts:l}=o,c=l.passContext?bu.default.this:an.nil;n?u():d();function u(){if(!a.$async)throw new Error("async schema referenced by sync schema");let m=i.let("valid");i.try(()=>{i.code((0,an._)`await ${(0,XO.callValidateCode)(t,e,c)}`),f(e),s||i.assign(m,!0)},h=>{i.if((0,an._)`!(${h} instanceof ${o.ValidationError})`,()=>i.throw(h)),p(h),s||i.assign(m,!1)}),t.ok(m)}function d(){t.result((0,XO.callValidateCode)(t,e,c),()=>f(e),()=>p(e))}function p(m){let h=(0,an._)`${m}.errors`;i.assign(bu.default.vErrors,(0,an._)`${bu.default.vErrors} === null ? ${h} : ${bu.default.vErrors}.concat(${h})`),i.assign(bu.default.errors,(0,an._)`${bu.default.vErrors}.length`)}function f(m){var h;if(!o.opts.unevaluated)return;let y=(h=r?.validate)===null||h===void 0?void 0:h.evaluated;if(o.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(o.props=Iy.mergeEvaluated.props(i,y.props,o.props));else{let g=i.var("props",(0,an._)`${m}.evaluated.props`);o.props=Iy.mergeEvaluated.props(i,g,o.props,an.Name)}if(o.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(o.items=Iy.mergeEvaluated.items(i,y.items,o.items));else{let g=i.var("items",(0,an._)`${m}.evaluated.items`);o.items=Iy.mergeEvaluated.items(i,g,o.items,an.Name)}}}qa.callRef=Ey;qa.default=mH});var QO=C(Kk=>{"use strict";Object.defineProperty(Kk,"__esModule",{value:!0});var hH=HO(),gH=YO(),yH=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",hH.default,gH.default];Kk.default=yH});var eR=C(Jk=>{"use strict";Object.defineProperty(Jk,"__esModule",{value:!0});var Py=Ne(),Ps=Py.operators,Ty={maximum:{okStr:"<=",ok:Ps.LTE,fail:Ps.GT},minimum:{okStr:">=",ok:Ps.GTE,fail:Ps.LT},exclusiveMaximum:{okStr:"<",ok:Ps.LT,fail:Ps.GTE},exclusiveMinimum:{okStr:">",ok:Ps.GT,fail:Ps.LTE}},vH={message:({keyword:t,schemaCode:e})=>(0,Py.str)`must be ${Ty[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Py._)`{comparison: ${Ty[t].okStr}, limit: ${e}}`},_H={keyword:Object.keys(Ty),type:"number",schemaType:"number",$data:!0,error:vH,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,Py._)`${r} ${Ty[e].fail} ${n} || isNaN(${r})`)}};Jk.default=_H});var tR=C(Yk=>{"use strict";Object.defineProperty(Yk,"__esModule",{value:!0});var fp=Ne(),bH={message:({schemaCode:t})=>(0,fp.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,fp._)`{multipleOf: ${t}}`},wH={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:bH,code(t){let{gen:e,data:r,schemaCode:n,it:i}=t,o=i.opts.multipleOfPrecision,s=e.let("res"),a=o?(0,fp._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${o}`:(0,fp._)`${s} !== parseInt(${s})`;t.fail$data((0,fp._)`(${n} === 0 || (${s} = ${r}/${n}, ${a}))`)}};Yk.default=wH});var nR=C(Qk=>{"use strict";Object.defineProperty(Qk,"__esModule",{value:!0});function rR(t){let e=t.length,r=0,n=0,i;for(;n<e;)r++,i=t.charCodeAt(n++),i>=55296&&i<=56319&&n<e&&(i=t.charCodeAt(n),(i&64512)===56320&&n++);return r}Qk.default=rR;rR.code='require("ajv/dist/runtime/ucs2length").default'});var iR=C(eS=>{"use strict";Object.defineProperty(eS,"__esModule",{value:!0});var Wa=Ne(),xH=et(),$H=nR(),kH={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,Wa.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,Wa._)`{limit: ${t}}`},SH={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:kH,code(t){let{keyword:e,data:r,schemaCode:n,it:i}=t,o=e==="maxLength"?Wa.operators.GT:Wa.operators.LT,s=i.opts.unicode===!1?(0,Wa._)`${r}.length`:(0,Wa._)`${(0,xH.useFunc)(t.gen,$H.default)}(${r})`;t.fail$data((0,Wa._)`${s} ${o} ${n}`)}};eS.default=SH});var oR=C(tS=>{"use strict";Object.defineProperty(tS,"__esModule",{value:!0});var IH=Fn(),Ay=Ne(),EH={message:({schemaCode:t})=>(0,Ay.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Ay._)`{pattern: ${t}}`},PH={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:EH,code(t){let{data:e,$data:r,schema:n,schemaCode:i,it:o}=t,s=o.opts.unicodeRegExp?"u":"",a=r?(0,Ay._)`(new RegExp(${i}, ${s}))`:(0,IH.usePattern)(t,n);t.fail$data((0,Ay._)`!${a}.test(${e})`)}};tS.default=PH});var sR=C(rS=>{"use strict";Object.defineProperty(rS,"__esModule",{value:!0});var pp=Ne(),TH={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,pp.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,pp._)`{limit: ${t}}`},AH={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:TH,code(t){let{keyword:e,data:r,schemaCode:n}=t,i=e==="maxProperties"?pp.operators.GT:pp.operators.LT;t.fail$data((0,pp._)`Object.keys(${r}).length ${i} ${n}`)}};rS.default=AH});var aR=C(nS=>{"use strict";Object.defineProperty(nS,"__esModule",{value:!0});var mp=Fn(),hp=Ne(),zH=et(),CH={message:({params:{missingProperty:t}})=>(0,hp.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,hp._)`{missingProperty: ${t}}`},NH={keyword:"required",type:"object",schemaType:"array",$data:!0,error:CH,code(t){let{gen:e,schema:r,schemaCode:n,data:i,$data:o,it:s}=t,{opts:a}=s;if(!o&&r.length===0)return;let l=r.length>=a.loopRequired;if(s.allErrors?c():u(),a.strictRequired){let f=t.parentSchema.properties,{definedProperties:m}=t.it;for(let h of r)if(f?.[h]===void 0&&!m.has(h)){let y=s.schemaEnv.baseId+s.errSchemaPath,g=`required property "${h}" is not defined at "${y}" (strictRequired)`;(0,zH.checkStrictMode)(s,g,s.opts.strictRequired)}}function c(){if(l||o)t.block$data(hp.nil,d);else for(let f of r)(0,mp.checkReportMissingProp)(t,f)}function u(){let f=e.let("missing");if(l||o){let m=e.let("valid",!0);t.block$data(m,()=>p(f,m)),t.ok(m)}else e.if((0,mp.checkMissingProp)(t,r,f)),(0,mp.reportMissingProp)(t,f),e.else()}function d(){e.forOf("prop",n,f=>{t.setParams({missingProperty:f}),e.if((0,mp.noPropertyInData)(e,i,f,a.ownProperties),()=>t.error())})}function p(f,m){t.setParams({missingProperty:f}),e.forOf(f,n,()=>{e.assign(m,(0,mp.propertyInData)(e,i,f,a.ownProperties)),e.if((0,hp.not)(m),()=>{t.error(),e.break()})},hp.nil)}}};nS.default=NH});var lR=C(iS=>{"use strict";Object.defineProperty(iS,"__esModule",{value:!0});var gp=Ne(),OH={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,gp.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,gp._)`{limit: ${t}}`},RH={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:OH,code(t){let{keyword:e,data:r,schemaCode:n}=t,i=e==="maxItems"?gp.operators.GT:gp.operators.LT;t.fail$data((0,gp._)`${r}.length ${i} ${n}`)}};iS.default=RH});var zy=C(oS=>{"use strict";Object.defineProperty(oS,"__esModule",{value:!0});var cR=Tf();cR.code='require("ajv/dist/runtime/equal").default';oS.default=cR});var uR=C(aS=>{"use strict";Object.defineProperty(aS,"__esModule",{value:!0});var sS=ip(),wr=Ne(),MH=et(),jH=zy(),DH={message:({params:{i:t,j:e}})=>(0,wr.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,wr._)`{i: ${t}, j: ${e}}`},LH={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:DH,code(t){let{gen:e,data:r,$data:n,schema:i,parentSchema:o,schemaCode:s,it:a}=t;if(!n&&!i)return;let l=e.let("valid"),c=o.items?(0,sS.getSchemaTypes)(o.items):[];t.block$data(l,u,(0,wr._)`${s} === false`),t.ok(l);function u(){let m=e.let("i",(0,wr._)`${r}.length`),h=e.let("j");t.setParams({i:m,j:h}),e.assign(l,!0),e.if((0,wr._)`${m} > 1`,()=>(d()?p:f)(m,h))}function d(){return c.length>0&&!c.some(m=>m==="object"||m==="array")}function p(m,h){let y=e.name("item"),g=(0,sS.checkDataTypes)(c,y,a.opts.strictNumbers,sS.DataType.Wrong),_=e.const("indices",(0,wr._)`{}`);e.for((0,wr._)`;${m}--;`,()=>{e.let(y,(0,wr._)`${r}[${m}]`),e.if(g,(0,wr._)`continue`),c.length>1&&e.if((0,wr._)`typeof ${y} == "string"`,(0,wr._)`${y} += "_"`),e.if((0,wr._)`typeof ${_}[${y}] == "number"`,()=>{e.assign(h,(0,wr._)`${_}[${y}]`),t.error(),e.assign(l,!1).break()}).code((0,wr._)`${_}[${y}] = ${m}`)})}function f(m,h){let y=(0,MH.useFunc)(e,jH.default),g=e.name("outer");e.label(g).for((0,wr._)`;${m}--;`,()=>e.for((0,wr._)`${h} = ${m}; ${h}--;`,()=>e.if((0,wr._)`${y}(${r}[${m}], ${r}[${h}])`,()=>{t.error(),e.assign(l,!1).break(g)})))}}};aS.default=LH});var dR=C(cS=>{"use strict";Object.defineProperty(cS,"__esModule",{value:!0});var lS=Ne(),UH=et(),ZH=zy(),FH={message:"must be equal to constant",params:({schemaCode:t})=>(0,lS._)`{allowedValue: ${t}}`},VH={keyword:"const",$data:!0,error:FH,code(t){let{gen:e,data:r,$data:n,schemaCode:i,schema:o}=t;n||o&&typeof o=="object"?t.fail$data((0,lS._)`!${(0,UH.useFunc)(e,ZH.default)}(${r}, ${i})`):t.fail((0,lS._)`${o} !== ${r}`)}};cS.default=VH});var fR=C(uS=>{"use strict";Object.defineProperty(uS,"__esModule",{value:!0});var yp=Ne(),qH=et(),WH=zy(),BH={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,yp._)`{allowedValues: ${t}}`},GH={keyword:"enum",schemaType:"array",$data:!0,error:BH,code(t){let{gen:e,data:r,$data:n,schema:i,schemaCode:o,it:s}=t;if(!n&&i.length===0)throw new Error("enum must have non-empty array");let a=i.length>=s.opts.loopEnum,l,c=()=>l??(l=(0,qH.useFunc)(e,WH.default)),u;if(a||n)u=e.let("valid"),t.block$data(u,d);else{if(!Array.isArray(i))throw new Error("ajv implementation error");let f=e.const("vSchema",o);u=(0,yp.or)(...i.map((m,h)=>p(f,h)))}t.pass(u);function d(){e.assign(u,!1),e.forOf("v",o,f=>e.if((0,yp._)`${c()}(${r}, ${f})`,()=>e.assign(u,!0).break()))}function p(f,m){let h=i[m];return typeof h=="object"&&h!==null?(0,yp._)`${c()}(${r}, ${f}[${m}])`:(0,yp._)`${r} === ${h}`}}};uS.default=GH});var pR=C(dS=>{"use strict";Object.defineProperty(dS,"__esModule",{value:!0});var HH=eR(),XH=tR(),KH=iR(),JH=oR(),YH=sR(),QH=aR(),eX=lR(),tX=uR(),rX=dR(),nX=fR(),iX=[HH.default,XH.default,KH.default,JH.default,YH.default,QH.default,eX.default,tX.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},rX.default,nX.default];dS.default=iX});var pS=C(vp=>{"use strict";Object.defineProperty(vp,"__esModule",{value:!0});vp.validateAdditionalItems=void 0;var Ba=Ne(),fS=et(),oX={message:({params:{len:t}})=>(0,Ba.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Ba._)`{limit: ${t}}`},sX={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:oX,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,fS.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}mR(t,n)}};function mR(t,e){let{gen:r,schema:n,data:i,keyword:o,it:s}=t;s.items=!0;let a=r.const("len",(0,Ba._)`${i}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Ba._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,fS.alwaysValidSchema)(s,n)){let c=r.var("valid",(0,Ba._)`${a} <= ${e.length}`);r.if((0,Ba.not)(c),()=>l(c)),t.ok(c)}function l(c){r.forRange("i",e.length,a,u=>{t.subschema({keyword:o,dataProp:u,dataPropType:fS.Type.Num},c),s.allErrors||r.if((0,Ba.not)(c),()=>r.break())})}}vp.validateAdditionalItems=mR;vp.default=sX});var mS=C(_p=>{"use strict";Object.defineProperty(_p,"__esModule",{value:!0});_p.validateTuple=void 0;var hR=Ne(),Cy=et(),aX=Fn(),lX={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return gR(t,"additionalItems",e);r.items=!0,!(0,Cy.alwaysValidSchema)(r,e)&&t.ok((0,aX.validateArray)(t))}};function gR(t,e,r=t.schema){let{gen:n,parentSchema:i,data:o,keyword:s,it:a}=t;u(i),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=Cy.mergeEvaluated.items(n,r.length,a.items));let l=n.name("valid"),c=n.const("len",(0,hR._)`${o}.length`);r.forEach((d,p)=>{(0,Cy.alwaysValidSchema)(a,d)||(n.if((0,hR._)`${c} > ${p}`,()=>t.subschema({keyword:s,schemaProp:p,dataProp:p},l)),t.ok(l))});function u(d){let{opts:p,errSchemaPath:f}=a,m=r.length,h=m===d.minItems&&(m===d.maxItems||d[e]===!1);if(p.strictTuples&&!h){let y=`"${s}" is ${m}-tuple, but minItems or maxItems/${e} are not specified or different at path "${f}"`;(0,Cy.checkStrictMode)(a,y,p.strictTuples)}}}_p.validateTuple=gR;_p.default=lX});var yR=C(hS=>{"use strict";Object.defineProperty(hS,"__esModule",{value:!0});var cX=mS(),uX={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,cX.validateTuple)(t,"items")};hS.default=uX});var _R=C(gS=>{"use strict";Object.defineProperty(gS,"__esModule",{value:!0});var vR=Ne(),dX=et(),fX=Fn(),pX=pS(),mX={message:({params:{len:t}})=>(0,vR.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,vR._)`{limit: ${t}}`},hX={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:mX,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:i}=r;n.items=!0,!(0,dX.alwaysValidSchema)(n,e)&&(i?(0,pX.validateAdditionalItems)(t,i):t.ok((0,fX.validateArray)(t)))}};gS.default=hX});var bR=C(yS=>{"use strict";Object.defineProperty(yS,"__esModule",{value:!0});var qn=Ne(),Ny=et(),gX={message:({params:{min:t,max:e}})=>e===void 0?(0,qn.str)`must contain at least ${t} valid item(s)`:(0,qn.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,qn._)`{minContains: ${t}}`:(0,qn._)`{minContains: ${t}, maxContains: ${e}}`},yX={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:gX,code(t){let{gen:e,schema:r,parentSchema:n,data:i,it:o}=t,s,a,{minContains:l,maxContains:c}=n;o.opts.next?(s=l===void 0?1:l,a=c):s=1;let u=e.const("len",(0,qn._)`${i}.length`);if(t.setParams({min:s,max:a}),a===void 0&&s===0){(0,Ny.checkStrictMode)(o,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&s>a){(0,Ny.checkStrictMode)(o,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Ny.alwaysValidSchema)(o,r)){let h=(0,qn._)`${u} >= ${s}`;a!==void 0&&(h=(0,qn._)`${h} && ${u} <= ${a}`),t.pass(h);return}o.items=!0;let d=e.name("valid");a===void 0&&s===1?f(d,()=>e.if(d,()=>e.break())):s===0?(e.let(d,!0),a!==void 0&&e.if((0,qn._)`${i}.length > 0`,p)):(e.let(d,!1),p()),t.result(d,()=>t.reset());function p(){let h=e.name("_valid"),y=e.let("count",0);f(h,()=>e.if(h,()=>m(y)))}function f(h,y){e.forRange("i",0,u,g=>{t.subschema({keyword:"contains",dataProp:g,dataPropType:Ny.Type.Num,compositeRule:!0},h),y()})}function m(h){e.code((0,qn._)`${h}++`),a===void 0?e.if((0,qn._)`${h} >= ${s}`,()=>e.assign(d,!0).break()):(e.if((0,qn._)`${h} > ${a}`,()=>e.assign(d,!1).break()),s===1?e.assign(d,!0):e.if((0,qn._)`${h} >= ${s}`,()=>e.assign(d,!0)))}}};yS.default=yX});var $R=C(Fi=>{"use strict";Object.defineProperty(Fi,"__esModule",{value:!0});Fi.validateSchemaDeps=Fi.validatePropertyDeps=Fi.error=void 0;var vS=Ne(),vX=et(),bp=Fn();Fi.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,vS.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,vS._)`{property: ${t},
|
|
13
|
+
missingProperty: ${n},
|
|
14
|
+
depsCount: ${e},
|
|
15
|
+
deps: ${r}}`};var _X={keyword:"dependencies",type:"object",schemaType:"object",error:Fi.error,code(t){let[e,r]=bX(t);wR(t,e),xR(t,r)}};function bX({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let i=Array.isArray(t[n])?e:r;i[n]=t[n]}return[e,r]}function wR(t,e=t.schema){let{gen:r,data:n,it:i}=t;if(Object.keys(e).length===0)return;let o=r.let("missing");for(let s in e){let a=e[s];if(a.length===0)continue;let l=(0,bp.propertyInData)(r,n,s,i.opts.ownProperties);t.setParams({property:s,depsCount:a.length,deps:a.join(", ")}),i.allErrors?r.if(l,()=>{for(let c of a)(0,bp.checkReportMissingProp)(t,c)}):(r.if((0,vS._)`${l} && (${(0,bp.checkMissingProp)(t,a,o)})`),(0,bp.reportMissingProp)(t,o),r.else())}}Fi.validatePropertyDeps=wR;function xR(t,e=t.schema){let{gen:r,data:n,keyword:i,it:o}=t,s=r.name("valid");for(let a in e)(0,vX.alwaysValidSchema)(o,e[a])||(r.if((0,bp.propertyInData)(r,n,a,o.opts.ownProperties),()=>{let l=t.subschema({keyword:i,schemaProp:a},s);t.mergeValidEvaluated(l,s)},()=>r.var(s,!0)),t.ok(s))}Fi.validateSchemaDeps=xR;Fi.default=_X});var SR=C(_S=>{"use strict";Object.defineProperty(_S,"__esModule",{value:!0});var kR=Ne(),wX=et(),xX={message:"property name must be valid",params:({params:t})=>(0,kR._)`{propertyName: ${t.propertyName}}`},$X={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:xX,code(t){let{gen:e,schema:r,data:n,it:i}=t;if((0,wX.alwaysValidSchema)(i,r))return;let o=e.name("valid");e.forIn("key",n,s=>{t.setParams({propertyName:s}),t.subschema({keyword:"propertyNames",data:s,dataTypes:["string"],propertyName:s,compositeRule:!0},o),e.if((0,kR.not)(o),()=>{t.error(!0),i.allErrors||e.break()})}),t.ok(o)}};_S.default=$X});var wS=C(bS=>{"use strict";Object.defineProperty(bS,"__esModule",{value:!0});var Oy=Fn(),mi=Ne(),kX=To(),Ry=et(),SX={message:"must NOT have additional properties",params:({params:t})=>(0,mi._)`{additionalProperty: ${t.additionalProperty}}`},IX={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:SX,code(t){let{gen:e,schema:r,parentSchema:n,data:i,errsCount:o,it:s}=t;if(!o)throw new Error("ajv implementation error");let{allErrors:a,opts:l}=s;if(s.props=!0,l.removeAdditional!=="all"&&(0,Ry.alwaysValidSchema)(s,r))return;let c=(0,Oy.allSchemaProperties)(n.properties),u=(0,Oy.allSchemaProperties)(n.patternProperties);d(),t.ok((0,mi._)`${o} === ${kX.default.errors}`);function d(){e.forIn("key",i,y=>{!c.length&&!u.length?m(y):e.if(p(y),()=>m(y))})}function p(y){let g;if(c.length>8){let _=(0,Ry.schemaRefOrVal)(s,n.properties,"properties");g=(0,Oy.isOwnProperty)(e,_,y)}else c.length?g=(0,mi.or)(...c.map(_=>(0,mi._)`${y} === ${_}`)):g=mi.nil;return u.length&&(g=(0,mi.or)(g,...u.map(_=>(0,mi._)`${(0,Oy.usePattern)(t,_)}.test(${y})`))),(0,mi.not)(g)}function f(y){e.code((0,mi._)`delete ${i}[${y}]`)}function m(y){if(l.removeAdditional==="all"||l.removeAdditional&&r===!1){f(y);return}if(r===!1){t.setParams({additionalProperty:y}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,Ry.alwaysValidSchema)(s,r)){let g=e.name("valid");l.removeAdditional==="failing"?(h(y,g,!1),e.if((0,mi.not)(g),()=>{t.reset(),f(y)})):(h(y,g),a||e.if((0,mi.not)(g),()=>e.break()))}}function h(y,g,_){let b={keyword:"additionalProperties",dataProp:y,dataPropType:Ry.Type.Str};_===!1&&Object.assign(b,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(b,g)}}};bS.default=IX});var PR=C($S=>{"use strict";Object.defineProperty($S,"__esModule",{value:!0});var EX=lp(),IR=Fn(),xS=et(),ER=wS(),PX={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:i,it:o}=t;o.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&ER.default.code(new EX.KeywordCxt(o,ER.default,"additionalProperties"));let s=(0,IR.allSchemaProperties)(r);for(let d of s)o.definedProperties.add(d);o.opts.unevaluated&&s.length&&o.props!==!0&&(o.props=xS.mergeEvaluated.props(e,(0,xS.toHash)(s),o.props));let a=s.filter(d=>!(0,xS.alwaysValidSchema)(o,r[d]));if(a.length===0)return;let l=e.name("valid");for(let d of a)c(d)?u(d):(e.if((0,IR.propertyInData)(e,i,d,o.opts.ownProperties)),u(d),o.allErrors||e.else().var(l,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(l);function c(d){return o.opts.useDefaults&&!o.compositeRule&&r[d].default!==void 0}function u(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},l)}}};$S.default=PX});var CR=C(kS=>{"use strict";Object.defineProperty(kS,"__esModule",{value:!0});var TR=Fn(),My=Ne(),AR=et(),zR=et(),TX={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:i,it:o}=t,{opts:s}=o,a=(0,TR.allSchemaProperties)(r),l=a.filter(h=>(0,AR.alwaysValidSchema)(o,r[h]));if(a.length===0||l.length===a.length&&(!o.opts.unevaluated||o.props===!0))return;let c=s.strictSchema&&!s.allowMatchingProperties&&i.properties,u=e.name("valid");o.props!==!0&&!(o.props instanceof My.Name)&&(o.props=(0,zR.evaluatedPropsToName)(e,o.props));let{props:d}=o;p();function p(){for(let h of a)c&&f(h),o.allErrors?m(h):(e.var(u,!0),m(h),e.if(u))}function f(h){for(let y in c)new RegExp(h).test(y)&&(0,AR.checkStrictMode)(o,`property ${y} matches pattern ${h} (use allowMatchingProperties)`)}function m(h){e.forIn("key",n,y=>{e.if((0,My._)`${(0,TR.usePattern)(t,h)}.test(${y})`,()=>{let g=l.includes(h);g||t.subschema({keyword:"patternProperties",schemaProp:h,dataProp:y,dataPropType:zR.Type.Str},u),o.opts.unevaluated&&d!==!0?e.assign((0,My._)`${d}[${y}]`,!0):!g&&!o.allErrors&&e.if((0,My.not)(u),()=>e.break())})})}}};kS.default=TX});var NR=C(SS=>{"use strict";Object.defineProperty(SS,"__esModule",{value:!0});var AX=et(),zX={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,AX.alwaysValidSchema)(n,r)){t.fail();return}let i=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},i),t.failResult(i,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};SS.default=zX});var OR=C(IS=>{"use strict";Object.defineProperty(IS,"__esModule",{value:!0});var CX=Fn(),NX={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:CX.validateUnion,error:{message:"must match a schema in anyOf"}};IS.default=NX});var RR=C(ES=>{"use strict";Object.defineProperty(ES,"__esModule",{value:!0});var jy=Ne(),OX=et(),RX={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,jy._)`{passingSchemas: ${t.passing}}`},MX={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:RX,code(t){let{gen:e,schema:r,parentSchema:n,it:i}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(i.opts.discriminator&&n.discriminator)return;let o=r,s=e.let("valid",!1),a=e.let("passing",null),l=e.name("_valid");t.setParams({passing:a}),e.block(c),t.result(s,()=>t.reset(),()=>t.error(!0));function c(){o.forEach((u,d)=>{let p;(0,OX.alwaysValidSchema)(i,u)?e.var(l,!0):p=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},l),d>0&&e.if((0,jy._)`${l} && ${s}`).assign(s,!1).assign(a,(0,jy._)`[${a}, ${d}]`).else(),e.if(l,()=>{e.assign(s,!0),e.assign(a,d),p&&t.mergeEvaluated(p,jy.Name)})})}}};ES.default=MX});var MR=C(PS=>{"use strict";Object.defineProperty(PS,"__esModule",{value:!0});var jX=et(),DX={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let i=e.name("valid");r.forEach((o,s)=>{if((0,jX.alwaysValidSchema)(n,o))return;let a=t.subschema({keyword:"allOf",schemaProp:s},i);t.ok(i),t.mergeEvaluated(a)})}};PS.default=DX});var LR=C(TS=>{"use strict";Object.defineProperty(TS,"__esModule",{value:!0});var Dy=Ne(),DR=et(),LX={message:({params:t})=>(0,Dy.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Dy._)`{failingKeyword: ${t.ifClause}}`},UX={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:LX,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,DR.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let i=jR(n,"then"),o=jR(n,"else");if(!i&&!o)return;let s=e.let("valid",!0),a=e.name("_valid");if(l(),t.reset(),i&&o){let u=e.let("ifClause");t.setParams({ifClause:u}),e.if(a,c("then",u),c("else",u))}else i?e.if(a,c("then")):e.if((0,Dy.not)(a),c("else"));t.pass(s,()=>t.error(!0));function l(){let u=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(u)}function c(u,d){return()=>{let p=t.subschema({keyword:u},a);e.assign(s,a),t.mergeValidEvaluated(p,s),d?e.assign(d,(0,Dy._)`${u}`):t.setParams({ifClause:u})}}}};function jR(t,e){let r=t.schema[e];return r!==void 0&&!(0,DR.alwaysValidSchema)(t,r)}TS.default=UX});var UR=C(AS=>{"use strict";Object.defineProperty(AS,"__esModule",{value:!0});var ZX=et(),FX={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,ZX.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};AS.default=FX});var ZR=C(zS=>{"use strict";Object.defineProperty(zS,"__esModule",{value:!0});var VX=pS(),qX=yR(),WX=mS(),BX=_R(),GX=bR(),HX=$R(),XX=SR(),KX=wS(),JX=PR(),YX=CR(),QX=NR(),eK=OR(),tK=RR(),rK=MR(),nK=LR(),iK=UR();function oK(t=!1){let e=[QX.default,eK.default,tK.default,rK.default,nK.default,iK.default,XX.default,KX.default,HX.default,JX.default,YX.default];return t?e.push(qX.default,BX.default):e.push(VX.default,WX.default),e.push(GX.default),e}zS.default=oK});var FR=C(CS=>{"use strict";Object.defineProperty(CS,"__esModule",{value:!0});var Lt=Ne(),sK={message:({schemaCode:t})=>(0,Lt.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Lt._)`{format: ${t}}`},aK={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:sK,code(t,e){let{gen:r,data:n,$data:i,schema:o,schemaCode:s,it:a}=t,{opts:l,errSchemaPath:c,schemaEnv:u,self:d}=a;if(!l.validateFormats)return;i?p():f();function p(){let m=r.scopeValue("formats",{ref:d.formats,code:l.code.formats}),h=r.const("fDef",(0,Lt._)`${m}[${s}]`),y=r.let("fType"),g=r.let("format");r.if((0,Lt._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>r.assign(y,(0,Lt._)`${h}.type || "string"`).assign(g,(0,Lt._)`${h}.validate`),()=>r.assign(y,(0,Lt._)`"string"`).assign(g,h)),t.fail$data((0,Lt.or)(_(),b()));function _(){return l.strictSchema===!1?Lt.nil:(0,Lt._)`${s} && !${g}`}function b(){let E=u.$async?(0,Lt._)`(${h}.async ? await ${g}(${n}) : ${g}(${n}))`:(0,Lt._)`${g}(${n})`,I=(0,Lt._)`(typeof ${g} == "function" ? ${E} : ${g}.test(${n}))`;return(0,Lt._)`${g} && ${g} !== true && ${y} === ${e} && !${I}`}}function f(){let m=d.formats[o];if(!m){_();return}if(m===!0)return;let[h,y,g]=b(m);h===e&&t.pass(E());function _(){if(l.strictSchema===!1){d.logger.warn(I());return}throw new Error(I());function I(){return`unknown format "${o}" ignored in schema at path "${c}"`}}function b(I){let P=I instanceof RegExp?(0,Lt.regexpCode)(I):l.code.formats?(0,Lt._)`${l.code.formats}${(0,Lt.getProperty)(o)}`:void 0,M=r.scopeValue("formats",{key:o,ref:I,code:P});return typeof I=="object"&&!(I instanceof RegExp)?[I.type||"string",I.validate,(0,Lt._)`${M}.validate`]:["string",I,M]}function E(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!u.$async)throw new Error("async format in sync schema");return(0,Lt._)`await ${g}(${n})`}return typeof y=="function"?(0,Lt._)`${g}(${n})`:(0,Lt._)`${g}.test(${n})`}}}};CS.default=aK});var VR=C(NS=>{"use strict";Object.defineProperty(NS,"__esModule",{value:!0});var lK=FR(),cK=[lK.default];NS.default=cK});var qR=C(wu=>{"use strict";Object.defineProperty(wu,"__esModule",{value:!0});wu.contentVocabulary=wu.metadataVocabulary=void 0;wu.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];wu.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var BR=C(OS=>{"use strict";Object.defineProperty(OS,"__esModule",{value:!0});var uK=QO(),dK=pR(),fK=ZR(),pK=VR(),WR=qR(),mK=[uK.default,dK.default,(0,fK.default)(),pK.default,WR.metadataVocabulary,WR.contentVocabulary];OS.default=mK});var GR=C(wp=>{"use strict";Object.defineProperty(wp,"__esModule",{value:!0});wp.DiscrError=void 0;var hK;(function(t){t.Tag="tag",t.Mapping="mapping"})(hK=wp.DiscrError||(wp.DiscrError={}))});var XR=C(MS=>{"use strict";Object.defineProperty(MS,"__esModule",{value:!0});var xu=Ne(),RS=GR(),HR=$y(),gK=et(),yK={message:({params:{discrError:t,tagName:e}})=>t===RS.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,xu._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},vK={keyword:"discriminator",type:"object",schemaType:"object",error:yK,code(t){let{gen:e,data:r,schema:n,parentSchema:i,it:o}=t,{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 l=e.let("valid",!1),c=e.const("tag",(0,xu._)`${r}${(0,xu.getProperty)(a)}`);e.if((0,xu._)`typeof ${c} == "string"`,()=>u(),()=>t.error(!1,{discrError:RS.DiscrError.Tag,tag:c,tagName:a})),t.ok(l);function u(){let f=p();e.if(!1);for(let m in f)e.elseIf((0,xu._)`${c} === ${m}`),e.assign(l,d(f[m]));e.else(),t.error(!1,{discrError:RS.DiscrError.Mapping,tag:c,tagName:a}),e.endIf()}function d(f){let m=e.name("valid"),h=t.subschema({keyword:"oneOf",schemaProp:f},m);return t.mergeEvaluated(h,xu.Name),m}function p(){var f;let m={},h=g(i),y=!0;for(let E=0;E<s.length;E++){let I=s[E];I?.$ref&&!(0,gK.schemaHasRulesButRef)(I,o.self.RULES)&&(I=HR.resolveRef.call(o.self,o.schemaEnv.root,o.baseId,I?.$ref),I instanceof HR.SchemaEnv&&(I=I.schema));let P=(f=I?.properties)===null||f===void 0?void 0:f[a];if(typeof P!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);y=y&&(h||g(I)),_(P,E)}if(!y)throw new Error(`discriminator: "${a}" must be required`);return m;function g({required:E}){return Array.isArray(E)&&E.includes(a)}function _(E,I){if(E.const)b(E.const,I);else if(E.enum)for(let P of E.enum)b(P,I);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function b(E,I){if(typeof E!="string"||E in m)throw new Error(`discriminator: "${a}" values must be unique strings`);m[E]=I}}}};MS.default=vK});var KR=C((wwe,_K)=>{_K.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 QR=C((Ct,YR)=>{"use strict";Object.defineProperty(Ct,"__esModule",{value:!0});Ct.MissingRefError=Ct.ValidationError=Ct.CodeGen=Ct.Name=Ct.nil=Ct.stringify=Ct.str=Ct._=Ct.KeywordCxt=void 0;var bK=GO(),wK=BR(),xK=XR(),JR=KR(),$K=["/properties"],Ly="http://json-schema.org/draft-07/schema",Uy=class extends bK.default{_addVocabularies(){super._addVocabularies(),wK.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(xK.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(JR,$K):JR;this.addMetaSchema(e,Ly,!1),this.refs["http://json-schema.org/schema"]=Ly}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Ly)?Ly:void 0)}};YR.exports=Ct=Uy;Object.defineProperty(Ct,"__esModule",{value:!0});Ct.default=Uy;var kK=lp();Object.defineProperty(Ct,"KeywordCxt",{enumerable:!0,get:function(){return kK.KeywordCxt}});var $u=Ne();Object.defineProperty(Ct,"_",{enumerable:!0,get:function(){return $u._}});Object.defineProperty(Ct,"str",{enumerable:!0,get:function(){return $u.str}});Object.defineProperty(Ct,"stringify",{enumerable:!0,get:function(){return $u.stringify}});Object.defineProperty(Ct,"nil",{enumerable:!0,get:function(){return $u.nil}});Object.defineProperty(Ct,"Name",{enumerable:!0,get:function(){return $u.Name}});Object.defineProperty(Ct,"CodeGen",{enumerable:!0,get:function(){return $u.CodeGen}});var SK=by();Object.defineProperty(Ct,"ValidationError",{enumerable:!0,get:function(){return SK.default}});var IK=wy();Object.defineProperty(Ct,"MissingRefError",{enumerable:!0,get:function(){return IK.default}})});var eM=C(ku=>{"use strict";Object.defineProperty(ku,"__esModule",{value:!0});ku.formatLimitDefinition=void 0;var EK=QR(),hi=Ne(),Ts=hi.operators,Zy={formatMaximum:{okStr:"<=",ok:Ts.LTE,fail:Ts.GT},formatMinimum:{okStr:">=",ok:Ts.GTE,fail:Ts.LT},formatExclusiveMaximum:{okStr:"<",ok:Ts.LT,fail:Ts.GTE},formatExclusiveMinimum:{okStr:">",ok:Ts.GT,fail:Ts.LTE}},PK={message:({keyword:t,schemaCode:e})=>(0,hi.str)`should be ${Zy[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,hi._)`{comparison: ${Zy[t].okStr}, limit: ${e}}`};ku.formatLimitDefinition={keyword:Object.keys(Zy),type:"string",schemaType:"string",$data:!0,error:PK,code(t){let{gen:e,data:r,schemaCode:n,keyword:i,it:o}=t,{opts:s,self:a}=o;if(!s.validateFormats)return;let l=new EK.KeywordCxt(o,a.RULES.all.format.definition,"format");l.$data?c():u();function c(){let p=e.scopeValue("formats",{ref:a.formats,code:s.code.formats}),f=e.const("fmt",(0,hi._)`${p}[${l.schemaCode}]`);t.fail$data((0,hi.or)((0,hi._)`typeof ${f} != "object"`,(0,hi._)`${f} instanceof RegExp`,(0,hi._)`typeof ${f}.compare != "function"`,d(f)))}function u(){let p=l.schema,f=a.formats[p];if(!f||f===!0)return;if(typeof f!="object"||f instanceof RegExp||typeof f.compare!="function")throw new Error(`"${i}": format "${p}" does not define "compare" function`);let m=e.scopeValue("formats",{key:p,ref:f,code:s.code.formats?(0,hi._)`${s.code.formats}${(0,hi.getProperty)(p)}`:void 0});t.fail$data(d(m))}function d(p){return(0,hi._)`${p}.compare(${r}, ${n}) ${Zy[i].fail} 0`}},dependencies:["format"]};var TK=t=>(t.addKeyword(ku.formatLimitDefinition),t);ku.default=TK});var iM=C((xp,nM)=>{"use strict";Object.defineProperty(xp,"__esModule",{value:!0});var Su=DN(),AK=eM(),jS=Ne(),tM=new jS.Name("fullFormats"),zK=new jS.Name("fastFormats"),DS=(t,e={keywords:!0})=>{if(Array.isArray(e))return rM(t,e,Su.fullFormats,tM),t;let[r,n]=e.mode==="fast"?[Su.fastFormats,zK]:[Su.fullFormats,tM],i=e.formats||Su.formatNames;return rM(t,i,r,n),e.keywords&&(0,AK.default)(t),t};DS.get=(t,e="full")=>{let n=(e==="fast"?Su.fastFormats:Su.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function rM(t,e,r,n){var i,o;(i=(o=t.opts.code).formats)!==null&&i!==void 0||(o.formats=(0,jS._)`require("ajv-formats/dist/formats").${n}`);for(let s of e)t.addFormat(s,r[s])}nM.exports=xp=DS;Object.defineProperty(xp,"__esModule",{value:!0});xp.default=DS});var CD=C((NTe,zD)=>{"use strict";var Mv=Object.prototype.hasOwnProperty,AD=Object.prototype.toString,kD=Object.defineProperty,SD=Object.getOwnPropertyDescriptor,ID=function(e){return typeof Array.isArray=="function"?Array.isArray(e):AD.call(e)==="[object Array]"},ED=function(e){if(!e||AD.call(e)!=="[object Object]")return!1;var r=Mv.call(e,"constructor"),n=e.constructor&&e.constructor.prototype&&Mv.call(e.constructor.prototype,"isPrototypeOf");if(e.constructor&&!r&&!n)return!1;var i;for(i in e);return typeof i>"u"||Mv.call(e,i)},PD=function(e,r){kD&&r.name==="__proto__"?kD(e,r.name,{enumerable:!0,configurable:!0,value:r.newValue,writable:!0}):e[r.name]=r.newValue},TD=function(e,r){if(r==="__proto__")if(Mv.call(e,r)){if(SD)return SD(e,r).value}else return;return e[r]};zD.exports=function t(){var e,r,n,i,o,s,a=arguments[0],l=1,c=arguments.length,u=!1;for(typeof a=="boolean"&&(u=a,a=arguments[1]||{},l=2),(a==null||typeof a!="object"&&typeof a!="function")&&(a={});l<c;++l)if(e=arguments[l],e!=null)for(r in e)n=TD(a,r),i=TD(e,r),a!==i&&(u&&i&&(ED(i)||(o=ID(i)))?(o?(o=!1,s=n&&ID(n)?n:[]):s=n&&ED(n)?n:{},PD(a,{name:r,newValue:t(u,s,i)})):typeof i<"u"&&PD(a,{name:r,newValue:i}));return a}});function ue(t,e,r,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(t,r):i?i.value=r:e.set(t,r),r}function T(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)}var n_=function(){let{crypto:t}=globalThis;if(t?.randomUUID)return n_=t.randomUUID.bind(t),t.randomUUID();let e=new Uint8Array(1),r=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^r()&15>>+n/4).toString(16))};function td(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var rd=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){let e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)};var ee=class extends Error{},Jt=class t extends ee{constructor(e,r,n,i){super(`${t.makeMessage(e,r,n)}`),this.status=e,this.headers=i,this.requestID=i?.get("x-request-id"),this.error=r;let o=r;this.code=o?.code,this.param=o?.param,this.type=o?.type}static makeMessage(e,r,n){let i=r?.message?typeof r.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):n;return e&&i?`${e} ${i}`:e?`${e} status code (no body)`:i||"(no status code or body)"}static generate(e,r,n,i){if(!e||!i)return new Lo({message:n,cause:rd(r)});let o=r?.error;return e===400?new hl(e,o,n,i):e===401?new gl(e,o,n,i):e===403?new yl(e,o,n,i):e===404?new vl(e,o,n,i):e===409?new _l(e,o,n,i):e===422?new bl(e,o,n,i):e===429?new wl(e,o,n,i):e>=500?new xl(e,o,n,i):new t(e,o,n,i)}},Gt=class extends Jt{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},Lo=class extends Jt{constructor({message:e,cause:r}){super(void 0,void 0,e||"Connection error.",void 0),r&&(this.cause=r)}},Uo=class extends Lo{constructor({message:e}={}){super({message:e??"Request timed out."})}},hl=class extends Jt{},gl=class extends Jt{},yl=class extends Jt{},vl=class extends Jt{},_l=class extends Jt{},bl=class extends Jt{},wl=class extends Jt{},xl=class extends Jt{},$l=class extends ee{constructor(){super("Could not parse response content as the length limit was reached")}},kl=class extends ee{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},bi=class extends Error{constructor(e){super(e)}};var a4=/^[a-z][a-z0-9+.-]*:/i,_E=t=>a4.test(t),kr=t=>(kr=Array.isArray,kr(t)),i_=kr;function o_(t){return typeof t!="object"?{}:t??{}}function bE(t){if(!t)return!0;for(let e in t)return!1;return!0}function wE(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function nd(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}var xE=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new ee(`${t} must be an integer`);if(e<0)throw new ee(`${t} must be a positive integer`);return e};var $E=t=>{try{return JSON.parse(t)}catch{return}};var wi=t=>new Promise(e=>setTimeout(e,t));var Zo="6.10.0";var EE=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function l4(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}var c4=()=>{let t=l4();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Zo,"X-Stainless-OS":SE(Deno.build.os),"X-Stainless-Arch":kE(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Zo,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(t==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Zo,"X-Stainless-OS":SE(globalThis.process.platform??"unknown"),"X-Stainless-Arch":kE(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=u4();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Zo,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Zo,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function u4(){if(typeof navigator>"u"||!navigator)return null;let t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:r}of t){let n=r.exec(navigator.userAgent);if(n){let i=n[1]||0,o=n[2]||0,s=n[3]||0;return{browser:e,version:`${i}.${o}.${s}`}}}return null}var kE=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",SE=t=>(t=t.toLowerCase(),t.includes("ios")?"iOS":t==="android"?"Android":t==="darwin"?"MacOS":t==="win32"?"Windows":t==="freebsd"?"FreeBSD":t==="openbsd"?"OpenBSD":t==="linux"?"Linux":t?`Other:${t}`:"Unknown"),IE,PE=()=>IE??(IE=c4());function TE(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function s_(...t){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...t)}function Im(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return s_({start(){},async pull(r){let{done:n,value:i}=await e.next();n?r.close():r.enqueue(i)},async cancel(){await e.return?.()}})}function a_(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{async next(){try{let r=await e.read();return r?.done&&e.releaseLock(),r}catch(r){throw e.releaseLock(),r}},async return(){let r=e.cancel();return e.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function AE(t){if(t===null||typeof t!="object")return;if(t[Symbol.asyncIterator]){await t[Symbol.asyncIterator]().return?.();return}let e=t.getReader(),r=e.cancel();e.releaseLock(),await r}var zE=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var Em="RFC3986",l_=t=>String(t),Pm={RFC1738:t=>String(t).replace(/%20/g,"+"),RFC3986:l_},c_="RFC1738";var Tm=(t,e)=>(Tm=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Tm(t,e)),xi=(()=>{let t=[];for(let e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t})();var u_=1024,CE=(t,e,r,n,i)=>{if(t.length===0)return t;let o=t;if(typeof t=="symbol"?o=Symbol.prototype.toString.call(t):typeof t!="string"&&(o=String(t)),r==="iso-8859-1")return escape(o).replace(/%u[0-9a-f]{4}/gi,function(a){return"%26%23"+parseInt(a.slice(2),16)+"%3B"});let s="";for(let a=0;a<o.length;a+=u_){let l=o.length>=u_?o.slice(a,a+u_):o,c=[];for(let u=0;u<l.length;++u){let d=l.charCodeAt(u);if(d===45||d===46||d===95||d===126||d>=48&&d<=57||d>=65&&d<=90||d>=97&&d<=122||i===c_&&(d===40||d===41)){c[c.length]=l.charAt(u);continue}if(d<128){c[c.length]=xi[d];continue}if(d<2048){c[c.length]=xi[192|d>>6]+xi[128|d&63];continue}if(d<55296||d>=57344){c[c.length]=xi[224|d>>12]+xi[128|d>>6&63]+xi[128|d&63];continue}u+=1,d=65536+((d&1023)<<10|l.charCodeAt(u)&1023),c[c.length]=xi[240|d>>18]+xi[128|d>>12&63]+xi[128|d>>6&63]+xi[128|d&63]}s+=c.join("")}return s};function NE(t){return!t||typeof t!="object"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}function d_(t,e){if(kr(t)){let r=[];for(let n=0;n<t.length;n+=1)r.push(e(t[n]));return r}return e(t)}var RE={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},ME=function(t,e){Array.prototype.push.apply(t,kr(e)?e:[e])},OE,Yt={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:CE,encodeValuesOnly:!1,format:Em,formatter:l_,indices:!1,serializeDate(t){return(OE??(OE=Function.prototype.call.bind(Date.prototype.toISOString)))(t)},skipNulls:!1,strictNullHandling:!1};function p4(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}var f_={};function jE(t,e,r,n,i,o,s,a,l,c,u,d,p,f,m,h,y,g){let _=t,b=g,E=0,I=!1;for(;(b=b.get(f_))!==void 0&&!I;){let L=b.get(t);if(E+=1,typeof L<"u"){if(L===E)throw new RangeError("Cyclic object value");I=!0}typeof b.get(f_)>"u"&&(E=0)}if(typeof c=="function"?_=c(e,_):_ instanceof Date?_=p?.(_):r==="comma"&&kr(_)&&(_=d_(_,function(L){return L instanceof Date?p?.(L):L})),_===null){if(o)return l&&!h?l(e,Yt.encoder,y,"key",f):e;_=""}if(p4(_)||NE(_)){if(l){let L=h?e:l(e,Yt.encoder,y,"key",f);return[m?.(L)+"="+m?.(l(_,Yt.encoder,y,"value",f))]}return[m?.(e)+"="+m?.(String(_))]}let P=[];if(typeof _>"u")return P;let M;if(r==="comma"&&kr(_))h&&l&&(_=d_(_,l)),M=[{value:_.length>0?_.join(",")||null:void 0}];else if(kr(c))M=c;else{let L=Object.keys(_);M=u?L.sort(u):L}let V=a?String(e).replace(/\./g,"%2E"):String(e),R=n&&kr(_)&&_.length===1?V+"[]":V;if(i&&kr(_)&&_.length===0)return R+"[]";for(let L=0;L<M.length;++L){let G=M[L],H=typeof G=="object"&&typeof G.value<"u"?G.value:_[G];if(s&&H===null)continue;let W=d&&a?G.replace(/\./g,"%2E"):G,Y=kr(_)?typeof r=="function"?r(R,W):R:R+(d?"."+W:"["+W+"]");g.set(t,E);let ie=new WeakMap;ie.set(f_,g),ME(P,jE(H,Y,r,n,i,o,s,a,r==="comma"&&h&&kr(_)?null:l,c,u,d,p,f,m,h,y,ie))}return P}function m4(t=Yt){if(typeof t.allowEmptyArrays<"u"&&typeof t.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof t.encodeDotInKeys<"u"&&typeof t.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(t.encoder!==null&&typeof t.encoder<"u"&&typeof t.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=t.charset||Yt.charset;if(typeof t.charset<"u"&&t.charset!=="utf-8"&&t.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let r=Em;if(typeof t.format<"u"){if(!Tm(Pm,t.format))throw new TypeError("Unknown format option provided.");r=t.format}let n=Pm[r],i=Yt.filter;(typeof t.filter=="function"||kr(t.filter))&&(i=t.filter);let o;if(t.arrayFormat&&t.arrayFormat in RE?o=t.arrayFormat:"indices"in t?o=t.indices?"indices":"repeat":o=Yt.arrayFormat,"commaRoundTrip"in t&&typeof t.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let s=typeof t.allowDots>"u"?t.encodeDotInKeys?!0:Yt.allowDots:!!t.allowDots;return{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:Yt.addQueryPrefix,allowDots:s,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:Yt.allowEmptyArrays,arrayFormat:o,charset:e,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:Yt.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:typeof t.delimiter>"u"?Yt.delimiter:t.delimiter,encode:typeof t.encode=="boolean"?t.encode:Yt.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:Yt.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:Yt.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:Yt.encodeValuesOnly,filter:i,format:r,formatter:n,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:Yt.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:Yt.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:Yt.strictNullHandling}}function p_(t,e={}){let r=t,n=m4(e),i,o;typeof n.filter=="function"?(o=n.filter,r=o("",r)):kr(n.filter)&&(o=n.filter,i=o);let s=[];if(typeof r!="object"||r===null)return"";let a=RE[n.arrayFormat],l=a==="comma"&&n.commaRoundTrip;i||(i=Object.keys(r)),n.sort&&i.sort(n.sort);let c=new WeakMap;for(let p=0;p<i.length;++p){let f=i[p];n.skipNulls&&r[f]===null||ME(s,jE(r[f],f,a,l,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,c))}let u=s.join(n.delimiter),d=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?d+="utf8=%26%2310003%3B&":d+="utf8=%E2%9C%93&"),u.length>0?d+u:""}function UE(t){let e=0;for(let i of t)e+=i.length;let r=new Uint8Array(e),n=0;for(let i of t)r.set(i,n),n+=i.length;return r}var DE;function Sl(t){let e;return(DE??(e=new globalThis.TextEncoder,DE=e.encode.bind(e)))(t)}var LE;function m_(t){let e;return(LE??(e=new globalThis.TextDecoder,LE=e.decode.bind(e)))(t)}var mn,hn,Fs=class{constructor(){mn.set(this,void 0),hn.set(this,void 0),ue(this,mn,new Uint8Array,"f"),ue(this,hn,null,"f")}decode(e){if(e==null)return[];let r=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Sl(e):e;ue(this,mn,UE([T(this,mn,"f"),r]),"f");let n=[],i;for(;(i=g4(T(this,mn,"f"),T(this,hn,"f")))!=null;){if(i.carriage&&T(this,hn,"f")==null){ue(this,hn,i.index,"f");continue}if(T(this,hn,"f")!=null&&(i.index!==T(this,hn,"f")+1||i.carriage)){n.push(m_(T(this,mn,"f").subarray(0,T(this,hn,"f")-1))),ue(this,mn,T(this,mn,"f").subarray(T(this,hn,"f")),"f"),ue(this,hn,null,"f");continue}let o=T(this,hn,"f")!==null?i.preceding-1:i.preceding,s=m_(T(this,mn,"f").subarray(0,o));n.push(s),ue(this,mn,T(this,mn,"f").subarray(i.index),"f"),ue(this,hn,null,"f")}return n}flush(){return T(this,mn,"f").length?this.decode(`
|
|
16
|
+
`):[]}};mn=new WeakMap,hn=new WeakMap;Fs.NEWLINE_CHARS=new Set([`
|
|
17
|
+
`,"\r"]);Fs.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function g4(t,e){for(let i=e??0;i<t.length;i++){if(t[i]===10)return{preceding:i,index:i+1,carriage:!1};if(t[i]===13)return{preceding:i,index:i+1,carriage:!0}}return null}function ZE(t){for(let n=0;n<t.length-1;n++){if(t[n]===10&&t[n+1]===10||t[n]===13&&t[n+1]===13)return n+2;if(t[n]===13&&t[n+1]===10&&n+3<t.length&&t[n+2]===13&&t[n+3]===10)return n+4}return-1}var zm={off:0,error:200,warn:300,info:400,debug:500},h_=(t,e,r)=>{if(t){if(wE(zm,t))return t;Mt(r).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(zm))}`)}};function id(){}function Am(t,e,r){return!e||zm[t]>zm[r]?id:e[t].bind(e)}var y4={error:id,warn:id,info:id,debug:id},FE=new WeakMap;function Mt(t){let e=t.logger,r=t.logLevel??"off";if(!e)return y4;let n=FE.get(e);if(n&&n[0]===r)return n[1];let i={error:Am("error",e,r),warn:Am("warn",e,r),info:Am("info",e,r),debug:Am("debug",e,r)};return FE.set(e,[r,i]),i}var Qi=t=>(t.options&&(t.options={...t.options},delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,r])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":r]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t);var od,$i=class t{constructor(e,r,n){this.iterator=e,od.set(this,void 0),this.controller=r,ue(this,od,n,"f")}static fromSSEResponse(e,r,n){let i=!1,o=n?Mt(n):console;async function*s(){if(i)throw new ee("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let a=!1;try{for await(let l of v4(e,r))if(!a){if(l.data.startsWith("[DONE]")){a=!0;continue}if(l.event===null||!l.event.startsWith("thread.")){let c;try{c=JSON.parse(l.data)}catch(u){throw o.error("Could not parse message into JSON:",l.data),o.error("From chunk:",l.raw),u}if(c&&c.error)throw new Jt(void 0,c.error,void 0,e.headers);yield c}else{let c;try{c=JSON.parse(l.data)}catch(u){throw console.error("Could not parse message into JSON:",l.data),console.error("From chunk:",l.raw),u}if(l.event=="error")throw new Jt(void 0,c.error,c.message,void 0);yield{event:l.event,data:c}}}a=!0}catch(l){if(td(l))return;throw l}finally{a||r.abort()}}return new t(s,r,n)}static fromReadableStream(e,r,n){let i=!1;async function*o(){let a=new Fs,l=a_(e);for await(let c of l)for(let u of a.decode(c))yield u;for(let c of a.flush())yield c}async function*s(){if(i)throw new ee("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let a=!1;try{for await(let l of o())a||l&&(yield JSON.parse(l));a=!0}catch(l){if(td(l))return;throw l}finally{a||r.abort()}}return new t(s,r,n)}[(od=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],r=[],n=this.iterator(),i=o=>({next:()=>{if(o.length===0){let s=n.next();e.push(s),r.push(s)}return o.shift()}});return[new t(()=>i(e),this.controller,T(this,od,"f")),new t(()=>i(r),this.controller,T(this,od,"f"))]}toReadableStream(){let e=this,r;return s_({async start(){r=e[Symbol.asyncIterator]()},async pull(n){try{let{value:i,done:o}=await r.next();if(o)return n.close();let s=Sl(JSON.stringify(i)+`
|
|
18
|
+
`);n.enqueue(s)}catch(i){n.error(i)}},async cancel(){await r.return?.()}})}};async function*v4(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new ee("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new ee("Attempted to iterate over a response with no body");let r=new g_,n=new Fs,i=a_(t.body);for await(let o of _4(i))for(let s of n.decode(o)){let a=r.decode(s);a&&(yield a)}for(let o of n.flush()){let s=r.decode(o);s&&(yield s)}}async function*_4(t){let e=new Uint8Array;for await(let r of t){if(r==null)continue;let n=r instanceof ArrayBuffer?new Uint8Array(r):typeof r=="string"?Sl(r):r,i=new Uint8Array(e.length+n.length);i.set(e),i.set(n,e.length),e=i;let o;for(;(o=ZE(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}var g_=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let o={event:this.event,data:this.data.join(`
|
|
19
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(e),e.startsWith(":"))return null;let[r,n,i]=b4(e,":");return i.startsWith(" ")&&(i=i.substring(1)),r==="event"?this.event=i:r==="data"&&this.data.push(i),null}};function b4(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}async function Cm(t,e){let{response:r,requestLogID:n,retryOfRequestLogID:i,startTime:o}=e,s=await(async()=>{if(e.options.stream)return Mt(t).debug("response",r.status,r.url,r.headers,r.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(r,e.controller,t):$i.fromSSEResponse(r,e.controller,t);if(r.status===204)return null;if(e.options.__binaryResponse)return r;let l=r.headers.get("content-type")?.split(";")[0]?.trim();if(l?.includes("application/json")||l?.endsWith("+json")){let d=await r.json();return y_(d,r)}return await r.text()})();return Mt(t).debug(`[${n}] response parsed`,Qi({retryOfRequestLogID:i,url:r.url,status:r.status,body:s,durationMs:Date.now()-o})),s}function y_(t,e){return!t||typeof t!="object"||Array.isArray(t)?t:Object.defineProperty(t,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var sd,Vs=class t extends Promise{constructor(e,r,n=Cm){super(i=>{i(null)}),this.responsePromise=r,this.parseResponse=n,sd.set(this,void 0),ue(this,sd,e,"f")}_thenUnwrap(e){return new t(T(this,sd,"f"),this.responsePromise,async(r,n)=>y_(e(await this.parseResponse(r,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,r]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:r,request_id:r.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(T(this,sd,"f"),e))),this.parsedPromise}then(e,r){return this.parse().then(e,r)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};sd=new WeakMap;var Nm,ad=class{constructor(e,r,n,i){Nm.set(this,void 0),ue(this,Nm,e,"f"),this.options=i,this.response=r,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new ee("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await T(this,Nm,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Nm=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let r of e.getPaginatedItems())yield r}},ld=class extends Vs{constructor(e,r,n){super(e,r,async(i,o)=>new n(i,o.response,await Cm(i,o),o.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let r of e)yield r}},ki=class extends ad{constructor(e,r,n,i){super(e,r,n,i),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},Ae=class extends ad{constructor(e,r,n,i){super(e,r,n,i),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),r=e[e.length-1]?.id;return r?{...this.options,query:{...o_(this.options.query),after:r}}:null}},eo=class extends ad{constructor(e,r,n,i){super(e,r,n,i),this.data=n.data||[],this.has_more=n.has_more||!1,this.last_id=n.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;return e?{...this.options,query:{...o_(this.options.query),after:e}}:null}};var b_=()=>{if(typeof File>"u"){let{process:t}=globalThis,e=typeof t?.versions?.node=="string"&&parseInt(t.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function Il(t,e,r){return b_(),new File(t,e??"unknown_file",r)}function cd(t){return(typeof t=="object"&&t!==null&&("name"in t&&t.name&&String(t.name)||"url"in t&&t.url&&String(t.url)||"filename"in t&&t.filename&&String(t.filename)||"path"in t&&t.path&&String(t.path))||"").split(/[\\/]/).pop()||void 0}var Om=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",w_=async(t,e)=>v_(t.body)?{...t,body:await qE(t.body,e)}:t,gn=async(t,e)=>({...t,body:await qE(t.body,e)}),VE=new WeakMap;function x4(t){let e=typeof t=="function"?t:t.fetch,r=VE.get(e);if(r)return r;let n=(async()=>{try{let i="Response"in e?e.Response:(await e("data:,")).constructor,o=new FormData;return o.toString()!==await new i(o).text()}catch{return!0}})();return VE.set(e,n),n}var qE=async(t,e)=>{if(!await x4(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let r=new FormData;return await Promise.all(Object.entries(t||{}).map(([n,i])=>__(r,n,i))),r},WE=t=>t instanceof Blob&&"name"in t,$4=t=>typeof t=="object"&&t!==null&&(t instanceof Response||Om(t)||WE(t)),v_=t=>{if($4(t))return!0;if(Array.isArray(t))return t.some(v_);if(t&&typeof t=="object"){for(let e in t)if(v_(t[e]))return!0}return!1},__=async(t,e,r)=>{if(r!==void 0){if(r==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")t.append(e,String(r));else if(r instanceof Response)t.append(e,Il([await r.blob()],cd(r)));else if(Om(r))t.append(e,Il([await new Response(Im(r)).blob()],cd(r)));else if(WE(r))t.append(e,r,cd(r));else if(Array.isArray(r))await Promise.all(r.map(n=>__(t,e+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,i])=>__(t,`${e}[${n}]`,i)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)}};var BE=t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function",k4=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&BE(t),S4=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function Rm(t,e,r){if(b_(),t=await t,k4(t))return t instanceof File?t:Il([await t.arrayBuffer()],t.name);if(S4(t)){let i=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),Il(await x_(i),e,r)}let n=await x_(t);if(e||(e=cd(t)),!r?.type){let i=n.find(o=>typeof o=="object"&&"type"in o&&o.type);typeof i=="string"&&(r={...r,type:i})}return Il(n,e,r)}async function x_(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(BE(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(Om(t))for await(let r of t)e.push(...await x_(r));else{let r=t?.constructor?.name;throw new Error(`Unexpected data type: ${typeof t}${r?`; constructor: ${r}`:""}${I4(t)}`)}return e}function I4(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}var D=class{constructor(e){this._client=e}};function HE(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var GE=Object.freeze(Object.create(null)),P4=(t=HE)=>function(r,...n){if(r.length===1)return r[0];let i=!1,o=[],s=r.reduce((u,d,p)=>{/[?#]/.test(d)&&(i=!0);let f=n[p],m=(i?encodeURIComponent:t)(""+f);return p!==n.length&&(f==null||typeof f=="object"&&f.toString===Object.getPrototypeOf(Object.getPrototypeOf(f.hasOwnProperty??GE)??GE)?.toString)&&(m=f+"",o.push({start:u.length+d.length,length:m.length,error:`Value of type ${Object.prototype.toString.call(f).slice(8,-1)} is not a valid path parameter`})),u+d+(p===n.length?"":m)},""),a=s.split(/[?#]/,1)[0],l=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,c;for(;(c=l.exec(a))!==null;)o.push({start:c.index,length:c[0].length,error:`Value "${c[0]}" can't be safely passed as a path parameter`});if(o.sort((u,d)=>u.start-d.start),o.length>0){let u=0,d=o.reduce((p,f)=>{let m=" ".repeat(f.start-u),h="^".repeat(f.length);return u=f.start+f.length,p+m+h},"");throw new ee(`Path parameters result in path with invalid segments:
|
|
20
|
+
${o.map(p=>p.error).join(`
|
|
21
|
+
`)}
|
|
22
|
+
${s}
|
|
23
|
+
${d}`)}return s},O=P4(HE);var qs=class extends D{list(e,r={},n){return this._client.getAPIList(O`/chat/completions/${e}/messages`,Ae,{query:r,...n})}};function ud(t){return t!==void 0&&"function"in t&&t.function!==void 0}function dd(t){return t?.$brand==="auto-parseable-response-format"}function Ws(t){return t?.$brand==="auto-parseable-tool"}function XE(t,e){return!e||!$_(e)?{...t,choices:t.choices.map(r=>(JE(r.message.tool_calls),{...r,message:{...r.message,parsed:null,...r.message.tool_calls?{tool_calls:r.message.tool_calls}:void 0}}))}:fd(t,e)}function fd(t,e){let r=t.choices.map(n=>{if(n.finish_reason==="length")throw new $l;if(n.finish_reason==="content_filter")throw new kl;return JE(n.message.tool_calls),{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:n.message.tool_calls?.map(i=>C4(e,i))??void 0}:void 0,parsed:n.message.content&&!n.message.refusal?z4(e,n.message.content):null}}});return{...t,choices:r}}function z4(t,e){return t.response_format?.type!=="json_schema"?null:t.response_format?.type==="json_schema"?"$parseRaw"in t.response_format?t.response_format.$parseRaw(e):JSON.parse(e):null}function C4(t,e){let r=t.tools?.find(n=>ud(n)&&n.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:Ws(r)?r.$parseRaw(e.function.arguments):r?.function.strict?JSON.parse(e.function.arguments):null}}}function KE(t,e){if(!t||!("tools"in t)||!t.tools)return!1;let r=t.tools?.find(n=>ud(n)&&n.function?.name===e.function.name);return ud(r)&&(Ws(r)||r?.function.strict||!1)}function $_(t){return dd(t.response_format)?!0:t.tools?.some(e=>Ws(e)||e.type==="function"&&e.function.strict===!0)??!1}function JE(t){for(let e of t||[])if(e.type!=="function")throw new ee(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function YE(t){for(let e of t??[]){if(e.type!=="function")throw new ee(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new ee(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var El=t=>t?.role==="assistant",k_=t=>t?.role==="tool";var S_,Mm,jm,pd,md,Dm,hd,to,gd,Lm,Um,Pl,QE,Fo=class{constructor(){S_.add(this),this.controller=new AbortController,Mm.set(this,void 0),jm.set(this,()=>{}),pd.set(this,()=>{}),md.set(this,void 0),Dm.set(this,()=>{}),hd.set(this,()=>{}),to.set(this,{}),gd.set(this,!1),Lm.set(this,!1),Um.set(this,!1),Pl.set(this,!1),ue(this,Mm,new Promise((e,r)=>{ue(this,jm,e,"f"),ue(this,pd,r,"f")}),"f"),ue(this,md,new Promise((e,r)=>{ue(this,Dm,e,"f"),ue(this,hd,r,"f")}),"f"),T(this,Mm,"f").catch(()=>{}),T(this,md,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},T(this,S_,"m",QE).bind(this))},0)}_connected(){this.ended||(T(this,jm,"f").call(this),this._emit("connect"))}get ended(){return T(this,gd,"f")}get errored(){return T(this,Lm,"f")}get aborted(){return T(this,Um,"f")}abort(){this.controller.abort()}on(e,r){return(T(this,to,"f")[e]||(T(this,to,"f")[e]=[])).push({listener:r}),this}off(e,r){let n=T(this,to,"f")[e];if(!n)return this;let i=n.findIndex(o=>o.listener===r);return i>=0&&n.splice(i,1),this}once(e,r){return(T(this,to,"f")[e]||(T(this,to,"f")[e]=[])).push({listener:r,once:!0}),this}emitted(e){return new Promise((r,n)=>{ue(this,Pl,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,r)})}async done(){ue(this,Pl,!0,"f"),await T(this,md,"f")}_emit(e,...r){if(T(this,gd,"f"))return;e==="end"&&(ue(this,gd,!0,"f"),T(this,Dm,"f").call(this));let n=T(this,to,"f")[e];if(n&&(T(this,to,"f")[e]=n.filter(i=>!i.once),n.forEach(({listener:i})=>i(...r))),e==="abort"){let i=r[0];!T(this,Pl,"f")&&!n?.length&&Promise.reject(i),T(this,pd,"f").call(this,i),T(this,hd,"f").call(this,i),this._emit("end");return}if(e==="error"){let i=r[0];!T(this,Pl,"f")&&!n?.length&&Promise.reject(i),T(this,pd,"f").call(this,i),T(this,hd,"f").call(this,i),this._emit("end")}}_emitFinal(){}};Mm=new WeakMap,jm=new WeakMap,pd=new WeakMap,md=new WeakMap,Dm=new WeakMap,hd=new WeakMap,to=new WeakMap,gd=new WeakMap,Lm=new WeakMap,Um=new WeakMap,Pl=new WeakMap,S_=new WeakSet,QE=function(e){if(ue(this,Lm,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new Gt),e instanceof Gt)return ue(this,Um,!0,"f"),this._emit("abort",e);if(e instanceof ee)return this._emit("error",e);if(e instanceof Error){let r=new ee(e.message);return r.cause=e,this._emit("error",r)}return this._emit("error",new ee(String(e)))};function e1(t){return typeof t.parse=="function"}var Lr,I_,Zm,E_,P_,T_,t1,r1,N4=10,Tl=class extends Fo{constructor(){super(...arguments),Lr.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);let r=e.choices[0]?.message;return r&&this._addMessage(r),e}_addMessage(e,r=!0){if("content"in e||(e.content=null),this.messages.push(e),r){if(this._emit("message",e),k_(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(El(e)&&e.tool_calls)for(let n of e.tool_calls)n.type==="function"&&this._emit("functionToolCall",n.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new ee("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),T(this,Lr,"m",I_).call(this)}async finalMessage(){return await this.done(),T(this,Lr,"m",Zm).call(this)}async finalFunctionToolCall(){return await this.done(),T(this,Lr,"m",E_).call(this)}async finalFunctionToolCallResult(){return await this.done(),T(this,Lr,"m",P_).call(this)}async totalUsage(){return await this.done(),T(this,Lr,"m",T_).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let r=T(this,Lr,"m",Zm).call(this);r&&this._emit("finalMessage",r);let n=T(this,Lr,"m",I_).call(this);n&&this._emit("finalContent",n);let i=T(this,Lr,"m",E_).call(this);i&&this._emit("finalFunctionToolCall",i);let o=T(this,Lr,"m",P_).call(this);o!=null&&this._emit("finalFunctionToolCallResult",o),this._chatCompletions.some(s=>s.usage)&&this._emit("totalUsage",T(this,Lr,"m",T_).call(this))}async _createChatCompletion(e,r,n){let i=n?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort())),T(this,Lr,"m",t1).call(this,r);let o=await e.chat.completions.create({...r,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(fd(o,r))}async _runChatCompletion(e,r,n){for(let i of r.messages)this._addMessage(i,!1);return await this._createChatCompletion(e,r,n)}async _runTools(e,r,n){let i="tool",{tool_choice:o="auto",stream:s,...a}=r,l=typeof o!="string"&&o.type==="function"&&o?.function?.name,{maxChatCompletions:c=N4}=n||{},u=r.tools.map(f=>{if(Ws(f)){if(!f.$callback)throw new ee("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:f.$callback,name:f.function.name,description:f.function.description||"",parameters:f.function.parameters,parse:f.$parseRaw,strict:!0}}}return f}),d={};for(let f of u)f.type==="function"&&(d[f.function.name||f.function.function.name]=f.function);let p="tools"in r?u.map(f=>f.type==="function"?{type:"function",function:{name:f.function.name||f.function.function.name,parameters:f.function.parameters,description:f.function.description,strict:f.function.strict}}:f):void 0;for(let f of r.messages)this._addMessage(f,!1);for(let f=0;f<c;++f){let h=(await this._createChatCompletion(e,{...a,tool_choice:o,tools:p,messages:[...this.messages]},n)).choices[0]?.message;if(!h)throw new ee("missing message in ChatCompletion response");if(!h.tool_calls?.length)return;for(let y of h.tool_calls){if(y.type!=="function")continue;let g=y.id,{name:_,arguments:b}=y.function,E=d[_];if(E){if(l&&l!==_){let V=`Invalid tool_call: ${JSON.stringify(_)}. ${JSON.stringify(l)} requested. Please try again`;this._addMessage({role:i,tool_call_id:g,content:V});continue}}else{let V=`Invalid tool_call: ${JSON.stringify(_)}. Available options are: ${Object.keys(d).map(R=>JSON.stringify(R)).join(", ")}. Please try again`;this._addMessage({role:i,tool_call_id:g,content:V});continue}let I;try{I=e1(E)?await E.parse(b):b}catch(V){let R=V instanceof Error?V.message:String(V);this._addMessage({role:i,tool_call_id:g,content:R});continue}let P=await E.function(I,this),M=T(this,Lr,"m",r1).call(this,P);if(this._addMessage({role:i,tool_call_id:g,content:M}),l)return}}}};Lr=new WeakSet,I_=function(){return T(this,Lr,"m",Zm).call(this).content??null},Zm=function(){let e=this.messages.length;for(;e-- >0;){let r=this.messages[e];if(El(r))return{...r,content:r.content??null,refusal:r.refusal??null}}throw new ee("stream ended without producing a ChatCompletionMessage with role=assistant")},E_=function(){for(let e=this.messages.length-1;e>=0;e--){let r=this.messages[e];if(El(r)&&r?.tool_calls?.length)return r.tool_calls.filter(n=>n.type==="function").at(-1)?.function}},P_=function(){for(let e=this.messages.length-1;e>=0;e--){let r=this.messages[e];if(k_(r)&&r.content!=null&&typeof r.content=="string"&&this.messages.some(n=>n.role==="assistant"&&n.tool_calls?.some(i=>i.type==="function"&&i.id===r.tool_call_id)))return r.content}},T_=function(){let e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:r}of this._chatCompletions)r&&(e.completion_tokens+=r.completion_tokens,e.prompt_tokens+=r.prompt_tokens,e.total_tokens+=r.total_tokens);return e},t1=function(e){if(e.n!=null&&e.n>1)throw new ee("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},r1=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var yd=class t extends Tl{static runTools(e,r,n){let i=new t,o={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return i._run(()=>i._runTools(e,r,o)),i}_addMessage(e,r=!0){super._addMessage(e,r),El(e)&&e.content&&this._emit("content",e.content)}};var rr={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511},A_=class extends Error{},z_=class extends Error{};function O4(t,e=rr.ALL){if(typeof t!="string")throw new TypeError(`expecting str, got ${typeof t}`);if(!t.trim())throw new Error(`${t} is empty`);return R4(t.trim(),e)}var R4=(t,e)=>{let r=t.length,n=0,i=p=>{throw new A_(`${p} at position ${n}`)},o=p=>{throw new z_(`${p} at position ${n}`)},s=()=>(d(),n>=r&&i("Unexpected end of input"),t[n]==='"'?a():t[n]==="{"?l():t[n]==="["?c():t.substring(n,n+4)==="null"||rr.NULL&e&&r-n<4&&"null".startsWith(t.substring(n))?(n+=4,null):t.substring(n,n+4)==="true"||rr.BOOL&e&&r-n<4&&"true".startsWith(t.substring(n))?(n+=4,!0):t.substring(n,n+5)==="false"||rr.BOOL&e&&r-n<5&&"false".startsWith(t.substring(n))?(n+=5,!1):t.substring(n,n+8)==="Infinity"||rr.INFINITY&e&&r-n<8&&"Infinity".startsWith(t.substring(n))?(n+=8,1/0):t.substring(n,n+9)==="-Infinity"||rr.MINUS_INFINITY&e&&1<r-n&&r-n<9&&"-Infinity".startsWith(t.substring(n))?(n+=9,-1/0):t.substring(n,n+3)==="NaN"||rr.NAN&e&&r-n<3&&"NaN".startsWith(t.substring(n))?(n+=3,NaN):u()),a=()=>{let p=n,f=!1;for(n++;n<r&&(t[n]!=='"'||f&&t[n-1]==="\\");)f=t[n]==="\\"?!f:!1,n++;if(t.charAt(n)=='"')try{return JSON.parse(t.substring(p,++n-Number(f)))}catch(m){o(String(m))}else if(rr.STR&e)try{return JSON.parse(t.substring(p,n-Number(f))+'"')}catch{return JSON.parse(t.substring(p,t.lastIndexOf("\\"))+'"')}i("Unterminated string literal")},l=()=>{n++,d();let p={};try{for(;t[n]!=="}";){if(d(),n>=r&&rr.OBJ&e)return p;let f=a();d(),n++;try{let m=s();Object.defineProperty(p,f,{value:m,writable:!0,enumerable:!0,configurable:!0})}catch(m){if(rr.OBJ&e)return p;throw m}d(),t[n]===","&&n++}}catch{if(rr.OBJ&e)return p;i("Expected '}' at end of object")}return n++,p},c=()=>{n++;let p=[];try{for(;t[n]!=="]";)p.push(s()),d(),t[n]===","&&n++}catch{if(rr.ARR&e)return p;i("Expected ']' at end of array")}return n++,p},u=()=>{if(n===0){t==="-"&&rr.NUM&e&&i("Not sure what '-' is");try{return JSON.parse(t)}catch(f){if(rr.NUM&e)try{return t[t.length-1]==="."?JSON.parse(t.substring(0,t.lastIndexOf("."))):JSON.parse(t.substring(0,t.lastIndexOf("e")))}catch{}o(String(f))}}let p=n;for(t[n]==="-"&&n++;t[n]&&!",]}".includes(t[n]);)n++;n==r&&!(rr.NUM&e)&&i("Unterminated number literal");try{return JSON.parse(t.substring(p,n))}catch{t.substring(p,n)==="-"&&rr.NUM&e&&i("Not sure what '-' is");try{return JSON.parse(t.substring(p,t.lastIndexOf("e")))}catch(m){o(String(m))}}},d=()=>{for(;n<r&&`
|
|
24
|
+
\r `.includes(t[n]);)n++};return s()},C_=t=>O4(t,rr.ALL^rr.NUM);var Qt,ro,Al,Vo,N_,Fm,O_,R_,M_,Vm,j_,n1,Bs=class t extends Tl{constructor(e){super(),Qt.add(this),ro.set(this,void 0),Al.set(this,void 0),Vo.set(this,void 0),ue(this,ro,e,"f"),ue(this,Al,[],"f")}get currentChatCompletionSnapshot(){return T(this,Vo,"f")}static fromReadableStream(e){let r=new t(null);return r._run(()=>r._fromReadableStream(e)),r}static createChatCompletion(e,r,n){let i=new t(r);return i._run(()=>i._runChatCompletion(e,{...r,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),i}async _createChatCompletion(e,r,n){super._createChatCompletion;let i=n?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort())),T(this,Qt,"m",N_).call(this);let o=await e.chat.completions.create({...r,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(let s of o)T(this,Qt,"m",O_).call(this,s);if(o.controller.signal?.aborted)throw new Gt;return this._addChatCompletion(T(this,Qt,"m",Vm).call(this))}async _fromReadableStream(e,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),T(this,Qt,"m",N_).call(this),this._connected();let i=$i.fromReadableStream(e,this.controller),o;for await(let s of i)o&&o!==s.id&&this._addChatCompletion(T(this,Qt,"m",Vm).call(this)),T(this,Qt,"m",O_).call(this,s),o=s.id;if(i.controller.signal?.aborted)throw new Gt;return this._addChatCompletion(T(this,Qt,"m",Vm).call(this))}[(ro=new WeakMap,Al=new WeakMap,Vo=new WeakMap,Qt=new WeakSet,N_=function(){this.ended||ue(this,Vo,void 0,"f")},Fm=function(r){let n=T(this,Al,"f")[r.index];return n||(n={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},T(this,Al,"f")[r.index]=n,n)},O_=function(r){if(this.ended)return;let n=T(this,Qt,"m",n1).call(this,r);this._emit("chunk",r,n);for(let i of r.choices){let o=n.choices[i.index];i.delta.content!=null&&o.message?.role==="assistant"&&o.message?.content&&(this._emit("content",i.delta.content,o.message.content),this._emit("content.delta",{delta:i.delta.content,snapshot:o.message.content,parsed:o.message.parsed})),i.delta.refusal!=null&&o.message?.role==="assistant"&&o.message?.refusal&&this._emit("refusal.delta",{delta:i.delta.refusal,snapshot:o.message.refusal}),i.logprobs?.content!=null&&o.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:i.logprobs?.content,snapshot:o.logprobs?.content??[]}),i.logprobs?.refusal!=null&&o.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:i.logprobs?.refusal,snapshot:o.logprobs?.refusal??[]});let s=T(this,Qt,"m",Fm).call(this,o);o.finish_reason&&(T(this,Qt,"m",M_).call(this,o),s.current_tool_call_index!=null&&T(this,Qt,"m",R_).call(this,o,s.current_tool_call_index));for(let a of i.delta.tool_calls??[])s.current_tool_call_index!==a.index&&(T(this,Qt,"m",M_).call(this,o),s.current_tool_call_index!=null&&T(this,Qt,"m",R_).call(this,o,s.current_tool_call_index)),s.current_tool_call_index=a.index;for(let a of i.delta.tool_calls??[]){let l=o.message.tool_calls?.[a.index];l?.type&&(l?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:l.function?.name,index:a.index,arguments:l.function.arguments,parsed_arguments:l.function.parsed_arguments,arguments_delta:a.function?.arguments??""}):(l?.type,void 0))}}},R_=function(r,n){if(T(this,Qt,"m",Fm).call(this,r).done_tool_calls.has(n))return;let o=r.message.tool_calls?.[n];if(!o)throw new Error("no tool call snapshot");if(!o.type)throw new Error("tool call snapshot missing `type`");if(o.type==="function"){let s=T(this,ro,"f")?.tools?.find(a=>ud(a)&&a.function.name===o.function.name);this._emit("tool_calls.function.arguments.done",{name:o.function.name,index:n,arguments:o.function.arguments,parsed_arguments:Ws(s)?s.$parseRaw(o.function.arguments):s?.function.strict?JSON.parse(o.function.arguments):null})}else o.type},M_=function(r){let n=T(this,Qt,"m",Fm).call(this,r);if(r.message.content&&!n.content_done){n.content_done=!0;let i=T(this,Qt,"m",j_).call(this);this._emit("content.done",{content:r.message.content,parsed:i?i.$parseRaw(r.message.content):null})}r.message.refusal&&!n.refusal_done&&(n.refusal_done=!0,this._emit("refusal.done",{refusal:r.message.refusal})),r.logprobs?.content&&!n.logprobs_content_done&&(n.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:r.logprobs.content})),r.logprobs?.refusal&&!n.logprobs_refusal_done&&(n.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:r.logprobs.refusal}))},Vm=function(){if(this.ended)throw new ee("stream has ended, this shouldn't happen");let r=T(this,Vo,"f");if(!r)throw new ee("request ended without sending any chunks");return ue(this,Vo,void 0,"f"),ue(this,Al,[],"f"),M4(r,T(this,ro,"f"))},j_=function(){let r=T(this,ro,"f")?.response_format;return dd(r)?r:null},n1=function(r){var n,i,o,s;let a=T(this,Vo,"f"),{choices:l,...c}=r;a?Object.assign(a,c):a=ue(this,Vo,{...c,choices:[]},"f");for(let{delta:u,finish_reason:d,index:p,logprobs:f=null,...m}of r.choices){let h=a.choices[p];if(h||(h=a.choices[p]={finish_reason:d,index:p,message:{},logprobs:f,...m}),f)if(!h.logprobs)h.logprobs=Object.assign({},f);else{let{content:P,refusal:M,...V}=f;Object.assign(h.logprobs,V),P&&((n=h.logprobs).content??(n.content=[]),h.logprobs.content.push(...P)),M&&((i=h.logprobs).refusal??(i.refusal=[]),h.logprobs.refusal.push(...M))}if(d&&(h.finish_reason=d,T(this,ro,"f")&&$_(T(this,ro,"f")))){if(d==="length")throw new $l;if(d==="content_filter")throw new kl}if(Object.assign(h,m),!u)continue;let{content:y,refusal:g,function_call:_,role:b,tool_calls:E,...I}=u;if(Object.assign(h.message,I),g&&(h.message.refusal=(h.message.refusal||"")+g),b&&(h.message.role=b),_&&(h.message.function_call?(_.name&&(h.message.function_call.name=_.name),_.arguments&&((o=h.message.function_call).arguments??(o.arguments=""),h.message.function_call.arguments+=_.arguments)):h.message.function_call=_),y&&(h.message.content=(h.message.content||"")+y,!h.message.refusal&&T(this,Qt,"m",j_).call(this)&&(h.message.parsed=C_(h.message.content))),E){h.message.tool_calls||(h.message.tool_calls=[]);for(let{index:P,id:M,type:V,function:R,...L}of E){let G=(s=h.message.tool_calls)[P]??(s[P]={});Object.assign(G,L),M&&(G.id=M),V&&(G.type=V),R&&(G.function??(G.function={name:R.name??"",arguments:""})),R?.name&&(G.function.name=R.name),R?.arguments&&(G.function.arguments+=R.arguments,KE(T(this,ro,"f"),G)&&(G.function.parsed_arguments=C_(G.function.arguments)))}}}return a},Symbol.asyncIterator)](){let e=[],r=[],n=!1;return this.on("chunk",i=>{let o=r.shift();o?o.resolve(i):e.push(i)}),this.on("end",()=>{n=!0;for(let i of r)i.resolve(void 0);r.length=0}),this.on("abort",i=>{n=!0;for(let o of r)o.reject(i);r.length=0}),this.on("error",i=>{n=!0;for(let o of r)o.reject(i);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((o,s)=>r.push({resolve:o,reject:s})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new $i(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function M4(t,e){let{id:r,choices:n,created:i,model:o,system_fingerprint:s,...a}=t,l={...a,id:r,choices:n.map(({message:c,finish_reason:u,index:d,logprobs:p,...f})=>{if(!u)throw new ee(`missing finish_reason for choice ${d}`);let{content:m=null,function_call:h,tool_calls:y,...g}=c,_=c.role;if(!_)throw new ee(`missing role for choice ${d}`);if(h){let{arguments:b,name:E}=h;if(b==null)throw new ee(`missing function_call.arguments for choice ${d}`);if(!E)throw new ee(`missing function_call.name for choice ${d}`);return{...f,message:{content:m,function_call:{arguments:b,name:E},role:_,refusal:c.refusal??null},finish_reason:u,index:d,logprobs:p}}return y?{...f,index:d,finish_reason:u,logprobs:p,message:{...g,role:_,content:m,refusal:c.refusal??null,tool_calls:y.map((b,E)=>{let{function:I,type:P,id:M,...V}=b,{arguments:R,name:L,...G}=I||{};if(M==null)throw new ee(`missing choices[${d}].tool_calls[${E}].id
|
|
25
|
+
${qm(t)}`);if(P==null)throw new ee(`missing choices[${d}].tool_calls[${E}].type
|
|
26
|
+
${qm(t)}`);if(L==null)throw new ee(`missing choices[${d}].tool_calls[${E}].function.name
|
|
27
|
+
${qm(t)}`);if(R==null)throw new ee(`missing choices[${d}].tool_calls[${E}].function.arguments
|
|
28
|
+
${qm(t)}`);return{...V,id:M,type:P,function:{...G,name:L,arguments:R}}})}}:{...f,message:{...g,content:m,role:_,refusal:c.refusal??null},finish_reason:u,index:d,logprobs:p}}),created:i,model:o,object:"chat.completion",...s?{system_fingerprint:s}:{}};return XE(l,e)}function qm(t){return JSON.stringify(t)}var vd=class t extends Bs{static fromReadableStream(e){let r=new t(null);return r._run(()=>r._fromReadableStream(e)),r}static runTools(e,r,n){let i=new t(r),o={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return i._run(()=>i._runTools(e,r,o)),i}};var no=class extends D{constructor(){super(...arguments),this.messages=new qs(this._client)}create(e,r){return this._client.post("/chat/completions",{body:e,...r,stream:e.stream??!1})}retrieve(e,r){return this._client.get(O`/chat/completions/${e}`,r)}update(e,r,n){return this._client.post(O`/chat/completions/${e}`,{body:r,...n})}list(e={},r){return this._client.getAPIList("/chat/completions",Ae,{query:e,...r})}delete(e,r){return this._client.delete(O`/chat/completions/${e}`,r)}parse(e,r){return YE(e.tools),this._client.chat.completions.create(e,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(n=>fd(n,e))}runTools(e,r){return e.stream?vd.runTools(this._client,e,r):yd.runTools(this._client,e,r)}stream(e,r){return Bs.createChatCompletion(this._client,e,r)}};no.Messages=qs;var qo=class extends D{constructor(){super(...arguments),this.completions=new no(this._client)}};qo.Completions=no;var i1=Symbol("brand.privateNullableHeaders");function*D4(t){if(!t)return;if(i1 in t){let{values:n,nulls:i}=t;yield*n.entries();for(let o of i)yield[o,null];return}let e=!1,r;t instanceof Headers?r=t.entries():i_(t)?r=t:(e=!0,r=Object.entries(t??{}));for(let n of r){let i=n[0];if(typeof i!="string")throw new TypeError("expected header name to be a string");let o=i_(n[1])?n[1]:[n[1]],s=!1;for(let a of o)a!==void 0&&(e&&!s&&(s=!0,yield[i,null]),yield[i,a])}}var B=t=>{let e=new Headers,r=new Set;for(let n of t){let i=new Set;for(let[o,s]of D4(n)){let a=o.toLowerCase();i.has(a)||(e.delete(o),i.add(a)),s===null?(e.delete(o),r.add(a)):(e.append(o,s),r.delete(a))}}return{[i1]:!0,values:e,nulls:r}};var zl=class extends D{create(e,r){return this._client.post("/audio/speech",{body:e,...r,headers:B([{Accept:"application/octet-stream"},r?.headers]),__binaryResponse:!0})}};var Cl=class extends D{create(e,r){return this._client.post("/audio/transcriptions",gn({body:e,...r,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}};var Nl=class extends D{create(e,r){return this._client.post("/audio/translations",gn({body:e,...r,__metadata:{model:e.model}},this._client))}};var Si=class extends D{constructor(){super(...arguments),this.transcriptions=new Cl(this._client),this.translations=new Nl(this._client),this.speech=new zl(this._client)}};Si.Transcriptions=Cl;Si.Translations=Nl;Si.Speech=zl;var Gs=class extends D{create(e,r){return this._client.post("/batches",{body:e,...r})}retrieve(e,r){return this._client.get(O`/batches/${e}`,r)}list(e={},r){return this._client.getAPIList("/batches",Ae,{query:e,...r})}cancel(e,r){return this._client.post(O`/batches/${e}/cancel`,r)}};var Ol=class extends D{create(e,r){return this._client.post("/assistants",{body:e,...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,r){return this._client.get(O`/assistants/${e}`,{...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,r,n){return this._client.post(O`/assistants/${e}`,{body:r,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e={},r){return this._client.getAPIList("/assistants",Ae,{query:e,...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,r){return this._client.delete(O`/assistants/${e}`,{...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};var Rl=class extends D{create(e,r){return this._client.post("/realtime/sessions",{body:e,...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};var Ml=class extends D{create(e,r){return this._client.post("/realtime/transcription_sessions",{body:e,...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};var Wo=class extends D{constructor(){super(...arguments),this.sessions=new Rl(this._client),this.transcriptionSessions=new Ml(this._client)}};Wo.Sessions=Rl;Wo.TranscriptionSessions=Ml;var jl=class extends D{create(e,r){return this._client.post("/chatkit/sessions",{body:e,...r,headers:B([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers])})}cancel(e,r){return this._client.post(O`/chatkit/sessions/${e}/cancel`,{...r,headers:B([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers])})}};var Dl=class extends D{retrieve(e,r){return this._client.get(O`/chatkit/threads/${e}`,{...r,headers:B([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers])})}list(e={},r){return this._client.getAPIList("/chatkit/threads",eo,{query:e,...r,headers:B([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers])})}delete(e,r){return this._client.delete(O`/chatkit/threads/${e}`,{...r,headers:B([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers])})}listItems(e,r={},n){return this._client.getAPIList(O`/chatkit/threads/${e}/items`,eo,{query:r,...n,headers:B([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers])})}};var Bo=class extends D{constructor(){super(...arguments),this.sessions=new jl(this._client),this.threads=new Dl(this._client)}};Bo.Sessions=jl;Bo.Threads=Dl;var Ll=class extends D{create(e,r,n){return this._client.post(O`/threads/${e}/messages`,{body:r,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(e,r,n){let{thread_id:i}=r;return this._client.get(O`/threads/${i}/messages/${e}`,{...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(e,r,n){let{thread_id:i,...o}=r;return this._client.post(O`/threads/${i}/messages/${e}`,{body:o,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e,r={},n){return this._client.getAPIList(O`/threads/${e}/messages`,Ae,{query:r,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}delete(e,r,n){let{thread_id:i}=r;return this._client.delete(O`/threads/${i}/messages/${e}`,{...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}};var Ul=class extends D{retrieve(e,r,n){let{thread_id:i,run_id:o,...s}=r;return this._client.get(O`/threads/${i}/runs/${o}/steps/${e}`,{query:s,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e,r,n){let{thread_id:i,...o}=r;return this._client.getAPIList(O`/threads/${i}/runs/${e}/steps`,Ae,{query:o,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}};var o1=t=>{if(typeof Buffer<"u"){let e=Buffer.from(t,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{let e=atob(t),r=e.length,n=new Uint8Array(r);for(let i=0;i<r;i++)n[i]=e.charCodeAt(i);return Array.from(new Float32Array(n.buffer))}};var Go=t=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[t]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(t)?.trim()};var cr,Xs,D_,Ii,Wm,Jn,Ks,Zl,Hs,Hm,yn,Bm,Gm,wd,_d,bd,s1,a1,l1,c1,u1,d1,f1,io=class extends Fo{constructor(){super(...arguments),cr.add(this),D_.set(this,[]),Ii.set(this,{}),Wm.set(this,{}),Jn.set(this,void 0),Ks.set(this,void 0),Zl.set(this,void 0),Hs.set(this,void 0),Hm.set(this,void 0),yn.set(this,void 0),Bm.set(this,void 0),Gm.set(this,void 0),wd.set(this,void 0)}[(D_=new WeakMap,Ii=new WeakMap,Wm=new WeakMap,Jn=new WeakMap,Ks=new WeakMap,Zl=new WeakMap,Hs=new WeakMap,Hm=new WeakMap,yn=new WeakMap,Bm=new WeakMap,Gm=new WeakMap,wd=new WeakMap,cr=new WeakSet,Symbol.asyncIterator)](){let e=[],r=[],n=!1;return this.on("event",i=>{let o=r.shift();o?o.resolve(i):e.push(i)}),this.on("end",()=>{n=!0;for(let i of r)i.resolve(void 0);r.length=0}),this.on("abort",i=>{n=!0;for(let o of r)o.reject(i);r.length=0}),this.on("error",i=>{n=!0;for(let o of r)o.reject(i);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((o,s)=>r.push({resolve:o,reject:s})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let r=new Xs;return r._run(()=>r._fromReadableStream(e)),r}async _fromReadableStream(e,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),this._connected();let i=$i.fromReadableStream(e,this.controller);for await(let o of i)T(this,cr,"m",_d).call(this,o);if(i.controller.signal?.aborted)throw new Gt;return this._addRun(T(this,cr,"m",bd).call(this))}toReadableStream(){return new $i(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,r,n,i){let o=new Xs;return o._run(()=>o._runToolAssistantStream(e,r,n,{...i,headers:{...i?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createToolAssistantStream(e,r,n,i){let o=i?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));let s={...n,stream:!0},a=await e.submitToolOutputs(r,s,{...i,signal:this.controller.signal});this._connected();for await(let l of a)T(this,cr,"m",_d).call(this,l);if(a.controller.signal?.aborted)throw new Gt;return this._addRun(T(this,cr,"m",bd).call(this))}static createThreadAssistantStream(e,r,n){let i=new Xs;return i._run(()=>i._threadAssistantStream(e,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),i}static createAssistantStream(e,r,n,i){let o=new Xs;return o._run(()=>o._runAssistantStream(e,r,n,{...i,headers:{...i?.headers,"X-Stainless-Helper-Method":"stream"}})),o}currentEvent(){return T(this,Bm,"f")}currentRun(){return T(this,Gm,"f")}currentMessageSnapshot(){return T(this,Jn,"f")}currentRunStepSnapshot(){return T(this,wd,"f")}async finalRunSteps(){return await this.done(),Object.values(T(this,Ii,"f"))}async finalMessages(){return await this.done(),Object.values(T(this,Wm,"f"))}async finalRun(){if(await this.done(),!T(this,Ks,"f"))throw Error("Final run was not received.");return T(this,Ks,"f")}async _createThreadAssistantStream(e,r,n){let i=n?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort()));let o={...r,stream:!0},s=await e.createAndRun(o,{...n,signal:this.controller.signal});this._connected();for await(let a of s)T(this,cr,"m",_d).call(this,a);if(s.controller.signal?.aborted)throw new Gt;return this._addRun(T(this,cr,"m",bd).call(this))}async _createAssistantStream(e,r,n,i){let o=i?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));let s={...n,stream:!0},a=await e.create(r,s,{...i,signal:this.controller.signal});this._connected();for await(let l of a)T(this,cr,"m",_d).call(this,l);if(a.controller.signal?.aborted)throw new Gt;return this._addRun(T(this,cr,"m",bd).call(this))}static accumulateDelta(e,r){for(let[n,i]of Object.entries(r)){if(!e.hasOwnProperty(n)){e[n]=i;continue}let o=e[n];if(o==null){e[n]=i;continue}if(n==="index"||n==="type"){e[n]=i;continue}if(typeof o=="string"&&typeof i=="string")o+=i;else if(typeof o=="number"&&typeof i=="number")o+=i;else if(nd(o)&&nd(i))o=this.accumulateDelta(o,i);else if(Array.isArray(o)&&Array.isArray(i)){if(o.every(s=>typeof s=="string"||typeof s=="number")){o.push(...i);continue}for(let s of i){if(!nd(s))throw new Error(`Expected array delta entry to be an object but got: ${s}`);let a=s.index;if(a==null)throw console.error(s),new Error("Expected array delta entry to have an `index` property");if(typeof a!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${a}`);let l=o[a];l==null?o.push(s):o[a]=this.accumulateDelta(l,s)}continue}else throw Error(`Unhandled record type: ${n}, deltaValue: ${i}, accValue: ${o}`);e[n]=o}return e}_addRun(e){return e}async _threadAssistantStream(e,r,n){return await this._createThreadAssistantStream(r,e,n)}async _runAssistantStream(e,r,n,i){return await this._createAssistantStream(r,e,n,i)}async _runToolAssistantStream(e,r,n,i){return await this._createToolAssistantStream(r,e,n,i)}};Xs=io,_d=function(e){if(!this.ended)switch(ue(this,Bm,e,"f"),T(this,cr,"m",l1).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":T(this,cr,"m",f1).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":T(this,cr,"m",a1).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":T(this,cr,"m",s1).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},bd=function(){if(this.ended)throw new ee("stream has ended, this shouldn't happen");if(!T(this,Ks,"f"))throw Error("Final run has not been received");return T(this,Ks,"f")},s1=function(e){let[r,n]=T(this,cr,"m",u1).call(this,e,T(this,Jn,"f"));ue(this,Jn,r,"f"),T(this,Wm,"f")[r.id]=r;for(let i of n){let o=r.content[i.index];o?.type=="text"&&this._emit("textCreated",o.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,r),e.data.delta.content)for(let i of e.data.delta.content){if(i.type=="text"&&i.text){let o=i.text,s=r.content[i.index];if(s&&s.type=="text")this._emit("textDelta",o,s.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(i.index!=T(this,Zl,"f")){if(T(this,Hs,"f"))switch(T(this,Hs,"f").type){case"text":this._emit("textDone",T(this,Hs,"f").text,T(this,Jn,"f"));break;case"image_file":this._emit("imageFileDone",T(this,Hs,"f").image_file,T(this,Jn,"f"));break}ue(this,Zl,i.index,"f")}ue(this,Hs,r.content[i.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(T(this,Zl,"f")!==void 0){let i=e.data.content[T(this,Zl,"f")];if(i)switch(i.type){case"image_file":this._emit("imageFileDone",i.image_file,T(this,Jn,"f"));break;case"text":this._emit("textDone",i.text,T(this,Jn,"f"));break}}T(this,Jn,"f")&&this._emit("messageDone",e.data),ue(this,Jn,void 0,"f")}},a1=function(e){let r=T(this,cr,"m",c1).call(this,e);switch(ue(this,wd,r,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":let n=e.data.delta;if(n.step_details&&n.step_details.type=="tool_calls"&&n.step_details.tool_calls&&r.step_details.type=="tool_calls")for(let o of n.step_details.tool_calls)o.index==T(this,Hm,"f")?this._emit("toolCallDelta",o,r.step_details.tool_calls[o.index]):(T(this,yn,"f")&&this._emit("toolCallDone",T(this,yn,"f")),ue(this,Hm,o.index,"f"),ue(this,yn,r.step_details.tool_calls[o.index],"f"),T(this,yn,"f")&&this._emit("toolCallCreated",T(this,yn,"f")));this._emit("runStepDelta",e.data.delta,r);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":ue(this,wd,void 0,"f"),e.data.step_details.type=="tool_calls"&&T(this,yn,"f")&&(this._emit("toolCallDone",T(this,yn,"f")),ue(this,yn,void 0,"f")),this._emit("runStepDone",e.data,r);break;case"thread.run.step.in_progress":break}},l1=function(e){T(this,D_,"f").push(e),this._emit("event",e)},c1=function(e){switch(e.event){case"thread.run.step.created":return T(this,Ii,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let r=T(this,Ii,"f")[e.data.id];if(!r)throw Error("Received a RunStepDelta before creation of a snapshot");let n=e.data;if(n.delta){let i=Xs.accumulateDelta(r,n.delta);T(this,Ii,"f")[e.data.id]=i}return T(this,Ii,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":T(this,Ii,"f")[e.data.id]=e.data;break}if(T(this,Ii,"f")[e.data.id])return T(this,Ii,"f")[e.data.id];throw new Error("No snapshot available")},u1=function(e,r){let n=[];switch(e.event){case"thread.message.created":return[e.data,n];case"thread.message.delta":if(!r)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let i=e.data;if(i.delta.content)for(let o of i.delta.content)if(o.index in r.content){let s=r.content[o.index];r.content[o.index]=T(this,cr,"m",d1).call(this,o,s)}else r.content[o.index]=o,n.push(o);return[r,n];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(r)return[r,n];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},d1=function(e,r){return Xs.accumulateDelta(r,e)},f1=function(e){switch(ue(this,Gm,e.data,"f"),e.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":ue(this,Ks,e.data,"f"),T(this,yn,"f")&&(this._emit("toolCallDone",T(this,yn,"f")),ue(this,yn,void 0,"f"));break;case"thread.run.cancelling":break}};var Js=class extends D{constructor(){super(...arguments),this.steps=new Ul(this._client)}create(e,r,n){let{include:i,...o}=r;return this._client.post(O`/threads/${e}/runs`,{query:{include:i},body:o,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:r.stream??!1})}retrieve(e,r,n){let{thread_id:i}=r;return this._client.get(O`/threads/${i}/runs/${e}`,{...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(e,r,n){let{thread_id:i,...o}=r;return this._client.post(O`/threads/${i}/runs/${e}`,{body:o,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e,r={},n){return this._client.getAPIList(O`/threads/${e}/runs`,Ae,{query:r,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}cancel(e,r,n){let{thread_id:i}=r;return this._client.post(O`/threads/${i}/runs/${e}/cancel`,{...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async createAndPoll(e,r,n){let i=await this.create(e,r,n);return await this.poll(i.id,{thread_id:e},n)}createAndStream(e,r,n){return io.createAssistantStream(e,this._client.beta.threads.runs,r,n)}async poll(e,r,n){let i=B([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:s}=await this.retrieve(e,r,{...n,headers:{...n?.headers,...i}}).withResponse();switch(o.status){case"queued":case"in_progress":case"cancelling":let a=5e3;if(n?.pollIntervalMs)a=n.pollIntervalMs;else{let l=s.headers.get("openai-poll-after-ms");if(l){let c=parseInt(l);isNaN(c)||(a=c)}}await wi(a);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return o}}}stream(e,r,n){return io.createAssistantStream(e,this._client.beta.threads.runs,r,n)}submitToolOutputs(e,r,n){let{thread_id:i,...o}=r;return this._client.post(O`/threads/${i}/runs/${e}/submit_tool_outputs`,{body:o,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:r.stream??!1})}async submitToolOutputsAndPoll(e,r,n){let i=await this.submitToolOutputs(e,r,n);return await this.poll(i.id,r,n)}submitToolOutputsStream(e,r,n){return io.createToolAssistantStream(e,this._client.beta.threads.runs,r,n)}};Js.Steps=Ul;var Ho=class extends D{constructor(){super(...arguments),this.runs=new Js(this._client),this.messages=new Ll(this._client)}create(e={},r){return this._client.post("/threads",{body:e,...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,r){return this._client.get(O`/threads/${e}`,{...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,r,n){return this._client.post(O`/threads/${e}`,{body:r,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}delete(e,r){return this._client.delete(O`/threads/${e}`,{...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}createAndRun(e,r){return this._client.post("/threads/runs",{body:e,...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:e.stream??!1})}async createAndRunPoll(e,r){let n=await this.createAndRun(e,r);return await this.runs.poll(n.id,{thread_id:n.thread_id},r)}createAndRunStream(e,r){return io.createThreadAssistantStream(e,this._client.beta.threads,r)}};Ho.Runs=Js;Ho.Messages=Ll;var Yn=class extends D{constructor(){super(...arguments),this.realtime=new Wo(this._client),this.chatkit=new Bo(this._client),this.assistants=new Ol(this._client),this.threads=new Ho(this._client)}};Yn.Realtime=Wo;Yn.ChatKit=Bo;Yn.Assistants=Ol;Yn.Threads=Ho;var Ys=class extends D{create(e,r){return this._client.post("/completions",{body:e,...r,stream:e.stream??!1})}};var Fl=class extends D{retrieve(e,r,n){let{container_id:i}=r;return this._client.get(O`/containers/${i}/files/${e}/content`,{...n,headers:B([{Accept:"application/binary"},n?.headers]),__binaryResponse:!0})}};var Qs=class extends D{constructor(){super(...arguments),this.content=new Fl(this._client)}create(e,r,n){return this._client.post(O`/containers/${e}/files`,gn({body:r,...n},this._client))}retrieve(e,r,n){let{container_id:i}=r;return this._client.get(O`/containers/${i}/files/${e}`,n)}list(e,r={},n){return this._client.getAPIList(O`/containers/${e}/files`,Ae,{query:r,...n})}delete(e,r,n){let{container_id:i}=r;return this._client.delete(O`/containers/${i}/files/${e}`,{...n,headers:B([{Accept:"*/*"},n?.headers])})}};Qs.Content=Fl;var Xo=class extends D{constructor(){super(...arguments),this.files=new Qs(this._client)}create(e,r){return this._client.post("/containers",{body:e,...r})}retrieve(e,r){return this._client.get(O`/containers/${e}`,r)}list(e={},r){return this._client.getAPIList("/containers",Ae,{query:e,...r})}delete(e,r){return this._client.delete(O`/containers/${e}`,{...r,headers:B([{Accept:"*/*"},r?.headers])})}};Xo.Files=Qs;var Vl=class extends D{create(e,r,n){let{include:i,...o}=r;return this._client.post(O`/conversations/${e}/items`,{query:{include:i},body:o,...n})}retrieve(e,r,n){let{conversation_id:i,...o}=r;return this._client.get(O`/conversations/${i}/items/${e}`,{query:o,...n})}list(e,r={},n){return this._client.getAPIList(O`/conversations/${e}/items`,eo,{query:r,...n})}delete(e,r,n){let{conversation_id:i}=r;return this._client.delete(O`/conversations/${i}/items/${e}`,n)}};var Ko=class extends D{constructor(){super(...arguments),this.items=new Vl(this._client)}create(e={},r){return this._client.post("/conversations",{body:e,...r})}retrieve(e,r){return this._client.get(O`/conversations/${e}`,r)}update(e,r,n){return this._client.post(O`/conversations/${e}`,{body:r,...n})}delete(e,r){return this._client.delete(O`/conversations/${e}`,r)}};Ko.Items=Vl;var ea=class extends D{create(e,r){let n=!!e.encoding_format,i=n?e.encoding_format:"base64";n&&Mt(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);let o=this._client.post("/embeddings",{body:{...e,encoding_format:i},...r});return n?o:(Mt(this._client).debug("embeddings/decoding base64 embeddings from base64"),o._thenUnwrap(s=>(s&&s.data&&s.data.forEach(a=>{let l=a.embedding;a.embedding=o1(l)}),s)))}};var ql=class extends D{retrieve(e,r,n){let{eval_id:i,run_id:o}=r;return this._client.get(O`/evals/${i}/runs/${o}/output_items/${e}`,n)}list(e,r,n){let{eval_id:i,...o}=r;return this._client.getAPIList(O`/evals/${i}/runs/${e}/output_items`,Ae,{query:o,...n})}};var ta=class extends D{constructor(){super(...arguments),this.outputItems=new ql(this._client)}create(e,r,n){return this._client.post(O`/evals/${e}/runs`,{body:r,...n})}retrieve(e,r,n){let{eval_id:i}=r;return this._client.get(O`/evals/${i}/runs/${e}`,n)}list(e,r={},n){return this._client.getAPIList(O`/evals/${e}/runs`,Ae,{query:r,...n})}delete(e,r,n){let{eval_id:i}=r;return this._client.delete(O`/evals/${i}/runs/${e}`,n)}cancel(e,r,n){let{eval_id:i}=r;return this._client.post(O`/evals/${i}/runs/${e}`,n)}};ta.OutputItems=ql;var Jo=class extends D{constructor(){super(...arguments),this.runs=new ta(this._client)}create(e,r){return this._client.post("/evals",{body:e,...r})}retrieve(e,r){return this._client.get(O`/evals/${e}`,r)}update(e,r,n){return this._client.post(O`/evals/${e}`,{body:r,...n})}list(e={},r){return this._client.getAPIList("/evals",Ae,{query:e,...r})}delete(e,r){return this._client.delete(O`/evals/${e}`,r)}};Jo.Runs=ta;var ra=class extends D{create(e,r){return this._client.post("/files",gn({body:e,...r},this._client))}retrieve(e,r){return this._client.get(O`/files/${e}`,r)}list(e={},r){return this._client.getAPIList("/files",Ae,{query:e,...r})}delete(e,r){return this._client.delete(O`/files/${e}`,r)}content(e,r){return this._client.get(O`/files/${e}/content`,{...r,headers:B([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:r=5e3,maxWait:n=30*60*1e3}={}){let i=new Set(["processed","error","deleted"]),o=Date.now(),s=await this.retrieve(e);for(;!s.status||!i.has(s.status);)if(await wi(r),s=await this.retrieve(e),Date.now()-o>n)throw new Uo({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return s}};var Wl=class extends D{};var Bl=class extends D{run(e,r){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...r})}validate(e,r){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...r})}};var na=class extends D{constructor(){super(...arguments),this.graders=new Bl(this._client)}};na.Graders=Bl;var Gl=class extends D{create(e,r,n){return this._client.getAPIList(O`/fine_tuning/checkpoints/${e}/permissions`,ki,{body:r,method:"post",...n})}retrieve(e,r={},n){return this._client.get(O`/fine_tuning/checkpoints/${e}/permissions`,{query:r,...n})}delete(e,r,n){let{fine_tuned_model_checkpoint:i}=r;return this._client.delete(O`/fine_tuning/checkpoints/${i}/permissions/${e}`,n)}};var ia=class extends D{constructor(){super(...arguments),this.permissions=new Gl(this._client)}};ia.Permissions=Gl;var Hl=class extends D{list(e,r={},n){return this._client.getAPIList(O`/fine_tuning/jobs/${e}/checkpoints`,Ae,{query:r,...n})}};var oa=class extends D{constructor(){super(...arguments),this.checkpoints=new Hl(this._client)}create(e,r){return this._client.post("/fine_tuning/jobs",{body:e,...r})}retrieve(e,r){return this._client.get(O`/fine_tuning/jobs/${e}`,r)}list(e={},r){return this._client.getAPIList("/fine_tuning/jobs",Ae,{query:e,...r})}cancel(e,r){return this._client.post(O`/fine_tuning/jobs/${e}/cancel`,r)}listEvents(e,r={},n){return this._client.getAPIList(O`/fine_tuning/jobs/${e}/events`,Ae,{query:r,...n})}pause(e,r){return this._client.post(O`/fine_tuning/jobs/${e}/pause`,r)}resume(e,r){return this._client.post(O`/fine_tuning/jobs/${e}/resume`,r)}};oa.Checkpoints=Hl;var Qn=class extends D{constructor(){super(...arguments),this.methods=new Wl(this._client),this.jobs=new oa(this._client),this.checkpoints=new ia(this._client),this.alpha=new na(this._client)}};Qn.Methods=Wl;Qn.Jobs=oa;Qn.Checkpoints=ia;Qn.Alpha=na;var Xl=class extends D{};var Yo=class extends D{constructor(){super(...arguments),this.graderModels=new Xl(this._client)}};Yo.GraderModels=Xl;var sa=class extends D{createVariation(e,r){return this._client.post("/images/variations",gn({body:e,...r},this._client))}edit(e,r){return this._client.post("/images/edits",gn({body:e,...r,stream:e.stream??!1},this._client))}generate(e,r){return this._client.post("/images/generations",{body:e,...r,stream:e.stream??!1})}};var aa=class extends D{retrieve(e,r){return this._client.get(O`/models/${e}`,r)}list(e){return this._client.getAPIList("/models",ki,e)}delete(e,r){return this._client.delete(O`/models/${e}`,r)}};var la=class extends D{create(e,r){return this._client.post("/moderations",{body:e,...r})}};var Kl=class extends D{accept(e,r,n){return this._client.post(O`/realtime/calls/${e}/accept`,{body:r,...n,headers:B([{Accept:"*/*"},n?.headers])})}hangup(e,r){return this._client.post(O`/realtime/calls/${e}/hangup`,{...r,headers:B([{Accept:"*/*"},r?.headers])})}refer(e,r,n){return this._client.post(O`/realtime/calls/${e}/refer`,{body:r,...n,headers:B([{Accept:"*/*"},n?.headers])})}reject(e,r={},n){return this._client.post(O`/realtime/calls/${e}/reject`,{body:r,...n,headers:B([{Accept:"*/*"},n?.headers])})}};var Jl=class extends D{create(e,r){return this._client.post("/realtime/client_secrets",{body:e,...r})}};var oo=class extends D{constructor(){super(...arguments),this.clientSecrets=new Jl(this._client),this.calls=new Kl(this._client)}};oo.ClientSecrets=Jl;oo.Calls=Kl;function p1(t,e){return!e||!h2(e)?{...t,output_parsed:null,output:t.output.map(r=>r.type==="function_call"?{...r,parsed_arguments:null}:r.type==="message"?{...r,content:r.content.map(n=>({...n,parsed:null}))}:r)}:L_(t,e)}function L_(t,e){let r=t.output.map(i=>{if(i.type==="function_call")return{...i,parsed_arguments:v2(e,i)};if(i.type==="message"){let o=i.content.map(s=>s.type==="output_text"?{...s,parsed:m2(e,s.text)}:s);return{...i,content:o}}return i}),n=Object.assign({},t,{output:r});return Object.getOwnPropertyDescriptor(t,"output_text")||Xm(n),Object.defineProperty(n,"output_parsed",{enumerable:!0,get(){for(let i of n.output)if(i.type==="message"){for(let o of i.content)if(o.type==="output_text"&&o.parsed!==null)return o.parsed}return null}}),n}function m2(t,e){return t.text?.format?.type!=="json_schema"?null:"$parseRaw"in t.text?.format?(t.text?.format).$parseRaw(e):JSON.parse(e)}function h2(t){return!!dd(t.text?.format)}function g2(t){return t?.$brand==="auto-parseable-tool"}function y2(t,e){return t.find(r=>r.type==="function"&&r.name===e)}function v2(t,e){let r=y2(t.tools??[],e.name);return{...e,...e,parsed_arguments:g2(r)?r.$parseRaw(e.arguments):r?.strict?JSON.parse(e.arguments):null}}function Xm(t){let e=[];for(let r of t.output)if(r.type==="message")for(let n of r.content)n.type==="output_text"&&e.push(n.text);t.output_text=e.join("")}var Yl,Km,Qo,Jm,m1,h1,g1,y1,Ym=class t extends Fo{constructor(e){super(),Yl.add(this),Km.set(this,void 0),Qo.set(this,void 0),Jm.set(this,void 0),ue(this,Km,e,"f")}static createResponse(e,r,n){let i=new t(r);return i._run(()=>i._createOrRetrieveResponse(e,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),i}async _createOrRetrieveResponse(e,r,n){let i=n?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort())),T(this,Yl,"m",m1).call(this);let o,s=null;"response_id"in r?(o=await e.responses.retrieve(r.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),s=r.starting_after??null):o=await e.responses.create({...r,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(let a of o)T(this,Yl,"m",h1).call(this,a,s);if(o.controller.signal?.aborted)throw new Gt;return T(this,Yl,"m",g1).call(this)}[(Km=new WeakMap,Qo=new WeakMap,Jm=new WeakMap,Yl=new WeakSet,m1=function(){this.ended||ue(this,Qo,void 0,"f")},h1=function(r,n){if(this.ended)return;let i=(s,a)=>{(n==null||a.sequence_number>n)&&this._emit(s,a)},o=T(this,Yl,"m",y1).call(this,r);switch(i("event",r),r.type){case"response.output_text.delta":{let s=o.output[r.output_index];if(!s)throw new ee(`missing output at index ${r.output_index}`);if(s.type==="message"){let a=s.content[r.content_index];if(!a)throw new ee(`missing content at index ${r.content_index}`);if(a.type!=="output_text")throw new ee(`expected content to be 'output_text', got ${a.type}`);i("response.output_text.delta",{...r,snapshot:a.text})}break}case"response.function_call_arguments.delta":{let s=o.output[r.output_index];if(!s)throw new ee(`missing output at index ${r.output_index}`);s.type==="function_call"&&i("response.function_call_arguments.delta",{...r,snapshot:s.arguments});break}default:i(r.type,r);break}},g1=function(){if(this.ended)throw new ee("stream has ended, this shouldn't happen");let r=T(this,Qo,"f");if(!r)throw new ee("request ended without sending any events");ue(this,Qo,void 0,"f");let n=_2(r,T(this,Km,"f"));return ue(this,Jm,n,"f"),n},y1=function(r){let n=T(this,Qo,"f");if(!n){if(r.type!=="response.created")throw new ee(`When snapshot hasn't been set yet, expected 'response.created' event, got ${r.type}`);return n=ue(this,Qo,r.response,"f"),n}switch(r.type){case"response.output_item.added":{n.output.push(r.item);break}case"response.content_part.added":{let i=n.output[r.output_index];if(!i)throw new ee(`missing output at index ${r.output_index}`);let o=i.type,s=r.part;o==="message"&&s.type!=="reasoning_text"?i.content.push(s):o==="reasoning"&&s.type==="reasoning_text"&&(i.content||(i.content=[]),i.content.push(s));break}case"response.output_text.delta":{let i=n.output[r.output_index];if(!i)throw new ee(`missing output at index ${r.output_index}`);if(i.type==="message"){let o=i.content[r.content_index];if(!o)throw new ee(`missing content at index ${r.content_index}`);if(o.type!=="output_text")throw new ee(`expected content to be 'output_text', got ${o.type}`);o.text+=r.delta}break}case"response.function_call_arguments.delta":{let i=n.output[r.output_index];if(!i)throw new ee(`missing output at index ${r.output_index}`);i.type==="function_call"&&(i.arguments+=r.delta);break}case"response.reasoning_text.delta":{let i=n.output[r.output_index];if(!i)throw new ee(`missing output at index ${r.output_index}`);if(i.type==="reasoning"){let o=i.content?.[r.content_index];if(!o)throw new ee(`missing content at index ${r.content_index}`);if(o.type!=="reasoning_text")throw new ee(`expected content to be 'reasoning_text', got ${o.type}`);o.text+=r.delta}break}case"response.completed":{ue(this,Qo,r.response,"f");break}}return n},Symbol.asyncIterator)](){let e=[],r=[],n=!1;return this.on("event",i=>{let o=r.shift();o?o.resolve(i):e.push(i)}),this.on("end",()=>{n=!0;for(let i of r)i.resolve(void 0);r.length=0}),this.on("abort",i=>{n=!0;for(let o of r)o.reject(i);r.length=0}),this.on("error",i=>{n=!0;for(let o of r)o.reject(i);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((o,s)=>r.push({resolve:o,reject:s})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=T(this,Jm,"f");if(!e)throw new ee("stream ended without producing a ChatCompletion");return e}};function _2(t,e){return p1(t,e)}var Ql=class extends D{list(e,r={},n){return this._client.getAPIList(O`/responses/${e}/input_items`,Ae,{query:r,...n})}};var ec=class extends D{count(e={},r){return this._client.post("/responses/input_tokens",{body:e,...r})}};var so=class extends D{constructor(){super(...arguments),this.inputItems=new Ql(this._client),this.inputTokens=new ec(this._client)}create(e,r){return this._client.post("/responses",{body:e,...r,stream:e.stream??!1})._thenUnwrap(n=>("object"in n&&n.object==="response"&&Xm(n),n))}retrieve(e,r={},n){return this._client.get(O`/responses/${e}`,{query:r,...n,stream:r?.stream??!1})._thenUnwrap(i=>("object"in i&&i.object==="response"&&Xm(i),i))}delete(e,r){return this._client.delete(O`/responses/${e}`,{...r,headers:B([{Accept:"*/*"},r?.headers])})}parse(e,r){return this._client.responses.create(e,r)._thenUnwrap(n=>L_(n,e))}stream(e,r){return Ym.createResponse(this._client,e,r)}cancel(e,r){return this._client.post(O`/responses/${e}/cancel`,r)}compact(e={},r){return this._client.post("/responses/compact",{body:e,...r})}};so.InputItems=Ql;so.InputTokens=ec;var tc=class extends D{create(e,r,n){return this._client.post(O`/uploads/${e}/parts`,gn({body:r,...n},this._client))}};var es=class extends D{constructor(){super(...arguments),this.parts=new tc(this._client)}create(e,r){return this._client.post("/uploads",{body:e,...r})}cancel(e,r){return this._client.post(O`/uploads/${e}/cancel`,r)}complete(e,r,n){return this._client.post(O`/uploads/${e}/complete`,{body:r,...n})}};es.Parts=tc;var v1=async t=>{let e=await Promise.allSettled(t),r=e.filter(i=>i.status==="rejected");if(r.length){for(let i of r)console.error(i.reason);throw new Error(`${r.length} promise(s) failed - see the above errors`)}let n=[];for(let i of e)i.status==="fulfilled"&&n.push(i.value);return n};var rc=class extends D{create(e,r,n){return this._client.post(O`/vector_stores/${e}/file_batches`,{body:r,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(e,r,n){let{vector_store_id:i}=r;return this._client.get(O`/vector_stores/${i}/file_batches/${e}`,{...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}cancel(e,r,n){let{vector_store_id:i}=r;return this._client.post(O`/vector_stores/${i}/file_batches/${e}/cancel`,{...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async createAndPoll(e,r,n){let i=await this.create(e,r);return await this.poll(e,i.id,n)}listFiles(e,r,n){let{vector_store_id:i,...o}=r;return this._client.getAPIList(O`/vector_stores/${i}/file_batches/${e}/files`,Ae,{query:o,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async poll(e,r,n){let i=B([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:s}=await this.retrieve(r,{vector_store_id:e},{...n,headers:i}).withResponse();switch(o.status){case"in_progress":let a=5e3;if(n?.pollIntervalMs)a=n.pollIntervalMs;else{let l=s.headers.get("openai-poll-after-ms");if(l){let c=parseInt(l);isNaN(c)||(a=c)}}await wi(a);break;case"failed":case"cancelled":case"completed":return o}}}async uploadAndPoll(e,{files:r,fileIds:n=[]},i){if(r==null||r.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let o=i?.maxConcurrency??5,s=Math.min(o,r.length),a=this._client,l=r.values(),c=[...n];async function u(p){for(let f of p){let m=await a.files.create({file:f,purpose:"assistants"},i);c.push(m.id)}}let d=Array(s).fill(l).map(u);return await v1(d),await this.createAndPoll(e,{file_ids:c})}};var nc=class extends D{create(e,r,n){return this._client.post(O`/vector_stores/${e}/files`,{body:r,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(e,r,n){let{vector_store_id:i}=r;return this._client.get(O`/vector_stores/${i}/files/${e}`,{...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(e,r,n){let{vector_store_id:i,...o}=r;return this._client.post(O`/vector_stores/${i}/files/${e}`,{body:o,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e,r={},n){return this._client.getAPIList(O`/vector_stores/${e}/files`,Ae,{query:r,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}delete(e,r,n){let{vector_store_id:i}=r;return this._client.delete(O`/vector_stores/${i}/files/${e}`,{...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async createAndPoll(e,r,n){let i=await this.create(e,r,n);return await this.poll(e,i.id,n)}async poll(e,r,n){let i=B([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let o=await this.retrieve(r,{vector_store_id:e},{...n,headers:i}).withResponse(),s=o.data;switch(s.status){case"in_progress":let a=5e3;if(n?.pollIntervalMs)a=n.pollIntervalMs;else{let l=o.response.headers.get("openai-poll-after-ms");if(l){let c=parseInt(l);isNaN(c)||(a=c)}}await wi(a);break;case"failed":case"completed":return s}}}async upload(e,r,n){let i=await this._client.files.create({file:r,purpose:"assistants"},n);return this.create(e,{file_id:i.id},n)}async uploadAndPoll(e,r,n){let i=await this.upload(e,r,n);return await this.poll(e,i.id,n)}content(e,r,n){let{vector_store_id:i}=r;return this._client.getAPIList(O`/vector_stores/${i}/files/${e}/content`,ki,{...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}};var ao=class extends D{constructor(){super(...arguments),this.files=new nc(this._client),this.fileBatches=new rc(this._client)}create(e,r){return this._client.post("/vector_stores",{body:e,...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,r){return this._client.get(O`/vector_stores/${e}`,{...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,r,n){return this._client.post(O`/vector_stores/${e}`,{body:r,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e={},r){return this._client.getAPIList("/vector_stores",Ae,{query:e,...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,r){return this._client.delete(O`/vector_stores/${e}`,{...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}search(e,r,n){return this._client.getAPIList(O`/vector_stores/${e}/search`,ki,{body:r,method:"post",...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}};ao.Files=nc;ao.FileBatches=rc;var ca=class extends D{create(e,r){return this._client.post("/videos",w_({body:e,...r},this._client))}retrieve(e,r){return this._client.get(O`/videos/${e}`,r)}list(e={},r){return this._client.getAPIList("/videos",eo,{query:e,...r})}delete(e,r){return this._client.delete(O`/videos/${e}`,r)}downloadContent(e,r={},n){return this._client.get(O`/videos/${e}/content`,{query:r,...n,headers:B([{Accept:"application/binary"},n?.headers]),__binaryResponse:!0})}remix(e,r,n){return this._client.post(O`/videos/${e}/remix`,w_({body:r,...n},this._client))}};var ic,_1,Qm,ua=class extends D{constructor(){super(...arguments),ic.add(this)}async unwrap(e,r,n=this._client.webhookSecret,i=300){return await this.verifySignature(e,r,n,i),JSON.parse(e)}async verifySignature(e,r,n=this._client.webhookSecret,i=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");T(this,ic,"m",_1).call(this,n);let o=B([r]).values,s=T(this,ic,"m",Qm).call(this,o,"webhook-signature"),a=T(this,ic,"m",Qm).call(this,o,"webhook-timestamp"),l=T(this,ic,"m",Qm).call(this,o,"webhook-id"),c=parseInt(a,10);if(isNaN(c))throw new bi("Invalid webhook timestamp format");let u=Math.floor(Date.now()/1e3);if(u-c>i)throw new bi("Webhook timestamp is too old");if(c>u+i)throw new bi("Webhook timestamp is too new");let d=s.split(" ").map(h=>h.startsWith("v1,")?h.substring(3):h),p=n.startsWith("whsec_")?Buffer.from(n.replace("whsec_",""),"base64"):Buffer.from(n,"utf-8"),f=l?`${l}.${a}.${e}`:`${a}.${e}`,m=await crypto.subtle.importKey("raw",p,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let h of d)try{let y=Buffer.from(h,"base64");if(await crypto.subtle.verify("HMAC",m,y,new TextEncoder().encode(f)))return}catch{continue}throw new bi("The given webhook signature does not match the expected signature")}};ic=new WeakSet,_1=function(e){if(typeof e!="string"||e.length===0)throw new Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},Qm=function(e,r){if(!e)throw new Error("Headers are required");let n=e.get(r);if(n==null)throw new Error(`Missing required header: ${r}`);return n};var U_,Z_,eh,b1,be=class{constructor({baseURL:e=Go("OPENAI_BASE_URL"),apiKey:r=Go("OPENAI_API_KEY"),organization:n=Go("OPENAI_ORG_ID")??null,project:i=Go("OPENAI_PROJECT_ID")??null,webhookSecret:o=Go("OPENAI_WEBHOOK_SECRET")??null,...s}={}){if(U_.add(this),eh.set(this,void 0),this.completions=new Ys(this),this.chat=new qo(this),this.embeddings=new ea(this),this.files=new ra(this),this.images=new sa(this),this.audio=new Si(this),this.moderations=new la(this),this.models=new aa(this),this.fineTuning=new Qn(this),this.graders=new Yo(this),this.vectorStores=new ao(this),this.webhooks=new ua(this),this.beta=new Yn(this),this.batches=new Gs(this),this.uploads=new es(this),this.responses=new so(this),this.realtime=new oo(this),this.conversations=new Ko(this),this.evals=new Jo(this),this.containers=new Xo(this),this.videos=new ca(this),r===void 0)throw new ee("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");let a={apiKey:r,organization:n,project:i,webhookSecret:o,...s,baseURL:e||"https://api.openai.com/v1"};if(!a.dangerouslyAllowBrowser&&EE())throw new ee(`It looks like you're running in a browser-like environment.
|
|
29
|
+
|
|
30
|
+
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
31
|
+
If you understand the risks and have appropriate mitigations in place,
|
|
32
|
+
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
33
|
+
|
|
34
|
+
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
35
|
+
|
|
36
|
+
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
37
|
+
`);this.baseURL=a.baseURL,this.timeout=a.timeout??Z_.DEFAULT_TIMEOUT,this.logger=a.logger??console;let l="warn";this.logLevel=l,this.logLevel=h_(a.logLevel,"ClientOptions.logLevel",this)??h_(Go("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??l,this.fetchOptions=a.fetchOptions,this.maxRetries=a.maxRetries??2,this.fetch=a.fetch??TE(),ue(this,eh,zE,"f"),this._options=a,this.apiKey=typeof r=="string"?r:"Missing Key",this.organization=n,this.project=i,this.webhookSecret=o}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:r}){}async authHeaders(e){return B([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return p_(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${Zo}`}defaultIdempotencyKey(){return`stainless-node-retry-${n_()}`}makeStatusError(e,r,n,i){return Jt.generate(e,r,n,i)}async _callApiKey(){let e=this._options.apiKey;if(typeof e!="function")return!1;let r;try{r=await e()}catch(n){throw n instanceof ee?n:new ee(`Failed to get token from 'apiKey' function: ${n.message}`,{cause:n})}if(typeof r!="string"||!r)throw new ee(`Expected 'apiKey' function argument to return a string but it returned ${r}`);return this.apiKey=r,!0}buildURL(e,r,n){let i=!T(this,U_,"m",b1).call(this)&&n||this.baseURL,o=_E(e)?new URL(e):new URL(i+(i.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),s=this.defaultQuery();return bE(s)||(r={...s,...r}),typeof r=="object"&&r&&!Array.isArray(r)&&(o.search=this.stringifyQuery(r)),o.toString()}async prepareOptions(e){await this._callApiKey()}async prepareRequest(e,{url:r,options:n}){}get(e,r){return this.methodRequest("get",e,r)}post(e,r){return this.methodRequest("post",e,r)}patch(e,r){return this.methodRequest("patch",e,r)}put(e,r){return this.methodRequest("put",e,r)}delete(e,r){return this.methodRequest("delete",e,r)}methodRequest(e,r,n){return this.request(Promise.resolve(n).then(i=>({method:e,path:r,...i})))}request(e,r=null){return new Vs(this,this.makeRequest(e,r,void 0))}async makeRequest(e,r,n){let i=await e,o=i.maxRetries??this.maxRetries;r==null&&(r=o),await this.prepareOptions(i);let{req:s,url:a,timeout:l}=await this.buildRequest(i,{retryCount:o-r});await this.prepareRequest(s,{url:a,options:i});let c="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),u=n===void 0?"":`, retryOf: ${n}`,d=Date.now();if(Mt(this).debug(`[${c}] sending request`,Qi({retryOfRequestLogID:n,method:i.method,url:a,options:i,headers:s.headers})),i.signal?.aborted)throw new Gt;let p=new AbortController,f=await this.fetchWithTimeout(a,s,l,p).catch(rd),m=Date.now();if(f instanceof globalThis.Error){let g=`retrying, ${r} attempts remaining`;if(i.signal?.aborted)throw new Gt;let _=td(f)||/timed? ?out/i.test(String(f)+("cause"in f?String(f.cause):""));if(r)return Mt(this).info(`[${c}] connection ${_?"timed out":"failed"} - ${g}`),Mt(this).debug(`[${c}] connection ${_?"timed out":"failed"} (${g})`,Qi({retryOfRequestLogID:n,url:a,durationMs:m-d,message:f.message})),this.retryRequest(i,r,n??c);throw Mt(this).info(`[${c}] connection ${_?"timed out":"failed"} - error; no more retries left`),Mt(this).debug(`[${c}] connection ${_?"timed out":"failed"} (error; no more retries left)`,Qi({retryOfRequestLogID:n,url:a,durationMs:m-d,message:f.message})),_?new Uo:new Lo({cause:f})}let h=[...f.headers.entries()].filter(([g])=>g==="x-request-id").map(([g,_])=>", "+g+": "+JSON.stringify(_)).join(""),y=`[${c}${u}${h}] ${s.method} ${a} ${f.ok?"succeeded":"failed"} with status ${f.status} in ${m-d}ms`;if(!f.ok){let g=await this.shouldRetry(f);if(r&&g){let M=`retrying, ${r} attempts remaining`;return await AE(f.body),Mt(this).info(`${y} - ${M}`),Mt(this).debug(`[${c}] response error (${M})`,Qi({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:m-d})),this.retryRequest(i,r,n??c,f.headers)}let _=g?"error; no more retries left":"error; not retryable";Mt(this).info(`${y} - ${_}`);let b=await f.text().catch(M=>rd(M).message),E=$E(b),I=E?void 0:b;throw Mt(this).debug(`[${c}] response error (${_})`,Qi({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,message:I,durationMs:Date.now()-d})),this.makeStatusError(f.status,E,I,f.headers)}return Mt(this).info(y),Mt(this).debug(`[${c}] response start`,Qi({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:m-d})),{response:f,options:i,controller:p,requestLogID:c,retryOfRequestLogID:n,startTime:d}}getAPIList(e,r,n){return this.requestAPIList(r,{method:"get",path:e,...n})}requestAPIList(e,r){let n=this.makeRequest(r,null,void 0);return new ld(this,n,e)}async fetchWithTimeout(e,r,n,i){let{signal:o,method:s,...a}=r||{};o&&o.addEventListener("abort",()=>i.abort());let l=setTimeout(()=>i.abort(),n),c=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body=="object"&&a.body!==null&&Symbol.asyncIterator in a.body,u={signal:i.signal,...c?{duplex:"half"}:{},method:"GET",...a};s&&(u.method=s.toUpperCase());try{return await this.fetch.call(void 0,e,u)}finally{clearTimeout(l)}}async shouldRetry(e){let r=e.headers.get("x-should-retry");return r==="true"?!0:r==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,r,n,i){let o,s=i?.get("retry-after-ms");if(s){let l=parseFloat(s);Number.isNaN(l)||(o=l)}let a=i?.get("retry-after");if(a&&!o){let l=parseFloat(a);Number.isNaN(l)?o=Date.parse(a)-Date.now():o=l*1e3}if(!(o&&0<=o&&o<60*1e3)){let l=e.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(r,l)}return await wi(o),this.makeRequest(e,r-1,n)}calculateDefaultRetryTimeoutMillis(e,r){let o=r-e,s=Math.min(.5*Math.pow(2,o),8),a=1-Math.random()*.25;return s*a*1e3}async buildRequest(e,{retryCount:r=0}={}){let n={...e},{method:i,path:o,query:s,defaultBaseURL:a}=n,l=this.buildURL(o,s,a);"timeout"in n&&xE("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:c,body:u}=this.buildBody({options:n}),d=await this.buildHeaders({options:e,method:i,bodyHeaders:c,retryCount:r});return{req:{method:i,headers:d,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&u instanceof globalThis.ReadableStream&&{duplex:"half"},...u&&{body:u},...this.fetchOptions??{},...n.fetchOptions??{}},url:l,timeout:n.timeout}}async buildHeaders({options:e,method:r,bodyHeaders:n,retryCount:i}){let o={};this.idempotencyHeader&&r!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);let s=B([o,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(i),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...PE(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(s),s.values}buildBody({options:{body:e,headers:r}}){if(!e)return{bodyHeaders:void 0,body:void 0};let n=B([r]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&n.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:Im(e)}:T(this,eh,"f").call(this,{body:e,headers:n})}};Z_=be,eh=new WeakMap,U_=new WeakSet,b1=function(){return this.baseURL!=="https://api.openai.com/v1"};be.OpenAI=Z_;be.DEFAULT_TIMEOUT=6e5;be.OpenAIError=ee;be.APIError=Jt;be.APIConnectionError=Lo;be.APIConnectionTimeoutError=Uo;be.APIUserAbortError=Gt;be.NotFoundError=vl;be.ConflictError=_l;be.RateLimitError=wl;be.BadRequestError=hl;be.AuthenticationError=gl;be.InternalServerError=xl;be.PermissionDeniedError=yl;be.UnprocessableEntityError=bl;be.InvalidWebhookSignatureError=bi;be.toFile=Rm;be.Completions=Ys;be.Chat=qo;be.Embeddings=ea;be.Files=ra;be.Images=sa;be.Audio=Si;be.Moderations=la;be.Models=aa;be.FineTuning=Qn;be.Graders=Yo;be.VectorStores=ao;be.Webhooks=ua;be.Beta=Yn;be.Batches=Gs;be.Uploads=es;be.Responses=so;be.Realtime=oo;be.Conversations=Ko;be.Evals=Jo;be.Containers=Xo;be.Videos=ca;var ur=[];for(th=0;th<256;++th)ur.push((th+256).toString(16).slice(1));var th;function w1(t,e=0){return(ur[t[e+0]]+ur[t[e+1]]+ur[t[e+2]]+ur[t[e+3]]+"-"+ur[t[e+4]]+ur[t[e+5]]+"-"+ur[t[e+6]]+ur[t[e+7]]+"-"+ur[t[e+8]]+ur[t[e+9]]+"-"+ur[t[e+10]]+ur[t[e+11]]+ur[t[e+12]]+ur[t[e+13]]+ur[t[e+14]]+ur[t[e+15]]).toLowerCase()}var rh,I2=new Uint8Array(16);function F_(){if(!rh&&(rh=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!rh))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return rh(I2)}var E2=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),V_={randomUUID:E2};function P2(t,e,r){if(V_.randomUUID&&!e&&!t)return V_.randomUUID();t=t||{};var n=t.random||(t.rng||F_)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){r=r||0;for(var i=0;i<16;++i)e[r+i]=n[i];return e}return w1(n)}var dr=P2;var ts=class{constructor(){this.size=4096;this.groups=[]}createGroup(e){let r=new q_;return r.id=e,this.groups.push(r),r}group(e){return this.groups.find(r=>r.id===e)}static countTokensInText(e){return e==null?e="":typeof e=="number"?e=e+"":typeof e!="string"&&(e=JSON.stringify(e)),Math.ceil(e.length/3)}countTokens(){return this.groups.reduce((e,r)=>e+r.tokenCount,0)}removeOverflow(){let e=this.countTokens(),r=this.groups.reduce((n,i)=>n+i.weight,0);for(;e>this.size;){let n=this.groups.slice().sort((o,s)=>{let a=Math.floor(o.weight/r*this.size),l=Math.floor(s.weight/r*this.size),c=o.tokenCount-a;return s.tokenCount-l-c}),i=this.removeOneItem(n);if(!i)throw new Error("Too many items in the token window that cannot be removed.");e-=i.tokenCount}}removeOneItem(e){for(let r of e){let n=r.items.findIndex(o=>!o.cannotRemove);if(n===-1)continue;let i=r.items[n];return r.items.splice(n,1),r.tokenCount-=i.tokenCount,i}return null}},q_=class{constructor(){this.id="";this.items=[];this.weight=1;this.tokenCount=0;this.separator=`
|
|
38
|
+
`;this.itemPadding=0;this.sortFunction=(e,r)=>e.sortOrder!==r.sortOrder?e.sortOrder-r.sortOrder:e.dateAdded!==r.dateAdded?e.dateAdded-r.dateAdded:0}setItemPadding(e){return this.itemPadding=e,this.recalculateTokens(),this}sortBy(e){return this.sortFunction=e,this.items.sort(this.sortFunction),this}setSeparator(e){return this.separator==e?this:(this.separator=e,this.recalculateTokens(),this)}setWeight(e){return this.weight=e,this}recalculateTokens(){this.tokenCount=this.items.reduce((e,r)=>(r.tokenCount=ts.countTokensInText(typeof r.data=="string"?r.data:JSON.stringify(r.data))+ts.countTokensInText(this.separator)+this.itemPadding,e+r.tokenCount),0)}add(e){typeof e=="string"&&(e={source:"user",data:e});let r=e;r.id===void 0&&(r.id=dr()),!r.sections?.length&&typeof r.data=="string"?r.text=r.data:r.text=r.sections?.map(i=>{if(i.type==="text")return i.text||"";if(i.type==="tool_call")return`[Tool Call: ${i.toolKbName||i.toolName}] `;if(i.type==="tool_result"&&i.toolErrorResponse)return`[Tool Error: ${i.toolErrorResponse}] `}).filter(i=>!!i).join(`
|
|
39
|
+
|
|
40
|
+
`)||"";let n=this.items.find(i=>i.id===r.id);return n?(this.tokenCount-=n.tokenCount,Object.assign(n,r),r=n):this.items.push(r),r.dateAdded===void 0&&(r.dateAdded=Date.now()),r.sortOrder===void 0&&(r.sortOrder=0),r.disabled===void 0&&(r.disabled=!1),r.source===void 0&&(r.source="user"),r.sections===void 0&&(r.sections=[]),r.tokenCount=r.disabled?0:ts.countTokensInText(typeof e.data=="string"?e.data:JSON.stringify(e.data))+ts.countTokensInText(this.separator)+this.itemPadding,this.tokenCount+=r.tokenCount,this.items.sort(this.sortFunction),r}getAllAsString(){return this.getAll().map(e=>e.text).join(this.separator)}getAll(){return this.items.filter(e=>!e.disabled)}empty(){this.items=[],this.tokenCount=0}};function nh(t){let e=(t||"").split(`
|
|
41
|
+
`);for(;e.length>0&&e[0].trim()=="";)e.shift();for(;e.length>0&&e[e.length-1].trim()=="";)e.pop();let r=1/0;for(let n of e){let i=n.match(/^\s*/)?.[0].length||0;r=Math.min(r,i)}return r>0&&r<1/0&&(e=e.map(n=>n.substring(r))),e.join(`
|
|
42
|
+
`)}var T2={};function rs(){return typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:T2}function bt(){return rs().intelliweave=rs().intelliweave||rs().webWeaver||{},rs().intelliweave}function x1(){if(bt().userID)return bt().userID||"";if(typeof localStorage<"u"&&localStorage.getItem&&localStorage.setItem){let t=localStorage.getItem("intelliweave.uid")||"";return t||(t=dr(),localStorage.setItem("intelliweave.uid",t),t)}else return dr()}function $1(t){let e=t;if(e?.type=="object"&&e.properties)return t;let r={type:"object",properties:{},required:[]};if(t&&Array.isArray(t)){let n=t;for(let i of n)r.properties[i.name]={type:i.type||"string",description:i.description||""}}return r}var ih=class ih{constructor(e){this.module="IntelliWeave";this.module=e}get debugEnabled(){return ih.debug?!0:typeof window<"u"&&bt().debug}log(...e){this.debugEnabled&&console.log(`[IntelliWeave > ${this.module}]`,...e)}debug(...e){this.debugEnabled&&console.debug(`[IntelliWeave > ${this.module}]`,...e)}info(...e){this.debugEnabled&&console.info(`[IntelliWeave > ${this.module}]`,...e)}warn(...e){console.warn(`[IntelliWeave > ${this.module}]`,...e)}error(...e){console.error(`[IntelliWeave > ${this.module}]`,...e)}timer(e,...r){let n=Date.now();return this.debug(`[${e} 0ms] Started`,...r),(...i)=>this.debug(`[${e} ${Math.floor(Date.now()-n)}ms]`,...i)}};ih.debug=!1;var Le=ih;var k1=new Le("ChatBase"),oc=class{constructor(e){this.id="";this.metadata={};this.maxToolCallsPerMessage=10;this.stats={tokensUsed:0};this.tokenWindow=(()=>{let e=new ts;return e.createGroup("context").setSeparator(`
|
|
43
|
+
|
|
44
|
+
`),e.createGroup("actions").setItemPadding(25),e.createGroup("messages").setItemPadding(10),e})();this.config=e,this.tokenWindow.size=this.config.maxTokens||16e3}get contextGroup(){return this.tokenWindow.group("context")}get toolGroup(){return this.tokenWindow.group("actions")}get messageGroup(){return this.tokenWindow.group("messages")}getBaseURL(){if(!this.config.endpoint)return;let e=this.config.endpoint;return e.endsWith("/chat/completions")&&(e=e.substring(0,e.length-17)),e}async sendMessage(e,r){throw new Error("Not implemented")}addUserMessage(e){throw new Error("Not implemented")}addAssistantMessage(e){throw new Error("Not implemented")}addTextMessage(e,r,n){this.messageGroup.add({id:"msg-"+dr(),source:r,data:n,sections:[{type:"text",text:e}]})}onBeforeIncomingMessage(e){}resetConversation(){this.messageGroup.empty(),this.toolGroup.empty(),this.contextGroup.empty()}async trimMessages(){this.tokenWindow.removeOverflow()}registerTool(e){return this.toolGroup.add({id:e.name,data:e,cannotRemove:!e.canRemove,sortOrder:101,disabled:!!e.kbItem?.disabled})}findToolBySafeName(e){return this.toolGroup.getAll().find(r=>r.id==e||r.data?.kbItem?.name==e)?.data}async executeTool(e,r){if(!e)throw new Error("Tool not found");k1.debug(`Executing tool '${e.name}'`,r,e),this.config.onAIToolStart?.(e.kbItem?.name||e.name,r);let n;try{n=await e.callback(r)}catch(i){throw k1.error(`Error executing tool '${e.name}'`,i),i}return typeof n!="string"&&(n=JSON.stringify(n)||""),(n===""||n==="undefined")&&(n="success"),n}};var W_=new Le("ChatGPT"),oh=class extends oc{addUserMessage(e){this.addTextMessage(e,"user",{role:"user",content:e||""})}addAssistantMessage(e){this.addTextMessage(e,"assistant",{role:"assistant",content:e||""})}createOpenAIClient(){return new be({apiKey:this.config.apiKey,baseURL:this.getBaseURL(),dangerouslyAllowBrowser:!0})}async sendMessage(e,r){this.addUserMessage(e);let n=this.createOpenAIClient(),i=!0,o=[];for(;i;){let s="msg-"+dr();i=!1,await this.config.onBeforeMessageProcessing?.(),await this.trimMessages(),W_.debug("Before processing state",{messages:this.messageGroup.getAll().map(d=>d.data),tools:this.toolGroup.getAll().map(d=>d.data),context:this.contextGroup.getAll().map(d=>d.text)});let a=this.toolGroup.getAll().filter(d=>!!d?.data).map(d=>({type:"function",function:{name:d.data.name,description:d.data.description||"",parameters:{type:"object",...d.data?.params}}})),l,c;if(this.config.stream){let d=n.chat.completions.stream({model:this.config.model,messages:[{role:"system",content:this.contextGroup.getAllAsString()},...this.messageGroup.getAll().map(p=>p.data)],tools:a,stream:!0,parallel_tool_calls:!0,stream_options:{include_usage:!0}});for await(let p of d){let f=d.currentChatCompletionSnapshot?.choices?.[0]?.message;if(!f)continue;let m=this.parseMessageBlock(s,f,void 0,!0);this.config.onAIMessage?.([...o,m],!0),r?.([...o,m])}l=await d.finalMessage(),c=await d.totalUsage()}else{let d=await n.chat.completions.create({model:this.config.model,messages:[{role:"system",content:this.contextGroup.getAllAsString()},...this.messageGroup.getAll().map(p=>p.data)],tools:a,parallel_tool_calls:!0});l=d.choices[0].message,c=d.usage}l.role=="assistant"&&!l.content&&!l.tool_calls?.length&&(l.content=""),W_.debug("Message received",l);let u=this.messageGroup.add(this.parseMessageBlock(s,l,c,!1));o.push(u),await Promise.all((l.tool_calls||[]).map(async d=>{if(d.type!="function")return;let p=this.findToolBySafeName(d.function.name);try{let f=null;try{f=d.function.arguments?JSON.parse(d.function.arguments):null}catch(y){throw new Error(`The AI provided invalid JSON arguments for tool call ${d.function.name}: ${y.message}`)}let m=await this.executeTool(p,f),h=this.messageGroup.add({source:"user",sections:[{type:"tool_result",toolName:d.function.name,toolKbID:p?.kbItem?.id,toolKbName:p?.kbItem?.name,toolSuccessResponse:m,toolCallInstanceID:d.id,toolCallHiddenInUI:p?.kbItem?.hideActionInUI}],data:{role:"tool",tool_call_id:d.id,content:m}});o.push(h)}catch(f){let m=f?.message||"An unknown error occurred",h=this.messageGroup.add({source:"user",sections:[{type:"tool_result",toolName:d.function.name,toolKbID:p?.kbItem?.id,toolKbName:p?.kbItem?.name,toolErrorResponse:m,toolCallInstanceID:d.id,toolCallHiddenInUI:p?.kbItem?.hideActionInUI}],data:{role:"tool",tool_call_id:d.id,content:`Error performing tool call ${d.function.name}: ${m}`}});o.push(h)}i=!0,this.config.onAIMessage?.(o,!0),r?.(o)})),this.stats.tokensUsed+=c?.total_tokens||0}return this.config.onAIMessage?.(o,!1),r?.(o),o}parseMessageBlock(e,r,n,i){let o=[];r.reasoning&&o.push({type:"thinking",text:r.reasoning});for(let s of r.tool_calls||[]){if(s.type!="function")continue;let a=this.findToolBySafeName(s.function.name),l=null;if(s.function.arguments)try{l=JSON.parse(s.function.arguments)}catch(c){i||W_.error(`Failed to parse tool parameters for tool call ${s.function.name}:`,c)}o.push({type:"tool_call",toolName:s.function.name,toolKbID:a?.kbItem?.id,toolKbName:a?.kbItem?.name,toolCallInstanceID:s.id,toolCallHiddenInUI:a?.kbItem?.hideActionInUI,toolParameters:l})}return typeof r.content=="string"&&o.push({type:"text",text:r.content||""}),{id:e,data:r,sections:o,source:"assistant",streamingInProgress:i,usage:{inputTokens:n?.prompt_tokens||0,outputTokens:n?.completion_tokens||0,cachedInputTokens:0,totalTokens:(n?.prompt_tokens||0)+(n?.completion_tokens||0)}}}async trimMessages(){for(await super.trimMessages();this.messageGroup.items.length&&this.messageGroup.items[0].data?.role=="tool";)this.messageGroup.items.shift()}};function he(t,e,r,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(t,r):i?i.value=r:e.set(t,r),r}function U(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)}var B_=function(){let{crypto:t}=globalThis;if(t?.randomUUID)return B_=t.randomUUID.bind(t),t.randomUUID();let e=new Uint8Array(1),r=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^r()&15>>+n/4).toString(16))};function lo(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var xd=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){let e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)};var pe=class extends Error{},nr=class t extends pe{constructor(e,r,n,i){super(`${t.makeMessage(e,r,n)}`),this.status=e,this.headers=i,this.requestID=i?.get("request-id"),this.error=r}static makeMessage(e,r,n){let i=r?.message?typeof r.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):n;return e&&i?`${e} ${i}`:e?`${e} status code (no body)`:i||"(no status code or body)"}static generate(e,r,n,i){if(!e||!i)return new ns({message:n,cause:xd(r)});let o=r;return e===400?new lc(e,o,n,i):e===401?new cc(e,o,n,i):e===403?new uc(e,o,n,i):e===404?new dc(e,o,n,i):e===409?new fc(e,o,n,i):e===422?new pc(e,o,n,i):e===429?new mc(e,o,n,i):e>=500?new hc(e,o,n,i):new t(e,o,n,i)}},fr=class extends nr{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},ns=class extends nr{constructor({message:e,cause:r}){super(void 0,void 0,e||"Connection error.",void 0),r&&(this.cause=r)}},ac=class extends ns{constructor({message:e}={}){super({message:e??"Request timed out."})}},lc=class extends nr{},cc=class extends nr{},uc=class extends nr{},dc=class extends nr{},fc=class extends nr{},pc=class extends nr{},mc=class extends nr{},hc=class extends nr{};var z2=/^[a-z][a-z0-9+.-]*:/i,S1=t=>z2.test(t),G_=t=>(G_=Array.isArray,G_(t)),H_=G_;function X_(t){return typeof t!="object"?{}:t??{}}function I1(t){if(!t)return!0;for(let e in t)return!1;return!0}function E1(t,e){return Object.prototype.hasOwnProperty.call(t,e)}var P1=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new pe(`${t} must be an integer`);if(e<0)throw new pe(`${t} must be a positive integer`);return e};var sh=t=>{try{return JSON.parse(t)}catch{return}};var T1=t=>new Promise(e=>setTimeout(e,t));var is="0.60.0";var N1=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function C2(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}var N2=()=>{let t=C2();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":is,"X-Stainless-OS":z1(Deno.build.os),"X-Stainless-Arch":A1(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":is,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(t==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":is,"X-Stainless-OS":z1(globalThis.process.platform??"unknown"),"X-Stainless-Arch":A1(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=O2();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":is,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":is,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function O2(){if(typeof navigator>"u"||!navigator)return null;let t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:r}of t){let n=r.exec(navigator.userAgent);if(n){let i=n[1]||0,o=n[2]||0,s=n[3]||0;return{browser:e,version:`${i}.${o}.${s}`}}}return null}var A1=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",z1=t=>(t=t.toLowerCase(),t.includes("ios")?"iOS":t==="android"?"Android":t==="darwin"?"MacOS":t==="win32"?"Windows":t==="freebsd"?"FreeBSD":t==="openbsd"?"OpenBSD":t==="linux"?"Linux":t?`Other:${t}`:"Unknown"),C1,O1=()=>C1??(C1=N2());function R1(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function K_(...t){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...t)}function ah(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return K_({start(){},async pull(r){let{done:n,value:i}=await e.next();n?r.close():r.enqueue(i)},async cancel(){await e.return?.()}})}function $d(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{async next(){try{let r=await e.read();return r?.done&&e.releaseLock(),r}catch(r){throw e.releaseLock(),r}},async return(){let r=e.cancel();return e.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function M1(t){if(t===null||typeof t!="object")return;if(t[Symbol.asyncIterator]){await t[Symbol.asyncIterator]().return?.();return}let e=t.getReader(),r=e.cancel();e.releaseLock(),await r}var j1=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});function U1(t){let e=0;for(let i of t)e+=i.length;let r=new Uint8Array(e),n=0;for(let i of t)r.set(i,n),n+=i.length;return r}var D1;function kd(t){let e;return(D1??(e=new globalThis.TextEncoder,D1=e.encode.bind(e)))(t)}var L1;function J_(t){let e;return(L1??(e=new globalThis.TextDecoder,L1=e.decode.bind(e)))(t)}var vn,_n,co=class{constructor(){vn.set(this,void 0),_n.set(this,void 0),he(this,vn,new Uint8Array,"f"),he(this,_n,null,"f")}decode(e){if(e==null)return[];let r=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?kd(e):e;he(this,vn,U1([U(this,vn,"f"),r]),"f");let n=[],i;for(;(i=j2(U(this,vn,"f"),U(this,_n,"f")))!=null;){if(i.carriage&&U(this,_n,"f")==null){he(this,_n,i.index,"f");continue}if(U(this,_n,"f")!=null&&(i.index!==U(this,_n,"f")+1||i.carriage)){n.push(J_(U(this,vn,"f").subarray(0,U(this,_n,"f")-1))),he(this,vn,U(this,vn,"f").subarray(U(this,_n,"f")),"f"),he(this,_n,null,"f");continue}let o=U(this,_n,"f")!==null?i.preceding-1:i.preceding,s=J_(U(this,vn,"f").subarray(0,o));n.push(s),he(this,vn,U(this,vn,"f").subarray(i.index),"f"),he(this,_n,null,"f")}return n}flush(){return U(this,vn,"f").length?this.decode(`
|
|
45
|
+
`):[]}};vn=new WeakMap,_n=new WeakMap;co.NEWLINE_CHARS=new Set([`
|
|
46
|
+
`,"\r"]);co.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function j2(t,e){for(let i=e??0;i<t.length;i++){if(t[i]===10)return{preceding:i,index:i+1,carriage:!1};if(t[i]===13)return{preceding:i,index:i+1,carriage:!0}}return null}function Z1(t){for(let n=0;n<t.length-1;n++){if(t[n]===10&&t[n+1]===10||t[n]===13&&t[n+1]===13)return n+2;if(t[n]===13&&t[n+1]===10&&n+3<t.length&&t[n+2]===13&&t[n+3]===10)return n+4}return-1}var ch={off:0,error:200,warn:300,info:400,debug:500},Y_=(t,e,r)=>{if(t){if(E1(ch,t))return t;ir(r).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(ch))}`)}};function Sd(){}function lh(t,e,r){return!e||ch[t]>ch[r]?Sd:e[t].bind(e)}var D2={error:Sd,warn:Sd,info:Sd,debug:Sd},F1=new WeakMap;function ir(t){let e=t.logger,r=t.logLevel??"off";if(!e)return D2;let n=F1.get(e);if(n&&n[0]===r)return n[1];let i={error:lh("error",e,r),warn:lh("warn",e,r),info:lh("info",e,r),debug:lh("debug",e,r)};return F1.set(e,[r,i]),i}var uo=t=>(t.options&&(t.options={...t.options},delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,r])=>[e,e.toLowerCase()==="x-api-key"||e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":r]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t);var Id,Ei=class t{constructor(e,r,n){this.iterator=e,Id.set(this,void 0),this.controller=r,he(this,Id,n,"f")}static fromSSEResponse(e,r,n){let i=!1,o=n?ir(n):console;async function*s(){if(i)throw new pe("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let a=!1;try{for await(let l of L2(e,r)){if(l.event==="completion")try{yield JSON.parse(l.data)}catch(c){throw o.error("Could not parse message into JSON:",l.data),o.error("From chunk:",l.raw),c}if(l.event==="message_start"||l.event==="message_delta"||l.event==="message_stop"||l.event==="content_block_start"||l.event==="content_block_delta"||l.event==="content_block_stop")try{yield JSON.parse(l.data)}catch(c){throw o.error("Could not parse message into JSON:",l.data),o.error("From chunk:",l.raw),c}if(l.event!=="ping"&&l.event==="error")throw new nr(void 0,sh(l.data)??l.data,void 0,e.headers)}a=!0}catch(l){if(lo(l))return;throw l}finally{a||r.abort()}}return new t(s,r,n)}static fromReadableStream(e,r,n){let i=!1;async function*o(){let a=new co,l=$d(e);for await(let c of l)for(let u of a.decode(c))yield u;for(let c of a.flush())yield c}async function*s(){if(i)throw new pe("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let a=!1;try{for await(let l of o())a||l&&(yield JSON.parse(l));a=!0}catch(l){if(lo(l))return;throw l}finally{a||r.abort()}}return new t(s,r,n)}[(Id=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],r=[],n=this.iterator(),i=o=>({next:()=>{if(o.length===0){let s=n.next();e.push(s),r.push(s)}return o.shift()}});return[new t(()=>i(e),this.controller,U(this,Id,"f")),new t(()=>i(r),this.controller,U(this,Id,"f"))]}toReadableStream(){let e=this,r;return K_({async start(){r=e[Symbol.asyncIterator]()},async pull(n){try{let{value:i,done:o}=await r.next();if(o)return n.close();let s=kd(JSON.stringify(i)+`
|
|
47
|
+
`);n.enqueue(s)}catch(i){n.error(i)}},async cancel(){await r.return?.()}})}};async function*L2(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new pe("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new pe("Attempted to iterate over a response with no body");let r=new Q_,n=new co,i=$d(t.body);for await(let o of U2(i))for(let s of n.decode(o)){let a=r.decode(s);a&&(yield a)}for(let o of n.flush()){let s=r.decode(o);s&&(yield s)}}async function*U2(t){let e=new Uint8Array;for await(let r of t){if(r==null)continue;let n=r instanceof ArrayBuffer?new Uint8Array(r):typeof r=="string"?kd(r):r,i=new Uint8Array(e.length+n.length);i.set(e),i.set(n,e.length),e=i;let o;for(;(o=Z1(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}var Q_=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let o={event:this.event,data:this.data.join(`
|
|
48
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(e),e.startsWith(":"))return null;let[r,n,i]=Z2(e,":");return i.startsWith(" ")&&(i=i.substring(1)),r==="event"?this.event=i:r==="data"&&this.data.push(i),null}};function Z2(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}async function uh(t,e){let{response:r,requestLogID:n,retryOfRequestLogID:i,startTime:o}=e,s=await(async()=>{if(e.options.stream)return ir(t).debug("response",r.status,r.url,r.headers,r.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(r,e.controller):Ei.fromSSEResponse(r,e.controller);if(r.status===204)return null;if(e.options.__binaryResponse)return r;let l=r.headers.get("content-type")?.split(";")[0]?.trim();if(l?.includes("application/json")||l?.endsWith("+json")){let d=await r.json();return eb(d,r)}return await r.text()})();return ir(t).debug(`[${n}] response parsed`,uo({retryOfRequestLogID:i,url:r.url,status:r.status,body:s,durationMs:Date.now()-o})),s}function eb(t,e){return!t||typeof t!="object"||Array.isArray(t)?t:Object.defineProperty(t,"_request_id",{value:e.headers.get("request-id"),enumerable:!1})}var Ed,da=class t extends Promise{constructor(e,r,n=uh){super(i=>{i(null)}),this.responsePromise=r,this.parseResponse=n,Ed.set(this,void 0),he(this,Ed,e,"f")}_thenUnwrap(e){return new t(U(this,Ed,"f"),this.responsePromise,async(r,n)=>eb(e(await this.parseResponse(r,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,r]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:r,request_id:r.headers.get("request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(U(this,Ed,"f"),e))),this.parsedPromise}then(e,r){return this.parse().then(e,r)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};Ed=new WeakMap;var dh,tb=class{constructor(e,r,n,i){dh.set(this,void 0),he(this,dh,e,"f"),this.options=i,this.response=r,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new pe("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await U(this,dh,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(dh=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let r of e.getPaginatedItems())yield r}},Pd=class extends da{constructor(e,r,n){super(e,r,async(i,o)=>new n(i,o.response,await uh(i,o),o.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let r of e)yield r}},Cn=class extends tb{constructor(e,r,n,i){super(e,r,n,i),this.data=n.data||[],this.has_more=n.has_more||!1,this.first_id=n.first_id||null,this.last_id=n.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){if(this.options.query?.before_id){let r=this.first_id;return r?{...this.options,query:{...X_(this.options.query),before_id:r}}:null}let e=this.last_id;return e?{...this.options,query:{...X_(this.options.query),after_id:e}}:null}};var nb=()=>{if(typeof File>"u"){let{process:t}=globalThis,e=typeof t?.versions?.node=="string"&&parseInt(t.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function fa(t,e,r){return nb(),new File(t,e??"unknown_file",r)}function Td(t){return(typeof t=="object"&&t!==null&&("name"in t&&t.name&&String(t.name)||"url"in t&&t.url&&String(t.url)||"filename"in t&&t.filename&&String(t.filename)||"path"in t&&t.path&&String(t.path))||"").split(/[\\/]/).pop()||void 0}var ib=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function";var q1=async(t,e)=>({...t,body:await q2(t.body,e)}),V1=new WeakMap;function V2(t){let e=typeof t=="function"?t:t.fetch,r=V1.get(e);if(r)return r;let n=(async()=>{try{let i="Response"in e?e.Response:(await e("data:,")).constructor,o=new FormData;return o.toString()!==await new i(o).text()}catch{return!0}})();return V1.set(e,n),n}var q2=async(t,e)=>{if(!await V2(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let r=new FormData;return await Promise.all(Object.entries(t||{}).map(([n,i])=>rb(r,n,i))),r},W2=t=>t instanceof Blob&&"name"in t;var rb=async(t,e,r)=>{if(r!==void 0){if(r==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")t.append(e,String(r));else if(r instanceof Response){let n={},i=r.headers.get("Content-Type");i&&(n={type:i}),t.append(e,fa([await r.blob()],Td(r),n))}else if(ib(r))t.append(e,fa([await new Response(ah(r)).blob()],Td(r)));else if(W2(r))t.append(e,fa([r],Td(r),{type:r.type}));else if(Array.isArray(r))await Promise.all(r.map(n=>rb(t,e+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,i])=>rb(t,`${e}[${n}]`,i)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)}};var W1=t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function",B2=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&W1(t),G2=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function fh(t,e,r){if(nb(),t=await t,e||(e=Td(t)),B2(t))return t instanceof File&&e==null&&r==null?t:fa([await t.arrayBuffer()],e??t.name,{type:t.type,lastModified:t.lastModified,...r});if(G2(t)){let i=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),fa(await ob(i),e,r)}let n=await ob(t);if(!r?.type){let i=n.find(o=>typeof o=="object"&&"type"in o&&o.type);typeof i=="string"&&(r={...r,type:i})}return fa(n,e,r)}async function ob(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(W1(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(ib(t))for await(let r of t)e.push(...await ob(r));else{let r=t?.constructor?.name;throw new Error(`Unexpected data type: ${typeof t}${r?`; constructor: ${r}`:""}${H2(t)}`)}return e}function H2(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}var Ht=class{constructor(e){this._client=e}};var B1=Symbol.for("brand.privateNullableHeaders");function*K2(t){if(!t)return;if(B1 in t){let{values:n,nulls:i}=t;yield*n.entries();for(let o of i)yield[o,null];return}let e=!1,r;t instanceof Headers?r=t.entries():H_(t)?r=t:(e=!0,r=Object.entries(t??{}));for(let n of r){let i=n[0];if(typeof i!="string")throw new TypeError("expected header name to be a string");let o=H_(n[1])?n[1]:[n[1]],s=!1;for(let a of o)a!==void 0&&(e&&!s&&(s=!0,yield[i,null]),yield[i,a])}}var rt=t=>{let e=new Headers,r=new Set;for(let n of t){let i=new Set;for(let[o,s]of K2(n)){let a=o.toLowerCase();i.has(a)||(e.delete(o),i.add(a)),s===null?(e.delete(o),r.add(a)):(e.append(o,s),r.delete(a))}}return{[B1]:!0,values:e,nulls:r}};function H1(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var G1=Object.freeze(Object.create(null)),J2=(t=H1)=>function(r,...n){if(r.length===1)return r[0];let i=!1,o=[],s=r.reduce((u,d,p)=>{/[?#]/.test(d)&&(i=!0);let f=n[p],m=(i?encodeURIComponent:t)(""+f);return p!==n.length&&(f==null||typeof f=="object"&&f.toString===Object.getPrototypeOf(Object.getPrototypeOf(f.hasOwnProperty??G1)??G1)?.toString)&&(m=f+"",o.push({start:u.length+d.length,length:m.length,error:`Value of type ${Object.prototype.toString.call(f).slice(8,-1)} is not a valid path parameter`})),u+d+(p===n.length?"":m)},""),a=s.split(/[?#]/,1)[0],l=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,c;for(;(c=l.exec(a))!==null;)o.push({start:c.index,length:c[0].length,error:`Value "${c[0]}" can't be safely passed as a path parameter`});if(o.sort((u,d)=>u.start-d.start),o.length>0){let u=0,d=o.reduce((p,f)=>{let m=" ".repeat(f.start-u),h="^".repeat(f.length);return u=f.start+f.length,p+m+h},"");throw new pe(`Path parameters result in path with invalid segments:
|
|
49
|
+
${o.map(p=>p.error).join(`
|
|
50
|
+
`)}
|
|
51
|
+
${s}
|
|
52
|
+
${d}`)}return s},Sr=J2(H1);var gc=class extends Ht{list(e={},r){let{betas:n,...i}=e??{};return this._client.getAPIList("/v1/files",Cn,{query:i,...r,headers:rt([{"anthropic-beta":[...n??[],"files-api-2025-04-14"].toString()},r?.headers])})}delete(e,r={},n){let{betas:i}=r??{};return this._client.delete(Sr`/v1/files/${e}`,{...n,headers:rt([{"anthropic-beta":[...i??[],"files-api-2025-04-14"].toString()},n?.headers])})}download(e,r={},n){let{betas:i}=r??{};return this._client.get(Sr`/v1/files/${e}/content`,{...n,headers:rt([{"anthropic-beta":[...i??[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},n?.headers]),__binaryResponse:!0})}retrieveMetadata(e,r={},n){let{betas:i}=r??{};return this._client.get(Sr`/v1/files/${e}`,{...n,headers:rt([{"anthropic-beta":[...i??[],"files-api-2025-04-14"].toString()},n?.headers])})}upload(e,r){let{betas:n,...i}=e;return this._client.post("/v1/files",q1({body:i,...r,headers:rt([{"anthropic-beta":[...n??[],"files-api-2025-04-14"].toString()},r?.headers])},this._client))}};var yc=class extends Ht{retrieve(e,r={},n){let{betas:i}=r??{};return this._client.get(Sr`/v1/models/${e}?beta=true`,{...n,headers:rt([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},n?.headers])})}list(e={},r){let{betas:n,...i}=e??{};return this._client.getAPIList("/v1/models?beta=true",Cn,{query:i,...r,headers:rt([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},r?.headers])})}};var vc=class t{constructor(e,r){this.iterator=e,this.controller=r}async*decoder(){let e=new co;for await(let r of this.iterator)for(let n of e.decode(r))yield JSON.parse(n);for(let r of e.flush())yield JSON.parse(r)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(e,r){if(!e.body)throw r.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new pe("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new pe("Attempted to iterate over a response with no body");return new t($d(e.body),r)}};var _c=class extends Ht{create(e,r){let{betas:n,...i}=e;return this._client.post("/v1/messages/batches?beta=true",{body:i,...r,headers:rt([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},r?.headers])})}retrieve(e,r={},n){let{betas:i}=r??{};return this._client.get(Sr`/v1/messages/batches/${e}?beta=true`,{...n,headers:rt([{"anthropic-beta":[...i??[],"message-batches-2024-09-24"].toString()},n?.headers])})}list(e={},r){let{betas:n,...i}=e??{};return this._client.getAPIList("/v1/messages/batches?beta=true",Cn,{query:i,...r,headers:rt([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},r?.headers])})}delete(e,r={},n){let{betas:i}=r??{};return this._client.delete(Sr`/v1/messages/batches/${e}?beta=true`,{...n,headers:rt([{"anthropic-beta":[...i??[],"message-batches-2024-09-24"].toString()},n?.headers])})}cancel(e,r={},n){let{betas:i}=r??{};return this._client.post(Sr`/v1/messages/batches/${e}/cancel?beta=true`,{...n,headers:rt([{"anthropic-beta":[...i??[],"message-batches-2024-09-24"].toString()},n?.headers])})}async results(e,r={},n){let i=await this.retrieve(e);if(!i.results_url)throw new pe(`No batch \`results_url\`; Has it finished processing? ${i.processing_status} - ${i.id}`);let{betas:o}=r??{};return this._client.get(i.results_url,{...n,headers:rt([{"anthropic-beta":[...o??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},n?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((s,a)=>vc.fromResponse(a.response,a.controller))}};var tL=t=>{let e=0,r=[];for(;e<t.length;){let n=t[e];if(n==="\\"){e++;continue}if(n==="{"){r.push({type:"brace",value:"{"}),e++;continue}if(n==="}"){r.push({type:"brace",value:"}"}),e++;continue}if(n==="["){r.push({type:"paren",value:"["}),e++;continue}if(n==="]"){r.push({type:"paren",value:"]"}),e++;continue}if(n===":"){r.push({type:"separator",value:":"}),e++;continue}if(n===","){r.push({type:"delimiter",value:","}),e++;continue}if(n==='"'){let a="",l=!1;for(n=t[++e];n!=='"';){if(e===t.length){l=!0;break}if(n==="\\"){if(e++,e===t.length){l=!0;break}a+=n+t[e],n=t[++e]}else a+=n,n=t[++e]}n=t[++e],l||r.push({type:"string",value:a});continue}if(n&&/\s/.test(n)){e++;continue}let o=/[0-9]/;if(n&&o.test(n)||n==="-"||n==="."){let a="";for(n==="-"&&(a+=n,n=t[++e]);n&&o.test(n)||n===".";)a+=n,n=t[++e];r.push({type:"number",value:a});continue}let s=/[a-z]/i;if(n&&s.test(n)){let a="";for(;n&&s.test(n)&&e!==t.length;)a+=n,n=t[++e];if(a=="true"||a=="false"||a==="null")r.push({type:"name",value:a});else{e++;continue}continue}e++}return r},bc=t=>{if(t.length===0)return t;let e=t[t.length-1];switch(e.type){case"separator":return t=t.slice(0,t.length-1),bc(t);break;case"number":let r=e.value[e.value.length-1];if(r==="."||r==="-")return t=t.slice(0,t.length-1),bc(t);case"string":let n=t[t.length-2];if(n?.type==="delimiter")return t=t.slice(0,t.length-1),bc(t);if(n?.type==="brace"&&n.value==="{")return t=t.slice(0,t.length-1),bc(t);break;case"delimiter":return t=t.slice(0,t.length-1),bc(t);break}return t},rL=t=>{let e=[];return t.map(r=>{r.type==="brace"&&(r.value==="{"?e.push("}"):e.splice(e.lastIndexOf("}"),1)),r.type==="paren"&&(r.value==="["?e.push("]"):e.splice(e.lastIndexOf("]"),1))}),e.length>0&&e.reverse().map(r=>{r==="}"?t.push({type:"brace",value:"}"}):r==="]"&&t.push({type:"paren",value:"]"})}),t},nL=t=>{let e="";return t.map(r=>{switch(r.type){case"string":e+='"'+r.value+'"';break;default:e+=r.value;break}}),e},ph=t=>JSON.parse(nL(rL(bc(tL(t)))));var Nn,os,Ad,mh,zd,Cd,hh,Nd,fo,Od,gh,yh,wc,vh,_h,sb,X1,bh,ab,lb,cb,K1,J1="__json_buf";function Y1(t){return t.type==="tool_use"||t.type==="server_tool_use"||t.type==="mcp_tool_use"}var wh=class t{constructor(){Nn.add(this),this.messages=[],this.receivedMessages=[],os.set(this,void 0),this.controller=new AbortController,Ad.set(this,void 0),mh.set(this,()=>{}),zd.set(this,()=>{}),Cd.set(this,void 0),hh.set(this,()=>{}),Nd.set(this,()=>{}),fo.set(this,{}),Od.set(this,!1),gh.set(this,!1),yh.set(this,!1),wc.set(this,!1),vh.set(this,void 0),_h.set(this,void 0),bh.set(this,e=>{if(he(this,gh,!0,"f"),lo(e)&&(e=new fr),e instanceof fr)return he(this,yh,!0,"f"),this._emit("abort",e);if(e instanceof pe)return this._emit("error",e);if(e instanceof Error){let r=new pe(e.message);return r.cause=e,this._emit("error",r)}return this._emit("error",new pe(String(e)))}),he(this,Ad,new Promise((e,r)=>{he(this,mh,e,"f"),he(this,zd,r,"f")}),"f"),he(this,Cd,new Promise((e,r)=>{he(this,hh,e,"f"),he(this,Nd,r,"f")}),"f"),U(this,Ad,"f").catch(()=>{}),U(this,Cd,"f").catch(()=>{})}get response(){return U(this,vh,"f")}get request_id(){return U(this,_h,"f")}async withResponse(){let e=await U(this,Ad,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){let r=new t;return r._run(()=>r._fromReadableStream(e)),r}static createMessage(e,r,n){let i=new t;for(let o of r.messages)i._addMessageParam(o);return i._run(()=>i._createMessage(e,{...r,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),i}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},U(this,bh,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,r=!0){this.receivedMessages.push(e),r&&this._emit("message",e)}async _createMessage(e,r,n){let i=n?.signal,o;i&&(i.aborted&&this.controller.abort(),o=this.controller.abort.bind(this.controller),i.addEventListener("abort",o));try{U(this,Nn,"m",ab).call(this);let{response:s,data:a}=await e.create({...r,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(s);for await(let l of a)U(this,Nn,"m",lb).call(this,l);if(a.controller.signal?.aborted)throw new fr;U(this,Nn,"m",cb).call(this)}finally{i&&o&&i.removeEventListener("abort",o)}}_connected(e){this.ended||(he(this,vh,e,"f"),he(this,_h,e?.headers.get("request-id"),"f"),U(this,mh,"f").call(this,e),this._emit("connect"))}get ended(){return U(this,Od,"f")}get errored(){return U(this,gh,"f")}get aborted(){return U(this,yh,"f")}abort(){this.controller.abort()}on(e,r){return(U(this,fo,"f")[e]||(U(this,fo,"f")[e]=[])).push({listener:r}),this}off(e,r){let n=U(this,fo,"f")[e];if(!n)return this;let i=n.findIndex(o=>o.listener===r);return i>=0&&n.splice(i,1),this}once(e,r){return(U(this,fo,"f")[e]||(U(this,fo,"f")[e]=[])).push({listener:r,once:!0}),this}emitted(e){return new Promise((r,n)=>{he(this,wc,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,r)})}async done(){he(this,wc,!0,"f"),await U(this,Cd,"f")}get currentMessage(){return U(this,os,"f")}async finalMessage(){return await this.done(),U(this,Nn,"m",sb).call(this)}async finalText(){return await this.done(),U(this,Nn,"m",X1).call(this)}_emit(e,...r){if(U(this,Od,"f"))return;e==="end"&&(he(this,Od,!0,"f"),U(this,hh,"f").call(this));let n=U(this,fo,"f")[e];if(n&&(U(this,fo,"f")[e]=n.filter(i=>!i.once),n.forEach(({listener:i})=>i(...r))),e==="abort"){let i=r[0];!U(this,wc,"f")&&!n?.length&&Promise.reject(i),U(this,zd,"f").call(this,i),U(this,Nd,"f").call(this,i),this._emit("end");return}if(e==="error"){let i=r[0];!U(this,wc,"f")&&!n?.length&&Promise.reject(i),U(this,zd,"f").call(this,i),U(this,Nd,"f").call(this,i),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",U(this,Nn,"m",sb).call(this))}async _fromReadableStream(e,r){let n=r?.signal,i;n&&(n.aborted&&this.controller.abort(),i=this.controller.abort.bind(this.controller),n.addEventListener("abort",i));try{U(this,Nn,"m",ab).call(this),this._connected(null);let o=Ei.fromReadableStream(e,this.controller);for await(let s of o)U(this,Nn,"m",lb).call(this,s);if(o.controller.signal?.aborted)throw new fr;U(this,Nn,"m",cb).call(this)}finally{n&&i&&n.removeEventListener("abort",i)}}[(os=new WeakMap,Ad=new WeakMap,mh=new WeakMap,zd=new WeakMap,Cd=new WeakMap,hh=new WeakMap,Nd=new WeakMap,fo=new WeakMap,Od=new WeakMap,gh=new WeakMap,yh=new WeakMap,wc=new WeakMap,vh=new WeakMap,_h=new WeakMap,bh=new WeakMap,Nn=new WeakSet,sb=function(){if(this.receivedMessages.length===0)throw new pe("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},X1=function(){if(this.receivedMessages.length===0)throw new pe("stream ended without producing a Message with role=assistant");let r=this.receivedMessages.at(-1).content.filter(n=>n.type==="text").map(n=>n.text);if(r.length===0)throw new pe("stream ended without producing a content block with type=text");return r.join(" ")},ab=function(){this.ended||he(this,os,void 0,"f")},lb=function(r){if(this.ended)return;let n=U(this,Nn,"m",K1).call(this,r);switch(this._emit("streamEvent",r,n),r.type){case"content_block_delta":{let i=n.content.at(-1);switch(r.delta.type){case"text_delta":{i.type==="text"&&this._emit("text",r.delta.text,i.text||"");break}case"citations_delta":{i.type==="text"&&this._emit("citation",r.delta.citation,i.citations??[]);break}case"input_json_delta":{Y1(i)&&i.input&&this._emit("inputJson",r.delta.partial_json,i.input);break}case"thinking_delta":{i.type==="thinking"&&this._emit("thinking",r.delta.thinking,i.thinking);break}case"signature_delta":{i.type==="thinking"&&this._emit("signature",i.signature);break}default:r.delta}break}case"message_stop":{this._addMessageParam(n),this._addMessage(n,!0);break}case"content_block_stop":{this._emit("contentBlock",n.content.at(-1));break}case"message_start":{he(this,os,n,"f");break}case"content_block_start":case"message_delta":break}},cb=function(){if(this.ended)throw new pe("stream has ended, this shouldn't happen");let r=U(this,os,"f");if(!r)throw new pe("request ended without sending any chunks");return he(this,os,void 0,"f"),r},K1=function(r){let n=U(this,os,"f");if(r.type==="message_start"){if(n)throw new pe(`Unexpected event order, got ${r.type} before receiving "message_stop"`);return r.message}if(!n)throw new pe(`Unexpected event order, got ${r.type} before "message_start"`);switch(r.type){case"message_stop":return n;case"message_delta":return n.container=r.delta.container,n.stop_reason=r.delta.stop_reason,n.stop_sequence=r.delta.stop_sequence,n.usage.output_tokens=r.usage.output_tokens,r.usage.input_tokens!=null&&(n.usage.input_tokens=r.usage.input_tokens),r.usage.cache_creation_input_tokens!=null&&(n.usage.cache_creation_input_tokens=r.usage.cache_creation_input_tokens),r.usage.cache_read_input_tokens!=null&&(n.usage.cache_read_input_tokens=r.usage.cache_read_input_tokens),r.usage.server_tool_use!=null&&(n.usage.server_tool_use=r.usage.server_tool_use),n;case"content_block_start":return n.content.push(r.content_block),n;case"content_block_delta":{let i=n.content.at(r.index);switch(r.delta.type){case"text_delta":{i?.type==="text"&&(n.content[r.index]={...i,text:(i.text||"")+r.delta.text});break}case"citations_delta":{i?.type==="text"&&(n.content[r.index]={...i,citations:[...i.citations??[],r.delta.citation]});break}case"input_json_delta":{if(i&&Y1(i)){let o=i[J1]||"";o+=r.delta.partial_json;let s={...i};if(Object.defineProperty(s,J1,{value:o,enumerable:!1,writable:!0}),o)try{s.input=ph(o)}catch(a){let l=new pe(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${a}. JSON: ${o}`);U(this,bh,"f").call(this,l)}n.content[r.index]=s}break}case"thinking_delta":{i?.type==="thinking"&&(n.content[r.index]={...i,thinking:i.thinking+r.delta.thinking});break}case"signature_delta":{i?.type==="thinking"&&(n.content[r.index]={...i,signature:r.delta.signature});break}default:r.delta}return n}case"content_block_stop":return n}},Symbol.asyncIterator)](){let e=[],r=[],n=!1;return this.on("streamEvent",i=>{let o=r.shift();o?o.resolve(i):e.push(i)}),this.on("end",()=>{n=!0;for(let i of r)i.resolve(void 0);r.length=0}),this.on("abort",i=>{n=!0;for(let o of r)o.reject(i);r.length=0}),this.on("error",i=>{n=!0;for(let o of r)o.reject(i);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((o,s)=>r.push({resolve:o,reject:s})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Ei(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};var xh={"claude-opus-4-20250514":8192,"claude-opus-4-0":8192,"claude-4-opus-20250514":8192,"anthropic.claude-opus-4-20250514-v1:0":8192,"claude-opus-4@20250514":8192,"claude-opus-4-1-20250805":8192,"anthropic.claude-opus-4-1-20250805-v1:0":8192,"claude-opus-4-1@20250805":8192};var Q1={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-5-sonnet-20241022":"October 22, 2025","claude-3-5-sonnet-20240620":"October 22, 2025"},pa=class extends Ht{constructor(){super(...arguments),this.batches=new _c(this._client)}create(e,r){let{betas:n,...i}=e;i.model in Q1&&console.warn(`The model '${i.model}' is deprecated and will reach end-of-life on ${Q1[i.model]}
|
|
53
|
+
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);let o=this._client._options.timeout;if(!i.stream&&o==null){let s=xh[i.model]??void 0;o=this._client.calculateNonstreamingTimeout(i.max_tokens,s)}return this._client.post("/v1/messages?beta=true",{body:i,timeout:o??6e5,...r,headers:rt([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},r?.headers]),stream:e.stream??!1})}stream(e,r){return wh.createMessage(this,e,r)}countTokens(e,r){let{betas:n,...i}=e;return this._client.post("/v1/messages/count_tokens?beta=true",{body:i,...r,headers:rt([{"anthropic-beta":[...n??[],"token-counting-2024-11-01"].toString()},r?.headers])})}};pa.Batches=_c;var Pi=class extends Ht{constructor(){super(...arguments),this.models=new yc(this._client),this.messages=new pa(this._client),this.files=new gc(this._client)}};Pi.Models=yc;Pi.Messages=pa;Pi.Files=gc;var ma=class extends Ht{create(e,r){let{betas:n,...i}=e;return this._client.post("/v1/complete",{body:i,timeout:this._client._options.timeout??6e5,...r,headers:rt([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},r?.headers]),stream:e.stream??!1})}};var On,ss,Rd,$h,Md,jd,kh,Dd,po,Ld,Sh,Ih,xc,Eh,Ph,ub,eP,db,fb,pb,mb,tP,rP="__json_buf";function nP(t){return t.type==="tool_use"||t.type==="server_tool_use"}var Th=class t{constructor(){On.add(this),this.messages=[],this.receivedMessages=[],ss.set(this,void 0),this.controller=new AbortController,Rd.set(this,void 0),$h.set(this,()=>{}),Md.set(this,()=>{}),jd.set(this,void 0),kh.set(this,()=>{}),Dd.set(this,()=>{}),po.set(this,{}),Ld.set(this,!1),Sh.set(this,!1),Ih.set(this,!1),xc.set(this,!1),Eh.set(this,void 0),Ph.set(this,void 0),db.set(this,e=>{if(he(this,Sh,!0,"f"),lo(e)&&(e=new fr),e instanceof fr)return he(this,Ih,!0,"f"),this._emit("abort",e);if(e instanceof pe)return this._emit("error",e);if(e instanceof Error){let r=new pe(e.message);return r.cause=e,this._emit("error",r)}return this._emit("error",new pe(String(e)))}),he(this,Rd,new Promise((e,r)=>{he(this,$h,e,"f"),he(this,Md,r,"f")}),"f"),he(this,jd,new Promise((e,r)=>{he(this,kh,e,"f"),he(this,Dd,r,"f")}),"f"),U(this,Rd,"f").catch(()=>{}),U(this,jd,"f").catch(()=>{})}get response(){return U(this,Eh,"f")}get request_id(){return U(this,Ph,"f")}async withResponse(){let e=await U(this,Rd,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){let r=new t;return r._run(()=>r._fromReadableStream(e)),r}static createMessage(e,r,n){let i=new t;for(let o of r.messages)i._addMessageParam(o);return i._run(()=>i._createMessage(e,{...r,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),i}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},U(this,db,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,r=!0){this.receivedMessages.push(e),r&&this._emit("message",e)}async _createMessage(e,r,n){let i=n?.signal,o;i&&(i.aborted&&this.controller.abort(),o=this.controller.abort.bind(this.controller),i.addEventListener("abort",o));try{U(this,On,"m",fb).call(this);let{response:s,data:a}=await e.create({...r,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(s);for await(let l of a)U(this,On,"m",pb).call(this,l);if(a.controller.signal?.aborted)throw new fr;U(this,On,"m",mb).call(this)}finally{i&&o&&i.removeEventListener("abort",o)}}_connected(e){this.ended||(he(this,Eh,e,"f"),he(this,Ph,e?.headers.get("request-id"),"f"),U(this,$h,"f").call(this,e),this._emit("connect"))}get ended(){return U(this,Ld,"f")}get errored(){return U(this,Sh,"f")}get aborted(){return U(this,Ih,"f")}abort(){this.controller.abort()}on(e,r){return(U(this,po,"f")[e]||(U(this,po,"f")[e]=[])).push({listener:r}),this}off(e,r){let n=U(this,po,"f")[e];if(!n)return this;let i=n.findIndex(o=>o.listener===r);return i>=0&&n.splice(i,1),this}once(e,r){return(U(this,po,"f")[e]||(U(this,po,"f")[e]=[])).push({listener:r,once:!0}),this}emitted(e){return new Promise((r,n)=>{he(this,xc,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,r)})}async done(){he(this,xc,!0,"f"),await U(this,jd,"f")}get currentMessage(){return U(this,ss,"f")}async finalMessage(){return await this.done(),U(this,On,"m",ub).call(this)}async finalText(){return await this.done(),U(this,On,"m",eP).call(this)}_emit(e,...r){if(U(this,Ld,"f"))return;e==="end"&&(he(this,Ld,!0,"f"),U(this,kh,"f").call(this));let n=U(this,po,"f")[e];if(n&&(U(this,po,"f")[e]=n.filter(i=>!i.once),n.forEach(({listener:i})=>i(...r))),e==="abort"){let i=r[0];!U(this,xc,"f")&&!n?.length&&Promise.reject(i),U(this,Md,"f").call(this,i),U(this,Dd,"f").call(this,i),this._emit("end");return}if(e==="error"){let i=r[0];!U(this,xc,"f")&&!n?.length&&Promise.reject(i),U(this,Md,"f").call(this,i),U(this,Dd,"f").call(this,i),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",U(this,On,"m",ub).call(this))}async _fromReadableStream(e,r){let n=r?.signal,i;n&&(n.aborted&&this.controller.abort(),i=this.controller.abort.bind(this.controller),n.addEventListener("abort",i));try{U(this,On,"m",fb).call(this),this._connected(null);let o=Ei.fromReadableStream(e,this.controller);for await(let s of o)U(this,On,"m",pb).call(this,s);if(o.controller.signal?.aborted)throw new fr;U(this,On,"m",mb).call(this)}finally{n&&i&&n.removeEventListener("abort",i)}}[(ss=new WeakMap,Rd=new WeakMap,$h=new WeakMap,Md=new WeakMap,jd=new WeakMap,kh=new WeakMap,Dd=new WeakMap,po=new WeakMap,Ld=new WeakMap,Sh=new WeakMap,Ih=new WeakMap,xc=new WeakMap,Eh=new WeakMap,Ph=new WeakMap,db=new WeakMap,On=new WeakSet,ub=function(){if(this.receivedMessages.length===0)throw new pe("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},eP=function(){if(this.receivedMessages.length===0)throw new pe("stream ended without producing a Message with role=assistant");let r=this.receivedMessages.at(-1).content.filter(n=>n.type==="text").map(n=>n.text);if(r.length===0)throw new pe("stream ended without producing a content block with type=text");return r.join(" ")},fb=function(){this.ended||he(this,ss,void 0,"f")},pb=function(r){if(this.ended)return;let n=U(this,On,"m",tP).call(this,r);switch(this._emit("streamEvent",r,n),r.type){case"content_block_delta":{let i=n.content.at(-1);switch(r.delta.type){case"text_delta":{i.type==="text"&&this._emit("text",r.delta.text,i.text||"");break}case"citations_delta":{i.type==="text"&&this._emit("citation",r.delta.citation,i.citations??[]);break}case"input_json_delta":{nP(i)&&i.input&&this._emit("inputJson",r.delta.partial_json,i.input);break}case"thinking_delta":{i.type==="thinking"&&this._emit("thinking",r.delta.thinking,i.thinking);break}case"signature_delta":{i.type==="thinking"&&this._emit("signature",i.signature);break}default:r.delta}break}case"message_stop":{this._addMessageParam(n),this._addMessage(n,!0);break}case"content_block_stop":{this._emit("contentBlock",n.content.at(-1));break}case"message_start":{he(this,ss,n,"f");break}case"content_block_start":case"message_delta":break}},mb=function(){if(this.ended)throw new pe("stream has ended, this shouldn't happen");let r=U(this,ss,"f");if(!r)throw new pe("request ended without sending any chunks");return he(this,ss,void 0,"f"),r},tP=function(r){let n=U(this,ss,"f");if(r.type==="message_start"){if(n)throw new pe(`Unexpected event order, got ${r.type} before receiving "message_stop"`);return r.message}if(!n)throw new pe(`Unexpected event order, got ${r.type} before "message_start"`);switch(r.type){case"message_stop":return n;case"message_delta":return n.stop_reason=r.delta.stop_reason,n.stop_sequence=r.delta.stop_sequence,n.usage.output_tokens=r.usage.output_tokens,r.usage.input_tokens!=null&&(n.usage.input_tokens=r.usage.input_tokens),r.usage.cache_creation_input_tokens!=null&&(n.usage.cache_creation_input_tokens=r.usage.cache_creation_input_tokens),r.usage.cache_read_input_tokens!=null&&(n.usage.cache_read_input_tokens=r.usage.cache_read_input_tokens),r.usage.server_tool_use!=null&&(n.usage.server_tool_use=r.usage.server_tool_use),n;case"content_block_start":return n.content.push({...r.content_block}),n;case"content_block_delta":{let i=n.content.at(r.index);switch(r.delta.type){case"text_delta":{i?.type==="text"&&(n.content[r.index]={...i,text:(i.text||"")+r.delta.text});break}case"citations_delta":{i?.type==="text"&&(n.content[r.index]={...i,citations:[...i.citations??[],r.delta.citation]});break}case"input_json_delta":{if(i&&nP(i)){let o=i[rP]||"";o+=r.delta.partial_json;let s={...i};Object.defineProperty(s,rP,{value:o,enumerable:!1,writable:!0}),o&&(s.input=ph(o)),n.content[r.index]=s}break}case"thinking_delta":{i?.type==="thinking"&&(n.content[r.index]={...i,thinking:i.thinking+r.delta.thinking});break}case"signature_delta":{i?.type==="thinking"&&(n.content[r.index]={...i,signature:r.delta.signature});break}default:r.delta}return n}case"content_block_stop":return n}},Symbol.asyncIterator)](){let e=[],r=[],n=!1;return this.on("streamEvent",i=>{let o=r.shift();o?o.resolve(i):e.push(i)}),this.on("end",()=>{n=!0;for(let i of r)i.resolve(void 0);r.length=0}),this.on("abort",i=>{n=!0;for(let o of r)o.reject(i);r.length=0}),this.on("error",i=>{n=!0;for(let o of r)o.reject(i);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((o,s)=>r.push({resolve:o,reject:s})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Ei(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};var $c=class extends Ht{create(e,r){return this._client.post("/v1/messages/batches",{body:e,...r})}retrieve(e,r){return this._client.get(Sr`/v1/messages/batches/${e}`,r)}list(e={},r){return this._client.getAPIList("/v1/messages/batches",Cn,{query:e,...r})}delete(e,r){return this._client.delete(Sr`/v1/messages/batches/${e}`,r)}cancel(e,r){return this._client.post(Sr`/v1/messages/batches/${e}/cancel`,r)}async results(e,r){let n=await this.retrieve(e);if(!n.results_url)throw new pe(`No batch \`results_url\`; Has it finished processing? ${n.processing_status} - ${n.id}`);return this._client.get(n.results_url,{...r,headers:rt([{Accept:"application/binary"},r?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((i,o)=>vc.fromResponse(o.response,o.controller))}};var as=class extends Ht{constructor(){super(...arguments),this.batches=new $c(this._client)}create(e,r){e.model in iP&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${iP[e.model]}
|
|
54
|
+
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);let n=this._client._options.timeout;if(!e.stream&&n==null){let i=xh[e.model]??void 0;n=this._client.calculateNonstreamingTimeout(e.max_tokens,i)}return this._client.post("/v1/messages",{body:e,timeout:n??6e5,...r,stream:e.stream??!1})}stream(e,r){return Th.createMessage(this,e,r)}countTokens(e,r){return this._client.post("/v1/messages/count_tokens",{body:e,...r})}},iP={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-5-sonnet-20241022":"October 22, 2025","claude-3-5-sonnet-20240620":"October 22, 2025"};as.Batches=$c;var ha=class extends Ht{retrieve(e,r={},n){let{betas:i}=r??{};return this._client.get(Sr`/v1/models/${e}`,{...n,headers:rt([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},n?.headers])})}list(e={},r){let{betas:n,...i}=e??{};return this._client.getAPIList("/v1/models",Cn,{query:i,...r,headers:rt([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},r?.headers])})}};var Ud=t=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[t]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(t)?.trim()};var hb,gb,Ah,oP,zt=class{constructor({baseURL:e=Ud("ANTHROPIC_BASE_URL"),apiKey:r=Ud("ANTHROPIC_API_KEY")??null,authToken:n=Ud("ANTHROPIC_AUTH_TOKEN")??null,...i}={}){hb.add(this),Ah.set(this,void 0);let o={apiKey:r,authToken:n,...i,baseURL:e||"https://api.anthropic.com"};if(!o.dangerouslyAllowBrowser&&N1())throw new pe(`It looks like you're running in a browser-like environment.
|
|
3
55
|
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
56
|
+
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
57
|
+
If you understand the risks and have appropriate mitigations in place,
|
|
58
|
+
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
7
59
|
|
|
8
|
-
|
|
9
|
-
`)||"- (
|
|
60
|
+
new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
|
|
61
|
+
`);this.baseURL=o.baseURL,this.timeout=o.timeout??gb.DEFAULT_TIMEOUT,this.logger=o.logger??console;let s="warn";this.logLevel=s,this.logLevel=Y_(o.logLevel,"ClientOptions.logLevel",this)??Y_(Ud("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??s,this.fetchOptions=o.fetchOptions,this.maxRetries=o.maxRetries??2,this.fetch=o.fetch??R1(),he(this,Ah,j1,"f"),this._options=o,this.apiKey=r,this.authToken=n}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:r}){if(!(this.apiKey&&e.get("x-api-key"))&&!r.has("x-api-key")&&!(this.authToken&&e.get("authorization"))&&!r.has("authorization"))throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}async authHeaders(e){return rt([await this.apiKeyAuth(e),await this.bearerAuth(e)])}async apiKeyAuth(e){if(this.apiKey!=null)return rt([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken!=null)return rt([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return Object.entries(e).filter(([r,n])=>typeof n<"u").map(([r,n])=>{if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return`${encodeURIComponent(r)}=${encodeURIComponent(n)}`;if(n===null)return`${encodeURIComponent(r)}=`;throw new pe(`Cannot stringify type ${typeof n}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${is}`}defaultIdempotencyKey(){return`stainless-node-retry-${B_()}`}makeStatusError(e,r,n,i){return nr.generate(e,r,n,i)}buildURL(e,r,n){let i=!U(this,hb,"m",oP).call(this)&&n||this.baseURL,o=S1(e)?new URL(e):new URL(i+(i.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),s=this.defaultQuery();return I1(s)||(r={...s,...r}),typeof r=="object"&&r&&!Array.isArray(r)&&(o.search=this.stringifyQuery(r)),o.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new pe("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600*1e3}async prepareOptions(e){}async prepareRequest(e,{url:r,options:n}){}get(e,r){return this.methodRequest("get",e,r)}post(e,r){return this.methodRequest("post",e,r)}patch(e,r){return this.methodRequest("patch",e,r)}put(e,r){return this.methodRequest("put",e,r)}delete(e,r){return this.methodRequest("delete",e,r)}methodRequest(e,r,n){return this.request(Promise.resolve(n).then(i=>({method:e,path:r,...i})))}request(e,r=null){return new da(this,this.makeRequest(e,r,void 0))}async makeRequest(e,r,n){let i=await e,o=i.maxRetries??this.maxRetries;r==null&&(r=o),await this.prepareOptions(i);let{req:s,url:a,timeout:l}=await this.buildRequest(i,{retryCount:o-r});await this.prepareRequest(s,{url:a,options:i});let c="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),u=n===void 0?"":`, retryOf: ${n}`,d=Date.now();if(ir(this).debug(`[${c}] sending request`,uo({retryOfRequestLogID:n,method:i.method,url:a,options:i,headers:s.headers})),i.signal?.aborted)throw new fr;let p=new AbortController,f=await this.fetchWithTimeout(a,s,l,p).catch(xd),m=Date.now();if(f instanceof Error){let g=`retrying, ${r} attempts remaining`;if(i.signal?.aborted)throw new fr;let _=lo(f)||/timed? ?out/i.test(String(f)+("cause"in f?String(f.cause):""));if(r)return ir(this).info(`[${c}] connection ${_?"timed out":"failed"} - ${g}`),ir(this).debug(`[${c}] connection ${_?"timed out":"failed"} (${g})`,uo({retryOfRequestLogID:n,url:a,durationMs:m-d,message:f.message})),this.retryRequest(i,r,n??c);throw ir(this).info(`[${c}] connection ${_?"timed out":"failed"} - error; no more retries left`),ir(this).debug(`[${c}] connection ${_?"timed out":"failed"} (error; no more retries left)`,uo({retryOfRequestLogID:n,url:a,durationMs:m-d,message:f.message})),_?new ac:new ns({cause:f})}let h=[...f.headers.entries()].filter(([g])=>g==="request-id").map(([g,_])=>", "+g+": "+JSON.stringify(_)).join(""),y=`[${c}${u}${h}] ${s.method} ${a} ${f.ok?"succeeded":"failed"} with status ${f.status} in ${m-d}ms`;if(!f.ok){let g=await this.shouldRetry(f);if(r&&g){let M=`retrying, ${r} attempts remaining`;return await M1(f.body),ir(this).info(`${y} - ${M}`),ir(this).debug(`[${c}] response error (${M})`,uo({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:m-d})),this.retryRequest(i,r,n??c,f.headers)}let _=g?"error; no more retries left":"error; not retryable";ir(this).info(`${y} - ${_}`);let b=await f.text().catch(M=>xd(M).message),E=sh(b),I=E?void 0:b;throw ir(this).debug(`[${c}] response error (${_})`,uo({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,message:I,durationMs:Date.now()-d})),this.makeStatusError(f.status,E,I,f.headers)}return ir(this).info(y),ir(this).debug(`[${c}] response start`,uo({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:m-d})),{response:f,options:i,controller:p,requestLogID:c,retryOfRequestLogID:n,startTime:d}}getAPIList(e,r,n){return this.requestAPIList(r,{method:"get",path:e,...n})}requestAPIList(e,r){let n=this.makeRequest(r,null,void 0);return new Pd(this,n,e)}async fetchWithTimeout(e,r,n,i){let{signal:o,method:s,...a}=r||{};o&&o.addEventListener("abort",()=>i.abort());let l=setTimeout(()=>i.abort(),n),c=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body=="object"&&a.body!==null&&Symbol.asyncIterator in a.body,u={signal:i.signal,...c?{duplex:"half"}:{},method:"GET",...a};s&&(u.method=s.toUpperCase());try{return await this.fetch.call(void 0,e,u)}finally{clearTimeout(l)}}async shouldRetry(e){let r=e.headers.get("x-should-retry");return r==="true"?!0:r==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,r,n,i){let o,s=i?.get("retry-after-ms");if(s){let l=parseFloat(s);Number.isNaN(l)||(o=l)}let a=i?.get("retry-after");if(a&&!o){let l=parseFloat(a);Number.isNaN(l)?o=Date.parse(a)-Date.now():o=l*1e3}if(!(o&&0<=o&&o<60*1e3)){let l=e.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(r,l)}return await T1(o),this.makeRequest(e,r-1,n)}calculateDefaultRetryTimeoutMillis(e,r){let o=r-e,s=Math.min(.5*Math.pow(2,o),8),a=1-Math.random()*.25;return s*a*1e3}calculateNonstreamingTimeout(e,r){if(36e5*e/128e3>6e5||r!=null&&e>r)throw new pe("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return 6e5}async buildRequest(e,{retryCount:r=0}={}){let n={...e},{method:i,path:o,query:s,defaultBaseURL:a}=n,l=this.buildURL(o,s,a);"timeout"in n&&P1("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:c,body:u}=this.buildBody({options:n}),d=await this.buildHeaders({options:e,method:i,bodyHeaders:c,retryCount:r});return{req:{method:i,headers:d,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&u instanceof globalThis.ReadableStream&&{duplex:"half"},...u&&{body:u},...this.fetchOptions??{},...n.fetchOptions??{}},url:l,timeout:n.timeout}}async buildHeaders({options:e,method:r,bodyHeaders:n,retryCount:i}){let o={};this.idempotencyHeader&&r!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);let s=rt([o,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(i),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...O1(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(s),s.values}buildBody({options:{body:e,headers:r}}){if(!e)return{bodyHeaders:void 0,body:void 0};let n=rt([r]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&n.values.has("content-type")||e instanceof Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:ah(e)}:U(this,Ah,"f").call(this,{body:e,headers:n})}};gb=zt,Ah=new WeakMap,hb=new WeakSet,oP=function(){return this.baseURL!=="https://api.anthropic.com"};zt.Anthropic=gb;zt.HUMAN_PROMPT=`
|
|
62
|
+
|
|
63
|
+
Human:`;zt.AI_PROMPT=`
|
|
64
|
+
|
|
65
|
+
Assistant:`;zt.DEFAULT_TIMEOUT=6e5;zt.AnthropicError=pe;zt.APIError=nr;zt.APIConnectionError=ns;zt.APIConnectionTimeoutError=ac;zt.APIUserAbortError=fr;zt.NotFoundError=dc;zt.ConflictError=fc;zt.RateLimitError=mc;zt.BadRequestError=lc;zt.AuthenticationError=cc;zt.InternalServerError=hc;zt.PermissionDeniedError=uc;zt.UnprocessableEntityError=pc;zt.toFile=fh;var ei=class extends zt{constructor(){super(...arguments),this.completions=new ma(this),this.messages=new as(this),this.models=new ha(this),this.beta=new Pi(this)}};ei.Completions=ma;ei.Messages=as;ei.Models=ha;ei.Beta=Pi;var{HUMAN_PROMPT:aL,AI_PROMPT:lL}=ei;var sP=new Le("AnthropicChat"),zh=class extends oc{addUserMessage(e){this.addTextMessage(e,"user",{role:"user",content:e||""})}addAssistantMessage(e){this.addTextMessage(e,"assistant",{role:"assistant",content:e||""})}async sendMessage(e,r){this.addUserMessage(e);let n=new ei({apiKey:this.config.apiKey,baseURL:this.getBaseURL(),dangerouslyAllowBrowser:!0}),i=!0,o=[];for(;i;){i=!1,await this.config.onBeforeMessageProcessing?.(),await this.trimMessages(),sP.debug("Before processing state",{messages:this.messageGroup.getAll().map(u=>u.data),tools:this.toolGroup.getAll().map(u=>u.data),context:this.contextGroup.getAll().map(u=>u.text)});let s=this.toolGroup.getAll().map(u=>({name:u.data?.name||"",description:u.data?.description||"",input_schema:{...u.data?.params,type:"object"}})),a;if(this.config.stream){let u=n.messages.stream({model:this.config.model,max_tokens:16e3,system:this.contextGroup.getAllAsString(),messages:this.messageGroup.getAll().map(d=>d.data),tools:s,stream:!0});u.on("streamEvent",(d,p)=>{let f=this.parseMessageBlock(p,!0);this.config.onAIMessage?.([...o,f],!0),r?.([...o,f])});try{a=await u.finalMessage()}catch(d){throw d?.error?.error?.message?d.error.error:d}}else try{a=await n.messages.create({model:this.config.model,max_tokens:16e3,system:this.contextGroup.getAllAsString(),messages:this.messageGroup.items.map(u=>u.data),tools:s})}catch(u){throw u?.error?.error?.message?u.error.error:u}if(sP.debug("Message received",a),a.content?.length){let u=this.messageGroup.add(this.parseMessageBlock(a,!1));o.push(u)}let l=[],c=[];if(await Promise.all(a.content.map(async u=>{if(u.type!="tool_use")return;let d=this.findToolBySafeName(u.name);try{let p=await this.executeTool(d,u.input);c.push({type:"tool_result",tool_use_id:u.id,content:p}),l.push({type:"tool_result",toolKbID:d?.kbItem?.id,toolKbName:d?.kbItem?.name,toolName:u.name,toolSuccessResponse:p,toolCallInstanceID:u.id,toolCallHiddenInUI:d?.kbItem?.hideActionInUI})}catch(p){let f=p?.message||"An unknown error occurred";c.push({type:"tool_result",tool_use_id:u.id,content:`Error performing tool call ${u.name}: ${f}`}),l.push({type:"tool_result",toolKbID:d?.kbItem?.id,toolKbName:d?.kbItem?.name,toolName:u.name,toolErrorResponse:f,toolCallInstanceID:u.id,toolCallHiddenInUI:d?.kbItem?.hideActionInUI})}})),c.length>0){let u=this.messageGroup.add({id:"msg-"+dr(),sections:l,data:{role:"user",content:c}});o.push(u),i=!0,this.config.onAIMessage?.(o,!0),r?.(o)}this.stats.tokensUsed+=a.usage.input_tokens+a.usage.output_tokens}return this.config.onAIMessage?.(o,!1),r?.(o),o}parseMessageBlock(e,r){let n=[];for(let i of e.content)if(i.type=="thinking")n.push({type:"thinking",text:i.thinking||""});else if(i.type=="text")n.push({type:"text",text:i.text||""});else if(i.type=="tool_use"){let o=this.findToolBySafeName(i.name);n.push({type:"tool_call",toolName:i.name,toolKbID:o?.kbItem?.id,toolKbName:o?.kbItem?.name,toolParameters:i.input,toolCallInstanceID:i.id,toolCallHiddenInUI:o?.kbItem?.hideActionInUI})}return{id:e.id,data:{role:e.role,content:e.content},sections:n,source:"assistant",streamingInProgress:r,usage:{inputTokens:e.usage?.input_tokens||0,outputTokens:e.usage?.output_tokens||0,cachedInputTokens:e.usage?.cache_read_input_tokens||0,totalTokens:(e.usage?.input_tokens||0)+(e.usage?.output_tokens||0)}}}async trimMessages(){for(await super.trimMessages();this.messageGroup.items[0]?.data?.content?.type=="tool_result";)this.messageGroup.items.shift()}};var gt=function(){return gt=Object.assign||function(e){for(var r,n=1,i=arguments.length;n<i;n++){r=arguments[n];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(e[o]=r[o])}return e},gt.apply(this,arguments)};function cL(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function a(u){try{c(n.next(u))}catch(d){s(d)}}function l(u){try{c(n.throw(u))}catch(d){s(d)}}function c(u){u.done?o(u.value):i(u.value).then(a,l)}c((n=n.apply(t,e||[])).next())})}function uL(t,e){var r={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},n,i,o,s;return s={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(s[Symbol.iterator]=function(){return this}),s;function a(c){return function(u){return l([c,u])}}function l(c){if(n)throw new TypeError("Generator is already executing.");for(;s&&(s=0,c[0]&&(r=0)),r;)try{if(n=1,i&&(o=c[0]&2?i.return:c[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,c[1])).done)return o;switch(i=0,o&&(c=[c[0]&2,o.value]),c[0]){case 0:case 1:o=c;break;case 4:return r.label++,{value:c[1],done:!1};case 5:r.label++,i=c[1],c=[0];continue;case 7:c=r.ops.pop(),r.trys.pop();continue;default:if(o=r.trys,!(o=o.length>0&&o[o.length-1])&&(c[0]===6||c[0]===2)){r=0;continue}if(c[0]===3&&(!o||c[1]>o[0]&&c[1]<o[3])){r.label=c[1];break}if(c[0]===6&&r.label<o[1]){r.label=o[1],o=c;break}if(o&&r.label<o[2]){r.label=o[2],r.ops.push(c);break}o[2]&&r.ops.pop(),r.trys.pop();continue}c=e.call(t,r)}catch(u){c=[6,u],i=0}finally{n=o=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}function Oe(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function jt(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,o=[],s;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(a){s={error:a}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(s)throw s.error}}return o}var dL="ENTRIES",dP="KEYS",fP="VALUES",pr="",yb=function(){function t(e,r){var n=e._tree,i=Array.from(n.keys());this.set=e,this._type=r,this._path=i.length>0?[{node:n,keys:i}]:[]}return t.prototype.next=function(){var e=this.dive();return this.backtrack(),e},t.prototype.dive=function(){if(this._path.length===0)return{done:!0,value:void 0};var e=kc(this._path),r=e.node,n=e.keys;if(kc(n)===pr)return{done:!1,value:this.result()};var i=r.get(kc(n));return this._path.push({node:i,keys:Array.from(i.keys())}),this.dive()},t.prototype.backtrack=function(){if(this._path.length!==0){var e=kc(this._path).keys;e.pop(),!(e.length>0)&&(this._path.pop(),this.backtrack())}},t.prototype.key=function(){return this.set._prefix+this._path.map(function(e){var r=e.keys;return kc(r)}).filter(function(e){return e!==pr}).join("")},t.prototype.value=function(){return kc(this._path).node.get(pr)},t.prototype.result=function(){switch(this._type){case fP:return this.value();case dP:return this.key();default:return[this.key(),this.value()]}},t.prototype[Symbol.iterator]=function(){return this},t}(),kc=function(t){return t[t.length-1]},fL=function(t,e,r){var n=new Map;if(e===void 0)return n;for(var i=e.length+1,o=i+r,s=new Uint8Array(o*i).fill(r+1),a=0;a<i;++a)s[a]=a;for(var l=1;l<o;++l)s[l*i]=l;return pP(t,e,r,n,s,1,i,""),n},pP=function(t,e,r,n,i,o,s,a){var l,c,u=o*s;try{e:for(var d=Oe(t.keys()),p=d.next();!p.done;p=d.next()){var f=p.value;if(f===pr){var m=i[u-1];m<=r&&n.set(a,[t.get(f),m])}else{for(var h=o,y=0;y<f.length;++y,++h){for(var g=f[y],_=s*h,b=_-s,E=i[_],I=Math.max(0,h-r-1),P=Math.min(s-1,h+r),M=I;M<P;++M){var V=g!==e[M],R=i[b+M]+ +V,L=i[b+M+1]+1,G=i[_+M]+1,H=i[_+M+1]=Math.min(R,L,G);H<E&&(E=H)}if(E>r)continue e}pP(t.get(f),e,r,n,i,h,s,a+f)}}}catch(W){l={error:W}}finally{try{p&&!p.done&&(c=d.return)&&c.call(d)}finally{if(l)throw l.error}}},vb=function(){function t(e,r){e===void 0&&(e=new Map),r===void 0&&(r=""),this._size=void 0,this._tree=e,this._prefix=r}return t.prototype.atPrefix=function(e){var r,n;if(!e.startsWith(this._prefix))throw new Error("Mismatched prefix");var i=jt(Nh(this._tree,e.slice(this._prefix.length)),2),o=i[0],s=i[1];if(o===void 0){var a=jt(Ib(s),2),l=a[0],c=a[1];try{for(var u=Oe(l.keys()),d=u.next();!d.done;d=u.next()){var p=d.value;if(p!==pr&&p.startsWith(c)){var f=new Map;return f.set(p.slice(c.length),l.get(p)),new t(f,e)}}}catch(m){r={error:m}}finally{try{d&&!d.done&&(n=u.return)&&n.call(u)}finally{if(r)throw r.error}}}return new t(o,e)},t.prototype.clear=function(){this._size=void 0,this._tree.clear()},t.prototype.delete=function(e){return this._size=void 0,pL(this._tree,e)},t.prototype.entries=function(){return new yb(this,dL)},t.prototype.forEach=function(e){var r,n;try{for(var i=Oe(this),o=i.next();!o.done;o=i.next()){var s=jt(o.value,2),a=s[0],l=s[1];e(a,l,this)}}catch(c){r={error:c}}finally{try{o&&!o.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}},t.prototype.fuzzyGet=function(e,r){return fL(this._tree,e,r)},t.prototype.get=function(e){var r=$b(this._tree,e);return r!==void 0?r.get(pr):void 0},t.prototype.has=function(e){var r=$b(this._tree,e);return r!==void 0&&r.has(pr)},t.prototype.keys=function(){return new yb(this,dP)},t.prototype.set=function(e,r){if(typeof e!="string")throw new Error("key must be a string");this._size=void 0;var n=_b(this._tree,e);return n.set(pr,r),this},Object.defineProperty(t.prototype,"size",{get:function(){if(this._size)return this._size;this._size=0;for(var e=this.entries();!e.next().done;)this._size+=1;return this._size},enumerable:!1,configurable:!0}),t.prototype.update=function(e,r){if(typeof e!="string")throw new Error("key must be a string");this._size=void 0;var n=_b(this._tree,e);return n.set(pr,r(n.get(pr))),this},t.prototype.fetch=function(e,r){if(typeof e!="string")throw new Error("key must be a string");this._size=void 0;var n=_b(this._tree,e),i=n.get(pr);return i===void 0&&n.set(pr,i=r()),i},t.prototype.values=function(){return new yb(this,fP)},t.prototype[Symbol.iterator]=function(){return this.entries()},t.from=function(e){var r,n,i=new t;try{for(var o=Oe(e),s=o.next();!s.done;s=o.next()){var a=jt(s.value,2),l=a[0],c=a[1];i.set(l,c)}}catch(u){r={error:u}}finally{try{s&&!s.done&&(n=o.return)&&n.call(o)}finally{if(r)throw r.error}}return i},t.fromObject=function(e){return t.from(Object.entries(e))},t}(),Nh=function(t,e,r){var n,i;if(r===void 0&&(r=[]),e.length===0||t==null)return[t,r];try{for(var o=Oe(t.keys()),s=o.next();!s.done;s=o.next()){var a=s.value;if(a!==pr&&e.startsWith(a))return r.push([t,a]),Nh(t.get(a),e.slice(a.length),r)}}catch(l){n={error:l}}finally{try{s&&!s.done&&(i=o.return)&&i.call(o)}finally{if(n)throw n.error}}return r.push([t,e]),Nh(void 0,"",r)},$b=function(t,e){var r,n;if(e.length===0||t==null)return t;try{for(var i=Oe(t.keys()),o=i.next();!o.done;o=i.next()){var s=o.value;if(s!==pr&&e.startsWith(s))return $b(t.get(s),e.slice(s.length))}}catch(a){r={error:a}}finally{try{o&&!o.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}},_b=function(t,e){var r,n,i=e.length;e:for(var o=0;t&&o<i;){try{for(var s=(r=void 0,Oe(t.keys())),a=s.next();!a.done;a=s.next()){var l=a.value;if(l!==pr&&e[o]===l[0]){for(var c=Math.min(i-o,l.length),u=1;u<c&&e[o+u]===l[u];)++u;var d=t.get(l);if(u===l.length)t=d;else{var p=new Map;p.set(l.slice(u),d),t.set(e.slice(o,o+u),p),t.delete(l),t=p}o+=u;continue e}}}catch(m){r={error:m}}finally{try{a&&!a.done&&(n=s.return)&&n.call(s)}finally{if(r)throw r.error}}var f=new Map;return t.set(e.slice(o),f),f}return t},pL=function(t,e){var r=jt(Nh(t,e),2),n=r[0],i=r[1];if(n!==void 0){if(n.delete(pr),n.size===0)mP(i);else if(n.size===1){var o=jt(n.entries().next().value,2),s=o[0],a=o[1];hP(i,s,a)}}},mP=function(t){if(t.length!==0){var e=jt(Ib(t),2),r=e[0],n=e[1];if(r.delete(n),r.size===0)mP(t.slice(0,-1));else if(r.size===1){var i=jt(r.entries().next().value,2),o=i[0],s=i[1];o!==pr&&hP(t.slice(0,-1),o,s)}}},hP=function(t,e,r){if(t.length!==0){var n=jt(Ib(t),2),i=n[0],o=n[1];i.set(o+e,r),i.delete(o)}},Ib=function(t){return t[t.length-1]},Zd,Eb="or",gP="and",mL="and_not",yP=function(){function t(e){if(e?.fields==null)throw new Error('MiniSearch: option "fields" must be provided');var r=e.autoVacuum==null||e.autoVacuum===!0?xb:e.autoVacuum;this._options=gt(gt(gt({},wb),e),{autoVacuum:r,searchOptions:gt(gt({},aP),e.searchOptions||{}),autoSuggestOptions:gt(gt({},_L),e.autoSuggestOptions||{})}),this._index=new vb,this._documentCount=0,this._documentIds=new Map,this._idToShortId=new Map,this._fieldIds={},this._fieldLength=new Map,this._avgFieldLength=[],this._nextId=0,this._storedFields=new Map,this._dirtCount=0,this._currentVacuum=null,this._enqueuedVacuum=null,this._enqueuedVacuumConditions=Sb,this.addFields(this._options.fields)}return t.prototype.add=function(e){var r,n,i,o,s,a,l=this._options,c=l.extractField,u=l.tokenize,d=l.processTerm,p=l.fields,f=l.idField,m=c(e,f);if(m==null)throw new Error('MiniSearch: document does not have ID field "'.concat(f,'"'));if(this._idToShortId.has(m))throw new Error("MiniSearch: duplicate ID ".concat(m));var h=this.addDocumentId(m);this.saveStoredFields(h,e);try{for(var y=Oe(p),g=y.next();!g.done;g=y.next()){var _=g.value,b=c(e,_);if(b!=null){var E=u(b.toString(),_),I=this._fieldIds[_],P=new Set(E).size;this.addFieldLength(h,I,this._documentCount-1,P);try{for(var M=(i=void 0,Oe(E)),V=M.next();!V.done;V=M.next()){var R=V.value,L=d(R,_);if(Array.isArray(L))try{for(var G=(s=void 0,Oe(L)),H=G.next();!H.done;H=G.next()){var W=H.value;this.addTerm(I,h,W)}}catch(Y){s={error:Y}}finally{try{H&&!H.done&&(a=G.return)&&a.call(G)}finally{if(s)throw s.error}}else L&&this.addTerm(I,h,L)}}catch(Y){i={error:Y}}finally{try{V&&!V.done&&(o=M.return)&&o.call(M)}finally{if(i)throw i.error}}}}}catch(Y){r={error:Y}}finally{try{g&&!g.done&&(n=y.return)&&n.call(y)}finally{if(r)throw r.error}}},t.prototype.addAll=function(e){var r,n;try{for(var i=Oe(e),o=i.next();!o.done;o=i.next()){var s=o.value;this.add(s)}}catch(a){r={error:a}}finally{try{o&&!o.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}},t.prototype.addAllAsync=function(e,r){var n=this;r===void 0&&(r={});var i=r.chunkSize,o=i===void 0?10:i,s={chunk:[],promise:Promise.resolve()},a=e.reduce(function(u,d,p){var f=u.chunk,m=u.promise;return f.push(d),(p+1)%o===0?{chunk:[],promise:m.then(function(){return new Promise(function(h){return setTimeout(h,0)})}).then(function(){return n.addAll(f)})}:{chunk:f,promise:m}},s),l=a.chunk,c=a.promise;return c.then(function(){return n.addAll(l)})},t.prototype.remove=function(e){var r,n,i,o,s,a,l=this._options,c=l.tokenize,u=l.processTerm,d=l.extractField,p=l.fields,f=l.idField,m=d(e,f);if(m==null)throw new Error('MiniSearch: document does not have ID field "'.concat(f,'"'));var h=this._idToShortId.get(m);if(h==null)throw new Error("MiniSearch: cannot remove document with ID ".concat(m,": it is not in the index"));try{for(var y=Oe(p),g=y.next();!g.done;g=y.next()){var _=g.value,b=d(e,_);if(b!=null){var E=c(b.toString(),_),I=this._fieldIds[_],P=new Set(E).size;this.removeFieldLength(h,I,this._documentCount,P);try{for(var M=(i=void 0,Oe(E)),V=M.next();!V.done;V=M.next()){var R=V.value,L=u(R,_);if(Array.isArray(L))try{for(var G=(s=void 0,Oe(L)),H=G.next();!H.done;H=G.next()){var W=H.value;this.removeTerm(I,h,W)}}catch(Y){s={error:Y}}finally{try{H&&!H.done&&(a=G.return)&&a.call(G)}finally{if(s)throw s.error}}else L&&this.removeTerm(I,h,L)}}catch(Y){i={error:Y}}finally{try{V&&!V.done&&(o=M.return)&&o.call(M)}finally{if(i)throw i.error}}}}}catch(Y){r={error:Y}}finally{try{g&&!g.done&&(n=y.return)&&n.call(y)}finally{if(r)throw r.error}}this._storedFields.delete(h),this._documentIds.delete(h),this._idToShortId.delete(m),this._fieldLength.delete(h),this._documentCount-=1},t.prototype.removeAll=function(e){var r,n;if(e)try{for(var i=Oe(e),o=i.next();!o.done;o=i.next()){var s=o.value;this.remove(s)}}catch(a){r={error:a}}finally{try{o&&!o.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}else{if(arguments.length>0)throw new Error("Expected documents to be present. Omit the argument to remove all documents.");this._index=new vb,this._documentCount=0,this._documentIds=new Map,this._idToShortId=new Map,this._fieldLength=new Map,this._avgFieldLength=[],this._storedFields=new Map,this._nextId=0}},t.prototype.discard=function(e){var r=this,n=this._idToShortId.get(e);if(n==null)throw new Error("MiniSearch: cannot discard document with ID ".concat(e,": it is not in the index"));this._idToShortId.delete(e),this._documentIds.delete(n),this._storedFields.delete(n),(this._fieldLength.get(n)||[]).forEach(function(i,o){r.removeFieldLength(n,o,r._documentCount,i)}),this._fieldLength.delete(n),this._documentCount-=1,this._dirtCount+=1,this.maybeAutoVacuum()},t.prototype.maybeAutoVacuum=function(){if(this._options.autoVacuum!==!1){var e=this._options.autoVacuum,r=e.minDirtFactor,n=e.minDirtCount,i=e.batchSize,o=e.batchWait;this.conditionalVacuum({batchSize:i,batchWait:o},{minDirtCount:n,minDirtFactor:r})}},t.prototype.discardAll=function(e){var r,n,i=this._options.autoVacuum;try{this._options.autoVacuum=!1;try{for(var o=Oe(e),s=o.next();!s.done;s=o.next()){var a=s.value;this.discard(a)}}catch(l){r={error:l}}finally{try{s&&!s.done&&(n=o.return)&&n.call(o)}finally{if(r)throw r.error}}}finally{this._options.autoVacuum=i}this.maybeAutoVacuum()},t.prototype.replace=function(e){var r=this._options,n=r.idField,i=r.extractField,o=i(e,n);this.discard(o),this.add(e)},t.prototype.vacuum=function(e){return e===void 0&&(e={}),this.conditionalVacuum(e)},t.prototype.conditionalVacuum=function(e,r){var n=this;return this._currentVacuum?(this._enqueuedVacuumConditions=this._enqueuedVacuumConditions&&r,this._enqueuedVacuum!=null?this._enqueuedVacuum:(this._enqueuedVacuum=this._currentVacuum.then(function(){var i=n._enqueuedVacuumConditions;return n._enqueuedVacuumConditions=Sb,n.performVacuuming(e,i)}),this._enqueuedVacuum)):this.vacuumConditionsMet(r)===!1?Promise.resolve():(this._currentVacuum=this.performVacuuming(e),this._currentVacuum)},t.prototype.performVacuuming=function(e,r){return cL(this,void 0,void 0,function(){var n,i,o,s,a,l,c,u,d,p,f,m,h,y,g,_,b,E,I,P,M,V,R,L,G;return uL(this,function(H){switch(H.label){case 0:if(n=this._dirtCount,!this.vacuumConditionsMet(r))return[3,10];i=e.batchSize||kb.batchSize,o=e.batchWait||kb.batchWait,s=1,H.label=1;case 1:H.trys.push([1,7,8,9]),a=Oe(this._index),l=a.next(),H.label=2;case 2:if(l.done)return[3,6];c=jt(l.value,2),u=c[0],d=c[1];try{for(p=(V=void 0,Oe(d)),f=p.next();!f.done;f=p.next()){m=jt(f.value,2),h=m[0],y=m[1];try{for(g=(L=void 0,Oe(y)),_=g.next();!_.done;_=g.next())b=jt(_.value,1),E=b[0],!this._documentIds.has(E)&&(y.size<=1?d.delete(h):y.delete(E))}catch(W){L={error:W}}finally{try{_&&!_.done&&(G=g.return)&&G.call(g)}finally{if(L)throw L.error}}}}catch(W){V={error:W}}finally{try{f&&!f.done&&(R=p.return)&&R.call(p)}finally{if(V)throw V.error}}return this._index.get(u).size===0&&this._index.delete(u),s%i!==0?[3,4]:[4,new Promise(function(W){return setTimeout(W,o)})];case 3:H.sent(),H.label=4;case 4:s+=1,H.label=5;case 5:return l=a.next(),[3,2];case 6:return[3,9];case 7:return I=H.sent(),P={error:I},[3,9];case 8:try{l&&!l.done&&(M=a.return)&&M.call(a)}finally{if(P)throw P.error}return[7];case 9:this._dirtCount-=n,H.label=10;case 10:return[4,null];case 11:return H.sent(),this._currentVacuum=this._enqueuedVacuum,this._enqueuedVacuum=null,[2]}})})},t.prototype.vacuumConditionsMet=function(e){if(e==null)return!0;var r=e.minDirtCount,n=e.minDirtFactor;return r=r||xb.minDirtCount,n=n||xb.minDirtFactor,this.dirtCount>=r&&this.dirtFactor>=n},Object.defineProperty(t.prototype,"isVacuuming",{get:function(){return this._currentVacuum!=null},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"dirtCount",{get:function(){return this._dirtCount},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"dirtFactor",{get:function(){return this._dirtCount/(1+this._documentCount+this._dirtCount)},enumerable:!1,configurable:!0}),t.prototype.has=function(e){return this._idToShortId.has(e)},t.prototype.getStoredFields=function(e){var r=this._idToShortId.get(e);if(r!=null)return this._storedFields.get(r)},t.prototype.search=function(e,r){var n,i;r===void 0&&(r={});var o=this.executeQuery(e,r),s=[];try{for(var a=Oe(o),l=a.next();!l.done;l=a.next()){var c=jt(l.value,2),u=c[0],d=c[1],p=d.score,f=d.terms,m=d.match,h=f.length||1,y={id:this._documentIds.get(u),score:p*h,terms:Object.keys(m),queryTerms:f,match:m};Object.assign(y,this._storedFields.get(u)),(r.filter==null||r.filter(y))&&s.push(y)}}catch(g){n={error:g}}finally{try{l&&!l.done&&(i=a.return)&&i.call(a)}finally{if(n)throw n.error}}return e===t.wildcard&&r.boostDocument==null&&this._options.searchOptions.boostDocument==null||s.sort(cP),s},t.prototype.autoSuggest=function(e,r){var n,i,o,s;r===void 0&&(r={}),r=gt(gt({},this._options.autoSuggestOptions),r);var a=new Map;try{for(var l=Oe(this.search(e,r)),c=l.next();!c.done;c=l.next()){var u=c.value,d=u.score,p=u.terms,f=p.join(" "),m=a.get(f);m!=null?(m.score+=d,m.count+=1):a.set(f,{score:d,terms:p,count:1})}}catch(I){n={error:I}}finally{try{c&&!c.done&&(i=l.return)&&i.call(l)}finally{if(n)throw n.error}}var h=[];try{for(var y=Oe(a),g=y.next();!g.done;g=y.next()){var _=jt(g.value,2),m=_[0],b=_[1],d=b.score,p=b.terms,E=b.count;h.push({suggestion:m,terms:p,score:d/E})}}catch(I){o={error:I}}finally{try{g&&!g.done&&(s=y.return)&&s.call(y)}finally{if(o)throw o.error}}return h.sort(cP),h},Object.defineProperty(t.prototype,"documentCount",{get:function(){return this._documentCount},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"termCount",{get:function(){return this._index.size},enumerable:!1,configurable:!0}),t.loadJSON=function(e,r){if(r==null)throw new Error("MiniSearch: loadJSON should be given the same options used when serializing the index");return this.loadJS(JSON.parse(e),r)},t.getDefault=function(e){if(wb.hasOwnProperty(e))return bb(wb,e);throw new Error('MiniSearch: unknown option "'.concat(e,'"'))},t.loadJS=function(e,r){var n,i,o,s,a,l,c=e.index,u=e.documentCount,d=e.nextId,p=e.documentIds,f=e.fieldIds,m=e.fieldLength,h=e.averageFieldLength,y=e.storedFields,g=e.dirtCount,_=e.serializationVersion;if(_!==1&&_!==2)throw new Error("MiniSearch: cannot deserialize an index created with an incompatible version");var b=new t(r);b._documentCount=u,b._nextId=d,b._documentIds=Ch(p),b._idToShortId=new Map,b._fieldIds=f,b._fieldLength=Ch(m),b._avgFieldLength=h,b._storedFields=Ch(y),b._dirtCount=g||0,b._index=new vb;try{for(var E=Oe(b._documentIds),I=E.next();!I.done;I=E.next()){var P=jt(I.value,2),M=P[0],V=P[1];b._idToShortId.set(V,M)}}catch(Pt){n={error:Pt}}finally{try{I&&!I.done&&(i=E.return)&&i.call(E)}finally{if(n)throw n.error}}try{for(var R=Oe(c),L=R.next();!L.done;L=R.next()){var G=jt(L.value,2),H=G[0],W=G[1],Y=new Map;try{for(var ie=(a=void 0,Oe(Object.keys(W))),Ve=ie.next();!Ve.done;Ve=ie.next()){var it=Ve.value,Ot=W[it];_===1&&(Ot=Ot.ds),Y.set(parseInt(it,10),Ch(Ot))}}catch(Pt){a={error:Pt}}finally{try{Ve&&!Ve.done&&(l=ie.return)&&l.call(ie)}finally{if(a)throw a.error}}b._index.set(H,Y)}}catch(Pt){o={error:Pt}}finally{try{L&&!L.done&&(s=R.return)&&s.call(R)}finally{if(o)throw o.error}}return b},t.prototype.executeQuery=function(e,r){var n=this;if(r===void 0&&(r={}),e===t.wildcard)return this.executeWildcardQuery(r);if(typeof e!="string"){var i=gt(gt(gt({},r),e),{queries:void 0}),o=e.queries.map(function(y){return n.executeQuery(y,i)});return this.combineResults(o,i.combineWith)}var s=this._options,a=s.tokenize,l=s.processTerm,c=s.searchOptions,u=gt(gt({tokenize:a,processTerm:l},c),r),d=u.tokenize,p=u.processTerm,f=d(e).flatMap(function(y){return p(y)}).filter(function(y){return!!y}),m=f.map(vL(u)),h=m.map(function(y){return n.executeQuerySpec(y,u)});return this.combineResults(h,u.combineWith)},t.prototype.executeQuerySpec=function(e,r){var n,i,o,s,a=gt(gt({},this._options.searchOptions),r),l=(a.fields||this._options.fields).reduce(function(it,Ot){var Pt;return gt(gt({},it),(Pt={},Pt[Ot]=bb(a.boost,Ot)||1,Pt))},{}),c=a.boostDocument,u=a.weights,d=a.maxFuzzy,p=a.bm25,f=gt(gt({},aP.weights),u),m=f.fuzzy,h=f.prefix,y=this._index.get(e.term),g=this.termResults(e.term,e.term,1,y,l,c,p),_,b;if(e.prefix&&(_=this._index.atPrefix(e.term)),e.fuzzy){var E=e.fuzzy===!0?.2:e.fuzzy,I=E<1?Math.min(d,Math.round(e.term.length*E)):E;I&&(b=this._index.fuzzyGet(e.term,I))}if(_)try{for(var P=Oe(_),M=P.next();!M.done;M=P.next()){var V=jt(M.value,2),R=V[0],L=V[1],G=R.length-e.term.length;if(G){b?.delete(R);var H=h*R.length/(R.length+.3*G);this.termResults(e.term,R,H,L,l,c,p,g)}}}catch(it){n={error:it}}finally{try{M&&!M.done&&(i=P.return)&&i.call(P)}finally{if(n)throw n.error}}if(b)try{for(var W=Oe(b.keys()),Y=W.next();!Y.done;Y=W.next()){var R=Y.value,ie=jt(b.get(R),2),Ve=ie[0],G=ie[1];if(G){var H=m*R.length/(R.length+G);this.termResults(e.term,R,H,Ve,l,c,p,g)}}}catch(it){o={error:it}}finally{try{Y&&!Y.done&&(s=W.return)&&s.call(W)}finally{if(o)throw o.error}}return g},t.prototype.executeWildcardQuery=function(e){var r,n,i=new Map,o=gt(gt({},this._options.searchOptions),e);try{for(var s=Oe(this._documentIds),a=s.next();!a.done;a=s.next()){var l=jt(a.value,2),c=l[0],u=l[1],d=o.boostDocument?o.boostDocument(u,"",this._storedFields.get(c)):1;i.set(c,{score:d,terms:[],match:{}})}}catch(p){r={error:p}}finally{try{a&&!a.done&&(n=s.return)&&n.call(s)}finally{if(r)throw r.error}}return i},t.prototype.combineResults=function(e,r){if(r===void 0&&(r=Eb),e.length===0)return new Map;var n=r.toLowerCase();return e.reduce(hL[n])||new Map},t.prototype.toJSON=function(){var e,r,n,i,o=[];try{for(var s=Oe(this._index),a=s.next();!a.done;a=s.next()){var l=jt(a.value,2),c=l[0],u=l[1],d={};try{for(var p=(n=void 0,Oe(u)),f=p.next();!f.done;f=p.next()){var m=jt(f.value,2),h=m[0],y=m[1];d[h]=Object.fromEntries(y)}}catch(g){n={error:g}}finally{try{f&&!f.done&&(i=p.return)&&i.call(p)}finally{if(n)throw n.error}}o.push([c,d])}}catch(g){e={error:g}}finally{try{a&&!a.done&&(r=s.return)&&r.call(s)}finally{if(e)throw e.error}}return{documentCount:this._documentCount,nextId:this._nextId,documentIds:Object.fromEntries(this._documentIds),fieldIds:this._fieldIds,fieldLength:Object.fromEntries(this._fieldLength),averageFieldLength:this._avgFieldLength,storedFields:Object.fromEntries(this._storedFields),dirtCount:this._dirtCount,index:o,serializationVersion:2}},t.prototype.termResults=function(e,r,n,i,o,s,a,l){var c,u,d,p,f;if(l===void 0&&(l=new Map),i==null)return l;try{for(var m=Oe(Object.keys(o)),h=m.next();!h.done;h=m.next()){var y=h.value,g=o[y],_=this._fieldIds[y],b=i.get(_);if(b!=null){var E=b.size,I=this._avgFieldLength[_];try{for(var P=(d=void 0,Oe(b.keys())),M=P.next();!M.done;M=P.next()){var V=M.value;if(!this._documentIds.has(V)){this.removeTerm(_,V,r),E-=1;continue}var R=s?s(this._documentIds.get(V),r,this._storedFields.get(V)):1;if(R){var L=b.get(V),G=this._fieldLength.get(V)[_],H=yL(L,E,this._documentCount,G,I,a),W=n*g*R*H,Y=l.get(V);if(Y){Y.score+=W,bL(Y.terms,e);var ie=bb(Y.match,r);ie?ie.push(y):Y.match[r]=[y]}else l.set(V,{score:W,terms:[e],match:(f={},f[r]=[y],f)})}}}catch(Ve){d={error:Ve}}finally{try{M&&!M.done&&(p=P.return)&&p.call(P)}finally{if(d)throw d.error}}}}}catch(Ve){c={error:Ve}}finally{try{h&&!h.done&&(u=m.return)&&u.call(m)}finally{if(c)throw c.error}}return l},t.prototype.addTerm=function(e,r,n){var i=this._index.fetch(n,uP),o=i.get(e);if(o==null)o=new Map,o.set(r,1),i.set(e,o);else{var s=o.get(r);o.set(r,(s||0)+1)}},t.prototype.removeTerm=function(e,r,n){if(!this._index.has(n)){this.warnDocumentChanged(r,e,n);return}var i=this._index.fetch(n,uP),o=i.get(e);o==null||o.get(r)==null?this.warnDocumentChanged(r,e,n):o.get(r)<=1?o.size<=1?i.delete(e):o.delete(r):o.set(r,o.get(r)-1),this._index.get(n).size===0&&this._index.delete(n)},t.prototype.warnDocumentChanged=function(e,r,n){var i,o;try{for(var s=Oe(Object.keys(this._fieldIds)),a=s.next();!a.done;a=s.next()){var l=a.value;if(this._fieldIds[l]===r){this._options.logger("warn","MiniSearch: document with ID ".concat(this._documentIds.get(e),' has changed before removal: term "').concat(n,'" was not present in field "').concat(l,'". Removing a document after it has changed can corrupt the index!'),"version_conflict");return}}}catch(c){i={error:c}}finally{try{a&&!a.done&&(o=s.return)&&o.call(s)}finally{if(i)throw i.error}}},t.prototype.addDocumentId=function(e){var r=this._nextId;return this._idToShortId.set(e,r),this._documentIds.set(r,e),this._documentCount+=1,this._nextId+=1,r},t.prototype.addFields=function(e){for(var r=0;r<e.length;r++)this._fieldIds[e[r]]=r},t.prototype.addFieldLength=function(e,r,n,i){var o=this._fieldLength.get(e);o==null&&this._fieldLength.set(e,o=[]),o[r]=i;var s=this._avgFieldLength[r]||0,a=s*n+i;this._avgFieldLength[r]=a/(n+1)},t.prototype.removeFieldLength=function(e,r,n,i){if(n===1){this._avgFieldLength[r]=0;return}var o=this._avgFieldLength[r]*n-i;this._avgFieldLength[r]=o/(n-1)},t.prototype.saveStoredFields=function(e,r){var n,i,o=this._options,s=o.storeFields,a=o.extractField;if(!(s==null||s.length===0)){var l=this._storedFields.get(e);l==null&&this._storedFields.set(e,l={});try{for(var c=Oe(s),u=c.next();!u.done;u=c.next()){var d=u.value,p=a(r,d);p!==void 0&&(l[d]=p)}}catch(f){n={error:f}}finally{try{u&&!u.done&&(i=c.return)&&i.call(c)}finally{if(n)throw n.error}}}},t.wildcard=Symbol("*"),t}(),bb=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0},hL=(Zd={},Zd[Eb]=function(t,e){var r,n;try{for(var i=Oe(e.keys()),o=i.next();!o.done;o=i.next()){var s=o.value,a=t.get(s);if(a==null)t.set(s,e.get(s));else{var l=e.get(s),c=l.score,u=l.terms,d=l.match;a.score=a.score+c,a.match=Object.assign(a.match,d),lP(a.terms,u)}}}catch(p){r={error:p}}finally{try{o&&!o.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}return t},Zd[gP]=function(t,e){var r,n,i=new Map;try{for(var o=Oe(e.keys()),s=o.next();!s.done;s=o.next()){var a=s.value,l=t.get(a);if(l!=null){var c=e.get(a),u=c.score,d=c.terms,p=c.match;lP(l.terms,d),i.set(a,{score:l.score+u,terms:l.terms,match:Object.assign(l.match,p)})}}}catch(f){r={error:f}}finally{try{s&&!s.done&&(n=o.return)&&n.call(o)}finally{if(r)throw r.error}}return i},Zd[mL]=function(t,e){var r,n;try{for(var i=Oe(e.keys()),o=i.next();!o.done;o=i.next()){var s=o.value;t.delete(s)}}catch(a){r={error:a}}finally{try{o&&!o.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}return t},Zd),gL={k:1.2,b:.7,d:.5},yL=function(t,e,r,n,i,o){var s=o.k,a=o.b,l=o.d,c=Math.log(1+(r-e+.5)/(e+.5));return c*(l+t*(s+1)/(t+s*(1-a+a*n/i)))},vL=function(t){return function(e,r,n){var i=typeof t.fuzzy=="function"?t.fuzzy(e,r,n):t.fuzzy||!1,o=typeof t.prefix=="function"?t.prefix(e,r,n):t.prefix===!0;return{term:e,fuzzy:i,prefix:o}}},wb={idField:"id",extractField:function(t,e){return t[e]},tokenize:function(t){return t.split(wL)},processTerm:function(t){return t.toLowerCase()},fields:void 0,searchOptions:void 0,storeFields:[],logger:function(t,e){typeof console?.[t]=="function"&&console[t](e)},autoVacuum:!0},aP={combineWith:Eb,prefix:!1,fuzzy:!1,maxFuzzy:6,boost:{},weights:{fuzzy:.45,prefix:.375},bm25:gL},_L={combineWith:gP,prefix:function(t,e,r){return e===r.length-1}},kb={batchSize:1e3,batchWait:10},Sb={minDirtFactor:.1,minDirtCount:20},xb=gt(gt({},kb),Sb),bL=function(t,e){t.includes(e)||t.push(e)},lP=function(t,e){var r,n;try{for(var i=Oe(e),o=i.next();!o.done;o=i.next()){var s=o.value;t.includes(s)||t.push(s)}}catch(a){r={error:a}}finally{try{o&&!o.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}},cP=function(t,e){var r=t.score,n=e.score;return n-r},uP=function(){return new Map},Ch=function(t){var e,r,n=new Map;try{for(var i=Oe(Object.keys(t)),o=i.next();!o.done;o=i.next()){var s=o.value;n.set(parseInt(s,10),t[s])}}catch(a){e={error:a}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(e)throw e.error}}return n},wL=/[\n\r -#%-*,-/:;?@[-\]_{}\u00A0\u00A1\u00A7\u00AB\u00B6\u00B7\u00BB\u00BF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061E\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u09FD\u0A76\u0AF0\u0C77\u0C84\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166E\u1680\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2000-\u200A\u2010-\u2029\u202F-\u2043\u2045-\u2051\u2053-\u205F\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E4F\u3000-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]+/u;var vP=t=>[{id:"search",type:"action",name:"Search the knowledge base.",content:"Search the knowledge base for information, actions, tools, tours, UI elements, etc. Use this on EVERY request if you don't have information. If the user asks for personal information, use this. If the user asks you to do something, use this to find the tool you need.",isContext:!0,hideActionInUI:"after-complete",parameters:[{name:"query",type:"string",description:"The search query"}],action:async(e,r)=>{let n=await r.knowledgeBase.search(e.query),i=r;i._lastKBsearch=e.query,i._nextRequestUseKBitems=n;let o=n.filter(a=>a.type!="action").map(a=>"- "+a.name).join(`
|
|
66
|
+
`)||"- (none)",s=n.filter(a=>a.type=="action").map(a=>"- "+a._functionID).join(`
|
|
10
67
|
`)||"- (none)";return`Search complete, context has been updated.
|
|
11
68
|
New information found:
|
|
12
|
-
${
|
|
69
|
+
${o}
|
|
13
70
|
|
|
14
71
|
New tools available:
|
|
15
|
-
${n}`}},{id:"ui.openURL",type:"action",name:"Open a URL in a new tab.",tags:"open, url, website, navigate, visit, go to, new tab, browser",isContext:!0,disabled:typeof window>"u"||!u?.flags?.allowOpenNewTab,content:"Opens the specified URL in a new tab. Use this when the user asks to open a website, visit a URL, go to a page, or navigate to a specific website. Only available when allowOpenNewTab flag is enabled.",parameters:[{name:"url",type:"string",description:"The URL to open in a new tab"}],action:(t,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowOpenNewTab)throw new Error("Open New Tab action is not enabled for this persona.");if(!t.url||typeof t.url!="string")throw new Error("URL parameter is required and must be a string.");if(!window.open(t.url,"_blank"))throw new Error("Window blocked by popup blocker. Please allow popups for this site.");return`Opened URL: ${t.url}`}},{id:"ui.changeRoute",type:"action",name:"Change the current page route.",tags:"navigate, route, path, page, go to, change page, routing, navigation",isContext:!0,disabled:typeof window>"u"||!u?.flags?.allowChangeRoute,content:"Changes the current page route to the specified path. Use this when the user asks to navigate to a different page, go to a specific section, or change the current page route. Only available when allowChangeRoute flag is enabled.",parameters:[{name:"path",type:"string",description:'The path to navigate to (e.g., "/home", "/dashboard")'}],action:(t,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowChangeRoute)throw new Error("Change Route action is not enabled for this persona.");if(!t.path||typeof t.path!="string")throw new Error("Path parameter is required and must be a string.");let i=new URL(t.path,window.location.origin).pathname;return window.location.href=i,`Changed route to: ${i}`}},{id:"ui.sendEmail",type:"action",name:"Send an email",tags:"email, send, mail, compose, message, contact, mailto",isContext:!0,disabled:typeof window>"u"||!u?.flags?.allowSendEmail,content:"Sends an email using the user's default mail client by opening a mailto: link. Use this when the user asks to send an email, compose a message, or contact someone via email. Only available when allowSendEmail flag is enabled.",parameters:[{name:"email_address",type:"string",description:"The recipient email address"},{name:"subject",type:"string",description:"The email subject line"},{name:"body",type:"string",description:"The email body content"}],action:(t,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowSendEmail)throw new Error("Send Email action is not enabled for this persona.");if(!t.email_address||typeof t.email_address!="string")throw new Error("Email address parameter is required and must be a string.");if(!t.subject||typeof t.subject!="string")throw new Error("Subject parameter is required and must be a string.");if(!t.body||typeof t.body!="string")throw new Error("Body parameter is required and must be a string.");let i=encodeURIComponent(t.email_address),o=encodeURIComponent(t.subject),s=encodeURIComponent(t.body),n=`mailto:${i}?subject=${o}&body=${s}`;try{window.location.href=n}catch(a){throw new Error(`Failed to open email client: ${a instanceof Error?a.message:String(a)}`)}return`Email opened in default mail client. Recipient: ${t.email_address}, Subject: ${t.subject}`}}];import{Client as De}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as at}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{SSEClientTransport as rt}from"@modelcontextprotocol/sdk/client/sse.js";var I={name:"@intelliweave/embedded",version:"2.0.72-beta.6",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && vitest run","test:local":"IW_API_URL=http://localhost:3000/api npm run test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.64","@types/lodash":"^4.17.13","@types/react":"^18.3.12","@types/uuid":"^10.0.0",bestzip:"^2.2.1","cross-env":"^7.0.3","find-cache-dir":"^5.0.0",lodash:"^4.17.21","onnxruntime-web":"^1.20.0",react:"^18.3.1","replace-in-file":"^8.2.0",tsup:"^8.3.5",tsx:"^4.19.2",typedoc:"^0.27.6",vitest:"^3.2.4"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.60.0","@modelcontextprotocol/sdk":"^1.24.1","@types/json-schema":"^7.0.15",minisearch:"^6.3.0",openai:"^6.10.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.0","rehype-stringify":"^10.0.0","remark-parse":"^11.0.0","remark-rehype":"^11.1.0",unified:"^11.0.4","utility-types":"^3.11.0",uuid:"^10.0.0"}};import{LoggingMessageNotificationSchema as lt,ToolListChangedNotificationSchema as ct}from"@modelcontextprotocol/sdk/types.js";var f=new p("MCPKnowledgeClient"),te=class{constructor(t){this.tools=[];this.iwActions=[];this.stats={toolsCalled:0};this.lastSearchQuery="";this.lastSearchResults=[];this.config=t}async connect(){return this.client?this.client:this.connectionPromise?await this.connectionPromise:(this.connectionPromise=this.connectInternal(),this.connectionPromise.finally(()=>{this.connectionPromise=void 0}),await this.connectionPromise)}async connectInternal(){f.debug("Connecting to MCP client");let t=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let e=new De({name:I.name,version:I.version}),i=new at(new URL(this.config.baseURL));return await e.connect(i),f.debug("Connected with HTTP streaming mode"),e}).catch(async e=>{let i=new De({name:I.name,version:I.version}),o=new rt(new URL(this.config.baseURL));return await i.connect(o),f.debug("Connected with SSE mode"),i});return await this.disconnect(),this.client=t,t.onerror=e=>{f.error(`MCP client error: ${e.message}`)},t.onclose=()=>{f.debug("MCP client connection closed"),this.client=void 0},t.setNotificationHandler(lt,e=>{e.params.level=="critical"?f.error(`[Server] ${e.params.data}`):e.params.level=="emergency"?f.error(`[Server] ${e.params.data}`):e.params.level=="error"?f.error(`[Server] ${e.params.data}`):e.params.level=="warning"?f.warn(`[Server] ${e.params.data}`):e.params.level=="info"?f.info(`[Server] ${e.params.data}`):e.params.level=="debug"?f.debug(`[Server] ${e.params.data}`):f.log(`[Server] ${e.params.data}`)}),t.setNotificationHandler(ct,e=>{f.debug("Tool list changed",e),this.fetchTools()}),f.debug("Fetching tools from MCP server..."),await this.fetchTools(),t}async disconnect(){await this.client?.close(),this.client=void 0,this.tools=[],this.iwActions=[]}async fetchTools(){let t=[],e;for(;;){let o=await this.client.listTools({cursor:e});e=o.nextCursor;for(let s of o.tools||[])t.push(s);if(!o?.tools?.length||!e)break}let i=[];for(let o of t){let s=!!(this.config.searchToolName&&o.name==this.config.searchToolName&&!this.config.searchToolVisible);i.push({id:o.name,name:o.name,content:o.description||"",type:"action",isContext:!0,parameters:o.inputSchema,action:n=>this.performToolCall(o.name,n),disabled:s})}f.debug(`Fetched ${t.length} tools from MCP server.`),this.tools=t,this.iwActions=i}async search(t){if(t==this.lastSearchQuery)return this.lastSearchResults;await this.connect();let e=this.iwActions.slice(),i=await this.performSearchCall(t);return e=e.concat(i),this.lastSearchQuery=t,this.lastSearchResults=e,f.debug(`Search completed, found ${e.length} items.`),e}async performSearchCall(t){let e=[];if(!this.config.searchToolName)return e;let i=this.tools.find(s=>s.name==this.config.searchToolName);if(!i)return f.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),e;let o;if(i.inputSchema.required?.length==1){let s=i.inputSchema.required[0];o=await this.performToolCall(this.config.searchToolName,{[s]:t})}else if(i.inputSchema.properties&&Object.keys(i.inputSchema.properties).length==1){let s=Object.keys(i.inputSchema.properties)[0];o=await this.performToolCall(this.config.searchToolName,{[s]:t})}else o=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(o))for(let s=0;s<o.length;s++){let n=o[s];e.push({id:this.config.id+":"+this.config.searchToolName+":"+s,name:`Search result ${s+1} in ${this.config.searchToolName}`,type:"info",content:typeof n=="string"?n:JSON.stringify(n)})}else e.push({id:this.config.id+":"+this.config.searchToolName+":result",name:`Search result in ${this.config.searchToolName}`,type:"info",content:typeof o=="string"?o:JSON.stringify(o)});return e}async performToolCall(t,e){await this.connect(),f.debug(`Performing tool call for ${t} with params:`,e),this.stats.toolsCalled+=1;let i=await this.client.callTool({name:t,arguments:e});if(i.isError){let o=i.content?.[0]?.text||"Unknown error";throw f.error(`Error calling tool ${t}: ${o}`),new Error(`Error calling tool ${t}: ${o}`)}if(Array.isArray(i.content)&&i.content.length==1&&i.content[0].type=="text")try{return JSON.parse(i.content[0].text)}catch{}return i.content||[]}};import{v4 as dt}from"uuid";var ut=new p("Statistics"),O=[];async function y(u,t){let e={...t,event_id:dt(),event_date:new Date().toISOString(),sdk_version:I.version,conversation_id:u?.conversationID||"",api_key:u?.apiKey||"",user_id:u?.userID||""};if(O.push(e),!u||(await new Promise(o=>setTimeout(o,5e3)),O.length===0))return;let i=O.slice();O.length=0;try{let o=await fetch(u.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:i})});if(!o.ok)throw new Error(`Analytics submission failed: ${o.status} ${o.statusText}`)}catch(o){ut.warn("Failed to submit analytics event:",o),O.push(...i);return}}var N=new p("KnowledgeBase"),Te=1,ie=class u{constructor(t){this._sources=[];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.allowWindowSources=!0;this.allowGlobalConfigSources=!0;this.ai=t,this.ensureInternalKnowledge()}ensureInternalKnowledge(){this._sources=this._sources.filter(t=>t.id!=="core.internal"),this._sources.push({id:"core.internal",query:async()=>We(this.ai)})}reset(){this._windowSources=[],this.manualEntries=[],this.lastResults=[],this._sources=[],this.ensureInternalKnowledge()}registerSource(t,e){let i=t;return typeof t=="function"&&(e=t,i=`source.${Te++}`),this._sources.push({id:i,query:e}),i}removeSource(t){this._sources=this.sources.filter(e=>e.id!==t&&e.query!==t)}addEntry(t){this.manualEntries.push(t)}removeEntry(t){this.manualEntries=this.manualEntries.filter(e=>e.id!==t)}get sources(){let t=this._sources;return this.allowGlobalConfigSources&&m().knowledgeBaseSources&&(t=t.concat(m().knowledgeBaseSources)),this.allowWindowSources&&typeof document<"u"&&(t=t.concat(this._windowSources)),t=t.filter(e=>!e.disabled),t}async search(t){N.debug(`Searching knowledge base for: ${t}`);let e=Date.now(),i=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});i.query=t,i.entries=[],i.sources=[],this.allowWindowSources&&typeof document<"u"?(document.dispatchEvent(i),this._windowSources=i.sources):this._windowSources=[];let s=(await Promise.all(this.sources.map(async c=>{try{let r=Date.now(),d=await c.query(t);return N.debug(`Source '${c.id}' took ${Date.now()-r}ms`),d||[]}catch(r){return N.warn(`Knowledge source '${c.id}' failed:`,r),[]}}))).flat();s=s.concat(i.entries),s=s.concat(this.manualEntries),this.allowGlobalConfigSources&&m().knowledgeBase&&(s=s.concat(m().knowledgeBase)),s=s.filter(c=>c&&!c.disabled);for(let c=0;c<s.length;c++){let r=s[c];r.id=r.id||`temp.${c}`,r._functionID=r.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")}let n=new pt({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});n.addAll(s);let l=n.search(t).map(c=>s.find(r=>r.id==c.id));for(let c of s)c.isContext&&(l.find(r=>r.id===c.id)||l.push(c));return this.lastResults=l,y(this.ai,{event_type:"kb_search",value:l.length,value_str:"",event_properties:{search_time_ms:Date.now()-e,sources_searched:this.sources.length}}),N.debug("Found results:",l),l}getCachedEntry(t){return this.lastResults.find(e=>e.id==t||e._functionID==t)}registerSourceFromURL(t,e){e||(e=`external.${Te++}`),N.debug(`Registering remote knowledge base source: ${t}`);let i=[],o=[],s=!0,n=async(l,c)=>{N.debug(`Calling remote knowledge base action: ${l.id}`);let r={type:"action",userID:this.ai.userID,actionID:l.id,parameters:c},d=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!d.ok)throw new Error(`HTTP Error ${d.status} ${d.statusText}`);let h=await d.json();return a(h.updateItems||[]),h.response},a=l=>{for(let c of l){if(!c.id){N.warn("KB item skipped since it has no ID.",c);continue}let r=i.find(d=>d.id==c.id);if(r){r.name=c.name||r.name||"",r.content=c.content||r.content||"",r.disabled=c.disabled??r.disabled,r.isContext=c.isContext??r.isContext,r.parameters=c.parameters||r.parameters||[],r.tags=c.tags||r.tags,r.type=c.type||r.type;continue}i.push({...c,action:d=>n(c,d)})}};this.registerSource(e,async l=>{if(s&&o.includes(l))return i;let c={type:"search",userID:this.ai?.userID||"",query:l},r=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!r.ok)throw new Error(`HTTP Error ${r.status} ${r.statusText}`);let d=await r.json();return s=!d.noCache,o.includes(l)||o.push(l),a(d.items),i})}clone(){let t=new u(this.ai);return t._sources=this._sources,t._windowSources=this._windowSources,t.manualEntries=this.manualEntries,t.ensureInternalKnowledge(),t}registerMCPSource(t){t.id||(t.id=`external.${Te++}`);let e=new te(t);return this.registerSource(t.id,i=>e.search(i)),e}};var oe=class{constructor(t){this.ai=t}async boolean(t){let e=await this.instruct({...t,instruction:`${t.instruction}
|
|
16
|
-
|
|
17
|
-
|
|
72
|
+
${s}`}},{id:"ui.openURL",type:"action",name:"Open a URL in a new tab.",tags:"open, url, website, navigate, visit, go to, new tab, browser",isContext:!0,disabled:typeof window>"u"||!t?.flags?.allowOpenNewTab,content:"Opens the specified URL in a new tab. Use this when the user asks to open a website, visit a URL, go to a page, or navigate to a specific website. Only available when allowOpenNewTab flag is enabled.",parameters:[{name:"url",type:"string",description:"The URL to open in a new tab"}],action:(e,r)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!r.flags.allowOpenNewTab)throw new Error("Open New Tab action is not enabled for this persona.");if(!e.url||typeof e.url!="string")throw new Error("URL parameter is required and must be a string.");if(!window.open(e.url,"_blank"))throw new Error("Window blocked by popup blocker. Please allow popups for this site.");return`Opened URL: ${e.url}`}},{id:"ui.changeRoute",type:"action",name:"Change the current page route.",tags:"navigate, route, path, page, go to, change page, routing, navigation",isContext:!0,disabled:typeof window>"u"||!t?.flags?.allowChangeRoute,content:"Changes the current page route to the specified path. Use this when the user asks to navigate to a different page, go to a specific section, or change the current page route. Only available when allowChangeRoute flag is enabled.",parameters:[{name:"path",type:"string",description:'The path to navigate to (e.g., "/home", "/dashboard")'}],action:(e,r)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!r.flags.allowChangeRoute)throw new Error("Change Route action is not enabled for this persona.");if(!e.path||typeof e.path!="string")throw new Error("Path parameter is required and must be a string.");let n=new URL(e.path,window.location.origin).pathname;return window.location.href=n,`Changed route to: ${n}`}},{id:"ui.sendEmail",type:"action",name:"Send an email",tags:"email, send, mail, compose, message, contact, mailto",isContext:!0,disabled:typeof window>"u"||!t?.flags?.allowSendEmail,content:"Sends an email using the user's default mail client by opening a mailto: link. Use this when the user asks to send an email, compose a message, or contact someone via email. Only available when allowSendEmail flag is enabled.",parameters:[{name:"email_address",type:"string",description:"The recipient email address"},{name:"subject",type:"string",description:"The email subject line"},{name:"body",type:"string",description:"The email body content"}],action:(e,r)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!r.flags.allowSendEmail)throw new Error("Send Email action is not enabled for this persona.");if(!e.email_address||typeof e.email_address!="string")throw new Error("Email address parameter is required and must be a string.");if(!e.subject||typeof e.subject!="string")throw new Error("Subject parameter is required and must be a string.");if(!e.body||typeof e.body!="string")throw new Error("Body parameter is required and must be a string.");let n=encodeURIComponent(e.email_address),i=encodeURIComponent(e.subject),o=encodeURIComponent(e.body),s=`mailto:${n}?subject=${i}&body=${o}`;try{window.location.href=s}catch(a){throw new Error(`Failed to open email client: ${a instanceof Error?a.message:String(a)}`)}return`Email opened in default mail client. Recipient: ${e.email_address}, Subject: ${e.subject}`}}];var qe;(function(t){t.assertEqual=i=>{};function e(i){}t.assertIs=e;function r(i){throw new Error}t.assertNever=r,t.arrayToEnum=i=>{let o={};for(let s of i)o[s]=s;return o},t.getValidEnumValues=i=>{let o=t.objectKeys(i).filter(a=>typeof i[i[a]]!="number"),s={};for(let a of o)s[a]=i[a];return t.objectValues(s)},t.objectValues=i=>t.objectKeys(i).map(function(o){return i[o]}),t.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},t.find=(i,o)=>{for(let s of i)if(o(s))return s},t.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)}t.joinValues=n,t.jsonStringifyReplacer=(i,o)=>typeof o=="bigint"?o.toString():o})(qe||(qe={}));var _P;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(_P||(_P={}));var te=qe.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),mo=t=>{switch(typeof t){case"undefined":return te.undefined;case"string":return te.string;case"number":return Number.isNaN(t)?te.nan:te.number;case"boolean":return te.boolean;case"function":return te.function;case"bigint":return te.bigint;case"symbol":return te.symbol;case"object":return Array.isArray(t)?te.array:t===null?te.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?te.promise:typeof Map<"u"&&t instanceof Map?te.map:typeof Set<"u"&&t instanceof Set?te.set:typeof Date<"u"&&t instanceof Date?te.date:te.object;default:return te.unknown}};var Z=qe.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"]);var bn=class t 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 r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=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(r(s));else{let a=n,l=0;for(;l<s.path.length;){let c=s.path[l];l===s.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(r(s))):a[c]=a[c]||{_errors:[]},a=a[c],l++}}};return i(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,qe.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r=Object.create(null),n=[];for(let i of this.issues)if(i.path.length>0){let o=i.path[0];r[o]=r[o]||[],r[o].push(e(i))}else n.push(e(i));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};bn.create=t=>new bn(t);var xL=(t,e)=>{let r;switch(t.code){case Z.invalid_type:t.received===te.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case Z.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,qe.jsonStringifyReplacer)}`;break;case Z.unrecognized_keys:r=`Unrecognized key(s) in object: ${qe.joinValues(t.keys,", ")}`;break;case Z.invalid_union:r="Invalid input";break;case Z.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${qe.joinValues(t.options)}`;break;case Z.invalid_enum_value:r=`Invalid enum value. Expected ${qe.joinValues(t.options)}, received '${t.received}'`;break;case Z.invalid_arguments:r="Invalid function arguments";break;case Z.invalid_return_type:r="Invalid function return type";break;case Z.invalid_date:r="Invalid date";break;case Z.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:qe.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case Z.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case Z.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case Z.custom:r="Invalid input";break;case Z.invalid_intersection_types:r="Intersection results could not be merged";break;case Z.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case Z.not_finite:r="Number must be finite";break;default:r=e.defaultError,qe.assertNever(t)}return{message:r}},ls=xL;var $L=ls;function Fd(){return $L}var Oh=t=>{let{data:e,path:r,errorMaps:n,issueData:i}=t,o=[...r,...i.path||[]],s={...i,path:o};if(i.message!==void 0)return{...i,path:o,message:i.message};let a="",l=n.filter(c=>!!c).slice().reverse();for(let c of l)a=c(s,{data:e,defaultError:a}).message;return{...i,path:o,message:a}};function Q(t,e){let r=Fd(),n=Oh({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===ls?void 0:ls].filter(i=>!!i)});t.common.issues.push(n)}var Ir=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let i of r){if(i.status==="aborted")return ye;i.status==="dirty"&&e.dirty(),n.push(i.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let i of r){let o=await i.key,s=await i.value;n.push({key:o,value:s})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let i of r){let{key:o,value:s}=i;if(o.status==="aborted"||s.status==="aborted")return ye;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}}},ye=Object.freeze({status:"aborted"}),Sc=t=>({status:"dirty",value:t}),Ur=t=>({status:"valid",value:t}),Pb=t=>t.status==="aborted",Tb=t=>t.status==="dirty",ga=t=>t.status==="valid",Vd=t=>typeof Promise<"u"&&t instanceof Promise;var oe;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(oe||(oe={}));var Rn=class{constructor(e,r,n,i){this._cachedPath=[],this.parent=e,this.data=r,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}},bP=(t,e)=>{if(ga(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new bn(t.common.issues);return this._error=r,this._error}}};function Ee(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:i}=t;if(e&&(r||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:l}=t;return s.code==="invalid_enum_value"?{message:l??a.defaultError}:typeof a.data>"u"?{message:l??n??a.defaultError}:s.code!=="invalid_type"?{message:a.defaultError}:{message:l??r??a.defaultError}},description:i}}var Re=class{get description(){return this._def.description}_getType(e){return mo(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:mo(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ir,ctx:{common:e.parent.common,data:e.data,parsedType:mo(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(Vd(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:mo(e)},i=this._parseSync({data:e,path:n.path,parent:n});return bP(n,i)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:mo(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return ga(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>ga(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:mo(e)},i=this._parse({data:e,path:n.path,parent:n}),o=await(Vd(i)?i:Promise.resolve(i));return bP(n,o)}refine(e,r){let n=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,o)=>{let s=e(i),a=()=>o.addIssue({code:Z.custom,...n(i)});return typeof Promise<"u"&&s instanceof Promise?s.then(l=>l?!0:(a(),!1)):s?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,i)=>e(n)?!0:(i.addIssue(typeof r=="function"?r(n,i):r),!1))}_refinement(e){return new ri({schema:this,typeName:ge.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:r=>this["~validate"](r)}}optional(){return ti.create(this,this._def)}nullable(){return yo.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return us.create(this)}promise(){return ya.create(this,this._def)}or(e){return Ac.create([this,e],this._def)}and(e){return zc.create(this,e,this._def)}transform(e){return new ri({...Ee(this._def),schema:this,typeName:ge.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new Mc({...Ee(this._def),innerType:this,defaultValue:r,typeName:ge.ZodDefault})}brand(){return new Rh({typeName:ge.ZodBranded,type:this,...Ee(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new jc({...Ee(this._def),innerType:this,catchValue:r,typeName:ge.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Mh.create(this,e)}readonly(){return Dc.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},kL=/^c[^\s-]{8,}$/i,SL=/^[0-9a-z]+$/,IL=/^[0-9A-HJKMNP-TV-Z]{26}$/i,EL=/^[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,PL=/^[a-z0-9_-]{21}$/i,TL=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,AL=/^[-+]?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)?)??$/,zL=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,CL="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Ab,NL=/^(?:(?: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])$/,OL=/^(?:(?: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])$/,RL=/^(([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]))$/,ML=/^(([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])$/,jL=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,DL=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,wP="((\\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])))",LL=new RegExp(`^${wP}$`);function xP(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function UL(t){return new RegExp(`^${xP(t)}$`)}function ZL(t){let e=`${wP}T${xP(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function FL(t,e){return!!((e==="v4"||!e)&&NL.test(t)||(e==="v6"||!e)&&RL.test(t))}function VL(t,e){if(!TL.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.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 qL(t,e){return!!((e==="v4"||!e)&&OL.test(t)||(e==="v6"||!e)&&ML.test(t))}var Ec=class t extends Re{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==te.string){let o=this._getOrReturnCtx(e);return Q(o,{code:Z.invalid_type,expected:te.string,received:o.parsedType}),ye}let n=new Ir,i;for(let o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(i=this._getOrReturnCtx(e,i),Q(i,{code:Z.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),Q(i,{code:Z.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?Q(i,{code:Z.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&Q(i,{code:Z.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")zL.test(e.data)||(i=this._getOrReturnCtx(e,i),Q(i,{validation:"email",code:Z.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")Ab||(Ab=new RegExp(CL,"u")),Ab.test(e.data)||(i=this._getOrReturnCtx(e,i),Q(i,{validation:"emoji",code:Z.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")EL.test(e.data)||(i=this._getOrReturnCtx(e,i),Q(i,{validation:"uuid",code:Z.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")PL.test(e.data)||(i=this._getOrReturnCtx(e,i),Q(i,{validation:"nanoid",code:Z.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")kL.test(e.data)||(i=this._getOrReturnCtx(e,i),Q(i,{validation:"cuid",code:Z.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")SL.test(e.data)||(i=this._getOrReturnCtx(e,i),Q(i,{validation:"cuid2",code:Z.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")IL.test(e.data)||(i=this._getOrReturnCtx(e,i),Q(i,{validation:"ulid",code:Z.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{i=this._getOrReturnCtx(e,i),Q(i,{validation:"url",code:Z.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),Q(i,{validation:"regex",code:Z.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),Q(i,{code:Z.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),Q(i,{code:Z.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(i=this._getOrReturnCtx(e,i),Q(i,{code:Z.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?ZL(o).test(e.data)||(i=this._getOrReturnCtx(e,i),Q(i,{code:Z.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?LL.test(e.data)||(i=this._getOrReturnCtx(e,i),Q(i,{code:Z.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?UL(o).test(e.data)||(i=this._getOrReturnCtx(e,i),Q(i,{code:Z.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?AL.test(e.data)||(i=this._getOrReturnCtx(e,i),Q(i,{validation:"duration",code:Z.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?FL(e.data,o.version)||(i=this._getOrReturnCtx(e,i),Q(i,{validation:"ip",code:Z.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?VL(e.data,o.alg)||(i=this._getOrReturnCtx(e,i),Q(i,{validation:"jwt",code:Z.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?qL(e.data,o.version)||(i=this._getOrReturnCtx(e,i),Q(i,{validation:"cidr",code:Z.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?jL.test(e.data)||(i=this._getOrReturnCtx(e,i),Q(i,{validation:"base64",code:Z.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?DL.test(e.data)||(i=this._getOrReturnCtx(e,i),Q(i,{validation:"base64url",code:Z.invalid_string,message:o.message}),n.dirty()):qe.assertNever(o);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(i=>e.test(i),{validation:r,code:Z.invalid_string,...oe.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...oe.errToObj(e)})}url(e){return this._addCheck({kind:"url",...oe.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...oe.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...oe.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...oe.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...oe.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...oe.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...oe.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...oe.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...oe.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...oe.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...oe.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...oe.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,...oe.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,...oe.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...oe.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...oe.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...oe.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...oe.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...oe.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...oe.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...oe.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...oe.errToObj(r)})}nonempty(e){return this.min(1,oe.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...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 r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Ec.create=t=>new Ec({checks:[],typeName:ge.ZodString,coerce:t?.coerce??!1,...Ee(t)});function WL(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,i=r>n?r:n,o=Number.parseInt(t.toFixed(i).replace(".","")),s=Number.parseInt(e.toFixed(i).replace(".",""));return o%s/10**i}var qd=class t extends Re{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)!==te.number){let o=this._getOrReturnCtx(e);return Q(o,{code:Z.invalid_type,expected:te.number,received:o.parsedType}),ye}let n,i=new Ir;for(let o of this._def.checks)o.kind==="int"?qe.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),Q(n,{code:Z.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),Q(n,{code:Z.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),Q(n,{code:Z.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?WL(e.data,o.value)!==0&&(n=this._getOrReturnCtx(e,n),Q(n,{code:Z.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),Q(n,{code:Z.not_finite,message:o.message}),i.dirty()):qe.assertNever(o);return{status:i.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,oe.toString(r))}gt(e,r){return this.setLimit("min",e,!1,oe.toString(r))}lte(e,r){return this.setLimit("max",e,!0,oe.toString(r))}lt(e,r){return this.setLimit("max",e,!1,oe.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:oe.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:oe.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:oe.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:oe.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:oe.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:oe.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:oe.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:oe.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:oe.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:oe.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&qe.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};qd.create=t=>new qd({checks:[],typeName:ge.ZodNumber,coerce:t?.coerce||!1,...Ee(t)});var Wd=class t extends Re{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)!==te.bigint)return this._getInvalidInput(e);let n,i=new Ir;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),Q(n,{code:Z.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),Q(n,{code:Z.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),Q(n,{code:Z.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):qe.assertNever(o);return{status:i.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return Q(r,{code:Z.invalid_type,expected:te.bigint,received:r.parsedType}),ye}gte(e,r){return this.setLimit("min",e,!0,oe.toString(r))}gt(e,r){return this.setLimit("min",e,!1,oe.toString(r))}lte(e,r){return this.setLimit("max",e,!0,oe.toString(r))}lt(e,r){return this.setLimit("max",e,!1,oe.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:oe.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:oe.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:oe.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:oe.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:oe.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:oe.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Wd.create=t=>new Wd({checks:[],typeName:ge.ZodBigInt,coerce:t?.coerce??!1,...Ee(t)});var Bd=class extends Re{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==te.boolean){let n=this._getOrReturnCtx(e);return Q(n,{code:Z.invalid_type,expected:te.boolean,received:n.parsedType}),ye}return Ur(e.data)}};Bd.create=t=>new Bd({typeName:ge.ZodBoolean,coerce:t?.coerce||!1,...Ee(t)});var Gd=class t extends Re{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==te.date){let o=this._getOrReturnCtx(e);return Q(o,{code:Z.invalid_type,expected:te.date,received:o.parsedType}),ye}if(Number.isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return Q(o,{code:Z.invalid_date}),ye}let n=new Ir,i;for(let o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(i=this._getOrReturnCtx(e,i),Q(i,{code:Z.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),Q(i,{code:Z.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):qe.assertNever(o);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:oe.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:oe.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};Gd.create=t=>new Gd({checks:[],coerce:t?.coerce||!1,typeName:ge.ZodDate,...Ee(t)});var Hd=class extends Re{_parse(e){if(this._getType(e)!==te.symbol){let n=this._getOrReturnCtx(e);return Q(n,{code:Z.invalid_type,expected:te.symbol,received:n.parsedType}),ye}return Ur(e.data)}};Hd.create=t=>new Hd({typeName:ge.ZodSymbol,...Ee(t)});var Pc=class extends Re{_parse(e){if(this._getType(e)!==te.undefined){let n=this._getOrReturnCtx(e);return Q(n,{code:Z.invalid_type,expected:te.undefined,received:n.parsedType}),ye}return Ur(e.data)}};Pc.create=t=>new Pc({typeName:ge.ZodUndefined,...Ee(t)});var Tc=class extends Re{_parse(e){if(this._getType(e)!==te.null){let n=this._getOrReturnCtx(e);return Q(n,{code:Z.invalid_type,expected:te.null,received:n.parsedType}),ye}return Ur(e.data)}};Tc.create=t=>new Tc({typeName:ge.ZodNull,...Ee(t)});var Xd=class extends Re{constructor(){super(...arguments),this._any=!0}_parse(e){return Ur(e.data)}};Xd.create=t=>new Xd({typeName:ge.ZodAny,...Ee(t)});var cs=class extends Re{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ur(e.data)}};cs.create=t=>new cs({typeName:ge.ZodUnknown,...Ee(t)});var Ti=class extends Re{_parse(e){let r=this._getOrReturnCtx(e);return Q(r,{code:Z.invalid_type,expected:te.never,received:r.parsedType}),ye}};Ti.create=t=>new Ti({typeName:ge.ZodNever,...Ee(t)});var Kd=class extends Re{_parse(e){if(this._getType(e)!==te.undefined){let n=this._getOrReturnCtx(e);return Q(n,{code:Z.invalid_type,expected:te.void,received:n.parsedType}),ye}return Ur(e.data)}};Kd.create=t=>new Kd({typeName:ge.ZodVoid,...Ee(t)});var us=class t extends Re{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),i=this._def;if(r.parsedType!==te.array)return Q(r,{code:Z.invalid_type,expected:te.array,received:r.parsedType}),ye;if(i.exactLength!==null){let s=r.data.length>i.exactLength.value,a=r.data.length<i.exactLength.value;(s||a)&&(Q(r,{code:s?Z.too_big:Z.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&&r.data.length<i.minLength.value&&(Q(r,{code:Z.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),n.dirty()),i.maxLength!==null&&r.data.length>i.maxLength.value&&(Q(r,{code:Z.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((s,a)=>i.type._parseAsync(new Rn(r,s,r.path,a)))).then(s=>Ir.mergeArray(n,s));let o=[...r.data].map((s,a)=>i.type._parseSync(new Rn(r,s,r.path,a)));return Ir.mergeArray(n,o)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:oe.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:oe.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:oe.toString(r)}})}nonempty(e){return this.min(1,e)}};us.create=(t,e)=>new us({type:t,minLength:null,maxLength:null,exactLength:null,typeName:ge.ZodArray,...Ee(e)});function Ic(t){if(t instanceof wn){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=ti.create(Ic(n))}return new wn({...t._def,shape:()=>e})}else return t instanceof us?new us({...t._def,type:Ic(t.element)}):t instanceof ti?ti.create(Ic(t.unwrap())):t instanceof yo?yo.create(Ic(t.unwrap())):t instanceof go?go.create(t.items.map(e=>Ic(e))):t}var wn=class t extends Re{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(),r=qe.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==te.object){let c=this._getOrReturnCtx(e);return Q(c,{code:Z.invalid_type,expected:te.object,received:c.parsedType}),ye}let{status:n,ctx:i}=this._processInputParams(e),{shape:o,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof Ti&&this._def.unknownKeys==="strip"))for(let c in i.data)s.includes(c)||a.push(c);let l=[];for(let c of s){let u=o[c],d=i.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new Rn(i,d,i.path,c)),alwaysSet:c in i.data})}if(this._def.catchall instanceof Ti){let c=this._def.unknownKeys;if(c==="passthrough")for(let u of a)l.push({key:{status:"valid",value:u},value:{status:"valid",value:i.data[u]}});else if(c==="strict")a.length>0&&(Q(i,{code:Z.unrecognized_keys,keys:a}),n.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let u of a){let d=i.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new Rn(i,d,i.path,u)),alwaysSet:u in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let c=[];for(let u of l){let d=await u.key,p=await u.value;c.push({key:d,value:p,alwaysSet:u.alwaysSet})}return c}).then(c=>Ir.mergeObjectSync(n,c)):Ir.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(e){return oe.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let i=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:oe.errToObj(e).message??i}:{message:i}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:ge.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of qe.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of qe.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return Ic(this)}partial(e){let r={};for(let n of qe.objectKeys(this.shape)){let i=this.shape[n];e&&!e[n]?r[n]=i:r[n]=i.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of qe.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof ti;)o=o._def.innerType;r[n]=o}return new t({...this._def,shape:()=>r})}keyof(){return $P(qe.objectKeys(this.shape))}};wn.create=(t,e)=>new wn({shape:()=>t,unknownKeys:"strip",catchall:Ti.create(),typeName:ge.ZodObject,...Ee(e)});wn.strictCreate=(t,e)=>new wn({shape:()=>t,unknownKeys:"strict",catchall:Ti.create(),typeName:ge.ZodObject,...Ee(e)});wn.lazycreate=(t,e)=>new wn({shape:t,unknownKeys:"strip",catchall:Ti.create(),typeName:ge.ZodObject,...Ee(e)});var Ac=class extends Re{_parse(e){let{ctx:r}=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 r.common.issues.push(...a.ctx.common.issues),a.result;let s=o.map(a=>new bn(a.ctx.common.issues));return Q(r,{code:Z.invalid_union,unionErrors:s}),ye}if(r.common.async)return Promise.all(n.map(async o=>{let s={...r,common:{...r.common,issues:[]},parent:null};return{result:await o._parseAsync({data:r.data,path:r.path,parent:s}),ctx:s}})).then(i);{let o,s=[];for(let l of n){let c={...r,common:{...r.common,issues:[]},parent:null},u=l._parseSync({data:r.data,path:r.path,parent:c});if(u.status==="valid")return u;u.status==="dirty"&&!o&&(o={result:u,ctx:c}),c.common.issues.length&&s.push(c.common.issues)}if(o)return r.common.issues.push(...o.ctx.common.issues),o.result;let a=s.map(l=>new bn(l));return Q(r,{code:Z.invalid_union,unionErrors:a}),ye}}get options(){return this._def.options}};Ac.create=(t,e)=>new Ac({options:t,typeName:ge.ZodUnion,...Ee(e)});var ho=t=>t instanceof Cc?ho(t.schema):t instanceof ri?ho(t.innerType()):t instanceof Nc?[t.value]:t instanceof Oc?t.options:t instanceof Rc?qe.objectValues(t.enum):t instanceof Mc?ho(t._def.innerType):t instanceof Pc?[void 0]:t instanceof Tc?[null]:t instanceof ti?[void 0,...ho(t.unwrap())]:t instanceof yo?[null,...ho(t.unwrap())]:t instanceof Rh||t instanceof Dc?ho(t.unwrap()):t instanceof jc?ho(t._def.innerType):[],zb=class t extends Re{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==te.object)return Q(r,{code:Z.invalid_type,expected:te.object,received:r.parsedType}),ye;let n=this.discriminator,i=r.data[n],o=this.optionsMap.get(i);return o?r.common.async?o._parseAsync({data:r.data,path:r.path,parent:r}):o._parseSync({data:r.data,path:r.path,parent:r}):(Q(r,{code:Z.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),ye)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let i=new Map;for(let o of r){let s=ho(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 t({typeName:ge.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:i,...Ee(n)})}};function Cb(t,e){let r=mo(t),n=mo(e);if(t===e)return{valid:!0,data:t};if(r===te.object&&n===te.object){let i=qe.objectKeys(e),o=qe.objectKeys(t).filter(a=>i.indexOf(a)!==-1),s={...t,...e};for(let a of o){let l=Cb(t[a],e[a]);if(!l.valid)return{valid:!1};s[a]=l.data}return{valid:!0,data:s}}else if(r===te.array&&n===te.array){if(t.length!==e.length)return{valid:!1};let i=[];for(let o=0;o<t.length;o++){let s=t[o],a=e[o],l=Cb(s,a);if(!l.valid)return{valid:!1};i.push(l.data)}return{valid:!0,data:i}}else return r===te.date&&n===te.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var zc=class extends Re{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),i=(o,s)=>{if(Pb(o)||Pb(s))return ye;let a=Cb(o.value,s.value);return a.valid?((Tb(o)||Tb(s))&&r.dirty(),{status:r.value,value:a.data}):(Q(n,{code:Z.invalid_intersection_types}),ye)};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}))}};zc.create=(t,e,r)=>new zc({left:t,right:e,typeName:ge.ZodIntersection,...Ee(r)});var go=class t extends Re{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==te.array)return Q(n,{code:Z.invalid_type,expected:te.array,received:n.parsedType}),ye;if(n.data.length<this._def.items.length)return Q(n,{code:Z.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),ye;!this._def.rest&&n.data.length>this._def.items.length&&(Q(n,{code:Z.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let o=[...n.data].map((s,a)=>{let l=this._def.items[a]||this._def.rest;return l?l._parse(new Rn(n,s,n.path,a)):null}).filter(s=>!!s);return n.common.async?Promise.all(o).then(s=>Ir.mergeArray(r,s)):Ir.mergeArray(r,o)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};go.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new go({items:t,typeName:ge.ZodTuple,rest:null,...Ee(e)})};var Nb=class t extends Re{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==te.object)return Q(n,{code:Z.invalid_type,expected:te.object,received:n.parsedType}),ye;let i=[],o=this._def.keyType,s=this._def.valueType;for(let a in n.data)i.push({key:o._parse(new Rn(n,a,n.path,a)),value:s._parse(new Rn(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Ir.mergeObjectAsync(r,i):Ir.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof Re?new t({keyType:e,valueType:r,typeName:ge.ZodRecord,...Ee(n)}):new t({keyType:Ec.create(),valueType:e,typeName:ge.ZodRecord,...Ee(r)})}},Jd=class extends Re{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==te.map)return Q(n,{code:Z.invalid_type,expected:te.map,received:n.parsedType}),ye;let i=this._def.keyType,o=this._def.valueType,s=[...n.data.entries()].map(([a,l],c)=>({key:i._parse(new Rn(n,a,n.path,[c,"key"])),value:o._parse(new Rn(n,l,n.path,[c,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let l of s){let c=await l.key,u=await l.value;if(c.status==="aborted"||u.status==="aborted")return ye;(c.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(c.value,u.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let l of s){let c=l.key,u=l.value;if(c.status==="aborted"||u.status==="aborted")return ye;(c.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(c.value,u.value)}return{status:r.value,value:a}}}};Jd.create=(t,e,r)=>new Jd({valueType:e,keyType:t,typeName:ge.ZodMap,...Ee(r)});var Yd=class t extends Re{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==te.set)return Q(n,{code:Z.invalid_type,expected:te.set,received:n.parsedType}),ye;let i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(Q(n,{code:Z.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),r.dirty()),i.maxSize!==null&&n.data.size>i.maxSize.value&&(Q(n,{code:Z.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());let o=this._def.valueType;function s(l){let c=new Set;for(let u of l){if(u.status==="aborted")return ye;u.status==="dirty"&&r.dirty(),c.add(u.value)}return{status:r.value,value:c}}let a=[...n.data.values()].map((l,c)=>o._parse(new Rn(n,l,n.path,c)));return n.common.async?Promise.all(a).then(l=>s(l)):s(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:oe.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:oe.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};Yd.create=(t,e)=>new Yd({valueType:t,minSize:null,maxSize:null,typeName:ge.ZodSet,...Ee(e)});var Ob=class t extends Re{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==te.function)return Q(r,{code:Z.invalid_type,expected:te.function,received:r.parsedType}),ye;function n(a,l){return Oh({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Fd(),ls].filter(c=>!!c),issueData:{code:Z.invalid_arguments,argumentsError:l}})}function i(a,l){return Oh({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Fd(),ls].filter(c=>!!c),issueData:{code:Z.invalid_return_type,returnTypeError:l}})}let o={errorMap:r.common.contextualErrorMap},s=r.data;if(this._def.returns instanceof ya){let a=this;return Ur(async function(...l){let c=new bn([]),u=await a._def.args.parseAsync(l,o).catch(f=>{throw c.addIssue(n(l,f)),c}),d=await Reflect.apply(s,this,u);return await a._def.returns._def.type.parseAsync(d,o).catch(f=>{throw c.addIssue(i(d,f)),c})})}else{let a=this;return Ur(function(...l){let c=a._def.args.safeParse(l,o);if(!c.success)throw new bn([n(l,c.error)]);let u=Reflect.apply(s,this,c.data),d=a._def.returns.safeParse(u,o);if(!d.success)throw new bn([i(u,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:go.create(e).rest(cs.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||go.create([]).rest(cs.create()),returns:r||cs.create(),typeName:ge.ZodFunction,...Ee(n)})}},Cc=class extends Re{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Cc.create=(t,e)=>new Cc({getter:t,typeName:ge.ZodLazy,...Ee(e)});var Nc=class extends Re{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return Q(r,{received:r.data,code:Z.invalid_literal,expected:this._def.value}),ye}return{status:"valid",value:e.data}}get value(){return this._def.value}};Nc.create=(t,e)=>new Nc({value:t,typeName:ge.ZodLiteral,...Ee(e)});function $P(t,e){return new Oc({values:t,typeName:ge.ZodEnum,...Ee(e)})}var Oc=class t extends Re{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return Q(r,{expected:qe.joinValues(n),received:r.parsedType,code:Z.invalid_type}),ye}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return Q(r,{received:r.data,code:Z.invalid_enum_value,options:n}),ye}return Ur(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};Oc.create=$P;var Rc=class extends Re{_parse(e){let r=qe.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==te.string&&n.parsedType!==te.number){let i=qe.objectValues(r);return Q(n,{expected:qe.joinValues(i),received:n.parsedType,code:Z.invalid_type}),ye}if(this._cache||(this._cache=new Set(qe.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let i=qe.objectValues(r);return Q(n,{received:n.data,code:Z.invalid_enum_value,options:i}),ye}return Ur(e.data)}get enum(){return this._def.values}};Rc.create=(t,e)=>new Rc({values:t,typeName:ge.ZodNativeEnum,...Ee(e)});var ya=class extends Re{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==te.promise&&r.common.async===!1)return Q(r,{code:Z.invalid_type,expected:te.promise,received:r.parsedType}),ye;let n=r.parsedType===te.promise?r.data:Promise.resolve(r.data);return Ur(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};ya.create=(t,e)=>new ya({type:t,typeName:ge.ZodPromise,...Ee(e)});var ri=class extends Re{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ge.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),i=this._def.effect||null,o={addIssue:s=>{Q(n,s),s.fatal?r.abort():r.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(r.value==="aborted")return ye;let l=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return l.status==="aborted"?ye:l.status==="dirty"?Sc(l.value):r.value==="dirty"?Sc(l.value):l});{if(r.value==="aborted")return ye;let a=this._def.schema._parseSync({data:s,path:n.path,parent:n});return a.status==="aborted"?ye:a.status==="dirty"?Sc(a.value):r.value==="dirty"?Sc(a.value):a}}if(i.type==="refinement"){let s=a=>{let l=i.refinement(a,o);if(n.common.async)return Promise.resolve(l);if(l 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"?ye:(a.status==="dirty"&&r.dirty(),s(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?ye:(a.status==="dirty"&&r.dirty(),s(a.value).then(()=>({status:r.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(!ga(s))return ye;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:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(s=>ga(s)?Promise.resolve(i.transform(s.value,o)).then(a=>({status:r.value,value:a})):ye);qe.assertNever(i)}};ri.create=(t,e,r)=>new ri({schema:t,typeName:ge.ZodEffects,effect:e,...Ee(r)});ri.createWithPreprocess=(t,e,r)=>new ri({schema:e,effect:{type:"preprocess",transform:t},typeName:ge.ZodEffects,...Ee(r)});var ti=class extends Re{_parse(e){return this._getType(e)===te.undefined?Ur(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ti.create=(t,e)=>new ti({innerType:t,typeName:ge.ZodOptional,...Ee(e)});var yo=class extends Re{_parse(e){return this._getType(e)===te.null?Ur(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};yo.create=(t,e)=>new yo({innerType:t,typeName:ge.ZodNullable,...Ee(e)});var Mc=class extends Re{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===te.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Mc.create=(t,e)=>new Mc({innerType:t,typeName:ge.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Ee(e)});var jc=class extends Re{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Vd(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new bn(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new bn(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};jc.create=(t,e)=>new jc({innerType:t,typeName:ge.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Ee(e)});var Qd=class extends Re{_parse(e){if(this._getType(e)!==te.nan){let n=this._getOrReturnCtx(e);return Q(n,{code:Z.invalid_type,expected:te.nan,received:n.parsedType}),ye}return{status:"valid",value:e.data}}};Qd.create=t=>new Qd({typeName:ge.ZodNaN,...Ee(t)});var gue=Symbol("zod_brand"),Rh=class extends Re{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},Mh=class t extends Re{_parse(e){let{status:r,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"?ye:o.status==="dirty"?(r.dirty(),Sc(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"?ye:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:ge.ZodPipeline})}},Dc=class extends Re{_parse(e){let r=this._def.innerType._parse(e),n=i=>(ga(i)&&(i.value=Object.freeze(i.value)),i);return Vd(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};Dc.create=(t,e)=>new Dc({innerType:t,typeName:ge.ZodReadonly,...Ee(e)});var yue={object:wn.lazycreate},ge;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(ge||(ge={}));var vue=Ec.create,_ue=qd.create,bue=Qd.create,wue=Wd.create,xue=Bd.create,$ue=Gd.create,kue=Hd.create,Sue=Pc.create,Iue=Tc.create,Eue=Xd.create,Pue=cs.create,Tue=Ti.create,Aue=Kd.create,zue=us.create,BL=wn.create,Cue=wn.strictCreate,Nue=Ac.create,Oue=zb.create,Rue=zc.create,Mue=go.create,jue=Nb.create,Due=Jd.create,Lue=Yd.create,Uue=Ob.create,Zue=Cc.create,Fue=Nc.create,Vue=Oc.create,que=Rc.create,Wue=ya.create,Bue=ri.create,Gue=ti.create,Hue=yo.create,Xue=ri.createWithPreprocess,Kue=Mh.create;var Dh=Object.freeze({status:"aborted"});function N(t,e,r){function n(a,l){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:l,constr:s,traits:new Set},enumerable:!1}),a._zod.traits.has(t))return;a._zod.traits.add(t),e(a,l);let c=s.prototype,u=Object.keys(c);for(let d=0;d<u.length;d++){let p=u[d];p in a||(a[p]=c[p].bind(a))}}let i=r?.Parent??Object;class o extends i{}Object.defineProperty(o,"name",{value:t});function s(a){var l;let c=r?.Parent?new o:this;n(c,a),(l=c._zod).deferred??(l.deferred=[]);for(let u of c._zod.deferred)u();return c}return Object.defineProperty(s,"init",{value:n}),Object.defineProperty(s,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(s,"name",{value:t}),s}var Rb=Symbol("zod_brand"),Ai=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Lc=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}},jh={};function Er(t){return t&&Object.assign(jh,t),jh}var X={};ed(X,{BIGINT_FORMAT_RANGES:()=>EP,Class:()=>jb,NUMBER_FORMAT_RANGES:()=>Vb,aborted:()=>ms,allowsEval:()=>Ub,assert:()=>QL,assertEqual:()=>XL,assertIs:()=>JL,assertNever:()=>YL,assertNotEqual:()=>KL,assignProp:()=>ds,base64ToUint8Array:()=>TP,base64urlToUint8Array:()=>gU,cached:()=>Zc,captureStackTrace:()=>Zh,cleanEnum:()=>hU,cleanRegex:()=>rf,clone:()=>Yr,cloneDef:()=>tU,createTransparentProxy:()=>aU,defineLazy:()=>ut,esc:()=>Uh,escapeRegex:()=>zi,extend:()=>uU,finalizeIssue:()=>ni,floatSafeRemainder:()=>Db,getElementAtPath:()=>rU,getEnumValues:()=>Lh,getLengthableOrigin:()=>nf,getParsedType:()=>sU,getSizableOrigin:()=>PP,hexToUint8Array:()=>vU,isObject:()=>va,isPlainObject:()=>ps,issue:()=>Fc,joinValues:()=>ve,jsonStringifyReplacer:()=>Uc,merge:()=>fU,mergeDefs:()=>fs,normalizeParams:()=>de,nullish:()=>tf,numKeys:()=>oU,objectClone:()=>eU,omit:()=>cU,optionalKeys:()=>Fb,partial:()=>pU,pick:()=>lU,prefixIssues:()=>vo,primitiveTypes:()=>IP,promiseAllObject:()=>nU,propertyKeyTypes:()=>Zb,randomString:()=>iU,required:()=>mU,safeExtend:()=>dU,shallowClone:()=>SP,slugify:()=>Lb,stringifyPrimitive:()=>_e,uint8ArrayToBase64:()=>AP,uint8ArrayToBase64url:()=>yU,uint8ArrayToHex:()=>_U,unwrapMessage:()=>ef});function XL(t){return t}function KL(t){return t}function JL(t){}function YL(t){throw new Error}function QL(t){}function Lh(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,i])=>e.indexOf(+n)===-1).map(([n,i])=>i)}function ve(t,e="|"){return t.map(r=>_e(r)).join(e)}function Uc(t,e){return typeof e=="bigint"?e.toString():e}function Zc(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function tf(t){return t==null}function rf(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function Db(t,e){let r=(t.toString().split(".")[1]||"").length,n=e.toString(),i=(n.split(".")[1]||"").length;if(i===0&&/\d?e-\d?/.test(n)){let l=n.match(/\d?e-(\d?)/);l?.[1]&&(i=Number.parseInt(l[1]))}let o=r>i?r:i,s=Number.parseInt(t.toFixed(o).replace(".","")),a=Number.parseInt(e.toFixed(o).replace(".",""));return s%a/10**o}var kP=Symbol("evaluating");function ut(t,e,r){let n;Object.defineProperty(t,e,{get(){if(n!==kP)return n===void 0&&(n=kP,n=r()),n},set(i){Object.defineProperty(t,e,{value:i})},configurable:!0})}function eU(t){return Object.create(Object.getPrototypeOf(t),Object.getOwnPropertyDescriptors(t))}function ds(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function fs(...t){let e={};for(let r of t){let n=Object.getOwnPropertyDescriptors(r);Object.assign(e,n)}return Object.defineProperties({},e)}function tU(t){return fs(t._zod.def)}function rU(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function nU(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let i={};for(let o=0;o<e.length;o++)i[e[o]]=n[o];return i})}function iU(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function Uh(t){return JSON.stringify(t)}function Lb(t){return t.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Zh="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};function va(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Ub=Zc(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function ps(t){if(va(t)===!1)return!1;let e=t.constructor;if(e===void 0||typeof e!="function")return!0;let r=e.prototype;return!(va(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function SP(t){return ps(t)?{...t}:Array.isArray(t)?[...t]:t}function oU(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}var sU=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},Zb=new Set(["string","number","symbol"]),IP=new Set(["string","number","bigint","boolean","symbol","undefined"]);function zi(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Yr(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function de(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function aU(t){let e;return new Proxy({},{get(r,n,i){return e??(e=t()),Reflect.get(e,n,i)},set(r,n,i,o){return e??(e=t()),Reflect.set(e,n,i,o)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,i){return e??(e=t()),Reflect.defineProperty(e,n,i)}})}function _e(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function Fb(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var Vb={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]},EP={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function lU(t,e){let r=t._zod.def,n=fs(t._zod.def,{get shape(){let i={};for(let o in e){if(!(o in r.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&(i[o]=r.shape[o])}return ds(this,"shape",i),i},checks:[]});return Yr(t,n)}function cU(t,e){let r=t._zod.def,n=fs(t._zod.def,{get shape(){let i={...t._zod.def.shape};for(let o in e){if(!(o in r.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&delete i[o]}return ds(this,"shape",i),i},checks:[]});return Yr(t,n)}function uU(t,e){if(!ps(e))throw new Error("Invalid input to extend: expected a plain object");let r=t._zod.def.checks;if(r&&r.length>0)throw new Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");let i=fs(t._zod.def,{get shape(){let o={...t._zod.def.shape,...e};return ds(this,"shape",o),o},checks:[]});return Yr(t,i)}function dU(t,e){if(!ps(e))throw new Error("Invalid input to safeExtend: expected a plain object");let r={...t._zod.def,get shape(){let n={...t._zod.def.shape,...e};return ds(this,"shape",n),n},checks:t._zod.def.checks};return Yr(t,r)}function fU(t,e){let r=fs(t._zod.def,{get shape(){let n={...t._zod.def.shape,...e._zod.def.shape};return ds(this,"shape",n),n},get catchall(){return e._zod.def.catchall},checks:[]});return Yr(t,r)}function pU(t,e,r){let n=fs(e._zod.def,{get shape(){let i=e._zod.def.shape,o={...i};if(r)for(let s in r){if(!(s in i))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=t?new t({type:"optional",innerType:i[s]}):i[s])}else for(let s in i)o[s]=t?new t({type:"optional",innerType:i[s]}):i[s];return ds(this,"shape",o),o},checks:[]});return Yr(e,n)}function mU(t,e,r){let n=fs(e._zod.def,{get shape(){let i=e._zod.def.shape,o={...i};if(r)for(let s in r){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=new t({type:"nonoptional",innerType:i[s]}))}else for(let s in i)o[s]=new t({type:"nonoptional",innerType:i[s]});return ds(this,"shape",o),o},checks:[]});return Yr(e,n)}function ms(t,e=0){if(t.aborted===!0)return!0;for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function vo(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function ef(t){return typeof t=="string"?t:t?.message}function ni(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let i=ef(t.inst?._zod.def?.error?.(t))??ef(e?.error?.(t))??ef(r.customError?.(t))??ef(r.localeError?.(t))??"Invalid input";n.message=i}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function PP(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function nf(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Fc(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function hU(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}function TP(t){let e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r}function AP(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return btoa(e)}function gU(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-e.length%4)%4);return TP(e+r)}function yU(t){return AP(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function vU(t){let e=t.replace(/^0x/,"");if(e.length%2!==0)throw new Error("Invalid hex string length");let r=new Uint8Array(e.length/2);for(let n=0;n<e.length;n+=2)r[n/2]=Number.parseInt(e.slice(n,n+2),16);return r}function _U(t){return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}var jb=class{constructor(...e){}};var zP=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),t.message=JSON.stringify(e,Uc,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Fh=N("$ZodError",zP),qb=N("$ZodError",zP,{Parent:Error});function Vh(t,e=r=>r.message){let r={},n=[];for(let i of t.issues)i.path.length>0?(r[i.path[0]]=r[i.path[0]]||[],r[i.path[0]].push(e(i))):n.push(e(i));return{formErrors:n,fieldErrors:r}}function qh(t,e=r=>r.message){let r={_errors:[]},n=i=>{for(let o of i.issues)if(o.code==="invalid_union"&&o.errors.length)o.errors.map(s=>n({issues:s}));else if(o.code==="invalid_key")n({issues:o.issues});else if(o.code==="invalid_element")n({issues:o.issues});else if(o.path.length===0)r._errors.push(e(o));else{let s=r,a=0;for(;a<o.path.length;){let l=o.path[a];a===o.path.length-1?(s[l]=s[l]||{_errors:[]},s[l]._errors.push(e(o))):s[l]=s[l]||{_errors:[]},s=s[l],a++}}};return n(t),r}var Wh=t=>(e,r,n,i)=>{let o=n?Object.assign(n,{async:!1}):{async:!1},s=e._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new Ai;if(s.issues.length){let a=new(i?.Err??t)(s.issues.map(l=>ni(l,o,Er())));throw Zh(a,i?.callee),a}return s.value};var Bh=t=>async(e,r,n,i)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},s=e._zod.run({value:r,issues:[]},o);if(s instanceof Promise&&(s=await s),s.issues.length){let a=new(i?.Err??t)(s.issues.map(l=>ni(l,o,Er())));throw Zh(a,i?.callee),a}return s.value};var of=t=>(e,r,n)=>{let i=n?{...n,async:!1}:{async:!1},o=e._zod.run({value:r,issues:[]},i);if(o instanceof Promise)throw new Ai;return o.issues.length?{success:!1,error:new(t??Fh)(o.issues.map(s=>ni(s,i,Er())))}:{success:!0,data:o.value}},Vc=of(qb),sf=t=>async(e,r,n)=>{let i=n?Object.assign(n,{async:!0}):{async:!0},o=e._zod.run({value:r,issues:[]},i);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new t(o.issues.map(s=>ni(s,i,Er())))}:{success:!0,data:o.value}},af=sf(qb),CP=t=>(e,r,n)=>{let i=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return Wh(t)(e,r,i)};var NP=t=>(e,r,n)=>Wh(t)(e,r,n);var OP=t=>async(e,r,n)=>{let i=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return Bh(t)(e,r,i)};var RP=t=>async(e,r,n)=>Bh(t)(e,r,n);var MP=t=>(e,r,n)=>{let i=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return of(t)(e,r,i)};var jP=t=>(e,r,n)=>of(t)(e,r,n);var DP=t=>async(e,r,n)=>{let i=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return sf(t)(e,r,i)};var LP=t=>async(e,r,n)=>sf(t)(e,r,n);var UP=/^[cC][^\s-]{8,}$/,ZP=/^[0-9a-z]+$/,FP=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,VP=/^[0-9a-vA-V]{20}$/,qP=/^[A-Za-z0-9]{27}$/,WP=/^[a-zA-Z0-9_-]{21}$/,BP=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var GP=/^([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})$/,Wb=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;var HP=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var wU="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function XP(){return new RegExp(wU,"u")}var KP=/^(?:(?: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])$/,JP=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;var YP=/^((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])$/,QP=/^(([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])$/,eT=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Bb=/^[A-Za-z0-9_-]*$/;var tT=/^\+(?:[0-9]){6,14}[0-9]$/,rT="(?:(?:\\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])))",nT=new RegExp(`^${rT}$`);function iT(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function oT(t){return new RegExp(`^${iT(t)}$`)}function sT(t){let e=iT({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let n=`${e}(?:${r.join("|")})`;return new RegExp(`^${rT}T(?:${n})$`)}var aT=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},lT=/^-?\d+n?$/,cT=/^-?\d+$/,uT=/^-?\d+(?:\.\d+)?/,dT=/^(?:true|false)$/i,fT=/^null$/i;var pT=/^[^A-Z]*$/,mT=/^[^a-z]*$/;var or=N("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),hT={number:"number",bigint:"bigint",object:"date"},Gb=N("$ZodCheckLessThan",(t,e)=>{or.init(t,e);let r=hT[typeof e.value];t._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)}),t._zod.check=n=>{(e.inclusive?n.value<=e.value:n.value<e.value)||n.issues.push({origin:r,code:"too_big",maximum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Hb=N("$ZodCheckGreaterThan",(t,e)=>{or.init(t,e);let r=hT[typeof e.value];t._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)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),gT=N("$ZodCheckMultipleOf",(t,e)=>{or.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):Db(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),yT=N("$ZodCheckNumberFormat",(t,e)=>{or.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[i,o]=Vb[e.format];t._zod.onattach.push(s=>{let a=s._zod.bag;a.format=e.format,a.minimum=i,a.maximum=o,r&&(a.pattern=cT)}),t._zod.check=s=>{let a=s.value;if(r){if(!Number.isInteger(a)){s.issues.push({expected:n,format:e.format,code:"invalid_type",continue:!1,input:a,inst:t});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:t,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:t,origin:n,continue:!e.abort});return}}a<i&&s.issues.push({origin:"number",input:a,code:"too_small",minimum:i,inclusive:!0,inst:t,continue:!e.abort}),a>o&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:o,inst:t})}});var vT=N("$ZodCheckMaxLength",(t,e)=>{var r;or.init(t,e),(r=t._zod.def).when??(r.when=n=>{let i=n.value;return!tf(i)&&i.length!==void 0}),t._zod.onattach.push(n=>{let i=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<i&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{let i=n.value;if(i.length<=e.maximum)return;let s=nf(i);n.issues.push({origin:s,code:"too_big",maximum:e.maximum,inclusive:!0,input:i,inst:t,continue:!e.abort})}}),_T=N("$ZodCheckMinLength",(t,e)=>{var r;or.init(t,e),(r=t._zod.def).when??(r.when=n=>{let i=n.value;return!tf(i)&&i.length!==void 0}),t._zod.onattach.push(n=>{let i=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>i&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let i=n.value;if(i.length>=e.minimum)return;let s=nf(i);n.issues.push({origin:s,code:"too_small",minimum:e.minimum,inclusive:!0,input:i,inst:t,continue:!e.abort})}}),bT=N("$ZodCheckLengthEquals",(t,e)=>{var r;or.init(t,e),(r=t._zod.def).when??(r.when=n=>{let i=n.value;return!tf(i)&&i.length!==void 0}),t._zod.onattach.push(n=>{let i=n._zod.bag;i.minimum=e.length,i.maximum=e.length,i.length=e.length}),t._zod.check=n=>{let i=n.value,o=i.length;if(o===e.length)return;let s=nf(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:t,continue:!e.abort})}}),lf=N("$ZodCheckStringFormat",(t,e)=>{var r,n;or.init(t,e),t._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?(r=t._zod).check??(r.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:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),wT=N("$ZodCheckRegex",(t,e)=>{lf.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),xT=N("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=pT),lf.init(t,e)}),$T=N("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=mT),lf.init(t,e)}),kT=N("$ZodCheckIncludes",(t,e)=>{or.init(t,e);let r=zi(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(i=>{let o=i._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),t._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:t,continue:!e.abort})}}),ST=N("$ZodCheckStartsWith",(t,e)=>{or.init(t,e);let r=new RegExp(`^${zi(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let i=n._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),t._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:t,continue:!e.abort})}}),IT=N("$ZodCheckEndsWith",(t,e)=>{or.init(t,e);let r=new RegExp(`.*${zi(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let i=n._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),t._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:t,continue:!e.abort})}});var ET=N("$ZodCheckOverwrite",(t,e)=>{or.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});var Gh=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(`
|
|
73
|
+
`).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,r=this?.args,i=[...(this?.content??[""]).map(o=>` ${o}`)];return new e(...r,i.join(`
|
|
74
|
+
`))}};var TT={major:4,minor:1,patch:13};var st=N("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=TT;let n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(let i of n)for(let o of i._zod.onattach)o(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let i=(s,a,l)=>{let c=ms(s),u;for(let d of a){if(d._zod.def.when){if(!d._zod.def.when(s))continue}else if(c)continue;let p=s.issues.length,f=d._zod.check(s);if(f instanceof Promise&&l?.async===!1)throw new Ai;if(u||f instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await f,s.issues.length!==p&&(c||(c=ms(s,p)))});else{if(s.issues.length===p)continue;c||(c=ms(s,p))}}return u?u.then(()=>s):s},o=(s,a,l)=>{if(ms(s))return s.aborted=!0,s;let c=i(a,n,l);if(c instanceof Promise){if(l.async===!1)throw new Ai;return c.then(u=>t._zod.parse(u,l))}return t._zod.parse(c,l)};t._zod.run=(s,a)=>{if(a.skipChecks)return t._zod.parse(s,a);if(a.direction==="backward"){let c=t._zod.parse({value:s.value,issues:[]},{...a,skipChecks:!0});return c instanceof Promise?c.then(u=>o(u,s,a)):o(c,s,a)}let l=t._zod.parse(s,a);if(l instanceof Promise){if(a.async===!1)throw new Ai;return l.then(c=>i(c,n,a))}return i(l,n,a)}}t["~standard"]={validate:i=>{try{let o=Vc(t,i);return o.success?{value:o.data}:{issues:o.error?.issues}}catch{return af(t,i).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}}),qc=N("$ZodString",(t,e)=>{st.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??aT(t._zod.bag),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),yt=N("$ZodStringFormat",(t,e)=>{lf.init(t,e),qc.init(t,e)}),Kb=N("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=GP),yt.init(t,e)}),Jb=N("$ZodUUID",(t,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=Wb(n))}else e.pattern??(e.pattern=Wb());yt.init(t,e)}),Yb=N("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=HP),yt.init(t,e)}),Qb=N("$ZodURL",(t,e)=>{yt.init(t,e),t._zod.check=r=>{try{let n=r.value.trim(),i=new URL(n);e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(i.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:e.hostname.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),e.normalize?r.value=i.href:r.value=n;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),ew=N("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=XP()),yt.init(t,e)}),tw=N("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=WP),yt.init(t,e)}),rw=N("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=UP),yt.init(t,e)}),nw=N("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=ZP),yt.init(t,e)}),iw=N("$ZodULID",(t,e)=>{e.pattern??(e.pattern=FP),yt.init(t,e)}),ow=N("$ZodXID",(t,e)=>{e.pattern??(e.pattern=VP),yt.init(t,e)}),sw=N("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=qP),yt.init(t,e)}),aw=N("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=sT(e)),yt.init(t,e)}),lw=N("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=nT),yt.init(t,e)}),cw=N("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=oT(e)),yt.init(t,e)}),uw=N("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=BP),yt.init(t,e)}),dw=N("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=KP),yt.init(t,e),t._zod.bag.format="ipv4"}),fw=N("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=JP),yt.init(t,e),t._zod.bag.format="ipv6",t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}});var pw=N("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=YP),yt.init(t,e)}),mw=N("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=QP),yt.init(t,e),t._zod.check=r=>{let n=r.value.split("/");try{if(n.length!==2)throw new Error;let[i,o]=n;if(!o)throw new Error;let s=Number(o);if(`${s}`!==o)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${i}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});function UT(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var hw=N("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=eT),yt.init(t,e),t._zod.bag.contentEncoding="base64",t._zod.check=r=>{UT(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});function xU(t){if(!Bb.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return UT(r)}var gw=N("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Bb),yt.init(t,e),t._zod.bag.contentEncoding="base64url",t._zod.check=r=>{xU(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),yw=N("$ZodE164",(t,e)=>{e.pattern??(e.pattern=tT),yt.init(t,e)});function $U(t,e=null){try{let r=t.split(".");if(r.length!==3)return!1;let[n]=r;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 vw=N("$ZodJWT",(t,e)=>{yt.init(t,e),t._zod.check=r=>{$U(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}});var Kh=N("$ZodNumber",(t,e)=>{st.init(t,e),t._zod.pattern=t._zod.bag.pattern??uT,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}let i=r.value;if(typeof i=="number"&&!Number.isNaN(i)&&Number.isFinite(i))return r;let o=typeof i=="number"?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:i,inst:t,...o?{received:o}:{}}),r}}),_w=N("$ZodNumberFormat",(t,e)=>{yT.init(t,e),Kh.init(t,e)}),Jh=N("$ZodBoolean",(t,e)=>{st.init(t,e),t._zod.pattern=dT,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=!!r.value}catch{}let i=r.value;return typeof i=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:t}),r}}),bw=N("$ZodBigInt",(t,e)=>{st.init(t,e),t._zod.pattern=lT,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=BigInt(r.value)}catch{}return typeof r.value=="bigint"||r.issues.push({expected:"bigint",code:"invalid_type",input:r.value,inst:t}),r}});var ww=N("$ZodNull",(t,e)=>{st.init(t,e),t._zod.pattern=fT,t._zod.values=new Set([null]),t._zod.parse=(r,n)=>{let i=r.value;return i===null||r.issues.push({expected:"null",code:"invalid_type",input:i,inst:t}),r}}),xw=N("$ZodAny",(t,e)=>{st.init(t,e),t._zod.parse=r=>r}),$w=N("$ZodUnknown",(t,e)=>{st.init(t,e),t._zod.parse=r=>r}),kw=N("$ZodNever",(t,e)=>{st.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});var Sw=N("$ZodDate",(t,e)=>{st.init(t,e),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=new Date(r.value)}catch{}let i=r.value,o=i instanceof Date;return o&&!Number.isNaN(i.getTime())||r.issues.push({expected:"date",code:"invalid_type",input:i,...o?{received:"Invalid Date"}:{},inst:t}),r}});function AT(t,e,r){t.issues.length&&e.issues.push(...vo(r,t.issues)),e.value[r]=t.value}var Iw=N("$ZodArray",(t,e)=>{st.init(t,e),t._zod.parse=(r,n)=>{let i=r.value;if(!Array.isArray(i))return r.issues.push({expected:"array",code:"invalid_type",input:i,inst:t}),r;r.value=Array(i.length);let o=[];for(let s=0;s<i.length;s++){let a=i[s],l=e.element._zod.run({value:a,issues:[]},n);l instanceof Promise?o.push(l.then(c=>AT(c,r,s))):AT(l,r,s)}return o.length?Promise.all(o).then(()=>r):r}});function Xh(t,e,r,n){t.issues.length&&e.issues.push(...vo(r,t.issues)),t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}function ZT(t){let e=Object.keys(t.shape);for(let n of e)if(!t.shape?.[n]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${n}": expected a Zod schema`);let r=Fb(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(r)}}function FT(t,e,r,n,i,o){let s=[],a=i.keySet,l=i.catchall._zod,c=l.def.type;for(let u in e){if(a.has(u))continue;if(c==="never"){s.push(u);continue}let d=l.run({value:e[u],issues:[]},n);d instanceof Promise?t.push(d.then(p=>Xh(p,r,u,e))):Xh(d,r,u,e)}return s.length&&r.issues.push({code:"unrecognized_keys",keys:s,input:e,inst:o}),t.length?Promise.all(t).then(()=>r):r}var VT=N("$ZodObject",(t,e)=>{if(st.init(t,e),!Object.getOwnPropertyDescriptor(e,"shape")?.get){let a=e.shape;Object.defineProperty(e,"shape",{get:()=>{let l={...a};return Object.defineProperty(e,"shape",{value:l}),l}})}let n=Zc(()=>ZT(e));ut(t._zod,"propValues",()=>{let a=e.shape,l={};for(let c in a){let u=a[c]._zod;if(u.values){l[c]??(l[c]=new Set);for(let d of u.values)l[c].add(d)}}return l});let i=va,o=e.catchall,s;t._zod.parse=(a,l)=>{s??(s=n.value);let c=a.value;if(!i(c))return a.issues.push({expected:"object",code:"invalid_type",input:c,inst:t}),a;a.value={};let u=[],d=s.shape;for(let p of s.keys){let m=d[p]._zod.run({value:c[p],issues:[]},l);m instanceof Promise?u.push(m.then(h=>Xh(h,a,p,c))):Xh(m,a,p,c)}return o?FT(u,c,a,l,n.value,t):u.length?Promise.all(u).then(()=>a):a}}),qT=N("$ZodObjectJIT",(t,e)=>{VT.init(t,e);let r=t._zod.parse,n=Zc(()=>ZT(e)),i=p=>{let f=new Gh(["shape","payload","ctx"]),m=n.value,h=b=>{let E=Uh(b);return`shape[${E}]._zod.run({ value: input[${E}], issues: [] }, ctx)`};f.write("const input = payload.value;");let y=Object.create(null),g=0;for(let b of m.keys)y[b]=`key_${g++}`;f.write("const newResult = {};");for(let b of m.keys){let E=y[b],I=Uh(b);f.write(`const ${E} = ${h(b)};`),f.write(`
|
|
75
|
+
if (${E}.issues.length) {
|
|
76
|
+
payload.issues = payload.issues.concat(${E}.issues.map(iss => ({
|
|
77
|
+
...iss,
|
|
78
|
+
path: iss.path ? [${I}, ...iss.path] : [${I}]
|
|
79
|
+
})));
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
if (${E}.value === undefined) {
|
|
84
|
+
if (${I} in input) {
|
|
85
|
+
newResult[${I}] = undefined;
|
|
86
|
+
}
|
|
87
|
+
} else {
|
|
88
|
+
newResult[${I}] = ${E}.value;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
`)}f.write("payload.value = newResult;"),f.write("return payload;");let _=f.compile();return(b,E)=>_(p,b,E)},o,s=va,a=!jh.jitless,c=a&&Ub.value,u=e.catchall,d;t._zod.parse=(p,f)=>{d??(d=n.value);let m=p.value;return s(m)?a&&c&&f?.async===!1&&f.jitless!==!0?(o||(o=i(e.shape)),p=o(p,f),u?FT([],m,p,f,d,t):p):r(p,f):(p.issues.push({expected:"object",code:"invalid_type",input:m,inst:t}),p)}});function zT(t,e,r,n){for(let o of t)if(o.issues.length===0)return e.value=o.value,e;let i=t.filter(o=>!ms(o));return i.length===1?(e.value=i[0].value,i[0]):(e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(o=>o.issues.map(s=>ni(s,n,Er())))}),e)}var Yh=N("$ZodUnion",(t,e)=>{st.init(t,e),ut(t._zod,"optin",()=>e.options.some(i=>i._zod.optin==="optional")?"optional":void 0),ut(t._zod,"optout",()=>e.options.some(i=>i._zod.optout==="optional")?"optional":void 0),ut(t._zod,"values",()=>{if(e.options.every(i=>i._zod.values))return new Set(e.options.flatMap(i=>Array.from(i._zod.values)))}),ut(t._zod,"pattern",()=>{if(e.options.every(i=>i._zod.pattern)){let i=e.options.map(o=>o._zod.pattern);return new RegExp(`^(${i.map(o=>rf(o.source)).join("|")})$`)}});let r=e.options.length===1,n=e.options[0]._zod.run;t._zod.parse=(i,o)=>{if(r)return n(i,o);let s=!1,a=[];for(let l of e.options){let c=l._zod.run({value:i.value,issues:[]},o);if(c instanceof Promise)a.push(c),s=!0;else{if(c.issues.length===0)return c;a.push(c)}}return s?Promise.all(a).then(l=>zT(l,i,t,o)):zT(a,i,t,o)}}),Ew=N("$ZodDiscriminatedUnion",(t,e)=>{Yh.init(t,e);let r=t._zod.parse;ut(t._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,l]of Object.entries(s)){i[a]||(i[a]=new Set);for(let c of l)i[a].add(c)}}return i});let n=Zc(()=>{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 l of a){if(o.has(l))throw new Error(`Duplicate discriminator value "${String(l)}"`);o.set(l,s)}}return o});t._zod.parse=(i,o)=>{let s=i.value;if(!va(s))return i.issues.push({code:"invalid_type",expected:"object",input:s,inst:t}),i;let a=n.value.get(s?.[e.discriminator]);return a?a._zod.run(i,o):e.unionFallback?r(i,o):(i.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:e.discriminator,input:s,path:[e.discriminator],inst:t}),i)}}),Pw=N("$ZodIntersection",(t,e)=>{st.init(t,e),t._zod.parse=(r,n)=>{let i=r.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(([l,c])=>CT(r,l,c)):CT(r,o,s)}});function Xb(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(ps(t)&&ps(e)){let r=Object.keys(e),n=Object.keys(t).filter(o=>r.indexOf(o)!==-1),i={...t,...e};for(let o of n){let s=Xb(t[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(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<t.length;n++){let i=t[n],o=e[n],s=Xb(i,o);if(!s.valid)return{valid:!1,mergeErrorPath:[n,...s.mergeErrorPath]};r.push(s.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function CT(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),ms(t))return t;let n=Xb(e.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return t.value=n.data,t}var Tw=N("$ZodRecord",(t,e)=>{st.init(t,e),t._zod.parse=(r,n)=>{let i=r.value;if(!ps(i))return r.issues.push({expected:"record",code:"invalid_type",input:i,inst:t}),r;let o=[],s=e.keyType._zod.values;if(s){r.value={};let a=new Set;for(let c of s)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){a.add(typeof c=="number"?c.toString():c);let u=e.valueType._zod.run({value:i[c],issues:[]},n);u instanceof Promise?o.push(u.then(d=>{d.issues.length&&r.issues.push(...vo(c,d.issues)),r.value[c]=d.value})):(u.issues.length&&r.issues.push(...vo(c,u.issues)),r.value[c]=u.value)}let l;for(let c in i)a.has(c)||(l=l??[],l.push(c));l&&l.length>0&&r.issues.push({code:"unrecognized_keys",input:i,inst:t,keys:l})}else{r.value={};for(let a of Reflect.ownKeys(i)){if(a==="__proto__")continue;let l=e.keyType._zod.run({value:a,issues:[]},n);if(l instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(l.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map(u=>ni(u,n,Er())),input:a,path:[a],inst:t}),r.value[l.value]=l.value;continue}let c=e.valueType._zod.run({value:i[a],issues:[]},n);c instanceof Promise?o.push(c.then(u=>{u.issues.length&&r.issues.push(...vo(a,u.issues)),r.value[l.value]=u.value})):(c.issues.length&&r.issues.push(...vo(a,c.issues)),r.value[l.value]=c.value)}}return o.length?Promise.all(o).then(()=>r):r}});var Aw=N("$ZodEnum",(t,e)=>{st.init(t,e);let r=Lh(e.entries),n=new Set(r);t._zod.values=n,t._zod.pattern=new RegExp(`^(${r.filter(i=>Zb.has(typeof i)).map(i=>typeof i=="string"?zi(i):i.toString()).join("|")})$`),t._zod.parse=(i,o)=>{let s=i.value;return n.has(s)||i.issues.push({code:"invalid_value",values:r,input:s,inst:t}),i}}),zw=N("$ZodLiteral",(t,e)=>{if(st.init(t,e),e.values.length===0)throw new Error("Cannot create literal schema with no valid values");let r=new Set(e.values);t._zod.values=r,t._zod.pattern=new RegExp(`^(${e.values.map(n=>typeof n=="string"?zi(n):n?zi(n.toString()):String(n)).join("|")})$`),t._zod.parse=(n,i)=>{let o=n.value;return r.has(o)||n.issues.push({code:"invalid_value",values:e.values,input:o,inst:t}),n}});var Cw=N("$ZodTransform",(t,e)=>{st.init(t,e),t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Lc(t.constructor.name);let i=e.transform(r.value,r);if(n.async)return(i instanceof Promise?i:Promise.resolve(i)).then(s=>(r.value=s,r));if(i instanceof Promise)throw new Ai;return r.value=i,r}});function NT(t,e){return t.issues.length&&e===void 0?{issues:[],value:void 0}:t}var Nw=N("$ZodOptional",(t,e)=>{st.init(t,e),t._zod.optin="optional",t._zod.optout="optional",ut(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),ut(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${rf(r.source)})?$`):void 0}),t._zod.parse=(r,n)=>{if(e.innerType._zod.optin==="optional"){let i=e.innerType._zod.run(r,n);return i instanceof Promise?i.then(o=>NT(o,r.value)):NT(i,r.value)}return r.value===void 0?r:e.innerType._zod.run(r,n)}}),Ow=N("$ZodNullable",(t,e)=>{st.init(t,e),ut(t._zod,"optin",()=>e.innerType._zod.optin),ut(t._zod,"optout",()=>e.innerType._zod.optout),ut(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${rf(r.source)}|null)$`):void 0}),ut(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),Rw=N("$ZodDefault",(t,e)=>{st.init(t,e),t._zod.optin="optional",ut(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(n.direction==="backward")return e.innerType._zod.run(r,n);if(r.value===void 0)return r.value=e.defaultValue,r;let i=e.innerType._zod.run(r,n);return i instanceof Promise?i.then(o=>OT(o,e)):OT(i,e)}});function OT(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var Mw=N("$ZodPrefault",(t,e)=>{st.init(t,e),t._zod.optin="optional",ut(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(n.direction==="backward"||r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),jw=N("$ZodNonOptional",(t,e)=>{st.init(t,e),ut(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{let i=e.innerType._zod.run(r,n);return i instanceof Promise?i.then(o=>RT(o,t)):RT(i,t)}});function RT(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}var Dw=N("$ZodCatch",(t,e)=>{st.init(t,e),ut(t._zod,"optin",()=>e.innerType._zod.optin),ut(t._zod,"optout",()=>e.innerType._zod.optout),ut(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(n.direction==="backward")return e.innerType._zod.run(r,n);let i=e.innerType._zod.run(r,n);return i instanceof Promise?i.then(o=>(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>ni(s,n,Er()))},input:r.value}),r.issues=[]),r)):(r.value=i.value,i.issues.length&&(r.value=e.catchValue({...r,error:{issues:i.issues.map(o=>ni(o,n,Er()))},input:r.value}),r.issues=[]),r)}});var Lw=N("$ZodPipe",(t,e)=>{st.init(t,e),ut(t._zod,"values",()=>e.in._zod.values),ut(t._zod,"optin",()=>e.in._zod.optin),ut(t._zod,"optout",()=>e.out._zod.optout),ut(t._zod,"propValues",()=>e.in._zod.propValues),t._zod.parse=(r,n)=>{if(n.direction==="backward"){let o=e.out._zod.run(r,n);return o instanceof Promise?o.then(s=>Hh(s,e.in,n)):Hh(o,e.in,n)}let i=e.in._zod.run(r,n);return i instanceof Promise?i.then(o=>Hh(o,e.out,n)):Hh(i,e.out,n)}});function Hh(t,e,r){return t.issues.length?(t.aborted=!0,t):e._zod.run({value:t.value,issues:t.issues},r)}var Uw=N("$ZodReadonly",(t,e)=>{st.init(t,e),ut(t._zod,"propValues",()=>e.innerType._zod.propValues),ut(t._zod,"values",()=>e.innerType._zod.values),ut(t._zod,"optin",()=>e.innerType?._zod?.optin),ut(t._zod,"optout",()=>e.innerType?._zod?.optout),t._zod.parse=(r,n)=>{if(n.direction==="backward")return e.innerType._zod.run(r,n);let i=e.innerType._zod.run(r,n);return i instanceof Promise?i.then(MT):MT(i)}});function MT(t){return t.value=Object.freeze(t.value),t}var Zw=N("$ZodCustom",(t,e)=>{or.init(t,e),st.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,i=e.fn(n);if(i instanceof Promise)return i.then(o=>jT(o,r,n,t));jT(i,r,n,t)}});function jT(t,e,r,n){if(!t){let i={code:"custom",input:r,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(Fc(i))}}var SU=t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},IU=()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function e(n){return t[n]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return n=>{switch(n.code){case"invalid_type":return`Invalid input: expected ${n.expected}, received ${SU(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${_e(n.values[0])}`:`Invalid option: expected one of ${ve(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 ${r[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":""}: ${ve(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 Fw(){return{localeError:IU()}}var WT,BT=Symbol("ZodOutput"),GT=Symbol("ZodInput"),Qh=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...r){let n=r[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 WeakMap,this._idmap=new Map,this}remove(e){let r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){let r=e._zod.parent;if(r){let n={...this.get(r)??{}};delete n.id;let i={...n,...this._map.get(e)};return Object.keys(i).length?i:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function qw(){return new Qh}(WT=globalThis).__zod_globalRegistry??(WT.__zod_globalRegistry=qw());var _o=globalThis.__zod_globalRegistry;function Ww(t,e){return new t({type:"string",...de(e)})}function Bw(t,e){return new t({type:"string",coerce:!0,...de(e)})}function Gw(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...de(e)})}function eg(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...de(e)})}function Hw(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...de(e)})}function Xw(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...de(e)})}function Kw(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...de(e)})}function Jw(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...de(e)})}function tg(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...de(e)})}function Yw(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...de(e)})}function Qw(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...de(e)})}function e0(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...de(e)})}function t0(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...de(e)})}function r0(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...de(e)})}function n0(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...de(e)})}function i0(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...de(e)})}function o0(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...de(e)})}function s0(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...de(e)})}function a0(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...de(e)})}function l0(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...de(e)})}function c0(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...de(e)})}function u0(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...de(e)})}function d0(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...de(e)})}function f0(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...de(e)})}function p0(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...de(e)})}function m0(t,e){return new t({type:"string",format:"date",check:"string_format",...de(e)})}function h0(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...de(e)})}function g0(t,e){return new t({type:"string",format:"duration",check:"string_format",...de(e)})}function y0(t,e){return new t({type:"number",checks:[],...de(e)})}function v0(t,e){return new t({type:"number",coerce:!0,checks:[],...de(e)})}function _0(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...de(e)})}function b0(t,e){return new t({type:"boolean",...de(e)})}function w0(t,e){return new t({type:"boolean",coerce:!0,...de(e)})}function x0(t,e){return new t({type:"bigint",coerce:!0,...de(e)})}function $0(t,e){return new t({type:"null",...de(e)})}function k0(t){return new t({type:"any"})}function S0(t){return new t({type:"unknown"})}function I0(t,e){return new t({type:"never",...de(e)})}function E0(t,e){return new t({type:"date",coerce:!0,...de(e)})}function ba(t,e){return new Gb({check:"less_than",...de(e),value:t,inclusive:!1})}function ii(t,e){return new Gb({check:"less_than",...de(e),value:t,inclusive:!0})}function wa(t,e){return new Hb({check:"greater_than",...de(e),value:t,inclusive:!1})}function xn(t,e){return new Hb({check:"greater_than",...de(e),value:t,inclusive:!0})}function Wc(t,e){return new gT({check:"multiple_of",...de(e),value:t})}function cf(t,e){return new vT({check:"max_length",...de(e),maximum:t})}function xa(t,e){return new _T({check:"min_length",...de(e),minimum:t})}function uf(t,e){return new bT({check:"length_equals",...de(e),length:t})}function rg(t,e){return new wT({check:"string_format",format:"regex",...de(e),pattern:t})}function ng(t){return new xT({check:"string_format",format:"lowercase",...de(t)})}function ig(t){return new $T({check:"string_format",format:"uppercase",...de(t)})}function og(t,e){return new kT({check:"string_format",format:"includes",...de(e),includes:t})}function sg(t,e){return new ST({check:"string_format",format:"starts_with",...de(e),prefix:t})}function ag(t,e){return new IT({check:"string_format",format:"ends_with",...de(e),suffix:t})}function bo(t){return new ET({check:"overwrite",tx:t})}function lg(t){return bo(e=>e.normalize(t))}function cg(){return bo(t=>t.trim())}function ug(){return bo(t=>t.toLowerCase())}function dg(){return bo(t=>t.toUpperCase())}function P0(){return bo(t=>Lb(t))}function XT(t,e,r){return new t({type:"array",element:e,...de(r)})}function T0(t,e,r){let n=de(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function A0(t,e,r){return new t({type:"custom",check:"custom",fn:e,...de(r)})}function z0(t){let e=AU(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(Fc(n,r.value,e._zod.def));else{let i=n;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=e),i.continue??(i.continue=!e._zod.def.abort),r.issues.push(Fc(i))}},t(r.value,r)));return e}function AU(t,e){let r=new or({check:"custom",...de(e)});return r._zod.check=t,r}function Bc(t){return!!t._zod}function si(t,e){return Bc(t)?Vc(t,e):t.safeParse(e)}function fg(t){var e,r;if(!t)return;let n;if(Bc(t)?n=(r=(e=t._zod)===null||e===void 0?void 0:e.def)===null||r===void 0?void 0:r.shape:n=t.shape,!!n){if(typeof n=="function")try{return n()}catch{return}return n}}function nA(t){var e;if(Bc(t)){let s=(e=t._zod)===null||e===void 0?void 0:e.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let n=t._def;if(n){if(n.value!==void 0)return n.value;if(Array.isArray(n.values)&&n.values.length>0)return n.values[0]}let i=t.value;if(i!==void 0)return i}var df={};ed(df,{ZodISODate:()=>O0,ZodISODateTime:()=>C0,ZodISODuration:()=>D0,ZodISOTime:()=>M0,date:()=>R0,datetime:()=>N0,duration:()=>L0,time:()=>j0});var C0=N("ZodISODateTime",(t,e)=>{aw.init(t,e),It.init(t,e)});function N0(t){return p0(C0,t)}var O0=N("ZodISODate",(t,e)=>{lw.init(t,e),It.init(t,e)});function R0(t){return m0(O0,t)}var M0=N("ZodISOTime",(t,e)=>{cw.init(t,e),It.init(t,e)});function j0(t){return h0(M0,t)}var D0=N("ZodISODuration",(t,e)=>{uw.init(t,e),It.init(t,e)});function L0(t){return g0(D0,t)}var oA=(t,e)=>{Fh.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>qh(t,r)},flatten:{value:r=>Vh(t,r)},addIssue:{value:r=>{t.issues.push(r),t.message=JSON.stringify(t.issues,Uc,2)}},addIssues:{value:r=>{t.issues.push(...r),t.message=JSON.stringify(t.issues,Uc,2)}},isEmpty:{get(){return t.issues.length===0}}})},Hme=N("ZodError",oA),$n=N("ZodError",oA,{Parent:Error});var sA=Wh($n),aA=Bh($n),lA=of($n),cA=sf($n),uA=CP($n),dA=NP($n),fA=OP($n),pA=RP($n),mA=MP($n),hA=jP($n),gA=DP($n),yA=LP($n);var vt=N("ZodType",(t,e)=>(st.init(t,e),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone(X.mergeDefs(e,{checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]})),t.clone=(r,n)=>Yr(t,r,n),t.brand=()=>t,t.register=(r,n)=>(r.add(t,n),t),t.parse=(r,n)=>sA(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>lA(t,r,n),t.parseAsync=async(r,n)=>aA(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>cA(t,r,n),t.spa=t.safeParseAsync,t.encode=(r,n)=>uA(t,r,n),t.decode=(r,n)=>dA(t,r,n),t.encodeAsync=async(r,n)=>fA(t,r,n),t.decodeAsync=async(r,n)=>pA(t,r,n),t.safeEncode=(r,n)=>mA(t,r,n),t.safeDecode=(r,n)=>hA(t,r,n),t.safeEncodeAsync=async(r,n)=>gA(t,r,n),t.safeDecodeAsync=async(r,n)=>yA(t,r,n),t.refine=(r,n)=>t.check(u6(r,n)),t.superRefine=r=>t.check(d6(r)),t.overwrite=r=>t.check(bo(r)),t.optional=()=>ae(t),t.nullable=()=>bA(t),t.nullish=()=>ae(bA(t)),t.nonoptional=r=>i6(t,r),t.array=()=>J(t),t.or=r=>wt([t,r]),t.and=r=>hg(t,r),t.transform=r=>Z0(t,TA(r)),t.default=r=>t6(t,r),t.prefault=r=>n6(t,r),t.catch=r=>s6(t,r),t.pipe=r=>Z0(t,r),t.readonly=()=>c6(t),t.describe=r=>{let n=t.clone();return _o.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return _o.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return _o.get(t);let n=t.clone();return _o.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),wA=N("_ZodString",(t,e)=>{qc.init(t,e),vt.init(t,e);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...n)=>t.check(rg(...n)),t.includes=(...n)=>t.check(og(...n)),t.startsWith=(...n)=>t.check(sg(...n)),t.endsWith=(...n)=>t.check(ag(...n)),t.min=(...n)=>t.check(xa(...n)),t.max=(...n)=>t.check(cf(...n)),t.length=(...n)=>t.check(uf(...n)),t.nonempty=(...n)=>t.check(xa(1,...n)),t.lowercase=n=>t.check(ng(n)),t.uppercase=n=>t.check(ig(n)),t.trim=()=>t.check(cg()),t.normalize=(...n)=>t.check(lg(...n)),t.toLowerCase=()=>t.check(ug()),t.toUpperCase=()=>t.check(dg()),t.slugify=()=>t.check(P0())}),F0=N("ZodString",(t,e)=>{qc.init(t,e),wA.init(t,e),t.email=r=>t.check(Gw(SZ,r)),t.url=r=>t.check(tg(xA,r)),t.jwt=r=>t.check(f0(UZ,r)),t.emoji=r=>t.check(Yw(IZ,r)),t.guid=r=>t.check(eg(vA,r)),t.uuid=r=>t.check(Hw(pg,r)),t.uuidv4=r=>t.check(Xw(pg,r)),t.uuidv6=r=>t.check(Kw(pg,r)),t.uuidv7=r=>t.check(Jw(pg,r)),t.nanoid=r=>t.check(Qw(EZ,r)),t.guid=r=>t.check(eg(vA,r)),t.cuid=r=>t.check(e0(PZ,r)),t.cuid2=r=>t.check(t0(TZ,r)),t.ulid=r=>t.check(r0(AZ,r)),t.base64=r=>t.check(c0(jZ,r)),t.base64url=r=>t.check(u0(DZ,r)),t.xid=r=>t.check(n0(zZ,r)),t.ksuid=r=>t.check(i0(CZ,r)),t.ipv4=r=>t.check(o0(NZ,r)),t.ipv6=r=>t.check(s0(OZ,r)),t.cidrv4=r=>t.check(a0(RZ,r)),t.cidrv6=r=>t.check(l0(MZ,r)),t.e164=r=>t.check(d0(LZ,r)),t.datetime=r=>t.check(N0(r)),t.date=r=>t.check(R0(r)),t.time=r=>t.check(j0(r)),t.duration=r=>t.check(L0(r))});function $(t){return Ww(F0,t)}var It=N("ZodStringFormat",(t,e)=>{yt.init(t,e),wA.init(t,e)}),SZ=N("ZodEmail",(t,e)=>{Yb.init(t,e),It.init(t,e)});var vA=N("ZodGUID",(t,e)=>{Kb.init(t,e),It.init(t,e)});var pg=N("ZodUUID",(t,e)=>{Jb.init(t,e),It.init(t,e)});var xA=N("ZodURL",(t,e)=>{Qb.init(t,e),It.init(t,e)});function $A(t){return tg(xA,t)}var IZ=N("ZodEmoji",(t,e)=>{ew.init(t,e),It.init(t,e)});var EZ=N("ZodNanoID",(t,e)=>{tw.init(t,e),It.init(t,e)});var PZ=N("ZodCUID",(t,e)=>{rw.init(t,e),It.init(t,e)});var TZ=N("ZodCUID2",(t,e)=>{nw.init(t,e),It.init(t,e)});var AZ=N("ZodULID",(t,e)=>{iw.init(t,e),It.init(t,e)});var zZ=N("ZodXID",(t,e)=>{ow.init(t,e),It.init(t,e)});var CZ=N("ZodKSUID",(t,e)=>{sw.init(t,e),It.init(t,e)});var NZ=N("ZodIPv4",(t,e)=>{dw.init(t,e),It.init(t,e)});var OZ=N("ZodIPv6",(t,e)=>{fw.init(t,e),It.init(t,e)});var RZ=N("ZodCIDRv4",(t,e)=>{pw.init(t,e),It.init(t,e)});var MZ=N("ZodCIDRv6",(t,e)=>{mw.init(t,e),It.init(t,e)});var jZ=N("ZodBase64",(t,e)=>{hw.init(t,e),It.init(t,e)});var DZ=N("ZodBase64URL",(t,e)=>{gw.init(t,e),It.init(t,e)});var LZ=N("ZodE164",(t,e)=>{yw.init(t,e),It.init(t,e)});var UZ=N("ZodJWT",(t,e)=>{vw.init(t,e),It.init(t,e)});var mg=N("ZodNumber",(t,e)=>{Kh.init(t,e),vt.init(t,e),t.gt=(n,i)=>t.check(wa(n,i)),t.gte=(n,i)=>t.check(xn(n,i)),t.min=(n,i)=>t.check(xn(n,i)),t.lt=(n,i)=>t.check(ba(n,i)),t.lte=(n,i)=>t.check(ii(n,i)),t.max=(n,i)=>t.check(ii(n,i)),t.int=n=>t.check(_A(n)),t.safe=n=>t.check(_A(n)),t.positive=n=>t.check(wa(0,n)),t.nonnegative=n=>t.check(xn(0,n)),t.negative=n=>t.check(ba(0,n)),t.nonpositive=n=>t.check(ii(0,n)),t.multipleOf=(n,i)=>t.check(Wc(n,i)),t.step=(n,i)=>t.check(Wc(n,i)),t.finite=()=>t;let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});function at(t){return y0(mg,t)}var ZZ=N("ZodNumberFormat",(t,e)=>{_w.init(t,e),mg.init(t,e)});function _A(t){return _0(ZZ,t)}var V0=N("ZodBoolean",(t,e)=>{Jh.init(t,e),vt.init(t,e)});function _t(t){return b0(V0,t)}var kA=N("ZodBigInt",(t,e)=>{bw.init(t,e),vt.init(t,e),t.gte=(n,i)=>t.check(xn(n,i)),t.min=(n,i)=>t.check(xn(n,i)),t.gt=(n,i)=>t.check(wa(n,i)),t.gte=(n,i)=>t.check(xn(n,i)),t.min=(n,i)=>t.check(xn(n,i)),t.lt=(n,i)=>t.check(ba(n,i)),t.lte=(n,i)=>t.check(ii(n,i)),t.max=(n,i)=>t.check(ii(n,i)),t.positive=n=>t.check(wa(BigInt(0),n)),t.negative=n=>t.check(ba(BigInt(0),n)),t.nonpositive=n=>t.check(ii(BigInt(0),n)),t.nonnegative=n=>t.check(xn(BigInt(0),n)),t.multipleOf=(n,i)=>t.check(Wc(n,i));let r=t._zod.bag;t.minValue=r.minimum??null,t.maxValue=r.maximum??null,t.format=r.format??null});var FZ=N("ZodNull",(t,e)=>{ww.init(t,e),vt.init(t,e)});function q0(t){return $0(FZ,t)}var VZ=N("ZodAny",(t,e)=>{xw.init(t,e),vt.init(t,e)});function SA(){return k0(VZ)}var qZ=N("ZodUnknown",(t,e)=>{$w.init(t,e),vt.init(t,e)});function Xt(){return S0(qZ)}var WZ=N("ZodNever",(t,e)=>{kw.init(t,e),vt.init(t,e)});function BZ(t){return I0(WZ,t)}var IA=N("ZodDate",(t,e)=>{Sw.init(t,e),vt.init(t,e),t.min=(n,i)=>t.check(xn(n,i)),t.max=(n,i)=>t.check(ii(n,i));let r=t._zod.bag;t.minDate=r.minimum?new Date(r.minimum):null,t.maxDate=r.maximum?new Date(r.maximum):null});var GZ=N("ZodArray",(t,e)=>{Iw.init(t,e),vt.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(xa(r,n)),t.nonempty=r=>t.check(xa(1,r)),t.max=(r,n)=>t.check(cf(r,n)),t.length=(r,n)=>t.check(uf(r,n)),t.unwrap=()=>t.element});function J(t,e){return XT(GZ,t,e)}var EA=N("ZodObject",(t,e)=>{qT.init(t,e),vt.init(t,e),X.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>mr(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Xt()}),t.loose=()=>t.clone({...t._zod.def,catchall:Xt()}),t.strict=()=>t.clone({...t._zod.def,catchall:BZ()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>X.extend(t,r),t.safeExtend=r=>X.safeExtend(t,r),t.merge=r=>X.merge(t,r),t.pick=r=>X.pick(t,r),t.omit=r=>X.omit(t,r),t.partial=(...r)=>X.partial(AA,t,r[0]),t.required=(...r)=>X.required(zA,t,r[0])});function q(t,e){let r={type:"object",shape:t??{},...X.normalizeParams(e)};return new EA(r)}function Pr(t,e){return new EA({type:"object",shape:t,catchall:Xt(),...X.normalizeParams(e)})}var PA=N("ZodUnion",(t,e)=>{Yh.init(t,e),vt.init(t,e),t.options=e.options});function wt(t,e){return new PA({type:"union",options:t,...X.normalizeParams(e)})}var HZ=N("ZodDiscriminatedUnion",(t,e)=>{PA.init(t,e),Ew.init(t,e)});function W0(t,e,r){return new HZ({type:"union",options:e,discriminator:t,...X.normalizeParams(r)})}var XZ=N("ZodIntersection",(t,e)=>{Pw.init(t,e),vt.init(t,e)});function hg(t,e){return new XZ({type:"intersection",left:t,right:e})}var KZ=N("ZodRecord",(t,e)=>{Tw.init(t,e),vt.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function Kt(t,e,r){return new KZ({type:"record",keyType:t,valueType:e,...X.normalizeParams(r)})}var U0=N("ZodEnum",(t,e)=>{Aw.init(t,e),vt.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,i)=>{let o={};for(let s of n)if(r.has(s))o[s]=e.entries[s];else throw new Error(`Key ${s} not found in enum`);return new U0({...e,checks:[],...X.normalizeParams(i),entries:o})},t.exclude=(n,i)=>{let o={...e.entries};for(let s of n)if(r.has(s))delete o[s];else throw new Error(`Key ${s} not found in enum`);return new U0({...e,checks:[],...X.normalizeParams(i),entries:o})}});function mr(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new U0({type:"enum",entries:r,...X.normalizeParams(e)})}var JZ=N("ZodLiteral",(t,e)=>{zw.init(t,e),vt.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function se(t,e){return new JZ({type:"literal",values:Array.isArray(t)?t:[t],...X.normalizeParams(e)})}var YZ=N("ZodTransform",(t,e)=>{Cw.init(t,e),vt.init(t,e),t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Lc(t.constructor.name);r.addIssue=o=>{if(typeof o=="string")r.issues.push(X.issue(o,r.value,e));else{let s=o;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=t),r.issues.push(X.issue(s))}};let i=e.transform(r.value,r);return i instanceof Promise?i.then(o=>(r.value=o,r)):(r.value=i,r)}});function TA(t){return new YZ({type:"transform",transform:t})}var AA=N("ZodOptional",(t,e)=>{Nw.init(t,e),vt.init(t,e),t.unwrap=()=>t._zod.def.innerType});function ae(t){return new AA({type:"optional",innerType:t})}var QZ=N("ZodNullable",(t,e)=>{Ow.init(t,e),vt.init(t,e),t.unwrap=()=>t._zod.def.innerType});function bA(t){return new QZ({type:"nullable",innerType:t})}var e6=N("ZodDefault",(t,e)=>{Rw.init(t,e),vt.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function t6(t,e){return new e6({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():X.shallowClone(e)}})}var r6=N("ZodPrefault",(t,e)=>{Mw.init(t,e),vt.init(t,e),t.unwrap=()=>t._zod.def.innerType});function n6(t,e){return new r6({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():X.shallowClone(e)}})}var zA=N("ZodNonOptional",(t,e)=>{jw.init(t,e),vt.init(t,e),t.unwrap=()=>t._zod.def.innerType});function i6(t,e){return new zA({type:"nonoptional",innerType:t,...X.normalizeParams(e)})}var o6=N("ZodCatch",(t,e)=>{Dw.init(t,e),vt.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function s6(t,e){return new o6({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var a6=N("ZodPipe",(t,e)=>{Lw.init(t,e),vt.init(t,e),t.in=e.in,t.out=e.out});function Z0(t,e){return new a6({type:"pipe",in:t,out:e})}var l6=N("ZodReadonly",(t,e)=>{Uw.init(t,e),vt.init(t,e),t.unwrap=()=>t._zod.def.innerType});function c6(t){return new l6({type:"readonly",innerType:t})}var CA=N("ZodCustom",(t,e)=>{Zw.init(t,e),vt.init(t,e)});function NA(t,e){return T0(CA,t??(()=>!0),e)}function u6(t,e={}){return A0(CA,t,e)}function d6(t){return z0(t)}function B0(t,e){return Z0(TA(t),e)}var RA={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};var OA;OA||(OA={});var gg={};ed(gg,{bigint:()=>h6,boolean:()=>m6,date:()=>g6,number:()=>p6,string:()=>f6});function f6(t){return Bw(F0,t)}function p6(t){return v0(mg,t)}function m6(t){return w0(V0,t)}function h6(t){return x0(kA,t)}function g6(t){return E0(IA,t)}Er(Fw());var Hc="2025-11-25";var jA=[Hc,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Ni="io.modelcontextprotocol/related-task",vg="2.0",Ci=NA(t=>t!==null&&(typeof t=="object"||typeof t=="function")),DA=wt([$(),at().int()]),LA=$(),v6=Pr({ttl:wt([at(),q0()]).optional(),pollInterval:at().optional()}),H0=Pr({taskId:$()}),_6=Pr({progressToken:DA.optional(),[Ni]:H0.optional()}),Qr=Pr({task:v6.optional(),_meta:_6.optional()}),hr=q({method:$(),params:Qr.optional()}),$a=Pr({_meta:q({[Ni]:ae(H0)}).passthrough().optional()}),Mn=q({method:$(),params:$a.optional()}),Tr=Pr({_meta:Pr({[Ni]:H0.optional()}).optional()}),_g=wt([$(),at().int()]),UA=q({jsonrpc:se(vg),id:_g,...hr.shape}).strict(),ff=t=>UA.safeParse(t).success,ZA=q({jsonrpc:se(vg),...Mn.shape}).strict(),FA=t=>ZA.safeParse(t).success,VA=q({jsonrpc:se(vg),id:_g,result:Tr}).strict(),ka=t=>VA.safeParse(t).success,we;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(we||(we={}));var qA=q({jsonrpc:se(vg),id:_g,error:q({code:at().int(),message:$(),data:ae(Xt())})}).strict(),WA=t=>qA.safeParse(t).success,Xc=wt([UA,ZA,VA,qA]),Sa=Tr.strict(),b6=$a.extend({requestId:_g,reason:$().optional()}),bg=Mn.extend({method:se("notifications/cancelled"),params:b6}),w6=q({src:$(),mimeType:$().optional(),sizes:J($()).optional()}),pf=q({icons:J(w6).optional()}),Gc=q({name:$(),title:$().optional()}),BA=Gc.extend({...Gc.shape,...pf.shape,version:$(),websiteUrl:$().optional()}),x6=hg(q({applyDefaults:_t().optional()}),Kt($(),Xt())),$6=B0(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,hg(q({form:x6.optional(),url:Ci.optional()}),Kt($(),Xt()).optional())),k6=q({list:ae(q({}).passthrough()),cancel:ae(q({}).passthrough()),requests:ae(q({sampling:ae(q({createMessage:ae(q({}).passthrough())}).passthrough()),elicitation:ae(q({create:ae(q({}).passthrough())}).passthrough())}).passthrough())}).passthrough(),S6=q({list:ae(q({}).passthrough()),cancel:ae(q({}).passthrough()),requests:ae(q({tools:ae(q({call:ae(q({}).passthrough())}).passthrough())}).passthrough())}).passthrough(),I6=q({experimental:Kt($(),Ci).optional(),sampling:q({context:Ci.optional(),tools:Ci.optional()}).optional(),elicitation:$6.optional(),roots:q({listChanged:_t().optional()}).optional(),tasks:ae(k6)}),E6=Qr.extend({protocolVersion:$(),capabilities:I6,clientInfo:BA}),P6=hr.extend({method:se("initialize"),params:E6});var T6=q({experimental:Kt($(),Ci).optional(),logging:Ci.optional(),completions:Ci.optional(),prompts:ae(q({listChanged:ae(_t())})),resources:q({subscribe:_t().optional(),listChanged:_t().optional()}).optional(),tools:q({listChanged:_t().optional()}).optional(),tasks:ae(S6)}).passthrough(),X0=Tr.extend({protocolVersion:$(),capabilities:T6,serverInfo:BA,instructions:$().optional()}),GA=Mn.extend({method:se("notifications/initialized")}),HA=t=>GA.safeParse(t).success,wg=hr.extend({method:se("ping")}),A6=q({progress:at(),total:ae(at()),message:ae($())}),z6=q({...$a.shape,...A6.shape,progressToken:DA}),xg=Mn.extend({method:se("notifications/progress"),params:z6}),C6=Qr.extend({cursor:LA.optional()}),mf=hr.extend({params:C6.optional()}),hf=Tr.extend({nextCursor:ae(LA)}),gf=q({taskId:$(),status:mr(["working","input_required","completed","failed","cancelled"]),ttl:wt([at(),q0()]),createdAt:$(),lastUpdatedAt:$(),pollInterval:ae(at()),statusMessage:ae($())}),Ia=Tr.extend({task:gf}),N6=$a.merge(gf),yf=Mn.extend({method:se("notifications/tasks/status"),params:N6}),$g=hr.extend({method:se("tasks/get"),params:Qr.extend({taskId:$()})}),kg=Tr.merge(gf),Sg=hr.extend({method:se("tasks/result"),params:Qr.extend({taskId:$()})}),Ig=mf.extend({method:se("tasks/list")}),Eg=hf.extend({tasks:J(gf)}),XA=hr.extend({method:se("tasks/cancel"),params:Qr.extend({taskId:$()})}),KA=Tr.merge(gf),JA=q({uri:$(),mimeType:ae($()),_meta:Kt($(),Xt()).optional()}),YA=JA.extend({text:$()}),K0=$().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),QA=JA.extend({blob:K0}),Kc=q({audience:J(mr(["user","assistant"])).optional(),priority:at().min(0).max(1).optional(),lastModified:df.datetime({offset:!0}).optional()}),ez=q({...Gc.shape,...pf.shape,uri:$(),description:ae($()),mimeType:ae($()),annotations:Kc.optional(),_meta:ae(Pr({}))}),O6=q({...Gc.shape,...pf.shape,uriTemplate:$(),description:ae($()),mimeType:ae($()),annotations:Kc.optional(),_meta:ae(Pr({}))}),R6=mf.extend({method:se("resources/list")}),J0=hf.extend({resources:J(ez)}),M6=mf.extend({method:se("resources/templates/list")}),Y0=hf.extend({resourceTemplates:J(O6)}),Q0=Qr.extend({uri:$()}),j6=Q0,D6=hr.extend({method:se("resources/read"),params:j6}),ex=Tr.extend({contents:J(wt([YA,QA]))}),L6=Mn.extend({method:se("notifications/resources/list_changed")}),U6=Q0,Z6=hr.extend({method:se("resources/subscribe"),params:U6}),F6=Q0,V6=hr.extend({method:se("resources/unsubscribe"),params:F6}),q6=$a.extend({uri:$()}),W6=Mn.extend({method:se("notifications/resources/updated"),params:q6}),B6=q({name:$(),description:ae($()),required:ae(_t())}),G6=q({...Gc.shape,...pf.shape,description:ae($()),arguments:ae(J(B6)),_meta:ae(Pr({}))}),H6=mf.extend({method:se("prompts/list")}),tx=hf.extend({prompts:J(G6)}),X6=Qr.extend({name:$(),arguments:Kt($(),$()).optional()}),K6=hr.extend({method:se("prompts/get"),params:X6}),rx=q({type:se("text"),text:$(),annotations:Kc.optional(),_meta:Kt($(),Xt()).optional()}),nx=q({type:se("image"),data:K0,mimeType:$(),annotations:Kc.optional(),_meta:Kt($(),Xt()).optional()}),ix=q({type:se("audio"),data:K0,mimeType:$(),annotations:Kc.optional(),_meta:Kt($(),Xt()).optional()}),J6=q({type:se("tool_use"),name:$(),id:$(),input:q({}).passthrough(),_meta:ae(q({}).passthrough())}).passthrough(),Y6=q({type:se("resource"),resource:wt([YA,QA]),annotations:Kc.optional(),_meta:Kt($(),Xt()).optional()}),Q6=ez.extend({type:se("resource_link")}),ox=wt([rx,nx,ix,Q6,Y6]),eF=q({role:mr(["user","assistant"]),content:ox}),sx=Tr.extend({description:ae($()),messages:J(eF)}),tF=Mn.extend({method:se("notifications/prompts/list_changed")}),rF=q({title:$().optional(),readOnlyHint:_t().optional(),destructiveHint:_t().optional(),idempotentHint:_t().optional(),openWorldHint:_t().optional()}),nF=q({taskSupport:mr(["required","optional","forbidden"]).optional()}),tz=q({...Gc.shape,...pf.shape,description:$().optional(),inputSchema:q({type:se("object"),properties:Kt($(),Ci).optional(),required:J($()).optional()}).catchall(Xt()),outputSchema:q({type:se("object"),properties:Kt($(),Ci).optional(),required:J($()).optional()}).catchall(Xt()).optional(),annotations:ae(rF),execution:ae(nF),_meta:Kt($(),Xt()).optional()}),iF=mf.extend({method:se("tools/list")}),ax=hf.extend({tools:J(tz)}),Jc=Tr.extend({content:J(ox).default([]),structuredContent:Kt($(),Xt()).optional(),isError:ae(_t())}),mhe=Jc.or(Tr.extend({toolResult:Xt()})),oF=Qr.extend({name:$(),arguments:ae(Kt($(),Xt()))}),sF=hr.extend({method:se("tools/call"),params:oF}),lx=Mn.extend({method:se("notifications/tools/list_changed")}),rz=mr(["debug","info","notice","warning","error","critical","alert","emergency"]),aF=Qr.extend({level:rz}),lF=hr.extend({method:se("logging/setLevel"),params:aF}),cF=$a.extend({level:rz,logger:$().optional(),data:Xt()}),cx=Mn.extend({method:se("notifications/message"),params:cF}),uF=q({name:$().optional()}),dF=q({hints:ae(J(uF)),costPriority:ae(at().min(0).max(1)),speedPriority:ae(at().min(0).max(1)),intelligencePriority:ae(at().min(0).max(1))}),fF=q({mode:ae(mr(["auto","required","none"]))}),pF=q({type:se("tool_result"),toolUseId:$().describe("The unique identifier for the corresponding tool call."),content:J(ox).default([]),structuredContent:q({}).passthrough().optional(),isError:ae(_t()),_meta:ae(q({}).passthrough())}).passthrough(),mF=W0("type",[rx,nx,ix]),yg=W0("type",[rx,nx,ix,J6,pF]),hF=q({role:mr(["user","assistant"]),content:wt([yg,J(yg)]),_meta:ae(q({}).passthrough())}).passthrough(),gF=Qr.extend({messages:J(hF),modelPreferences:dF.optional(),systemPrompt:$().optional(),includeContext:mr(["none","thisServer","allServers"]).optional(),temperature:at().optional(),maxTokens:at().int(),stopSequences:J($()).optional(),metadata:Ci.optional(),tools:ae(J(tz)),toolChoice:ae(fF)}),ux=hr.extend({method:se("sampling/createMessage"),params:gF}),dx=Tr.extend({model:$(),stopReason:ae(mr(["endTurn","stopSequence","maxTokens"]).or($())),role:mr(["user","assistant"]),content:mF}),yF=Tr.extend({model:$(),stopReason:ae(mr(["endTurn","stopSequence","maxTokens","toolUse"]).or($())),role:mr(["user","assistant"]),content:wt([yg,J(yg)])}),vF=q({type:se("boolean"),title:$().optional(),description:$().optional(),default:_t().optional()}),_F=q({type:se("string"),title:$().optional(),description:$().optional(),minLength:at().optional(),maxLength:at().optional(),format:mr(["email","uri","date","date-time"]).optional(),default:$().optional()}),bF=q({type:mr(["number","integer"]),title:$().optional(),description:$().optional(),minimum:at().optional(),maximum:at().optional(),default:at().optional()}),wF=q({type:se("string"),title:$().optional(),description:$().optional(),enum:J($()),default:$().optional()}),xF=q({type:se("string"),title:$().optional(),description:$().optional(),oneOf:J(q({const:$(),title:$()})),default:$().optional()}),$F=q({type:se("string"),title:$().optional(),description:$().optional(),enum:J($()),enumNames:J($()).optional(),default:$().optional()}),kF=wt([wF,xF]),SF=q({type:se("array"),title:$().optional(),description:$().optional(),minItems:at().optional(),maxItems:at().optional(),items:q({type:se("string"),enum:J($())}),default:J($()).optional()}),IF=q({type:se("array"),title:$().optional(),description:$().optional(),minItems:at().optional(),maxItems:at().optional(),items:q({anyOf:J(q({const:$(),title:$()}))}),default:J($()).optional()}),EF=wt([SF,IF]),PF=wt([$F,kF,EF]),TF=wt([PF,vF,_F,bF]),AF=Qr.extend({mode:se("form").optional(),message:$(),requestedSchema:q({type:se("object"),properties:Kt($(),TF),required:J($()).optional()})}),zF=Qr.extend({mode:se("url"),message:$(),elicitationId:$(),url:$().url()}),CF=wt([AF,zF]),fx=hr.extend({method:se("elicitation/create"),params:CF}),NF=$a.extend({elicitationId:$()}),OF=Mn.extend({method:se("notifications/elicitation/complete"),params:NF}),px=Tr.extend({action:mr(["accept","decline","cancel"]),content:B0(t=>t===null?void 0:t,Kt($(),wt([$(),at(),_t(),J($())])).optional())}),RF=q({type:se("ref/resource"),uri:$()});var MF=q({type:se("ref/prompt"),name:$()}),jF=Qr.extend({ref:wt([MF,RF]),argument:q({name:$(),value:$()}),context:q({arguments:Kt($(),$()).optional()}).optional()}),DF=hr.extend({method:se("completion/complete"),params:jF});var mx=Tr.extend({completion:Pr({values:J($()).max(100),total:ae(at().int()),hasMore:ae(_t())})}),LF=q({uri:$().startsWith("file://"),name:$().optional(),_meta:Kt($(),Xt()).optional()}),UF=hr.extend({method:se("roots/list")}),ZF=Tr.extend({roots:J(LF)}),FF=Mn.extend({method:se("notifications/roots/list_changed")}),hhe=wt([wg,P6,DF,lF,K6,H6,R6,M6,D6,Z6,V6,sF,iF,$g,Sg,Ig]),ghe=wt([bg,xg,GA,FF,yf]),yhe=wt([Sa,dx,yF,px,ZF,kg,Eg,Ia]),vhe=wt([wg,ux,fx,UF,$g,Sg,Ig]),_he=wt([bg,xg,cx,W6,L6,lx,tF,yf,OF]),bhe=wt([Sa,X0,mx,sx,tx,J0,Y0,ex,Jc,ax,kg,Eg,Ia]),me=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===we.UrlElicitationRequired&&n){let i=n;if(i.elicitations)return new G0(i.elicitations,r)}return new t(e,r,n)}},G0=class extends me{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(we.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){var e,r;return(r=(e=this.data)===null||e===void 0?void 0:e.elicitations)!==null&&r!==void 0?r:[]}};function hs(t){return t==="completed"||t==="failed"||t==="cancelled"}var VF=Symbol("Let zodToJsonSchema decide on which parser to use");var ege=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function hx(t){let e=fg(t),r=e?.method;if(!r)throw new Error("Schema is missing a method literal");let n=nA(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function gx(t,e){let r=si(t,e);if(!r.success)throw r.error;return r.data}var XF=6e4,Pg=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(bg,r=>{this._oncancel(r)}),this.setNotificationHandler(xg,r=>{this._onprogress(r)}),this.setRequestHandler(wg,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler($g,async(r,n)=>{let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new me(we.InvalidParams,"Failed to retrieve task: Task not found");return{...i}}),this.setRequestHandler(Sg,async(r,n)=>{let i=async()=>{var o;let s=r.params.taskId;if(this._taskMessageQueue){let l;for(;l=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(l.type==="response"||l.type==="error"){let c=l.message,u=c.id,d=this._requestResolvers.get(u);if(d)if(this._requestResolvers.delete(u),l.type==="response")d(c);else{let p=c,f=new me(p.error.code,p.error.message,p.error.data);d(f)}else{let p=l.type==="response"?"Response":"Error";this._onerror(new Error(`${p} handler missing for request ${u}`))}continue}await((o=this._transport)===null||o===void 0?void 0:o.send(l.message,{relatedRequestId:n.requestId}))}}let a=await this._taskStore.getTask(s,n.sessionId);if(!a)throw new me(we.InvalidParams,`Task not found: ${s}`);if(!hs(a.status))return await this._waitForTaskUpdate(s,n.signal),await i();if(hs(a.status)){let l=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...l,_meta:{...l._meta,[Ni]:{taskId:s}}}}return await i()};return await i()}),this.setRequestHandler(Ig,async(r,n)=>{var i;try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks((i=r.params)===null||i===void 0?void 0:i.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new me(we.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(XA,async(r,n)=>{try{let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new me(we.InvalidParams,`Task not found: ${r.params.taskId}`);if(hs(i.status))throw new me(we.InvalidParams,`Cannot cancel task in terminal status: ${i.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new me(we.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...o}}catch(i){throw i instanceof me?i:new me(we.InvalidRequest,`Failed to cancel task: ${i instanceof Error?i.message:String(i)}`)}}))}async _oncancel(e){let r=this._requestHandlerAbortControllers.get(e.params.requestId);r?.abort(e.params.reason)}_setupTimeout(e,r,n,i,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(i,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:o,onTimeout:i})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),me.fromError(we.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){var r,n,i;this._transport=e;let o=(r=this.transport)===null||r===void 0?void 0:r.onclose;this._transport.onclose=()=>{o?.(),this._onclose()};let s=(n=this.transport)===null||n===void 0?void 0:n.onerror;this._transport.onerror=l=>{s?.(l),this._onerror(l)};let a=(i=this._transport)===null||i===void 0?void 0:i.onmessage;this._transport.onmessage=(l,c)=>{a?.(l,c),ka(l)||WA(l)?this._onresponse(l):ff(l)?this._onrequest(l,c):FA(l)?this._onnotification(l):this._onerror(new Error(`Unknown message type: ${JSON.stringify(l)}`))},await this._transport.start()}_onclose(){var e;let r=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();let n=me.fromError(we.ConnectionClosed,"Connection closed");this._transport=void 0,(e=this.onclose)===null||e===void 0||e.call(this);for(let i of r.values())i(n)}_onerror(e){var r;(r=this.onerror)===null||r===void 0||r.call(this,e)}_onnotification(e){var r;let n=(r=this._notificationHandlers.get(e.method))!==null&&r!==void 0?r:this.fallbackNotificationHandler;n!==void 0&&Promise.resolve().then(()=>n(e)).catch(i=>this._onerror(new Error(`Uncaught error in notification handler: ${i}`)))}_onrequest(e,r){var n,i,o,s,a,l;let c=(n=this._requestHandlers.get(e.method))!==null&&n!==void 0?n:this.fallbackRequestHandler,u=this._transport,d=(s=(o=(i=e.params)===null||i===void 0?void 0:i._meta)===null||o===void 0?void 0:o[Ni])===null||s===void 0?void 0:s.taskId;if(c===void 0){let y={jsonrpc:"2.0",id:e.id,error:{code:we.MethodNotFound,message:"Method not found"}};d&&this._taskMessageQueue?this._enqueueTaskMessage(d,{type:"error",message:y,timestamp:Date.now()},u?.sessionId).catch(g=>this._onerror(new Error(`Failed to enqueue error response: ${g}`))):u?.send(y).catch(g=>this._onerror(new Error(`Failed to send an error response: ${g}`)));return}let p=new AbortController;this._requestHandlerAbortControllers.set(e.id,p);let f=(a=e.params)===null||a===void 0?void 0:a.task,m=this._taskStore?this.requestTaskStore(e,u?.sessionId):void 0,h={signal:p.signal,sessionId:u?.sessionId,_meta:(l=e.params)===null||l===void 0?void 0:l._meta,sendNotification:async y=>{let g={relatedRequestId:e.id};d&&(g.relatedTask={taskId:d}),await this.notification(y,g)},sendRequest:async(y,g,_)=>{var b,E;let I={..._,relatedRequestId:e.id};d&&!I.relatedTask&&(I.relatedTask={taskId:d});let P=(E=(b=I.relatedTask)===null||b===void 0?void 0:b.taskId)!==null&&E!==void 0?E:d;return P&&m&&await m.updateTaskStatus(P,"input_required"),await this.request(y,g,I)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:d,taskStore:m,taskRequestedTtl:f?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{f&&this.assertTaskHandlerCapability(e.method)}).then(()=>c(e,h)).then(async y=>{if(p.signal.aborted)return;let g={result:y,jsonrpc:"2.0",id:e.id};d&&this._taskMessageQueue?await this._enqueueTaskMessage(d,{type:"response",message:g,timestamp:Date.now()},u?.sessionId):await u?.send(g)},async y=>{var g;if(p.signal.aborted)return;let _={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(y.code)?y.code:we.InternalError,message:(g=y.message)!==null&&g!==void 0?g:"Internal error",...y.data!==void 0&&{data:y.data}}};d&&this._taskMessageQueue?await this._enqueueTaskMessage(d,{type:"error",message:_,timestamp:Date.now()},u?.sessionId):await u?.send(_)}).catch(y=>this._onerror(new Error(`Failed to send response: ${y}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,i=Number(r),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(l){this._responseHandlers.delete(i),this._progressHandlers.delete(i),this._cleanupTimeout(i),s(l);return}o(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),ka(e))n(e);else{let s=new me(e.error.code,e.error.message,e.error.data);n(s)}return}let i=this._responseHandlers.get(r);if(i===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let o=!1;if(ka(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,r))}}if(o||this._progressHandlers.delete(r),ka(e))i(e);else{let s=me.fromError(e.error.code,e.error.message,e.error.data);i(s)}}get transport(){return this._transport}async close(){var e;await((e=this._transport)===null||e===void 0?void 0:e.close())}async*requestStream(e,r,n){var i,o,s,a;let{task:l}=n??{};if(!l){try{yield{type:"result",result:await this.request(e,r,n)}}catch(u){yield{type:"error",error:u instanceof me?u:new me(we.InternalError,String(u))}}return}let c;try{let u=await this.request(e,Ia,n);if(u.task)c=u.task.taskId,yield{type:"taskCreated",task:u.task};else throw new me(we.InternalError,"Task creation did not return a task");for(;;){let d=await this.getTask({taskId:c},n);if(yield{type:"taskStatus",task:d},hs(d.status)){d.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:c},r,n)}:d.status==="failed"?yield{type:"error",error:new me(we.InternalError,`Task ${c} failed`)}:d.status==="cancelled"&&(yield{type:"error",error:new me(we.InternalError,`Task ${c} was cancelled`)});return}if(d.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:c},r,n)};return}let p=(s=(i=d.pollInterval)!==null&&i!==void 0?i:(o=this._options)===null||o===void 0?void 0:o.defaultTaskPollInterval)!==null&&s!==void 0?s:1e3;await new Promise(f=>setTimeout(f,p)),(a=n?.signal)===null||a===void 0||a.throwIfAborted()}}catch(u){yield{type:"error",error:u instanceof me?u:new me(we.InternalError,String(u))}}}request(e,r,n){let{relatedRequestId:i,resumptionToken:o,onresumptiontoken:s,task:a,relatedTask:l}=n??{};return new Promise((c,u)=>{var d,p,f,m,h,y,g;let _=R=>{u(R)};if(!this._transport){_(new Error("Not connected"));return}if(((d=this._options)===null||d===void 0?void 0:d.enforceStrictCapabilities)===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(R){_(R);return}(p=n?.signal)===null||p===void 0||p.throwIfAborted();let b=this._requestMessageId++,E={...e,jsonrpc:"2.0",id:b};n?.onprogress&&(this._progressHandlers.set(b,n.onprogress),E.params={...e.params,_meta:{...((f=e.params)===null||f===void 0?void 0:f._meta)||{},progressToken:b}}),a&&(E.params={...E.params,task:a}),l&&(E.params={...E.params,_meta:{...((m=E.params)===null||m===void 0?void 0:m._meta)||{},[Ni]:l}});let I=R=>{var L;this._responseHandlers.delete(b),this._progressHandlers.delete(b),this._cleanupTimeout(b),(L=this._transport)===null||L===void 0||L.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:b,reason:String(R)}},{relatedRequestId:i,resumptionToken:o,onresumptiontoken:s}).catch(H=>this._onerror(new Error(`Failed to send cancellation: ${H}`)));let G=R instanceof me?R:new me(we.RequestTimeout,String(R));u(G)};this._responseHandlers.set(b,R=>{var L;if(!(!((L=n?.signal)===null||L===void 0)&&L.aborted)){if(R instanceof Error)return u(R);try{let G=si(r,R.result);G.success?c(G.data):u(G.error)}catch(G){u(G)}}}),(h=n?.signal)===null||h===void 0||h.addEventListener("abort",()=>{var R;I((R=n?.signal)===null||R===void 0?void 0:R.reason)});let P=(y=n?.timeout)!==null&&y!==void 0?y:XF,M=()=>I(me.fromError(we.RequestTimeout,"Request timed out",{timeout:P}));this._setupTimeout(b,P,n?.maxTotalTimeout,M,(g=n?.resetTimeoutOnProgress)!==null&&g!==void 0?g:!1);let V=l?.taskId;if(V){let R=L=>{let G=this._responseHandlers.get(b);G?G(L):this._onerror(new Error(`Response handler missing for side-channeled request ${b}`))};this._requestResolvers.set(b,R),this._enqueueTaskMessage(V,{type:"request",message:E,timestamp:Date.now()}).catch(L=>{this._cleanupTimeout(b),u(L)})}else this._transport.send(E,{relatedRequestId:i,resumptionToken:o,onresumptiontoken:s}).catch(R=>{this._cleanupTimeout(b),u(R)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},kg,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},Eg,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},KA,r)}async notification(e,r){var n,i,o,s,a;if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let l=(n=r?.relatedTask)===null||n===void 0?void 0:n.taskId;if(l){let p={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...((i=e.params)===null||i===void 0?void 0:i._meta)||{},[Ni]:r.relatedTask}}};await this._enqueueTaskMessage(l,{type:"notification",message:p,timestamp:Date.now()});return}if(((s=(o=this._options)===null||o===void 0?void 0:o.debouncedNotificationMethods)!==null&&s!==void 0?s:[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{var p,f;if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let m={...e,jsonrpc:"2.0"};r?.relatedTask&&(m={...m,params:{...m.params,_meta:{...((p=m.params)===null||p===void 0?void 0:p._meta)||{},[Ni]:r.relatedTask}}}),(f=this._transport)===null||f===void 0||f.send(m,r).catch(h=>this._onerror(h))});return}let d={...e,jsonrpc:"2.0"};r?.relatedTask&&(d={...d,params:{...d.params,_meta:{...((a=d.params)===null||a===void 0?void 0:a._meta)||{},[Ni]:r.relatedTask}}}),await this._transport.send(d,r)}setRequestHandler(e,r){let n=hx(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(i,o)=>{let s=gx(e,i);return Promise.resolve(r(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,r){let n=hx(e);this._notificationHandlers.set(n,i=>{let o=gx(e,i);return Promise.resolve(r(o))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){var i;if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=(i=this._options)===null||i===void 0?void 0:i.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,o)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let i of n)if(i.type==="request"&&ff(i.message)){let o=i.message.id,s=this._requestResolvers.get(o);s?(s(new me(we.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,r){var n,i,o;let s=(i=(n=this._options)===null||n===void 0?void 0:n.defaultTaskPollInterval)!==null&&i!==void 0?i:1e3;try{let a=await((o=this._taskStore)===null||o===void 0?void 0:o.getTask(e));a?.pollInterval&&(s=a.pollInterval)}catch{}return new Promise((a,l)=>{if(r.aborted){l(new me(we.InvalidRequest,"Request cancelled"));return}let c=setTimeout(a,s);r.addEventListener("abort",()=>{clearTimeout(c),l(new me(we.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){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},r)},getTask:async i=>{let o=await n.getTask(i,r);if(!o)throw new me(we.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(i,o,s)=>{await n.storeTaskResult(i,o,s,r);let a=await n.getTask(i,r);if(a){let l=yf.parse({method:"notifications/tasks/status",params:a});await this.notification(l),hs(a.status)&&this._cleanupTaskProgressHandler(i)}},getTaskResult:i=>n.getTaskResult(i,r),updateTaskStatus:async(i,o,s)=>{let a=await n.getTask(i,r);if(!a)throw new me(we.InvalidParams,`Task "${i}" not found - it may have been cleaned up`);if(hs(a.status))throw new me(we.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,r);let l=await n.getTask(i,r);if(l){let c=yf.parse({method:"notifications/tasks/status",params:l});await this.notification(c),hs(l.status)&&this._cleanupTaskProgressHandler(i)}},listTasks:i=>n.listTasks(i,r)}}};function nz(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function iz(t,e){let r={...t};for(let n in e){let i=n,o=e[i];if(o===void 0)continue;let s=r[i];nz(s)&&nz(o)?r[i]={...s,...o}:r[i]=o}return r}var oM=r_(AN(),1),sM=r_(iM(),1);function CK(){let t=new oM.Ajv({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,sM.default)(t),t}var Fy=class{constructor(e){this._ajv=e??CK()}getValidator(e){var r;let n="$id"in e&&typeof e.$id=="string"?(r=this._ajv.getSchema(e.$id))!==null&&r!==void 0?r:this._ajv.compile(e):this._ajv.compile(e);return i=>n(i)?{valid:!0,data:i,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(n.errors)}}};var Vy=class{constructor(e){this._client=e}async*callToolStream(e,r=Jc,n){var i;let o=this._client,s={...n,task:(i=n?.task)!==null&&i!==void 0?i:o.isToolTask(e.name)?{}:void 0},a=o.requestStream({method:"tools/call",params:e},r,s),l=o.getToolOutputValidator(e.name);for await(let c of a){if(c.type==="result"&&l){let u=c.result;if(!u.structuredContent&&!u.isError){yield{type:"error",error:new me(we.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)};return}if(u.structuredContent)try{let d=l(u.structuredContent);if(!d.valid){yield{type:"error",error:new me(we.InvalidParams,`Structured content does not match the tool's output schema: ${d.errorMessage}`)};return}}catch(d){if(d instanceof me){yield{type:"error",error:d};return}yield{type:"error",error:new me(we.InvalidParams,`Failed to validate structured content: ${d instanceof Error?d.message:String(d)}`)};return}}yield c}}async getTask(e,r){return this._client.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._client.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._client.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._client.cancelTask({taskId:e},r)}requestStream(e,r,n){return this._client.requestStream(e,r,n)}};function aM(t,e,r){var n;if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!(!((n=t.tools)===null||n===void 0)&&n.call))throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function lM(t,e,r){var n,i;if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!(!((n=t.sampling)===null||n===void 0)&&n.createMessage))throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!(!((i=t.elicitation)===null||i===void 0)&&i.create))throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}function qy(t,e){if(!(!t||e===null||typeof e!="object")){if(t.type==="object"&&t.properties&&typeof t.properties=="object"){let r=e,n=t.properties;for(let i of Object.keys(n)){let o=n[i];r[i]===void 0&&Object.prototype.hasOwnProperty.call(o,"default")&&(r[i]=o.default),r[i]!==void 0&&qy(o,r[i])}}if(Array.isArray(t.anyOf))for(let r of t.anyOf)qy(r,e);if(Array.isArray(t.oneOf))for(let r of t.oneOf)qy(r,e)}}function NK(t){if(!t)return{supportsFormMode:!1,supportsUrlMode:!1};let e=t.form!==void 0,r=t.url!==void 0;return{supportsFormMode:e||!e&&!r,supportsUrlMode:r}}var $p=class extends Pg{constructor(e,r){var n,i;super(r),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._capabilities=(n=r?.capabilities)!==null&&n!==void 0?n:{},this._jsonSchemaValidator=(i=r?.jsonSchemaValidator)!==null&&i!==void 0?i:new Fy}get experimental(){return this._experimental||(this._experimental={tasks:new Vy(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=iz(this._capabilities,e)}setRequestHandler(e,r){var n,i,o;let s=fg(e),a=s?.method;if(!a)throw new Error("Schema is missing a method literal");let l;if(Bc(a)){let u=a,d=(n=u._zod)===null||n===void 0?void 0:n.def;l=(i=d?.value)!==null&&i!==void 0?i:u.value}else{let u=a,d=u._def;l=(o=d?.value)!==null&&o!==void 0?o:u.value}if(typeof l!="string")throw new Error("Schema method literal must be a string");let c=l;if(c==="elicitation/create"){let u=async(d,p)=>{var f,m,h;let y=si(fx,d);if(!y.success){let R=y.error instanceof Error?y.error.message:String(y.error);throw new me(we.InvalidParams,`Invalid elicitation request: ${R}`)}let{params:g}=y.data,_=(f=g.mode)!==null&&f!==void 0?f:"form",{supportsFormMode:b,supportsUrlMode:E}=NK(this._capabilities.elicitation);if(_==="form"&&!b)throw new me(we.InvalidParams,"Client does not support form-mode elicitation requests");if(_==="url"&&!E)throw new me(we.InvalidParams,"Client does not support URL-mode elicitation requests");let I=await Promise.resolve(r(d,p));if(g.task){let R=si(Ia,I);if(!R.success){let L=R.error instanceof Error?R.error.message:String(R.error);throw new me(we.InvalidParams,`Invalid task creation result: ${L}`)}return R.data}let P=si(px,I);if(!P.success){let R=P.error instanceof Error?P.error.message:String(P.error);throw new me(we.InvalidParams,`Invalid elicitation result: ${R}`)}let M=P.data,V=_==="form"?g.requestedSchema:void 0;if(_==="form"&&M.action==="accept"&&M.content&&V&&!((h=(m=this._capabilities.elicitation)===null||m===void 0?void 0:m.form)===null||h===void 0)&&h.applyDefaults)try{qy(V,M.content)}catch{}return M};return super.setRequestHandler(e,u)}if(c==="sampling/createMessage"){let u=async(d,p)=>{let f=si(ux,d);if(!f.success){let g=f.error instanceof Error?f.error.message:String(f.error);throw new me(we.InvalidParams,`Invalid sampling request: ${g}`)}let{params:m}=f.data,h=await Promise.resolve(r(d,p));if(m.task){let g=si(Ia,h);if(!g.success){let _=g.error instanceof Error?g.error.message:String(g.error);throw new me(we.InvalidParams,`Invalid task creation result: ${_}`)}return g.data}let y=si(dx,h);if(!y.success){let g=y.error instanceof Error?y.error.message:String(y.error);throw new me(we.InvalidParams,`Invalid sampling result: ${g}`)}return y.data};return super.setRequestHandler(e,u)}return super.setRequestHandler(e,r)}assertCapability(e,r){var n;if(!(!((n=this._serverCapabilities)===null||n===void 0)&&n[e]))throw new Error(`Server does not support ${e} (required for ${r})`)}async connect(e,r){if(await super.connect(e),e.sessionId===void 0)try{let n=await this.request({method:"initialize",params:{protocolVersion:Hc,capabilities:this._capabilities,clientInfo:this._clientInfo}},X0,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!jA.includes(n.protocolVersion))throw new Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:"notifications/initialized"})}catch(n){throw this.close(),n}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){var r,n,i,o,s;switch(e){case"logging/setLevel":if(!(!((r=this._serverCapabilities)===null||r===void 0)&&r.logging))throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!(!((n=this._serverCapabilities)===null||n===void 0)&&n.prompts))throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!(!((i=this._serverCapabilities)===null||i===void 0)&&i.resources))throw new Error(`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!(!((o=this._serverCapabilities)===null||o===void 0)&&o.tools))throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!(!((s=this._serverCapabilities)===null||s===void 0)&&s.completions))throw new Error(`Server does not support completions (required for ${e})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(e){var r;switch(e){case"notifications/roots/list_changed":if(!(!((r=this._capabilities.roots)===null||r===void 0)&&r.listChanged))throw new Error(`Client does not support roots list changed notifications (required for ${e})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client does not support tasks capability (required for ${e})`);break;case"ping":break}}assertTaskCapability(e){var r,n;aM((n=(r=this._serverCapabilities)===null||r===void 0?void 0:r.tasks)===null||n===void 0?void 0:n.requests,e,"Server")}assertTaskHandlerCapability(e){var r;this._capabilities&&lM((r=this._capabilities.tasks)===null||r===void 0?void 0:r.requests,e,"Client")}async ping(e){return this.request({method:"ping"},Sa,e)}async complete(e,r){return this.request({method:"completion/complete",params:e},mx,r)}async setLoggingLevel(e,r){return this.request({method:"logging/setLevel",params:{level:e}},Sa,r)}async getPrompt(e,r){return this.request({method:"prompts/get",params:e},sx,r)}async listPrompts(e,r){return this.request({method:"prompts/list",params:e},tx,r)}async listResources(e,r){return this.request({method:"resources/list",params:e},J0,r)}async listResourceTemplates(e,r){return this.request({method:"resources/templates/list",params:e},Y0,r)}async readResource(e,r){return this.request({method:"resources/read",params:e},ex,r)}async subscribeResource(e,r){return this.request({method:"resources/subscribe",params:e},Sa,r)}async unsubscribeResource(e,r){return this.request({method:"resources/unsubscribe",params:e},Sa,r)}async callTool(e,r=Jc,n){if(this.isToolTaskRequired(e.name))throw new me(we.InvalidRequest,`Tool "${e.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let i=await this.request({method:"tools/call",params:e},r,n),o=this.getToolOutputValidator(e.name);if(o){if(!i.structuredContent&&!i.isError)throw new me(we.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(i.structuredContent)try{let s=o(i.structuredContent);if(!s.valid)throw new me(we.InvalidParams,`Structured content does not match the tool's output schema: ${s.errorMessage}`)}catch(s){throw s instanceof me?s:new me(we.InvalidParams,`Failed to validate structured content: ${s instanceof Error?s.message:String(s)}`)}}return i}isToolTask(e){var r,n,i,o;return!((o=(i=(n=(r=this._serverCapabilities)===null||r===void 0?void 0:r.tasks)===null||n===void 0?void 0:n.requests)===null||i===void 0?void 0:i.tools)===null||o===void 0)&&o.call?this._cachedKnownTaskTools.has(e):!1}isToolTaskRequired(e){return this._cachedRequiredTaskTools.has(e)}cacheToolMetadata(e){var r;this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(let n of e){if(n.outputSchema){let o=this._jsonSchemaValidator.getValidator(n.outputSchema);this._cachedToolOutputValidators.set(n.name,o)}let i=(r=n.execution)===null||r===void 0?void 0:r.taskSupport;(i==="required"||i==="optional")&&this._cachedKnownTaskTools.add(n.name),i==="required"&&this._cachedRequiredTaskTools.add(n.name)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,r){let n=await this.request({method:"tools/list",params:e},ax,r);return this.cacheToolMetadata(n.tools),n}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};function Iu(t){return t?t instanceof Headers?Object.fromEntries(t.entries()):Array.isArray(t)?Object.fromEntries(t):{...t}:{}}function Wy(t=fetch,e){return e?async(r,n)=>{let i={...e,...n,headers:n?.headers?{...Iu(e.headers),...Iu(n.headers)}:e.headers};return t(r,i)}:t}var LS;LS=globalThis.crypto;async function OK(t){return(await LS).getRandomValues(new Uint8Array(t))}async function RK(t){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r="",n=await OK(t);for(let i=0;i<t;i++){let o=n[i]%e.length;r+=e[o]}return r}async function MK(t){return await RK(t)}async function jK(t){let e=await(await LS).subtle.digest("SHA-256",new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function US(t){if(t||(t=43),t<43||t>128)throw`Expected a length between 43 and 128. Received ${t}.`;let e=await MK(t),r=await jK(e);return{code_verifier:e,code_challenge:r}}var xr=$A().superRefine((t,e)=>{if(!URL.canParse(t))return e.addIssue({code:RA.custom,message:"URL must be parseable",fatal:!0}),Dh}).refine(t=>{let e=new URL(t);return e.protocol!=="javascript:"&&e.protocol!=="data:"&&e.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),uM=Pr({resource:$().url(),authorization_servers:J(xr).optional(),jwks_uri:$().url().optional(),scopes_supported:J($()).optional(),bearer_methods_supported:J($()).optional(),resource_signing_alg_values_supported:J($()).optional(),resource_name:$().optional(),resource_documentation:$().optional(),resource_policy_uri:$().url().optional(),resource_tos_uri:$().url().optional(),tls_client_certificate_bound_access_tokens:_t().optional(),authorization_details_types_supported:J($()).optional(),dpop_signing_alg_values_supported:J($()).optional(),dpop_bound_access_tokens_required:_t().optional()}),ZS=Pr({issuer:$(),authorization_endpoint:xr,token_endpoint:xr,registration_endpoint:xr.optional(),scopes_supported:J($()).optional(),response_types_supported:J($()),response_modes_supported:J($()).optional(),grant_types_supported:J($()).optional(),token_endpoint_auth_methods_supported:J($()).optional(),token_endpoint_auth_signing_alg_values_supported:J($()).optional(),service_documentation:xr.optional(),revocation_endpoint:xr.optional(),revocation_endpoint_auth_methods_supported:J($()).optional(),revocation_endpoint_auth_signing_alg_values_supported:J($()).optional(),introspection_endpoint:$().optional(),introspection_endpoint_auth_methods_supported:J($()).optional(),introspection_endpoint_auth_signing_alg_values_supported:J($()).optional(),code_challenge_methods_supported:J($()).optional(),client_id_metadata_document_supported:_t().optional()}),DK=Pr({issuer:$(),authorization_endpoint:xr,token_endpoint:xr,userinfo_endpoint:xr.optional(),jwks_uri:xr,registration_endpoint:xr.optional(),scopes_supported:J($()).optional(),response_types_supported:J($()),response_modes_supported:J($()).optional(),grant_types_supported:J($()).optional(),acr_values_supported:J($()).optional(),subject_types_supported:J($()),id_token_signing_alg_values_supported:J($()),id_token_encryption_alg_values_supported:J($()).optional(),id_token_encryption_enc_values_supported:J($()).optional(),userinfo_signing_alg_values_supported:J($()).optional(),userinfo_encryption_alg_values_supported:J($()).optional(),userinfo_encryption_enc_values_supported:J($()).optional(),request_object_signing_alg_values_supported:J($()).optional(),request_object_encryption_alg_values_supported:J($()).optional(),request_object_encryption_enc_values_supported:J($()).optional(),token_endpoint_auth_methods_supported:J($()).optional(),token_endpoint_auth_signing_alg_values_supported:J($()).optional(),display_values_supported:J($()).optional(),claim_types_supported:J($()).optional(),claims_supported:J($()).optional(),service_documentation:$().optional(),claims_locales_supported:J($()).optional(),ui_locales_supported:J($()).optional(),claims_parameter_supported:_t().optional(),request_parameter_supported:_t().optional(),request_uri_parameter_supported:_t().optional(),require_request_uri_registration:_t().optional(),op_policy_uri:xr.optional(),op_tos_uri:xr.optional(),client_id_metadata_document_supported:_t().optional()}),dM=q({...DK.shape,...ZS.pick({code_challenge_methods_supported:!0}).shape}),fM=q({access_token:$(),id_token:$().optional(),token_type:$(),expires_in:gg.number().optional(),scope:$().optional(),refresh_token:$().optional()}).strip(),pM=q({error:$(),error_description:$().optional(),error_uri:$().optional()}),cM=xr.optional().or(se("").transform(()=>{})),LK=q({redirect_uris:J(xr),token_endpoint_auth_method:$().optional(),grant_types:J($()).optional(),response_types:J($()).optional(),client_name:$().optional(),client_uri:xr.optional(),logo_uri:cM,scope:$().optional(),contacts:J($()).optional(),tos_uri:cM,policy_uri:$().optional(),jwks_uri:xr.optional(),jwks:SA().optional(),software_id:$().optional(),software_version:$().optional(),software_statement:$().optional()}).strip(),UK=q({client_id:$(),client_secret:$().optional(),client_id_issued_at:at().optional(),client_secret_expires_at:at().optional()}).strip(),mM=LK.merge(UK),Mwe=q({error:$(),error_description:$().optional()}).strip(),jwe=q({token:$(),token_type_hint:$().optional()}).strip();function hM(t){let e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function gM({requestedResource:t,configuredResource:e}){let r=typeof t=="string"?new URL(t):new URL(t.href),n=typeof e=="string"?new URL(e):new URL(e.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;let i=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",o=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return i.startsWith(o)}var Ut=class extends Error{constructor(e,r){super(e),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){let e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}},kp=class extends Ut{};kp.errorCode="invalid_request";var Ga=class extends Ut{};Ga.errorCode="invalid_client";var Ha=class extends Ut{};Ha.errorCode="invalid_grant";var Xa=class extends Ut{};Xa.errorCode="unauthorized_client";var Sp=class extends Ut{};Sp.errorCode="unsupported_grant_type";var Ip=class extends Ut{};Ip.errorCode="invalid_scope";var Ep=class extends Ut{};Ep.errorCode="access_denied";var zo=class extends Ut{};zo.errorCode="server_error";var Pp=class extends Ut{};Pp.errorCode="temporarily_unavailable";var Tp=class extends Ut{};Tp.errorCode="unsupported_response_type";var Ap=class extends Ut{};Ap.errorCode="unsupported_token_type";var zp=class extends Ut{};zp.errorCode="invalid_token";var Cp=class extends Ut{};Cp.errorCode="method_not_allowed";var Np=class extends Ut{};Np.errorCode="too_many_requests";var Ka=class extends Ut{};Ka.errorCode="invalid_client_metadata";var Op=class extends Ut{};Op.errorCode="insufficient_scope";var Rp=class extends Ut{};Rp.errorCode="invalid_target";var yM={[kp.errorCode]:kp,[Ga.errorCode]:Ga,[Ha.errorCode]:Ha,[Xa.errorCode]:Xa,[Sp.errorCode]:Sp,[Ip.errorCode]:Ip,[Ep.errorCode]:Ep,[zo.errorCode]:zo,[Pp.errorCode]:Pp,[Tp.errorCode]:Tp,[Ap.errorCode]:Ap,[zp.errorCode]:zp,[Cp.errorCode]:Cp,[Np.errorCode]:Np,[Ka.errorCode]:Ka,[Op.errorCode]:Op,[Rp.errorCode]:Rp};var Br=class extends Error{constructor(e){super(e??"Unauthorized")}};function ZK(t){return["client_secret_basic","client_secret_post","none"].includes(t)}var FS="code",VS="S256";function FK(t,e){let r=t.client_secret!==void 0;return e.length===0?r?"client_secret_post":"none":"token_endpoint_auth_method"in t&&t.token_endpoint_auth_method&&ZK(t.token_endpoint_auth_method)&&e.includes(t.token_endpoint_auth_method)?t.token_endpoint_auth_method:r&&e.includes("client_secret_basic")?"client_secret_basic":r&&e.includes("client_secret_post")?"client_secret_post":e.includes("none")?"none":r?"client_secret_post":"none"}function VK(t,e,r,n){let{client_id:i,client_secret:o}=e;switch(t){case"client_secret_basic":qK(i,o,r);return;case"client_secret_post":WK(i,o,n);return;case"none":BK(i,n);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function qK(t,e,r){if(!e)throw new Error("client_secret_basic authentication requires a client_secret");let n=btoa(`${t}:${e}`);r.set("Authorization",`Basic ${n}`)}function WK(t,e,r){r.set("client_id",t),e&&r.set("client_secret",e)}function BK(t,e){e.set("client_id",t)}async function _M(t){let e=t instanceof Response?t.status:void 0,r=t instanceof Response?await t.text():t;try{let n=pM.parse(JSON.parse(r)),{error:i,error_description:o,error_uri:s}=n,a=yM[i]||zo;return new a(o||"",s)}catch(n){let i=`${e?`HTTP ${e}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new zo(i)}}async function Co(t,e){var r,n;try{return await qS(t,e)}catch(i){if(i instanceof Ga||i instanceof Xa)return await((r=t.invalidateCredentials)===null||r===void 0?void 0:r.call(t,"all")),await qS(t,e);if(i instanceof Ha)return await((n=t.invalidateCredentials)===null||n===void 0?void 0:n.call(t,"tokens")),await qS(t,e);throw i}}async function qS(t,{serverUrl:e,authorizationCode:r,scope:n,resourceMetadataUrl:i,fetchFn:o}){var s,a;let l,c;try{l=await XK(e,{resourceMetadataUrl:i},o),l.authorization_servers&&l.authorization_servers.length>0&&(c=l.authorization_servers[0])}catch{}c||(c=new URL("/",e));let u=await HK(e,t,l),d=await e8(c,{fetchFn:o}),p=await Promise.resolve(t.clientInformation());if(!p){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let _=d?.client_id_metadata_document_supported===!0,b=t.clientMetadataUrl;if(b&&!GK(b))throw new Ka(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${b}`);if(_&&b)p={client_id:b},await((s=t.saveClientInformation)===null||s===void 0?void 0:s.call(t,p));else{if(!t.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let I=await o8(c,{metadata:d,clientMetadata:t.clientMetadata,fetchFn:o});await t.saveClientInformation(I),p=I}}let f=!t.redirectUrl;if(r!==void 0||f){let _=await i8(t,c,{metadata:d,resource:u,authorizationCode:r,fetchFn:o});return await t.saveTokens(_),"AUTHORIZED"}let m=await t.tokens();if(m?.refresh_token)try{let _=await n8(c,{metadata:d,clientInformation:p,refreshToken:m.refresh_token,resource:u,addClientAuthentication:t.addClientAuthentication,fetchFn:o});return await t.saveTokens(_),"AUTHORIZED"}catch(_){if(!(!(_ instanceof Ut)||_ instanceof zo))throw _}let h=t.state?await t.state():void 0,{authorizationUrl:y,codeVerifier:g}=await t8(c,{metadata:d,clientInformation:p,state:h,redirectUrl:t.redirectUrl,scope:n||((a=l?.scopes_supported)===null||a===void 0?void 0:a.join(" "))||t.clientMetadata.scope,resource:u});return await t.saveCodeVerifier(g),await t.redirectToAuthorization(y),"REDIRECT"}function GK(t){if(!t)return!1;try{let e=new URL(t);return e.protocol==="https:"&&e.pathname!=="/"}catch{return!1}}async function HK(t,e,r){let n=hM(t);if(e.validateResourceURL)return await e.validateResourceURL(n,r?.resource);if(r){if(!gM({requestedResource:n,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${n} (or origin)`);return new URL(r.resource)}}function Eu(t){let e=t.headers.get("WWW-Authenticate");if(!e)return{};let[r,n]=e.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};let i=WS(t,"resource_metadata")||void 0,o;if(i)try{o=new URL(i)}catch{}let s=WS(t,"scope")||void 0,a=WS(t,"error")||void 0;return{resourceMetadataUrl:o,scope:s,error:a}}function WS(t,e){let r=t.headers.get("WWW-Authenticate");if(!r)return null;let n=new RegExp(`${e}=(?:"([^"]+)"|([^\\s,]+))`),i=r.match(n);return i?i[1]||i[2]:null}async function XK(t,e,r=fetch){var n,i;let o=await YK(t,"oauth-protected-resource",r,{protocolVersion:e?.protocolVersion,metadataUrl:e?.resourceMetadataUrl});if(!o||o.status===404)throw await((n=o?.body)===null||n===void 0?void 0:n.cancel()),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!o.ok)throw await((i=o.body)===null||i===void 0?void 0:i.cancel()),new Error(`HTTP ${o.status} trying to load well-known OAuth protected resource metadata.`);return uM.parse(await o.json())}async function BS(t,e,r=fetch){try{return await r(t,{headers:e})}catch(n){if(n instanceof TypeError)return e?BS(t,void 0,r):void 0;throw n}}function KK(t,e="",r={}){return e.endsWith("/")&&(e=e.slice(0,-1)),r.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function vM(t,e,r=fetch){return await BS(t,{"MCP-Protocol-Version":e},r)}function JK(t,e){return!t||t.status>=400&&t.status<500&&e!=="/"}async function YK(t,e,r,n){var i,o;let s=new URL(t),a=(i=n?.protocolVersion)!==null&&i!==void 0?i:Hc,l;if(n?.metadataUrl)l=new URL(n.metadataUrl);else{let u=KK(e,s.pathname);l=new URL(u,(o=n?.metadataServerUrl)!==null&&o!==void 0?o:s),l.search=s.search}let c=await vM(l,a,r);if(!n?.metadataUrl&&JK(c,s.pathname)){let u=new URL(`/.well-known/${e}`,s);c=await vM(u,a,r)}return c}function QK(t){let e=typeof t=="string"?new URL(t):t,r=e.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",e.origin),type:"oidc"}),n;let i=e.pathname;return i.endsWith("/")&&(i=i.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${i}`,e.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${i}`,e.origin),type:"oidc"}),n.push({url:new URL(`${i}/.well-known/openid-configuration`,e.origin),type:"oidc"}),n}async function e8(t,{fetchFn:e=fetch,protocolVersion:r=Hc}={}){var n;let i={"MCP-Protocol-Version":r,Accept:"application/json"},o=QK(t);for(let{url:s,type:a}of o){let l=await BS(s,i,e);if(l){if(!l.ok){if(await((n=l.body)===null||n===void 0?void 0:n.cancel()),l.status>=400&&l.status<500)continue;throw new Error(`HTTP ${l.status} trying to load ${a==="oauth"?"OAuth":"OpenID provider"} metadata from ${s}`)}return a==="oauth"?ZS.parse(await l.json()):dM.parse(await l.json())}}}async function t8(t,{metadata:e,clientInformation:r,redirectUrl:n,scope:i,state:o,resource:s}){let a;if(e){if(a=new URL(e.authorization_endpoint),!e.response_types_supported.includes(FS))throw new Error(`Incompatible auth server: does not support response type ${FS}`);if(e.code_challenge_methods_supported&&!e.code_challenge_methods_supported.includes(VS))throw new Error(`Incompatible auth server: does not support code challenge method ${VS}`)}else a=new URL("/authorize",t);let l=await US(),c=l.code_verifier,u=l.code_challenge;return a.searchParams.set("response_type",FS),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",u),a.searchParams.set("code_challenge_method",VS),a.searchParams.set("redirect_uri",String(n)),o&&a.searchParams.set("state",o),i&&a.searchParams.set("scope",i),i?.includes("offline_access")&&a.searchParams.append("prompt","consent"),s&&a.searchParams.set("resource",s.href),{authorizationUrl:a,codeVerifier:c}}function r8(t,e,r){return new URLSearchParams({grant_type:"authorization_code",code:t,code_verifier:e,redirect_uri:String(r)})}async function bM(t,{metadata:e,tokenRequestParams:r,clientInformation:n,addClientAuthentication:i,resource:o,fetchFn:s}){var a;let l=e?.token_endpoint?new URL(e.token_endpoint):new URL("/token",t),c=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(o&&r.set("resource",o.href),i)await i(c,r,l,e);else if(n){let d=(a=e?.token_endpoint_auth_methods_supported)!==null&&a!==void 0?a:[],p=FK(n,d);VK(p,n,c,r)}let u=await(s??fetch)(l,{method:"POST",headers:c,body:r});if(!u.ok)throw await _M(u);return fM.parse(await u.json())}async function n8(t,{metadata:e,clientInformation:r,refreshToken:n,resource:i,addClientAuthentication:o,fetchFn:s}){let a=new URLSearchParams({grant_type:"refresh_token",refresh_token:n}),l=await bM(t,{metadata:e,tokenRequestParams:a,clientInformation:r,addClientAuthentication:o,resource:i,fetchFn:s});return{refresh_token:n,...l}}async function i8(t,e,{metadata:r,resource:n,authorizationCode:i,fetchFn:o}={}){let s=t.clientMetadata.scope,a;if(t.prepareTokenRequest&&(a=await t.prepareTokenRequest(s)),!a){if(!i)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!t.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");let c=await t.codeVerifier();a=r8(i,c,t.redirectUrl)}let l=await t.clientInformation();return bM(e,{metadata:r,tokenRequestParams:a,clientInformation:l??void 0,addClientAuthentication:t.addClientAuthentication,resource:n,fetchFn:o})}async function o8(t,{metadata:e,clientMetadata:r,fetchFn:n}){let i;if(e){if(!e.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");i=new URL(e.registration_endpoint)}else i=new URL("/register",t);let o=await(n??fetch)(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!o.ok)throw await _M(o);return mM.parse(await o.json())}var By=class extends Error{constructor(e,r){super(e),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}};function GS(t){}function Gy(t){if(typeof t=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:e=GS,onError:r=GS,onRetry:n=GS,onComment:i}=t,o="",s=!0,a,l="",c="";function u(h){let y=s?h.replace(/^\xEF\xBB\xBF/,""):h,[g,_]=s8(`${o}${y}`);for(let b of g)d(b);o=_,s=!1}function d(h){if(h===""){f();return}if(h.startsWith(":")){i&&i(h.slice(h.startsWith(": ")?2:1));return}let y=h.indexOf(":");if(y!==-1){let g=h.slice(0,y),_=h[y+1]===" "?2:1,b=h.slice(y+_);p(g,b,h);return}p(h,"",h)}function p(h,y,g){switch(h){case"event":c=y;break;case"data":l=`${l}${y}
|
|
92
|
+
`;break;case"id":a=y.includes("\0")?void 0:y;break;case"retry":/^\d+$/.test(y)?n(parseInt(y,10)):r(new By(`Invalid \`retry\` value: "${y}"`,{type:"invalid-retry",value:y,line:g}));break;default:r(new By(`Unknown field "${h.length>20?`${h.slice(0,20)}\u2026`:h}"`,{type:"unknown-field",field:h,value:y,line:g}));break}}function f(){l.length>0&&e({id:a,event:c||void 0,data:l.endsWith(`
|
|
93
|
+
`)?l.slice(0,-1):l}),a=void 0,l="",c=""}function m(h={}){o&&h.consume&&d(o),s=!0,a=void 0,l="",c="",o=""}return{feed:u,reset:m}}function s8(t){let e=[],r="",n=0;for(;n<t.length;){let i=t.indexOf("\r",n),o=t.indexOf(`
|
|
94
|
+
`,n),s=-1;if(i!==-1&&o!==-1?s=Math.min(i,o):i!==-1?s=i:o!==-1&&(s=o),s===-1){r=t.slice(n);break}else{let a=t.slice(n,s);e.push(a),n=s+1,t[n-1]==="\r"&&t[n]===`
|
|
95
|
+
`&&n++}}return[e,r]}var Hy=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:n}={}){let i;super({start(o){i=Gy({onEvent:s=>{o.enqueue(s)},onError(s){e==="terminate"?o.error(s):typeof e=="function"&&e(s)},onRetry:r,onComment:n})},transform(o){i.feed(o)}})}};var a8={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},As=class extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},Xy=class{constructor(e,r){var n;this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=Wy(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=(n=r?.reconnectionOptions)!==null&&n!==void 0?n:a8}async _authThenStart(){var e;if(!this._authProvider)throw new Br("No auth provider");let r;try{r=await Co(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(n){throw(e=this.onerror)===null||e===void 0||e.call(this,n),n}if(r!=="AUTHORIZED")throw new Br;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;let r={};if(this._authProvider){let i=await this._authProvider.tokens();i&&(r.Authorization=`Bearer ${i.access_token}`)}this._sessionId&&(r["mcp-session-id"]=this._sessionId),this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion);let n=Iu((e=this._requestInit)===null||e===void 0?void 0:e.headers);return new Headers({...r,...n})}async _startOrAuthSse(e){var r,n,i,o;let{resumptionToken:s}=e;try{let a=await this._commonHeaders();a.set("Accept","text/event-stream"),s&&a.set("last-event-id",s);let l=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,{method:"GET",headers:a,signal:(n=this._abortController)===null||n===void 0?void 0:n.signal});if(!l.ok){if(await((i=l.body)===null||i===void 0?void 0:i.cancel()),l.status===401&&this._authProvider)return await this._authThenStart();if(l.status===405)return;throw new As(l.status,`Failed to open SSE stream: ${l.statusText}`)}this._handleSseStream(l.body,e,!0)}catch(a){throw(o=this.onerror)===null||o===void 0||o.call(this,a),a}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let r=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,i=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(n,e),i)}_scheduleReconnection(e,r=0){var n;let i=this._reconnectionOptions.maxRetries;if(r>=i){(n=this.onerror)===null||n===void 0||n.call(this,new Error(`Maximum reconnection attempts (${i}) exceeded.`));return}let o=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(s=>{var a;(a=this.onerror)===null||a===void 0||a.call(this,new Error(`Failed to reconnect SSE stream: ${s instanceof Error?s.message:String(s)}`)),this._scheduleReconnection(e,r+1)})},o)}_handleSseStream(e,r,n){if(!e)return;let{onresumptiontoken:i,replayMessageId:o}=r,s,a=!1,l=!1;(async()=>{var u,d,p,f;try{let m=e.pipeThrough(new TextDecoderStream).pipeThrough(new Hy({onRetry:g=>{this._serverRetryMs=g}})).getReader();for(;;){let{value:g,done:_}=await m.read();if(_)break;if(g.id&&(s=g.id,a=!0,i?.(g.id)),!!g.data&&(!g.event||g.event==="message"))try{let b=Xc.parse(JSON.parse(g.data));ka(b)&&(l=!0,o!==void 0&&(b.id=o)),(u=this.onmessage)===null||u===void 0||u.call(this,b)}catch(b){(d=this.onerror)===null||d===void 0||d.call(this,b)}}(n||a)&&!l&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:s,onresumptiontoken:i,replayMessageId:o},0)}catch(m){if((p=this.onerror)===null||p===void 0||p.call(this,new Error(`SSE stream disconnected: ${m}`)),(n||a)&&!l&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:s,onresumptiontoken:i,replayMessageId:o},0)}catch(g){(f=this.onerror)===null||f===void 0||f.call(this,new Error(`Failed to reconnect: ${g instanceof Error?g.message:String(g)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new Br("No auth provider");if(await Co(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Br("Failed to authorize")}async close(){var e,r;this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),(e=this._abortController)===null||e===void 0||e.abort(),(r=this.onclose)===null||r===void 0||r.call(this)}async send(e,r){var n,i,o,s,a,l,c;try{let{resumptionToken:u,onresumptiontoken:d}=r||{};if(u){this._startOrAuthSse({resumptionToken:u,replayMessageId:ff(e)?e.id:void 0}).catch(b=>{var E;return(E=this.onerror)===null||E===void 0?void 0:E.call(this,b)});return}let p=await this._commonHeaders();p.set("content-type","application/json"),p.set("accept","application/json, text/event-stream");let f={...this._requestInit,method:"POST",headers:p,body:JSON.stringify(e),signal:(n=this._abortController)===null||n===void 0?void 0:n.signal},m=await((i=this._fetch)!==null&&i!==void 0?i:fetch)(this._url,f),h=m.headers.get("mcp-session-id");if(h&&(this._sessionId=h),!m.ok){let b=await m.text().catch(()=>null);if(m.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new As(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:E,scope:I}=Eu(m);if(this._resourceMetadataUrl=E,this._scope=I,await Co(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Br;return this._hasCompletedAuthFlow=!0,this.send(e)}if(m.status===403&&this._authProvider){let{resourceMetadataUrl:E,scope:I,error:P}=Eu(m);if(P==="insufficient_scope"){let M=m.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===M)throw new As(403,"Server returned 403 after trying upscoping");if(I&&(this._scope=I),E&&(this._resourceMetadataUrl=E),this._lastUpscopingHeader=M??void 0,await Co(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new Br;return this.send(e)}}throw new As(m.status,`Error POSTing to endpoint: ${b}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,m.status===202){await((o=m.body)===null||o===void 0?void 0:o.cancel()),HA(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(b=>{var E;return(E=this.onerror)===null||E===void 0?void 0:E.call(this,b)});return}let g=(Array.isArray(e)?e:[e]).filter(b=>"method"in b&&"id"in b&&b.id!==void 0).length>0,_=m.headers.get("content-type");if(g)if(_?.includes("text/event-stream"))this._handleSseStream(m.body,{onresumptiontoken:d},!1);else if(_?.includes("application/json")){let b=await m.json(),E=Array.isArray(b)?b.map(I=>Xc.parse(I)):[Xc.parse(b)];for(let I of E)(s=this.onmessage)===null||s===void 0||s.call(this,I)}else throw await((a=m.body)===null||a===void 0?void 0:a.cancel()),new As(-1,`Unexpected content type: ${_}`);else await((l=m.body)===null||l===void 0?void 0:l.cancel())}catch(u){throw(c=this.onerror)===null||c===void 0||c.call(this,u),u}}get sessionId(){return this._sessionId}async terminateSession(){var e,r,n,i;if(this._sessionId)try{let o=await this._commonHeaders(),s={...this._requestInit,method:"DELETE",headers:o,signal:(e=this._abortController)===null||e===void 0?void 0:e.signal},a=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,s);if(await((n=a.body)===null||n===void 0?void 0:n.cancel()),!a.ok&&a.status!==405)throw new As(a.status,`Failed to terminate session: ${a.statusText}`);this._sessionId=void 0}catch(o){throw(i=this.onerror)===null||i===void 0||i.call(this,o),o}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,r){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:r?.onresumptiontoken})}};var Jy=class extends Event{constructor(e,r){var n,i;super(e),this.code=(n=r?.code)!=null?n:void 0,this.message=(i=r?.message)!=null?i:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,r,n){return n(wM(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e(wM(this),r)}};function l8(t){let e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function HS(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(HS).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${HS(t.cause)}`:t.message:`${t}`}function wM(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}var $M=t=>{throw TypeError(t)},rI=(t,e,r)=>e.has(t)||$M("Cannot "+r),Fe=(t,e,r)=>(rI(t,e,"read from private field"),r?r.call(t):e.get(t)),er=(t,e,r)=>e.has(t)?$M("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),Et=(t,e,r,n)=>(rI(t,e,"write to private field"),e.set(t,r),r),No=(t,e,r)=>(rI(t,e,"access private method"),r),ln,Ja,Pu,Ky,Yy,Dp,zu,Lp,zs,Tu,Cu,Au,Mp,gi,XS,KS,JS,xM,YS,QS,jp,eI,tI,Ya=class extends EventTarget{constructor(e,r){var n,i;super(),er(this,gi),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,er(this,ln),er(this,Ja),er(this,Pu),er(this,Ky),er(this,Yy),er(this,Dp),er(this,zu),er(this,Lp,null),er(this,zs),er(this,Tu),er(this,Cu,null),er(this,Au,null),er(this,Mp,null),er(this,KS,async o=>{var s;Fe(this,Tu).reset();let{body:a,redirected:l,status:c,headers:u}=o;if(c===204){No(this,gi,jp).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(l?Et(this,Pu,new URL(o.url)):Et(this,Pu,void 0),c!==200){No(this,gi,jp).call(this,`Non-200 status code (${c})`,c);return}if(!(u.get("content-type")||"").startsWith("text/event-stream")){No(this,gi,jp).call(this,'Invalid content type, expected "text/event-stream"',c);return}if(Fe(this,ln)===this.CLOSED)return;Et(this,ln,this.OPEN);let d=new Event("open");if((s=Fe(this,Mp))==null||s.call(this,d),this.dispatchEvent(d),typeof a!="object"||!a||!("getReader"in a)){No(this,gi,jp).call(this,"Invalid response body, expected a web ReadableStream",c),this.close();return}let p=new TextDecoder,f=a.getReader(),m=!0;do{let{done:h,value:y}=await f.read();y&&Fe(this,Tu).feed(p.decode(y,{stream:!h})),h&&(m=!1,Fe(this,Tu).reset(),No(this,gi,eI).call(this))}while(m)}),er(this,JS,o=>{Et(this,zs,void 0),!(o.name==="AbortError"||o.type==="aborted")&&No(this,gi,eI).call(this,HS(o))}),er(this,YS,o=>{typeof o.id=="string"&&Et(this,Lp,o.id);let s=new MessageEvent(o.event||"message",{data:o.data,origin:Fe(this,Pu)?Fe(this,Pu).origin:Fe(this,Ja).origin,lastEventId:o.id||""});Fe(this,Au)&&(!o.event||o.event==="message")&&Fe(this,Au).call(this,s),this.dispatchEvent(s)}),er(this,QS,o=>{Et(this,Dp,o)}),er(this,tI,()=>{Et(this,zu,void 0),Fe(this,ln)===this.CONNECTING&&No(this,gi,XS).call(this)});try{if(e instanceof URL)Et(this,Ja,e);else if(typeof e=="string")Et(this,Ja,new URL(e,c8()));else throw new Error("Invalid URL")}catch{throw l8("An invalid or illegal string was specified")}Et(this,Tu,Gy({onEvent:Fe(this,YS),onRetry:Fe(this,QS)})),Et(this,ln,this.CONNECTING),Et(this,Dp,3e3),Et(this,Yy,(n=r?.fetch)!=null?n:globalThis.fetch),Et(this,Ky,(i=r?.withCredentials)!=null?i:!1),No(this,gi,XS).call(this)}get readyState(){return Fe(this,ln)}get url(){return Fe(this,Ja).href}get withCredentials(){return Fe(this,Ky)}get onerror(){return Fe(this,Cu)}set onerror(e){Et(this,Cu,e)}get onmessage(){return Fe(this,Au)}set onmessage(e){Et(this,Au,e)}get onopen(){return Fe(this,Mp)}set onopen(e){Et(this,Mp,e)}addEventListener(e,r,n){let i=r;super.addEventListener(e,i,n)}removeEventListener(e,r,n){let i=r;super.removeEventListener(e,i,n)}close(){Fe(this,zu)&&clearTimeout(Fe(this,zu)),Fe(this,ln)!==this.CLOSED&&(Fe(this,zs)&&Fe(this,zs).abort(),Et(this,ln,this.CLOSED),Et(this,zs,void 0))}};ln=new WeakMap,Ja=new WeakMap,Pu=new WeakMap,Ky=new WeakMap,Yy=new WeakMap,Dp=new WeakMap,zu=new WeakMap,Lp=new WeakMap,zs=new WeakMap,Tu=new WeakMap,Cu=new WeakMap,Au=new WeakMap,Mp=new WeakMap,gi=new WeakSet,XS=function(){Et(this,ln,this.CONNECTING),Et(this,zs,new AbortController),Fe(this,Yy)(Fe(this,Ja),No(this,gi,xM).call(this)).then(Fe(this,KS)).catch(Fe(this,JS))},KS=new WeakMap,JS=new WeakMap,xM=function(){var t;let e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...Fe(this,Lp)?{"Last-Event-ID":Fe(this,Lp)}:void 0},cache:"no-store",signal:(t=Fe(this,zs))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},YS=new WeakMap,QS=new WeakMap,jp=function(t,e){var r;Fe(this,ln)!==this.CLOSED&&Et(this,ln,this.CLOSED);let n=new Jy("error",{code:e,message:t});(r=Fe(this,Cu))==null||r.call(this,n),this.dispatchEvent(n)},eI=function(t,e){var r;if(Fe(this,ln)===this.CLOSED)return;Et(this,ln,this.CONNECTING);let n=new Jy("error",{code:e,message:t});(r=Fe(this,Cu))==null||r.call(this,n),this.dispatchEvent(n),Et(this,zu,setTimeout(Fe(this,tI),Fe(this,Dp)))},tI=new WeakMap,Ya.CONNECTING=0,Ya.OPEN=1,Ya.CLOSED=2;function c8(){let t="document"in globalThis?globalThis.document:void 0;return t&&typeof t=="object"&&"baseURI"in t&&typeof t.baseURI=="string"?t.baseURI:void 0}var nI=class extends Error{constructor(e,r,n){super(`SSE error: ${r}`),this.code=e,this.event=n}},Qy=class{constructor(e,r){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=r?.eventSourceInit,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=Wy(r?.fetch,r?.requestInit)}async _authThenStart(){var e;if(!this._authProvider)throw new Br("No auth provider");let r;try{r=await Co(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(n){throw(e=this.onerror)===null||e===void 0||e.call(this,n),n}if(r!=="AUTHORIZED")throw new Br;return await this._startOrAuth()}async _commonHeaders(){var e;let r={};if(this._authProvider){let i=await this._authProvider.tokens();i&&(r.Authorization=`Bearer ${i.access_token}`)}this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion);let n=Iu((e=this._requestInit)===null||e===void 0?void 0:e.headers);return new Headers({...r,...n})}_startOrAuth(){var e,r,n;let i=(n=(r=(e=this===null||this===void 0?void 0:this._eventSourceInit)===null||e===void 0?void 0:e.fetch)!==null&&r!==void 0?r:this._fetch)!==null&&n!==void 0?n:fetch;return new Promise((o,s)=>{this._eventSource=new Ya(this._url.href,{...this._eventSourceInit,fetch:async(a,l)=>{let c=await this._commonHeaders();c.set("Accept","text/event-stream");let u=await i(a,{...l,headers:c});if(u.status===401&&u.headers.has("www-authenticate")){let{resourceMetadataUrl:d,scope:p}=Eu(u);this._resourceMetadataUrl=d,this._scope=p}return u}}),this._abortController=new AbortController,this._eventSource.onerror=a=>{var l;if(a.code===401&&this._authProvider){this._authThenStart().then(o,s);return}let c=new nI(a.code,a.message,a);s(c),(l=this.onerror)===null||l===void 0||l.call(this,c)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",a=>{var l;let c=a;try{if(this._endpoint=new URL(c.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(u){s(u),(l=this.onerror)===null||l===void 0||l.call(this,u),this.close();return}o()}),this._eventSource.onmessage=a=>{var l,c;let u=a,d;try{d=Xc.parse(JSON.parse(u.data))}catch(p){(l=this.onerror)===null||l===void 0||l.call(this,p);return}(c=this.onmessage)===null||c===void 0||c.call(this,d)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new Br("No auth provider");if(await Co(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Br("Failed to authorize")}async close(){var e,r,n;(e=this._abortController)===null||e===void 0||e.abort(),(r=this._eventSource)===null||r===void 0||r.close(),(n=this.onclose)===null||n===void 0||n.call(this)}async send(e){var r,n,i,o;if(!this._endpoint)throw new Error("Not connected");try{let s=await this._commonHeaders();s.set("content-type","application/json");let a={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(e),signal:(r=this._abortController)===null||r===void 0?void 0:r.signal},l=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._endpoint,a);if(!l.ok){let c=await l.text().catch(()=>null);if(l.status===401&&this._authProvider){let{resourceMetadataUrl:u,scope:d}=Eu(l);if(this._resourceMetadataUrl=u,this._scope=d,await Co(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Br;return this.send(e)}throw new Error(`Error POSTing to endpoint (HTTP ${l.status}): ${c}`)}await((i=l.body)===null||i===void 0?void 0:i.cancel())}catch(s){throw(o=this.onerror)===null||o===void 0||o.call(this,s),s}}setProtocolVersion(e){this._protocolVersion=e}};var Vi={name:"@intelliweave/embedded",version:"2.0.72-beta.8",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && vitest run","test:local":"IW_API_URL=http://localhost:3000/api npm run test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.64","@types/lodash":"^4.17.13","@types/react":"^18.3.12","@types/uuid":"^10.0.0",bestzip:"^2.2.1","cross-env":"^7.0.3","find-cache-dir":"^5.0.0",lodash:"^4.17.21","onnxruntime-web":"^1.20.0",react:"^18.3.1","replace-in-file":"^8.2.0",tsup:"^8.3.5",tsx:"^4.19.2",typedoc:"^0.27.6",vitest:"^3.2.4"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.60.0","@modelcontextprotocol/sdk":"^1.24.1","@types/json-schema":"^7.0.15",minisearch:"^6.3.0",openai:"^6.10.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.0","rehype-stringify":"^10.0.0","remark-parse":"^11.0.0","remark-rehype":"^11.1.0",unified:"^11.0.4","utility-types":"^3.11.0",uuid:"^10.0.0"}};var tr=new Le("MCPKnowledgeClient"),ev=class{constructor(e){this.tools=[];this.iwActions=[];this.stats={toolsCalled:0};this.lastSearchQuery="";this.lastSearchResults=[];this.config=e}async connect(){return this.client?this.client:this.connectionPromise?await this.connectionPromise:(this.connectionPromise=this.connectInternal(),this.connectionPromise.finally(()=>{this.connectionPromise=void 0}),await this.connectionPromise)}async connectInternal(){tr.debug("Connecting to MCP client");let e=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let r=new $p({name:Vi.name,version:Vi.version}),n=new Xy(new URL(this.config.baseURL));return await r.connect(n),tr.debug("Connected with HTTP streaming mode"),r}).catch(async r=>{let n=new $p({name:Vi.name,version:Vi.version}),i=new Qy(new URL(this.config.baseURL));return await n.connect(i),tr.debug("Connected with SSE mode"),n});return await this.disconnect(),this.client=e,e.onerror=r=>{tr.error(`MCP client error: ${r.message}`)},e.onclose=()=>{tr.debug("MCP client connection closed"),this.client=void 0},e.setNotificationHandler(cx,r=>{r.params.level=="critical"?tr.error(`[Server] ${r.params.data}`):r.params.level=="emergency"?tr.error(`[Server] ${r.params.data}`):r.params.level=="error"?tr.error(`[Server] ${r.params.data}`):r.params.level=="warning"?tr.warn(`[Server] ${r.params.data}`):r.params.level=="info"?tr.info(`[Server] ${r.params.data}`):r.params.level=="debug"?tr.debug(`[Server] ${r.params.data}`):tr.log(`[Server] ${r.params.data}`)}),e.setNotificationHandler(lx,r=>{tr.debug("Tool list changed",r),this.fetchTools()}),tr.debug("Fetching tools from MCP server..."),await this.fetchTools(),e}async disconnect(){await this.client?.close(),this.client=void 0,this.tools=[],this.iwActions=[]}async fetchTools(){let e=[],r;for(;;){let i=await this.client.listTools({cursor:r});r=i.nextCursor;for(let o of i.tools||[])e.push(o);if(!i?.tools?.length||!r)break}let n=[];for(let i of e){let o=!!(this.config.searchToolName&&i.name==this.config.searchToolName&&!this.config.searchToolVisible);n.push({id:i.name,name:i.name,content:i.description||"",type:"action",isContext:!0,parameters:i.inputSchema,action:s=>this.performToolCall(i.name,s),disabled:o})}tr.debug(`Fetched ${e.length} tools from MCP server.`),this.tools=e,this.iwActions=n}async search(e){if(e==this.lastSearchQuery)return this.lastSearchResults;await this.connect();let r=this.iwActions.slice(),n=await this.performSearchCall(e);return r=r.concat(n),this.lastSearchQuery=e,this.lastSearchResults=r,tr.debug(`Search completed, found ${r.length} items.`),r}async performSearchCall(e){let r=[];if(!this.config.searchToolName)return r;let n=this.tools.find(o=>o.name==this.config.searchToolName);if(!n)return tr.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),r;let i;if(n.inputSchema.required?.length==1){let o=n.inputSchema.required[0];i=await this.performToolCall(this.config.searchToolName,{[o]:e})}else if(n.inputSchema.properties&&Object.keys(n.inputSchema.properties).length==1){let o=Object.keys(n.inputSchema.properties)[0];i=await this.performToolCall(this.config.searchToolName,{[o]:e})}else i=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(i))for(let o=0;o<i.length;o++){let s=i[o];r.push({id:this.config.id+":"+this.config.searchToolName+":"+o,name:`Search result ${o+1} in ${this.config.searchToolName}`,type:"info",content:typeof s=="string"?s:JSON.stringify(s)})}else r.push({id:this.config.id+":"+this.config.searchToolName+":result",name:`Search result in ${this.config.searchToolName}`,type:"info",content:typeof i=="string"?i:JSON.stringify(i)});return r}async performToolCall(e,r){await this.connect(),tr.debug(`Performing tool call for ${e} with params:`,r),this.stats.toolsCalled+=1;let n=await this.client.callTool({name:e,arguments:r});if(n.isError){let i=n.content?.[0]?.text||"Unknown error";throw tr.error(`Error calling tool ${e}: ${i}`),new Error(`Error calling tool ${e}: ${i}`)}if(Array.isArray(n.content)&&n.content.length==1&&n.content[0].type=="text")try{return JSON.parse(n.content[0].text)}catch{}return n.content||[]}};var d8=new Le("Statistics"),Up=[];async function Gr(t,e){let r={...e,event_id:dr(),event_date:new Date().toISOString(),sdk_version:Vi.version,conversation_id:t?.conversationID||"",api_key:t?.apiKey||"",user_id:t?.userID||""};if(Up.push(r),!t||(await new Promise(i=>setTimeout(i,5e3)),Up.length===0))return;let n=Up.slice();Up.length=0;try{let i=await fetch(t.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:n})});if(!i.ok)throw new Error(`Analytics submission failed: ${i.status} ${i.statusText}`)}catch(i){d8.warn("Failed to submit analytics event:",i),Up.push(...n);return}}var Qa=new Le("KnowledgeBase"),iI=1,tv=class t{constructor(e){this._sources=[];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.allowWindowSources=!0;this.allowGlobalConfigSources=!0;this.ai=e,this.ensureInternalKnowledge()}ensureInternalKnowledge(){this._sources=this._sources.filter(e=>e.id!=="core.internal"),this._sources.push({id:"core.internal",query:async()=>vP(this.ai)})}reset(){this._windowSources=[],this.manualEntries=[],this.lastResults=[],this._sources=[],this.ensureInternalKnowledge()}registerSource(e,r){let n=e;return typeof e=="function"&&(r=e,n=`source.${iI++}`),this._sources.push({id:n,query:r}),n}removeSource(e){this._sources=this.sources.filter(r=>r.id!==e&&r.query!==e)}addEntry(e){this.manualEntries.push(e)}removeEntry(e){this.manualEntries=this.manualEntries.filter(r=>r.id!==e)}get sources(){let e=this._sources;return this.allowGlobalConfigSources&&bt().knowledgeBaseSources&&(e=e.concat(bt().knowledgeBaseSources)),this.allowWindowSources&&typeof document<"u"&&(e=e.concat(this._windowSources)),e=e.filter(r=>!r.disabled),e}async search(e){Qa.debug(`Searching knowledge base for: ${e}`);let r=Date.now(),n=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});n.query=e,n.entries=[],n.sources=[],this.allowWindowSources&&typeof document<"u"?(document.dispatchEvent(n),this._windowSources=n.sources):this._windowSources=[];let o=(await Promise.all(this.sources.map(async c=>{try{let u=Date.now(),d=await c.query(e);return Qa.debug(`Source '${c.id}' took ${Date.now()-u}ms`),d||[]}catch(u){return Qa.warn(`Knowledge source '${c.id}' failed:`,u),[]}}))).flat();o=o.concat(n.entries),o=o.concat(this.manualEntries),this.allowGlobalConfigSources&&bt().knowledgeBase&&(o=o.concat(bt().knowledgeBase)),o=o.filter(c=>c&&!c.disabled);for(let c=0;c<o.length;c++){let u=o[c];u.id=u.id||`temp.${c}`,u._functionID=u.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")}let s=new yP({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});s.addAll(o);let l=s.search(e).map(c=>o.find(u=>u.id==c.id));for(let c of o)c.isContext&&(l.find(u=>u.id===c.id)||l.push(c));return this.lastResults=l,Gr(this.ai,{event_type:"kb_search",value:l.length,value_str:"",event_properties:{search_time_ms:Date.now()-r,sources_searched:this.sources.length}}),Qa.debug("Found results:",l),l}getCachedEntry(e){return this.lastResults.find(r=>r.id==e||r._functionID==e)}registerSourceFromURL(e,r){r||(r=`external.${iI++}`),Qa.debug(`Registering remote knowledge base source: ${e}`);let n=[],i=[],o=!0,s=async(l,c)=>{Qa.debug(`Calling remote knowledge base action: ${l.id}`);let u={type:"action",userID:this.ai.userID,actionID:l.id,parameters:c},d=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});if(!d.ok)throw new Error(`HTTP Error ${d.status} ${d.statusText}`);let p=await d.json();return a(p.updateItems||[]),p.response},a=l=>{for(let c of l){if(!c.id){Qa.warn("KB item skipped since it has no ID.",c);continue}let u=n.find(d=>d.id==c.id);if(u){u.name=c.name||u.name||"",u.content=c.content||u.content||"",u.disabled=c.disabled??u.disabled,u.isContext=c.isContext??u.isContext,u.parameters=c.parameters||u.parameters||[],u.tags=c.tags||u.tags,u.type=c.type||u.type;continue}n.push({...c,action:d=>s(c,d)})}};this.registerSource(r,async l=>{if(o&&i.includes(l))return n;let c={type:"search",userID:this.ai?.userID||"",query:l},u=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!u.ok)throw new Error(`HTTP Error ${u.status} ${u.statusText}`);let d=await u.json();return o=!d.noCache,i.includes(l)||i.push(l),a(d.items),n})}clone(){let e=new t(this.ai);return e._sources=this._sources,e._windowSources=this._windowSources,e.manualEntries=this.manualEntries,e.ensureInternalKnowledge(),e}registerMCPSource(e){e.id||(e.id=`external.${iI++}`);let r=new ev(e);return this.registerSource(e.id,n=>r.search(n)),r}};var rv=class{constructor(e){this.ai=e}async boolean(e){let r=await this.instruct({...e,instruction:`${e.instruction}
|
|
96
|
+
|
|
97
|
+
Return only the text "true" or "false" to indicate the answer to the question. Do not include any additional text or explanations.`});if(r.toLowerCase().includes("true"))return!0;if(r.toLowerCase().includes("false"))return!1;throw new Error("The AI did not give a boolean answer: "+r)}async choose(e){let r=await this.instruct({...e,instruction:`${e.instruction}
|
|
18
98
|
|
|
19
99
|
Reply only with one of the following options:
|
|
20
|
-
${
|
|
100
|
+
${e.options.map(n=>`- "${n}"`).join(`
|
|
21
101
|
`)}
|
|
22
102
|
|
|
23
|
-
Do not include any additional text or explanations.`});return
|
|
24
|
-
You will receive some data. Extraction instructions: ${
|
|
103
|
+
Do not include any additional text or explanations.`});return e.options.includes(r)?r:e.options.find(n=>r.toLowerCase().includes(n.toLowerCase()))}async extract(e){let r=`
|
|
104
|
+
You will receive some data. Extraction instructions: ${e.instruction}
|
|
25
105
|
|
|
26
|
-
${
|
|
106
|
+
${e.allowMultiple?"Return a JSONL string only, one JSON object on each line.":"Return a valid JSON object only."}
|
|
27
107
|
|
|
28
108
|
Objects should have the following keys:
|
|
29
|
-
${
|
|
109
|
+
${e.extractions.map(i=>`- ${i.name} (${i.type}): ${i.description||"No description provided."}`).join(`
|
|
30
110
|
`)}
|
|
31
|
-
`,
|
|
32
|
-
`).map(
|
|
111
|
+
`,n=await this.instruct({...e,instruction:r});if(n=n.replace(/```jsonl/g,"").replace(/```json/g,"").replace(/```/g,""),e.allowMultiple){let i=n.split(`
|
|
112
|
+
`).map(s=>s.trim()).filter(s=>!!s.trim()),o=[];for(let s of i)try{o.push(JSON.parse(s))}catch(a){console.error("Failed to parse line as JSON:",s,a.message)}return o}else return[JSON.parse(n.trim())]}async generateMarkdown(e){return this.instruct({...e,instruction:"Generate a Markdown document based on the input text. Always include a header on every response. Give long detailed answers with many paragraphs, and explain concepts step by step."})}async instruct(e){let r=this.ai.clone();return r.resetConversation(),r.getContextPrefix=async()=>e.instruction,e.callback&&r.addEventListener("output",n=>{e.callback(n.detail.message)}),e.allowKB||(r.knowledgeBase._sources=[]),await r.sendMessage(typeof e.data=="string"?e.data:JSON.stringify(e.data)).then(n=>n.text())}};var Nu=class{constructor(e){this.messages=e}text(){return this.messages?.flatMap(e=>e.sections)?.filter(e=>e?.type=="text")?.map(e=>e?.text||"")?.filter(e=>!!e)?.join(`
|
|
33
113
|
|
|
34
|
-
`)?.trim()||""}tokenUsage(){return{cachedInputTokens:this.messages?.reduce((
|
|
114
|
+
`)?.trim()||""}tokenUsage(){return{cachedInputTokens:this.messages?.reduce((e,r)=>e+(r.usage?.cachedInputTokens||0),0)||0,inputTokens:this.messages?.reduce((e,r)=>e+(r.usage?.inputTokens||0),0)||0,outputTokens:this.messages?.reduce((e,r)=>e+(r.usage?.outputTokens||0),0)||0,totalTokens:this.messages?.reduce((e,r)=>e+(r.usage?.totalTokens||0),0)||0}}sections(){return this.messages?.flatMap(e=>e.sections||[])||[]}toolCalls(){return this.messages?.flatMap(e=>e.sections?.filter(r=>r.type=="tool_call")||[])||[]}toolResult(e){return this.messages?.map(r=>r.sections?.find(n=>n.type=="tool_result"&&n.toolCallInstanceID==e)).filter(r=>!!r)[0]||null}};var nv=class{constructor(e){this.subagents=[];this.cachedSubagents={};this.ai=e}register(e){if(this.subagents.find(r=>r.id==e.id))throw new Error(`Sub-agent with ID ${e.id} already exists`);this.subagents.push(e),this.ai.knowledgeBase.registerSource("subagent:"+e.id,r=>[{type:"action",id:"ask:"+e.id,name:`Ask ${e.name||"subagent"}`,content:e.usageInstructions||`Use this tool to ask ${e.name||"subagent"} a question.`,isContext:!0,parameters:[{type:"string",name:"query",description:"The question to ask the subagent"}],action:async(n,i)=>await this.runQuery(e,n.query)}])}remove(e){this.subagents=this.subagents.filter(r=>r.id!=e),this.ai.knowledgeBase.removeSource("subagent:"+e)}async runQuery(e,r){let n=e.apiKey||this.ai.apiKey,i=this.cachedSubagents[n];return i||(i=new Ou,await i.load(n,e.config),this.cachedSubagents[n]=i),i=i.clone(),i.knowledgeBase.allowGlobalConfigSources=!1,i.knowledgeBase.allowWindowSources=!1,e.clearExistingKnowledge&&i.knowledgeBase.reset(),e.knowledge&&i.knowledgeBase.registerSource(e.knowledge),e.onAgentLoaded&&await e.onAgentLoaded(i),(await i.sendMessage(r)).text()}};var Wn=new Le("Main"),kM=new Set,el=class el extends EventTarget{constructor(){super(...arguments);this.conversationID=dr();this.knowledgeBase=new tv(this);this.subAgents=new nv(this);this._lastKBsearch="";this.models=[];this.audio=null;this.apiKey="";this.logic=new rv(this);this.userID=x1();this.hubAPI="https://intelliweave.ai/api";this._lastSystemMsg="";this.isProcessing=!1;this.activeAnalyticsPromises=[]}get loaded(){return!!(this.config&&this.currentModel)}get flags(){return this.config?.flags||{}}getBuiltInActionsInfo(){return{version:el.builtInActionsVersion,availableActions:["ui.openURL - Open URLs in new tabs","ui.changeRoute - Change page routes","ui.sendEmail - Send emails via mailto links","search - Search knowledge base"],enabledFlags:this.flags}}async load(r,n){if(this.apiKey=r,!r)throw new Error("API key is required to load the AI.");try{await Promise.all([(async()=>{Wn.debug("Loading configuration...");let i=await fetch(this.hubAPI+"/config/get",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:r})});if(!i.ok)throw new Error(`Failed to load configuration: ${i.status} ${i.statusText}`);try{this.config=await i.json(),Wn.debug("Config loaded successfully:",this.config),n&&(this.config={...this.config,...n}),this.config&&Wn.debug("UI Properties - logo:",this.config.logo,"background:",this.config.background,"textColor:",this.config.textColor)}catch(o){Wn.error("Failed to parse JSON response:",o);try{let s=await i.clone().text();Wn.error("Raw response that failed parsing:",s)}catch{Wn.error("Could not get raw response text either")}throw new Error(`Failed to parse configuration: ${o}`)}})(),(async()=>{try{let i=await fetch("https://cdn.intelliweave.ai/models/silero_vad_3.onnx");if(!i.ok)throw new Error(`Failed to load VAD model: ${i.status} ${i.statusText}`);this.vadModel=await i.blob()}catch(i){Wn.warn(`Failed to load VAD model, some features will be unavailable. ${i.message}`)}})()]),this.models=[{id:this.config.id,config:this.config.model}],this.setModel(this.config.id);for(let i of this.config.knowledge||[])i.url&&i.backendType=="mcp"?this.knowledgeBase.registerMCPSource({id:i.id,searchToolName:i.mcpSearchToolName,baseURL:i.url}):i.url&&this.knowledgeBase.registerSourceFromURL(i.url);for(let i of this.config.knowledge||[])i.entries?.length&&this.knowledgeBase.registerSource(i.id,()=>i.entries||[]);if(this.config.mcpServers)for(let i of this.config.mcpServers)this.knowledgeBase.registerMCPSource(i);for(let i of this.config.subagents||[])this.subAgents.register(i);return this.resetConversation(),this.dispatchEvent(new CustomEvent("load",{detail:{ai:this}})),typeof window<"u"&&window.dispatchEvent(new CustomEvent("webweaver_loaded",{detail:{ai:this}})),this}catch(i){throw Wn.warn("Failed to load:",i),this.error=i,this.dispatchEvent(new CustomEvent("error",{detail:{ai:this,error:i}})),typeof window<"u"&&window.dispatchEvent(new CustomEvent("webweaver_error",{detail:{ai:this,error:i}})),i}}setModel(r){let n=this.models.find(o=>o.id==r);if(!n)throw new Error(`Model with ID "${r}" not found.`);let i={...n.config,stream:!0,systemMessage:"",onBeforeMessageProcessing:this.onBeforeMessageProcessing.bind(this),onAIMessage:this.processIncomingMessage.bind(this),onAIToolStart:(o,s)=>{let a=this.knowledgeBase.getCachedEntry(o);this.onAIToolStart?.(a?.id||o,s)}};this.config?.onCreateProvider?this.currentModel=this.config.onCreateProvider(i):n.config.providerID==="anthropic"?this.currentModel=new zh(i):this.currentModel=new oh(i),this.currentModel.id=n.id,this.currentModel.metadata=n}async getContextPrefix(){let r=bt().pageSummary||`You are ${this.config?.name||"IntelliWeave"}. ${this.config?.instructions||"Speak in short sentences."}`;return typeof r=="function"&&(r=await r()),r}async onBeforeMessageProcessing(){this._lastKBsearch||(this._lastKBsearch="__intelliweaveblanksearchforcontextitems__");let r=this._nextRequestUseKBitems||await this.knowledgeBase.search(this._lastKBsearch);this._nextRequestUseKBitems=void 0;let n=await this.getContextPrefix();this.currentModel.contextGroup.add({id:"_iw_main",sortOrder:1,cannotRemove:!0,data:n}),this.currentModel.contextGroup.add({id:"_iw_kb_only_rule",sortOrder:2,cannotRemove:!0,disabled:!this.flags.onlyUseKnowledgeBase,data:"Important rule: Only use knowledge from your knowledge base to answer questions, do not speak about anything that is not included in your knowledge base."}),this.currentModel.contextGroup.add({id:"_iw_kb_rag",sortOrder:99,cannotRemove:!0,data:nh(`
|
|
35
115
|
# RAG search
|
|
36
116
|
Use the \`search\` tool proactively as much as possible to find missing information or tools.
|
|
37
117
|
Use the \`search\` tool when you are unsure about specific details or actions to take.
|
|
38
118
|
Use the \`search\` tool if you are unable to complete the user's request.
|
|
39
119
|
If you're about to say "I don't have access..." or "I can't..." use the \`search\` tool first.
|
|
40
|
-
`)}),this.currentModel.contextGroup.add({id:"_iw_kb_description",sortOrder:100,cannotRemove:!0,data:`# Knowledge Database${
|
|
120
|
+
`)}),this.currentModel.contextGroup.add({id:"_iw_kb_description",sortOrder:100,cannotRemove:!0,data:`# Knowledge Database${r.length==0?`
|
|
121
|
+
|
|
122
|
+
(no items found)`:""}`});for(let i of r)if(i.type=="info"||i.type=="tour"||i.type=="input-event"){let o=nh(i.content),s=!0;if(i.attachments?.length)for(let a of i.attachments)a.url&&(s&&(o+=`
|
|
41
123
|
|
|
42
|
-
|
|
43
|
-
|
|
124
|
+
\`\`\`yaml
|
|
125
|
+
attachments:
|
|
126
|
+
`,s=!1),o+=`- name: "${a.name||""}"
|
|
127
|
+
mimetype: "${a.mimeType||""}"
|
|
128
|
+
url: "${a.url}"
|
|
129
|
+
`);s||(o+="```\n"),this.currentModel.contextGroup.add({id:i.id,data:`## ${i.type}: ${i.name}
|
|
130
|
+
${o}`,cannotRemove:i.isContext,sortOrder:101,disabled:typeof i.disabled=="function"?i.disabled(this):i.disabled})}else if(i.type=="action"){let o={name:i._functionID,description:nh(i.content),params:$1(i.parameters||[{name:"value",type:"string",description:"Input"}]),callback:s=>this.toolRunKBAction(i,s),canRemove:!i.isContext,kbItem:i};this.currentModel.registerTool(o)}else continue}processIncomingMessage(r,n){if(!n){let i=this.currentModel?.stats?.tokensUsed||0,o=r.reduce((s,a)=>s+(a.usage?.totalTokens||0),0);Gr(this,{event_type:"message_receive",value:o,value_str:"",event_properties:{response_time_ms:Date.now()-(this._messageStartTime||Date.now()),is_streaming:!1,is_chunk:!1,total_tokens:i}})}this.dispatchEvent(new CustomEvent("output",{detail:{ai:this,isPartial:n,messages:r}})),this.onAIMessage?.(r,!!n)}async sendMessage(r,n){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");if(this.isProcessing)throw new Error("Cannot send message while another message is being processed.");this.isProcessing=!0;try{this._messageStartTime=Date.now(),kM.has(this.conversationID)||(kM.add(this.conversationID),Gr(this,{event_type:"session_start"})),Gr(this,{event_type:"message_send",value_str:"",event_properties:{message_length:r.length,is_voice_input:!!this.audio?.speechRecognition?.isRunning}}),this.dispatchEvent(new CustomEvent("input",{detail:{ai:this,message:r}})),this.submitAnalyticsEvent({type:"message",role:"user",message:r});let i=Date.now(),o=await this.currentModel.sendMessage(r),s=new Nu(o);(this._voiceTracker||Wn.debug.bind(Wn))(`LLM response took ${Date.now()-i}ms`);let l=this.currentModel.contextGroup.getAllAsString();l+=`
|
|
44
131
|
|
|
45
132
|
=== TOOLS ===
|
|
46
133
|
|
|
47
|
-
`+this.currentModel.toolGroup.getAll().map(
|
|
48
|
-
`),this._lastSystemMsg!=n&&(this._lastSystemMsg=n,this.submitAnalyticsEvent({type:"system-msg",txt:n}));for(let a of o)for(let l of a.sections||[])if(l.type=="text")this.submitAnalyticsEvent({type:"message",role:"assistant",message:l.text||""});else if(l.type=="thinking")this.submitAnalyticsEvent({type:"thinking",role:"assistant",message:l.text||""});else if(l.type=="tool_call"){let c=s.toolResult(l.toolCallInstanceID);this.submitAnalyticsEvent({type:"action",role:"assistant",action:l.toolKbID||"",actionName:l.toolKbName||"",value:l.toolParameters,result:c?.toolErrorResponse||c?.toolSuccessResponse,isError:!!c?.toolErrorResponse})}else l.type=="tool_result"||this.submitAnalyticsEvent({type:"other",role:"assistant"});return s}finally{this.isProcessing=!1}}async toolRunKBAction(e,i){let o=Date.now();try{this.dispatchEvent(new CustomEvent("toolstart",{detail:{knowledgeBaseEntry:e,input:i,ai:this}}));let s=await e.action(i,this),n=Date.now()-o;return y(this,{event_type:"tool_call",value_str:e.id||"",event_properties:{tool_args:i,execution_time_ms:n,success:!0}}),this.dispatchEvent(new CustomEvent("tool",{detail:{knowledgeBaseEntry:e,input:i,ai:this,result:s}})),s}catch(s){let n=Date.now()-o;throw y(this,{event_type:"tool_call",value_str:e.id||"",event_properties:{tool_args:i,execution_time_ms:n,success:!1,error_message:s.message}}),this.dispatchEvent(new CustomEvent("tool",{detail:{knowledgeBaseEntry:e,input:i,ai:this,error:s}})),s}}submitAnalyticsEvent(e){if(m().analytics===!1||this.config?.analytics===!1)return;let i=fetch(this.hubAPI+"/analytics/post",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,apiKey:this.apiKey,time:Date.now(),conversationID:this.conversationID,personaID:this.config?.id})}).catch(o=>{T.debug("Failed to submit analytics event:",o)});this.activeAnalyticsPromises.push(i),i.finally(()=>{this.activeAnalyticsPromises=this.activeAnalyticsPromises.filter(o=>o!==i)})}async waitForAnalytics(){this.activeAnalyticsPromises.length!==0&&(await Promise.all(this.activeAnalyticsPromises),this.activeAnalyticsPromises.length>0&&await this.waitForAnalytics())}resetConversation(){this.currentModel&&(this.currentModel.resetConversation(),this._lastKBsearch="",this._nextRequestUseKBitems=void 0,this.conversationID=Xe(),this._lastSystemMsg="")}insertAssistantMessage(e){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");this.currentModel.addAssistantMessage(e)}exportState(){return{type:"intelliweave/state/v2",conversationID:this.conversationID,messages:this.currentModel?.messageGroup.getAll()}}importState(e){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");if(e?.type!="intelliweave/state/v2")throw new Error(`Invalid state type: ${e.type}`);this.conversationID=e.conversationID;for(let i of e.messages)this.currentModel.messageGroup.add(i)}clone(){let e=new G;return e.apiKey=this.apiKey,e.config=this.config,e.models=this.models,this.config?.id&&e.setModel(this.config.id),e.audio=this.audio,e.vadModel=this.vadModel,e.userID=this.userID,e.knowledgeBase=this.knowledgeBase.clone(),e}get messages(){return this.currentModel?.messageGroup.items||[]}};G.version=I.version,G.builtInActionsVersion="1.0.0",T.debug(`Loaded: version=${I.version} builtInActionsVersion=${G.builtInActionsVersion}`);var W=G;var w=class extends HTMLElement{constructor(){super(...arguments);this._state={}}get root(){return this._shadow}static register(){this._isRegistered||(this._isRegistered=!0,this.tagName||(this.tagName="anonymous-component-"+this.name.toLowerCase().replace(/[^a-z0-9-]/g,"-")+"--"+Math.random().toString(36).substring(2)),window.customElements.define(this.tagName,this))}static create(e={},i=""){this.register();let o=document.createElement(this.tagName);for(let s in e)o.setAttribute(s,e[s]);return o.onBeforeCreate(),o.innerHTML=i,o}static add(e={},i=""){this.register();let o=s=>s.replaceAll("&","&").replaceAll('"',""").replaceAll("<","<").replaceAll(">",">");return`<${this.tagName} ${Object.keys(e).map(s=>`${s}="${o(e[s]+"")}"`).join(" ")}>${i}</${this.tagName}>`}static createElement(){return this.register(),document.createElement(this.tagName)}connectedCallback(){this._shadow||(this._shadow=this.attachShadow({mode:"closed"}),this._shadow.innerHTML=this.html(),this.onCreate()),this.onUpdate()}disconnectedCallback(){this._shadow=void 0,this.onDestroy()}html(){return""}onBeforeCreate(){}onCreate(){}onUpdate(){}onDestroy(){}attributeChangedCallback(e,i,o){this._shadow&&this.onUpdate()}get attr(){return this._attrProxy?this._attrProxy:(this._attrProxy=new Proxy({},{get:(e,i)=>this.getAttribute(i.toString())||"",set:(e,i,o)=>(this.getAttribute(i.toString())===o||(o?this.setAttribute(i.toString(),o):this.removeAttribute(i.toString()),this._shadow&&this.onUpdate()),!0)}),this._attrProxy)}get state(){return this._stateProxy?this._stateProxy:(this._stateProxy=new Proxy({},{get:(e,i)=>this._state[i],set:(e,i,o)=>(this._state[i]=o,this._shadow&&this.onUpdate(),!0)}),this._stateProxy)}hasChild(e){return!!this.root?.getElementById(e)}child(e){let i=this.root?.getElementById(e);if(!i)throw new Error(`Child with ID ${e} not found`);return i}};w.observedAttributes=[],w.tagName="",w._isRegistered=!1;var Ve='data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid" width="200" height="200" style="shape-rendering: auto; display: block; " xmlns:xlink="http://www.w3.org/1999/xlink"><g><circle cx="84" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="0.5s" calcMode="spline" keyTimes="0;1" values="10;0" keySplines="0 0.5 0.5 1" begin="0s"></animate>%0A <animate attributeName="fill" repeatCount="indefinite" dur="2s" calcMode="discrete" keyTimes="0;0.25;0.5;0.75;1" values="%23797979;%23797979;%23797979;%23797979;%23797979" begin="0s"></animate>%0A</circle><circle cx="16" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="0s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="0s"></animate>%0A</circle><circle cx="50" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-0.5s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-0.5s"></animate>%0A</circle><circle cx="84" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1s"></animate>%0A</circle><circle cx="16" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1.5s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1.5s"></animate>%0A</circle><g></g></g><!-- [ldio] generated by https://loading.io --></svg>';var Pe='data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" width="512" height="512" x="0" y="0" viewBox="0 0 475.085 475.085" style="enable-background:new 0 0 512 512" xml:space="preserve" class=""><g><path d="M237.541 328.897c25.128 0 46.632-8.946 64.523-26.83 17.888-17.884 26.833-39.399 26.833-64.525V91.365c0-25.126-8.938-46.632-26.833-64.525C284.173 8.951 262.669 0 237.541 0c-25.125 0-46.632 8.951-64.524 26.84-17.893 17.89-26.838 39.399-26.838 64.525v146.177c0 25.125 8.949 46.641 26.838 64.525 17.889 17.884 39.399 26.83 64.524 26.83z" fill="%23ffffff" opacity="1" data-original="%23000000" class=""></path><path d="M396.563 188.15c-3.606-3.617-7.898-5.426-12.847-5.426-4.944 0-9.226 1.809-12.847 5.426-3.613 3.616-5.421 7.898-5.421 12.845v36.547c0 35.214-12.518 65.333-37.548 90.362-25.022 25.03-55.145 37.545-90.36 37.545-35.214 0-65.334-12.515-90.365-37.545-25.028-25.022-37.541-55.147-37.541-90.362v-36.547c0-4.947-1.809-9.229-5.424-12.845-3.617-3.617-7.895-5.426-12.847-5.426s-9.235 1.809-12.85 5.426c-3.618 3.616-5.426 7.898-5.426 12.845v36.547c0 42.065 14.04 78.659 42.112 109.776 28.073 31.118 62.762 48.961 104.068 53.526v37.691h-73.089c-4.949 0-9.231 1.811-12.847 5.428-3.617 3.614-5.426 7.898-5.426 12.847 0 4.941 1.809 9.233 5.426 12.847 3.616 3.614 7.898 5.428 12.847 5.428h182.719c4.948 0 9.236-1.813 12.847-5.428 3.621-3.613 5.431-7.905 5.431-12.847 0-4.948-1.81-9.232-5.431-12.847-3.61-3.617-7.898-5.428-12.847-5.428h-73.08v-37.691c41.299-4.565 75.985-22.408 104.061-53.526 28.076-31.117 42.12-67.711 42.12-109.776v-36.547c0-4.946-1.813-9.225-5.435-12.845z" fill="%23ffffff" opacity="1" data-original="%23000000" class=""></path></g></svg>';var je='data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" width="512" height="512" x="0" y="0" viewBox="0 0 448.075 448.075" style="enable-background:new 0 0 512 512" xml:space="preserve" class=""><g><path d="M352.021 16.075c0-6.08-3.52-11.84-8.96-14.4-5.76-2.88-12.16-1.92-16.96 1.92l-141.76 112.96 167.68 167.68zM443.349 420.747l-416-416c-6.24-6.24-16.384-6.24-22.624 0s-6.24 16.384 0 22.624l100.672 100.704h-9.376c-9.92 0-18.56 4.48-24.32 11.52-4.8 5.44-7.68 12.8-7.68 20.48v128c0 17.6 14.4 32 32 32h74.24l155.84 124.48c2.88 2.24 6.4 3.52 9.92 3.52 2.24 0 4.8-.64 7.04-1.6 5.44-2.56 8.96-8.32 8.96-14.4v-57.376l68.672 68.672c3.136 3.136 7.232 4.704 11.328 4.704s8.192-1.568 11.328-4.672c6.24-6.272 6.24-16.384 0-22.656z" fill="%23ffffff" opacity="1" data-original="%23000000" class=""></path></g></svg>';var B=class extends w{constructor(){super(...arguments);this.html=()=>`
|
|
134
|
+
`+this.currentModel.toolGroup.getAll().map(c=>"- "+c.data?.name).join(`
|
|
135
|
+
`),this._lastSystemMsg!=l&&(this._lastSystemMsg=l,this.submitAnalyticsEvent({type:"system-msg",txt:l}));for(let c of o)for(let u of c.sections||[])if(u.type=="text")this.submitAnalyticsEvent({type:"message",role:"assistant",message:u.text||""});else if(u.type=="thinking")this.submitAnalyticsEvent({type:"thinking",role:"assistant",message:u.text||""});else if(u.type=="tool_call"){let d=s.toolResult(u.toolCallInstanceID);this.submitAnalyticsEvent({type:"action",role:"assistant",action:u.toolKbID||"",actionName:u.toolKbName||"",value:u.toolParameters,result:d?.toolErrorResponse||d?.toolSuccessResponse,isError:!!d?.toolErrorResponse})}else u.type=="tool_result"||this.submitAnalyticsEvent({type:"other",role:"assistant"});return s}finally{this.isProcessing=!1}}async toolRunKBAction(r,n){let i=Date.now();try{this.dispatchEvent(new CustomEvent("toolstart",{detail:{knowledgeBaseEntry:r,input:n,ai:this}}));let o=await r.action(n,this),s=Date.now()-i;return Gr(this,{event_type:"tool_call",value_str:r.id||"",event_properties:{tool_args:n,execution_time_ms:s,success:!0}}),this.dispatchEvent(new CustomEvent("tool",{detail:{knowledgeBaseEntry:r,input:n,ai:this,result:o}})),o}catch(o){let s=Date.now()-i;throw Gr(this,{event_type:"tool_call",value_str:r.id||"",event_properties:{tool_args:n,execution_time_ms:s,success:!1,error_message:o.message}}),this.dispatchEvent(new CustomEvent("tool",{detail:{knowledgeBaseEntry:r,input:n,ai:this,error:o}})),o}}submitAnalyticsEvent(r){if(bt().analytics===!1||this.config?.analytics===!1)return;let n=fetch(this.hubAPI+"/analytics/post",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,apiKey:this.apiKey,time:Date.now(),conversationID:this.conversationID,personaID:this.config?.id})}).catch(i=>{Wn.debug("Failed to submit analytics event:",i)});this.activeAnalyticsPromises.push(n),n.finally(()=>{this.activeAnalyticsPromises=this.activeAnalyticsPromises.filter(i=>i!==n)})}async waitForAnalytics(){this.activeAnalyticsPromises.length!==0&&(await Promise.all(this.activeAnalyticsPromises),this.activeAnalyticsPromises.length>0&&await this.waitForAnalytics())}resetConversation(){this.currentModel&&(this.currentModel.resetConversation(),this._lastKBsearch="",this._nextRequestUseKBitems=void 0,this.conversationID=dr(),this._lastSystemMsg="")}insertAssistantMessage(r){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");this.currentModel.addAssistantMessage(r)}exportState(){return{type:"intelliweave/state/v2",conversationID:this.conversationID,messages:this.currentModel?.messageGroup.getAll()}}importState(r){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");if(r?.type!="intelliweave/state/v2")throw new Error(`Invalid state type: ${r.type}`);this.conversationID=r.conversationID;for(let n of r.messages)this.currentModel.messageGroup.add(n)}clone(){let r=new el;return r.apiKey=this.apiKey,r.config=this.config,r.models=this.models,this.config?.id&&r.setModel(this.config.id),r.audio=this.audio,r.vadModel=this.vadModel,r.userID=this.userID,r.knowledgeBase=this.knowledgeBase.clone(),r}get messages(){return this.currentModel?.messageGroup.items||[]}};el.version=Vi.version,el.builtInActionsVersion="1.0.0",Wn.debug(`Loaded: version=${Vi.version} builtInActionsVersion=${el.builtInActionsVersion}`);var Ou=el;var kn=class extends HTMLElement{constructor(){super(...arguments);this._state={}}get root(){return this._shadow}static register(){this._isRegistered||(this._isRegistered=!0,this.tagName||(this.tagName="anonymous-component-"+this.name.toLowerCase().replace(/[^a-z0-9-]/g,"-")+"--"+Math.random().toString(36).substring(2)),window.customElements.define(this.tagName,this))}static create(r={},n=""){this.register();let i=document.createElement(this.tagName);for(let o in r)i.setAttribute(o,r[o]);return i.onBeforeCreate(),i.innerHTML=n,i}static add(r={},n=""){this.register();let i=o=>o.replaceAll("&","&").replaceAll('"',""").replaceAll("<","<").replaceAll(">",">");return`<${this.tagName} ${Object.keys(r).map(o=>`${o}="${i(r[o]+"")}"`).join(" ")}>${n}</${this.tagName}>`}static createElement(){return this.register(),document.createElement(this.tagName)}connectedCallback(){this._shadow||(this._shadow=this.attachShadow({mode:"closed"}),this._shadow.innerHTML=this.html(),this.onCreate()),this.onUpdate()}disconnectedCallback(){this._shadow=void 0,this.onDestroy()}html(){return""}onBeforeCreate(){}onCreate(){}onUpdate(){}onDestroy(){}attributeChangedCallback(r,n,i){this._shadow&&this.onUpdate()}get attr(){return this._attrProxy?this._attrProxy:(this._attrProxy=new Proxy({},{get:(r,n)=>this.getAttribute(n.toString())||"",set:(r,n,i)=>(this.getAttribute(n.toString())===i||(i?this.setAttribute(n.toString(),i):this.removeAttribute(n.toString()),this._shadow&&this.onUpdate()),!0)}),this._attrProxy)}get state(){return this._stateProxy?this._stateProxy:(this._stateProxy=new Proxy({},{get:(r,n)=>this._state[n],set:(r,n,i)=>(this._state[n]=i,this._shadow&&this.onUpdate(),!0)}),this._stateProxy)}hasChild(r){return!!this.root?.getElementById(r)}child(r){let n=this.root?.getElementById(r);if(!n)throw new Error(`Child with ID ${r} not found`);return n}};kn.observedAttributes=[],kn.tagName="",kn._isRegistered=!1;var SM='data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid" width="200" height="200" style="shape-rendering: auto; display: block; " xmlns:xlink="http://www.w3.org/1999/xlink"><g><circle cx="84" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="0.5s" calcMode="spline" keyTimes="0;1" values="10;0" keySplines="0 0.5 0.5 1" begin="0s"></animate>%0A <animate attributeName="fill" repeatCount="indefinite" dur="2s" calcMode="discrete" keyTimes="0;0.25;0.5;0.75;1" values="%23797979;%23797979;%23797979;%23797979;%23797979" begin="0s"></animate>%0A</circle><circle cx="16" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="0s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="0s"></animate>%0A</circle><circle cx="50" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-0.5s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-0.5s"></animate>%0A</circle><circle cx="84" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1s"></animate>%0A</circle><circle cx="16" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1.5s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1.5s"></animate>%0A</circle><g></g></g><!-- [ldio] generated by https://loading.io --></svg>';var IM='data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" width="512" height="512" x="0" y="0" viewBox="0 0 475.085 475.085" style="enable-background:new 0 0 512 512" xml:space="preserve" class=""><g><path d="M237.541 328.897c25.128 0 46.632-8.946 64.523-26.83 17.888-17.884 26.833-39.399 26.833-64.525V91.365c0-25.126-8.938-46.632-26.833-64.525C284.173 8.951 262.669 0 237.541 0c-25.125 0-46.632 8.951-64.524 26.84-17.893 17.89-26.838 39.399-26.838 64.525v146.177c0 25.125 8.949 46.641 26.838 64.525 17.889 17.884 39.399 26.83 64.524 26.83z" fill="%23ffffff" opacity="1" data-original="%23000000" class=""></path><path d="M396.563 188.15c-3.606-3.617-7.898-5.426-12.847-5.426-4.944 0-9.226 1.809-12.847 5.426-3.613 3.616-5.421 7.898-5.421 12.845v36.547c0 35.214-12.518 65.333-37.548 90.362-25.022 25.03-55.145 37.545-90.36 37.545-35.214 0-65.334-12.515-90.365-37.545-25.028-25.022-37.541-55.147-37.541-90.362v-36.547c0-4.947-1.809-9.229-5.424-12.845-3.617-3.617-7.895-5.426-12.847-5.426s-9.235 1.809-12.85 5.426c-3.618 3.616-5.426 7.898-5.426 12.845v36.547c0 42.065 14.04 78.659 42.112 109.776 28.073 31.118 62.762 48.961 104.068 53.526v37.691h-73.089c-4.949 0-9.231 1.811-12.847 5.428-3.617 3.614-5.426 7.898-5.426 12.847 0 4.941 1.809 9.233 5.426 12.847 3.616 3.614 7.898 5.428 12.847 5.428h182.719c4.948 0 9.236-1.813 12.847-5.428 3.621-3.613 5.431-7.905 5.431-12.847 0-4.948-1.81-9.232-5.431-12.847-3.61-3.617-7.898-5.428-12.847-5.428h-73.08v-37.691c41.299-4.565 75.985-22.408 104.061-53.526 28.076-31.117 42.12-67.711 42.12-109.776v-36.547c0-4.946-1.813-9.225-5.435-12.845z" fill="%23ffffff" opacity="1" data-original="%23000000" class=""></path></g></svg>';var EM='data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" width="512" height="512" x="0" y="0" viewBox="0 0 448.075 448.075" style="enable-background:new 0 0 512 512" xml:space="preserve" class=""><g><path d="M352.021 16.075c0-6.08-3.52-11.84-8.96-14.4-5.76-2.88-12.16-1.92-16.96 1.92l-141.76 112.96 167.68 167.68zM443.349 420.747l-416-416c-6.24-6.24-16.384-6.24-22.624 0s-6.24 16.384 0 22.624l100.672 100.704h-9.376c-9.92 0-18.56 4.48-24.32 11.52-4.8 5.44-7.68 12.8-7.68 20.48v128c0 17.6 14.4 32 32 32h74.24l155.84 124.48c2.88 2.24 6.4 3.52 9.92 3.52 2.24 0 4.8-.64 7.04-1.6 5.44-2.56 8.96-8.32 8.96-14.4v-57.376l68.672 68.672c3.136 3.136 7.232 4.704 11.328 4.704s8.192-1.568 11.328-4.672c6.24-6.272 6.24-16.384 0-22.656z" fill="%23ffffff" opacity="1" data-original="%23000000" class=""></path></g></svg>';var Zp=class extends kn{constructor(){super(...arguments);this.html=()=>`
|
|
49
136
|
|
|
50
137
|
<!-- Styling -->
|
|
51
138
|
<style>
|
|
@@ -62,6 +149,11 @@ ${s}`,cannotRemove:o.isContext,sortOrder:101,disabled:typeof o.disabled=="functi
|
|
|
62
149
|
color: var(--intelliweave-text-color, white);
|
|
63
150
|
}
|
|
64
151
|
|
|
152
|
+
/** Remove top border in fullscreen UI */
|
|
153
|
+
:host([layout="fullscreen"]) {
|
|
154
|
+
border-top: none;
|
|
155
|
+
}
|
|
156
|
+
|
|
65
157
|
:host input {
|
|
66
158
|
flex: 1 1 1px;
|
|
67
159
|
border: none;
|
|
@@ -88,8 +180,39 @@ ${s}`,cannotRemove:o.isContext,sortOrder:101,disabled:typeof o.disabled=="functi
|
|
|
88
180
|
border: 1px solid rgba(255, 255, 255, 0.2);
|
|
89
181
|
}
|
|
90
182
|
|
|
183
|
+
:host #send-button {
|
|
184
|
+
flex: 0 0 auto;
|
|
185
|
+
width: 34px;
|
|
186
|
+
height: 34px;
|
|
187
|
+
margin: 0 4px 0 0;
|
|
188
|
+
border-radius: 8px;
|
|
189
|
+
background-color: var(--intelliweave-persona-bg, var(--intelliweave-background, #4a6572));
|
|
190
|
+
border: none;
|
|
191
|
+
cursor: pointer;
|
|
192
|
+
display: flex;
|
|
193
|
+
align-items: center;
|
|
194
|
+
justify-content: center;
|
|
195
|
+
transition: opacity 0.15s ease;
|
|
196
|
+
}
|
|
197
|
+
:host #send-button svg {
|
|
198
|
+
width: 18px;
|
|
199
|
+
height: 18px;
|
|
200
|
+
fill: var(--intelliweave-text-color, white);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** Remove send button background in widget UI */
|
|
204
|
+
:host([layout="widget"]) #send-button {
|
|
205
|
+
background-color: transparent;
|
|
206
|
+
opacity: 0.5;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** Send button hover */
|
|
210
|
+
:host #send-button:hover {
|
|
211
|
+
opacity: 0.85;
|
|
212
|
+
}
|
|
213
|
+
|
|
91
214
|
:host #loader {
|
|
92
|
-
background-image: url('${
|
|
215
|
+
background-image: url('${SM}');
|
|
93
216
|
background-size: 64px 64px;
|
|
94
217
|
background-position: center;
|
|
95
218
|
background-repeat: no-repeat;
|
|
@@ -112,7 +235,7 @@ ${s}`,cannotRemove:o.isContext,sortOrder:101,disabled:typeof o.disabled=="functi
|
|
|
112
235
|
}
|
|
113
236
|
|
|
114
237
|
:host #microphone-button {
|
|
115
|
-
background-image: url('${
|
|
238
|
+
background-image: url('${IM}');
|
|
116
239
|
z-index: 2;
|
|
117
240
|
margin-right: -10px;
|
|
118
241
|
}
|
|
@@ -136,7 +259,7 @@ ${s}`,cannotRemove:o.isContext,sortOrder:101,disabled:typeof o.disabled=="functi
|
|
|
136
259
|
}
|
|
137
260
|
|
|
138
261
|
:host #cancel-speech-button {
|
|
139
|
-
background-image: url('${
|
|
262
|
+
background-image: url('${EM}');
|
|
140
263
|
z-index: 2;
|
|
141
264
|
}
|
|
142
265
|
|
|
@@ -157,10 +280,17 @@ ${s}`,cannotRemove:o.isContext,sortOrder:101,disabled:typeof o.disabled=="functi
|
|
|
157
280
|
<!-- LLM button -->
|
|
158
281
|
<div id='llm-button'>LLM</div>
|
|
159
282
|
|
|
283
|
+
<!-- Send button -->
|
|
284
|
+
<button id='send-button' type='button' aria-label='Send message'>
|
|
285
|
+
<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
|
|
286
|
+
<path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/>
|
|
287
|
+
</svg>
|
|
288
|
+
</button>
|
|
289
|
+
|
|
160
290
|
<!-- Loader bar -->
|
|
161
291
|
<div id='loader'></div>
|
|
162
292
|
|
|
163
|
-
`;this._wasLoading=!1;this.voiceAnimationPieces=[];this._micAnimFrameCounter=0}onCreate(){this.child("input-field").addEventListener("keypress",
|
|
293
|
+
`;this._wasLoading=!1;this.voiceAnimationPieces=[];this._micAnimFrameCounter=0}onCreate(){this.child("input-field").addEventListener("keypress",r=>this.onInputKeyPress(r),{capture:!0}),this.child("input-field").addEventListener("keydown",r=>r.stopPropagation(),{capture:!0}),this.child("llm-button").addEventListener("click",r=>this.onLLMButtonClick(r)),this.child("send-button").addEventListener("click",r=>this.onSendButtonClick(r)),this.child("microphone-button").addEventListener("click",r=>this.onMicButtonClick(r)),this.child("cancel-speech-button").addEventListener("click",r=>this.onCancelSpeechButtonClick(r))}connectAI(r){this.ai=r,this.ai.audio?.speechRecognition.addEventListener("speech",n=>this.onSpeechEvent(n)),this.ai.audio?.speechRecognition.addEventListener("start",n=>this.onUpdate()),this.ai.audio?.speechRecognition.addEventListener("end",n=>this.onUpdate()),this.ai.audio?.speechOutput.addEventListener("speechstart",n=>this.onUpdate()),this.ai.audio?.speechOutput.addEventListener("speechend",n=>this.onUpdate()),this.onUpdate()}onUpdate(){this.attr.textColor&&document.documentElement.style.setProperty("--intelliweave-text-color",this.attr.textColor),this.child("input-field").style.display=this.attr.loading||this.ai?.audio?.speechRecognition.isRunning?"none":"",this.child("llm-button").style.display=this.attr.loading||!this.attr.llmButtonVisible||this.state.micActiv?"none":"",this.child("llm-button").innerText=this.attr.llmName||"LLM",this.child("send-button").style.display=this.attr.loading||this.ai?.audio?.speechRecognition.isRunning?"none":"",this.child("loader").style.display=this.attr.loading?"block":"",this.child("microphone-button").style.display=!this.ai?.audio?.speechRecognition?.isSupported||this.attr.loading&&!this.ai?.audio?.speechRecognition.isRunning?"none":"",this.child("cancel-speech-button").style.display="none",this.ai?.audio?.speechRecognition.isRunning&&this.ai?.audio?.speechOutput.isSpeaking&&(this.child("microphone-button").style.display="none",this.child("cancel-speech-button").style.display=""),!this.attr.loading&&this._wasLoading&&this.child("input-field").focus(),this._wasLoading=this.attr.loading,this.child("microphone-button-bg").classList.toggle("active",!!this.ai?.audio?.speechRecognition.isRunning);let r=this.ai?.audio?.speechRecognition.isRunning&&!this.attr.loading;r&&!this.micStateAnimationTimer?this.micStateAnimationTimer=setInterval(()=>this.onMicAnimation(),1e3/60):!r&&this.micStateAnimationTimer&&(this.voiceAnimationPieces.forEach(n=>n.remove()),this.voiceAnimationPieces=[],clearInterval(this.micStateAnimationTimer),this.micStateAnimationTimer=void 0)}onInputKeyPress(r){if(r.stopPropagation(),r.key!="Enter")return;let n=this.child("input-field"),i=n.value?.trim();n.value="",i&&this.dispatchEvent(new CustomEvent("input-message",{detail:i}))}onLLMButtonClick(r){r.preventDefault(),this.dispatchEvent(new CustomEvent("llm-button-click"))}onSendButtonClick(r){r.preventDefault();let n=this.child("input-field"),i=n.value?.trim();n.value="",i&&this.dispatchEvent(new CustomEvent("input-message",{detail:i}))}onMicButtonClick(r){r.preventDefault(),this.ai.audio?.speechRecognition.isRunning?this.ai.audio?.speechRecognition.stop():this.ai.audio?.speechRecognition.start()}onMicAnimation(){if(!this.attr.loading){if(this._micAnimFrameCounter++,this._micAnimFrameCounter%5==0){let r="rgba(140, 170, 200, 0.5)";this.ai?.audio?.speechRecognition.voiceDetection?.isModelLoaded||(r="rgba(255, 0, 0, 0.5)"),this.ai?.audio?.speechRecognition.voiceDetection?.isTranscribing&&(r="rgba(96, 66, 245, 0.9)"),this.ai?.audio?.speechRecognition.wordsCurrentlyBeingSpoken&&(r="rgba(0, 128, 255, 0.9)"),this.ai?.audio?.speechRecognition.voiceDetection?.isVoicePossiblyEnding&&(r="rgba(0, 128, 255, 0.5)"),this.ai?.isProcessing&&(r="rgba(255, 255, 0, 0.5)"),this.ai?.audio?.speechOutput.isSpeaking&&(r="rgba(0, 255, 0, 0.5)");let n=this.ai?.audio?.speechRecognition.volumeLevel||0,i=30,o=6,s=Math.round(n*(i-o)+o),a=document.createElement("div");a.posX=50,a.style.cssText=`position: absolute; top: calc(50% - ${s}px/2); left: 0px; width: 6px; height: ${s}px; background-color: ${r}; border-radius: 3px; pointer-events: none; `,this.root?.appendChild(a),this.voiceAnimationPieces.push(a)}for(let r=0;r<this.voiceAnimationPieces.length;r++){let n=this.voiceAnimationPieces[r];n.posX+=2,n.style.transform=`translate(${n.posX}px, 0px)`,!(n.posX<400)&&(this.voiceAnimationPieces.splice(r--,1),n.remove())}}}onSpeechEvent(r){this.attr.loading||r.detail.isFinal&&this.dispatchEvent(new CustomEvent("input-message",{detail:r.detail.transcript}))}onCancelSpeechButtonClick(r){this.ai.audio?.speechOutput.interrupt(),this.onUpdate()}};Zp.observedAttributes=["loading","llmName","llmButtonVisible","textColor","layout"];var PM='data:image/svg+xml,<svg id="eLjt8NmVnoY1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 300 300" shape-rendering="geometricPrecision" text-rendering="geometricPrecision" project-id="defaf4a7213e40159eb368f9622a2af1" export-id="e0405e7e1d4a45c0a08fbbedb06a02a8" cached="false"><defs><radialGradient id="eLjt8NmVnoY6-fill" cx="0" cy="0" r="1" spreadMethod="pad" gradientUnits="userSpaceOnUse" gradientTransform="matrix(-58.520001 292.985 -172.197 -34.394001 203.907 57.158)"><stop id="eLjt8NmVnoY6-fill-0" offset="0%" stop-color="%232b3d43"/><stop id="eLjt8NmVnoY6-fill-1" offset="33%" stop-color="%23328897"/><stop id="eLjt8NmVnoY6-fill-2" offset="58%" stop-color="%23328897"/><stop id="eLjt8NmVnoY6-fill-3" offset="100%" stop-color="%237ebf96"/></radialGradient><radialGradient id="eLjt8NmVnoY7-fill" cx="0" cy="0" r="1.112049" spreadMethod="pad" gradientUnits="userSpaceOnUse" gradientTransform="matrix(182.129 -94.016999 94.016999 182.129 43.4553 184.626)"><stop id="eLjt8NmVnoY7-fill-0" offset="0%" stop-color="%233f2d2d"/><stop id="eLjt8NmVnoY7-fill-1" offset="28%" stop-color="%23c83b35"/><stop id="eLjt8NmVnoY7-fill-2" offset="81%" stop-color="%23f69153"/><stop id="eLjt8NmVnoY7-fill-3" offset="100%" stop-color="%23ffe388"/></radialGradient><radialGradient id="eLjt8NmVnoY9-fill" cx="0" cy="0" r="593.59" spreadMethod="pad" gradientUnits="userSpaceOnUse" gradientTransform="matrix(-0.196117 0.98058 -0.578542 -0.115709 406.499077 117.274778)"><stop id="eLjt8NmVnoY9-fill-0" offset="0%" stop-color="%23252d3a"/><stop id="eLjt8NmVnoY9-fill-1" offset="60%" stop-color="%23c50"/><stop id="eLjt8NmVnoY9-fill-2" offset="100%" stop-color="%23fddc85"/></radialGradient><radialGradient id="eLjt8NmVnoY10-fill" cx="0" cy="0" r="454.77" spreadMethod="pad" gradientUnits="userSpaceOnUse" gradientTransform="translate(87.33 340.7)"><stop id="eLjt8NmVnoY10-fill-0" offset="0%" stop-color="%23002936"/><stop id="eLjt8NmVnoY10-fill-1" offset="44%" stop-color="%23007aa1"/><stop id="eLjt8NmVnoY10-fill-2" offset="67%" stop-color="%2326ab7f"/><stop id="eLjt8NmVnoY10-fill-3" offset="100%" stop-color="%2395e0c8"/></radialGradient></defs><g transform="matrix(.339855 0 0 0.339855 65.056641 64.89012)"><path d="M337.93,111.85c17.31-4.12,30.6-2.15,38.55,5.96c12.9,13.16,10.13,41.58-7.64,77.95-34.66,70.98-116.01,153.37-181.35,183.6-4.15,1.92-8.16,3.6-12.02,5.03l.05.18C83.95,418.36,13.7,365.53,1.49,278.27C15.34,403.24,121.28,500.43,249.94,500.43c138.07,0,250-111.93,250-250c0-9.8-.58-19.46-1.68-28.96-12-82.27-75.81-133.5-160.33-109.62Z" fill="url(%23eLjt8NmVnoY9-fill)"/><path d="M249.94,0.43c-138.07,0-250,111.93-250,250c0,9.41.54,18.69,1.55,27.84C13.7,365.54,83.95,418.36,175.52,384.58l-.05-.18c-11.22,4.17-21.17,6.24-29.61,6.24-9.59,0-17.18-2.67-22.44-8.03-12.9-13.19-10.13-41.61,7.64-77.98c18.26-37.41,49.51-77.98,84.51-112.41c31.45-32.33,62.2-54.66,91.14-68.47.16-.08.34-.16.49-.23c1.74-.85,3.47-1.68,5.18-2.49c9.22-4.27,17.77-7.33,25.54-9.17c84.52-23.88,148.33,27.35,160.33,109.62C483.91,97.04,378.22,0.43,249.94,0.43Z" fill="url(%23eLjt8NmVnoY10-fill)"/><path d="M337.93,111.85c-7.77,1.84-16.32,4.9-25.54,9.17-1.71.8-3.45,1.63-5.18,2.49-.16.08-.34.16-.49.23-28.94,13.81-59.69,36.14-91.14,68.47-35,34.43-66.24,75-84.51,112.41-17.77,36.37-20.54,64.79-7.64,77.98c5.26,5.36,12.85,8.03,22.44,8.03c8.45,0,18.39-2.07,29.61-6.24c3.86-1.42,7.88-3.11,12.02-5.03c65.34-30.23,146.68-112.62,181.35-183.6c17.77-36.37,20.54-64.79,7.64-77.95-7.95-8.11-21.24-10.08-38.55-5.96h-.01Z" fill="%23252d3a"/></g></svg>%0D%0A';var Fp=class extends kn{constructor(){super(...arguments);this.html=()=>`
|
|
164
294
|
|
|
165
295
|
<!-- Styling -->
|
|
166
296
|
<style>
|
|
@@ -213,7 +343,32 @@ ${s}`,cannotRemove:o.isContext,sortOrder:101,disabled:typeof o.disabled=="functi
|
|
|
213
343
|
<!-- Logo -->
|
|
214
344
|
<img id='root' />
|
|
215
345
|
|
|
216
|
-
`;this._lastLogoSrc=""}onCreate(){this.layoutUpdateTimer=setInterval(()=>this.onUpdate(),100)}onDestroy(){clearInterval(this.layoutUpdateTimer)}onUpdate(){let e=this.child("root");if(!e)return;let i=this.attr.logo||ze;this._lastLogoSrc!=i&&(this._lastLogoSrc=i,e.src=i);let o=this.attr.focusID?document.getElementById(this.attr.focusID):null;if(o){let s=window.visualViewport?.offsetTop||0,n=window.visualViewport?.offsetLeft||0,a=o.getBoundingClientRect();if(!a)return;e.classList.add("focused-mode"),e.style.width="128px",e.style.height="128px",e.style.left=Math.round(a.x+a.width/2-128/2+n)+"px",e.style.top=Math.round(a.y+a.height/2-128/2+s)+"px"}else e.classList.remove("focused-mode"),e.style.width="",e.style.height="",e.style.left="",e.style.top=""}refreshLayout(){setTimeout(()=>this.onUpdate(),100)}};Y.observedAttributes=["logo","focusID"];import Ue from"rehype-external-links";import Ke from"rehype-format";import Fe from"rehype-stringify";import He from"remark-parse";import Je from"remark-rehype";import{unified as Qe}from"unified";var _=class extends w{constructor(){super(...arguments);this.html=()=>`
|
|
346
|
+
`;this._lastLogoSrc=""}onCreate(){this.layoutUpdateTimer=setInterval(()=>this.onUpdate(),100)}onDestroy(){clearInterval(this.layoutUpdateTimer)}onUpdate(){let r=this.child("root");if(!r)return;let n=this.attr.logo||PM;this._lastLogoSrc!=n&&(this._lastLogoSrc=n,r.src=n);let i=this.attr.focusID?document.getElementById(this.attr.focusID):null;if(i){let o=window.visualViewport?.offsetTop||0,s=window.visualViewport?.offsetLeft||0,a=i.getBoundingClientRect();if(!a)return;r.classList.add("focused-mode"),r.style.width="128px",r.style.height="128px",r.style.left=Math.round(a.x+a.width/2-128/2+s)+"px",r.style.top=Math.round(a.y+a.height/2-128/2+o)+"px"}else r.classList.remove("focused-mode"),r.style.width="",r.style.height="",r.style.left="",r.style.top=""}refreshLayout(){setTimeout(()=>this.onUpdate(),100)}};Fp.observedAttributes=["logo","focusID"];var TM=typeof self=="object"?self:globalThis,g8=(t,e)=>{let r=(i,o)=>(t.set(o,i),i),n=i=>{if(t.has(i))return t.get(i);let[o,s]=e[i];switch(o){case 0:case-1:return r(s,i);case 1:{let a=r([],i);for(let l of s)a.push(n(l));return a}case 2:{let a=r({},i);for(let[l,c]of s)a[n(l)]=n(c);return a}case 3:return r(new Date(s),i);case 4:{let{source:a,flags:l}=s;return r(new RegExp(a,l),i)}case 5:{let a=r(new Map,i);for(let[l,c]of s)a.set(n(l),n(c));return a}case 6:{let a=r(new Set,i);for(let l of s)a.add(n(l));return a}case 7:{let{name:a,message:l}=s;return r(new TM[a](l),i)}case 8:return r(BigInt(s),i);case"BigInt":return r(Object(BigInt(s)),i)}return r(new TM[o](s),i)};return n},lI=t=>g8(new Map,t)(0);var Ru="",{toString:y8}={},{keys:v8}=Object,Bp=t=>{let e=typeof t;if(e!=="object"||!t)return[0,e];let r=y8.call(t).slice(8,-1);switch(r){case"Array":return[1,Ru];case"Object":return[2,Ru];case"Date":return[3,Ru];case"RegExp":return[4,Ru];case"Map":return[5,Ru];case"Set":return[6,Ru]}return r.includes("Array")?[1,r]:r.includes("Error")?[7,r]:[2,r]},lv=([t,e])=>t===0&&(e==="function"||e==="symbol"),_8=(t,e,r,n)=>{let i=(s,a)=>{let l=n.push(s)-1;return r.set(a,l),l},o=s=>{if(r.has(s))return r.get(s);let[a,l]=Bp(s);switch(a){case 0:{let u=s;switch(l){case"bigint":a=8,u=s.toString();break;case"function":case"symbol":if(t)throw new TypeError("unable to serialize "+l);u=null;break;case"undefined":return i([-1],s)}return i([a,u],s)}case 1:{if(l)return i([l,[...s]],s);let u=[],d=i([a,u],s);for(let p of s)u.push(o(p));return d}case 2:{if(l)switch(l){case"BigInt":return i([l,s.toString()],s);case"Boolean":case"Number":case"String":return i([l,s.valueOf()],s)}if(e&&"toJSON"in s)return o(s.toJSON());let u=[],d=i([a,u],s);for(let p of v8(s))(t||!lv(Bp(s[p])))&&u.push([o(p),o(s[p])]);return d}case 3:return i([a,s.toISOString()],s);case 4:{let{source:u,flags:d}=s;return i([a,{source:u,flags:d}],s)}case 5:{let u=[],d=i([a,u],s);for(let[p,f]of s)(t||!(lv(Bp(p))||lv(Bp(f))))&&u.push([o(p),o(f)]);return d}case 6:{let u=[],d=i([a,u],s);for(let p of s)(t||!lv(Bp(p)))&&u.push(o(p));return d}}let{message:c}=s;return i([a,{name:l,message:c}],s)};return o},cI=(t,{json:e,lossy:r}={})=>{let n=[];return _8(!(e||r),!!e,new Map,n)(t),n};var qi=typeof structuredClone=="function"?(t,e)=>e&&("json"in e||"lossy"in e)?lI(cI(t,e)):structuredClone(t):(t,e)=>lI(cI(t,e));var Wi=function(t,e,r,n,i){let o=Bi(e);if(r!=null&&(typeof r!="number"||r<0||r===Number.POSITIVE_INFINITY))throw new Error("Expected positive finite `index`");if(n!=null&&(!n.type||!n.children))throw new Error("Expected valid `parent`");if(r==null!=(n==null))throw new Error("Expected both `index` and `parent`");return AM(t)?o.call(i,t,r,n):!1},Bi=function(t){if(t==null)return x8;if(typeof t=="string")return w8(t);if(typeof t=="object")return b8(t);if(typeof t=="function")return uI(t);throw new Error("Expected function, string, or array as `test`")};function b8(t){let e=[],r=-1;for(;++r<t.length;)e[r]=Bi(t[r]);return uI(n);function n(...i){let o=-1;for(;++o<e.length;)if(e[o].apply(this,i))return!0;return!1}}function w8(t){return uI(e);function e(r){return r.tagName===t}}function uI(t){return e;function e(r,n,i){return!!(AM(r)&&t.call(this,r,typeof n=="number"?n:void 0,i||void 0))}}function x8(t){return!!(t&&typeof t=="object"&&"type"in t&&t.type==="element"&&"tagName"in t&&typeof t.tagName=="string")}function AM(t){return t!==null&&typeof t=="object"&&"type"in t&&"tagName"in t}var $8=/^[a-zA-Z][a-zA-Z\d+\-.]*?:/,k8=/^[a-zA-Z]:\\/;function dI(t){if(typeof t!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof t}\``);return k8.test(t)?!1:$8.test(t)}function zM(t){let e=String(t||"").trim();return e?e.split(/[ \t\n\r\f]+/g):[]}function CM(t){return t.join(" ").trim()}var Mu=function(t){if(t==null)return P8;if(typeof t=="function")return cv(t);if(typeof t=="object")return Array.isArray(t)?S8(t):I8(t);if(typeof t=="string")return E8(t);throw new Error("Expected function, string, or object as test")};function S8(t){let e=[],r=-1;for(;++r<t.length;)e[r]=Mu(t[r]);return cv(n);function n(...i){let o=-1;for(;++o<e.length;)if(e[o].apply(this,i))return!0;return!1}}function I8(t){let e=t;return cv(r);function r(n){let i=n,o;for(o in t)if(i[o]!==e[o])return!1;return!0}}function E8(t){return cv(e);function e(r){return r&&r.type===t}}function cv(t){return e;function e(r,n,i){return!!(T8(r)&&t.call(this,r,typeof n=="number"?n:void 0,i||void 0))}}function P8(){return!0}function T8(t){return t!==null&&typeof t=="object"&&"type"in t}var NM=[],fI=!0,uv=!1,Gp="skip";function Hp(t,e,r,n){let i;typeof e=="function"&&typeof r!="function"?(n=r,r=e):i=e;let o=Mu(i),s=n?-1:1;a(t,void 0,[])();function a(l,c,u){let d=l&&typeof l=="object"?l:{};if(typeof d.type=="string"){let f=typeof d.tagName=="string"?d.tagName:typeof d.name=="string"?d.name:void 0;Object.defineProperty(p,"name",{value:"node ("+(l.type+(f?"<"+f+">":""))+")"})}return p;function p(){let f=NM,m,h,y;if((!e||o(l,c,u[u.length-1]||void 0))&&(f=A8(r(l,u)),f[0]===uv))return f;if("children"in l&&l.children){let g=l;if(g.children&&f[0]!==Gp)for(h=(n?g.children.length:-1)+s,y=u.concat(g);h>-1&&h<g.children.length;){let _=g.children[h];if(m=a(_,h,y)(),m[0]===uv)return m;h=typeof m[1]=="number"?m[1]:h+s}}return f}}}function A8(t){return Array.isArray(t)?t:typeof t=="number"?[fI,t]:t==null?NM:[t]}function Xp(t,e,r,n){let i,o,s;typeof e=="function"&&typeof r!="function"?(o=void 0,s=e,i=r):(o=e,s=r,i=n),Hp(t,o,a,i);function a(l,c){let u=c[c.length-1],d=u?u.children.indexOf(l):void 0;return s(l,d,u)}}var z8=["http","https"],C8=["nofollow"],N8={};function Jp(t){let e=t||N8,r=e.protocols||z8,n=Bi(e.test);return function(i){Xp(i,"element",function(o,s,a){if(o.tagName==="a"&&typeof o.properties.href=="string"&&n(o,s,a)){let l=o.properties.href;if(dI(l)?r.includes(l.slice(0,l.indexOf(":"))):l.startsWith("//")){let c=Kp(e.content,o),u=c&&!Array.isArray(c)?[c]:c,d=Kp(e.rel,o)||C8,p=typeof d=="string"?zM(d):d,f=Kp(e.target,o),m=Kp(e.properties,o);if(m&&Object.assign(o.properties,qi(m)),p.length>0&&(o.properties.rel=[...p]),f&&(o.properties.target=f),u){let h=Kp(e.contentProperties,o)||{};o.children.push({type:"element",tagName:"span",properties:qi(h),children:qi(u)})}}}})}}function Kp(t,e){return typeof t=="function"?t(e):t}var tl=Bi(function(t){return t.tagName==="audio"||t.tagName==="canvas"||t.tagName==="embed"||t.tagName==="iframe"||t.tagName==="img"||t.tagName==="math"||t.tagName==="object"||t.tagName==="picture"||t.tagName==="svg"||t.tagName==="video"});var O8={}.hasOwnProperty;function pI(t,e){let r=t.type==="element"&&O8.call(t.properties,e)&&t.properties[e];return r!=null&&r!==!1}var R8=new Set(["pingback","prefetch","stylesheet"]);function mI(t){if(t.type!=="element"||t.tagName!=="link")return!1;if(t.properties.itemProp)return!0;let e=t.properties.rel,r=-1;if(!Array.isArray(e)||e.length===0)return!1;for(;++r<e.length;)if(!R8.has(String(e[r])))return!1;return!0}var M8=Bi(["a","abbr","area","b","bdi","bdo","br","button","cite","code","data","datalist","del","dfn","em","i","input","ins","kbd","keygen","label","map","mark","meter","noscript","output","progress","q","ruby","s","samp","script","select","small","span","strong","sub","sup","template","textarea","time","u","var","wbr"]),j8=Bi("meta");function hI(t){return!!(t.type==="text"||M8(t)||tl(t)||mI(t)||j8(t)&&pI(t,"itemProp"))}var D8=/[ \t\n\f\r]/g;function Sn(t){return typeof t=="object"?t.type==="text"?OM(t.value):!1:OM(t)}function OM(t){return t.replace(D8,"")===""}var gI=["pre","script","style","textarea"];var RM=["address","article","aside","blockquote","body","br","caption","center","col","colgroup","dd","dialog","dir","div","dl","dt","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","legend","li","li","listing","main","menu","nav","ol","optgroup","option","p","plaintext","pre","section","summary","table","tbody","td","td","tfoot","th","th","thead","tr","ul","wbr","xmp"];var MM=["button","input","select","textarea"];var jM=["area","base","basefont","dialog","datalist","head","link","meta","noembed","noframes","param","rp","script","source","style","template","track","title"];var L8={},yI=Mu(["doctype","comment"]);function dv(t){let r=B8((t||L8).newlines?q8:W8);return function(n){LM(n,{collapse:r,whitespace:"normal"})}}function LM(t,e){if("children"in t){let r={...e};return(t.type==="root"||FM(t))&&(r.before=!0,r.after=!0),r.whitespace=G8(t,e),Z8(t,r)}if(t.type==="text"){if(e.whitespace==="normal")return U8(t,e);e.whitespace==="nowrap"&&(t.value=e.collapse(t.value))}return{ignore:yI(t),stripAtStart:!1,remove:!1}}function U8(t,e){let r=e.collapse(t.value),n={ignore:!1,stripAtStart:!1,remove:!1},i=0,o=r.length;return e.before&&DM(r.charAt(0))&&i++,i!==o&&DM(r.charAt(o-1))&&(e.after?o--:n.stripAtStart=!0),i===o?n.remove=!0:t.value=r.slice(i,o),n}function Z8(t,e){let r=e.before,n=e.after,i=t.children,o=i.length,s=-1;for(;++s<o;){let a=LM(i[s],{...e,after:UM(i,s,n),before:r});a.remove?(i.splice(s,1),s--,o--):a.ignore||(r=a.stripAtStart),ZM(i[s])&&(r=!1)}return{ignore:!1,stripAtStart:!!(r||n),remove:!1}}function UM(t,e,r){for(;++e<t.length;){let n=t[e],i=F8(n);if(i===void 0&&"children"in n&&!V8(n)&&(i=UM(n.children,-1)),typeof i=="boolean")return i}return r}function F8(t){if(t.type==="element"){if(ZM(t))return!1;if(FM(t))return!0}else if(t.type==="text"){if(!Sn(t))return!1}else if(!yI(t))return!1}function ZM(t){return tl(t)||Wi(t,MM)}function FM(t){return Wi(t,RM)}function V8(t){return!!(t.type==="element"&&t.properties.hidden)||yI(t)||Wi(t,jM)}function DM(t){return t===" "||t===`
|
|
347
|
+
`}function q8(t){let e=/\r?\n|\r/.exec(t);return e?e[0]:" "}function W8(){return" "}function B8(t){return e;function e(r){return String(r).replace(/[\t\n\v\f\r ]+/g,t)}}function G8(t,e){if("tagName"in t&&t.properties)switch(t.tagName){case"listing":case"plaintext":case"script":case"style":case"xmp":return"pre";case"nobr":return"nowrap";case"pre":return t.properties.wrap?"pre-wrap":"pre";case"td":case"th":return t.properties.noWrap?"nowrap":e.whitespace;case"textarea":return"pre-wrap";default:}return e.whitespace}var H8={},X8=dv({newlines:!0});function Yp(t){let e=t||H8,r=e.indent||2,n=e.indentInitial;return typeof r=="number"&&(r=" ".repeat(r)),n==null&&(n=!0),function(s){let a;X8(s),Hp(s,function(l,c){let u=-1;if(!("children"in l))return;if(Wi(l,"head")&&(a=!0),a&&Wi(l,"body")&&(a=void 0),Wi(l,gI))return Gp;let d=l.children,p=c.length;if(d.length===0||!vI(l,a))return;n||p--;let f;for(;++u<d.length;){let y=d[u];(y.type==="text"||y.type==="comment")&&(y.value.includes(`
|
|
348
|
+
`)&&(f=!0),y.value=y.value.replace(/ *\n/g,"$&"+String(r).repeat(p)))}let m=[],h;for(u=-1;++u<d.length;){let y=d[u];(vI(y,a)||f&&!u)&&(i(m,p,y),f=!0),h=y,m.push(y)}h&&(f||vI(h,a))&&(Sn(h)&&(m.pop(),h=m[m.length-1]),i(m,p-1)),l.children=m})};function i(s,a,l){let c=s[s.length-1],u=c&&Sn(c)?s[s.length-2]:c,d=(o(u)&&o(l)?`
|
|
349
|
+
|
|
350
|
+
`:`
|
|
351
|
+
`)+String(r).repeat(Math.max(a,0));c&&c.type==="text"?c.value=Sn(c)?d:c.value+d:s.push({type:"text",value:d})}function o(s){return!!(s&&s.type==="element"&&e.blanks&&e.blanks.length>0&&e.blanks.includes(s.tagName))}}function vI(t,e){return t.type==="root"||(t.type==="element"?e||Wi(t,"script")||tl(t)||!hI(t):!1)}var VM=["area","base","basefont","bgsound","br","col","command","embed","frame","hr","image","img","input","keygen","link","meta","param","source","track","wbr"];var Oo=class{constructor(e,r,n){this.property=e,this.normal=r,n&&(this.space=n)}};Oo.prototype.property={};Oo.prototype.normal={};Oo.prototype.space=null;function _I(t,e){let r={},n={},i=-1;for(;++i<t.length;)Object.assign(r,t[i].property),Object.assign(n,t[i].normal);return new Oo(r,n,e)}function Qp(t){return t.toLowerCase()}var Rr=class{constructor(e,r){this.property=e,this.attribute=r}};Rr.prototype.space=null;Rr.prototype.boolean=!1;Rr.prototype.booleanish=!1;Rr.prototype.overloadedBoolean=!1;Rr.prototype.number=!1;Rr.prototype.commaSeparated=!1;Rr.prototype.spaceSeparated=!1;Rr.prototype.commaOrSpaceSeparated=!1;Rr.prototype.mustUseProperty=!1;Rr.prototype.defined=!1;var em={};ed(em,{boolean:()=>ke,booleanish:()=>Nt,commaOrSpaceSeparated:()=>cn,commaSeparated:()=>Cs,number:()=>F,overloadedBoolean:()=>bI,spaceSeparated:()=>lt});var K8=0,ke=rl(),Nt=rl(),bI=rl(),F=rl(),lt=rl(),Cs=rl(),cn=rl();function rl(){return 2**++K8}var wI=Object.keys(em),nl=class extends Rr{constructor(e,r,n,i){let o=-1;if(super(e,r),qM(this,"space",i),typeof n=="number")for(;++o<wI.length;){let s=wI[o];qM(this,wI[o],(n&em[s])===em[s])}}};nl.prototype.defined=!0;function qM(t,e,r){r&&(t[e]=r)}var J8={}.hasOwnProperty;function Bn(t){let e={},r={},n;for(n in t.properties)if(J8.call(t.properties,n)){let i=t.properties[n],o=new nl(n,t.transform(t.attributes||{},n),i,t.space);t.mustUseProperty&&t.mustUseProperty.includes(n)&&(o.mustUseProperty=!0),e[n]=o,r[Qp(n)]=n,r[Qp(o.attribute)]=n}return new Oo(e,r,t.space)}var xI=Bn({space:"xlink",transform(t,e){return"xlink:"+e.slice(5).toLowerCase()},properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null}});var $I=Bn({space:"xml",transform(t,e){return"xml:"+e.slice(3).toLowerCase()},properties:{xmlLang:null,xmlBase:null,xmlSpace:null}});function fv(t,e){return e in t?t[e]:e}function pv(t,e){return fv(t,e.toLowerCase())}var kI=Bn({space:"xmlns",attributes:{xmlnsxlink:"xmlns:xlink"},transform:pv,properties:{xmlns:null,xmlnsXLink:null}});var SI=Bn({transform(t,e){return e==="role"?e:"aria-"+e.slice(4).toLowerCase()},properties:{ariaActiveDescendant:null,ariaAtomic:Nt,ariaAutoComplete:null,ariaBusy:Nt,ariaChecked:Nt,ariaColCount:F,ariaColIndex:F,ariaColSpan:F,ariaControls:lt,ariaCurrent:null,ariaDescribedBy:lt,ariaDetails:null,ariaDisabled:Nt,ariaDropEffect:lt,ariaErrorMessage:null,ariaExpanded:Nt,ariaFlowTo:lt,ariaGrabbed:Nt,ariaHasPopup:null,ariaHidden:Nt,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:lt,ariaLevel:F,ariaLive:null,ariaModal:Nt,ariaMultiLine:Nt,ariaMultiSelectable:Nt,ariaOrientation:null,ariaOwns:lt,ariaPlaceholder:null,ariaPosInSet:F,ariaPressed:Nt,ariaReadOnly:Nt,ariaRelevant:null,ariaRequired:Nt,ariaRoleDescription:lt,ariaRowCount:F,ariaRowIndex:F,ariaRowSpan:F,ariaSelected:Nt,ariaSetSize:F,ariaSort:null,ariaValueMax:F,ariaValueMin:F,ariaValueNow:F,ariaValueText:null,role:null}});var WM=Bn({space:"html",attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},transform:pv,mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:Cs,acceptCharset:lt,accessKey:lt,action:null,allow:null,allowFullScreen:ke,allowPaymentRequest:ke,allowUserMedia:ke,alt:null,as:null,async:ke,autoCapitalize:null,autoComplete:lt,autoFocus:ke,autoPlay:ke,blocking:lt,capture:null,charSet:null,checked:ke,cite:null,className:lt,cols:F,colSpan:null,content:null,contentEditable:Nt,controls:ke,controlsList:lt,coords:F|Cs,crossOrigin:null,data:null,dateTime:null,decoding:null,default:ke,defer:ke,dir:null,dirName:null,disabled:ke,download:bI,draggable:Nt,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:ke,formTarget:null,headers:lt,height:F,hidden:ke,high:F,href:null,hrefLang:null,htmlFor:lt,httpEquiv:lt,id:null,imageSizes:null,imageSrcSet:null,inert:ke,inputMode:null,integrity:null,is:null,isMap:ke,itemId:null,itemProp:lt,itemRef:lt,itemScope:ke,itemType:lt,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:ke,low:F,manifest:null,max:null,maxLength:F,media:null,method:null,min:null,minLength:F,multiple:ke,muted:ke,name:null,nonce:null,noModule:ke,noValidate:ke,onAbort:null,onAfterPrint:null,onAuxClick:null,onBeforeMatch:null,onBeforePrint:null,onBeforeToggle:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextLost:null,onContextMenu:null,onContextRestored:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onScrollEnd:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:ke,optimum:F,pattern:null,ping:lt,placeholder:null,playsInline:ke,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:ke,referrerPolicy:null,rel:lt,required:ke,reversed:ke,rows:F,rowSpan:F,sandbox:lt,scope:null,scoped:ke,seamless:ke,selected:ke,shadowRootClonable:ke,shadowRootDelegatesFocus:ke,shadowRootMode:null,shape:null,size:F,sizes:null,slot:null,span:F,spellCheck:Nt,src:null,srcDoc:null,srcLang:null,srcSet:null,start:F,step:null,style:null,tabIndex:F,target:null,title:null,translate:null,type:null,typeMustMatch:ke,useMap:null,value:Nt,width:F,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:lt,axis:null,background:null,bgColor:null,border:F,borderColor:null,bottomMargin:F,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:ke,declare:ke,event:null,face:null,frame:null,frameBorder:null,hSpace:F,leftMargin:F,link:null,longDesc:null,lowSrc:null,marginHeight:F,marginWidth:F,noResize:ke,noHref:ke,noShade:ke,noWrap:ke,object:null,profile:null,prompt:null,rev:null,rightMargin:F,rules:null,scheme:null,scrolling:Nt,standby:null,summary:null,text:null,topMargin:F,valueType:null,version:null,vAlign:null,vLink:null,vSpace:F,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:ke,disableRemotePlayback:ke,prefix:null,property:null,results:F,security:null,unselectable:null}});var BM=Bn({space:"svg",attributes:{accentHeight:"accent-height",alignmentBaseline:"alignment-baseline",arabicForm:"arabic-form",baselineShift:"baseline-shift",capHeight:"cap-height",className:"class",clipPath:"clip-path",clipRule:"clip-rule",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",crossOrigin:"crossorigin",dataType:"datatype",dominantBaseline:"dominant-baseline",enableBackground:"enable-background",fillOpacity:"fill-opacity",fillRule:"fill-rule",floodColor:"flood-color",floodOpacity:"flood-opacity",fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",hrefLang:"hreflang",horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",horizOriginY:"horiz-origin-y",imageRendering:"image-rendering",letterSpacing:"letter-spacing",lightingColor:"lighting-color",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",navDown:"nav-down",navDownLeft:"nav-down-left",navDownRight:"nav-down-right",navLeft:"nav-left",navNext:"nav-next",navPrev:"nav-prev",navRight:"nav-right",navUp:"nav-up",navUpLeft:"nav-up-left",navUpRight:"nav-up-right",onAbort:"onabort",onActivate:"onactivate",onAfterPrint:"onafterprint",onBeforePrint:"onbeforeprint",onBegin:"onbegin",onCancel:"oncancel",onCanPlay:"oncanplay",onCanPlayThrough:"oncanplaythrough",onChange:"onchange",onClick:"onclick",onClose:"onclose",onCopy:"oncopy",onCueChange:"oncuechange",onCut:"oncut",onDblClick:"ondblclick",onDrag:"ondrag",onDragEnd:"ondragend",onDragEnter:"ondragenter",onDragExit:"ondragexit",onDragLeave:"ondragleave",onDragOver:"ondragover",onDragStart:"ondragstart",onDrop:"ondrop",onDurationChange:"ondurationchange",onEmptied:"onemptied",onEnd:"onend",onEnded:"onended",onError:"onerror",onFocus:"onfocus",onFocusIn:"onfocusin",onFocusOut:"onfocusout",onHashChange:"onhashchange",onInput:"oninput",onInvalid:"oninvalid",onKeyDown:"onkeydown",onKeyPress:"onkeypress",onKeyUp:"onkeyup",onLoad:"onload",onLoadedData:"onloadeddata",onLoadedMetadata:"onloadedmetadata",onLoadStart:"onloadstart",onMessage:"onmessage",onMouseDown:"onmousedown",onMouseEnter:"onmouseenter",onMouseLeave:"onmouseleave",onMouseMove:"onmousemove",onMouseOut:"onmouseout",onMouseOver:"onmouseover",onMouseUp:"onmouseup",onMouseWheel:"onmousewheel",onOffline:"onoffline",onOnline:"ononline",onPageHide:"onpagehide",onPageShow:"onpageshow",onPaste:"onpaste",onPause:"onpause",onPlay:"onplay",onPlaying:"onplaying",onPopState:"onpopstate",onProgress:"onprogress",onRateChange:"onratechange",onRepeat:"onrepeat",onReset:"onreset",onResize:"onresize",onScroll:"onscroll",onSeeked:"onseeked",onSeeking:"onseeking",onSelect:"onselect",onShow:"onshow",onStalled:"onstalled",onStorage:"onstorage",onSubmit:"onsubmit",onSuspend:"onsuspend",onTimeUpdate:"ontimeupdate",onToggle:"ontoggle",onUnload:"onunload",onVolumeChange:"onvolumechange",onWaiting:"onwaiting",onZoom:"onzoom",overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pointerEvents:"pointer-events",referrerPolicy:"referrerpolicy",renderingIntent:"rendering-intent",shapeRendering:"shape-rendering",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",strokeDashArray:"stroke-dasharray",strokeDashOffset:"stroke-dashoffset",strokeLineCap:"stroke-linecap",strokeLineJoin:"stroke-linejoin",strokeMiterLimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",tabIndex:"tabindex",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",transformOrigin:"transform-origin",typeOf:"typeof",underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",vectorEffect:"vector-effect",vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",wordSpacing:"word-spacing",writingMode:"writing-mode",xHeight:"x-height",playbackOrder:"playbackorder",timelineBegin:"timelinebegin"},transform:fv,properties:{about:cn,accentHeight:F,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:F,amplitude:F,arabicForm:null,ascent:F,attributeName:null,attributeType:null,azimuth:F,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:F,by:null,calcMode:null,capHeight:F,className:lt,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:F,diffuseConstant:F,direction:null,display:null,dur:null,divisor:F,dominantBaseline:null,download:ke,dx:null,dy:null,edgeMode:null,editable:null,elevation:F,enableBackground:null,end:null,event:null,exponent:F,externalResourcesRequired:null,fill:null,fillOpacity:F,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:Cs,g2:Cs,glyphName:Cs,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:F,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:F,horizOriginX:F,horizOriginY:F,id:null,ideographic:F,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:F,k:F,k1:F,k2:F,k3:F,k4:F,kernelMatrix:cn,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:F,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:F,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,onZoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:F,overlineThickness:F,paintOrder:null,panose1:null,path:null,pathLength:F,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:lt,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:F,pointsAtY:F,pointsAtZ:F,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:cn,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:cn,rev:cn,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:cn,requiredFeatures:cn,requiredFonts:cn,requiredFormats:cn,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:F,specularExponent:F,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:F,strikethroughThickness:F,string:null,stroke:null,strokeDashArray:cn,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:F,strokeOpacity:F,strokeWidth:null,style:null,surfaceScale:F,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:cn,tabIndex:F,tableValues:null,target:null,targetX:F,targetY:F,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:cn,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:F,underlineThickness:F,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:F,values:null,vAlphabetic:F,vMathematical:F,vectorEffect:null,vHanging:F,vIdeographic:F,version:null,vertAdvY:F,vertOriginX:F,vertOriginY:F,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:F,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null}});var Y8=/^data[-\w.:]+$/i,GM=/-[a-z]/g,Q8=/[A-Z]/g;function II(t,e){let r=Qp(e),n=e,i=Rr;if(r in t.normal)return t.property[t.normal[r]];if(r.length>4&&r.slice(0,4)==="data"&&Y8.test(e)){if(e.charAt(4)==="-"){let o=e.slice(5).replace(GM,tJ);n="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{let o=e.slice(4);if(!GM.test(o)){let s=o.replace(Q8,eJ);s.charAt(0)!=="-"&&(s="-"+s),e="data"+s}}i=nl}return new i(n,e)}function eJ(t){return"-"+t.toLowerCase()}function tJ(t){return t.charAt(1).toUpperCase()}var HM=_I([$I,xI,kI,SI,WM],"html"),mv=_I([$I,xI,kI,SI,BM],"svg");var XM={}.hasOwnProperty;function KM(t,e){let r=e||{};function n(i,...o){let s=n.invalid,a=n.handlers;if(i&&XM.call(i,t)){let l=String(i[t]);s=XM.call(a,l)?a[l]:n.unknown}if(s)return s.call(this,i,...o)}return n.handlers=r.handlers||{},n.invalid=r.invalid,n.unknown=r.unknown,n}var rJ=/["&'<>`]/g,nJ=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,iJ=/[\x01-\t\v\f\x0E-\x1F\x7F\x81\x8D\x8F\x90\x9D\xA0-\uFFFF]/g,oJ=/[|\\{}()[\]^$+*?.]/g,JM=new WeakMap;function YM(t,e){if(t=t.replace(e.subset?sJ(e.subset):rJ,n),e.subset||e.escapeOnly)return t;return t.replace(nJ,r).replace(iJ,n);function r(i,o,s){return e.format((i.charCodeAt(0)-55296)*1024+i.charCodeAt(1)-56320+65536,s.charCodeAt(o+2),e)}function n(i,o,s){return e.format(i.charCodeAt(0),s.charCodeAt(o+1),e)}}function sJ(t){let e=JM.get(t);return e||(e=aJ(t),JM.set(t,e)),e}function aJ(t){let e=[],r=-1;for(;++r<t.length;)e.push(t[r].replace(oJ,"\\$&"));return new RegExp("(?:"+e.join("|")+")","g")}var lJ=/[\dA-Fa-f]/;function QM(t,e,r){let n="&#x"+t.toString(16).toUpperCase();return r&&e&&!lJ.test(String.fromCharCode(e))?n:n+";"}var cJ=/\d/;function ej(t,e,r){let n="&#"+String(t);return r&&e&&!cJ.test(String.fromCharCode(e))?n:n+";"}var tj=["AElig","AMP","Aacute","Acirc","Agrave","Aring","Atilde","Auml","COPY","Ccedil","ETH","Eacute","Ecirc","Egrave","Euml","GT","Iacute","Icirc","Igrave","Iuml","LT","Ntilde","Oacute","Ocirc","Ograve","Oslash","Otilde","Ouml","QUOT","REG","THORN","Uacute","Ucirc","Ugrave","Uuml","Yacute","aacute","acirc","acute","aelig","agrave","amp","aring","atilde","auml","brvbar","ccedil","cedil","cent","copy","curren","deg","divide","eacute","ecirc","egrave","eth","euml","frac12","frac14","frac34","gt","iacute","icirc","iexcl","igrave","iquest","iuml","laquo","lt","macr","micro","middot","nbsp","not","ntilde","oacute","ocirc","ograve","ordf","ordm","oslash","otilde","ouml","para","plusmn","pound","quot","raquo","reg","sect","shy","sup1","sup2","sup3","szlig","thorn","times","uacute","ucirc","ugrave","uml","uuml","yacute","yen","yuml"];var hv={nbsp:"\xA0",iexcl:"\xA1",cent:"\xA2",pound:"\xA3",curren:"\xA4",yen:"\xA5",brvbar:"\xA6",sect:"\xA7",uml:"\xA8",copy:"\xA9",ordf:"\xAA",laquo:"\xAB",not:"\xAC",shy:"\xAD",reg:"\xAE",macr:"\xAF",deg:"\xB0",plusmn:"\xB1",sup2:"\xB2",sup3:"\xB3",acute:"\xB4",micro:"\xB5",para:"\xB6",middot:"\xB7",cedil:"\xB8",sup1:"\xB9",ordm:"\xBA",raquo:"\xBB",frac14:"\xBC",frac12:"\xBD",frac34:"\xBE",iquest:"\xBF",Agrave:"\xC0",Aacute:"\xC1",Acirc:"\xC2",Atilde:"\xC3",Auml:"\xC4",Aring:"\xC5",AElig:"\xC6",Ccedil:"\xC7",Egrave:"\xC8",Eacute:"\xC9",Ecirc:"\xCA",Euml:"\xCB",Igrave:"\xCC",Iacute:"\xCD",Icirc:"\xCE",Iuml:"\xCF",ETH:"\xD0",Ntilde:"\xD1",Ograve:"\xD2",Oacute:"\xD3",Ocirc:"\xD4",Otilde:"\xD5",Ouml:"\xD6",times:"\xD7",Oslash:"\xD8",Ugrave:"\xD9",Uacute:"\xDA",Ucirc:"\xDB",Uuml:"\xDC",Yacute:"\xDD",THORN:"\xDE",szlig:"\xDF",agrave:"\xE0",aacute:"\xE1",acirc:"\xE2",atilde:"\xE3",auml:"\xE4",aring:"\xE5",aelig:"\xE6",ccedil:"\xE7",egrave:"\xE8",eacute:"\xE9",ecirc:"\xEA",euml:"\xEB",igrave:"\xEC",iacute:"\xED",icirc:"\xEE",iuml:"\xEF",eth:"\xF0",ntilde:"\xF1",ograve:"\xF2",oacute:"\xF3",ocirc:"\xF4",otilde:"\xF5",ouml:"\xF6",divide:"\xF7",oslash:"\xF8",ugrave:"\xF9",uacute:"\xFA",ucirc:"\xFB",uuml:"\xFC",yacute:"\xFD",thorn:"\xFE",yuml:"\xFF",fnof:"\u0192",Alpha:"\u0391",Beta:"\u0392",Gamma:"\u0393",Delta:"\u0394",Epsilon:"\u0395",Zeta:"\u0396",Eta:"\u0397",Theta:"\u0398",Iota:"\u0399",Kappa:"\u039A",Lambda:"\u039B",Mu:"\u039C",Nu:"\u039D",Xi:"\u039E",Omicron:"\u039F",Pi:"\u03A0",Rho:"\u03A1",Sigma:"\u03A3",Tau:"\u03A4",Upsilon:"\u03A5",Phi:"\u03A6",Chi:"\u03A7",Psi:"\u03A8",Omega:"\u03A9",alpha:"\u03B1",beta:"\u03B2",gamma:"\u03B3",delta:"\u03B4",epsilon:"\u03B5",zeta:"\u03B6",eta:"\u03B7",theta:"\u03B8",iota:"\u03B9",kappa:"\u03BA",lambda:"\u03BB",mu:"\u03BC",nu:"\u03BD",xi:"\u03BE",omicron:"\u03BF",pi:"\u03C0",rho:"\u03C1",sigmaf:"\u03C2",sigma:"\u03C3",tau:"\u03C4",upsilon:"\u03C5",phi:"\u03C6",chi:"\u03C7",psi:"\u03C8",omega:"\u03C9",thetasym:"\u03D1",upsih:"\u03D2",piv:"\u03D6",bull:"\u2022",hellip:"\u2026",prime:"\u2032",Prime:"\u2033",oline:"\u203E",frasl:"\u2044",weierp:"\u2118",image:"\u2111",real:"\u211C",trade:"\u2122",alefsym:"\u2135",larr:"\u2190",uarr:"\u2191",rarr:"\u2192",darr:"\u2193",harr:"\u2194",crarr:"\u21B5",lArr:"\u21D0",uArr:"\u21D1",rArr:"\u21D2",dArr:"\u21D3",hArr:"\u21D4",forall:"\u2200",part:"\u2202",exist:"\u2203",empty:"\u2205",nabla:"\u2207",isin:"\u2208",notin:"\u2209",ni:"\u220B",prod:"\u220F",sum:"\u2211",minus:"\u2212",lowast:"\u2217",radic:"\u221A",prop:"\u221D",infin:"\u221E",ang:"\u2220",and:"\u2227",or:"\u2228",cap:"\u2229",cup:"\u222A",int:"\u222B",there4:"\u2234",sim:"\u223C",cong:"\u2245",asymp:"\u2248",ne:"\u2260",equiv:"\u2261",le:"\u2264",ge:"\u2265",sub:"\u2282",sup:"\u2283",nsub:"\u2284",sube:"\u2286",supe:"\u2287",oplus:"\u2295",otimes:"\u2297",perp:"\u22A5",sdot:"\u22C5",lceil:"\u2308",rceil:"\u2309",lfloor:"\u230A",rfloor:"\u230B",lang:"\u2329",rang:"\u232A",loz:"\u25CA",spades:"\u2660",clubs:"\u2663",hearts:"\u2665",diams:"\u2666",quot:'"',amp:"&",lt:"<",gt:">",OElig:"\u0152",oelig:"\u0153",Scaron:"\u0160",scaron:"\u0161",Yuml:"\u0178",circ:"\u02C6",tilde:"\u02DC",ensp:"\u2002",emsp:"\u2003",thinsp:"\u2009",zwnj:"\u200C",zwj:"\u200D",lrm:"\u200E",rlm:"\u200F",ndash:"\u2013",mdash:"\u2014",lsquo:"\u2018",rsquo:"\u2019",sbquo:"\u201A",ldquo:"\u201C",rdquo:"\u201D",bdquo:"\u201E",dagger:"\u2020",Dagger:"\u2021",permil:"\u2030",lsaquo:"\u2039",rsaquo:"\u203A",euro:"\u20AC"};var rj=["cent","copy","divide","gt","lt","not","para","times"];var nj={}.hasOwnProperty,EI={},gv;for(gv in hv)nj.call(hv,gv)&&(EI[hv[gv]]=gv);var uJ=/[^\dA-Za-z]/;function ij(t,e,r,n){let i=String.fromCharCode(t);if(nj.call(EI,i)){let o=EI[i],s="&"+o;return r&&tj.includes(o)&&!rj.includes(o)&&(!n||e&&e!==61&&uJ.test(String.fromCharCode(e)))?s:s+";"}return""}function oj(t,e,r){let n=QM(t,e,r.omitOptionalSemicolons),i;if((r.useNamedReferences||r.useShortestReferences)&&(i=ij(t,e,r.omitOptionalSemicolons,r.attribute)),(r.useShortestReferences||!i)&&r.useShortestReferences){let o=ej(t,e,r.omitOptionalSemicolons);o.length<n.length&&(n=o)}return i&&(!r.useShortestReferences||i.length<n.length)?i:n}function Ro(t,e){return YM(t,Object.assign({format:oj},e))}var dJ=/^>|^->|<!--|-->|--!>|<!-$/g,fJ=[">"],pJ=["<",">"];function sj(t,e,r,n){return n.settings.bogusComments?"<?"+Ro(t.value,Object.assign({},n.settings.characterReferences,{subset:fJ}))+">":"<!--"+t.value.replace(dJ,i)+"-->";function i(o){return Ro(o,Object.assign({},n.settings.characterReferences,{subset:pJ}))}}function aj(t,e,r,n){return"<!"+(n.settings.upperDoctype?"DOCTYPE":"doctype")+(n.settings.tightDoctype?"":" ")+"html>"}function PI(t,e){let r=String(t);if(typeof e!="string")throw new TypeError("Expected character");let n=0,i=r.indexOf(e);for(;i!==-1;)n++,i=r.indexOf(e,i+e.length);return n}function lj(t,e){let r=e||{};return(t[t.length-1]===""?[...t,""]:t).join((r.padRight?" ":"")+","+(r.padLeft===!1?"":" ")).trim()}var Zt=cj(1),TI=cj(-1),mJ=[];function cj(t){return e;function e(r,n,i){let o=r?r.children:mJ,s=(n||0)+t,a=o[s];if(!i)for(;a&&Sn(a);)s+=t,a=o[s];return a}}var hJ={}.hasOwnProperty;function yv(t){return e;function e(r,n,i){return hJ.call(t,r.tagName)&&t[r.tagName](r,n,i)}}var tm=yv({body:yJ,caption:AI,colgroup:AI,dd:wJ,dt:bJ,head:AI,html:gJ,li:_J,optgroup:xJ,option:$J,p:vJ,rp:uj,rt:uj,tbody:SJ,td:dj,tfoot:IJ,th:dj,thead:kJ,tr:EJ});function AI(t,e,r){let n=Zt(r,e,!0);return!n||n.type!=="comment"&&!(n.type==="text"&&Sn(n.value.charAt(0)))}function gJ(t,e,r){let n=Zt(r,e);return!n||n.type!=="comment"}function yJ(t,e,r){let n=Zt(r,e);return!n||n.type!=="comment"}function vJ(t,e,r){let n=Zt(r,e);return n?n.type==="element"&&(n.tagName==="address"||n.tagName==="article"||n.tagName==="aside"||n.tagName==="blockquote"||n.tagName==="details"||n.tagName==="div"||n.tagName==="dl"||n.tagName==="fieldset"||n.tagName==="figcaption"||n.tagName==="figure"||n.tagName==="footer"||n.tagName==="form"||n.tagName==="h1"||n.tagName==="h2"||n.tagName==="h3"||n.tagName==="h4"||n.tagName==="h5"||n.tagName==="h6"||n.tagName==="header"||n.tagName==="hgroup"||n.tagName==="hr"||n.tagName==="main"||n.tagName==="menu"||n.tagName==="nav"||n.tagName==="ol"||n.tagName==="p"||n.tagName==="pre"||n.tagName==="section"||n.tagName==="table"||n.tagName==="ul"):!r||!(r.type==="element"&&(r.tagName==="a"||r.tagName==="audio"||r.tagName==="del"||r.tagName==="ins"||r.tagName==="map"||r.tagName==="noscript"||r.tagName==="video"))}function _J(t,e,r){let n=Zt(r,e);return!n||n.type==="element"&&n.tagName==="li"}function bJ(t,e,r){let n=Zt(r,e);return!!(n&&n.type==="element"&&(n.tagName==="dt"||n.tagName==="dd"))}function wJ(t,e,r){let n=Zt(r,e);return!n||n.type==="element"&&(n.tagName==="dt"||n.tagName==="dd")}function uj(t,e,r){let n=Zt(r,e);return!n||n.type==="element"&&(n.tagName==="rp"||n.tagName==="rt")}function xJ(t,e,r){let n=Zt(r,e);return!n||n.type==="element"&&n.tagName==="optgroup"}function $J(t,e,r){let n=Zt(r,e);return!n||n.type==="element"&&(n.tagName==="option"||n.tagName==="optgroup")}function kJ(t,e,r){let n=Zt(r,e);return!!(n&&n.type==="element"&&(n.tagName==="tbody"||n.tagName==="tfoot"))}function SJ(t,e,r){let n=Zt(r,e);return!n||n.type==="element"&&(n.tagName==="tbody"||n.tagName==="tfoot")}function IJ(t,e,r){return!Zt(r,e)}function EJ(t,e,r){let n=Zt(r,e);return!n||n.type==="element"&&n.tagName==="tr"}function dj(t,e,r){let n=Zt(r,e);return!n||n.type==="element"&&(n.tagName==="td"||n.tagName==="th")}var fj=yv({body:AJ,colgroup:zJ,head:TJ,html:PJ,tbody:CJ});function PJ(t){let e=Zt(t,-1);return!e||e.type!=="comment"}function TJ(t){let e=t.children,r=[],n=-1;for(;++n<e.length;){let i=e[n];if(i.type==="element"&&(i.tagName==="title"||i.tagName==="base")){if(r.includes(i.tagName))return!1;r.push(i.tagName)}}return e.length>0}function AJ(t){let e=Zt(t,-1,!0);return!e||e.type!=="comment"&&!(e.type==="text"&&Sn(e.value.charAt(0)))&&!(e.type==="element"&&(e.tagName==="meta"||e.tagName==="link"||e.tagName==="script"||e.tagName==="style"||e.tagName==="template"))}function zJ(t,e,r){let n=TI(r,e),i=Zt(t,-1,!0);return r&&n&&n.type==="element"&&n.tagName==="colgroup"&&tm(n,r.children.indexOf(n),r)?!1:!!(i&&i.type==="element"&&i.tagName==="col")}function CJ(t,e,r){let n=TI(r,e),i=Zt(t,-1);return r&&n&&n.type==="element"&&(n.tagName==="thead"||n.tagName==="tbody")&&tm(n,r.children.indexOf(n),r)?!1:!!(i&&i.type==="element"&&i.tagName==="tr")}var vv={name:[[`
|
|
352
|
+
\f\r &/=>`.split(""),`
|
|
353
|
+
\f\r "&'/=>\``.split("")],[`\0
|
|
354
|
+
\f\r "&'/<=>`.split(""),`\0
|
|
355
|
+
\f\r "&'/<=>\``.split("")]],unquoted:[[`
|
|
356
|
+
\f\r &>`.split(""),`\0
|
|
357
|
+
\f\r "&'<=>\``.split("")],[`\0
|
|
358
|
+
\f\r "&'<=>\``.split(""),`\0
|
|
359
|
+
\f\r "&'<=>\``.split("")]],single:[["&'".split(""),"\"&'`".split("")],["\0&'".split(""),"\0\"&'`".split("")]],double:[['"&'.split(""),"\"&'`".split("")],['\0"&'.split(""),"\0\"&'`".split("")]]};function pj(t,e,r,n){let i=n.schema,o=i.space==="svg"?!1:n.settings.omitOptionalTags,s=i.space==="svg"?n.settings.closeEmptyElements:n.settings.voids.includes(t.tagName.toLowerCase()),a=[],l;i.space==="html"&&t.tagName==="svg"&&(n.schema=mv);let c=NJ(n,t.properties),u=n.all(i.space==="html"&&t.tagName==="template"?t.content:t);return n.schema=i,u&&(s=!1),(c||!o||!fj(t,e,r))&&(a.push("<",t.tagName,c?" "+c:""),s&&(i.space==="svg"||n.settings.closeSelfClosing)&&(l=c.charAt(c.length-1),(!n.settings.tightSelfClosing||l==="/"||l&&l!=='"'&&l!=="'")&&a.push(" "),a.push("/")),a.push(">")),a.push(u),!s&&(!o||!tm(t,e,r))&&a.push("</"+t.tagName+">"),a.join("")}function NJ(t,e){let r=[],n=-1,i;if(e){for(i in e)if(e[i]!==null&&e[i]!==void 0){let o=OJ(t,i,e[i]);o&&r.push(o)}}for(;++n<r.length;){let o=t.settings.tightAttributes?r[n].charAt(r[n].length-1):void 0;n!==r.length-1&&o!=='"'&&o!=="'"&&(r[n]+=" ")}return r.join("")}function OJ(t,e,r){let n=II(t.schema,e),i=t.settings.allowParseErrors&&t.schema.space==="html"?0:1,o=t.settings.allowDangerousCharacters?0:1,s=t.quote,a;if(n.overloadedBoolean&&(r===n.attribute||r==="")?r=!0:(n.boolean||n.overloadedBoolean&&typeof r!="string")&&(r=!!r),r==null||r===!1||typeof r=="number"&&Number.isNaN(r))return"";let l=Ro(n.attribute,Object.assign({},t.settings.characterReferences,{subset:vv.name[i][o]}));return r===!0||(r=Array.isArray(r)?(n.commaSeparated?lj:CM)(r,{padLeft:!t.settings.tightCommaSeparatedLists}):String(r),t.settings.collapseEmptyAttributes&&!r)?l:(t.settings.preferUnquoted&&(a=Ro(r,Object.assign({},t.settings.characterReferences,{attribute:!0,subset:vv.unquoted[i][o]}))),a!==r&&(t.settings.quoteSmart&&PI(r,s)>PI(r,t.alternative)&&(s=t.alternative),a=s+Ro(r,Object.assign({},t.settings.characterReferences,{subset:(s==="'"?vv.single:vv.double)[i][o],attribute:!0}))+s),l+(a&&"="+a))}var RJ=["<","&"];function _v(t,e,r,n){return r&&r.type==="element"&&(r.tagName==="script"||r.tagName==="style")?t.value:Ro(t.value,Object.assign({},n.settings.characterReferences,{subset:RJ}))}function mj(t,e,r,n){return n.settings.allowDangerousHtml?t.value:_v(t,e,r,n)}function hj(t,e,r,n){return n.all(t)}var gj=KM("type",{invalid:MJ,unknown:jJ,handlers:{comment:sj,doctype:aj,element:pj,raw:mj,root:hj,text:_v}});function MJ(t){throw new Error("Expected node, not `"+t+"`")}function jJ(t){let e=t;throw new Error("Cannot compile unknown node `"+e.type+"`")}var DJ={},LJ={},UJ=[];function zI(t,e){let r=e||DJ,n=r.quote||'"',i=n==='"'?"'":'"';if(n!=='"'&&n!=="'")throw new Error("Invalid quote `"+n+"`, expected `'` or `\"`");return{one:ZJ,all:FJ,settings:{omitOptionalTags:r.omitOptionalTags||!1,allowParseErrors:r.allowParseErrors||!1,allowDangerousCharacters:r.allowDangerousCharacters||!1,quoteSmart:r.quoteSmart||!1,preferUnquoted:r.preferUnquoted||!1,tightAttributes:r.tightAttributes||!1,upperDoctype:r.upperDoctype||!1,tightDoctype:r.tightDoctype||!1,bogusComments:r.bogusComments||!1,tightCommaSeparatedLists:r.tightCommaSeparatedLists||!1,tightSelfClosing:r.tightSelfClosing||!1,collapseEmptyAttributes:r.collapseEmptyAttributes||!1,allowDangerousHtml:r.allowDangerousHtml||!1,voids:r.voids||VM,characterReferences:r.characterReferences||LJ,closeSelfClosing:r.closeSelfClosing||!1,closeEmptyElements:r.closeEmptyElements||!1},schema:r.space==="svg"?mv:HM,quote:n,alternative:i}.one(Array.isArray(t)?{type:"root",children:t}:t,void 0,void 0)}function ZJ(t,e,r){return gj(t,e,r,this)}function FJ(t){let e=[],r=t&&t.children||UJ,n=-1;for(;++n<r.length;)e[n]=this.one(r[n],n,t);return e.join("")}function rm(t){let e=this,r={...e.data("settings"),...t};e.compiler=n;function n(i){return zI(i,r)}}var VJ={};function CI(t,e){let r=e||VJ,n=typeof r.includeImageAlt=="boolean"?r.includeImageAlt:!0,i=typeof r.includeHtml=="boolean"?r.includeHtml:!0;return vj(t,n,i)}function vj(t,e,r){if(qJ(t)){if("value"in t)return t.type==="html"&&!r?"":t.value;if(e&&"alt"in t&&t.alt)return t.alt;if("children"in t)return yj(t.children,e,r)}return Array.isArray(t)?yj(t,e,r):""}function yj(t,e,r){let n=[],i=-1;for(;++i<t.length;)n[i]=vj(t[i],e,r);return n.join("")}function qJ(t){return!!(t&&typeof t=="object")}var _j=document.createElement("i");function ju(t){let e="&"+t+";";_j.innerHTML=e;let r=_j.textContent;return r.charCodeAt(r.length-1)===59&&t!=="semi"||r===e?!1:r}function Mr(t,e,r,n){let i=t.length,o=0,s;if(e<0?e=-e>i?0:i+e:e=e>i?i:e,r=r>0?r:0,n.length<1e4)s=Array.from(n),s.unshift(e,r),t.splice(...s);else for(r&&t.splice(e,r);o<n.length;)s=n.slice(o,o+1e4),s.unshift(e,0),t.splice(...s),o+=1e4,e+=1e4}function Hr(t,e){return t.length>0?(Mr(t,t.length,0,e),t):e}var bj={}.hasOwnProperty;function wj(t){let e={},r=-1;for(;++r<t.length;)WJ(e,t[r]);return e}function WJ(t,e){let r;for(r in e){let i=(bj.call(t,r)?t[r]:void 0)||(t[r]={}),o=e[r],s;if(o)for(s in o){bj.call(i,s)||(i[s]=[]);let a=o[s];BJ(i[s],Array.isArray(a)?a:a?[a]:[])}}}function BJ(t,e){let r=-1,n=[];for(;++r<e.length;)(e[r].add==="after"?t:n).push(e[r]);Mr(t,0,0,n)}function bv(t,e){let r=Number.parseInt(t,e);return r<9||r===11||r>13&&r<32||r>126&&r<160||r>55295&&r<57344||r>64975&&r<65008||(r&65535)===65535||(r&65535)===65534||r>1114111?"\uFFFD":String.fromCodePoint(r)}function Mo(t){return t.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}var In=Ns(/[A-Za-z]/),sr=Ns(/[\dA-Za-z]/),xj=Ns(/[#-'*+\--9=?A-Z^-~]/);function nm(t){return t!==null&&(t<32||t===127)}var im=Ns(/\d/),$j=Ns(/[\dA-Fa-f]/),kj=Ns(/[!-/:-@[-`{-~]/);function ne(t){return t!==null&&t<-2}function Ft(t){return t!==null&&(t<0||t===32)}function Se(t){return t===-2||t===-1||t===32}var Sj=Ns(/\p{P}|\p{S}/u),Ij=Ns(/\s/);function Ns(t){return e;function e(r){return r!==null&&r>-1&&t.test(String.fromCharCode(r))}}function Gn(t){let e=[],r=-1,n=0,i=0;for(;++r<t.length;){let o=t.charCodeAt(r),s="";if(o===37&&sr(t.charCodeAt(r+1))&&sr(t.charCodeAt(r+2)))i=2;else if(o<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(o))||(s=String.fromCharCode(o));else if(o>55295&&o<57344){let a=t.charCodeAt(r+1);o<56320&&a>56319&&a<57344?(s=String.fromCharCode(o,a),i=1):s="\uFFFD"}else s=String.fromCharCode(o);s&&(e.push(t.slice(n,r),encodeURIComponent(s)),n=r+i+1,s=""),i&&(r+=i,i=0)}return e.join("")+t.slice(n)}function Ie(t,e,r,n){let i=n?n-1:Number.POSITIVE_INFINITY,o=0;return s;function s(l){return Se(l)?(t.enter(r),a(l)):e(l)}function a(l){return Se(l)&&o++<i?(t.consume(l),a):(t.exit(r),e(l))}}var Ej={tokenize:GJ};function GJ(t){let e=t.attempt(this.parser.constructs.contentInitial,n,i),r;return e;function n(a){if(a===null){t.consume(a);return}return t.enter("lineEnding"),t.consume(a),t.exit("lineEnding"),Ie(t,e,"linePrefix")}function i(a){return t.enter("paragraph"),o(a)}function o(a){let l=t.enter("chunkText",{contentType:"text",previous:r});return r&&(r.next=l),r=l,s(a)}function s(a){if(a===null){t.exit("chunkText"),t.exit("paragraph"),t.consume(a);return}return ne(a)?(t.consume(a),t.exit("chunkText"),o):(t.consume(a),s)}}var Tj={tokenize:HJ},Pj={tokenize:XJ};function HJ(t){let e=this,r=[],n=0,i,o,s;return a;function a(b){if(n<r.length){let E=r[n];return e.containerState=E[1],t.attempt(E[0].continuation,l,c)(b)}return c(b)}function l(b){if(n++,e.containerState._closeFlow){e.containerState._closeFlow=void 0,i&&_();let E=e.events.length,I=E,P;for(;I--;)if(e.events[I][0]==="exit"&&e.events[I][1].type==="chunkFlow"){P=e.events[I][1].end;break}g(n);let M=E;for(;M<e.events.length;)e.events[M][1].end=Object.assign({},P),M++;return Mr(e.events,I+1,0,e.events.slice(E)),e.events.length=M,c(b)}return a(b)}function c(b){if(n===r.length){if(!i)return p(b);if(i.currentConstruct&&i.currentConstruct.concrete)return m(b);e.interrupt=!!(i.currentConstruct&&!i._gfmTableDynamicInterruptHack)}return e.containerState={},t.check(Pj,u,d)(b)}function u(b){return i&&_(),g(n),p(b)}function d(b){return e.parser.lazy[e.now().line]=n!==r.length,s=e.now().offset,m(b)}function p(b){return e.containerState={},t.attempt(Pj,f,m)(b)}function f(b){return n++,r.push([e.currentConstruct,e.containerState]),p(b)}function m(b){if(b===null){i&&_(),g(0),t.consume(b);return}return i=i||e.parser.flow(e.now()),t.enter("chunkFlow",{contentType:"flow",previous:o,_tokenizer:i}),h(b)}function h(b){if(b===null){y(t.exit("chunkFlow"),!0),g(0),t.consume(b);return}return ne(b)?(t.consume(b),y(t.exit("chunkFlow")),n=0,e.interrupt=void 0,a):(t.consume(b),h)}function y(b,E){let I=e.sliceStream(b);if(E&&I.push(null),b.previous=o,o&&(o.next=b),o=b,i.defineSkip(b.start),i.write(I),e.parser.lazy[b.start.line]){let P=i.events.length;for(;P--;)if(i.events[P][1].start.offset<s&&(!i.events[P][1].end||i.events[P][1].end.offset>s))return;let M=e.events.length,V=M,R,L;for(;V--;)if(e.events[V][0]==="exit"&&e.events[V][1].type==="chunkFlow"){if(R){L=e.events[V][1].end;break}R=!0}for(g(n),P=M;P<e.events.length;)e.events[P][1].end=Object.assign({},L),P++;Mr(e.events,V+1,0,e.events.slice(M)),e.events.length=P}}function g(b){let E=r.length;for(;E-- >b;){let I=r[E];e.containerState=I[1],I[0].exit.call(e,t)}r.length=b}function _(){i.write([null]),o=void 0,i=void 0,e.containerState._closeFlow=void 0}}function XJ(t,e,r){return Ie(t,t.attempt(this.parser.constructs.document,e,r),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function NI(t){if(t===null||Ft(t)||Ij(t))return 1;if(Sj(t))return 2}function Du(t,e,r){let n=[],i=-1;for(;++i<t.length;){let o=t[i].resolveAll;o&&!n.includes(o)&&(e=o(e,r),n.push(o))}return e}var om={name:"attention",tokenize:JJ,resolveAll:KJ};function KJ(t,e){let r=-1,n,i,o,s,a,l,c,u;for(;++r<t.length;)if(t[r][0]==="enter"&&t[r][1].type==="attentionSequence"&&t[r][1]._close){for(n=r;n--;)if(t[n][0]==="exit"&&t[n][1].type==="attentionSequence"&&t[n][1]._open&&e.sliceSerialize(t[n][1]).charCodeAt(0)===e.sliceSerialize(t[r][1]).charCodeAt(0)){if((t[n][1]._close||t[r][1]._open)&&(t[r][1].end.offset-t[r][1].start.offset)%3&&!((t[n][1].end.offset-t[n][1].start.offset+t[r][1].end.offset-t[r][1].start.offset)%3))continue;l=t[n][1].end.offset-t[n][1].start.offset>1&&t[r][1].end.offset-t[r][1].start.offset>1?2:1;let d=Object.assign({},t[n][1].end),p=Object.assign({},t[r][1].start);Aj(d,-l),Aj(p,l),s={type:l>1?"strongSequence":"emphasisSequence",start:d,end:Object.assign({},t[n][1].end)},a={type:l>1?"strongSequence":"emphasisSequence",start:Object.assign({},t[r][1].start),end:p},o={type:l>1?"strongText":"emphasisText",start:Object.assign({},t[n][1].end),end:Object.assign({},t[r][1].start)},i={type:l>1?"strong":"emphasis",start:Object.assign({},s.start),end:Object.assign({},a.end)},t[n][1].end=Object.assign({},s.start),t[r][1].start=Object.assign({},a.end),c=[],t[n][1].end.offset-t[n][1].start.offset&&(c=Hr(c,[["enter",t[n][1],e],["exit",t[n][1],e]])),c=Hr(c,[["enter",i,e],["enter",s,e],["exit",s,e],["enter",o,e]]),c=Hr(c,Du(e.parser.constructs.insideSpan.null,t.slice(n+1,r),e)),c=Hr(c,[["exit",o,e],["enter",a,e],["exit",a,e],["exit",i,e]]),t[r][1].end.offset-t[r][1].start.offset?(u=2,c=Hr(c,[["enter",t[r][1],e],["exit",t[r][1],e]])):u=0,Mr(t,n-1,r-n+3,c),r=n+c.length-u-2;break}}for(r=-1;++r<t.length;)t[r][1].type==="attentionSequence"&&(t[r][1].type="data");return t}function JJ(t,e){let r=this.parser.constructs.attentionMarkers.null,n=this.previous,i=NI(n),o;return s;function s(l){return o=l,t.enter("attentionSequence"),a(l)}function a(l){if(l===o)return t.consume(l),a;let c=t.exit("attentionSequence"),u=NI(l),d=!u||u===2&&i||r.includes(l),p=!i||i===2&&u||r.includes(n);return c._open=!!(o===42?d:d&&(i||!p)),c._close=!!(o===42?p:p&&(u||!d)),e(l)}}function Aj(t,e){t.column+=e,t.offset+=e,t._bufferIndex+=e}var OI={name:"autolink",tokenize:YJ};function YJ(t,e,r){let n=0;return i;function i(f){return t.enter("autolink"),t.enter("autolinkMarker"),t.consume(f),t.exit("autolinkMarker"),t.enter("autolinkProtocol"),o}function o(f){return In(f)?(t.consume(f),s):f===64?r(f):c(f)}function s(f){return f===43||f===45||f===46||sr(f)?(n=1,a(f)):c(f)}function a(f){return f===58?(t.consume(f),n=0,l):(f===43||f===45||f===46||sr(f))&&n++<32?(t.consume(f),a):(n=0,c(f))}function l(f){return f===62?(t.exit("autolinkProtocol"),t.enter("autolinkMarker"),t.consume(f),t.exit("autolinkMarker"),t.exit("autolink"),e):f===null||f===32||f===60||nm(f)?r(f):(t.consume(f),l)}function c(f){return f===64?(t.consume(f),u):xj(f)?(t.consume(f),c):r(f)}function u(f){return sr(f)?d(f):r(f)}function d(f){return f===46?(t.consume(f),n=0,u):f===62?(t.exit("autolinkProtocol").type="autolinkEmail",t.enter("autolinkMarker"),t.consume(f),t.exit("autolinkMarker"),t.exit("autolink"),e):p(f)}function p(f){if((f===45||sr(f))&&n++<63){let m=f===45?p:d;return t.consume(f),m}return r(f)}}var Os={tokenize:QJ,partial:!0};function QJ(t,e,r){return n;function n(o){return Se(o)?Ie(t,i,"linePrefix")(o):i(o)}function i(o){return o===null||ne(o)?e(o):r(o)}}var wv={name:"blockQuote",tokenize:e7,continuation:{tokenize:t7},exit:r7};function e7(t,e,r){let n=this;return i;function i(s){if(s===62){let a=n.containerState;return a.open||(t.enter("blockQuote",{_container:!0}),a.open=!0),t.enter("blockQuotePrefix"),t.enter("blockQuoteMarker"),t.consume(s),t.exit("blockQuoteMarker"),o}return r(s)}function o(s){return Se(s)?(t.enter("blockQuotePrefixWhitespace"),t.consume(s),t.exit("blockQuotePrefixWhitespace"),t.exit("blockQuotePrefix"),e):(t.exit("blockQuotePrefix"),e(s))}}function t7(t,e,r){let n=this;return i;function i(s){return Se(s)?Ie(t,o,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(s):o(s)}function o(s){return t.attempt(wv,e,r)(s)}}function r7(t){t.exit("blockQuote")}var xv={name:"characterEscape",tokenize:n7};function n7(t,e,r){return n;function n(o){return t.enter("characterEscape"),t.enter("escapeMarker"),t.consume(o),t.exit("escapeMarker"),i}function i(o){return kj(o)?(t.enter("characterEscapeValue"),t.consume(o),t.exit("characterEscapeValue"),t.exit("characterEscape"),e):r(o)}}var $v={name:"characterReference",tokenize:i7};function i7(t,e,r){let n=this,i=0,o,s;return a;function a(d){return t.enter("characterReference"),t.enter("characterReferenceMarker"),t.consume(d),t.exit("characterReferenceMarker"),l}function l(d){return d===35?(t.enter("characterReferenceMarkerNumeric"),t.consume(d),t.exit("characterReferenceMarkerNumeric"),c):(t.enter("characterReferenceValue"),o=31,s=sr,u(d))}function c(d){return d===88||d===120?(t.enter("characterReferenceMarkerHexadecimal"),t.consume(d),t.exit("characterReferenceMarkerHexadecimal"),t.enter("characterReferenceValue"),o=6,s=$j,u):(t.enter("characterReferenceValue"),o=7,s=im,u(d))}function u(d){if(d===59&&i){let p=t.exit("characterReferenceValue");return s===sr&&!ju(n.sliceSerialize(p))?r(d):(t.enter("characterReferenceMarker"),t.consume(d),t.exit("characterReferenceMarker"),t.exit("characterReference"),e)}return s(d)&&i++<o?(t.consume(d),u):r(d)}}var zj={tokenize:s7,partial:!0},kv={name:"codeFenced",tokenize:o7,concrete:!0};function o7(t,e,r){let n=this,i={tokenize:I,partial:!0},o=0,s=0,a;return l;function l(P){return c(P)}function c(P){let M=n.events[n.events.length-1];return o=M&&M[1].type==="linePrefix"?M[2].sliceSerialize(M[1],!0).length:0,a=P,t.enter("codeFenced"),t.enter("codeFencedFence"),t.enter("codeFencedFenceSequence"),u(P)}function u(P){return P===a?(s++,t.consume(P),u):s<3?r(P):(t.exit("codeFencedFenceSequence"),Se(P)?Ie(t,d,"whitespace")(P):d(P))}function d(P){return P===null||ne(P)?(t.exit("codeFencedFence"),n.interrupt?e(P):t.check(zj,h,E)(P)):(t.enter("codeFencedFenceInfo"),t.enter("chunkString",{contentType:"string"}),p(P))}function p(P){return P===null||ne(P)?(t.exit("chunkString"),t.exit("codeFencedFenceInfo"),d(P)):Se(P)?(t.exit("chunkString"),t.exit("codeFencedFenceInfo"),Ie(t,f,"whitespace")(P)):P===96&&P===a?r(P):(t.consume(P),p)}function f(P){return P===null||ne(P)?d(P):(t.enter("codeFencedFenceMeta"),t.enter("chunkString",{contentType:"string"}),m(P))}function m(P){return P===null||ne(P)?(t.exit("chunkString"),t.exit("codeFencedFenceMeta"),d(P)):P===96&&P===a?r(P):(t.consume(P),m)}function h(P){return t.attempt(i,E,y)(P)}function y(P){return t.enter("lineEnding"),t.consume(P),t.exit("lineEnding"),g}function g(P){return o>0&&Se(P)?Ie(t,_,"linePrefix",o+1)(P):_(P)}function _(P){return P===null||ne(P)?t.check(zj,h,E)(P):(t.enter("codeFlowValue"),b(P))}function b(P){return P===null||ne(P)?(t.exit("codeFlowValue"),_(P)):(t.consume(P),b)}function E(P){return t.exit("codeFenced"),e(P)}function I(P,M,V){let R=0;return L;function L(ie){return P.enter("lineEnding"),P.consume(ie),P.exit("lineEnding"),G}function G(ie){return P.enter("codeFencedFence"),Se(ie)?Ie(P,H,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(ie):H(ie)}function H(ie){return ie===a?(P.enter("codeFencedFenceSequence"),W(ie)):V(ie)}function W(ie){return ie===a?(R++,P.consume(ie),W):R>=s?(P.exit("codeFencedFenceSequence"),Se(ie)?Ie(P,Y,"whitespace")(ie):Y(ie)):V(ie)}function Y(ie){return ie===null||ne(ie)?(P.exit("codeFencedFence"),M(ie)):V(ie)}}}function s7(t,e,r){let n=this;return i;function i(s){return s===null?r(s):(t.enter("lineEnding"),t.consume(s),t.exit("lineEnding"),o)}function o(s){return n.parser.lazy[n.now().line]?r(s):e(s)}}var sm={name:"codeIndented",tokenize:l7},a7={tokenize:c7,partial:!0};function l7(t,e,r){let n=this;return i;function i(c){return t.enter("codeIndented"),Ie(t,o,"linePrefix",5)(c)}function o(c){let u=n.events[n.events.length-1];return u&&u[1].type==="linePrefix"&&u[2].sliceSerialize(u[1],!0).length>=4?s(c):r(c)}function s(c){return c===null?l(c):ne(c)?t.attempt(a7,s,l)(c):(t.enter("codeFlowValue"),a(c))}function a(c){return c===null||ne(c)?(t.exit("codeFlowValue"),s(c)):(t.consume(c),a)}function l(c){return t.exit("codeIndented"),e(c)}}function c7(t,e,r){let n=this;return i;function i(s){return n.parser.lazy[n.now().line]?r(s):ne(s)?(t.enter("lineEnding"),t.consume(s),t.exit("lineEnding"),i):Ie(t,o,"linePrefix",5)(s)}function o(s){let a=n.events[n.events.length-1];return a&&a[1].type==="linePrefix"&&a[2].sliceSerialize(a[1],!0).length>=4?e(s):ne(s)?i(s):r(s)}}var RI={name:"codeText",tokenize:f7,resolve:u7,previous:d7};function u7(t){let e=t.length-4,r=3,n,i;if((t[r][1].type==="lineEnding"||t[r][1].type==="space")&&(t[e][1].type==="lineEnding"||t[e][1].type==="space")){for(n=r;++n<e;)if(t[n][1].type==="codeTextData"){t[r][1].type="codeTextPadding",t[e][1].type="codeTextPadding",r+=2,e-=2;break}}for(n=r-1,e++;++n<=e;)i===void 0?n!==e&&t[n][1].type!=="lineEnding"&&(i=n):(n===e||t[n][1].type==="lineEnding")&&(t[i][1].type="codeTextData",n!==i+2&&(t[i][1].end=t[n-1][1].end,t.splice(i+2,n-i-2),e-=n-i-2,n=i+2),i=void 0);return t}function d7(t){return t!==96||this.events[this.events.length-1][1].type==="characterEscape"}function f7(t,e,r){let n=this,i=0,o,s;return a;function a(p){return t.enter("codeText"),t.enter("codeTextSequence"),l(p)}function l(p){return p===96?(t.consume(p),i++,l):(t.exit("codeTextSequence"),c(p))}function c(p){return p===null?r(p):p===32?(t.enter("space"),t.consume(p),t.exit("space"),c):p===96?(s=t.enter("codeTextSequence"),o=0,d(p)):ne(p)?(t.enter("lineEnding"),t.consume(p),t.exit("lineEnding"),c):(t.enter("codeTextData"),u(p))}function u(p){return p===null||p===32||p===96||ne(p)?(t.exit("codeTextData"),c(p)):(t.consume(p),u)}function d(p){return p===96?(t.consume(p),o++,d):o===i?(t.exit("codeTextSequence"),t.exit("codeText"),e(p)):(s.type="codeTextData",u(p))}}var Sv=class{constructor(e){this.left=e?[...e]:[],this.right=[]}get(e){if(e<0||e>=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+e+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return e<this.left.length?this.left[e]:this.right[this.right.length-e+this.left.length-1]}get length(){return this.left.length+this.right.length}shift(){return this.setCursor(0),this.right.pop()}slice(e,r){let n=r??Number.POSITIVE_INFINITY;return n<this.left.length?this.left.slice(e,n):e>this.left.length?this.right.slice(this.right.length-n+this.left.length,this.right.length-e+this.left.length).reverse():this.left.slice(e).concat(this.right.slice(this.right.length-n+this.left.length).reverse())}splice(e,r,n){let i=r||0;this.setCursor(Math.trunc(e));let o=this.right.splice(this.right.length-i,Number.POSITIVE_INFINITY);return n&&am(this.left,n),o.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(e){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(e)}pushMany(e){this.setCursor(Number.POSITIVE_INFINITY),am(this.left,e)}unshift(e){this.setCursor(0),this.right.push(e)}unshiftMany(e){this.setCursor(0),am(this.right,e.reverse())}setCursor(e){if(!(e===this.left.length||e>this.left.length&&this.right.length===0||e<0&&this.left.length===0))if(e<this.left.length){let r=this.left.splice(e,Number.POSITIVE_INFINITY);am(this.right,r.reverse())}else{let r=this.right.splice(this.left.length+this.right.length-e,Number.POSITIVE_INFINITY);am(this.left,r.reverse())}}};function am(t,e){let r=0;if(e.length<1e4)t.push(...e);else for(;r<e.length;)t.push(...e.slice(r,r+1e4)),r+=1e4}function Iv(t){let e={},r=-1,n,i,o,s,a,l,c,u=new Sv(t);for(;++r<u.length;){for(;r in e;)r=e[r];if(n=u.get(r),r&&n[1].type==="chunkFlow"&&u.get(r-1)[1].type==="listItemPrefix"&&(l=n[1]._tokenizer.events,o=0,o<l.length&&l[o][1].type==="lineEndingBlank"&&(o+=2),o<l.length&&l[o][1].type==="content"))for(;++o<l.length&&l[o][1].type!=="content";)l[o][1].type==="chunkText"&&(l[o][1]._isInFirstContentOfListItem=!0,o++);if(n[0]==="enter")n[1].contentType&&(Object.assign(e,p7(u,r)),r=e[r],c=!0);else if(n[1]._container){for(o=r,i=void 0;o--&&(s=u.get(o),s[1].type==="lineEnding"||s[1].type==="lineEndingBlank");)s[0]==="enter"&&(i&&(u.get(i)[1].type="lineEndingBlank"),s[1].type="lineEnding",i=o);i&&(n[1].end=Object.assign({},u.get(i)[1].start),a=u.slice(i,r),a.unshift(n),u.splice(i,r-i+1,a))}}return Mr(t,0,Number.POSITIVE_INFINITY,u.slice(0)),!c}function p7(t,e){let r=t.get(e)[1],n=t.get(e)[2],i=e-1,o=[],s=r._tokenizer||n.parser[r.contentType](r.start),a=s.events,l=[],c={},u,d,p=-1,f=r,m=0,h=0,y=[h];for(;f;){for(;t.get(++i)[1]!==f;);o.push(i),f._tokenizer||(u=n.sliceStream(f),f.next||u.push(null),d&&s.defineSkip(f.start),f._isInFirstContentOfListItem&&(s._gfmTasklistFirstContentOfListItem=!0),s.write(u),f._isInFirstContentOfListItem&&(s._gfmTasklistFirstContentOfListItem=void 0)),d=f,f=f.next}for(f=r;++p<a.length;)a[p][0]==="exit"&&a[p-1][0]==="enter"&&a[p][1].type===a[p-1][1].type&&a[p][1].start.line!==a[p][1].end.line&&(h=p+1,y.push(h),f._tokenizer=void 0,f.previous=void 0,f=f.next);for(s.events=[],f?(f._tokenizer=void 0,f.previous=void 0):y.pop(),p=y.length;p--;){let g=a.slice(y[p],y[p+1]),_=o.pop();l.push([_,_+g.length-1]),t.splice(_,2,g)}for(l.reverse(),p=-1;++p<l.length;)c[m+l[p][0]]=m+l[p][1],m+=l[p][1]-l[p][0]-1;return c}var MI={tokenize:g7,resolve:h7},m7={tokenize:y7,partial:!0};function h7(t){return Iv(t),t}function g7(t,e){let r;return n;function n(a){return t.enter("content"),r=t.enter("chunkContent",{contentType:"content"}),i(a)}function i(a){return a===null?o(a):ne(a)?t.check(m7,s,o)(a):(t.consume(a),i)}function o(a){return t.exit("chunkContent"),t.exit("content"),e(a)}function s(a){return t.consume(a),t.exit("chunkContent"),r.next=t.enter("chunkContent",{contentType:"content",previous:r}),r=r.next,i}}function y7(t,e,r){let n=this;return i;function i(s){return t.exit("chunkContent"),t.enter("lineEnding"),t.consume(s),t.exit("lineEnding"),Ie(t,o,"linePrefix")}function o(s){if(s===null||ne(s))return r(s);let a=n.events[n.events.length-1];return!n.parser.constructs.disable.null.includes("codeIndented")&&a&&a[1].type==="linePrefix"&&a[2].sliceSerialize(a[1],!0).length>=4?e(s):t.interrupt(n.parser.constructs.flow,r,e)(s)}}function Ev(t,e,r,n,i,o,s,a,l){let c=l||Number.POSITIVE_INFINITY,u=0;return d;function d(g){return g===60?(t.enter(n),t.enter(i),t.enter(o),t.consume(g),t.exit(o),p):g===null||g===32||g===41||nm(g)?r(g):(t.enter(n),t.enter(s),t.enter(a),t.enter("chunkString",{contentType:"string"}),h(g))}function p(g){return g===62?(t.enter(o),t.consume(g),t.exit(o),t.exit(i),t.exit(n),e):(t.enter(a),t.enter("chunkString",{contentType:"string"}),f(g))}function f(g){return g===62?(t.exit("chunkString"),t.exit(a),p(g)):g===null||g===60||ne(g)?r(g):(t.consume(g),g===92?m:f)}function m(g){return g===60||g===62||g===92?(t.consume(g),f):f(g)}function h(g){return!u&&(g===null||g===41||Ft(g))?(t.exit("chunkString"),t.exit(a),t.exit(s),t.exit(n),e(g)):u<c&&g===40?(t.consume(g),u++,h):g===41?(t.consume(g),u--,h):g===null||g===32||g===40||nm(g)?r(g):(t.consume(g),g===92?y:h)}function y(g){return g===40||g===41||g===92?(t.consume(g),h):h(g)}}function Pv(t,e,r,n,i,o){let s=this,a=0,l;return c;function c(f){return t.enter(n),t.enter(i),t.consume(f),t.exit(i),t.enter(o),u}function u(f){return a>999||f===null||f===91||f===93&&!l||f===94&&!a&&"_hiddenFootnoteSupport"in s.parser.constructs?r(f):f===93?(t.exit(o),t.enter(i),t.consume(f),t.exit(i),t.exit(n),e):ne(f)?(t.enter("lineEnding"),t.consume(f),t.exit("lineEnding"),u):(t.enter("chunkString",{contentType:"string"}),d(f))}function d(f){return f===null||f===91||f===93||ne(f)||a++>999?(t.exit("chunkString"),u(f)):(t.consume(f),l||(l=!Se(f)),f===92?p:d)}function p(f){return f===91||f===92||f===93?(t.consume(f),a++,d):d(f)}}function Tv(t,e,r,n,i,o){let s;return a;function a(p){return p===34||p===39||p===40?(t.enter(n),t.enter(i),t.consume(p),t.exit(i),s=p===40?41:p,l):r(p)}function l(p){return p===s?(t.enter(i),t.consume(p),t.exit(i),t.exit(n),e):(t.enter(o),c(p))}function c(p){return p===s?(t.exit(o),l(s)):p===null?r(p):ne(p)?(t.enter("lineEnding"),t.consume(p),t.exit("lineEnding"),Ie(t,c,"linePrefix")):(t.enter("chunkString",{contentType:"string"}),u(p))}function u(p){return p===s||p===null||ne(p)?(t.exit("chunkString"),c(p)):(t.consume(p),p===92?d:u)}function d(p){return p===s||p===92?(t.consume(p),u):u(p)}}function il(t,e){let r;return n;function n(i){return ne(i)?(t.enter("lineEnding"),t.consume(i),t.exit("lineEnding"),r=!0,n):Se(i)?Ie(t,n,r?"linePrefix":"lineSuffix")(i):e(i)}}var jI={name:"definition",tokenize:_7},v7={tokenize:b7,partial:!0};function _7(t,e,r){let n=this,i;return o;function o(f){return t.enter("definition"),s(f)}function s(f){return Pv.call(n,t,a,r,"definitionLabel","definitionLabelMarker","definitionLabelString")(f)}function a(f){return i=Mo(n.sliceSerialize(n.events[n.events.length-1][1]).slice(1,-1)),f===58?(t.enter("definitionMarker"),t.consume(f),t.exit("definitionMarker"),l):r(f)}function l(f){return Ft(f)?il(t,c)(f):c(f)}function c(f){return Ev(t,u,r,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(f)}function u(f){return t.attempt(v7,d,d)(f)}function d(f){return Se(f)?Ie(t,p,"whitespace")(f):p(f)}function p(f){return f===null||ne(f)?(t.exit("definition"),n.parser.defined.push(i),e(f)):r(f)}}function b7(t,e,r){return n;function n(a){return Ft(a)?il(t,i)(a):r(a)}function i(a){return Tv(t,o,r,"definitionTitle","definitionTitleMarker","definitionTitleString")(a)}function o(a){return Se(a)?Ie(t,s,"whitespace")(a):s(a)}function s(a){return a===null||ne(a)?e(a):r(a)}}var DI={name:"hardBreakEscape",tokenize:w7};function w7(t,e,r){return n;function n(o){return t.enter("hardBreakEscape"),t.consume(o),i}function i(o){return ne(o)?(t.exit("hardBreakEscape"),e(o)):r(o)}}var LI={name:"headingAtx",tokenize:$7,resolve:x7};function x7(t,e){let r=t.length-2,n=3,i,o;return t[n][1].type==="whitespace"&&(n+=2),r-2>n&&t[r][1].type==="whitespace"&&(r-=2),t[r][1].type==="atxHeadingSequence"&&(n===r-1||r-4>n&&t[r-2][1].type==="whitespace")&&(r-=n+1===r?2:4),r>n&&(i={type:"atxHeadingText",start:t[n][1].start,end:t[r][1].end},o={type:"chunkText",start:t[n][1].start,end:t[r][1].end,contentType:"text"},Mr(t,n,r-n+1,[["enter",i,e],["enter",o,e],["exit",o,e],["exit",i,e]])),t}function $7(t,e,r){let n=0;return i;function i(u){return t.enter("atxHeading"),o(u)}function o(u){return t.enter("atxHeadingSequence"),s(u)}function s(u){return u===35&&n++<6?(t.consume(u),s):u===null||Ft(u)?(t.exit("atxHeadingSequence"),a(u)):r(u)}function a(u){return u===35?(t.enter("atxHeadingSequence"),l(u)):u===null||ne(u)?(t.exit("atxHeading"),e(u)):Se(u)?Ie(t,a,"whitespace")(u):(t.enter("atxHeadingText"),c(u))}function l(u){return u===35?(t.consume(u),l):(t.exit("atxHeadingSequence"),a(u))}function c(u){return u===null||u===35||Ft(u)?(t.exit("atxHeadingText"),a(u)):(t.consume(u),c)}}var Cj=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],UI=["pre","script","style","textarea"];var ZI={name:"htmlFlow",tokenize:E7,resolveTo:I7,concrete:!0},k7={tokenize:T7,partial:!0},S7={tokenize:P7,partial:!0};function I7(t){let e=t.length;for(;e--&&!(t[e][0]==="enter"&&t[e][1].type==="htmlFlow"););return e>1&&t[e-2][1].type==="linePrefix"&&(t[e][1].start=t[e-2][1].start,t[e+1][1].start=t[e-2][1].start,t.splice(e-2,2)),t}function E7(t,e,r){let n=this,i,o,s,a,l;return c;function c(k){return u(k)}function u(k){return t.enter("htmlFlow"),t.enter("htmlFlowData"),t.consume(k),d}function d(k){return k===33?(t.consume(k),p):k===47?(t.consume(k),o=!0,h):k===63?(t.consume(k),i=3,n.interrupt?e:x):In(k)?(t.consume(k),s=String.fromCharCode(k),y):r(k)}function p(k){return k===45?(t.consume(k),i=2,f):k===91?(t.consume(k),i=5,a=0,m):In(k)?(t.consume(k),i=4,n.interrupt?e:x):r(k)}function f(k){return k===45?(t.consume(k),n.interrupt?e:x):r(k)}function m(k){let Vt="CDATA[";return k===Vt.charCodeAt(a++)?(t.consume(k),a===Vt.length?n.interrupt?e:H:m):r(k)}function h(k){return In(k)?(t.consume(k),s=String.fromCharCode(k),y):r(k)}function y(k){if(k===null||k===47||k===62||Ft(k)){let Vt=k===47,qt=s.toLowerCase();return!Vt&&!o&&UI.includes(qt)?(i=1,n.interrupt?e(k):H(k)):Cj.includes(s.toLowerCase())?(i=6,Vt?(t.consume(k),g):n.interrupt?e(k):H(k)):(i=7,n.interrupt&&!n.parser.lazy[n.now().line]?r(k):o?_(k):b(k))}return k===45||sr(k)?(t.consume(k),s+=String.fromCharCode(k),y):r(k)}function g(k){return k===62?(t.consume(k),n.interrupt?e:H):r(k)}function _(k){return Se(k)?(t.consume(k),_):L(k)}function b(k){return k===47?(t.consume(k),L):k===58||k===95||In(k)?(t.consume(k),E):Se(k)?(t.consume(k),b):L(k)}function E(k){return k===45||k===46||k===58||k===95||sr(k)?(t.consume(k),E):I(k)}function I(k){return k===61?(t.consume(k),P):Se(k)?(t.consume(k),I):b(k)}function P(k){return k===null||k===60||k===61||k===62||k===96?r(k):k===34||k===39?(t.consume(k),l=k,M):Se(k)?(t.consume(k),P):V(k)}function M(k){return k===l?(t.consume(k),l=null,R):k===null||ne(k)?r(k):(t.consume(k),M)}function V(k){return k===null||k===34||k===39||k===47||k===60||k===61||k===62||k===96||Ft(k)?I(k):(t.consume(k),V)}function R(k){return k===47||k===62||Se(k)?b(k):r(k)}function L(k){return k===62?(t.consume(k),G):r(k)}function G(k){return k===null||ne(k)?H(k):Se(k)?(t.consume(k),G):r(k)}function H(k){return k===45&&i===2?(t.consume(k),Ve):k===60&&i===1?(t.consume(k),it):k===62&&i===4?(t.consume(k),Dr):k===63&&i===3?(t.consume(k),x):k===93&&i===5?(t.consume(k),Pt):ne(k)&&(i===6||i===7)?(t.exit("htmlFlowData"),t.check(k7,Hn,W)(k)):k===null||ne(k)?(t.exit("htmlFlowData"),W(k)):(t.consume(k),H)}function W(k){return t.check(S7,Y,Hn)(k)}function Y(k){return t.enter("lineEnding"),t.consume(k),t.exit("lineEnding"),ie}function ie(k){return k===null||ne(k)?W(k):(t.enter("htmlFlowData"),H(k))}function Ve(k){return k===45?(t.consume(k),x):H(k)}function it(k){return k===47?(t.consume(k),s="",Ot):H(k)}function Ot(k){if(k===62){let Vt=s.toLowerCase();return UI.includes(Vt)?(t.consume(k),Dr):H(k)}return In(k)&&s.length<8?(t.consume(k),s+=String.fromCharCode(k),Ot):H(k)}function Pt(k){return k===93?(t.consume(k),x):H(k)}function x(k){return k===62?(t.consume(k),Dr):k===45&&i===2?(t.consume(k),x):H(k)}function Dr(k){return k===null||ne(k)?(t.exit("htmlFlowData"),Hn(k)):(t.consume(k),Dr)}function Hn(k){return t.exit("htmlFlow"),e(k)}}function P7(t,e,r){let n=this;return i;function i(s){return ne(s)?(t.enter("lineEnding"),t.consume(s),t.exit("lineEnding"),o):r(s)}function o(s){return n.parser.lazy[n.now().line]?r(s):e(s)}}function T7(t,e,r){return n;function n(i){return t.enter("lineEnding"),t.consume(i),t.exit("lineEnding"),t.attempt(Os,e,r)}}var FI={name:"htmlText",tokenize:A7};function A7(t,e,r){let n=this,i,o,s;return a;function a(x){return t.enter("htmlText"),t.enter("htmlTextData"),t.consume(x),l}function l(x){return x===33?(t.consume(x),c):x===47?(t.consume(x),I):x===63?(t.consume(x),b):In(x)?(t.consume(x),V):r(x)}function c(x){return x===45?(t.consume(x),u):x===91?(t.consume(x),o=0,m):In(x)?(t.consume(x),_):r(x)}function u(x){return x===45?(t.consume(x),f):r(x)}function d(x){return x===null?r(x):x===45?(t.consume(x),p):ne(x)?(s=d,it(x)):(t.consume(x),d)}function p(x){return x===45?(t.consume(x),f):d(x)}function f(x){return x===62?Ve(x):x===45?p(x):d(x)}function m(x){let Dr="CDATA[";return x===Dr.charCodeAt(o++)?(t.consume(x),o===Dr.length?h:m):r(x)}function h(x){return x===null?r(x):x===93?(t.consume(x),y):ne(x)?(s=h,it(x)):(t.consume(x),h)}function y(x){return x===93?(t.consume(x),g):h(x)}function g(x){return x===62?Ve(x):x===93?(t.consume(x),g):h(x)}function _(x){return x===null||x===62?Ve(x):ne(x)?(s=_,it(x)):(t.consume(x),_)}function b(x){return x===null?r(x):x===63?(t.consume(x),E):ne(x)?(s=b,it(x)):(t.consume(x),b)}function E(x){return x===62?Ve(x):b(x)}function I(x){return In(x)?(t.consume(x),P):r(x)}function P(x){return x===45||sr(x)?(t.consume(x),P):M(x)}function M(x){return ne(x)?(s=M,it(x)):Se(x)?(t.consume(x),M):Ve(x)}function V(x){return x===45||sr(x)?(t.consume(x),V):x===47||x===62||Ft(x)?R(x):r(x)}function R(x){return x===47?(t.consume(x),Ve):x===58||x===95||In(x)?(t.consume(x),L):ne(x)?(s=R,it(x)):Se(x)?(t.consume(x),R):Ve(x)}function L(x){return x===45||x===46||x===58||x===95||sr(x)?(t.consume(x),L):G(x)}function G(x){return x===61?(t.consume(x),H):ne(x)?(s=G,it(x)):Se(x)?(t.consume(x),G):R(x)}function H(x){return x===null||x===60||x===61||x===62||x===96?r(x):x===34||x===39?(t.consume(x),i=x,W):ne(x)?(s=H,it(x)):Se(x)?(t.consume(x),H):(t.consume(x),Y)}function W(x){return x===i?(t.consume(x),i=void 0,ie):x===null?r(x):ne(x)?(s=W,it(x)):(t.consume(x),W)}function Y(x){return x===null||x===34||x===39||x===60||x===61||x===96?r(x):x===47||x===62||Ft(x)?R(x):(t.consume(x),Y)}function ie(x){return x===47||x===62||Ft(x)?R(x):r(x)}function Ve(x){return x===62?(t.consume(x),t.exit("htmlTextData"),t.exit("htmlText"),e):r(x)}function it(x){return t.exit("htmlTextData"),t.enter("lineEnding"),t.consume(x),t.exit("lineEnding"),Ot}function Ot(x){return Se(x)?Ie(t,Pt,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(x):Pt(x)}function Pt(x){return t.enter("htmlTextData"),s(x)}}var ol={name:"labelEnd",tokenize:M7,resolveTo:R7,resolveAll:O7},z7={tokenize:j7},C7={tokenize:D7},N7={tokenize:L7};function O7(t){let e=-1;for(;++e<t.length;){let r=t[e][1];(r.type==="labelImage"||r.type==="labelLink"||r.type==="labelEnd")&&(t.splice(e+1,r.type==="labelImage"?4:2),r.type="data",e++)}return t}function R7(t,e){let r=t.length,n=0,i,o,s,a;for(;r--;)if(i=t[r][1],o){if(i.type==="link"||i.type==="labelLink"&&i._inactive)break;t[r][0]==="enter"&&i.type==="labelLink"&&(i._inactive=!0)}else if(s){if(t[r][0]==="enter"&&(i.type==="labelImage"||i.type==="labelLink")&&!i._balanced&&(o=r,i.type!=="labelLink")){n=2;break}}else i.type==="labelEnd"&&(s=r);let l={type:t[o][1].type==="labelLink"?"link":"image",start:Object.assign({},t[o][1].start),end:Object.assign({},t[t.length-1][1].end)},c={type:"label",start:Object.assign({},t[o][1].start),end:Object.assign({},t[s][1].end)},u={type:"labelText",start:Object.assign({},t[o+n+2][1].end),end:Object.assign({},t[s-2][1].start)};return a=[["enter",l,e],["enter",c,e]],a=Hr(a,t.slice(o+1,o+n+3)),a=Hr(a,[["enter",u,e]]),a=Hr(a,Du(e.parser.constructs.insideSpan.null,t.slice(o+n+4,s-3),e)),a=Hr(a,[["exit",u,e],t[s-2],t[s-1],["exit",c,e]]),a=Hr(a,t.slice(s+1)),a=Hr(a,[["exit",l,e]]),Mr(t,o,t.length,a),t}function M7(t,e,r){let n=this,i=n.events.length,o,s;for(;i--;)if((n.events[i][1].type==="labelImage"||n.events[i][1].type==="labelLink")&&!n.events[i][1]._balanced){o=n.events[i][1];break}return a;function a(p){return o?o._inactive?d(p):(s=n.parser.defined.includes(Mo(n.sliceSerialize({start:o.end,end:n.now()}))),t.enter("labelEnd"),t.enter("labelMarker"),t.consume(p),t.exit("labelMarker"),t.exit("labelEnd"),l):r(p)}function l(p){return p===40?t.attempt(z7,u,s?u:d)(p):p===91?t.attempt(C7,u,s?c:d)(p):s?u(p):d(p)}function c(p){return t.attempt(N7,u,d)(p)}function u(p){return e(p)}function d(p){return o._balanced=!0,r(p)}}function j7(t,e,r){return n;function n(d){return t.enter("resource"),t.enter("resourceMarker"),t.consume(d),t.exit("resourceMarker"),i}function i(d){return Ft(d)?il(t,o)(d):o(d)}function o(d){return d===41?u(d):Ev(t,s,a,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(d)}function s(d){return Ft(d)?il(t,l)(d):u(d)}function a(d){return r(d)}function l(d){return d===34||d===39||d===40?Tv(t,c,r,"resourceTitle","resourceTitleMarker","resourceTitleString")(d):u(d)}function c(d){return Ft(d)?il(t,u)(d):u(d)}function u(d){return d===41?(t.enter("resourceMarker"),t.consume(d),t.exit("resourceMarker"),t.exit("resource"),e):r(d)}}function D7(t,e,r){let n=this;return i;function i(a){return Pv.call(n,t,o,s,"reference","referenceMarker","referenceString")(a)}function o(a){return n.parser.defined.includes(Mo(n.sliceSerialize(n.events[n.events.length-1][1]).slice(1,-1)))?e(a):r(a)}function s(a){return r(a)}}function L7(t,e,r){return n;function n(o){return t.enter("reference"),t.enter("referenceMarker"),t.consume(o),t.exit("referenceMarker"),i}function i(o){return o===93?(t.enter("referenceMarker"),t.consume(o),t.exit("referenceMarker"),t.exit("reference"),e):r(o)}}var VI={name:"labelStartImage",tokenize:U7,resolveAll:ol.resolveAll};function U7(t,e,r){let n=this;return i;function i(a){return t.enter("labelImage"),t.enter("labelImageMarker"),t.consume(a),t.exit("labelImageMarker"),o}function o(a){return a===91?(t.enter("labelMarker"),t.consume(a),t.exit("labelMarker"),t.exit("labelImage"),s):r(a)}function s(a){return a===94&&"_hiddenFootnoteSupport"in n.parser.constructs?r(a):e(a)}}var qI={name:"labelStartLink",tokenize:Z7,resolveAll:ol.resolveAll};function Z7(t,e,r){let n=this;return i;function i(s){return t.enter("labelLink"),t.enter("labelMarker"),t.consume(s),t.exit("labelMarker"),t.exit("labelLink"),o}function o(s){return s===94&&"_hiddenFootnoteSupport"in n.parser.constructs?r(s):e(s)}}var lm={name:"lineEnding",tokenize:F7};function F7(t,e){return r;function r(n){return t.enter("lineEnding"),t.consume(n),t.exit("lineEnding"),Ie(t,e,"linePrefix")}}var sl={name:"thematicBreak",tokenize:V7};function V7(t,e,r){let n=0,i;return o;function o(c){return t.enter("thematicBreak"),s(c)}function s(c){return i=c,a(c)}function a(c){return c===i?(t.enter("thematicBreakSequence"),l(c)):n>=3&&(c===null||ne(c))?(t.exit("thematicBreak"),e(c)):r(c)}function l(c){return c===i?(t.consume(c),n++,l):(t.exit("thematicBreakSequence"),Se(c)?Ie(t,a,"whitespace")(c):a(c))}}var jr={name:"list",tokenize:B7,continuation:{tokenize:G7},exit:X7},q7={tokenize:K7,partial:!0},W7={tokenize:H7,partial:!0};function B7(t,e,r){let n=this,i=n.events[n.events.length-1],o=i&&i[1].type==="linePrefix"?i[2].sliceSerialize(i[1],!0).length:0,s=0;return a;function a(f){let m=n.containerState.type||(f===42||f===43||f===45?"listUnordered":"listOrdered");if(m==="listUnordered"?!n.containerState.marker||f===n.containerState.marker:im(f)){if(n.containerState.type||(n.containerState.type=m,t.enter(m,{_container:!0})),m==="listUnordered")return t.enter("listItemPrefix"),f===42||f===45?t.check(sl,r,c)(f):c(f);if(!n.interrupt||f===49)return t.enter("listItemPrefix"),t.enter("listItemValue"),l(f)}return r(f)}function l(f){return im(f)&&++s<10?(t.consume(f),l):(!n.interrupt||s<2)&&(n.containerState.marker?f===n.containerState.marker:f===41||f===46)?(t.exit("listItemValue"),c(f)):r(f)}function c(f){return t.enter("listItemMarker"),t.consume(f),t.exit("listItemMarker"),n.containerState.marker=n.containerState.marker||f,t.check(Os,n.interrupt?r:u,t.attempt(q7,p,d))}function u(f){return n.containerState.initialBlankLine=!0,o++,p(f)}function d(f){return Se(f)?(t.enter("listItemPrefixWhitespace"),t.consume(f),t.exit("listItemPrefixWhitespace"),p):r(f)}function p(f){return n.containerState.size=o+n.sliceSerialize(t.exit("listItemPrefix"),!0).length,e(f)}}function G7(t,e,r){let n=this;return n.containerState._closeFlow=void 0,t.check(Os,i,o);function i(a){return n.containerState.furtherBlankLines=n.containerState.furtherBlankLines||n.containerState.initialBlankLine,Ie(t,e,"listItemIndent",n.containerState.size+1)(a)}function o(a){return n.containerState.furtherBlankLines||!Se(a)?(n.containerState.furtherBlankLines=void 0,n.containerState.initialBlankLine=void 0,s(a)):(n.containerState.furtherBlankLines=void 0,n.containerState.initialBlankLine=void 0,t.attempt(W7,e,s)(a))}function s(a){return n.containerState._closeFlow=!0,n.interrupt=void 0,Ie(t,t.attempt(jr,e,r),"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(a)}}function H7(t,e,r){let n=this;return Ie(t,i,"listItemIndent",n.containerState.size+1);function i(o){let s=n.events[n.events.length-1];return s&&s[1].type==="listItemIndent"&&s[2].sliceSerialize(s[1],!0).length===n.containerState.size?e(o):r(o)}}function X7(t){t.exit(this.containerState.type)}function K7(t,e,r){let n=this;return Ie(t,i,"listItemPrefixWhitespace",n.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function i(o){let s=n.events[n.events.length-1];return!Se(o)&&s&&s[1].type==="listItemPrefixWhitespace"?e(o):r(o)}}var Av={name:"setextUnderline",tokenize:Y7,resolveTo:J7};function J7(t,e){let r=t.length,n,i,o;for(;r--;)if(t[r][0]==="enter"){if(t[r][1].type==="content"){n=r;break}t[r][1].type==="paragraph"&&(i=r)}else t[r][1].type==="content"&&t.splice(r,1),!o&&t[r][1].type==="definition"&&(o=r);let s={type:"setextHeading",start:Object.assign({},t[i][1].start),end:Object.assign({},t[t.length-1][1].end)};return t[i][1].type="setextHeadingText",o?(t.splice(i,0,["enter",s,e]),t.splice(o+1,0,["exit",t[n][1],e]),t[n][1].end=Object.assign({},t[o][1].end)):t[n][1]=s,t.push(["exit",s,e]),t}function Y7(t,e,r){let n=this,i;return o;function o(c){let u=n.events.length,d;for(;u--;)if(n.events[u][1].type!=="lineEnding"&&n.events[u][1].type!=="linePrefix"&&n.events[u][1].type!=="content"){d=n.events[u][1].type==="paragraph";break}return!n.parser.lazy[n.now().line]&&(n.interrupt||d)?(t.enter("setextHeadingLine"),i=c,s(c)):r(c)}function s(c){return t.enter("setextHeadingLineSequence"),a(c)}function a(c){return c===i?(t.consume(c),a):(t.exit("setextHeadingLineSequence"),Se(c)?Ie(t,l,"lineSuffix")(c):l(c))}function l(c){return c===null||ne(c)?(t.exit("setextHeadingLine"),e(c)):r(c)}}var Nj={tokenize:Q7};function Q7(t){let e=this,r=t.attempt(Os,n,t.attempt(this.parser.constructs.flowInitial,i,Ie(t,t.attempt(this.parser.constructs.flow,i,t.attempt(MI,i)),"linePrefix")));return r;function n(o){if(o===null){t.consume(o);return}return t.enter("lineEndingBlank"),t.consume(o),t.exit("lineEndingBlank"),e.currentConstruct=void 0,r}function i(o){if(o===null){t.consume(o);return}return t.enter("lineEnding"),t.consume(o),t.exit("lineEnding"),e.currentConstruct=void 0,r}}var Oj={resolveAll:Dj()},Rj=jj("string"),Mj=jj("text");function jj(t){return{tokenize:e,resolveAll:Dj(t==="text"?eY:void 0)};function e(r){let n=this,i=this.parser.constructs[t],o=r.attempt(i,s,a);return s;function s(u){return c(u)?o(u):a(u)}function a(u){if(u===null){r.consume(u);return}return r.enter("data"),r.consume(u),l}function l(u){return c(u)?(r.exit("data"),o(u)):(r.consume(u),l)}function c(u){if(u===null)return!0;let d=i[u],p=-1;if(d)for(;++p<d.length;){let f=d[p];if(!f.previous||f.previous.call(n,n.previous))return!0}return!1}}}function Dj(t){return e;function e(r,n){let i=-1,o;for(;++i<=r.length;)o===void 0?r[i]&&r[i][1].type==="data"&&(o=i,i++):(!r[i]||r[i][1].type!=="data")&&(i!==o+2&&(r[o][1].end=r[i-1][1].end,r.splice(o+2,i-o-2),i=o+2),o=void 0);return t?t(r,n):r}}function eY(t,e){let r=0;for(;++r<=t.length;)if((r===t.length||t[r][1].type==="lineEnding")&&t[r-1][1].type==="data"){let n=t[r-1][1],i=e.sliceStream(n),o=i.length,s=-1,a=0,l;for(;o--;){let c=i[o];if(typeof c=="string"){for(s=c.length;c.charCodeAt(s-1)===32;)a++,s--;if(s)break;s=-1}else if(c===-2)l=!0,a++;else if(c!==-1){o++;break}}if(a){let c={type:r===t.length||l||a<2?"lineSuffix":"hardBreakTrailing",start:{line:n.end.line,column:n.end.column-a,offset:n.end.offset-a,_index:n.start._index+o,_bufferIndex:o?s:n.start._bufferIndex+s},end:Object.assign({},n.end)};n.end=Object.assign({},c.start),n.start.offset===n.end.offset?Object.assign(n,c):(t.splice(r,0,["enter",c,e],["exit",c,e]),r+=2)}r++}return t}function Lj(t,e,r){let n=Object.assign(r?Object.assign({},r):{line:1,column:1,offset:0},{_index:0,_bufferIndex:-1}),i={},o=[],s=[],a=[],l=!0,c={consume:E,enter:I,exit:P,attempt:R(M),check:R(V),interrupt:R(V,{interrupt:!0})},u={previous:null,code:null,containerState:{},events:[],parser:t,sliceStream:h,sliceSerialize:m,now:y,defineSkip:g,write:f},d=e.tokenize.call(u,c),p;return e.resolveAll&&o.push(e),u;function f(W){return s=Hr(s,W),_(),s[s.length-1]!==null?[]:(L(e,0),u.events=Du(o,u.events,u),u.events)}function m(W,Y){return rY(h(W),Y)}function h(W){return tY(s,W)}function y(){let{line:W,column:Y,offset:ie,_index:Ve,_bufferIndex:it}=n;return{line:W,column:Y,offset:ie,_index:Ve,_bufferIndex:it}}function g(W){i[W.line]=W.column,H()}function _(){let W;for(;n._index<s.length;){let Y=s[n._index];if(typeof Y=="string")for(W=n._index,n._bufferIndex<0&&(n._bufferIndex=0);n._index===W&&n._bufferIndex<Y.length;)b(Y.charCodeAt(n._bufferIndex));else b(Y)}}function b(W){l=void 0,p=W,d=d(W)}function E(W){ne(W)?(n.line++,n.column=1,n.offset+=W===-3?2:1,H()):W!==-1&&(n.column++,n.offset++),n._bufferIndex<0?n._index++:(n._bufferIndex++,n._bufferIndex===s[n._index].length&&(n._bufferIndex=-1,n._index++)),u.previous=W,l=!0}function I(W,Y){let ie=Y||{};return ie.type=W,ie.start=y(),u.events.push(["enter",ie,u]),a.push(ie),ie}function P(W){let Y=a.pop();return Y.end=y(),u.events.push(["exit",Y,u]),Y}function M(W,Y){L(W,Y.from)}function V(W,Y){Y.restore()}function R(W,Y){return ie;function ie(Ve,it,Ot){let Pt,x,Dr,Hn;return Array.isArray(Ve)?Vt(Ve):"tokenize"in Ve?Vt([Ve]):k(Ve);function k(Rt){return Hi;function Hi(Kr){let Xi=Kr!==null&&Rt[Kr],jo=Kr!==null&&Rt.null,Bu=[...Array.isArray(Xi)?Xi:Xi?[Xi]:[],...Array.isArray(jo)?jo:jo?[jo]:[]];return Vt(Bu)(Kr)}}function Vt(Rt){return Pt=Rt,x=0,Rt.length===0?Ot:qt(Rt[x])}function qt(Rt){return Hi;function Hi(Kr){return Hn=G(),Dr=Rt,Rt.partial||(u.currentConstruct=Rt),Rt.name&&u.parser.constructs.disable.null.includes(Rt.name)?Xn(Kr):Rt.tokenize.call(Y?Object.assign(Object.create(u),Y):u,c,Xr,Xn)(Kr)}}function Xr(Rt){return l=!0,W(Dr,Hn),it}function Xn(Rt){return l=!0,Hn.restore(),++x<Pt.length?qt(Pt[x]):Ot}}}function L(W,Y){W.resolveAll&&!o.includes(W)&&o.push(W),W.resolve&&Mr(u.events,Y,u.events.length-Y,W.resolve(u.events.slice(Y),u)),W.resolveTo&&(u.events=W.resolveTo(u.events,u))}function G(){let W=y(),Y=u.previous,ie=u.currentConstruct,Ve=u.events.length,it=Array.from(a);return{restore:Ot,from:Ve};function Ot(){n=W,u.previous=Y,u.currentConstruct=ie,u.events.length=Ve,a=it,H()}}function H(){n.line in i&&n.column<2&&(n.column=i[n.line],n.offset+=i[n.line]-1)}}function tY(t,e){let r=e.start._index,n=e.start._bufferIndex,i=e.end._index,o=e.end._bufferIndex,s;if(r===i)s=[t[r].slice(n,o)];else{if(s=t.slice(r,i),n>-1){let a=s[0];typeof a=="string"?s[0]=a.slice(n):s.shift()}o>0&&s.push(t[i].slice(0,o))}return s}function rY(t,e){let r=-1,n=[],i;for(;++r<t.length;){let o=t[r],s;if(typeof o=="string")s=o;else switch(o){case-5:{s="\r";break}case-4:{s=`
|
|
360
|
+
`;break}case-3:{s=`\r
|
|
361
|
+
`;break}case-2:{s=e?" ":" ";break}case-1:{if(!e&&i)continue;s=" ";break}default:s=String.fromCharCode(o)}i=o===-2,n.push(s)}return n.join("")}var WI={};ed(WI,{attentionMarkers:()=>uY,contentInitial:()=>iY,disable:()=>dY,document:()=>nY,flow:()=>sY,flowInitial:()=>oY,insideSpan:()=>cY,string:()=>aY,text:()=>lY});var nY={42:jr,43:jr,45:jr,48:jr,49:jr,50:jr,51:jr,52:jr,53:jr,54:jr,55:jr,56:jr,57:jr,62:wv},iY={91:jI},oY={[-2]:sm,[-1]:sm,32:sm},sY={35:LI,42:sl,45:[Av,sl],60:ZI,61:Av,95:sl,96:kv,126:kv},aY={38:$v,92:xv},lY={[-5]:lm,[-4]:lm,[-3]:lm,33:VI,38:$v,42:om,60:[OI,FI],91:qI,92:[DI,xv],93:ol,95:om,96:RI},cY={null:[om,Oj]},uY={null:[42,95]},dY={null:[]};function BI(t){let r=wj([WI,...(t||{}).extensions||[]]),n={defined:[],lazy:{},constructs:r,content:i(Ej),document:i(Tj),flow:i(Nj),string:i(Rj),text:i(Mj)};return n;function i(o){return s;function s(a){return Lj(n,o,a)}}}function GI(t){for(;!Iv(t););return t}var Uj=/[\0\t\n\r]/g;function HI(){let t=1,e="",r=!0,n;return i;function i(o,s,a){let l=[],c,u,d,p,f;for(o=e+(typeof o=="string"?o.toString():new TextDecoder(s||void 0).decode(o)),d=0,e="",r&&(o.charCodeAt(0)===65279&&d++,r=void 0);d<o.length;){if(Uj.lastIndex=d,c=Uj.exec(o),p=c&&c.index!==void 0?c.index:o.length,f=o.charCodeAt(p),!c){e=o.slice(d);break}if(f===10&&d===p&&n)l.push(-3),n=void 0;else switch(n&&(l.push(-5),n=void 0),d<p&&(l.push(o.slice(d,p)),t+=p-d),f){case 0:{l.push(65533),t++;break}case 9:{for(u=Math.ceil(t/4)*4,l.push(-2);t++<u;)l.push(-1);break}case 10:{l.push(-4),t=1;break}default:n=!0,t=1}d=p+1}return a&&(n&&l.push(-5),e&&l.push(e),l.push(null)),l}}var fY=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function Zj(t){return t.replace(fY,pY)}function pY(t,e,r){if(e)return e;if(r.charCodeAt(0)===35){let i=r.charCodeAt(1),o=i===120||i===88;return bv(r.slice(o?2:1),o?16:10)}return ju(r)||t}function Rs(t){return!t||typeof t!="object"?"":"position"in t||"type"in t?Fj(t.position):"start"in t||"end"in t?Fj(t):"line"in t||"column"in t?XI(t):""}function XI(t){return Vj(t&&t.line)+":"+Vj(t&&t.column)}function Fj(t){return XI(t&&t.start)+"-"+XI(t&&t.end)}function Vj(t){return t&&typeof t=="number"?t:1}var Wj={}.hasOwnProperty;function KI(t,e,r){return typeof e!="string"&&(r=e,e=void 0),mY(r)(GI(BI(r).document().write(HI()(t,e,!0))))}function mY(t){let e={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:o(Hu),autolinkProtocol:R,autolinkEmail:R,atxHeading:o(En),blockQuote:o(Hi),characterEscape:R,characterReference:R,codeFenced:o(Kr),codeFencedFenceInfo:s,codeFencedFenceMeta:s,codeIndented:o(Kr,s),codeText:o(Xi,s),codeTextData:R,data:R,codeFlowValue:R,definition:o(jo),definitionDestinationString:s,definitionLabelString:s,definitionTitleString:s,emphasis:o(Bu),hardBreakEscape:o(_m),hardBreakTrailing:o(_m),htmlFlow:o(Gu,s),htmlFlowData:R,htmlText:o(Gu,s),htmlTextData:R,image:o(bm),label:s,link:o(Hu),listItem:o(Do),listItemValue:p,listOrdered:o(wm,d),listUnordered:o(wm),paragraph:o(Pn),reference:k,referenceString:s,resourceDestinationString:s,resourceTitleString:s,setextHeading:o(En),strong:o(xm),thematicBreak:o(Yv)},exit:{atxHeading:l(),atxHeadingSequence:I,autolink:l(),autolinkEmail:Rt,autolinkProtocol:Xn,blockQuote:l(),characterEscapeValue:L,characterReferenceMarkerHexadecimal:qt,characterReferenceMarkerNumeric:qt,characterReferenceValue:Xr,codeFenced:l(y),codeFencedFence:h,codeFencedFenceInfo:f,codeFencedFenceMeta:m,codeFlowValue:L,codeIndented:l(g),codeText:l(ie),codeTextData:L,data:L,definition:l(),definitionDestinationString:E,definitionLabelString:_,definitionTitleString:b,emphasis:l(),hardBreakEscape:l(H),hardBreakTrailing:l(H),htmlFlow:l(W),htmlFlowData:L,htmlText:l(Y),htmlTextData:L,image:l(it),label:Pt,labelText:Ot,lineEnding:G,link:l(Ve),listItem:l(),listOrdered:l(),listUnordered:l(),paragraph:l(),referenceString:Vt,resourceDestinationString:x,resourceTitleString:Dr,resource:Hn,setextHeading:l(V),setextHeadingLineSequence:M,setextHeadingText:P,strong:l(),thematicBreak:l()}};Bj(e,(t||{}).mdastExtensions||[]);let r={};return n;function n(j){let K={type:"root",children:[]},fe={stack:[K],tokenStack:[],config:e,enter:a,exit:c,buffer:s,resume:u,data:r},Pe=[],nt=-1;for(;++nt<j.length;)if(j[nt][1].type==="listOrdered"||j[nt][1].type==="listUnordered")if(j[nt][0]==="enter")Pe.push(nt);else{let Jr=Pe.pop();nt=i(j,Jr,nt)}for(nt=-1;++nt<j.length;){let Jr=e[j[nt][0]];Wj.call(Jr,j[nt][1].type)&&Jr[j[nt][1].type].call(Object.assign({sliceSerialize:j[nt][2].sliceSerialize},fe),j[nt][1])}if(fe.tokenStack.length>0){let Jr=fe.tokenStack[fe.tokenStack.length-1];(Jr[1]||qj).call(fe,void 0,Jr[0])}for(K.position={start:Ms(j.length>0?j[0][1].start:{line:1,column:1,offset:0}),end:Ms(j.length>0?j[j.length-2][1].end:{line:1,column:1,offset:0})},nt=-1;++nt<e.transforms.length;)K=e.transforms[nt](K)||K;return K}function i(j,K,fe){let Pe=K-1,nt=-1,Jr=!1,dn,Tn,js,Ds;for(;++Pe<=fe;){let $r=j[Pe];switch($r[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{$r[0]==="enter"?nt++:nt--,Ds=void 0;break}case"lineEndingBlank":{$r[0]==="enter"&&(dn&&!Ds&&!nt&&!js&&(js=Pe),Ds=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:Ds=void 0}if(!nt&&$r[0]==="enter"&&$r[1].type==="listItemPrefix"||nt===-1&&$r[0]==="exit"&&($r[1].type==="listUnordered"||$r[1].type==="listOrdered")){if(dn){let lr=Pe;for(Tn=void 0;lr--;){let Kn=j[lr];if(Kn[1].type==="lineEnding"||Kn[1].type==="lineEndingBlank"){if(Kn[0]==="exit")continue;Tn&&(j[Tn][1].type="lineEndingBlank",Jr=!0),Kn[1].type="lineEnding",Tn=lr}else if(!(Kn[1].type==="linePrefix"||Kn[1].type==="blockQuotePrefix"||Kn[1].type==="blockQuotePrefixWhitespace"||Kn[1].type==="blockQuoteMarker"||Kn[1].type==="listItemIndent"))break}js&&(!Tn||js<Tn)&&(dn._spread=!0),dn.end=Object.assign({},Tn?j[Tn][1].start:$r[1].end),j.splice(Tn||Pe,0,["exit",dn,$r[2]]),Pe++,fe++}if($r[1].type==="listItemPrefix"){let lr={type:"listItem",_spread:!1,start:Object.assign({},$r[1].start),end:void 0};dn=lr,j.splice(Pe,0,["enter",lr,$r[2]]),Pe++,fe++,js=void 0,Ds=!0}}}return j[K][1]._spread=Jr,fe}function o(j,K){return fe;function fe(Pe){a.call(this,j(Pe),Pe),K&&K.call(this,Pe)}}function s(){this.stack.push({type:"fragment",children:[]})}function a(j,K,fe){this.stack[this.stack.length-1].children.push(j),this.stack.push(j),this.tokenStack.push([K,fe]),j.position={start:Ms(K.start),end:void 0}}function l(j){return K;function K(fe){j&&j.call(this,fe),c.call(this,fe)}}function c(j,K){let fe=this.stack.pop(),Pe=this.tokenStack.pop();if(Pe)Pe[0].type!==j.type&&(K?K.call(this,j,Pe[0]):(Pe[1]||qj).call(this,j,Pe[0]));else throw new Error("Cannot close `"+j.type+"` ("+Rs({start:j.start,end:j.end})+"): it\u2019s not open");fe.position.end=Ms(j.end)}function u(){return CI(this.stack.pop())}function d(){this.data.expectingFirstListItemValue=!0}function p(j){if(this.data.expectingFirstListItemValue){let K=this.stack[this.stack.length-2];K.start=Number.parseInt(this.sliceSerialize(j),10),this.data.expectingFirstListItemValue=void 0}}function f(){let j=this.resume(),K=this.stack[this.stack.length-1];K.lang=j}function m(){let j=this.resume(),K=this.stack[this.stack.length-1];K.meta=j}function h(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function y(){let j=this.resume(),K=this.stack[this.stack.length-1];K.value=j.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function g(){let j=this.resume(),K=this.stack[this.stack.length-1];K.value=j.replace(/(\r?\n|\r)$/g,"")}function _(j){let K=this.resume(),fe=this.stack[this.stack.length-1];fe.label=K,fe.identifier=Mo(this.sliceSerialize(j)).toLowerCase()}function b(){let j=this.resume(),K=this.stack[this.stack.length-1];K.title=j}function E(){let j=this.resume(),K=this.stack[this.stack.length-1];K.url=j}function I(j){let K=this.stack[this.stack.length-1];if(!K.depth){let fe=this.sliceSerialize(j).length;K.depth=fe}}function P(){this.data.setextHeadingSlurpLineEnding=!0}function M(j){let K=this.stack[this.stack.length-1];K.depth=this.sliceSerialize(j).codePointAt(0)===61?1:2}function V(){this.data.setextHeadingSlurpLineEnding=void 0}function R(j){let fe=this.stack[this.stack.length-1].children,Pe=fe[fe.length-1];(!Pe||Pe.type!=="text")&&(Pe=Jv(),Pe.position={start:Ms(j.start),end:void 0},fe.push(Pe)),this.stack.push(Pe)}function L(j){let K=this.stack.pop();K.value+=this.sliceSerialize(j),K.position.end=Ms(j.end)}function G(j){let K=this.stack[this.stack.length-1];if(this.data.atHardBreak){let fe=K.children[K.children.length-1];fe.position.end=Ms(j.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&e.canContainEols.includes(K.type)&&(R.call(this,j),L.call(this,j))}function H(){this.data.atHardBreak=!0}function W(){let j=this.resume(),K=this.stack[this.stack.length-1];K.value=j}function Y(){let j=this.resume(),K=this.stack[this.stack.length-1];K.value=j}function ie(){let j=this.resume(),K=this.stack[this.stack.length-1];K.value=j}function Ve(){let j=this.stack[this.stack.length-1];if(this.data.inReference){let K=this.data.referenceType||"shortcut";j.type+="Reference",j.referenceType=K,delete j.url,delete j.title}else delete j.identifier,delete j.label;this.data.referenceType=void 0}function it(){let j=this.stack[this.stack.length-1];if(this.data.inReference){let K=this.data.referenceType||"shortcut";j.type+="Reference",j.referenceType=K,delete j.url,delete j.title}else delete j.identifier,delete j.label;this.data.referenceType=void 0}function Ot(j){let K=this.sliceSerialize(j),fe=this.stack[this.stack.length-2];fe.label=Zj(K),fe.identifier=Mo(K).toLowerCase()}function Pt(){let j=this.stack[this.stack.length-1],K=this.resume(),fe=this.stack[this.stack.length-1];if(this.data.inReference=!0,fe.type==="link"){let Pe=j.children;fe.children=Pe}else fe.alt=K}function x(){let j=this.resume(),K=this.stack[this.stack.length-1];K.url=j}function Dr(){let j=this.resume(),K=this.stack[this.stack.length-1];K.title=j}function Hn(){this.data.inReference=void 0}function k(){this.data.referenceType="collapsed"}function Vt(j){let K=this.resume(),fe=this.stack[this.stack.length-1];fe.label=K,fe.identifier=Mo(this.sliceSerialize(j)).toLowerCase(),this.data.referenceType="full"}function qt(j){this.data.characterReferenceType=j.type}function Xr(j){let K=this.sliceSerialize(j),fe=this.data.characterReferenceType,Pe;fe?(Pe=bv(K,fe==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):Pe=ju(K);let nt=this.stack.pop();nt.value+=Pe,nt.position.end=Ms(j.end)}function Xn(j){L.call(this,j);let K=this.stack[this.stack.length-1];K.url=this.sliceSerialize(j)}function Rt(j){L.call(this,j);let K=this.stack[this.stack.length-1];K.url="mailto:"+this.sliceSerialize(j)}function Hi(){return{type:"blockquote",children:[]}}function Kr(){return{type:"code",lang:null,meta:null,value:""}}function Xi(){return{type:"inlineCode",value:""}}function jo(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function Bu(){return{type:"emphasis",children:[]}}function En(){return{type:"heading",depth:0,children:[]}}function _m(){return{type:"break"}}function Gu(){return{type:"html",value:""}}function bm(){return{type:"image",title:null,url:"",alt:null}}function Hu(){return{type:"link",title:null,url:"",children:[]}}function wm(j){return{type:"list",ordered:j.type==="listOrdered",start:null,spread:j._spread,children:[]}}function Do(j){return{type:"listItem",spread:j._spread,checked:null,children:[]}}function Pn(){return{type:"paragraph",children:[]}}function xm(){return{type:"strong",children:[]}}function Jv(){return{type:"text",value:""}}function Yv(){return{type:"thematicBreak"}}}function Ms(t){return{line:t.line,column:t.column,offset:t.offset}}function Bj(t,e){let r=-1;for(;++r<e.length;){let n=e[r];Array.isArray(n)?Bj(t,n):hY(t,n)}}function hY(t,e){let r;for(r in e)if(Wj.call(e,r))switch(r){case"canContainEols":{let n=e[r];n&&t[r].push(...n);break}case"transforms":{let n=e[r];n&&t[r].push(...n);break}case"enter":case"exit":{let n=e[r];n&&Object.assign(t[r],n);break}}}function qj(t,e){throw t?new Error("Cannot close `"+t.type+"` ("+Rs({start:t.start,end:t.end})+"): a different token (`"+e.type+"`, "+Rs({start:e.start,end:e.end})+") is open"):new Error("Cannot close document, a token (`"+e.type+"`, "+Rs({start:e.start,end:e.end})+") is still open")}function cm(t){let e=this;e.parser=r;function r(n){return KI(n,{...e.data("settings"),...t,extensions:e.data("micromarkExtensions")||[],mdastExtensions:e.data("fromMarkdownExtensions")||[]})}}function Gj(t,e){let r={type:"element",tagName:"blockquote",properties:{},children:t.wrap(t.all(e),!0)};return t.patch(e,r),t.applyData(e,r)}function Hj(t,e){let r={type:"element",tagName:"br",properties:{},children:[]};return t.patch(e,r),[t.applyData(e,r),{type:"text",value:`
|
|
362
|
+
`}]}function Xj(t,e){let r=e.value?e.value+`
|
|
363
|
+
`:"",n={};e.lang&&(n.className=["language-"+e.lang]);let i={type:"element",tagName:"code",properties:n,children:[{type:"text",value:r}]};return e.meta&&(i.data={meta:e.meta}),t.patch(e,i),i=t.applyData(e,i),i={type:"element",tagName:"pre",properties:{},children:[i]},t.patch(e,i),i}function Kj(t,e){let r={type:"element",tagName:"del",properties:{},children:t.all(e)};return t.patch(e,r),t.applyData(e,r)}function Jj(t,e){let r={type:"element",tagName:"em",properties:{},children:t.all(e)};return t.patch(e,r),t.applyData(e,r)}function Yj(t,e){let r=typeof t.options.clobberPrefix=="string"?t.options.clobberPrefix:"user-content-",n=String(e.identifier).toUpperCase(),i=Gn(n.toLowerCase()),o=t.footnoteOrder.indexOf(n),s,a=t.footnoteCounts.get(n);a===void 0?(a=0,t.footnoteOrder.push(n),s=t.footnoteOrder.length):s=o+1,a+=1,t.footnoteCounts.set(n,a);let l={type:"element",tagName:"a",properties:{href:"#"+r+"fn-"+i,id:r+"fnref-"+i+(a>1?"-"+a:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(s)}]};t.patch(e,l);let c={type:"element",tagName:"sup",properties:{},children:[l]};return t.patch(e,c),t.applyData(e,c)}function Qj(t,e){let r={type:"element",tagName:"h"+e.depth,properties:{},children:t.all(e)};return t.patch(e,r),t.applyData(e,r)}function eD(t,e){if(t.options.allowDangerousHtml){let r={type:"raw",value:e.value};return t.patch(e,r),t.applyData(e,r)}}function zv(t,e){let r=e.referenceType,n="]";if(r==="collapsed"?n+="[]":r==="full"&&(n+="["+(e.label||e.identifier)+"]"),e.type==="imageReference")return[{type:"text",value:"!["+e.alt+n}];let i=t.all(e),o=i[0];o&&o.type==="text"?o.value="["+o.value:i.unshift({type:"text",value:"["});let s=i[i.length-1];return s&&s.type==="text"?s.value+=n:i.push({type:"text",value:n}),i}function tD(t,e){let r=String(e.identifier).toUpperCase(),n=t.definitionById.get(r);if(!n)return zv(t,e);let i={src:Gn(n.url||""),alt:e.alt};n.title!==null&&n.title!==void 0&&(i.title=n.title);let o={type:"element",tagName:"img",properties:i,children:[]};return t.patch(e,o),t.applyData(e,o)}function rD(t,e){let r={src:Gn(e.url)};e.alt!==null&&e.alt!==void 0&&(r.alt=e.alt),e.title!==null&&e.title!==void 0&&(r.title=e.title);let n={type:"element",tagName:"img",properties:r,children:[]};return t.patch(e,n),t.applyData(e,n)}function nD(t,e){let r={type:"text",value:e.value.replace(/\r?\n|\r/g," ")};t.patch(e,r);let n={type:"element",tagName:"code",properties:{},children:[r]};return t.patch(e,n),t.applyData(e,n)}function iD(t,e){let r=String(e.identifier).toUpperCase(),n=t.definitionById.get(r);if(!n)return zv(t,e);let i={href:Gn(n.url||"")};n.title!==null&&n.title!==void 0&&(i.title=n.title);let o={type:"element",tagName:"a",properties:i,children:t.all(e)};return t.patch(e,o),t.applyData(e,o)}function oD(t,e){let r={href:Gn(e.url)};e.title!==null&&e.title!==void 0&&(r.title=e.title);let n={type:"element",tagName:"a",properties:r,children:t.all(e)};return t.patch(e,n),t.applyData(e,n)}function sD(t,e,r){let n=t.all(e),i=r?gY(r):aD(e),o={},s=[];if(typeof e.checked=="boolean"){let u=n[0],d;u&&u.type==="element"&&u.tagName==="p"?d=u:(d={type:"element",tagName:"p",properties:{},children:[]},n.unshift(d)),d.children.length>0&&d.children.unshift({type:"text",value:" "}),d.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:e.checked,disabled:!0},children:[]}),o.className=["task-list-item"]}let a=-1;for(;++a<n.length;){let u=n[a];(i||a!==0||u.type!=="element"||u.tagName!=="p")&&s.push({type:"text",value:`
|
|
364
|
+
`}),u.type==="element"&&u.tagName==="p"&&!i?s.push(...u.children):s.push(u)}let l=n[n.length-1];l&&(i||l.type!=="element"||l.tagName!=="p")&&s.push({type:"text",value:`
|
|
365
|
+
`});let c={type:"element",tagName:"li",properties:o,children:s};return t.patch(e,c),t.applyData(e,c)}function gY(t){let e=!1;if(t.type==="list"){e=t.spread||!1;let r=t.children,n=-1;for(;!e&&++n<r.length;)e=aD(r[n])}return e}function aD(t){let e=t.spread;return e??t.children.length>1}function lD(t,e){let r={},n=t.all(e),i=-1;for(typeof e.start=="number"&&e.start!==1&&(r.start=e.start);++i<n.length;){let s=n[i];if(s.type==="element"&&s.tagName==="li"&&s.properties&&Array.isArray(s.properties.className)&&s.properties.className.includes("task-list-item")){r.className=["contains-task-list"];break}}let o={type:"element",tagName:e.ordered?"ol":"ul",properties:r,children:t.wrap(n,!0)};return t.patch(e,o),t.applyData(e,o)}function cD(t,e){let r={type:"element",tagName:"p",properties:{},children:t.all(e)};return t.patch(e,r),t.applyData(e,r)}function uD(t,e){let r={type:"root",children:t.wrap(t.all(e))};return t.patch(e,r),t.applyData(e,r)}function dD(t,e){let r={type:"element",tagName:"strong",properties:{},children:t.all(e)};return t.patch(e,r),t.applyData(e,r)}var Cv=fD("end"),Nv=fD("start");function fD(t){return e;function e(r){let n=r&&r.position&&r.position[t]||{};if(typeof n.line=="number"&&n.line>0&&typeof n.column=="number"&&n.column>0)return{line:n.line,column:n.column,offset:typeof n.offset=="number"&&n.offset>-1?n.offset:void 0}}}function JI(t){let e=Nv(t),r=Cv(t);if(e&&r)return{start:e,end:r}}function pD(t,e){let r=t.all(e),n=r.shift(),i=[];if(n){let s={type:"element",tagName:"thead",properties:{},children:t.wrap([n],!0)};t.patch(e.children[0],s),i.push(s)}if(r.length>0){let s={type:"element",tagName:"tbody",properties:{},children:t.wrap(r,!0)},a=Nv(e.children[1]),l=Cv(e.children[e.children.length-1]);a&&l&&(s.position={start:a,end:l}),i.push(s)}let o={type:"element",tagName:"table",properties:{},children:t.wrap(i,!0)};return t.patch(e,o),t.applyData(e,o)}function mD(t,e,r){let n=r?r.children:void 0,o=(n?n.indexOf(e):1)===0?"th":"td",s=r&&r.type==="table"?r.align:void 0,a=s?s.length:e.children.length,l=-1,c=[];for(;++l<a;){let d=e.children[l],p={},f=s?s[l]:void 0;f&&(p.align=f);let m={type:"element",tagName:o,properties:p,children:[]};d&&(m.children=t.all(d),t.patch(d,m),m=t.applyData(d,m)),c.push(m)}let u={type:"element",tagName:"tr",properties:{},children:t.wrap(c,!0)};return t.patch(e,u),t.applyData(e,u)}function hD(t,e){let r={type:"element",tagName:"td",properties:{},children:t.all(e)};return t.patch(e,r),t.applyData(e,r)}function yD(t){let e=String(t),r=/\r?\n|\r/g,n=r.exec(e),i=0,o=[];for(;n;)o.push(gD(e.slice(i,n.index),i>0,!0),n[0]),i=n.index+n[0].length,n=r.exec(e);return o.push(gD(e.slice(i),i>0,!1)),o.join("")}function gD(t,e,r){let n=0,i=t.length;if(e){let o=t.codePointAt(n);for(;o===9||o===32;)n++,o=t.codePointAt(n)}if(r){let o=t.codePointAt(i-1);for(;o===9||o===32;)i--,o=t.codePointAt(i-1)}return i>n?t.slice(n,i):""}function vD(t,e){let r={type:"text",value:yD(String(e.value))};return t.patch(e,r),t.applyData(e,r)}function _D(t,e){let r={type:"element",tagName:"hr",properties:{},children:[]};return t.patch(e,r),t.applyData(e,r)}var bD={blockquote:Gj,break:Hj,code:Xj,delete:Kj,emphasis:Jj,footnoteReference:Yj,heading:Qj,html:eD,imageReference:tD,image:rD,inlineCode:nD,linkReference:iD,link:oD,listItem:sD,list:lD,paragraph:cD,root:uD,strong:dD,table:pD,tableCell:hD,tableRow:mD,text:vD,thematicBreak:_D,toml:Ov,yaml:Ov,definition:Ov,footnoteDefinition:Ov};function Ov(){}function yY(t,e){let r=[{type:"text",value:"\u21A9"}];return e>1&&r.push({type:"element",tagName:"sup",properties:{},children:[{type:"text",value:String(e)}]}),r}function vY(t,e){return"Back to reference "+(t+1)+(e>1?"-"+e:"")}function wD(t){let e=typeof t.options.clobberPrefix=="string"?t.options.clobberPrefix:"user-content-",r=t.options.footnoteBackContent||yY,n=t.options.footnoteBackLabel||vY,i=t.options.footnoteLabel||"Footnotes",o=t.options.footnoteLabelTagName||"h2",s=t.options.footnoteLabelProperties||{className:["sr-only"]},a=[],l=-1;for(;++l<t.footnoteOrder.length;){let c=t.footnoteById.get(t.footnoteOrder[l]);if(!c)continue;let u=t.all(c),d=String(c.identifier).toUpperCase(),p=Gn(d.toLowerCase()),f=0,m=[],h=t.footnoteCounts.get(d);for(;h!==void 0&&++f<=h;){m.length>0&&m.push({type:"text",value:" "});let _=typeof r=="string"?r:r(l,f);typeof _=="string"&&(_={type:"text",value:_}),m.push({type:"element",tagName:"a",properties:{href:"#"+e+"fnref-"+p+(f>1?"-"+f:""),dataFootnoteBackref:"",ariaLabel:typeof n=="string"?n:n(l,f),className:["data-footnote-backref"]},children:Array.isArray(_)?_:[_]})}let y=u[u.length-1];if(y&&y.type==="element"&&y.tagName==="p"){let _=y.children[y.children.length-1];_&&_.type==="text"?_.value+=" ":y.children.push({type:"text",value:" "}),y.children.push(...m)}else u.push(...m);let g={type:"element",tagName:"li",properties:{id:e+"fn-"+p},children:t.wrap(u,!0)};t.patch(c,g),a.push(g)}if(a.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:o,properties:{...qi(s),id:"footnote-label"},children:[{type:"text",value:i}]},{type:"text",value:`
|
|
366
|
+
`},{type:"element",tagName:"ol",properties:{},children:t.wrap(a,!0)},{type:"text",value:`
|
|
367
|
+
`}]}}var YI={}.hasOwnProperty,_Y={};function $D(t,e){let r=e||_Y,n=new Map,i=new Map,o=new Map,s={...bD,...r.handlers},a={all:c,applyData:wY,definitionById:n,footnoteById:i,footnoteCounts:o,footnoteOrder:[],handlers:s,one:l,options:r,patch:bY,wrap:$Y};return Xp(t,function(u){if(u.type==="definition"||u.type==="footnoteDefinition"){let d=u.type==="definition"?n:i,p=String(u.identifier).toUpperCase();d.has(p)||d.set(p,u)}}),a;function l(u,d){let p=u.type,f=a.handlers[p];if(YI.call(a.handlers,p)&&f)return f(a,u,d);if(a.options.passThrough&&a.options.passThrough.includes(p)){if("children"in u){let{children:h,...y}=u,g=qi(y);return g.children=a.all(u),g}return qi(u)}return(a.options.unknownHandler||xY)(a,u,d)}function c(u){let d=[];if("children"in u){let p=u.children,f=-1;for(;++f<p.length;){let m=a.one(p[f],u);if(m){if(f&&p[f-1].type==="break"&&(!Array.isArray(m)&&m.type==="text"&&(m.value=xD(m.value)),!Array.isArray(m)&&m.type==="element")){let h=m.children[0];h&&h.type==="text"&&(h.value=xD(h.value))}Array.isArray(m)?d.push(...m):d.push(m)}}}return d}}function bY(t,e){t.position&&(e.position=JI(t))}function wY(t,e){let r=e;if(t&&t.data){let n=t.data.hName,i=t.data.hChildren,o=t.data.hProperties;if(typeof n=="string")if(r.type==="element")r.tagName=n;else{let s="children"in r?r.children:[r];r={type:"element",tagName:n,properties:{},children:s}}r.type==="element"&&o&&Object.assign(r.properties,qi(o)),"children"in r&&r.children&&i!==null&&i!==void 0&&(r.children=i)}return r}function xY(t,e){let r=e.data||{},n="value"in e&&!(YI.call(r,"hProperties")||YI.call(r,"hChildren"))?{type:"text",value:e.value}:{type:"element",tagName:"div",properties:{},children:t.all(e)};return t.patch(e,n),t.applyData(e,n)}function $Y(t,e){let r=[],n=-1;for(e&&r.push({type:"text",value:`
|
|
368
|
+
`});++n<t.length;)n&&r.push({type:"text",value:`
|
|
369
|
+
`}),r.push(t[n]);return e&&t.length>0&&r.push({type:"text",value:`
|
|
370
|
+
`}),r}function xD(t){let e=0,r=t.charCodeAt(e);for(;r===9||r===32;)e++,r=t.charCodeAt(e);return t.slice(e)}function Rv(t,e){let r=$D(t,e),n=r.one(t,void 0),i=wD(r),o=Array.isArray(n)?{type:"root",children:n}:n||{type:"root",children:[]};return i&&("children"in o,o.children.push({type:"text",value:`
|
|
371
|
+
`},i)),o}function um(t,e){return t&&"run"in t?async function(r,n){let i=Rv(r,{file:n,...e});await t.run(i,n)}:function(r,n){return Rv(r,{file:n,...e||t})}}function QI(t){if(t)throw t}var Dv=r_(CD(),1);function dm(t){if(typeof t!="object"||t===null)return!1;let e=Object.getPrototypeOf(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)}function eE(){let t=[],e={run:r,use:n};return e;function r(...i){let o=-1,s=i.pop();if(typeof s!="function")throw new TypeError("Expected function as last argument, not "+s);a(null,...i);function a(l,...c){let u=t[++o],d=-1;if(l){s(l);return}for(;++d<i.length;)(c[d]===null||c[d]===void 0)&&(c[d]=i[d]);i=c,u?ND(u,a)(...c):s(null,...c)}}function n(i){if(typeof i!="function")throw new TypeError("Expected `middelware` to be a function, not "+i);return t.push(i),e}}function ND(t,e){let r;return n;function n(...s){let a=t.length>s.length,l;a&&s.push(i);try{l=t.apply(this,s)}catch(c){let u=c;if(a&&r)throw u;return i(u)}a||(l&&l.then&&typeof l.then=="function"?l.then(o,i):l instanceof Error?i(l):o(l))}function i(s,...a){r||(r=!0,e(s,...a))}function o(s){i(null,s)}}var ar=class extends Error{constructor(e,r,n){super(),typeof r=="string"&&(n=r,r=void 0);let i="",o={},s=!1;if(r&&("line"in r&&"column"in r?o={place:r}:"start"in r&&"end"in r?o={place:r}:"type"in r?o={ancestors:[r],place:r.position}:o={...r}),typeof e=="string"?i=e:!o.cause&&e&&(s=!0,i=e.message,o.cause=e),!o.ruleId&&!o.source&&typeof n=="string"){let l=n.indexOf(":");l===-1?o.ruleId=n:(o.source=n.slice(0,l),o.ruleId=n.slice(l+1))}if(!o.place&&o.ancestors&&o.ancestors){let l=o.ancestors[o.ancestors.length-1];l&&(o.place=l.position)}let a=o.place&&"start"in o.place?o.place.start:o.place;this.ancestors=o.ancestors||void 0,this.cause=o.cause||void 0,this.column=a?a.column:void 0,this.fatal=void 0,this.file,this.message=i,this.line=a?a.line:void 0,this.name=Rs(o.place)||"1:1",this.place=o.place||void 0,this.reason=this.message,this.ruleId=o.ruleId||void 0,this.source=o.source||void 0,this.stack=s&&o.cause&&typeof o.cause.stack=="string"?o.cause.stack:"",this.actual,this.expected,this.note,this.url}};ar.prototype.file="";ar.prototype.name="";ar.prototype.reason="";ar.prototype.message="";ar.prototype.stack="";ar.prototype.column=void 0;ar.prototype.line=void 0;ar.prototype.ancestors=void 0;ar.prototype.cause=void 0;ar.prototype.fatal=void 0;ar.prototype.place=void 0;ar.prototype.ruleId=void 0;ar.prototype.source=void 0;var yi={basename:kY,dirname:SY,extname:IY,join:EY,sep:"/"};function kY(t,e){if(e!==void 0&&typeof e!="string")throw new TypeError('"ext" argument must be a string');fm(t);let r=0,n=-1,i=t.length,o;if(e===void 0||e.length===0||e.length>t.length){for(;i--;)if(t.codePointAt(i)===47){if(o){r=i+1;break}}else n<0&&(o=!0,n=i+1);return n<0?"":t.slice(r,n)}if(e===t)return"";let s=-1,a=e.length-1;for(;i--;)if(t.codePointAt(i)===47){if(o){r=i+1;break}}else s<0&&(o=!0,s=i+1),a>-1&&(t.codePointAt(i)===e.codePointAt(a--)?a<0&&(n=i):(a=-1,n=s));return r===n?n=s:n<0&&(n=t.length),t.slice(r,n)}function SY(t){if(fm(t),t.length===0)return".";let e=-1,r=t.length,n;for(;--r;)if(t.codePointAt(r)===47){if(n){e=r;break}}else n||(n=!0);return e<0?t.codePointAt(0)===47?"/":".":e===1&&t.codePointAt(0)===47?"//":t.slice(0,e)}function IY(t){fm(t);let e=t.length,r=-1,n=0,i=-1,o=0,s;for(;e--;){let a=t.codePointAt(e);if(a===47){if(s){n=e+1;break}continue}r<0&&(s=!0,r=e+1),a===46?i<0?i=e:o!==1&&(o=1):i>-1&&(o=-1)}return i<0||r<0||o===0||o===1&&i===r-1&&i===n+1?"":t.slice(i,r)}function EY(...t){let e=-1,r;for(;++e<t.length;)fm(t[e]),t[e]&&(r=r===void 0?t[e]:r+"/"+t[e]);return r===void 0?".":PY(r)}function PY(t){fm(t);let e=t.codePointAt(0)===47,r=TY(t,!e);return r.length===0&&!e&&(r="."),r.length>0&&t.codePointAt(t.length-1)===47&&(r+="/"),e?"/"+r:r}function TY(t,e){let r="",n=0,i=-1,o=0,s=-1,a,l;for(;++s<=t.length;){if(s<t.length)a=t.codePointAt(s);else{if(a===47)break;a=47}if(a===47){if(!(i===s-1||o===1))if(i!==s-1&&o===2){if(r.length<2||n!==2||r.codePointAt(r.length-1)!==46||r.codePointAt(r.length-2)!==46){if(r.length>2){if(l=r.lastIndexOf("/"),l!==r.length-1){l<0?(r="",n=0):(r=r.slice(0,l),n=r.length-1-r.lastIndexOf("/")),i=s,o=0;continue}}else if(r.length>0){r="",n=0,i=s,o=0;continue}}e&&(r=r.length>0?r+"/..":"..",n=2)}else r.length>0?r+="/"+t.slice(i+1,s):r=t.slice(i+1,s),n=s-i-1;i=s,o=0}else a===46&&o>-1?o++:o=-1}return r}function fm(t){if(typeof t!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(t))}var OD={cwd:AY};function AY(){return"/"}function Lu(t){return!!(t!==null&&typeof t=="object"&&"href"in t&&t.href&&"protocol"in t&&t.protocol&&t.auth===void 0)}function RD(t){if(typeof t=="string")t=new URL(t);else if(!Lu(t)){let e=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+t+"`");throw e.code="ERR_INVALID_ARG_TYPE",e}if(t.protocol!=="file:"){let e=new TypeError("The URL must be of scheme file");throw e.code="ERR_INVALID_URL_SCHEME",e}return zY(t)}function zY(t){if(t.hostname!==""){let n=new TypeError('File URL host must be "localhost" or empty on darwin');throw n.code="ERR_INVALID_FILE_URL_HOST",n}let e=t.pathname,r=-1;for(;++r<e.length;)if(e.codePointAt(r)===37&&e.codePointAt(r+1)===50){let n=e.codePointAt(r+2);if(n===70||n===102){let i=new TypeError("File URL path must not include encoded / characters");throw i.code="ERR_INVALID_FILE_URL_PATH",i}}return decodeURIComponent(e)}var tE=["history","path","basename","stem","extname","dirname"],pm=class{constructor(e){let r;e?Lu(e)?r={path:e}:typeof e=="string"||CY(e)?r={value:e}:r=e:r={},this.cwd=OD.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let n=-1;for(;++n<tE.length;){let o=tE[n];o in r&&r[o]!==void 0&&r[o]!==null&&(this[o]=o==="history"?[...r[o]]:r[o])}let i;for(i in r)tE.includes(i)||(this[i]=r[i])}get basename(){return typeof this.path=="string"?yi.basename(this.path):void 0}set basename(e){nE(e,"basename"),rE(e,"basename"),this.path=yi.join(this.dirname||"",e)}get dirname(){return typeof this.path=="string"?yi.dirname(this.path):void 0}set dirname(e){MD(this.basename,"dirname"),this.path=yi.join(e||"",this.basename)}get extname(){return typeof this.path=="string"?yi.extname(this.path):void 0}set extname(e){if(rE(e,"extname"),MD(this.dirname,"extname"),e){if(e.codePointAt(0)!==46)throw new Error("`extname` must start with `.`");if(e.includes(".",1))throw new Error("`extname` cannot contain multiple dots")}this.path=yi.join(this.dirname,this.stem+(e||""))}get path(){return this.history[this.history.length-1]}set path(e){Lu(e)&&(e=RD(e)),nE(e,"path"),this.path!==e&&this.history.push(e)}get stem(){return typeof this.path=="string"?yi.basename(this.path,this.extname):void 0}set stem(e){nE(e,"stem"),rE(e,"stem"),this.path=yi.join(this.dirname||"",e+(this.extname||""))}fail(e,r,n){let i=this.message(e,r,n);throw i.fatal=!0,i}info(e,r,n){let i=this.message(e,r,n);return i.fatal=void 0,i}message(e,r,n){let i=new ar(e,r,n);return this.path&&(i.name=this.path+":"+i.name,i.file=this.path),i.fatal=!1,this.messages.push(i),i}toString(e){return this.value===void 0?"":typeof this.value=="string"?this.value:new TextDecoder(e||void 0).decode(this.value)}};function rE(t,e){if(t&&t.includes(yi.sep))throw new Error("`"+e+"` cannot be a path: did not expect `"+yi.sep+"`")}function nE(t,e){if(!t)throw new Error("`"+e+"` cannot be empty")}function MD(t,e){if(!t)throw new Error("Setting `"+e+"` requires `path` to be set too")}function CY(t){return!!(t&&typeof t=="object"&&"byteLength"in t&&"byteOffset"in t)}var jD=function(t){let n=this.constructor.prototype,i=n[t],o=function(){return i.apply(o,arguments)};Object.setPrototypeOf(o,n);let s=Object.getOwnPropertyNames(i);for(let a of s){let l=Object.getOwnPropertyDescriptor(i,a);l&&Object.defineProperty(o,a,l)}return o};var NY={}.hasOwnProperty,aE=class t extends jD{constructor(){super("copy"),this.Compiler=void 0,this.Parser=void 0,this.attachers=[],this.compiler=void 0,this.freezeIndex=-1,this.frozen=void 0,this.namespace={},this.parser=void 0,this.transformers=eE()}copy(){let e=new t,r=-1;for(;++r<this.attachers.length;){let n=this.attachers[r];e.use(...n)}return e.data((0,Dv.default)(!0,{},this.namespace)),e}data(e,r){return typeof e=="string"?arguments.length===2?(sE("data",this.frozen),this.namespace[e]=r,this):NY.call(this.namespace,e)&&this.namespace[e]||void 0:e?(sE("data",this.frozen),this.namespace=e,this):this.namespace}freeze(){if(this.frozen)return this;let e=this;for(;++this.freezeIndex<this.attachers.length;){let[r,...n]=this.attachers[this.freezeIndex];if(n[0]===!1)continue;n[0]===!0&&(n[0]=void 0);let i=r.call(e,...n);typeof i=="function"&&this.transformers.use(i)}return this.frozen=!0,this.freezeIndex=Number.POSITIVE_INFINITY,this}parse(e){this.freeze();let r=jv(e),n=this.parser||this.Parser;return iE("parse",n),n(String(r),r)}process(e,r){let n=this;return this.freeze(),iE("process",this.parser||this.Parser),oE("process",this.compiler||this.Compiler),r?i(void 0,r):new Promise(i);function i(o,s){let a=jv(e),l=n.parse(a);n.run(l,a,function(u,d,p){if(u||!d||!p)return c(u);let f=d,m=n.stringify(f,p);RY(m)?p.value=m:p.result=m,c(u,p)});function c(u,d){u||!d?s(u):o?o(d):r(void 0,d)}}}processSync(e){let r=!1,n;return this.freeze(),iE("processSync",this.parser||this.Parser),oE("processSync",this.compiler||this.Compiler),this.process(e,i),LD("processSync","process",r),n;function i(o,s){r=!0,QI(o),n=s}}run(e,r,n){DD(e),this.freeze();let i=this.transformers;return!n&&typeof r=="function"&&(n=r,r=void 0),n?o(void 0,n):new Promise(o);function o(s,a){let l=jv(r);i.run(e,l,c);function c(u,d,p){let f=d||e;u?a(u):s?s(f):n(void 0,f,p)}}}runSync(e,r){let n=!1,i;return this.run(e,r,o),LD("runSync","run",n),i;function o(s,a){QI(s),i=a,n=!0}}stringify(e,r){this.freeze();let n=jv(r),i=this.compiler||this.Compiler;return oE("stringify",i),DD(e),i(e,n)}use(e,...r){let n=this.attachers,i=this.namespace;if(sE("use",this.frozen),e!=null)if(typeof e=="function")l(e,r);else if(typeof e=="object")Array.isArray(e)?a(e):s(e);else throw new TypeError("Expected usable value, not `"+e+"`");return this;function o(c){if(typeof c=="function")l(c,[]);else if(typeof c=="object")if(Array.isArray(c)){let[u,...d]=c;l(u,d)}else s(c);else throw new TypeError("Expected usable value, not `"+c+"`")}function s(c){if(!("plugins"in c)&&!("settings"in c))throw new Error("Expected usable value but received an empty preset, which is probably a mistake: presets typically come with `plugins` and sometimes with `settings`, but this has neither");a(c.plugins),c.settings&&(i.settings=(0,Dv.default)(!0,i.settings,c.settings))}function a(c){let u=-1;if(c!=null)if(Array.isArray(c))for(;++u<c.length;){let d=c[u];o(d)}else throw new TypeError("Expected a list of plugins, not `"+c+"`")}function l(c,u){let d=-1,p=-1;for(;++d<n.length;)if(n[d][0]===c){p=d;break}if(p===-1)n.push([c,...u]);else if(u.length>0){let[f,...m]=u,h=n[p][1];dm(h)&&dm(f)&&(f=(0,Dv.default)(!0,h,f)),n[p]=[c,f,...m]}}}},Lv=new aE().freeze();function iE(t,e){if(typeof e!="function")throw new TypeError("Cannot `"+t+"` without `parser`")}function oE(t,e){if(typeof e!="function")throw new TypeError("Cannot `"+t+"` without `compiler`")}function sE(t,e){if(e)throw new Error("Cannot call `"+t+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function DD(t){if(!dm(t)||typeof t.type!="string")throw new TypeError("Expected node, got `"+t+"`")}function LD(t,e,r){if(!r)throw new Error("`"+t+"` finished async. Use `"+e+"` instead")}function jv(t){return OY(t)?t:new pm(t)}function OY(t){return!!(t&&typeof t=="object"&&"message"in t&&"messages"in t)}function RY(t){return typeof t=="string"||MY(t)}function MY(t){return!!(t&&typeof t=="object"&&"byteLength"in t&&"byteOffset"in t)}var mm=class extends kn{constructor(){super(...arguments);this.html=()=>`
|
|
217
372
|
|
|
218
373
|
<!-- Styling -->
|
|
219
374
|
<style>
|
|
@@ -296,11 +451,11 @@ ${s}`,cannotRemove:o.isContext,sortOrder:101,disabled:typeof o.disabled=="functi
|
|
|
296
451
|
<div id='llm-selector-list'></div>
|
|
297
452
|
</div>
|
|
298
453
|
|
|
299
|
-
`}onUpdate(){this.child("llm-selector-panel").className=this.attr.open?"open":"closed";let
|
|
300
|
-
<div class='llm-selector-item-icon' style="background-image: url('${
|
|
301
|
-
<div class='llm-selector-item-name'>${
|
|
302
|
-
<div class='llm-selector-item-provider'>${
|
|
303
|
-
`,o.addEventListener("click",s=>{this.dispatchEvent(new CustomEvent("select",{detail:i.id}))}),e.appendChild(o)}}};_.observedAttributes=["open"];var D=new p("ONNXModel"),M=class u{constructor(t){this.stateTensors={};this.constantTensors={};this._runActive=!1;this.ignoreIfBusy=!1;this.session=t,D.debug(`Model input parameters: ${t.inputNames.join(", ")}`),D.debug(`Model output parameters: ${t.outputNames.join(", ")}`)}static isSupported(){return!!u.lib}static async load(t){if(!u.lib)throw new Error("ONNX runtime not loaded, please set the runtime loader. Example: ONNXModel.lib = () => import('onnxruntime-web')");this.onnx||(D.debug("Loading ONNX runtime"),this.onnx=await u.lib()),D.debug(`Loading model: ${t}`);let e=await this.onnx.InferenceSession.create(t);return new u(e)}makeTensor(t,e,i=0){let o=1;for(let n of e)o*=n;let s;if(t=="float32")s=new u.onnx.Tensor(new Float32Array(o),e);else if(t=="int8")s=new u.onnx.Tensor(new Int8Array(o),e);else if(t=="int16")s=new u.onnx.Tensor(new Int16Array(o),e);else if(t=="int32")s=new u.onnx.Tensor(new Int32Array(o),e);else if(t=="int64")s=new u.onnx.Tensor(new BigInt64Array(o),e);else if(t=="uint8")s=new u.onnx.Tensor(new Uint8Array(o),e);else if(t=="uint16")s=new u.onnx.Tensor(new Uint16Array(o),e);else if(t=="uint32")s=new u.onnx.Tensor(new Uint32Array(o),e);else if(t=="uint64")s=new u.onnx.Tensor(new BigUint64Array(o),e);else throw new Error(`Invalid type: ${t}`);return i!==0&&(t=="int64"||t=="uint64")?s.data.fill(BigInt(i)):i!==0&&s.data.fill(i),s}registerConstant(t,e){if(!this.session.inputNames.includes(t))throw new Error(`Model does not have an input named: ${t}`);return this.constantTensors[t]=e,e}makeConstant(t,e,i,o=0){return this.registerConstant(t,this.makeTensor(e,i,o))}registerState(t,e,i){if(e||(e=t),!this.session.inputNames.includes(t))throw new Error(`Model does not have an input named: ${t}`);if(!this.session.outputNames.includes(e))throw new Error(`Model does not have an output named: ${e}`);return this.stateTensors[t]={outputName:e,tensor:i},i}makeState(t,e,i,o,s=0){return this.registerState(t,e,this.makeTensor(i,o,s))}async run(t={}){if(this._runActive&&this.ignoreIfBusy)return D.debug("Ignoring run request because a previous run is still active");if(this._runActive)throw new Error("A previous run is still active");this._runActive=!0;for(let e in this.stateTensors)t[e]=this.stateTensors[e].tensor;for(let e in this.constantTensors)t[e]=this.constantTensors[e];try{let e=await this.session.run(t);for(let i in this.stateTensors){let o=e[this.stateTensors[i].outputName];this.stateTensors[i].tensor=o}return e}finally{this._runActive=!1}}resetState(){D.debug("Resetting state tensors");for(let t in this.stateTensors)this.stateTensors[t].tensor.data.fill(0)}};var Oe="data:application/javascript;base64,dmFyIGM9Y2xhc3N7Y29uc3RydWN0b3IoaSx0KXt0aGlzLm91dHB1dEJ1ZmZlclNpemU9MDt0aGlzLnBhcnRpYWxCdWZmZXJzPVtdO3RoaXMucGFydGlhbEJ1ZmZlck9mZnNldD0wO2lmKCFpKXRocm93IG5ldyBFcnJvcihgSW52YWxpZCBhcnJheSBjbGFzczogJHtpfWApO2lmKCF0fHx0PD0wKXRocm93IG5ldyBFcnJvcihgSW52YWxpZCBvdXRwdXQgYnVmZmVyIHNpemU6ICR7dH1gKTt0aGlzLkFycmF5Q2xhc3M9aSx0aGlzLm91dHB1dEJ1ZmZlclNpemU9dH1nZXQgcXVldWVkU2l6ZSgpe3JldHVybiB0aGlzLnBhcnRpYWxCdWZmZXJzLnJlZHVjZSgoaSx0KT0+aSt0Lmxlbmd0aCwwKX1mZWVkKGkpe3RoaXMucGFydGlhbEJ1ZmZlcnMucHVzaChpKX1nZXQgY2FuRHJhaW4oKXtyZXR1cm4gdGhpcy5wYXJ0aWFsQnVmZmVycy5yZWR1Y2UoKHQscik9PnQrci5sZW5ndGgsMCktdGhpcy5wYXJ0aWFsQnVmZmVyT2Zmc2V0Pj10aGlzLm91dHB1dEJ1ZmZlclNpemV9ZHJhaW4oKXtpZighdGhpcy5jYW5EcmFpbilyZXR1cm4gbnVsbDtsZXQgaT10aGlzLkFycmF5Q2xhc3MsdD1uZXcgaSh0aGlzLm91dHB1dEJ1ZmZlclNpemUpLHI9MDtmb3IoO3IhPXQubGVuZ3RoOyl7aWYocj50Lmxlbmd0aCl0aHJvdyBuZXcgRXJyb3IoYEJ1ZmZlciBvdmVyZmxvdzogJHtyfSA+ICR7dC5sZW5ndGh9YCk7bGV0IGE9dC5sZW5ndGgtcixzPXRoaXMucGFydGlhbEJ1ZmZlcnNbMF0sZj1zLmxlbmd0aC10aGlzLnBhcnRpYWxCdWZmZXJPZmZzZXQ7ZjxhPyh0LnNldChzLnN1YmFycmF5KHRoaXMucGFydGlhbEJ1ZmZlck9mZnNldCkscikscis9Zix0aGlzLnBhcnRpYWxCdWZmZXJzLnNoaWZ0KCksdGhpcy5wYXJ0aWFsQnVmZmVyT2Zmc2V0PTApOih0LnNldChzLnN1YmFycmF5KHRoaXMucGFydGlhbEJ1ZmZlck9mZnNldCx0aGlzLnBhcnRpYWxCdWZmZXJPZmZzZXQrYSkscikscis9YSx0aGlzLnBhcnRpYWxCdWZmZXJPZmZzZXQrPWEpfXJldHVybiB0fXBhZCgpe2xldCBpPXRoaXMucXVldWVkU2l6ZSV0aGlzLm91dHB1dEJ1ZmZlclNpemU7aWYoaT09MClyZXR1cm47bGV0IHQ9dGhpcy5BcnJheUNsYXNzLHI9bmV3IHQoaSk7dGhpcy5mZWVkKHIpfX07dmFyIGQ9Y2xhc3N7Y29uc3RydWN0b3IoaSx0LHIsYSl7aWYoIWl8fCF0fHwhcil0aHJvdyBuZXcgRXJyb3IoIkludmFsaWQgc2V0dGluZ3Mgc3BlY2lmaWVkIGZvciB0aGUgcmVzYW1wbGVyLiIpO3RoaXMucmVzYW1wbGVyPW51bGwsdGhpcy5mcm9tU2FtcGxlUmF0ZT1pLHRoaXMudG9TYW1wbGVSYXRlPXQsdGhpcy5jaGFubmVscz1yfHwwLHRoaXMuaW5wdXRCdWZmZXJTaXplPWEsdGhpcy5pbml0aWFsaXplKCl9aW5pdGlhbGl6ZSgpe3RoaXMuZnJvbVNhbXBsZVJhdGU9PXRoaXMudG9TYW1wbGVSYXRlPyh0aGlzLnJlc2FtcGxlcj1pPT5pLHRoaXMucmF0aW9XZWlnaHQ9MSk6KHRoaXMuZnJvbVNhbXBsZVJhdGU8dGhpcy50b1NhbXBsZVJhdGU/KHRoaXMubGluZWFySW50ZXJwb2xhdGlvbigpLHRoaXMubGFzdFdlaWdodD0xKToodGhpcy5tdWx0aVRhcCgpLHRoaXMudGFpbEV4aXN0cz0hMSx0aGlzLmxhc3RXZWlnaHQ9MCksdGhpcy5pbml0aWFsaXplQnVmZmVycygpLHRoaXMucmF0aW9XZWlnaHQ9dGhpcy5mcm9tU2FtcGxlUmF0ZS90aGlzLnRvU2FtcGxlUmF0ZSl9YnVmZmVyU2xpY2UoaSl7dHJ5e3JldHVybiB0aGlzLm91dHB1dEJ1ZmZlci5zdWJhcnJheSgwLGkpfWNhdGNoe3RyeXtyZXR1cm4gdGhpcy5vdXRwdXRCdWZmZXIubGVuZ3RoPWksdGhpcy5vdXRwdXRCdWZmZXJ9Y2F0Y2h7cmV0dXJuIHRoaXMub3V0cHV0QnVmZmVyLnNsaWNlKDAsaSl9fX1pbml0aWFsaXplQnVmZmVycygpe3RoaXMub3V0cHV0QnVmZmVyU2l6ZT1NYXRoLmNlaWwodGhpcy5pbnB1dEJ1ZmZlclNpemUqdGhpcy50b1NhbXBsZVJhdGUvdGhpcy5mcm9tU2FtcGxlUmF0ZS90aGlzLmNoYW5uZWxzKjEuMDAwMDAwNDc2ODM3MTU4MikrdGhpcy5jaGFubmVscyt0aGlzLmNoYW5uZWxzO3RyeXt0aGlzLm91dHB1dEJ1ZmZlcj1uZXcgRmxvYXQzMkFycmF5KHRoaXMub3V0cHV0QnVmZmVyU2l6ZSksdGhpcy5sYXN0T3V0cHV0PW5ldyBGbG9hdDMyQXJyYXkodGhpcy5jaGFubmVscyl9Y2F0Y2h7dGhpcy5vdXRwdXRCdWZmZXI9W10sdGhpcy5sYXN0T3V0cHV0PVtdfX1saW5lYXJJbnRlcnBvbGF0aW9uKCl7dGhpcy5yZXNhbXBsZXI9aT0+e2xldCB0PWkubGVuZ3RoLHI9dGhpcy5jaGFubmVscyxhLHMsZixoLGUsbix1LG8sbDtpZih0JXIhPT0wKXRocm93IG5ldyBFcnJvcigiQnVmZmVyIHdhcyBvZiBpbmNvcnJlY3Qgc2FtcGxlIGxlbmd0aC4iKTtpZih0PD0wKXJldHVybltdO2ZvcihhPXRoaXMub3V0cHV0QnVmZmVyU2l6ZSxzPXRoaXMucmF0aW9XZWlnaHQsZj10aGlzLmxhc3RXZWlnaHQsaD0wLGU9MCxuPTAsdT0wLG89dGhpcy5vdXRwdXRCdWZmZXI7ZjwxO2YrPXMpZm9yKGU9ZiUxLGg9MS1lLHRoaXMubGFzdFdlaWdodD1mJTEsbD0wO2w8dGhpcy5jaGFubmVsczsrK2wpb1t1KytdPXRoaXMubGFzdE91dHB1dFtsXSpoK2lbbF0qZTtmb3IoZi09MSx0LT1yLG49TWF0aC5mbG9vcihmKSpyO3U8YSYmbjx0Oyl7Zm9yKGU9ZiUxLGg9MS1lLGw9MDtsPHRoaXMuY2hhbm5lbHM7KytsKW9bdSsrXT1pW24rKGw+MD9sOjApXSpoK2lbbisocitsKV0qZTtmKz1zLG49TWF0aC5mbG9vcihmKSpyfWZvcihsPTA7bDxyOysrbCl0aGlzLmxhc3RPdXRwdXRbbF09aVtuKytdO3JldHVybiB0aGlzLmJ1ZmZlclNsaWNlKHUpfX1tdWx0aVRhcCgpe3RoaXMucmVzYW1wbGVyPWk9PntsZXQgdD1pLmxlbmd0aCxyLGEscz10aGlzLmNoYW5uZWxzLGYsaCxlLG4sdSxvLGwsbSxnO2lmKHQlcyE9PTApdGhyb3cgbmV3IEVycm9yKCJCdWZmZXIgd2FzIG9mIGluY29ycmVjdCBzYW1wbGUgbGVuZ3RoLiIpO2lmKHQ8PTApcmV0dXJuW107Zm9yKHI9dGhpcy5vdXRwdXRCdWZmZXJTaXplLGE9W10sZj10aGlzLnJhdGlvV2VpZ2h0LGg9MCxuPTAsdT0wLG89IXRoaXMudGFpbEV4aXN0cyx0aGlzLnRhaWxFeGlzdHM9ITEsbD10aGlzLm91dHB1dEJ1ZmZlcixtPTAsZz0wLGU9MDtlPHM7KytlKWFbZV09MDtkb3tpZihvKWZvcihoPWYsZT0wO2U8czsrK2UpYVtlXT0wO2Vsc2V7Zm9yKGg9dGhpcy5sYXN0V2VpZ2h0LGU9MDtlPHM7KytlKWFbZV09dGhpcy5sYXN0T3V0cHV0W2VdO289ITB9Zm9yKDtoPjAmJm48dDspaWYodT0xK24tZyxoPj11KXtmb3IoZT0wO2U8czsrK2UpYVtlXSs9aVtuKytdKnU7Zz1uLGgtPXV9ZWxzZXtmb3IoZT0wO2U8czsrK2UpYVtlXSs9aVtuKyhlPjA/ZTowKV0qaDtnKz1oLGg9MDticmVha31pZihoPT09MClmb3IoZT0wO2U8czsrK2UpbFttKytdPWFbZV0vZjtlbHNle2Zvcih0aGlzLmxhc3RXZWlnaHQ9aCxlPTA7ZTxzOysrZSl0aGlzLmxhc3RPdXRwdXRbZV09YVtlXTt0aGlzLnRhaWxFeGlzdHM9ITA7YnJlYWt9fXdoaWxlKG48dCYmbTxyKTtyZXR1cm4gdGhpcy5idWZmZXJTbGljZShtKX19cmVzYW1wbGUoaSl7cmV0dXJuIHRoaXMuZnJvbVNhbXBsZVJhdGU9PXRoaXMudG9TYW1wbGVSYXRlP3RoaXMucmF0aW9XZWlnaHQ9MToodGhpcy5mcm9tU2FtcGxlUmF0ZTx0aGlzLnRvU2FtcGxlUmF0ZT90aGlzLmxhc3RXZWlnaHQ9MToodGhpcy50YWlsRXhpc3RzPSExLHRoaXMubGFzdFdlaWdodD0wKSx0aGlzLmluaXRpYWxpemVCdWZmZXJzKCksdGhpcy5yYXRpb1dlaWdodD10aGlzLmZyb21TYW1wbGVSYXRlL3RoaXMudG9TYW1wbGVSYXRlKSx0aGlzLnJlc2FtcGxlcihpKX19O2Z1bmN0aW9uIFMocCl7bGV0IGk9cC5sZW5ndGgsdD1uZXcgRmxvYXQzMkFycmF5KGkpO2Zvcig7aS0tOyl7bGV0IHI9cFtpXTt0W2ldPXI+PTMyNzY4Py0oNjU1MzYtcikvMzI3Njg6ci8zMjc2N31yZXR1cm4gdH12YXIgeT0xMDI0KjgsQj1jbGFzcyBleHRlbmRzIEF1ZGlvV29ya2xldFByb2Nlc3Nvcntjb25zdHJ1Y3Rvcih0KXtzdXBlcih0KTt0aGlzLmNodW5rcz1bXTt0aGlzLmNodW5rUG9zaXRpb249MDt0aGlzLmlzRW5kZWQ9ITE7dGhpcy5pc0NhbmNlbGxlZD0hMTt0aGlzLnNhbXBsZVJhdGU9MDt0aGlzLmZvcm1hdD0iaW50MTYiO3RoaXMuYnVmZmVyT2Zmc2V0PTA7dGhpcy5sYXN0UGxheWVkQnVmZmVyU2l6ZT0wO3RoaXMuX2hhc1NlbnRFbmRFdmVudD0hMTt0aGlzLnBvcnQub25tZXNzYWdlPXI9PnRoaXMub25NZXNzYWdlKHIpfW9uTWVzc2FnZSh0KXtpZih0LmRhdGEuYWN0aW9uPT0ic3RhcnQiKXRoaXMuZm9ybWF0PXQuZGF0YS5mb3JtYXQsdGhpcy5zYW1wbGVSYXRlPXQuZGF0YS5pbnB1dFNhbXBsZVJhdGUsdGhpcy5yZXNhbXBsZXI9bmV3IGQodC5kYXRhLmlucHV0U2FtcGxlUmF0ZSx0LmRhdGEub3V0cHV0U2FtcGxlUmF0ZSwxLHkpLHRoaXMuZm9ybWF0PT0iaW50MTYiP3RoaXMuaW5wdXRCdWZmZXI9bmV3IGMoVWludDhBcnJheSx5KjIpOnRoaXMuZm9ybWF0PT0iZmxvYXQzMiImJih0aGlzLmlucHV0QnVmZmVyPW5ldyBjKFVpbnQ4QXJyYXkseSo0KSk7ZWxzZSBpZih0LmRhdGEuYWN0aW9uPT0iZGF0YSIpe2xldCByPW5ldyBVaW50OEFycmF5KHQuZGF0YS5idWZmZXIpO2Zvcih0aGlzLmlucHV0QnVmZmVyLmZlZWQocik7dGhpcy5pbnB1dEJ1ZmZlci5jYW5EcmFpbjspdGhpcy5kcmFpbkJ1ZmZlcigpfWVsc2UgdC5kYXRhLmFjdGlvbj09ImVuZCI/KHRoaXMubGFzdFBsYXllZEJ1ZmZlclNpemUmJnRoaXMuY2h1bmtzLnB1c2gobmV3IEZsb2F0MzJBcnJheSh0aGlzLmxhc3RQbGF5ZWRCdWZmZXJTaXplKjIpKSx0aGlzLmlzRW5kZWQ9ITApOnQuZGF0YS5hY3Rpb249PSJjYW5jZWwiJiYodGhpcy5pc0VuZGVkPSEwLHRoaXMuaXNDYW5jZWxsZWQ9ITApfWRyYWluQnVmZmVyKCl7bGV0IHQ9dGhpcy5pbnB1dEJ1ZmZlci5kcmFpbigpO2lmKCF0KXJldHVybjtsZXQgcjtpZih0aGlzLmZvcm1hdD09ImludDE2Iil7bGV0IHM9bmV3IEludDE2QXJyYXkodC5idWZmZXIsdC5ieXRlT2Zmc2V0LHQuYnl0ZUxlbmd0aC8yKTtyPVMocyl9ZWxzZSBpZih0aGlzLmZvcm1hdD09ImZsb2F0MzIiKXI9bmV3IEZsb2F0MzJBcnJheSh0LmJ1ZmZlcix0LmJ5dGVPZmZzZXQsdC5ieXRlTGVuZ3RoLzQpO2Vsc2UgdGhyb3cgbmV3IEVycm9yKGBJbnZhbGlkIGZvcm1hdDogJHt0aGlzLmZvcm1hdH1gKTtsZXQgYT10aGlzLnJlc2FtcGxlci5yZXNhbXBsZShyKTt0aGlzLmNodW5rcy5wdXNoKGEpfW5leHRGbG9hdCgpe2lmKCF0aGlzLmNodW5rcy5sZW5ndGgpcmV0dXJuIDA7bGV0IHQ9dGhpcy5jaHVua3NbMF1bdGhpcy5jaHVua1Bvc2l0aW9uXTtyZXR1cm4gdGhpcy5jaHVua1Bvc2l0aW9uKyssdGhpcy5jaHVua1Bvc2l0aW9uPHRoaXMuY2h1bmtzWzBdLmxlbmd0aHx8KHRoaXMuY2h1bmtzLnNoaWZ0KCksdGhpcy5jaHVua1Bvc2l0aW9uPTApLHR9cHJvY2Vzcyh0LHIsYSl7aWYodGhpcy5pc0NhbmNlbGxlZClyZXR1cm4hMTtpZih0aGlzLmlzRW5kZWQmJiF0aGlzLmNodW5rcy5sZW5ndGgpcmV0dXJuIHRoaXMuX2hhc1NlbnRFbmRFdmVudHx8KHRoaXMuX2hhc1NlbnRFbmRFdmVudD0hMCx0aGlzLnBvcnQucG9zdE1lc3NhZ2Uoe2FjdGlvbjoiZW5kIn0pKSwhMTtsZXQgcz1yWzBdPy5bMF0/Lmxlbmd0aDtpZighcylyZXR1cm4hMDt0aGlzLmxhc3RQbGF5ZWRCdWZmZXJTaXplPXM7Zm9yKGxldCBmPTA7ZjxzO2YrKyl7bGV0IGg9dGhpcy5uZXh0RmxvYXQoKTtmb3IobGV0IGU9MDtlPHIubGVuZ3RoO2UrKylmb3IobGV0IG49MDtuPHJbZV0ubGVuZ3RoO24rKylyW2VdW25dW2ZdPWh9cmV0dXJuITB9fTtyZWdpc3RlclByb2Nlc3NvcigicGNtLXBsYXllci1ub2RlIixCKTsK";var bt=new p("PCMPlayerNode"),X=class extends AudioWorkletNode{constructor(e,i,o){super(e,"pcm-player-node",{numberOfInputs:0});this.sampleRate=0;this.format="int16";this.isCancelled=!1;if(!i||i<=0)throw new Error(`Invalid sample rate: ${i}`);if(!o||o!="int16"&&o!="float32")throw new Error(`Invalid format: ${o}`);this.sampleRate=i,this.format=o,this.port.onmessage=s=>this.onWorkletMessage(s),this.port.postMessage({action:"start",inputSampleRate:i,outputSampleRate:e.sampleRate,format:o})}static async registerModule(e){await e.audioWorklet.addModule(Oe)}feed(e){this.port.postMessage({action:"data",buffer:e.buffer},[e.buffer])}async play(e){if(this.isCancelled)throw new Error("PCMPlayerNode has already been cancelled.");if(this._playPromise)throw new Error("Already playing a stream");this._playPromise=new Promise(i=>this._playPromiseResolve=i),this.dispatchEvent(new CustomEvent("start",{detail:{player:this,stream:e}}));try{let i=e.getReader();for(;!this.isCancelled;){let{done:o,value:s}=await i.read();if(o||!s)break;this.feed(s)}}catch(i){bt.warn("Stream error:",i),this.dispatchEvent(new CustomEvent("error",{detail:{player:this,stream:e,error:i}}))}this.port.postMessage({action:"end"}),await this._playPromise}onWorkletMessage(e){e.data.action=="end"&&(this._playPromiseResolve?.(),this.dispatchEvent(new CustomEvent("end",{detail:{player:this}})))}stop(){this.isCancelled=!0,this.port.postMessage({action:"cancel"}),this._playPromiseResolve?.()}};var ne=new p("SpeechOutput"),Be=.5,wt=.8,ae=class extends EventTarget{constructor(e){super();this.maxVolumeHeard=0;this.ai=e,this.ai.addEventListener("output",i=>this.onTextOutputFromAI(i)),this.ai.audio?.speechRecognition.addEventListener("speechstart",i=>this.interrupt()),this.ai.knowledgeBase.registerSource(()=>[{id:"system.voice",type:"info",name:"Voice active",isContext:!0,disabled:!1,content:"Text-to-speech is active. The user can hear your voice."}])}onTextOutputFromAI(e){e.detail.isChunk||this.ai?.audio?.speechRecognition.isRunning&&this.speak(e.detail.message)}get volumeLevel(){if(!this.analyserNode||!this.analyserBuffer)return 0;this.analyserNode.getFloatTimeDomainData(this.analyserBuffer);let e=0;for(let o of this.analyserBuffer)e+=o*o;let i=Math.sqrt(e/this.analyserBuffer.length);return i>this.maxVolumeHeard&&(this.maxVolumeHeard=i),this.maxVolumeHeard*=.999,this.maxVolumeHeard<.01&&(this.maxVolumeHeard=.01),Math.min(1,Math.max(0,i/this.maxVolumeHeard))}async speak(e){if(!this.ai?.config?.voice?.providerID)return ne.warn("No voice provider configured");let i=`speech-${vt++}`;await this.ai.audio.beginAccess(i);try{await this._speakWithLock(e)}finally{this.ai.audio.endAccess(i)}}async _speakWithLock(e){let i=new CustomEvent("speechfilter",{detail:{ai:this.ai,message:e}});if(this.dispatchEvent(i),e=i.detail.message,i.defaultPrevented||!e)return;this.interrupt(),this.ai.audio.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=wt);let o=this.ai?._voiceTracker||ne.timer(`${this.ai.config.voice.providerID} voice`);o(`Speak: ${e}`),this.currentPlayerVolume?.disconnect(),this.currentPlayerVolume=this.ai.audio.context.createGain(),this.currentPlayerVolume.connect(this.ai.audio.context.destination),this.analyserNode=this.ai.audio.context.createAnalyser(),this.analyserNode.fftSize=32,this.analyserNode.connect(this.currentPlayerVolume),this.maxVolumeHeard=0,this.analyserBuffer=new Float32Array(this.analyserNode.fftSize);let s=new X(this.ai.audio.context,24e3,"int16");this.currentPlayer=s,s.connect(this.analyserNode),s.addEventListener("end",a=>{let l=a;o(`PCM stream ${l.detail.interrupted?"interrupted":"ended"}`),this.currentPlayer==s&&!l.detail.interrupted&&(this.currentPlayer=void 0,this.onSpeechEnd())});let n;if(this.ai.config.voice.providerID=="openai")n=await fetch("https://api.openai.com/v1/audio/speech",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.ai.config.voice.apiKey}`},body:JSON.stringify({model:"tts-1",input:e,voice:this.ai.config.voice.voiceID,response_format:"pcm"})});else if(this.ai.config.voice.providerID=="elevenlabs")n=await fetch(`https://api.elevenlabs.io/v1/text-to-speech/${this.ai.config.voice.voiceID}?output_format=pcm_24000`,{method:"POST",headers:{"xi-api-key":`${this.ai.config.voice.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({text:e})});else{ne.warn(`Unknown voice provider: ${this.ai.config.voice.providerID}`);return}if(o(`Received response ${n.status} ${n.statusText}`),!n.ok){ne.warn(`Failed to generate voice sample: ${n.status} ${n.statusText}`);return}this.dispatchEvent(new CustomEvent("speechstart",{detail:{ai:this.ai,message:e}})),o("Playing PCM stream"),await s.play(n.body),o("Audio has ended")}get isSpeaking(){return!!this.currentPlayer}async interrupt(){if(!this.currentPlayerVolume)return;let e=this.currentPlayerVolume,i=this.currentPlayer;this.currentPlayerVolume=void 0,this.currentPlayer=void 0,this.ai?.audio?.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=Be);let o=400;e.gain.linearRampToValueAtTime(0,o/1e3),await new Promise(s=>setTimeout(s,o+250)),e.disconnect(),i?.stop(),i?.disconnect()}onSpeechEnd(){this.dispatchEvent(new CustomEvent("speechend",{detail:{ai:this.ai}})),this.ai?.audio?.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=Be)}},vt=1;function re(u,t){let e=t.reduce((l,c)=>l+c.byteLength,0),i=new DataView(new ArrayBuffer(44));i.setUint8(0,82),i.setUint8(1,73),i.setUint8(2,70),i.setUint8(3,70),i.setUint32(4,44+e,!0),i.setUint8(8,87),i.setUint8(9,65),i.setUint8(10,86),i.setUint8(11,69);let o=1,s=32,n=o*s/8,a=u*n;return i.setUint8(12,102),i.setUint8(13,109),i.setUint8(14,116),i.setUint8(15,32),i.setUint32(16,16,!0),i.setUint16(20,3,!0),i.setUint16(22,o,!0),i.setUint32(24,u,!0),i.setUint32(28,a,!0),i.setUint16(32,n,!0),i.setUint16(34,s,!0),i.setUint8(36,100),i.setUint8(37,97),i.setUint8(38,116),i.setUint8(39,97),i.setUint32(40,e,!0),new File([i,...t],"audio.wav",{type:"audio/wav"})}var Ye="data:application/javascript;base64,dmFyIGc9Y2xhc3N7Y29uc3RydWN0b3IoZSx0LGksZil7aWYoIWV8fCF0fHwhaSl0aHJvdyBuZXcgRXJyb3IoIkludmFsaWQgc2V0dGluZ3Mgc3BlY2lmaWVkIGZvciB0aGUgcmVzYW1wbGVyLiIpO3RoaXMucmVzYW1wbGVyPW51bGwsdGhpcy5mcm9tU2FtcGxlUmF0ZT1lLHRoaXMudG9TYW1wbGVSYXRlPXQsdGhpcy5jaGFubmVscz1pfHwwLHRoaXMuaW5wdXRCdWZmZXJTaXplPWYsdGhpcy5pbml0aWFsaXplKCl9aW5pdGlhbGl6ZSgpe3RoaXMuZnJvbVNhbXBsZVJhdGU9PXRoaXMudG9TYW1wbGVSYXRlPyh0aGlzLnJlc2FtcGxlcj1lPT5lLHRoaXMucmF0aW9XZWlnaHQ9MSk6KHRoaXMuZnJvbVNhbXBsZVJhdGU8dGhpcy50b1NhbXBsZVJhdGU/KHRoaXMubGluZWFySW50ZXJwb2xhdGlvbigpLHRoaXMubGFzdFdlaWdodD0xKToodGhpcy5tdWx0aVRhcCgpLHRoaXMudGFpbEV4aXN0cz0hMSx0aGlzLmxhc3RXZWlnaHQ9MCksdGhpcy5pbml0aWFsaXplQnVmZmVycygpLHRoaXMucmF0aW9XZWlnaHQ9dGhpcy5mcm9tU2FtcGxlUmF0ZS90aGlzLnRvU2FtcGxlUmF0ZSl9YnVmZmVyU2xpY2UoZSl7dHJ5e3JldHVybiB0aGlzLm91dHB1dEJ1ZmZlci5zdWJhcnJheSgwLGUpfWNhdGNoe3RyeXtyZXR1cm4gdGhpcy5vdXRwdXRCdWZmZXIubGVuZ3RoPWUsdGhpcy5vdXRwdXRCdWZmZXJ9Y2F0Y2h7cmV0dXJuIHRoaXMub3V0cHV0QnVmZmVyLnNsaWNlKDAsZSl9fX1pbml0aWFsaXplQnVmZmVycygpe3RoaXMub3V0cHV0QnVmZmVyU2l6ZT1NYXRoLmNlaWwodGhpcy5pbnB1dEJ1ZmZlclNpemUqdGhpcy50b1NhbXBsZVJhdGUvdGhpcy5mcm9tU2FtcGxlUmF0ZS90aGlzLmNoYW5uZWxzKjEuMDAwMDAwNDc2ODM3MTU4MikrdGhpcy5jaGFubmVscyt0aGlzLmNoYW5uZWxzO3RyeXt0aGlzLm91dHB1dEJ1ZmZlcj1uZXcgRmxvYXQzMkFycmF5KHRoaXMub3V0cHV0QnVmZmVyU2l6ZSksdGhpcy5sYXN0T3V0cHV0PW5ldyBGbG9hdDMyQXJyYXkodGhpcy5jaGFubmVscyl9Y2F0Y2h7dGhpcy5vdXRwdXRCdWZmZXI9W10sdGhpcy5sYXN0T3V0cHV0PVtdfX1saW5lYXJJbnRlcnBvbGF0aW9uKCl7dGhpcy5yZXNhbXBsZXI9ZT0+e2xldCB0PWUubGVuZ3RoLGk9dGhpcy5jaGFubmVscyxmLGgsYSxzLHIsdSxuLHAsbDtpZih0JWkhPT0wKXRocm93IG5ldyBFcnJvcigiQnVmZmVyIHdhcyBvZiBpbmNvcnJlY3Qgc2FtcGxlIGxlbmd0aC4iKTtpZih0PD0wKXJldHVybltdO2ZvcihmPXRoaXMub3V0cHV0QnVmZmVyU2l6ZSxoPXRoaXMucmF0aW9XZWlnaHQsYT10aGlzLmxhc3RXZWlnaHQscz0wLHI9MCx1PTAsbj0wLHA9dGhpcy5vdXRwdXRCdWZmZXI7YTwxO2ErPWgpZm9yKHI9YSUxLHM9MS1yLHRoaXMubGFzdFdlaWdodD1hJTEsbD0wO2w8dGhpcy5jaGFubmVsczsrK2wpcFtuKytdPXRoaXMubGFzdE91dHB1dFtsXSpzK2VbbF0qcjtmb3IoYS09MSx0LT1pLHU9TWF0aC5mbG9vcihhKSppO248ZiYmdTx0Oyl7Zm9yKHI9YSUxLHM9MS1yLGw9MDtsPHRoaXMuY2hhbm5lbHM7KytsKXBbbisrXT1lW3UrKGw+MD9sOjApXSpzK2VbdSsoaStsKV0qcjthKz1oLHU9TWF0aC5mbG9vcihhKSppfWZvcihsPTA7bDxpOysrbCl0aGlzLmxhc3RPdXRwdXRbbF09ZVt1KytdO3JldHVybiB0aGlzLmJ1ZmZlclNsaWNlKG4pfX1tdWx0aVRhcCgpe3RoaXMucmVzYW1wbGVyPWU9PntsZXQgdD1lLmxlbmd0aCxpLGYsaD10aGlzLmNoYW5uZWxzLGEscyxyLHUsbixwLGwsbSxCO2lmKHQlaCE9PTApdGhyb3cgbmV3IEVycm9yKCJCdWZmZXIgd2FzIG9mIGluY29ycmVjdCBzYW1wbGUgbGVuZ3RoLiIpO2lmKHQ8PTApcmV0dXJuW107Zm9yKGk9dGhpcy5vdXRwdXRCdWZmZXJTaXplLGY9W10sYT10aGlzLnJhdGlvV2VpZ2h0LHM9MCx1PTAsbj0wLHA9IXRoaXMudGFpbEV4aXN0cyx0aGlzLnRhaWxFeGlzdHM9ITEsbD10aGlzLm91dHB1dEJ1ZmZlcixtPTAsQj0wLHI9MDtyPGg7KytyKWZbcl09MDtkb3tpZihwKWZvcihzPWEscj0wO3I8aDsrK3IpZltyXT0wO2Vsc2V7Zm9yKHM9dGhpcy5sYXN0V2VpZ2h0LHI9MDtyPGg7KytyKWZbcl09dGhpcy5sYXN0T3V0cHV0W3JdO3A9ITB9Zm9yKDtzPjAmJnU8dDspaWYobj0xK3UtQixzPj1uKXtmb3Iocj0wO3I8aDsrK3IpZltyXSs9ZVt1KytdKm47Qj11LHMtPW59ZWxzZXtmb3Iocj0wO3I8aDsrK3IpZltyXSs9ZVt1KyhyPjA/cjowKV0qcztCKz1zLHM9MDticmVha31pZihzPT09MClmb3Iocj0wO3I8aDsrK3IpbFttKytdPWZbcl0vYTtlbHNle2Zvcih0aGlzLmxhc3RXZWlnaHQ9cyxyPTA7cjxoOysrcil0aGlzLmxhc3RPdXRwdXRbcl09ZltyXTt0aGlzLnRhaWxFeGlzdHM9ITA7YnJlYWt9fXdoaWxlKHU8dCYmbTxpKTtyZXR1cm4gdGhpcy5idWZmZXJTbGljZShtKX19cmVzYW1wbGUoZSl7cmV0dXJuIHRoaXMuZnJvbVNhbXBsZVJhdGU9PXRoaXMudG9TYW1wbGVSYXRlP3RoaXMucmF0aW9XZWlnaHQ9MToodGhpcy5mcm9tU2FtcGxlUmF0ZTx0aGlzLnRvU2FtcGxlUmF0ZT90aGlzLmxhc3RXZWlnaHQ9MToodGhpcy50YWlsRXhpc3RzPSExLHRoaXMubGFzdFdlaWdodD0wKSx0aGlzLmluaXRpYWxpemVCdWZmZXJzKCksdGhpcy5yYXRpb1dlaWdodD10aGlzLmZyb21TYW1wbGVSYXRlL3RoaXMudG9TYW1wbGVSYXRlKSx0aGlzLnJlc2FtcGxlcihlKX19O2Z1bmN0aW9uIGQobyl7bGV0IGU9by5sZW5ndGgsdD1uZXcgSW50MTZBcnJheShlKTtmb3IoO2UtLTspe2xldCBpPU1hdGgubWF4KC0xLE1hdGgubWluKDEsb1tlXSkpO3RbZV09aTwwP2kqMzI3Njg6aSozMjc2N31yZXR1cm4gdH1mdW5jdGlvbiB3KG8pe2xldCBlPW8ubGVuZ3RoLHQ9bmV3IEJpZ0ludDY0QXJyYXkoZSk7Zm9yKDtlLS07KXtsZXQgaT1NYXRoLm1heCgtMSxNYXRoLm1pbigxLG9bZV0pKTt0W2VdPUJpZ0ludChNYXRoLmZsb29yKGk8MD9pKjMyNzY4OmkqMzI3NjcpKSoweDEwMDAwMDAwMDAwMG59cmV0dXJuIHR9dmFyIGM9Y2xhc3N7Y29uc3RydWN0b3IoZSx0KXt0aGlzLm91dHB1dEJ1ZmZlclNpemU9MDt0aGlzLnBhcnRpYWxCdWZmZXJzPVtdO3RoaXMucGFydGlhbEJ1ZmZlck9mZnNldD0wO2lmKCFlKXRocm93IG5ldyBFcnJvcihgSW52YWxpZCBhcnJheSBjbGFzczogJHtlfWApO2lmKCF0fHx0PD0wKXRocm93IG5ldyBFcnJvcihgSW52YWxpZCBvdXRwdXQgYnVmZmVyIHNpemU6ICR7dH1gKTt0aGlzLkFycmF5Q2xhc3M9ZSx0aGlzLm91dHB1dEJ1ZmZlclNpemU9dH1nZXQgcXVldWVkU2l6ZSgpe3JldHVybiB0aGlzLnBhcnRpYWxCdWZmZXJzLnJlZHVjZSgoZSx0KT0+ZSt0Lmxlbmd0aCwwKX1mZWVkKGUpe3RoaXMucGFydGlhbEJ1ZmZlcnMucHVzaChlKX1nZXQgY2FuRHJhaW4oKXtyZXR1cm4gdGhpcy5wYXJ0aWFsQnVmZmVycy5yZWR1Y2UoKHQsaSk9PnQraS5sZW5ndGgsMCktdGhpcy5wYXJ0aWFsQnVmZmVyT2Zmc2V0Pj10aGlzLm91dHB1dEJ1ZmZlclNpemV9ZHJhaW4oKXtpZighdGhpcy5jYW5EcmFpbilyZXR1cm4gbnVsbDtsZXQgZT10aGlzLkFycmF5Q2xhc3MsdD1uZXcgZSh0aGlzLm91dHB1dEJ1ZmZlclNpemUpLGk9MDtmb3IoO2khPXQubGVuZ3RoOyl7aWYoaT50Lmxlbmd0aCl0aHJvdyBuZXcgRXJyb3IoYEJ1ZmZlciBvdmVyZmxvdzogJHtpfSA+ICR7dC5sZW5ndGh9YCk7bGV0IGY9dC5sZW5ndGgtaSxoPXRoaXMucGFydGlhbEJ1ZmZlcnNbMF0sYT1oLmxlbmd0aC10aGlzLnBhcnRpYWxCdWZmZXJPZmZzZXQ7YTxmPyh0LnNldChoLnN1YmFycmF5KHRoaXMucGFydGlhbEJ1ZmZlck9mZnNldCksaSksaSs9YSx0aGlzLnBhcnRpYWxCdWZmZXJzLnNoaWZ0KCksdGhpcy5wYXJ0aWFsQnVmZmVyT2Zmc2V0PTApOih0LnNldChoLnN1YmFycmF5KHRoaXMucGFydGlhbEJ1ZmZlck9mZnNldCx0aGlzLnBhcnRpYWxCdWZmZXJPZmZzZXQrZiksaSksaSs9Zix0aGlzLnBhcnRpYWxCdWZmZXJPZmZzZXQrPWYpfXJldHVybiB0fXBhZCgpe2xldCBlPXRoaXMucXVldWVkU2l6ZSV0aGlzLm91dHB1dEJ1ZmZlclNpemU7aWYoZT09MClyZXR1cm47bGV0IHQ9dGhpcy5BcnJheUNsYXNzLGk9bmV3IHQoZSk7dGhpcy5mZWVkKGkpfX07dmFyIHk9Y2xhc3MgZXh0ZW5kcyBBdWRpb1dvcmtsZXRQcm9jZXNzb3J7Y29uc3RydWN0b3IodCl7c3VwZXIodCk7dGhpcy5mb3JtYXQ9ImludDE2Ijt0aGlzLmlucHV0QnVmZmVyPW5ldyBjKEZsb2F0MzJBcnJheSw0MDk2KTt0aGlzLnBvcnQub25tZXNzYWdlPWk9PnRoaXMub25NZXNzYWdlKGkpfW9uTWVzc2FnZSh0KXt0LmRhdGEuYWN0aW9uPT0ic3RhcnQiJiYodGhpcy5mb3JtYXQ9dC5kYXRhLmZvcm1hdCx0aGlzLnJlc2FtcGxlcj1uZXcgZyh0LmRhdGEuaW5wdXRTYW1wbGVSYXRlLHQuZGF0YS5vdXRwdXRTYW1wbGVSYXRlLDEsNDA5NiksdGhpcy5mb3JtYXQ9PSJpbnQxNiI/dGhpcy5vdXRwdXRCdWZmZXI9bmV3IGMoSW50MTZBcnJheSx0LmRhdGEuYnVmZmVyU2l6ZSk6dGhpcy5mb3JtYXQ9PSJpbnQ2NCI/dGhpcy5vdXRwdXRCdWZmZXI9bmV3IGMoQmlnSW50NjRBcnJheSx0LmRhdGEuYnVmZmVyU2l6ZSk6dGhpcy5mb3JtYXQ9PSJmbG9hdDMyIiYmKHRoaXMub3V0cHV0QnVmZmVyPW5ldyBjKEZsb2F0MzJBcnJheSx0LmRhdGEuYnVmZmVyU2l6ZSkpKX1wcm9jZXNzKHQsaSxmKXtmb3IobGV0IGE9MDthPGkubGVuZ3RoO2ErKyl7bGV0IHM9TWF0aC5taW4oaVthXS5sZW5ndGgsdFswXS5sZW5ndGgpO2ZvcihsZXQgcj0wO3I8cztyKyspaVthXVtyXS5zZXQodFswXVtyXSl9aWYoIXRoaXMucmVzYW1wbGVyKXJldHVybiEwO2xldCBoPW5ldyBGbG9hdDMyQXJyYXkoaVswXVswXS5sZW5ndGgpO2ZvcihoLnNldChpWzBdWzBdKSx0aGlzLmlucHV0QnVmZmVyLmZlZWQoaCk7dGhpcy5pbnB1dEJ1ZmZlci5jYW5EcmFpbjspe2xldCBhPXRoaXMuaW5wdXRCdWZmZXIuZHJhaW4oKSxzPXRoaXMucmVzYW1wbGVyLnJlc2FtcGxlKGEpO3RoaXMuZm9ybWF0PT0iaW50MTYiP3RoaXMub3V0cHV0QnVmZmVyLmZlZWQoZChzKSk6dGhpcy5mb3JtYXQ9PSJpbnQ2NCI/dGhpcy5vdXRwdXRCdWZmZXIuZmVlZCh3KHMpKTp0aGlzLmZvcm1hdD09ImZsb2F0MzIiJiZ0aGlzLm91dHB1dEJ1ZmZlci5mZWVkKHMpfWZvcig7dGhpcy5vdXRwdXRCdWZmZXIuY2FuRHJhaW47KXtsZXQgYT10aGlzLm91dHB1dEJ1ZmZlci5kcmFpbigpO2lmKCFhKWJyZWFrO3RoaXMucG9ydC5wb3N0TWVzc2FnZSh7YWN0aW9uOiJkYXRhIixidWZmZXI6YS5idWZmZXJ9LFthLmJ1ZmZlcl0pfXJldHVybiEwfX07cmVnaXN0ZXJQcm9jZXNzb3IoInBjbS1yZWNlaXZlci1ub2RlIix5KTsK";var R=class extends AudioWorkletNode{constructor(e,i,o,s){super(e,"pcm-receiver-node",{numberOfInputs:1});this.format="int16";this.format=o;let n=["int16","int64","float32"];if(!i||i<=0)throw new Error(`Invalid sample rate: ${i}`);if(!n.includes(o))throw new Error(`Invalid format ${o}, must be one of: ${n.join(", ")}`);if(!s||s<=0)throw new Error(`Invalid buffer size: ${s}`);this.port.onmessage=a=>this.onWorkletMessage(a),this.port.postMessage({action:"start",inputSampleRate:e.sampleRate,outputSampleRate:i,format:o,bufferSize:s})}static async registerModule(e){await e.audioWorklet.addModule(Ye)}onWorkletMessage(e){if(e.data.action=="data"){let i=null;if(this.format=="int16"&&(i=new Int16Array(e.data.buffer)),this.format=="int64"&&(i=new BigInt64Array(e.data.buffer)),this.format=="float32"&&(i=new Float32Array(e.data.buffer)),!i)throw new Error(`Invalid format: ${this.format}`);this.onData(i),this.dispatchEvent(new CustomEvent("data",{detail:{data:i}}))}}onData(e){}};var Se=16e3,le=256,V=8,U=new p("VoiceDetectionNode"),K=class K extends R{constructor(e){super(e,Se,"float32",le*V);this.isVoiceActive=!1;this.lastVoiceActiveDate=0;this.voiceEndTimeout=50;this.sensitivity=.5;this.sentivityEnd=.2;this.nextVadReset=0;this.currentProbability=0;this._lastVoiceActive=!1;if(!K.vadModelURL)throw new Error("VAD model url not set, please load it and set it to VoiceDetectionNode.vadModelURL");this.loadModel()}get isVoicePossiblyEnding(){return this.isVoiceActive&&this.currentProbability<this.sensitivity}get sampleRate(){return Se}get numberOfSamples(){return le}get numberOfSampleChunks(){return V}get outputBufferSize(){return le*V}get isModelLoaded(){return!!this.vad}async loadModel(){U.debug("Loading VAD model"),this.vad=await M.load(K.vadModelURL),this.vad.ignoreIfBusy=!0,U.debug("Model loaded"),this.vad.makeConstant("sr","int64",[1],Se),this.vad.makeState("h","hn","float32",[2,V,64]),this.vad.makeState("c","cn","float32",[2,V,64])}async onData(e){if(this.vad)try{let i=await this.vad.run({input:new M.onnx.Tensor(e,[V,le])});if(!i)return;this.currentProbability=0;for(let n=0;n<i.output.data.length;n++)i.output.data[n]>this.currentProbability&&(this.currentProbability=i.output.data[n]);let o=this.isVoiceActive?this.sentivityEnd:this.sensitivity,s=this.currentProbability>o;if(!s&&this._lastVoiceActive&&(this.nextVadReset=Date.now(),this.vad.resetState()),this._lastVoiceActive=s,s&&!this.isVoiceActive?(this.lastVoiceActiveDate=Date.now(),this.isVoiceActive=!0,this.dispatchEvent(new CustomEvent("speechstart")),this.onSpeechStart(),U.debug("Started speaking")):s?this.lastVoiceActiveDate=Date.now():!s&&this.isVoiceActive&&Date.now()<this.lastVoiceActiveDate+this.voiceEndTimeout||!s&&this.isVoiceActive&&(this.isVoiceActive=!1,this.dispatchEvent(new CustomEvent("speechend")),this.onSpeechEnd(),U.debug("Stopped speaking after timeout")),!s){let n=Date.now();n>this.nextVadReset&&(this.nextVadReset=n+5e3,this.vad.resetState())}}catch(i){U.error("VAD failed:",i)}}onSpeechStart(){}onSpeechEnd(){}};K.vadModelURL="";var P=K;var _e=new p("VoiceChunkOutputNode"),j=class extends P{constructor(){super(...arguments);this.buffers=[];this.recordedBuffers=[];this._voiceRecording=!1;this.backBufferDurationSeconds=3}get bufferDuration(){return this.buffers.reduce((e,i)=>e+i.length,0)/8e3}async onData(e){if(await super.onData(e),this.isVoiceActive&&!this._voiceRecording){_e.debug(`Voice detected, sending ${this.buffers.length} existing chunks`),this._voiceRecording=!0;for(let i of this.buffers)this.recordedBuffers.push(i),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:i,isFinal:!1}})),this.onVoiceChunk(i);this.recordedBuffers.push(e),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:e,isFinal:!1}})),this.onVoiceChunk(e),this.buffers=[]}else if(this.isVoiceActive)this.recordedBuffers.push(e),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:e,isFinal:!1}})),this.onVoiceChunk(e);else if(!this.isVoiceActive&&this._voiceRecording){this.recordedBuffers.push(e),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:e,isFinal:!0}})),this.onVoiceChunk(e),this._voiceRecording=!1;let i=this.recordedBuffers.reduce((o,s)=>o+s.length,0);_e.debug(`Voice complete, recorded ${(i/8e3).toFixed(2)} seconds of audio, ${i*4/1024} KB of data`),this.dispatchEvent(new CustomEvent("voicedataend",{detail:{data:this.recordedBuffers}})),this.onVoiceEnd(this.recordedBuffers),this.recordedBuffers=[]}else for(this.buffers.push(e);this.bufferDuration>this.backBufferDurationSeconds;)this.buffers.shift()}onVoiceChunk(e){}onVoiceEnd(e){}};var ce=new p("OpenAITranscriptionNode"),de=class extends j{constructor(e,i){super(e);this.apiKey="";this.pendingBuffers=[];this.isTranscribing=!1;this.apiKey=i}async onVoiceEnd(e){let i=ce.timer("OpenAI Transcribe");this.isTranscribing=!0,this.pendingBuffers.push(...e);let o=re(this.sampleRate,this.pendingBuffers);this.lastRequestAbortController?.abort(),this.lastRequestAbortController=new AbortController;let s="";try{let n=new FormData;n.append("file",o),n.append("model","whisper-1"),n.append("response_format","text");let a=await fetch("https://api.openai.com/v1/audio/transcriptions",{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`},body:n,signal:this.lastRequestAbortController.signal});if(!a.ok)throw new Error(`Failed to generate voice sample: ${a.status} ${a.statusText}`);i("Response received"),s=await a.text(),i("Content received: "+s),this.lastRequestAbortController=void 0}catch(n){ce.error(`Failed to transcribe speech: ${n.message}`);return}finally{this.isTranscribing=!1}if(this.pendingBuffers=[],!s)return ce.debug("Transcription complete, but no text was found");ce.debug(`Transcription: ${s}`),this.onVoiceTranscription(s),this.dispatchEvent(new CustomEvent("transcription",{detail:{text:s}}))}onVoiceTranscription(e){}};var ue=class extends WebSocket{constructor(e){super(e);this.pendingData=[];this.addEventListener("open",()=>this._onOpen())}send(e){this.readyState==WebSocket.OPEN?super.send(e):this.pendingData.push(e)}_onOpen(){for(let e of this.pendingData)super.send(e);this.pendingData=[]}};var S=new p("IntelliWeaveTranscriptionNode"),Mt="wss://speech.intelliweave.ai/api/v1/transcribe",he=class he extends j{constructor(e,i){super(e);this.apiAddress=Mt;this.apiKey="";this.isTranscribing=!1;this.apiKey=i}async onVoiceChunk(e){this.isTranscribing=!0,this.ws?this.ws.send(e):(S.debug("Opening WebSocket connection"),this.ws=new ue(this.apiAddress),this.ws.send(JSON.stringify({type:"hello",sampleRate:16e3,channels:1,format:"float32",apiKey:this.apiKey})),this.ws.send(e.buffer),this.ws.onopen=()=>{S.debug("WebSocket connection opened")},this.ws.addEventListener("message",o=>{let s=JSON.parse(o.data);if(s.error)return S.warn("Error: "+s.error);if(s.type!="transcription")return S.warn("Invalid response type",s);if(s.streaming&&!s.final)return S.debug("Partial transcription: "+s.partialText);if(this.isTranscribing=!1,!s.text.trim())return S.warn(`Empty transcription (${s.processingTime}ms)`);S.debug(`Transcription: ${s.text} (${s.processingTime}ms)`),this.onVoiceTranscription(s.text),this.dispatchEvent(new CustomEvent("transcription",{detail:{text:s.text}}))}),this.ws.addEventListener("close",()=>this.onSocketClose()),this.ws.addEventListener("error",o=>S.warn("WebSocket error")));let i=1e3*60*1;this.shutdownTimer&&clearTimeout(this.shutdownTimer),this.shutdownTimer=setTimeout(()=>{S.debug("Shutting down WebSocket connection"),this.ws?.close(),this.ws=void 0},i)}async onVoiceEnd(e){if(this.ws?.send(JSON.stringify({type:"end"})),he.debugExportWav){let i=re(this.sampleRate,e),o=document.createElement("a");o.href=URL.createObjectURL(i),o.download="recording.wav",o.click()}}onVoiceTranscription(e){}onSocketClose(){S.debug("WebSocket connection closed"),this.ws=void 0,this.isTranscribing=!1}};he.debugExportWav=!1;var pe=he;var ke=new p("SpeechRecognition"),me=class extends EventTarget{constructor(e){super();this.isRunning=!1;this._skipEvents=!1;this.maxVolumeHeard=0;this.ai=e}get isSupported(){if(!M.lib||!this.ai?.vadModel||!C().AudioWorkletNode)return!1;if(this.ai?.config?.transcription?.providerID!="intelliweave"){if(!(this.ai?.config?.transcription?.providerID=="openai"&&this.ai.config?.transcription?.apiKey))return!1}return!0}async start(){if(!this.isSupported)throw new Error("Speech recognition not supported in this persona and browser.");if(!this.isRunning){this.isRunning=!0;try{await this.ai.audio.beginAccess("speech-recognition"),this.micStream=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}});let e=this.ai.audio.context.createMediaStreamSource(this.micStream);this.analyserNode=this.ai.audio.context.createAnalyser(),this.analyserNode.fftSize=32,e.connect(this.analyserNode),this.analyserBuffer=new Float32Array(this.analyserNode.fftSize),P.vadModelURL=URL.createObjectURL(this.ai.vadModel),this.ai?.config?.transcription?.providerID=="openai"?(this.voiceDetection=new de(this.ai.audio.context,this.ai.config.transcription.apiKey),e.connect(this.voiceDetection)):(this.voiceDetection=new pe(this.ai.audio.context,this.ai.apiKey),this.voiceDetection.apiAddress=this.ai?.config?.transcription?.url||this.voiceDetection.apiAddress,e.connect(this.voiceDetection)),this.voiceDetection.addEventListener("speechstart",i=>{this.ai._voiceTracker=ke.timer("voice interaction","Speech started"),this.recordingStartTime=Date.now(),y(this.ai,{event_type:"voice_start",event_properties:{audio_provider:this.ai.config?.transcription?.providerID||"intelliweave",sample_rate:16e3}}),this.dispatchEvent(new CustomEvent(i.type,{detail:i.detail}))}),this.voiceDetection.addEventListener("speechend",i=>{this.ai._voiceTracker?.("Speech ended");let o=this.recordingStartTime?Date.now()-this.recordingStartTime:0;y(this.ai,{event_type:"voice_end",event_properties:{recording_duration_ms:o}}),this.dispatchEvent(new CustomEvent(i.type,{detail:i.detail}))}),this.voiceDetection.addEventListener("transcription",i=>{this.ai._voiceTracker?.(`Transcription: ${i.detail.text}`),y(this.ai,{event_type:"voice_submit",value_str:"",event_properties:{transcription_provider:this.ai.config?.transcription?.providerID||"intelliweave",confidence_score:i.detail.confidence||void 0}}),this.onTranscription(i)}),this._skipEvents||this.dispatchEvent(new CustomEvent("start",{detail:{speechRecognition:this}}))}catch(e){ke.error("Failed to start speech recognition:",e),this.stop()}}}stop(){this.isRunning&&(this.isRunning=!1,this.ai.audio.endAccess("speech-recognition"),this.voiceDetection?.disconnect(),this.voiceDetection=void 0,this.micStream?.getTracks().forEach(e=>e.stop()),this.micStream=void 0,this.analyserNode=void 0,this.analyserBuffer=void 0,this._skipEvents||this.dispatchEvent(new CustomEvent("end",{detail:{speechRecognition:this}})))}get volumeLevel(){if(!this.analyserNode||!this.analyserBuffer)return 0;this.analyserNode.getFloatTimeDomainData(this.analyserBuffer);let e=0;for(let o of this.analyserBuffer)e+=o*o;let i=Math.sqrt(e/this.analyserBuffer.length);return i>this.maxVolumeHeard&&(this.maxVolumeHeard=i),this.maxVolumeHeard*=.999,this.maxVolumeHeard<.01&&(this.maxVolumeHeard=.01),Math.min(1,Math.max(0,i/this.maxVolumeHeard))}get wordsCurrentlyBeingSpoken(){return!!this.voiceDetection?.isVoiceActive}get isTranscribing(){return!!this.voiceDetection?.isTranscribing}onTranscription(e){let i=e.detail.text;ke.debug("Heard:",i),this.dispatchEvent(new CustomEvent("speech",{detail:{transcript:i,isFinal:!0}}))}async reset(){if(this.isRunning){this._skipEvents=!0;try{this.stop(),await this.start(),this._skipEvents=!1}catch(e){throw this._skipEvents=!1,e}}}};var ge=new p("AudioSystem"),F=class u{constructor(t){this.locks=[];if(!t)throw new Error("AI reference is required. Please pass in the IntelliWeave instance to the constructor.");this.ai=t,this.ai.audio=this,this.speechRecognition=new me(this.ai),this.speechOutput=new ae(this.ai)}static get isSupported(){return!(!M.lib||!C().AudioWorkletNode)}static async registerModules(t){await Promise.all([X.registerModule(t),R.registerModule(t)])}async beginAccess(t){ge.debug(`Began access for: ${t}`),this.locks.includes(t)||this.locks.push(t),!this.context&&(ge.debug("Creating AudioContext"),this.context=new AudioContext({latencyHint:"interactive"}),this.context.resume(),await u.registerModules(this.context))}endAccess(t){ge.debug(`Ended access for: ${t}`),this.locks=this.locks.filter(e=>e!=t),!this.locks.length&&(ge.debug("Closing AudioContext"),this.context?.close(),this.context=void 0)}};var b=new p("Embed"),A=class extends w{constructor(){super();this.config={};this.suggestions=[];this._previousOpenState=!1;this.html=()=>`
|
|
454
|
+
`}onUpdate(){this.child("llm-selector-panel").className=this.attr.open?"open":"closed";let r=this.child("llm-selector-list");for(;r.lastChild;)r.lastChild.remove();for(let n of this.state.items||[]){let i=document.createElement("div");i.className="llm-selector-item"+(n.id==this.state.selectedID?" selected":""),i.innerHTML=`
|
|
455
|
+
<div class='llm-selector-item-icon' style="background-image: url('${n.icon}'); "></div>
|
|
456
|
+
<div class='llm-selector-item-name'>${n.name}</div>
|
|
457
|
+
<div class='llm-selector-item-provider'>${n.provider}</div>
|
|
458
|
+
`,i.addEventListener("click",o=>{this.dispatchEvent(new CustomEvent("select",{detail:n.id}))}),r.appendChild(i)}}};mm.observedAttributes=["open"];var Uu=new Le("ONNXModel"),vi=class t{constructor(e){this.stateTensors={};this.constantTensors={};this._runActive=!1;this.ignoreIfBusy=!1;this.session=e,Uu.debug(`Model input parameters: ${e.inputNames.join(", ")}`),Uu.debug(`Model output parameters: ${e.outputNames.join(", ")}`)}static isSupported(){return!!t.lib}static async load(e){if(!t.lib)throw new Error("ONNX runtime not loaded, please set the runtime loader. Example: ONNXModel.lib = () => import('onnxruntime-web')");this.onnx||(Uu.debug("Loading ONNX runtime"),this.onnx=await t.lib()),Uu.debug(`Loading model: ${e}`);let r=await this.onnx.InferenceSession.create(e);return new t(r)}makeTensor(e,r,n=0){let i=1;for(let s of r)i*=s;let o;if(e=="float32")o=new t.onnx.Tensor(new Float32Array(i),r);else if(e=="int8")o=new t.onnx.Tensor(new Int8Array(i),r);else if(e=="int16")o=new t.onnx.Tensor(new Int16Array(i),r);else if(e=="int32")o=new t.onnx.Tensor(new Int32Array(i),r);else if(e=="int64")o=new t.onnx.Tensor(new BigInt64Array(i),r);else if(e=="uint8")o=new t.onnx.Tensor(new Uint8Array(i),r);else if(e=="uint16")o=new t.onnx.Tensor(new Uint16Array(i),r);else if(e=="uint32")o=new t.onnx.Tensor(new Uint32Array(i),r);else if(e=="uint64")o=new t.onnx.Tensor(new BigUint64Array(i),r);else throw new Error(`Invalid type: ${e}`);return n!==0&&(e=="int64"||e=="uint64")?o.data.fill(BigInt(n)):n!==0&&o.data.fill(n),o}registerConstant(e,r){if(!this.session.inputNames.includes(e))throw new Error(`Model does not have an input named: ${e}`);return this.constantTensors[e]=r,r}makeConstant(e,r,n,i=0){return this.registerConstant(e,this.makeTensor(r,n,i))}registerState(e,r,n){if(r||(r=e),!this.session.inputNames.includes(e))throw new Error(`Model does not have an input named: ${e}`);if(!this.session.outputNames.includes(r))throw new Error(`Model does not have an output named: ${r}`);return this.stateTensors[e]={outputName:r,tensor:n},n}makeState(e,r,n,i,o=0){return this.registerState(e,r,this.makeTensor(n,i,o))}async run(e={}){if(this._runActive&&this.ignoreIfBusy)return Uu.debug("Ignoring run request because a previous run is still active");if(this._runActive)throw new Error("A previous run is still active");this._runActive=!0;for(let r in this.stateTensors)e[r]=this.stateTensors[r].tensor;for(let r in this.constantTensors)e[r]=this.constantTensors[r];try{let r=await this.session.run(e);for(let n in this.stateTensors){let i=r[this.stateTensors[n].outputName];this.stateTensors[n].tensor=i}return r}finally{this._runActive=!1}}resetState(){Uu.debug("Resetting state tensors");for(let e in this.stateTensors)this.stateTensors[e].tensor.data.fill(0)}};var UD="data:application/javascript;base64,dmFyIGM9Y2xhc3N7Y29uc3RydWN0b3IoaSx0KXt0aGlzLm91dHB1dEJ1ZmZlclNpemU9MDt0aGlzLnBhcnRpYWxCdWZmZXJzPVtdO3RoaXMucGFydGlhbEJ1ZmZlck9mZnNldD0wO2lmKCFpKXRocm93IG5ldyBFcnJvcihgSW52YWxpZCBhcnJheSBjbGFzczogJHtpfWApO2lmKCF0fHx0PD0wKXRocm93IG5ldyBFcnJvcihgSW52YWxpZCBvdXRwdXQgYnVmZmVyIHNpemU6ICR7dH1gKTt0aGlzLkFycmF5Q2xhc3M9aSx0aGlzLm91dHB1dEJ1ZmZlclNpemU9dH1nZXQgcXVldWVkU2l6ZSgpe3JldHVybiB0aGlzLnBhcnRpYWxCdWZmZXJzLnJlZHVjZSgoaSx0KT0+aSt0Lmxlbmd0aCwwKX1mZWVkKGkpe3RoaXMucGFydGlhbEJ1ZmZlcnMucHVzaChpKX1nZXQgY2FuRHJhaW4oKXtyZXR1cm4gdGhpcy5wYXJ0aWFsQnVmZmVycy5yZWR1Y2UoKHQscik9PnQrci5sZW5ndGgsMCktdGhpcy5wYXJ0aWFsQnVmZmVyT2Zmc2V0Pj10aGlzLm91dHB1dEJ1ZmZlclNpemV9ZHJhaW4oKXtpZighdGhpcy5jYW5EcmFpbilyZXR1cm4gbnVsbDtsZXQgaT10aGlzLkFycmF5Q2xhc3MsdD1uZXcgaSh0aGlzLm91dHB1dEJ1ZmZlclNpemUpLHI9MDtmb3IoO3IhPXQubGVuZ3RoOyl7aWYocj50Lmxlbmd0aCl0aHJvdyBuZXcgRXJyb3IoYEJ1ZmZlciBvdmVyZmxvdzogJHtyfSA+ICR7dC5sZW5ndGh9YCk7bGV0IGE9dC5sZW5ndGgtcixzPXRoaXMucGFydGlhbEJ1ZmZlcnNbMF0sZj1zLmxlbmd0aC10aGlzLnBhcnRpYWxCdWZmZXJPZmZzZXQ7ZjxhPyh0LnNldChzLnN1YmFycmF5KHRoaXMucGFydGlhbEJ1ZmZlck9mZnNldCkscikscis9Zix0aGlzLnBhcnRpYWxCdWZmZXJzLnNoaWZ0KCksdGhpcy5wYXJ0aWFsQnVmZmVyT2Zmc2V0PTApOih0LnNldChzLnN1YmFycmF5KHRoaXMucGFydGlhbEJ1ZmZlck9mZnNldCx0aGlzLnBhcnRpYWxCdWZmZXJPZmZzZXQrYSkscikscis9YSx0aGlzLnBhcnRpYWxCdWZmZXJPZmZzZXQrPWEpfXJldHVybiB0fXBhZCgpe2xldCBpPXRoaXMucXVldWVkU2l6ZSV0aGlzLm91dHB1dEJ1ZmZlclNpemU7aWYoaT09MClyZXR1cm47bGV0IHQ9dGhpcy5BcnJheUNsYXNzLHI9bmV3IHQoaSk7dGhpcy5mZWVkKHIpfX07dmFyIGQ9Y2xhc3N7Y29uc3RydWN0b3IoaSx0LHIsYSl7aWYoIWl8fCF0fHwhcil0aHJvdyBuZXcgRXJyb3IoIkludmFsaWQgc2V0dGluZ3Mgc3BlY2lmaWVkIGZvciB0aGUgcmVzYW1wbGVyLiIpO3RoaXMucmVzYW1wbGVyPW51bGwsdGhpcy5mcm9tU2FtcGxlUmF0ZT1pLHRoaXMudG9TYW1wbGVSYXRlPXQsdGhpcy5jaGFubmVscz1yfHwwLHRoaXMuaW5wdXRCdWZmZXJTaXplPWEsdGhpcy5pbml0aWFsaXplKCl9aW5pdGlhbGl6ZSgpe3RoaXMuZnJvbVNhbXBsZVJhdGU9PXRoaXMudG9TYW1wbGVSYXRlPyh0aGlzLnJlc2FtcGxlcj1pPT5pLHRoaXMucmF0aW9XZWlnaHQ9MSk6KHRoaXMuZnJvbVNhbXBsZVJhdGU8dGhpcy50b1NhbXBsZVJhdGU/KHRoaXMubGluZWFySW50ZXJwb2xhdGlvbigpLHRoaXMubGFzdFdlaWdodD0xKToodGhpcy5tdWx0aVRhcCgpLHRoaXMudGFpbEV4aXN0cz0hMSx0aGlzLmxhc3RXZWlnaHQ9MCksdGhpcy5pbml0aWFsaXplQnVmZmVycygpLHRoaXMucmF0aW9XZWlnaHQ9dGhpcy5mcm9tU2FtcGxlUmF0ZS90aGlzLnRvU2FtcGxlUmF0ZSl9YnVmZmVyU2xpY2UoaSl7dHJ5e3JldHVybiB0aGlzLm91dHB1dEJ1ZmZlci5zdWJhcnJheSgwLGkpfWNhdGNoe3RyeXtyZXR1cm4gdGhpcy5vdXRwdXRCdWZmZXIubGVuZ3RoPWksdGhpcy5vdXRwdXRCdWZmZXJ9Y2F0Y2h7cmV0dXJuIHRoaXMub3V0cHV0QnVmZmVyLnNsaWNlKDAsaSl9fX1pbml0aWFsaXplQnVmZmVycygpe3RoaXMub3V0cHV0QnVmZmVyU2l6ZT1NYXRoLmNlaWwodGhpcy5pbnB1dEJ1ZmZlclNpemUqdGhpcy50b1NhbXBsZVJhdGUvdGhpcy5mcm9tU2FtcGxlUmF0ZS90aGlzLmNoYW5uZWxzKjEuMDAwMDAwNDc2ODM3MTU4MikrdGhpcy5jaGFubmVscyt0aGlzLmNoYW5uZWxzO3RyeXt0aGlzLm91dHB1dEJ1ZmZlcj1uZXcgRmxvYXQzMkFycmF5KHRoaXMub3V0cHV0QnVmZmVyU2l6ZSksdGhpcy5sYXN0T3V0cHV0PW5ldyBGbG9hdDMyQXJyYXkodGhpcy5jaGFubmVscyl9Y2F0Y2h7dGhpcy5vdXRwdXRCdWZmZXI9W10sdGhpcy5sYXN0T3V0cHV0PVtdfX1saW5lYXJJbnRlcnBvbGF0aW9uKCl7dGhpcy5yZXNhbXBsZXI9aT0+e2xldCB0PWkubGVuZ3RoLHI9dGhpcy5jaGFubmVscyxhLHMsZixoLGUsbix1LG8sbDtpZih0JXIhPT0wKXRocm93IG5ldyBFcnJvcigiQnVmZmVyIHdhcyBvZiBpbmNvcnJlY3Qgc2FtcGxlIGxlbmd0aC4iKTtpZih0PD0wKXJldHVybltdO2ZvcihhPXRoaXMub3V0cHV0QnVmZmVyU2l6ZSxzPXRoaXMucmF0aW9XZWlnaHQsZj10aGlzLmxhc3RXZWlnaHQsaD0wLGU9MCxuPTAsdT0wLG89dGhpcy5vdXRwdXRCdWZmZXI7ZjwxO2YrPXMpZm9yKGU9ZiUxLGg9MS1lLHRoaXMubGFzdFdlaWdodD1mJTEsbD0wO2w8dGhpcy5jaGFubmVsczsrK2wpb1t1KytdPXRoaXMubGFzdE91dHB1dFtsXSpoK2lbbF0qZTtmb3IoZi09MSx0LT1yLG49TWF0aC5mbG9vcihmKSpyO3U8YSYmbjx0Oyl7Zm9yKGU9ZiUxLGg9MS1lLGw9MDtsPHRoaXMuY2hhbm5lbHM7KytsKW9bdSsrXT1pW24rKGw+MD9sOjApXSpoK2lbbisocitsKV0qZTtmKz1zLG49TWF0aC5mbG9vcihmKSpyfWZvcihsPTA7bDxyOysrbCl0aGlzLmxhc3RPdXRwdXRbbF09aVtuKytdO3JldHVybiB0aGlzLmJ1ZmZlclNsaWNlKHUpfX1tdWx0aVRhcCgpe3RoaXMucmVzYW1wbGVyPWk9PntsZXQgdD1pLmxlbmd0aCxyLGEscz10aGlzLmNoYW5uZWxzLGYsaCxlLG4sdSxvLGwsbSxnO2lmKHQlcyE9PTApdGhyb3cgbmV3IEVycm9yKCJCdWZmZXIgd2FzIG9mIGluY29ycmVjdCBzYW1wbGUgbGVuZ3RoLiIpO2lmKHQ8PTApcmV0dXJuW107Zm9yKHI9dGhpcy5vdXRwdXRCdWZmZXJTaXplLGE9W10sZj10aGlzLnJhdGlvV2VpZ2h0LGg9MCxuPTAsdT0wLG89IXRoaXMudGFpbEV4aXN0cyx0aGlzLnRhaWxFeGlzdHM9ITEsbD10aGlzLm91dHB1dEJ1ZmZlcixtPTAsZz0wLGU9MDtlPHM7KytlKWFbZV09MDtkb3tpZihvKWZvcihoPWYsZT0wO2U8czsrK2UpYVtlXT0wO2Vsc2V7Zm9yKGg9dGhpcy5sYXN0V2VpZ2h0LGU9MDtlPHM7KytlKWFbZV09dGhpcy5sYXN0T3V0cHV0W2VdO289ITB9Zm9yKDtoPjAmJm48dDspaWYodT0xK24tZyxoPj11KXtmb3IoZT0wO2U8czsrK2UpYVtlXSs9aVtuKytdKnU7Zz1uLGgtPXV9ZWxzZXtmb3IoZT0wO2U8czsrK2UpYVtlXSs9aVtuKyhlPjA/ZTowKV0qaDtnKz1oLGg9MDticmVha31pZihoPT09MClmb3IoZT0wO2U8czsrK2UpbFttKytdPWFbZV0vZjtlbHNle2Zvcih0aGlzLmxhc3RXZWlnaHQ9aCxlPTA7ZTxzOysrZSl0aGlzLmxhc3RPdXRwdXRbZV09YVtlXTt0aGlzLnRhaWxFeGlzdHM9ITA7YnJlYWt9fXdoaWxlKG48dCYmbTxyKTtyZXR1cm4gdGhpcy5idWZmZXJTbGljZShtKX19cmVzYW1wbGUoaSl7cmV0dXJuIHRoaXMuZnJvbVNhbXBsZVJhdGU9PXRoaXMudG9TYW1wbGVSYXRlP3RoaXMucmF0aW9XZWlnaHQ9MToodGhpcy5mcm9tU2FtcGxlUmF0ZTx0aGlzLnRvU2FtcGxlUmF0ZT90aGlzLmxhc3RXZWlnaHQ9MToodGhpcy50YWlsRXhpc3RzPSExLHRoaXMubGFzdFdlaWdodD0wKSx0aGlzLmluaXRpYWxpemVCdWZmZXJzKCksdGhpcy5yYXRpb1dlaWdodD10aGlzLmZyb21TYW1wbGVSYXRlL3RoaXMudG9TYW1wbGVSYXRlKSx0aGlzLnJlc2FtcGxlcihpKX19O2Z1bmN0aW9uIFMocCl7bGV0IGk9cC5sZW5ndGgsdD1uZXcgRmxvYXQzMkFycmF5KGkpO2Zvcig7aS0tOyl7bGV0IHI9cFtpXTt0W2ldPXI+PTMyNzY4Py0oNjU1MzYtcikvMzI3Njg6ci8zMjc2N31yZXR1cm4gdH12YXIgeT0xMDI0KjgsQj1jbGFzcyBleHRlbmRzIEF1ZGlvV29ya2xldFByb2Nlc3Nvcntjb25zdHJ1Y3Rvcih0KXtzdXBlcih0KTt0aGlzLmNodW5rcz1bXTt0aGlzLmNodW5rUG9zaXRpb249MDt0aGlzLmlzRW5kZWQ9ITE7dGhpcy5pc0NhbmNlbGxlZD0hMTt0aGlzLnNhbXBsZVJhdGU9MDt0aGlzLmZvcm1hdD0iaW50MTYiO3RoaXMuYnVmZmVyT2Zmc2V0PTA7dGhpcy5sYXN0UGxheWVkQnVmZmVyU2l6ZT0wO3RoaXMuX2hhc1NlbnRFbmRFdmVudD0hMTt0aGlzLnBvcnQub25tZXNzYWdlPXI9PnRoaXMub25NZXNzYWdlKHIpfW9uTWVzc2FnZSh0KXtpZih0LmRhdGEuYWN0aW9uPT0ic3RhcnQiKXRoaXMuZm9ybWF0PXQuZGF0YS5mb3JtYXQsdGhpcy5zYW1wbGVSYXRlPXQuZGF0YS5pbnB1dFNhbXBsZVJhdGUsdGhpcy5yZXNhbXBsZXI9bmV3IGQodC5kYXRhLmlucHV0U2FtcGxlUmF0ZSx0LmRhdGEub3V0cHV0U2FtcGxlUmF0ZSwxLHkpLHRoaXMuZm9ybWF0PT0iaW50MTYiP3RoaXMuaW5wdXRCdWZmZXI9bmV3IGMoVWludDhBcnJheSx5KjIpOnRoaXMuZm9ybWF0PT0iZmxvYXQzMiImJih0aGlzLmlucHV0QnVmZmVyPW5ldyBjKFVpbnQ4QXJyYXkseSo0KSk7ZWxzZSBpZih0LmRhdGEuYWN0aW9uPT0iZGF0YSIpe2xldCByPW5ldyBVaW50OEFycmF5KHQuZGF0YS5idWZmZXIpO2Zvcih0aGlzLmlucHV0QnVmZmVyLmZlZWQocik7dGhpcy5pbnB1dEJ1ZmZlci5jYW5EcmFpbjspdGhpcy5kcmFpbkJ1ZmZlcigpfWVsc2UgdC5kYXRhLmFjdGlvbj09ImVuZCI/KHRoaXMubGFzdFBsYXllZEJ1ZmZlclNpemUmJnRoaXMuY2h1bmtzLnB1c2gobmV3IEZsb2F0MzJBcnJheSh0aGlzLmxhc3RQbGF5ZWRCdWZmZXJTaXplKjIpKSx0aGlzLmlzRW5kZWQ9ITApOnQuZGF0YS5hY3Rpb249PSJjYW5jZWwiJiYodGhpcy5pc0VuZGVkPSEwLHRoaXMuaXNDYW5jZWxsZWQ9ITApfWRyYWluQnVmZmVyKCl7bGV0IHQ9dGhpcy5pbnB1dEJ1ZmZlci5kcmFpbigpO2lmKCF0KXJldHVybjtsZXQgcjtpZih0aGlzLmZvcm1hdD09ImludDE2Iil7bGV0IHM9bmV3IEludDE2QXJyYXkodC5idWZmZXIsdC5ieXRlT2Zmc2V0LHQuYnl0ZUxlbmd0aC8yKTtyPVMocyl9ZWxzZSBpZih0aGlzLmZvcm1hdD09ImZsb2F0MzIiKXI9bmV3IEZsb2F0MzJBcnJheSh0LmJ1ZmZlcix0LmJ5dGVPZmZzZXQsdC5ieXRlTGVuZ3RoLzQpO2Vsc2UgdGhyb3cgbmV3IEVycm9yKGBJbnZhbGlkIGZvcm1hdDogJHt0aGlzLmZvcm1hdH1gKTtsZXQgYT10aGlzLnJlc2FtcGxlci5yZXNhbXBsZShyKTt0aGlzLmNodW5rcy5wdXNoKGEpfW5leHRGbG9hdCgpe2lmKCF0aGlzLmNodW5rcy5sZW5ndGgpcmV0dXJuIDA7bGV0IHQ9dGhpcy5jaHVua3NbMF1bdGhpcy5jaHVua1Bvc2l0aW9uXTtyZXR1cm4gdGhpcy5jaHVua1Bvc2l0aW9uKyssdGhpcy5jaHVua1Bvc2l0aW9uPHRoaXMuY2h1bmtzWzBdLmxlbmd0aHx8KHRoaXMuY2h1bmtzLnNoaWZ0KCksdGhpcy5jaHVua1Bvc2l0aW9uPTApLHR9cHJvY2Vzcyh0LHIsYSl7aWYodGhpcy5pc0NhbmNlbGxlZClyZXR1cm4hMTtpZih0aGlzLmlzRW5kZWQmJiF0aGlzLmNodW5rcy5sZW5ndGgpcmV0dXJuIHRoaXMuX2hhc1NlbnRFbmRFdmVudHx8KHRoaXMuX2hhc1NlbnRFbmRFdmVudD0hMCx0aGlzLnBvcnQucG9zdE1lc3NhZ2Uoe2FjdGlvbjoiZW5kIn0pKSwhMTtsZXQgcz1yWzBdPy5bMF0/Lmxlbmd0aDtpZighcylyZXR1cm4hMDt0aGlzLmxhc3RQbGF5ZWRCdWZmZXJTaXplPXM7Zm9yKGxldCBmPTA7ZjxzO2YrKyl7bGV0IGg9dGhpcy5uZXh0RmxvYXQoKTtmb3IobGV0IGU9MDtlPHIubGVuZ3RoO2UrKylmb3IobGV0IG49MDtuPHJbZV0ubGVuZ3RoO24rKylyW2VdW25dW2ZdPWh9cmV0dXJuITB9fTtyZWdpc3RlclByb2Nlc3NvcigicGNtLXBsYXllci1ub2RlIixCKTsK";var DY=new Le("PCMPlayerNode"),Zu=class extends AudioWorkletNode{constructor(r,n,i){super(r,"pcm-player-node",{numberOfInputs:0});this.sampleRate=0;this.format="int16";this.isCancelled=!1;if(!n||n<=0)throw new Error(`Invalid sample rate: ${n}`);if(!i||i!="int16"&&i!="float32")throw new Error(`Invalid format: ${i}`);this.sampleRate=n,this.format=i,this.port.onmessage=o=>this.onWorkletMessage(o),this.port.postMessage({action:"start",inputSampleRate:n,outputSampleRate:r.sampleRate,format:i})}static async registerModule(r){await r.audioWorklet.addModule(UD)}feed(r){this.port.postMessage({action:"data",buffer:r.buffer},[r.buffer])}async play(r){if(this.isCancelled)throw new Error("PCMPlayerNode has already been cancelled.");if(this._playPromise)throw new Error("Already playing a stream");this._playPromise=new Promise(n=>this._playPromiseResolve=n),this.dispatchEvent(new CustomEvent("start",{detail:{player:this,stream:r}}));try{let n=r.getReader();for(;!this.isCancelled;){let{done:i,value:o}=await n.read();if(i||!o)break;this.feed(o)}}catch(n){DY.warn("Stream error:",n),this.dispatchEvent(new CustomEvent("error",{detail:{player:this,stream:r,error:n}}))}this.port.postMessage({action:"end"}),await this._playPromise}onWorkletMessage(r){r.data.action=="end"&&(this._playPromiseResolve?.(),this.dispatchEvent(new CustomEvent("end",{detail:{player:this}})))}stop(){this.isCancelled=!0,this.port.postMessage({action:"cancel"}),this._playPromiseResolve?.()}};var hm=new Le("ElevenLabs");function lE(t,e,r="pcm_24000"){let n=[],i=Date.now(),o=!1,s,a;return{stream:new ReadableStream({start:d=>{s=d,a=new WebSocket(`wss://api.elevenlabs.io/v1/text-to-speech/${e}/stream-input?inactivity_timeout=120&output_format=${r}`),a.addEventListener("open",()=>{hm.debug(`[at ${Date.now()-i}ms] WebSocket connected`),a.send(JSON.stringify({text:" ","xi-api-key":t}));for(let p of n)a.send(JSON.stringify({text:p}));n.length=0}),a.addEventListener("close",()=>{hm.debug(`[at ${Date.now()-i}ms] WebSocket closed`),s?.close(),o=!0}),a.addEventListener("message",p=>{let f=JSON.parse(p.data);if(f.final){a.close(),s?.close();return}if(hm.debug(`[at ${Date.now()-i}ms] Message received: ${f.audio?.length||0} bytes of audio data`),!f.audio)return;let m=Uint8Array.from(atob(f.audio),h=>h.charCodeAt(0));s?.enqueue(m)})},cancel:()=>{hm.debug(`[at ${Date.now()-i}ms] Stream cancelled`),a?.close(),o=!0}}),sendText:d=>{d&&(hm.debug(`[at ${Date.now()-i}ms] Sending text: "${d}"`),a?.readyState===WebSocket.OPEN?a.send(JSON.stringify({text:d})):n.push(d))},endText:()=>{a?.readyState===WebSocket.OPEN?a.send(JSON.stringify({text:""})):n.push("")},get isClosed(){return o}}}var Uv=new Le("SpeechOutput"),ZD=.5,LY=.8,Zv=class extends EventTarget{constructor(r){super();this.autoSpeak=!0;this.preemptiveConnection=!0;this.processedMessages=new Set;this.maxVolumeHeard=0;this._queuedText=[];this._queueActive=!1;this.ai=r,this.ai.addEventListener("output",n=>this.onOutputFromAI(n)),this.ai.audio?.speechRecognition.addEventListener("speechstart",n=>this.interrupt())}onOutputFromAI(r){let n=r.detail.messages,i=r.detail.isPartial;if(!(!this.ai?.audio?.speechRecognition.isRunning||!this.autoSpeak)){for(let o of n)if(!o.streamingInProgress&&!(!o.id||this.processedMessages.has(o.id))){this.processedMessages.add(o.id);for(let s of o.sections||[])s.type=="text"&&s.text&&this.speak(s.text)}i||this.processedMessages.clear()}}get volumeLevel(){if(!this.analyserNode||!this.analyserBuffer)return 0;this.analyserNode.getFloatTimeDomainData(this.analyserBuffer);let r=0;for(let i of this.analyserBuffer)r+=i*i;let n=Math.sqrt(r/this.analyserBuffer.length);return n>this.maxVolumeHeard&&(this.maxVolumeHeard=n),this.maxVolumeHeard*=.999,this.maxVolumeHeard<.01&&(this.maxVolumeHeard=.01),Math.min(1,Math.max(0,n/this.maxVolumeHeard))}async speak(r){if(!this.ai?.config?.voice?.providerID)return Uv.warn("No voice provider configured");this.ai._voiceTracker?.(`Added text to queue: ${r}`),this._queuedText.push(r),this._runQueue()}async _runQueue(){if(this._queueActive)return;let r=this._queuedText.shift();if(!r)return;this._queueActive=!0;let n=`speech-${UY++}`;try{await this.ai.audio.beginAccess(n),await this._speakWithLock(r)}finally{this._queueActive=!1,this.ai.audio.endAccess(n)}this._queuedText.length?await this._runQueue():this.onSpeechEnd()}_getElevenLabsConnection(){let r=this._elevenLabsPrecachedConnection;return(!r||r.isClosed)&&(r=lE(this.ai.config.voice.apiKey,this.ai.config.voice.voiceID,"pcm_24000")),this.preemptiveConnection&&(this._elevenLabsPrecachedConnection=lE(this.ai.config.voice.apiKey,this.ai.config.voice.voiceID,"pcm_24000")),r}async _speakWithLock(r){let n=new CustomEvent("speechfilter",{detail:{ai:this.ai,message:r}});if(this.dispatchEvent(n),r=n.detail.message,n.defaultPrevented||!r)return;this.ai.audio.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=LY);let i=this.ai?._voiceTracker||Uv.timer(`${this.ai.config.voice.providerID} voice`);i(`Speak: ${r}`),this.currentPlayerVolume?.disconnect(),this.currentPlayerVolume=this.ai.audio.context.createGain(),this.currentPlayerVolume.connect(this.ai.audio.context.destination),this.analyserNode=this.ai.audio.context.createAnalyser(),this.analyserNode.fftSize=32,this.analyserNode.connect(this.currentPlayerVolume),this.maxVolumeHeard=0,this.analyserBuffer=new Float32Array(this.analyserNode.fftSize);let o=new Zu(this.ai.audio.context,24e3,"int16");this.currentPlayer=o,o.connect(this.analyserNode),o.addEventListener("end",l=>{let c=l;i(`PCM stream ${c.detail.interrupted?"interrupted":"ended"}`),this.currentPlayer==o&&!c.detail.interrupted&&(this.currentPlayer=void 0)});let s=Date.now(),a=null;if(this.ai.config.voice.providerID=="openai"){let l=await fetch("https://api.openai.com/v1/audio/speech",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.ai.config.voice.apiKey}`},body:JSON.stringify({model:"tts-1",input:r,voice:this.ai.config.voice.voiceID,response_format:"pcm"})});if(!l.ok){Uv.warn(`Failed to generate voice sample: ${l.status} ${l.statusText}`);return}a=l.body}else if(this.ai.config.voice.providerID=="elevenlabs"){let l=this._getElevenLabsConnection();l.sendText(r),l.endText(),a=l.stream}else{Uv.warn(`Unknown voice provider: ${this.ai.config.voice.providerID}`);return}i(`Received response in ${Date.now()-s}ms`),this.dispatchEvent(new CustomEvent("speechstart",{detail:{ai:this.ai,message:r}})),i("Playing PCM stream"),await o.play(a),i("Audio has ended")}get isSpeaking(){return!!this.currentPlayer}async interrupt(){if(this._queuedText=[],!this.currentPlayerVolume)return;this.ai._voiceTracker?.("Interrupted");let r=this.currentPlayerVolume,n=this.currentPlayer;this.currentPlayerVolume=void 0,this.currentPlayer=void 0,this.ai?.audio?.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=ZD);let i=400;r.gain.linearRampToValueAtTime(0,i/1e3),await new Promise(o=>setTimeout(o,i+250)),r.disconnect(),n?.stop(),n?.disconnect()}onSpeechEnd(){this.dispatchEvent(new CustomEvent("speechend",{detail:{ai:this.ai}})),this.ai?.audio?.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=ZD)}},UY=1;function Fv(t,e){let r=e.reduce((l,c)=>l+c.byteLength,0),n=new DataView(new ArrayBuffer(44));n.setUint8(0,82),n.setUint8(1,73),n.setUint8(2,70),n.setUint8(3,70),n.setUint32(4,44+r,!0),n.setUint8(8,87),n.setUint8(9,65),n.setUint8(10,86),n.setUint8(11,69);let i=1,o=32,s=i*o/8,a=t*s;return n.setUint8(12,102),n.setUint8(13,109),n.setUint8(14,116),n.setUint8(15,32),n.setUint32(16,16,!0),n.setUint16(20,3,!0),n.setUint16(22,i,!0),n.setUint32(24,t,!0),n.setUint32(28,a,!0),n.setUint16(32,s,!0),n.setUint16(34,o,!0),n.setUint8(36,100),n.setUint8(37,97),n.setUint8(38,116),n.setUint8(39,97),n.setUint32(40,r,!0),new File([n,...e],"audio.wav",{type:"audio/wav"})}var FD="data:application/javascript;base64,dmFyIGc9Y2xhc3N7Y29uc3RydWN0b3IoZSx0LGksZil7aWYoIWV8fCF0fHwhaSl0aHJvdyBuZXcgRXJyb3IoIkludmFsaWQgc2V0dGluZ3Mgc3BlY2lmaWVkIGZvciB0aGUgcmVzYW1wbGVyLiIpO3RoaXMucmVzYW1wbGVyPW51bGwsdGhpcy5mcm9tU2FtcGxlUmF0ZT1lLHRoaXMudG9TYW1wbGVSYXRlPXQsdGhpcy5jaGFubmVscz1pfHwwLHRoaXMuaW5wdXRCdWZmZXJTaXplPWYsdGhpcy5pbml0aWFsaXplKCl9aW5pdGlhbGl6ZSgpe3RoaXMuZnJvbVNhbXBsZVJhdGU9PXRoaXMudG9TYW1wbGVSYXRlPyh0aGlzLnJlc2FtcGxlcj1lPT5lLHRoaXMucmF0aW9XZWlnaHQ9MSk6KHRoaXMuZnJvbVNhbXBsZVJhdGU8dGhpcy50b1NhbXBsZVJhdGU/KHRoaXMubGluZWFySW50ZXJwb2xhdGlvbigpLHRoaXMubGFzdFdlaWdodD0xKToodGhpcy5tdWx0aVRhcCgpLHRoaXMudGFpbEV4aXN0cz0hMSx0aGlzLmxhc3RXZWlnaHQ9MCksdGhpcy5pbml0aWFsaXplQnVmZmVycygpLHRoaXMucmF0aW9XZWlnaHQ9dGhpcy5mcm9tU2FtcGxlUmF0ZS90aGlzLnRvU2FtcGxlUmF0ZSl9YnVmZmVyU2xpY2UoZSl7dHJ5e3JldHVybiB0aGlzLm91dHB1dEJ1ZmZlci5zdWJhcnJheSgwLGUpfWNhdGNoe3RyeXtyZXR1cm4gdGhpcy5vdXRwdXRCdWZmZXIubGVuZ3RoPWUsdGhpcy5vdXRwdXRCdWZmZXJ9Y2F0Y2h7cmV0dXJuIHRoaXMub3V0cHV0QnVmZmVyLnNsaWNlKDAsZSl9fX1pbml0aWFsaXplQnVmZmVycygpe3RoaXMub3V0cHV0QnVmZmVyU2l6ZT1NYXRoLmNlaWwodGhpcy5pbnB1dEJ1ZmZlclNpemUqdGhpcy50b1NhbXBsZVJhdGUvdGhpcy5mcm9tU2FtcGxlUmF0ZS90aGlzLmNoYW5uZWxzKjEuMDAwMDAwNDc2ODM3MTU4MikrdGhpcy5jaGFubmVscyt0aGlzLmNoYW5uZWxzO3RyeXt0aGlzLm91dHB1dEJ1ZmZlcj1uZXcgRmxvYXQzMkFycmF5KHRoaXMub3V0cHV0QnVmZmVyU2l6ZSksdGhpcy5sYXN0T3V0cHV0PW5ldyBGbG9hdDMyQXJyYXkodGhpcy5jaGFubmVscyl9Y2F0Y2h7dGhpcy5vdXRwdXRCdWZmZXI9W10sdGhpcy5sYXN0T3V0cHV0PVtdfX1saW5lYXJJbnRlcnBvbGF0aW9uKCl7dGhpcy5yZXNhbXBsZXI9ZT0+e2xldCB0PWUubGVuZ3RoLGk9dGhpcy5jaGFubmVscyxmLGgsYSxzLHIsdSxuLHAsbDtpZih0JWkhPT0wKXRocm93IG5ldyBFcnJvcigiQnVmZmVyIHdhcyBvZiBpbmNvcnJlY3Qgc2FtcGxlIGxlbmd0aC4iKTtpZih0PD0wKXJldHVybltdO2ZvcihmPXRoaXMub3V0cHV0QnVmZmVyU2l6ZSxoPXRoaXMucmF0aW9XZWlnaHQsYT10aGlzLmxhc3RXZWlnaHQscz0wLHI9MCx1PTAsbj0wLHA9dGhpcy5vdXRwdXRCdWZmZXI7YTwxO2ErPWgpZm9yKHI9YSUxLHM9MS1yLHRoaXMubGFzdFdlaWdodD1hJTEsbD0wO2w8dGhpcy5jaGFubmVsczsrK2wpcFtuKytdPXRoaXMubGFzdE91dHB1dFtsXSpzK2VbbF0qcjtmb3IoYS09MSx0LT1pLHU9TWF0aC5mbG9vcihhKSppO248ZiYmdTx0Oyl7Zm9yKHI9YSUxLHM9MS1yLGw9MDtsPHRoaXMuY2hhbm5lbHM7KytsKXBbbisrXT1lW3UrKGw+MD9sOjApXSpzK2VbdSsoaStsKV0qcjthKz1oLHU9TWF0aC5mbG9vcihhKSppfWZvcihsPTA7bDxpOysrbCl0aGlzLmxhc3RPdXRwdXRbbF09ZVt1KytdO3JldHVybiB0aGlzLmJ1ZmZlclNsaWNlKG4pfX1tdWx0aVRhcCgpe3RoaXMucmVzYW1wbGVyPWU9PntsZXQgdD1lLmxlbmd0aCxpLGYsaD10aGlzLmNoYW5uZWxzLGEscyxyLHUsbixwLGwsbSxCO2lmKHQlaCE9PTApdGhyb3cgbmV3IEVycm9yKCJCdWZmZXIgd2FzIG9mIGluY29ycmVjdCBzYW1wbGUgbGVuZ3RoLiIpO2lmKHQ8PTApcmV0dXJuW107Zm9yKGk9dGhpcy5vdXRwdXRCdWZmZXJTaXplLGY9W10sYT10aGlzLnJhdGlvV2VpZ2h0LHM9MCx1PTAsbj0wLHA9IXRoaXMudGFpbEV4aXN0cyx0aGlzLnRhaWxFeGlzdHM9ITEsbD10aGlzLm91dHB1dEJ1ZmZlcixtPTAsQj0wLHI9MDtyPGg7KytyKWZbcl09MDtkb3tpZihwKWZvcihzPWEscj0wO3I8aDsrK3IpZltyXT0wO2Vsc2V7Zm9yKHM9dGhpcy5sYXN0V2VpZ2h0LHI9MDtyPGg7KytyKWZbcl09dGhpcy5sYXN0T3V0cHV0W3JdO3A9ITB9Zm9yKDtzPjAmJnU8dDspaWYobj0xK3UtQixzPj1uKXtmb3Iocj0wO3I8aDsrK3IpZltyXSs9ZVt1KytdKm47Qj11LHMtPW59ZWxzZXtmb3Iocj0wO3I8aDsrK3IpZltyXSs9ZVt1KyhyPjA/cjowKV0qcztCKz1zLHM9MDticmVha31pZihzPT09MClmb3Iocj0wO3I8aDsrK3IpbFttKytdPWZbcl0vYTtlbHNle2Zvcih0aGlzLmxhc3RXZWlnaHQ9cyxyPTA7cjxoOysrcil0aGlzLmxhc3RPdXRwdXRbcl09ZltyXTt0aGlzLnRhaWxFeGlzdHM9ITA7YnJlYWt9fXdoaWxlKHU8dCYmbTxpKTtyZXR1cm4gdGhpcy5idWZmZXJTbGljZShtKX19cmVzYW1wbGUoZSl7cmV0dXJuIHRoaXMuZnJvbVNhbXBsZVJhdGU9PXRoaXMudG9TYW1wbGVSYXRlP3RoaXMucmF0aW9XZWlnaHQ9MToodGhpcy5mcm9tU2FtcGxlUmF0ZTx0aGlzLnRvU2FtcGxlUmF0ZT90aGlzLmxhc3RXZWlnaHQ9MToodGhpcy50YWlsRXhpc3RzPSExLHRoaXMubGFzdFdlaWdodD0wKSx0aGlzLmluaXRpYWxpemVCdWZmZXJzKCksdGhpcy5yYXRpb1dlaWdodD10aGlzLmZyb21TYW1wbGVSYXRlL3RoaXMudG9TYW1wbGVSYXRlKSx0aGlzLnJlc2FtcGxlcihlKX19O2Z1bmN0aW9uIGQobyl7bGV0IGU9by5sZW5ndGgsdD1uZXcgSW50MTZBcnJheShlKTtmb3IoO2UtLTspe2xldCBpPU1hdGgubWF4KC0xLE1hdGgubWluKDEsb1tlXSkpO3RbZV09aTwwP2kqMzI3Njg6aSozMjc2N31yZXR1cm4gdH1mdW5jdGlvbiB3KG8pe2xldCBlPW8ubGVuZ3RoLHQ9bmV3IEJpZ0ludDY0QXJyYXkoZSk7Zm9yKDtlLS07KXtsZXQgaT1NYXRoLm1heCgtMSxNYXRoLm1pbigxLG9bZV0pKTt0W2VdPUJpZ0ludChNYXRoLmZsb29yKGk8MD9pKjMyNzY4OmkqMzI3NjcpKSoweDEwMDAwMDAwMDAwMG59cmV0dXJuIHR9dmFyIGM9Y2xhc3N7Y29uc3RydWN0b3IoZSx0KXt0aGlzLm91dHB1dEJ1ZmZlclNpemU9MDt0aGlzLnBhcnRpYWxCdWZmZXJzPVtdO3RoaXMucGFydGlhbEJ1ZmZlck9mZnNldD0wO2lmKCFlKXRocm93IG5ldyBFcnJvcihgSW52YWxpZCBhcnJheSBjbGFzczogJHtlfWApO2lmKCF0fHx0PD0wKXRocm93IG5ldyBFcnJvcihgSW52YWxpZCBvdXRwdXQgYnVmZmVyIHNpemU6ICR7dH1gKTt0aGlzLkFycmF5Q2xhc3M9ZSx0aGlzLm91dHB1dEJ1ZmZlclNpemU9dH1nZXQgcXVldWVkU2l6ZSgpe3JldHVybiB0aGlzLnBhcnRpYWxCdWZmZXJzLnJlZHVjZSgoZSx0KT0+ZSt0Lmxlbmd0aCwwKX1mZWVkKGUpe3RoaXMucGFydGlhbEJ1ZmZlcnMucHVzaChlKX1nZXQgY2FuRHJhaW4oKXtyZXR1cm4gdGhpcy5wYXJ0aWFsQnVmZmVycy5yZWR1Y2UoKHQsaSk9PnQraS5sZW5ndGgsMCktdGhpcy5wYXJ0aWFsQnVmZmVyT2Zmc2V0Pj10aGlzLm91dHB1dEJ1ZmZlclNpemV9ZHJhaW4oKXtpZighdGhpcy5jYW5EcmFpbilyZXR1cm4gbnVsbDtsZXQgZT10aGlzLkFycmF5Q2xhc3MsdD1uZXcgZSh0aGlzLm91dHB1dEJ1ZmZlclNpemUpLGk9MDtmb3IoO2khPXQubGVuZ3RoOyl7aWYoaT50Lmxlbmd0aCl0aHJvdyBuZXcgRXJyb3IoYEJ1ZmZlciBvdmVyZmxvdzogJHtpfSA+ICR7dC5sZW5ndGh9YCk7bGV0IGY9dC5sZW5ndGgtaSxoPXRoaXMucGFydGlhbEJ1ZmZlcnNbMF0sYT1oLmxlbmd0aC10aGlzLnBhcnRpYWxCdWZmZXJPZmZzZXQ7YTxmPyh0LnNldChoLnN1YmFycmF5KHRoaXMucGFydGlhbEJ1ZmZlck9mZnNldCksaSksaSs9YSx0aGlzLnBhcnRpYWxCdWZmZXJzLnNoaWZ0KCksdGhpcy5wYXJ0aWFsQnVmZmVyT2Zmc2V0PTApOih0LnNldChoLnN1YmFycmF5KHRoaXMucGFydGlhbEJ1ZmZlck9mZnNldCx0aGlzLnBhcnRpYWxCdWZmZXJPZmZzZXQrZiksaSksaSs9Zix0aGlzLnBhcnRpYWxCdWZmZXJPZmZzZXQrPWYpfXJldHVybiB0fXBhZCgpe2xldCBlPXRoaXMucXVldWVkU2l6ZSV0aGlzLm91dHB1dEJ1ZmZlclNpemU7aWYoZT09MClyZXR1cm47bGV0IHQ9dGhpcy5BcnJheUNsYXNzLGk9bmV3IHQoZSk7dGhpcy5mZWVkKGkpfX07dmFyIHk9Y2xhc3MgZXh0ZW5kcyBBdWRpb1dvcmtsZXRQcm9jZXNzb3J7Y29uc3RydWN0b3IodCl7c3VwZXIodCk7dGhpcy5mb3JtYXQ9ImludDE2Ijt0aGlzLmlucHV0QnVmZmVyPW5ldyBjKEZsb2F0MzJBcnJheSw0MDk2KTt0aGlzLnBvcnQub25tZXNzYWdlPWk9PnRoaXMub25NZXNzYWdlKGkpfW9uTWVzc2FnZSh0KXt0LmRhdGEuYWN0aW9uPT0ic3RhcnQiJiYodGhpcy5mb3JtYXQ9dC5kYXRhLmZvcm1hdCx0aGlzLnJlc2FtcGxlcj1uZXcgZyh0LmRhdGEuaW5wdXRTYW1wbGVSYXRlLHQuZGF0YS5vdXRwdXRTYW1wbGVSYXRlLDEsNDA5NiksdGhpcy5mb3JtYXQ9PSJpbnQxNiI/dGhpcy5vdXRwdXRCdWZmZXI9bmV3IGMoSW50MTZBcnJheSx0LmRhdGEuYnVmZmVyU2l6ZSk6dGhpcy5mb3JtYXQ9PSJpbnQ2NCI/dGhpcy5vdXRwdXRCdWZmZXI9bmV3IGMoQmlnSW50NjRBcnJheSx0LmRhdGEuYnVmZmVyU2l6ZSk6dGhpcy5mb3JtYXQ9PSJmbG9hdDMyIiYmKHRoaXMub3V0cHV0QnVmZmVyPW5ldyBjKEZsb2F0MzJBcnJheSx0LmRhdGEuYnVmZmVyU2l6ZSkpKX1wcm9jZXNzKHQsaSxmKXtmb3IobGV0IGE9MDthPGkubGVuZ3RoO2ErKyl7bGV0IHM9TWF0aC5taW4oaVthXS5sZW5ndGgsdFswXS5sZW5ndGgpO2ZvcihsZXQgcj0wO3I8cztyKyspaVthXVtyXS5zZXQodFswXVtyXSl9aWYoIXRoaXMucmVzYW1wbGVyKXJldHVybiEwO2xldCBoPW5ldyBGbG9hdDMyQXJyYXkoaVswXVswXS5sZW5ndGgpO2ZvcihoLnNldChpWzBdWzBdKSx0aGlzLmlucHV0QnVmZmVyLmZlZWQoaCk7dGhpcy5pbnB1dEJ1ZmZlci5jYW5EcmFpbjspe2xldCBhPXRoaXMuaW5wdXRCdWZmZXIuZHJhaW4oKSxzPXRoaXMucmVzYW1wbGVyLnJlc2FtcGxlKGEpO3RoaXMuZm9ybWF0PT0iaW50MTYiP3RoaXMub3V0cHV0QnVmZmVyLmZlZWQoZChzKSk6dGhpcy5mb3JtYXQ9PSJpbnQ2NCI/dGhpcy5vdXRwdXRCdWZmZXIuZmVlZCh3KHMpKTp0aGlzLmZvcm1hdD09ImZsb2F0MzIiJiZ0aGlzLm91dHB1dEJ1ZmZlci5mZWVkKHMpfWZvcig7dGhpcy5vdXRwdXRCdWZmZXIuY2FuRHJhaW47KXtsZXQgYT10aGlzLm91dHB1dEJ1ZmZlci5kcmFpbigpO2lmKCFhKWJyZWFrO3RoaXMucG9ydC5wb3N0TWVzc2FnZSh7YWN0aW9uOiJkYXRhIixidWZmZXI6YS5idWZmZXJ9LFthLmJ1ZmZlcl0pfXJldHVybiEwfX07cmVnaXN0ZXJQcm9jZXNzb3IoInBjbS1yZWNlaXZlci1ub2RlIix5KTsK";var Fu=class extends AudioWorkletNode{constructor(r,n,i,o){super(r,"pcm-receiver-node",{numberOfInputs:1});this.format="int16";this.format=i;let s=["int16","int64","float32"];if(!n||n<=0)throw new Error(`Invalid sample rate: ${n}`);if(!s.includes(i))throw new Error(`Invalid format ${i}, must be one of: ${s.join(", ")}`);if(!o||o<=0)throw new Error(`Invalid buffer size: ${o}`);this.port.onmessage=a=>this.onWorkletMessage(a),this.port.postMessage({action:"start",inputSampleRate:r.sampleRate,outputSampleRate:n,format:i,bufferSize:o})}static async registerModule(r){await r.audioWorklet.addModule(FD)}onWorkletMessage(r){if(r.data.action=="data"){let n=null;if(this.format=="int16"&&(n=new Int16Array(r.data.buffer)),this.format=="int64"&&(n=new BigInt64Array(r.data.buffer)),this.format=="float32"&&(n=new Float32Array(r.data.buffer)),!n)throw new Error(`Invalid format: ${this.format}`);this.onData(n),this.dispatchEvent(new CustomEvent("data",{detail:{data:n}}))}}onData(r){}};var cE=16e3,Vv=256,Vu=8,gm=new Le("VoiceDetectionNode"),ym=class ym extends Fu{constructor(r){super(r,cE,"float32",Vv*Vu);this.isVoiceActive=!1;this.lastVoiceActiveDate=0;this.voiceEndTimeout=50;this.sensitivity=.5;this.sentivityEnd=.2;this.nextVadReset=0;this.currentProbability=0;this._lastVoiceActive=!1;if(!ym.vadModelURL)throw new Error("VAD model url not set, please load it and set it to VoiceDetectionNode.vadModelURL");this.loadModel()}get isVoicePossiblyEnding(){return this.isVoiceActive&&this.currentProbability<this.sensitivity}get sampleRate(){return cE}get numberOfSamples(){return Vv}get numberOfSampleChunks(){return Vu}get outputBufferSize(){return Vv*Vu}get isModelLoaded(){return!!this.vad}async loadModel(){gm.debug("Loading VAD model"),this.vad=await vi.load(ym.vadModelURL),this.vad.ignoreIfBusy=!0,gm.debug("Model loaded"),this.vad.makeConstant("sr","int64",[1],cE),this.vad.makeState("h","hn","float32",[2,Vu,64]),this.vad.makeState("c","cn","float32",[2,Vu,64])}async onData(r){if(this.vad)try{let n=await this.vad.run({input:new vi.onnx.Tensor(r,[Vu,Vv])});if(!n)return;this.currentProbability=0;for(let s=0;s<n.output.data.length;s++)n.output.data[s]>this.currentProbability&&(this.currentProbability=n.output.data[s]);let i=this.isVoiceActive?this.sentivityEnd:this.sensitivity,o=this.currentProbability>i;if(!o&&this._lastVoiceActive&&(this.nextVadReset=Date.now(),this.vad.resetState()),this._lastVoiceActive=o,o&&!this.isVoiceActive?(this.lastVoiceActiveDate=Date.now(),this.isVoiceActive=!0,this.dispatchEvent(new CustomEvent("speechstart")),this.onSpeechStart(),gm.debug("Started speaking")):o?this.lastVoiceActiveDate=Date.now():!o&&this.isVoiceActive&&Date.now()<this.lastVoiceActiveDate+this.voiceEndTimeout||!o&&this.isVoiceActive&&(this.isVoiceActive=!1,this.dispatchEvent(new CustomEvent("speechend")),this.onSpeechEnd(),gm.debug("Stopped speaking after timeout")),!o){let s=Date.now();s>this.nextVadReset&&(this.nextVadReset=s+5e3,this.vad.resetState())}}catch(n){gm.error("VAD failed:",n)}}onSpeechStart(){}onSpeechEnd(){}};ym.vadModelURL="";var qu=ym;var VD=new Le("VoiceChunkOutputNode"),Wu=class extends qu{constructor(){super(...arguments);this.buffers=[];this.recordedBuffers=[];this._voiceRecording=!1;this.backBufferDurationSeconds=3}get bufferDuration(){return this.buffers.reduce((r,n)=>r+n.length,0)/8e3}async onData(r){if(await super.onData(r),this.isVoiceActive&&!this._voiceRecording){VD.debug(`Voice detected, sending ${this.buffers.length} existing chunks`),this._voiceRecording=!0;for(let n of this.buffers)this.recordedBuffers.push(n),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:n,isFinal:!1}})),this.onVoiceChunk(n);this.recordedBuffers.push(r),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:r,isFinal:!1}})),this.onVoiceChunk(r),this.buffers=[]}else if(this.isVoiceActive)this.recordedBuffers.push(r),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:r,isFinal:!1}})),this.onVoiceChunk(r);else if(!this.isVoiceActive&&this._voiceRecording){this.recordedBuffers.push(r),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:r,isFinal:!0}})),this.onVoiceChunk(r),this._voiceRecording=!1;let n=this.recordedBuffers.reduce((i,o)=>i+o.length,0);VD.debug(`Voice complete, recorded ${(n/8e3).toFixed(2)} seconds of audio, ${n*4/1024} KB of data`),this.dispatchEvent(new CustomEvent("voicedataend",{detail:{data:this.recordedBuffers}})),this.onVoiceEnd(this.recordedBuffers),this.recordedBuffers=[]}else for(this.buffers.push(r);this.bufferDuration>this.backBufferDurationSeconds;)this.buffers.shift()}onVoiceChunk(r){}onVoiceEnd(r){}};var qv=new Le("OpenAITranscriptionNode"),Wv=class extends Wu{constructor(r,n){super(r);this.apiKey="";this.pendingBuffers=[];this.isTranscribing=!1;this.apiKey=n}async onVoiceEnd(r){let n=qv.timer("OpenAI Transcribe");this.isTranscribing=!0,this.pendingBuffers.push(...r);let i=Fv(this.sampleRate,this.pendingBuffers);this.lastRequestAbortController?.abort(),this.lastRequestAbortController=new AbortController;let o="";try{let s=new FormData;s.append("file",i),s.append("model","whisper-1"),s.append("response_format","text");let a=await fetch("https://api.openai.com/v1/audio/transcriptions",{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`},body:s,signal:this.lastRequestAbortController.signal});if(!a.ok)throw new Error(`Failed to generate voice sample: ${a.status} ${a.statusText}`);n("Response received"),o=await a.text(),n("Content received: "+o),this.lastRequestAbortController=void 0}catch(s){qv.error(`Failed to transcribe speech: ${s.message}`);return}finally{this.isTranscribing=!1}if(this.pendingBuffers=[],!o)return qv.debug("Transcription complete, but no text was found");qv.debug(`Transcription: ${o}`),this.onVoiceTranscription(o),this.dispatchEvent(new CustomEvent("transcription",{detail:{text:o}}))}onVoiceTranscription(r){}};var Bv=class extends WebSocket{constructor(r){super(r);this.pendingData=[];this.addEventListener("open",()=>this._onOpen())}send(r){this.readyState==WebSocket.OPEN?super.send(r):this.pendingData.push(r)}_onOpen(){for(let r of this.pendingData)super.send(r);this.pendingData=[]}};var Gi=new Le("IntelliWeaveTranscriptionNode"),FY="wss://speech.intelliweave.ai/api/v1/transcribe",Hv=class Hv extends Wu{constructor(r,n){super(r);this.apiAddress=FY;this.apiKey="";this.isTranscribing=!1;this.apiKey=n}async onVoiceChunk(r){this.isTranscribing=!0,this.ws?this.ws.send(r):(Gi.debug("Opening WebSocket connection"),this.ws=new Bv(this.apiAddress),this.ws.send(JSON.stringify({type:"hello",sampleRate:16e3,channels:1,format:"float32",apiKey:this.apiKey})),this.ws.send(r.buffer),this.ws.onopen=()=>{Gi.debug("WebSocket connection opened")},this.ws.addEventListener("message",i=>{let o=JSON.parse(i.data);if(o.error)return Gi.warn("Error: "+o.error);if(o.type!="transcription")return Gi.warn("Invalid response type",o);if(o.streaming&&!o.final)return Gi.debug("Partial transcription: "+o.partialText);if(this.isTranscribing=!1,!o.text.trim())return Gi.warn(`Empty transcription (${o.processingTime}ms)`);Gi.debug(`Transcription: ${o.text} (${o.processingTime}ms)`),this.onVoiceTranscription(o.text),this.dispatchEvent(new CustomEvent("transcription",{detail:{text:o.text}}))}),this.ws.addEventListener("close",()=>this.onSocketClose()),this.ws.addEventListener("error",i=>Gi.warn("WebSocket error")));let n=1e3*60*1;this.shutdownTimer&&clearTimeout(this.shutdownTimer),this.shutdownTimer=setTimeout(()=>{Gi.debug("Shutting down WebSocket connection"),this.ws?.close(),this.ws=void 0},n)}async onVoiceEnd(r){if(this.ws?.send(JSON.stringify({type:"end"})),Hv.debugExportWav){let n=Fv(this.sampleRate,r),i=document.createElement("a");i.href=URL.createObjectURL(n),i.download="recording.wav",i.click()}}onVoiceTranscription(r){}onSocketClose(){Gi.debug("WebSocket connection closed"),this.ws=void 0,this.isTranscribing=!1}};Hv.debugExportWav=!1;var Gv=Hv;var uE=new Le("SpeechRecognition"),Xv=class extends EventTarget{constructor(r){super();this.isRunning=!1;this._skipEvents=!1;this.maxVolumeHeard=0;this.ai=r}get isSupported(){if(!vi.lib||!this.ai?.vadModel||!rs().AudioWorkletNode)return!1;if(this.ai?.config?.transcription?.providerID!="intelliweave"){if(!(this.ai?.config?.transcription?.providerID=="openai"&&this.ai.config?.transcription?.apiKey))return!1}return!0}async start(){if(!this.isSupported)throw new Error("Speech recognition not supported in this persona and browser.");if(!this.isRunning){this.isRunning=!0;try{await this.ai.audio.beginAccess("speech-recognition"),this.micStream=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}});let r=this.ai.audio.context.createMediaStreamSource(this.micStream);this.analyserNode=this.ai.audio.context.createAnalyser(),this.analyserNode.fftSize=32,r.connect(this.analyserNode),this.analyserBuffer=new Float32Array(this.analyserNode.fftSize),qu.vadModelURL=URL.createObjectURL(this.ai.vadModel),this.ai?.config?.transcription?.providerID=="openai"?(this.voiceDetection=new Wv(this.ai.audio.context,this.ai.config.transcription.apiKey),r.connect(this.voiceDetection)):(this.voiceDetection=new Gv(this.ai.audio.context,this.ai.apiKey),this.voiceDetection.apiAddress=this.ai?.config?.transcription?.url||this.voiceDetection.apiAddress,r.connect(this.voiceDetection)),this.voiceDetection.addEventListener("speechstart",n=>{this.ai._voiceTracker=uE.timer("voice interaction","Speech started"),this.recordingStartTime=Date.now(),Gr(this.ai,{event_type:"voice_start",event_properties:{audio_provider:this.ai.config?.transcription?.providerID||"intelliweave",sample_rate:16e3}}),this.dispatchEvent(new CustomEvent(n.type,{detail:n.detail}))}),this.voiceDetection.addEventListener("speechend",n=>{this.ai._voiceTracker?.("Speech ended");let i=this.recordingStartTime?Date.now()-this.recordingStartTime:0;Gr(this.ai,{event_type:"voice_end",event_properties:{recording_duration_ms:i}}),this.dispatchEvent(new CustomEvent(n.type,{detail:n.detail}))}),this.voiceDetection.addEventListener("transcription",n=>{this.ai._voiceTracker?.(`Transcription: ${n.detail.text}`),Gr(this.ai,{event_type:"voice_submit",value_str:"",event_properties:{transcription_provider:this.ai.config?.transcription?.providerID||"intelliweave",confidence_score:n.detail.confidence||void 0}}),this.onTranscription(n)}),this._skipEvents||this.dispatchEvent(new CustomEvent("start",{detail:{speechRecognition:this}}))}catch(r){uE.error("Failed to start speech recognition:",r),this.stop()}}}stop(){this.isRunning&&(this.isRunning=!1,this.ai.audio.endAccess("speech-recognition"),this.voiceDetection?.disconnect(),this.voiceDetection=void 0,this.micStream?.getTracks().forEach(r=>r.stop()),this.micStream=void 0,this.analyserNode=void 0,this.analyserBuffer=void 0,this._skipEvents||this.dispatchEvent(new CustomEvent("end",{detail:{speechRecognition:this}})))}get volumeLevel(){if(!this.analyserNode||!this.analyserBuffer)return 0;this.analyserNode.getFloatTimeDomainData(this.analyserBuffer);let r=0;for(let i of this.analyserBuffer)r+=i*i;let n=Math.sqrt(r/this.analyserBuffer.length);return n>this.maxVolumeHeard&&(this.maxVolumeHeard=n),this.maxVolumeHeard*=.999,this.maxVolumeHeard<.01&&(this.maxVolumeHeard=.01),Math.min(1,Math.max(0,n/this.maxVolumeHeard))}get wordsCurrentlyBeingSpoken(){return!!this.voiceDetection?.isVoiceActive}get isTranscribing(){return!!this.voiceDetection?.isTranscribing}onTranscription(r){let n=r.detail.text;uE.debug("Heard:",n),this.dispatchEvent(new CustomEvent("speech",{detail:{transcript:n,isFinal:!0}}))}async reset(){if(this.isRunning){this._skipEvents=!0;try{this.stop(),await this.start(),this._skipEvents=!1}catch(r){throw this._skipEvents=!1,r}}}};var Kv=new Le("AudioSystem"),vm=class t{constructor(e){this.locks=[];if(!e)throw new Error("AI reference is required. Please pass in the IntelliWeave instance to the constructor.");this.ai=e,this.ai.audio=this,this.speechRecognition=new Xv(this.ai),this.speechOutput=new Zv(this.ai)}static get isSupported(){return!(!vi.lib||!rs().AudioWorkletNode)}static async registerModules(e){await Promise.all([Zu.registerModule(e),Fu.registerModule(e)])}async beginAccess(e){Kv.debug(`Began access for: ${e}`),this.locks.includes(e)||this.locks.push(e),!this.context&&(Kv.debug("Creating AudioContext"),this.context=new AudioContext({latencyHint:"interactive"}),this.context.resume(),await t.registerModules(this.context))}endAccess(e){Kv.debug(`Ended access for: ${e}`),this.locks=this.locks.filter(r=>r!=e),!this.locks.length&&(Kv.debug("Closing AudioContext"),this.context?.close(),this.context=void 0)}};var un=new Le("Embed"),al=class extends kn{constructor(){super();this.config={};this.suggestions=[];this._previousOpenState=!1;this.html=()=>`
|
|
304
459
|
|
|
305
460
|
<!-- Styling -->
|
|
306
461
|
<style>
|
|
@@ -379,12 +534,19 @@ ${s}`,cannotRemove:o.isContext,sortOrder:101,disabled:typeof o.disabled=="functi
|
|
|
379
534
|
#root #fullscreen-header {
|
|
380
535
|
display: none;
|
|
381
536
|
width: 100%;
|
|
382
|
-
|
|
537
|
+
max-width: 860px;
|
|
538
|
+
padding: 12px 24px;
|
|
383
539
|
box-sizing: border-box;
|
|
540
|
+
position: absolute;
|
|
541
|
+
top: 0;
|
|
542
|
+
left: 50%;
|
|
543
|
+
transform: translateX(-50%);
|
|
544
|
+
z-index: 10;
|
|
545
|
+
transition: opacity 0.2s ease;
|
|
384
546
|
}
|
|
385
547
|
#root.layout-fullscreen #fullscreen-header {
|
|
386
548
|
display: flex;
|
|
387
|
-
justify-content:
|
|
549
|
+
justify-content: space-between;
|
|
388
550
|
align-items: center;
|
|
389
551
|
}
|
|
390
552
|
#root.layout-fullscreen #fullscreen-persona {
|
|
@@ -393,14 +555,33 @@ ${s}`,cannotRemove:o.isContext,sortOrder:101,disabled:typeof o.disabled=="functi
|
|
|
393
555
|
gap: 10px;
|
|
394
556
|
font-size: 16px;
|
|
395
557
|
font-weight: 600;
|
|
396
|
-
color:
|
|
558
|
+
color: #333;
|
|
397
559
|
}
|
|
398
560
|
#root.layout-fullscreen #fullscreen-logo {
|
|
399
561
|
width: 32px;
|
|
400
562
|
height: 32px;
|
|
401
|
-
border-radius:
|
|
402
|
-
object-fit:
|
|
563
|
+
border-radius: 8px;
|
|
564
|
+
object-fit: contain;
|
|
565
|
+
}
|
|
566
|
+
#root.layout-fullscreen #fullscreen-branding {
|
|
403
567
|
display: none;
|
|
568
|
+
align-items: center;
|
|
569
|
+
gap: 6px;
|
|
570
|
+
font-size: 11px;
|
|
571
|
+
color: #666;
|
|
572
|
+
text-transform: uppercase;
|
|
573
|
+
letter-spacing: 0.5px;
|
|
574
|
+
}
|
|
575
|
+
#root.layout-fullscreen #fullscreen-branding.visible {
|
|
576
|
+
display: flex;
|
|
577
|
+
}
|
|
578
|
+
#root.layout-fullscreen #fullscreen-branding .brand-label {
|
|
579
|
+
opacity: 0.6;
|
|
580
|
+
font-weight: 400;
|
|
581
|
+
}
|
|
582
|
+
#root.layout-fullscreen #fullscreen-branding .brand-name {
|
|
583
|
+
font-weight: 600;
|
|
584
|
+
color: #333;
|
|
404
585
|
}
|
|
405
586
|
|
|
406
587
|
#root.open #web-weaver-logo {
|
|
@@ -464,7 +645,7 @@ ${s}`,cannotRemove:o.isContext,sortOrder:101,disabled:typeof o.disabled=="functi
|
|
|
464
645
|
line-height: 1.3;
|
|
465
646
|
}
|
|
466
647
|
#root.layout-fullscreen #web-weaver-embed-inner {
|
|
467
|
-
padding:
|
|
648
|
+
padding: 56px 24px 16px 24px;
|
|
468
649
|
display: flex;
|
|
469
650
|
flex-direction: column;
|
|
470
651
|
gap: 12px;
|
|
@@ -483,10 +664,12 @@ ${s}`,cannotRemove:o.isContext,sortOrder:101,disabled:typeof o.disabled=="functi
|
|
|
483
664
|
font-size: 14px;
|
|
484
665
|
}
|
|
485
666
|
#root.layout-fullscreen #web-weaver-embed-inner .introduction-message {
|
|
486
|
-
padding: 12px
|
|
667
|
+
padding: 8px 12px;
|
|
487
668
|
border-radius: 14px;
|
|
488
669
|
background: var(--intelliweave-persona-bg-muted, rgba(32, 38, 44, 0.8));
|
|
489
670
|
text-align: center;
|
|
671
|
+
width: 100%;
|
|
672
|
+
box-sizing: border-box;
|
|
490
673
|
}
|
|
491
674
|
|
|
492
675
|
#web-weaver-embed-inner .suggestion-button {
|
|
@@ -544,6 +727,22 @@ ${s}`,cannotRemove:o.isContext,sortOrder:101,disabled:typeof o.disabled=="functi
|
|
|
544
727
|
margin-top: 8px;
|
|
545
728
|
}
|
|
546
729
|
|
|
730
|
+
/* Image styles for markdown-rendered images in AI responses */
|
|
731
|
+
#web-weaver-embed-inner .output img {
|
|
732
|
+
max-width: 100%;
|
|
733
|
+
max-height: 300px;
|
|
734
|
+
width: auto;
|
|
735
|
+
height: auto;
|
|
736
|
+
border-radius: 8px;
|
|
737
|
+
margin: 8px 0;
|
|
738
|
+
display: block;
|
|
739
|
+
object-fit: contain;
|
|
740
|
+
}
|
|
741
|
+
#root.layout-fullscreen #web-weaver-embed-inner .output img {
|
|
742
|
+
max-width: 100%;
|
|
743
|
+
max-height: 400px;
|
|
744
|
+
}
|
|
745
|
+
|
|
547
746
|
/** Info block */
|
|
548
747
|
#web-weaver-embed-inner .info-block {
|
|
549
748
|
display: flex;
|
|
@@ -637,20 +836,32 @@ ${s}`,cannotRemove:o.isContext,sortOrder:101,disabled:typeof o.disabled=="functi
|
|
|
637
836
|
<div id='root' class='hidden'>
|
|
638
837
|
|
|
639
838
|
<!-- Logo -->
|
|
640
|
-
${
|
|
839
|
+
${Fp.add({id:"web-weaver-logo",logo:this.attr.logo})}
|
|
641
840
|
<div id='pulseanim' class="circle pulse"></div>
|
|
642
841
|
|
|
643
842
|
|
|
644
843
|
|
|
844
|
+
<!-- Fullscreen header -->
|
|
845
|
+
<div id='fullscreen-header'>
|
|
846
|
+
<div id='fullscreen-persona'>
|
|
847
|
+
<img id='fullscreen-logo' src='' alt='' />
|
|
848
|
+
<span id='fullscreen-name'></span>
|
|
849
|
+
</div>
|
|
850
|
+
<div id='fullscreen-branding' class='branding-chatterly'>
|
|
851
|
+
<span class='brand-label'>CREATED WITH</span>
|
|
852
|
+
<span class='brand-name'>Chatterly</span>
|
|
853
|
+
</div>
|
|
854
|
+
</div>
|
|
855
|
+
|
|
645
856
|
<!-- Inner container contains all the UI when the panel is open -->
|
|
646
857
|
<div id='web-weaver-embed-inner'>
|
|
647
858
|
</div>
|
|
648
859
|
|
|
649
860
|
<!-- LLM selector panel -->
|
|
650
|
-
${
|
|
861
|
+
${mm.add({id:"llm-selector-panel"})}
|
|
651
862
|
|
|
652
863
|
<!-- Interaction panel -->
|
|
653
|
-
${
|
|
864
|
+
${Zp.add({id:"interaction-bar"})}
|
|
654
865
|
|
|
655
866
|
|
|
656
867
|
<!-- Powered by IW banner -->
|
|
@@ -660,9 +871,16 @@ ${s}`,cannotRemove:o.isContext,sortOrder:101,disabled:typeof o.disabled=="functi
|
|
|
660
871
|
|
|
661
872
|
</div>
|
|
662
873
|
|
|
663
|
-
`;this._lastLogo="";this._lastBackground="";this._lastTextColor="";this._lastDisplayMode="";this._lastLayout="";this._lastPersonaName="";this._lastHeaderLogo="";this._lastPositioningMode="";this._lastPositionX="";this._lastPositionY="";this._isProcessing=!1;this.ai=new W,F.isSupported&&(this.ai.audio=new F(this.ai))}onCreate(){m().embed&&b.warn("Only one <web-weaver-embed> element should be on the page."),m().embed=this;let e=m();b.debug("[WebWeaverEmbed] Client config:",e),e.displayMode&&!this.attr.displayMode&&(b.debug("[WebWeaverEmbed] Setting displayMode from client config:",e.displayMode),this.attr.displayMode=e.displayMode),e.layout&&!this.attr.layout&&(b.debug("[WebWeaverEmbed] Setting layout from client config:",e.layout),this.attr.layout=e.layout),e.positioningMode&&!this.attr.positioningMode&&(b.debug("[WebWeaverEmbed] Setting positioningMode from client config:",e.positioningMode),this.attr.positioningMode=e.positioningMode),e.positionX&&!this.attr.positionX&&(b.debug("[WebWeaverEmbed] Setting positionX from client config:",e.positionX),this.attr.positionX=e.positionX),e.positionY&&!this.attr.positionY&&(b.debug("[WebWeaverEmbed] Setting positionY from client config:",e.positionY),this.attr.positionY=e.positionY),e.offsetX!==void 0&&!this.attr.offsetX&&(b.debug("[WebWeaverEmbed] Setting offsetX from client config:",e.offsetX),this.attr.offsetX=String(e.offsetX)),e.offsetY!==void 0&&!this.attr.offsetY&&(b.debug("[WebWeaverEmbed] Setting offsetY from client config:",e.offsetY),this.attr.offsetY=String(e.offsetY)),b.debug("[WebWeaverEmbed] Attributes after setting:",{displayMode:this.attr.displayMode,positionX:this.attr.positionX,positionY:this.attr.positionY,offsetX:this.attr.offsetX,offsetY:this.attr.offsetY}),this.applyConfigStylesAndAttributes(),this.child("root").addEventListener("click",s=>this.onContainerClick(s)),this.child("web-weaver-logo").addEventListener("click",s=>this.onLogoClick(s)),this.child("interaction-bar").addEventListener("input-message",s=>this.processInput(s.detail)),this.child("interaction-bar").addEventListener("llm-button-click",s=>this.state.llmPanelOpen=!this.state.llmPanelOpen),this.child("llm-selector-panel").addEventListener("select",s=>this.onLLMModelSelect(s)),this.child("interaction-bar").connectAI(this.ai),this.ai.onAIMessage=this.onAIMessage.bind(this),this.ai.knowledgeBase.addEntry({id:"ui.suggestResponse",type:"action",name:"Suggest a response",content:"Add a button with a suggested response for the user's next message. Supports multiple calls at once.",isContext:!0,hideActionInUI:"always",parameters:[{name:"text",type:"string",description:"The suggested response for the user's next message."}],action:s=>(this.suggestions.push(s.text),"Suggestion button added")});let o=this.attr.apiKey||m().apiKey;if(!o)return b.warn("No API key specified, some features may be unavailable.");this.state.loading=!0,this.attr.hubAPI&&(this.ai.hubAPI=this.attr.hubAPI),this.ai.load(o).then(s=>{this.config=s.config,m().introductionMessage=this.config.introductionMessage,m().analytics=this.config.analytics!==void 0?!!this.config.analytics:m().analytics,this.applyConfigStylesAndAttributes(),this.child("root").classList.remove("hidden"),this.state.loading=!1,this.resetConversation()}).catch(s=>{b.error("Failed to load AI configuration:",s),this.state.loading=!1;let n=this.child("web-weaver-embed-inner");n&&(n.innerHTML='<div class="output" style="color: red; padding: 20px;">Error loading configuration. Please try again later.</div>')})}applyPersonaColorVariants(e,i){if(!i){e.style.removeProperty("--intelliweave-persona-bg-muted"),e.style.removeProperty("--intelliweave-assistant-bubble-bg"),e.style.removeProperty("--intelliweave-interaction-bg");return}let o=this.parseColorToRGB(i);if(!o){e.style.removeProperty("--intelliweave-persona-bg-muted"),e.style.removeProperty("--intelliweave-assistant-bubble-bg"),e.style.setProperty("--intelliweave-interaction-bg",i);return}let{r:s,g:n,b:a}=o;e.style.setProperty("--intelliweave-persona-bg-muted",`rgba(${s}, ${n}, ${a}, 0.65)`),e.style.setProperty("--intelliweave-assistant-bubble-bg",`rgba(${Math.round(s*.85)}, ${Math.round(n*.85)}, ${Math.round(a*.85)}, 0.85)`),e.style.setProperty("--intelliweave-interaction-bg",`rgba(${s}, ${n}, ${a}, 0.9)`)}parseColorToRGB(e){if(!e)return null;let i=e.trim();if(i.startsWith("#")){let o=i.slice(1);if(o.length===3){let s=parseInt(o[0]+o[0],16),n=parseInt(o[1]+o[1],16),a=parseInt(o[2]+o[2],16);return{r:s,g:n,b:a}}if(o.length===6){let s=parseInt(o.slice(0,2),16),n=parseInt(o.slice(2,4),16),a=parseInt(o.slice(4,6),16);return{r:s,g:n,b:a}}return null}if(i.startsWith("rgb")){let o=i.match(/rgba?\s*\(\s*([0-9.]+)\s*,\s*([0-9.]+)\s*,\s*([0-9.]+)/i);return o?{r:Math.max(0,Math.min(255,Math.round(Number(o[1])))),g:Math.max(0,Math.min(255,Math.round(Number(o[2])))),b:Math.max(0,Math.min(255,Math.round(Number(o[3]))))}:null}return null}applyConfigStylesAndAttributes(){let e=this.config,i=this.child("root");if(!i)return;let o=!1,n=this.attr.logo||e.logo;if(n&&n!==this._lastLogo){this._lastLogo=n,o=!0;let J=this.child("web-weaver-logo");J&&J.setAttribute("logo",n)}let a=this.root?.getElementById("fullscreen-logo"),l=this.root?.getElementById("fullscreen-name"),c=e.name||"";c!==this._lastPersonaName&&(this._lastPersonaName=c,l&&(l.textContent=c),o=!0),n!==this._lastHeaderLogo&&(this._lastHeaderLogo=n||"",a&&(n?(a.src=n,a.style.display=""):a.style.display="none"),o=!0);let r=this.root?.getElementById("fullscreen-header"),d=(this.attr.header||"").toLowerCase();if(r){let J=d==="hidden"||d==="none"||d==="false";r.style.display=!J&&(n||c)?"":"none"}let g=this.attr.background||e.background;g!==this._lastBackground&&(this._lastBackground=g,o=!0,g?(i.style.background=g,i.style.setProperty("--intelliweave-persona-bg",g),this.applyPersonaColorVariants(i,g)):(i.style.background="",i.style.removeProperty("--intelliweave-persona-bg"),this.applyPersonaColorVariants(i,void 0)));let x=this.attr.textColor||e.textColor,L=this.child("interaction-bar");x!==this._lastTextColor&&(this._lastTextColor=x,o=!0,x?(i.style.color=x,i.style.setProperty("--intelliweave-user-bubble-text",x),i.style.setProperty("--intelliweave-assistant-bubble-text",x),L&&L.setAttribute("textColor",x)):(i.style.color="",i.style.removeProperty("--intelliweave-user-bubble-text"),i.style.removeProperty("--intelliweave-assistant-bubble-text"),L&&L.removeAttribute("textColor")));let H=this.attr.displayMode||e.displayMode||"closed";H!==this._lastDisplayMode&&(this._lastDisplayMode=H,o=!0,H==="open"&&!this.attr.open&&(this.attr.open=!0));let fe=this.attr.layout||e.layout||"widget";fe!==this._lastLayout&&(this._lastLayout=fe,o=!0);let ye=this.attr.positioningMode||e.positioningMode||"fixed";ye!==this._lastPositioningMode&&(this._lastPositioningMode=ye,o=!0);let be=this.attr.positionX||e.positionX||"right";be!==this._lastPositionX&&(this._lastPositionX=be,o=!0);let we=this.attr.positionY||e.positionY||"bottom";we!==this._lastPositionY&&(this._lastPositionY=we,o=!0);let Ce=this.attr.offsetX?parseInt(this.attr.offsetX):void 0,ve=Ce!==void 0?Ce:e.offsetX!==void 0?e.offsetX:20;ve!==this._lastOffsetX&&(this._lastOffsetX=ve,o=!0);let Ne=this.attr.offsetY?parseInt(this.attr.offsetY):void 0,xe=Ne!==void 0?Ne:e.offsetY!==void 0?e.offsetY:20;xe!==this._lastOffsetY&&(this._lastOffsetY=xe,o=!0),o&&b.debug("[WebWeaverEmbed] Applied UI Styling:",{finalLogo:n,finalBackground:i.style.background,finalTextColor:i.style.color,finalDisplayMode:H,finalLayout:fe,finalPositioningMode:ye,finalPositionX:be,finalPositionY:we,finalOffsetX:ve,finalOffsetY:xe})}onUpdate(){if(this.applyConfigStylesAndAttributes(),this.child("web-weaver-embed-inner").style.display=this.attr.open?"":"none",this.child("interaction-bar").style.display=this.attr.open?"":"none",this.child("llm-selector-panel").attr.open=this.state.llmPanelOpen,this.child("pulseanim").style.display=this.attr.open?"none":"",this.child("poweredby").style.display=this.attr.open?"flex":"none",this.attr.open&&!this._previousOpenState)this._uiSessionStartTime=Date.now(),y(this.ai,{event_type:"ui_open",event_properties:{trigger:"button_click"}});else if(!this.attr.open&&this._previousOpenState){let c=this._uiSessionStartTime?Date.now()-this._uiSessionStartTime:0;y(this.ai,{event_type:"ui_close",event_properties:{trigger:"button_click",session_duration_ms:c}})}this._previousOpenState=this.attr.open;let e=this.child("root");this.attr.open?e.classList.add("open"):e.classList.remove("open"),(this._lastLayout||"widget")==="fullscreen"?(e.classList.add("layout-fullscreen"),this.attr.open||(this.attr.open=!0)):e.classList.remove("layout-fullscreen");let o=this._lastPositioningMode||"fixed",s=this._lastPositionX||"right",n=this._lastPositionY||"bottom",a=this._lastOffsetX!==void 0?this._lastOffsetX:20,l=this._lastOffsetY!==void 0?this._lastOffsetY:20;o==="container"?(e.classList.add("container-mode"),this.attr.open||(this.attr.open=!0)):e.classList.remove("container-mode"),o!=="container"&&(e.style.left="",e.style.right="",e.style.top="",e.style.bottom="",s==="left"?e.style.left=a+"px":e.style.right=a+"px",n==="top"?e.style.top=l+"px":e.style.bottom=l+"px"),this.child("interaction-bar").attr.loading=this.state.loading,this.child("interaction-bar").attr.llmName=this.ai.currentModel?.metadata?.name||this.ai.currentModel?.id||"None",this.child("interaction-bar").attr.llmButtonVisible=this.ai.models.length>1,this.child("llm-selector-panel").state.items=this.ai.models.sort((c,r)=>(r.priority||0)-(c.priority||0)),this.child("llm-selector-panel").state.selectedID=this.ai.currentModel?.id}onDestroy(){m().embed==this&&(m().embed=void 0)}onContainerClick(e){let i=this._lastDisplayMode||"closed";(this._lastLayout||"widget")!=="fullscreen"&&i!=="open"&&(this.attr.open||(e.preventDefault(),this.attr.open=!0))}onLogoClick(e){if(e.preventDefault(),e.stopPropagation(),this.attr.focusID)this.attr.focusID="";else{let i=this._lastDisplayMode||"closed";if((this._lastLayout||"widget")==="fullscreen"||i==="open")return;this.attr.open=!this.attr.open}}open(){this.attr.open=!0}close(){this.attr.open=!1}resetConversation(){let e=this.child("web-weaver-embed-inner");for(this.state.llmPanelOpen=!1;e.children.length>0;)e.children[0].remove();this.ai.resetConversation(),this.suggestions=[];let i=document.createElement("div");i.className="introduction-message",i.innerHTML=m().introductionMessage||`Welcome to <b>${document.title||"Web Weaver"}</b>. How can I help you?`,e.appendChild(i),this.ai.insertAssistantMessage(i.innerText);for(let o of m().introductionSuggestions||[]){let s=document.createElement("div");s.className="suggestion-button",s.innerText=o,s.addEventListener("click",n=>this.onSuggestionClick(n,o)),e.appendChild(s)}}async processInput(e){if(this._isProcessing)return;this._isProcessing=!0,this.state.loading=!0,this.state.llmPanelOpen=!1;let i=this.child("web-weaver-embed-inner");this.suggestions=[];try{for(let c of Array.from(i.querySelectorAll(".suggestion-button")))c.remove();this.attr.focusID="";let o=document.createElement("div");o.className="input",o.innerText=e,i.appendChild(o);let s=this.currentOutputElement;this.currentOutputElement=document.createElement("div"),this.currentOutputElement.className="output-container",i.appendChild(this.currentOutputElement);let n=Math.ceil(i.clientHeight-300);n<0&&(n=0),n>600&&(n=600),s&&(s.style.minHeight=""),this.currentOutputElement.style.minHeight=n+"px",this.currentOutputElement.offsetHeight,this.currentOutputElement.scrollIntoView({behavior:"smooth",block:"start"});let a=await this.ai.sendMessage(e);for(let c of this.suggestions){let r=document.createElement("div");r.className="suggestion-button",r.innerText=c,r.addEventListener("click",d=>this.onSuggestionClick(d,c)),this.currentOutputElement.appendChild(r)}let l=a.text()||"";this.ai.audio?.speechRecognition?.isRunning&&this.ai.audio.speechOutput.speak(l)}catch(o){b.error("Failed to process input:",o);let s=document.createElement("div");s.className="output",s.innerText="Sorry, there was a problem getting a response. "+o.message,i.appendChild(s);let n=document.createElement("div");n.className="suggestion-button",n.innerText="Reset conversation",n.addEventListener("click",a=>this.resetConversation()),i.appendChild(n)}this.state.loading=!1,this._isProcessing=!1}async onAIMessage(e,i){let o=[];for(let s of e)for(let n=0;n<(s.sections?.length||0);n++){let a=s.sections[n],l=`msgelem-${s.id||""}_${n}_${a.type||"unknown"}`;if(l=l.replace(/[^a-zA-Z0-9-_]/g,"_"),a.type=="thinking"){if(!a.text)continue;let c=a.text||"";c.includes(`
|
|
874
|
+
`;this._lastLogo="";this._lastBackground="";this._lastTextColor="";this._lastDisplayMode="";this._lastLayout="";this._lastPersonaName="";this._lastHeaderLogo="";this._lastPositioningMode="";this._lastPositionX="";this._lastPositionY="";this._isProcessing=!1;this.ai=new Ou,vm.isSupported&&(this.ai.audio=new vm(this.ai))}onCreate(){bt().embed&&un.warn("Only one <web-weaver-embed> element should be on the page."),bt().embed=this;let r=bt();un.debug("[WebWeaverEmbed] Client config:",r),r.displayMode&&!this.attr.displayMode&&(un.debug("[WebWeaverEmbed] Setting displayMode from client config:",r.displayMode),this.attr.displayMode=r.displayMode),r.layout&&!this.attr.layout&&(un.debug("[WebWeaverEmbed] Setting layout from client config:",r.layout),this.attr.layout=r.layout),r.positioningMode&&!this.attr.positioningMode&&(un.debug("[WebWeaverEmbed] Setting positioningMode from client config:",r.positioningMode),this.attr.positioningMode=r.positioningMode),r.positionX&&!this.attr.positionX&&(un.debug("[WebWeaverEmbed] Setting positionX from client config:",r.positionX),this.attr.positionX=r.positionX),r.positionY&&!this.attr.positionY&&(un.debug("[WebWeaverEmbed] Setting positionY from client config:",r.positionY),this.attr.positionY=r.positionY),r.offsetX!==void 0&&!this.attr.offsetX&&(un.debug("[WebWeaverEmbed] Setting offsetX from client config:",r.offsetX),this.attr.offsetX=String(r.offsetX)),r.offsetY!==void 0&&!this.attr.offsetY&&(un.debug("[WebWeaverEmbed] Setting offsetY from client config:",r.offsetY),this.attr.offsetY=String(r.offsetY)),un.debug("[WebWeaverEmbed] Attributes after setting:",{displayMode:this.attr.displayMode,positionX:this.attr.positionX,positionY:this.attr.positionY,offsetX:this.attr.offsetX,offsetY:this.attr.offsetY}),this.applyConfigStylesAndAttributes(),this.child("root").addEventListener("click",o=>this.onContainerClick(o)),this.child("web-weaver-logo").addEventListener("click",o=>this.onLogoClick(o)),this.child("interaction-bar").addEventListener("input-message",o=>this.processInput(o.detail)),this.child("interaction-bar").addEventListener("llm-button-click",o=>this.state.llmPanelOpen=!this.state.llmPanelOpen),this.child("llm-selector-panel").addEventListener("select",o=>this.onLLMModelSelect(o)),this.child("web-weaver-embed-inner").addEventListener("scroll",o=>this.onContentScroll(o)),this.child("interaction-bar").connectAI(this.ai),this.ai.onAIMessage=this.onAIMessage.bind(this),this.ai.knowledgeBase.addEntry({id:"ui.suggestResponse",type:"action",name:"Suggest a response",content:"Add a button with a suggested response for the user's next message. Supports multiple calls at once.",isContext:!0,hideActionInUI:"always",parameters:[{name:"text",type:"string",description:"The suggested response for the user's next message."}],action:o=>(this.suggestions.push(o.text),"Suggestion button added")}),this.ai.knowledgeBase.addEntry({id:"_iw_image_instructions",type:"info",name:"Using Images",content:`
|
|
875
|
+
You can display images in Markdown format, example: 
|
|
876
|
+
Image URLs must be absolute. When using an image URL from the knowledge base, include all parameters.`,isContext:!0});let i=this.attr.apiKey||bt().apiKey;if(!i)return un.warn("No API key specified, some features may be unavailable.");this.state.loading=!0,this.attr.hubAPI&&(this.ai.hubAPI=this.attr.hubAPI),this.ai.load(i).then(o=>{this.config=o.config,bt().introductionMessage||(bt().introductionMessage=this.config.introductionMessage),bt().analytics=this.config.analytics!==void 0?!!this.config.analytics:bt().analytics,this.applyConfigStylesAndAttributes(),this.child("root").classList.remove("hidden"),this.state.loading=!1,this.config.managedBy&&this.updateBrandingFor(this.config.managedBy),this.resetConversation()}).catch(o=>{un.error("Failed to load AI configuration:",o),this.state.loading=!1;let s=this.child("web-weaver-embed-inner");s&&(s.innerHTML='<div class="output" style="color: red; padding: 20px;">Error loading configuration. Please try again later.</div>')})}applyPersonaColorVariants(r,n){if(!n){r.style.removeProperty("--intelliweave-persona-bg-muted"),r.style.removeProperty("--intelliweave-assistant-bubble-bg"),r.style.removeProperty("--intelliweave-interaction-bg");return}let i=this.parseColorToRGB(n);if(!i){r.style.removeProperty("--intelliweave-persona-bg-muted"),r.style.removeProperty("--intelliweave-assistant-bubble-bg"),r.style.setProperty("--intelliweave-interaction-bg",n);return}let{r:o,g:s,b:a}=i;r.style.setProperty("--intelliweave-persona-bg-muted",`rgba(${o}, ${s}, ${a}, 0.65)`),r.style.setProperty("--intelliweave-assistant-bubble-bg",`rgba(${Math.round(o*.85)}, ${Math.round(s*.85)}, ${Math.round(a*.85)}, 0.85)`),r.style.setProperty("--intelliweave-interaction-bg",`rgba(${o}, ${s}, ${a}, 0.9)`)}parseColorToRGB(r){if(!r)return null;let n=r.trim();if(n.startsWith("#")){let i=n.slice(1);if(i.length===3){let o=parseInt(i[0]+i[0],16),s=parseInt(i[1]+i[1],16),a=parseInt(i[2]+i[2],16);return{r:o,g:s,b:a}}if(i.length===6){let o=parseInt(i.slice(0,2),16),s=parseInt(i.slice(2,4),16),a=parseInt(i.slice(4,6),16);return{r:o,g:s,b:a}}return null}if(n.startsWith("rgb")){let i=n.match(/rgba?\s*\(\s*([0-9.]+)\s*,\s*([0-9.]+)\s*,\s*([0-9.]+)/i);return i?{r:Math.max(0,Math.min(255,Math.round(Number(i[1])))),g:Math.max(0,Math.min(255,Math.round(Number(i[2])))),b:Math.max(0,Math.min(255,Math.round(Number(i[3]))))}:null}return null}applyConfigStylesAndAttributes(){let r=this.config,n=this.child("root");if(!n)return;let i=!1,s=this.attr.logo||r.logo;if(s&&s!==this._lastLogo){this._lastLogo=s,i=!0;let ie=this.child("web-weaver-logo");ie&&ie.setAttribute("logo",s)}let a=this.root?.getElementById("fullscreen-logo"),l=this.root?.getElementById("fullscreen-name"),c=r.name||"";c!==this._lastPersonaName&&(this._lastPersonaName=c,l&&(l.textContent=c),i=!0),s!==this._lastHeaderLogo&&(this._lastHeaderLogo=s||"",a&&(s?(a.src=s,a.style.display=""):a.style.display="none"),i=!0);let u=this.root?.getElementById("fullscreen-header"),d=(this.attr.header||"").toLowerCase();if(u){let ie=d==="hidden"||d==="none"||d==="false";u.style.display=!ie&&(s||c)?"":"none"}let f=this.attr.background||r.background;f!==this._lastBackground&&(this._lastBackground=f,i=!0,f?(n.style.background=f,n.style.setProperty("--intelliweave-persona-bg",f),this.applyPersonaColorVariants(n,f)):(n.style.background="",n.style.removeProperty("--intelliweave-persona-bg"),this.applyPersonaColorVariants(n,void 0)));let h=this.attr.textColor||r.textColor,y=this.child("interaction-bar");h!==this._lastTextColor&&(this._lastTextColor=h,i=!0,h?(n.style.color=h,n.style.setProperty("--intelliweave-user-bubble-text",h),n.style.setProperty("--intelliweave-assistant-bubble-text",h),y&&y.setAttribute("textColor",h)):(n.style.color="",n.style.removeProperty("--intelliweave-user-bubble-text"),n.style.removeProperty("--intelliweave-assistant-bubble-text"),y&&y.removeAttribute("textColor")));let _=this.attr.displayMode||r.displayMode||"closed";_!==this._lastDisplayMode&&(this._lastDisplayMode=_,i=!0,_==="open"&&!this.attr.open&&(this.attr.open=!0));let E=this.attr.layout||r.layout||"widget";E!==this._lastLayout&&(this._lastLayout=E,i=!0);let P=this.attr.positioningMode||r.positioningMode||"fixed";P!==this._lastPositioningMode&&(this._lastPositioningMode=P,i=!0);let V=this.attr.positionX||r.positionX||"right";V!==this._lastPositionX&&(this._lastPositionX=V,i=!0);let L=this.attr.positionY||r.positionY||"bottom";L!==this._lastPositionY&&(this._lastPositionY=L,i=!0);let G=this.attr.offsetX?parseInt(this.attr.offsetX):void 0,H=G!==void 0?G:r.offsetX!==void 0?r.offsetX:20;H!==this._lastOffsetX&&(this._lastOffsetX=H,i=!0);let W=this.attr.offsetY?parseInt(this.attr.offsetY):void 0,Y=W!==void 0?W:r.offsetY!==void 0?r.offsetY:20;Y!==this._lastOffsetY&&(this._lastOffsetY=Y,i=!0),i&&un.debug("[WebWeaverEmbed] Applied UI Styling:",{finalLogo:s,finalBackground:n.style.background,finalTextColor:n.style.color,finalDisplayMode:_,finalLayout:E,finalPositioningMode:P,finalPositionX:V,finalPositionY:L,finalOffsetX:H,finalOffsetY:Y})}onUpdate(){if(this.applyConfigStylesAndAttributes(),this.child("web-weaver-embed-inner").style.display=this.attr.open?"":"none",this.child("interaction-bar").style.display=this.attr.open?"":"none",this.child("llm-selector-panel").attr.open=this.state.llmPanelOpen,this.child("pulseanim").style.display=this.attr.open?"none":"",this.child("poweredby").style.display=this.attr.open?"flex":"none",this.child("interaction-bar").attr.layout=this._lastLayout||"widget",this.attr.open&&!this._previousOpenState)this._uiSessionStartTime=Date.now(),Gr(this.ai,{event_type:"ui_open",event_properties:{trigger:"button_click"}});else if(!this.attr.open&&this._previousOpenState){let c=this._uiSessionStartTime?Date.now()-this._uiSessionStartTime:0;Gr(this.ai,{event_type:"ui_close",event_properties:{trigger:"button_click",session_duration_ms:c}})}this._previousOpenState=this.attr.open;let r=this.child("root");this.attr.open?r.classList.add("open"):r.classList.remove("open"),(this._lastLayout||"widget")==="fullscreen"?(r.classList.add("layout-fullscreen"),this.attr.open||(this.attr.open=!0)):r.classList.remove("layout-fullscreen");let i=this._lastPositioningMode||"fixed",o=this._lastPositionX||"right",s=this._lastPositionY||"bottom",a=this._lastOffsetX!==void 0?this._lastOffsetX:20,l=this._lastOffsetY!==void 0?this._lastOffsetY:20;i==="container"?(r.classList.add("container-mode"),this.attr.open||(this.attr.open=!0)):r.classList.remove("container-mode"),i!=="container"&&(r.style.left="",r.style.right="",r.style.top="",r.style.bottom="",o==="left"?r.style.left=a+"px":r.style.right=a+"px",s==="top"?r.style.top=l+"px":r.style.bottom=l+"px"),this.child("interaction-bar").attr.loading=this.state.loading,this.child("interaction-bar").attr.llmName=this.ai.currentModel?.metadata?.name||this.ai.currentModel?.id||"None",this.child("interaction-bar").attr.llmButtonVisible=this.ai.models.length>1,this.child("llm-selector-panel").state.items=this.ai.models.sort((c,u)=>(u.priority||0)-(c.priority||0)),this.child("llm-selector-panel").state.selectedID=this.ai.currentModel?.id}onDestroy(){bt().embed==this&&(bt().embed=void 0)}onContainerClick(r){let n=this._lastDisplayMode||"closed";(this._lastLayout||"widget")!=="fullscreen"&&n!=="open"&&(this.attr.open||(r.preventDefault(),this.attr.open=!0))}onLogoClick(r){if(r.preventDefault(),r.stopPropagation(),this.attr.focusID)this.attr.focusID="";else{let n=this._lastDisplayMode||"closed";if((this._lastLayout||"widget")==="fullscreen"||n==="open")return;this.attr.open=!this.attr.open}}open(){this.attr.open=!0}close(){this.attr.open=!1}resetConversation(){let r=this.child("web-weaver-embed-inner");for(this.state.llmPanelOpen=!1;r.children.length>0;)r.children[0].remove();this.ai.resetConversation(),this.suggestions=[];let n=document.createElement("div");n.className="introduction-message",n.innerHTML=bt().introductionMessage||`Welcome to <b>${document.title||"Web Weaver"}</b>. How can I help you?`,r.appendChild(n),this.ai.insertAssistantMessage(n.innerText);for(let i of bt().introductionSuggestions||[]){let o=document.createElement("div");o.className="suggestion-button",o.innerText=i,o.addEventListener("click",s=>this.onSuggestionClick(s,i)),r.appendChild(o)}}async processInput(r){if(this._isProcessing)return;this._isProcessing=!0,this.state.loading=!0,this.state.llmPanelOpen=!1;let n=this.child("web-weaver-embed-inner");this.suggestions=[];try{for(let a of Array.from(n.querySelectorAll(".suggestion-button")))a.remove();this.attr.focusID="";let i=document.createElement("div");i.className="input",i.innerText=r,n.appendChild(i);let o=this.currentOutputElement;this.currentOutputElement=document.createElement("div"),this.currentOutputElement.className="output-container",n.appendChild(this.currentOutputElement);let s=Math.ceil(n.clientHeight-300);s<0&&(s=0),s>600&&(s=600),o&&(o.style.minHeight=""),this.currentOutputElement.style.minHeight=s+"px",this.currentOutputElement.offsetHeight,this.currentOutputElement.scrollIntoView({behavior:"smooth",block:"start"}),await this.ai.sendMessage(r);for(let a of this.suggestions){let l=document.createElement("div");l.className="suggestion-button",l.innerText=a,l.addEventListener("click",c=>this.onSuggestionClick(c,a)),this.currentOutputElement.appendChild(l)}}catch(i){un.error("Failed to process input:",i);let o=document.createElement("div");o.className="output",o.innerText="Sorry, there was a problem getting a response. "+i.message,n.appendChild(o);let s=document.createElement("div");s.className="suggestion-button",s.innerText="Reset conversation",s.addEventListener("click",a=>this.resetConversation()),n.appendChild(s)}this.state.loading=!1,this._isProcessing=!1}async onAIMessage(r,n){let i=[];for(let o of r)for(let s=0;s<(o.sections?.length||0);s++){let a=o.sections[s],l=`msgelem-${o.id||""}_${s}_${a.type||"unknown"}`;if(l=l.replace(/[^a-zA-Z0-9-_]/g,"_"),a.type=="thinking"){if(!a.text)continue;let c=a.text||"";c.includes(`
|
|
664
877
|
`)&&(c=c.split(`
|
|
665
|
-
`)[0]),this.updateInfoElement(l,c,"thinking-icon"),
|
|
878
|
+
`)[0]),this.updateInfoElement(l,c,"thinking-icon"),i.push(l)}else if(a.type=="tool_call"){let u=new Nu(r).toolResult(a.toolCallInstanceID||"");if(a.toolCallHiddenInUI!="always"){if(u?.toolErrorResponse)this.updateInfoElement(l,"**Error:** "+u.toolErrorResponse||"","tool-icon"),i.push(l);else if(!(a.toolCallHiddenInUI=="after-complete"&&u))if(a.toolKbID=="search"){let d=a.toolParameters?.query?`**Search:** ${a.toolParameters.query}`:"**Search**";this.updateInfoElement(l,d,"tool-icon"),i.push(l)}else if(a.toolKbID?.startsWith("ask:")&&a.toolParameters?.query){let d=a.toolKbID.substring(4),f=`**Ask ${this.ai.subAgents.subagents.find(m=>m.id===d)?.name||"agent"}:** ${a.toolParameters.query}`;this.updateInfoElement(l,f,"tool-icon"),i.push(l)}else this.updateInfoElement(l,a.toolKbName||"","tool-icon"),i.push(l)}}else if(a.type!="tool_result"){if(!a.text)continue;this.updateTextElement(l,a.text||""),i.push(l)}}for(let o of Array.from(this.currentOutputElement.children))i.includes(o.id)||o.remove()}updateTextElement(r,n){let i=this.currentOutputElement.querySelector(`#${r}`);i||(i=document.createElement("div"),i.id=r,i.className="output",this.currentOutputElement.appendChild(i));let o=Lv().use(cm).use(um).use(Jp,{target:"_blank",rel:["noopener","noreferrer"]}).use(Yp).use(rm).processSync(n||"");i.innerHTML=o.toString("utf-8")}updateInfoElement(r,n,i){let o=this.currentOutputElement.querySelector(`#${r}`);o||(o=document.createElement("div"),o.id=r,o.className="info-block",o.innerHTML=`
|
|
666
879
|
<div class='info-block-icon'></div>
|
|
667
880
|
<div class='info-block-text'></div>
|
|
668
|
-
`,this.currentOutputElement.appendChild(
|
|
881
|
+
`,this.currentOutputElement.appendChild(o));let s=Lv().use(cm).use(um).use(Jp,{target:"_blank",rel:["noopener","noreferrer"]}).use(Yp).use(rm).processSync(n||"");o.querySelector(".info-block-icon").className="info-block-icon "+i,o.querySelector(".info-block-text").innerHTML=s.toString("utf-8")}onSuggestionClick(r,n){this.processInput(n)}onLLMModelSelect(r){r.preventDefault(),this.ai.setModel(r.detail),this.state.llmPanelOpen=!1}onContentScroll(r){let n=this.child("fullscreen-header");if(!n)return;let i=r.target.scrollTop,o=0,s=60;if(i<=o)n.style.opacity="1",n.style.pointerEvents="";else if(i>=s)n.style.opacity="0",n.style.pointerEvents="none";else{let a=1-(i-o)/(s-o);n.style.opacity=String(a),n.style.pointerEvents=a<.5?"none":""}}updateBrandingFor(r){if(!r)return;this.root?.querySelectorAll(`.branding-${r}`)?.forEach(i=>{i.classList.add("visible")})}};al.tagName="intelliweave-embed",al.observedAttributes=["logo","focusID","open","background","textColor","displayMode","layout","header","positioningMode","positionX","positionY","offsetX","offsetY"];var Cze=al;vi.lib=()=>import("./ort.bundle.min-5QOPZPPI.js");al.register();export{Cze as default};
|
|
882
|
+
/*! Bundled license information:
|
|
883
|
+
|
|
884
|
+
uri-js/dist/es5/uri.all.js:
|
|
885
|
+
(** @license URI.js v4.4.1 (c) 2011 Gary Court. License: http://github.com/garycourt/uri-js *)
|
|
886
|
+
*/
|